API Reference

Complete TypeScript and JavaScript API reference for UrduMagic core functions, static transliteration engine, instance methods, and React hooks.


Package Subpath Exports

UrduMagic provides tree-shakeable modular subpath exports:

| Import Path | Type | Description | | :--- | :--- | :--- | | urdumagic | Core Engine | Core client library, static engine, transliteration, and dictionary utilities. | | urdumagic/react | React Hooks | Native useUrduMagic hook, UrduMagicProvider, and context consumer. | | urdumagic/server | SSR / Node.js | Server-side HTML translation (renderToString) for Server Components & pre-rendering. | | urdumagic/next | Next.js Helpers | Static param generators (generateUrduParams) and routing middleware helpers. |


Static Engine & Methods

These core methods can be called directly without creating or managing an instance.

Static / Initialization

UrduMagic.init

returnsUrduMagicInstance
UrduMagic.init(config: UrduMagicConfig): UrduMagicInstance

Initializes the UrduMagic engine in browser DOM, attaches live mutation observers, injects font styles, and optionally renders the floating switcher UI button.

Parameters
configUrduMagicConfig— Configuration object specifying default language, supported modes, switcher visibility, and security settings.
Example
import { UrduMagic } from 'urdumagic';

const app = UrduMagic.init({
defaultLang: 'en',
modes: ['en', 'ur', 'roman'],
showSwitcher: true
});
Offline Dictionary

UrduMagic.fromEnglish

returns{ urdu: string; roman: string; confidence: string }
UrduMagic.fromEnglish(text: string): { urdu: string; roman: string; confidence: 'full' | 'partial' | 'none' }

Synchronously looks up English words in the built-in 10,000+ offline dictionary with O(1) instant memory lookup.

Parameters
textstring— English word or phrase to translate.
Example
const res = UrduMagic.fromEnglish('welcome');
console.log(res.urdu); // → 'خوش آمدید'
console.log(res.roman); // → 'khush amdeed'
Transliteration

UrduMagic.toUrdu

returnsstring
UrduMagic.toUrdu(text: string): string

Converts phonetic Roman Urdu text directly into Nastaliq Urdu script offline using the built-in rules engine.

Parameters
textstring— Phonetic Roman Urdu string.
Example
const script = UrduMagic.toUrdu('aap kaise hain');
console.log(script); // → 'آپ کیسے ہیں'
Transliteration

UrduMagic.toRoman

returnsstring
UrduMagic.toRoman(text: string): string

Transliterates Urdu script back into readable Roman Urdu Latin characters offline.

Parameters
textstring— Urdu script text.
Example
const roman = UrduMagic.toRoman('شکریہ');
console.log(roman); // → 'shukriya'
Script Analysis

UrduMagic.detectScript

returnsScriptType
UrduMagic.detectScript(text: string): 'arabic' | 'latin' | 'roman-urdu' | 'english' | 'mixed'

Analyzes character codepoints and linguistic patterns to detect the script family and language.

Parameters
textstring— Input text to inspect.
Example
const type = UrduMagic.detectScript('سلام');
console.log(type); // → 'arabic'
SSR / Server

UrduMagic.renderToString

returnsPromise<string>
UrduMagic.renderToString(html: string, targetLang: 'ur' | 'roman' | 'en', config?: UrduMagicConfig): Promise<string>

Server-Side Rendering utility. Translates raw HTML strings on Node.js/SSR, preserves tags and attributes, translates text nodes, and injects dir='rtl' for Urdu.

Parameters
htmlstring— Input HTML markup.
targetLang'ur' | 'roman' | 'en'— Target language mode.
config?UrduMagicConfig— Optional configuration.
Example
import { renderToString } from 'urdumagic/server';

const output = await renderToString('<p>Welcome to our store</p>', 'ur');
// Output: '<p dir="rtl">ہمارے اسٹور میں خوش آمدید</p>'
Custom Vocabulary

extendDictionary

returnsvoid
extendDictionary(words: Record<string, string>): void

Injects custom domain terminology, company brand names, or slang into the offline dictionary. Automatically updates cache and alerts active listeners.

Parameters
wordsRecord<string, string>— Key-value dictionary mapping English terms to Urdu translations.
Example
import { extendDictionary } from 'urdumagic';

extendDictionary({
'urdumagic': 'اردو میجک',
'fintech': 'فن ٹیک',
});

Instance Methods

These methods are available on the instance object returned by UrduMagic.init() or UrduMagic.getInstance().

DOM Language Switch

app.switchLang

returnsvoid
app.switchLang(lang: 'en' | 'ur' | 'roman'): void

Switches the entire active website language, scans and mutates visible text nodes, applies dir='rtl'/'ltr', and updates localStorage.

Parameters
lang'en' | 'ur' | 'roman'— Target language code.
Example
app.switchLang('ur'); // Translates entire website to Urdu
State

app.getCurrentLang

returns'en' | 'ur' | 'roman'
app.getCurrentLang(): 'en' | 'ur' | 'roman'

Returns the currently active language mode of the application.

Example
const current = app.getCurrentLang(); // → 'en'
Async Pipeline

app.translate

returnsPromise<string>
app.translate(text: string, target: 'en' | 'ur' | 'roman'): Promise<string>

Translates a phrase or sentence using the full multi-tier offline pipeline.

Parameters
textstring— Input text to translate.
target'en' | 'ur' | 'roman'— Target language.
Example
const translated = await app.translate('Contact Us', 'ur');
console.log(translated); // → 'ہم سے رابطہ کریں'
Collector

app.getMissingWords

returnsMissingWordRecord[]
app.getMissingWords(): MissingWordRecord[]

Returns all unknown or untranslated words tracked during user browsing sessions.

Example
const missing = app.getMissingWords();
console.log(missing);
Cleanup

app.destroy

returnsvoid
app.destroy(): void

Unmounts the floating switcher UI, detaches DOM mutation observers, and frees memory listeners.

Example
app.destroy();

Configuration Options (UrduMagicConfig)

Configuration object accepted by UrduMagic.init(config) and <UrduMagicProvider config={...}>:

| Option | Type | Default | Required | Description | | :--- | :--- | :--- | :--- | :--- | | defaultLang | 'en' \| 'ur' \| 'roman' | 'en' | Yes | Initial active language mode on first page load. | | modes | ('en' \| 'ur' \| 'roman')[] | ['en', 'ur', 'roman'] | Yes | Supported language options displayed in the UI switcher. | | showSwitcher | boolean | true | No | Automatically renders the floating language switcher button. | | strategy | 'offline' | 'offline' | No | Translation execution strategy (offline-first). | | performance | PerformanceConfig | { debounceMs: 300 } | No | Controls DOM mutation debounce timing and LRU cache sizes. | | security | SecurityConfig | { sanitizeHtml: true } | No | XSS sanitization and prototype pollution protection. | | onLangSwitch | (lang: LangMode) => void | undefined | No | Callback invoked whenever the user switches languages. |


React Integration (urdumagic/react)

UrduMagic provides idiomatic React hooks and Context Providers:

tsx
import { useUrduMagic, UrduMagicProvider, useUrduMagicContext } from 'urdumagic/react';

Hook Return Value (useUrduMagic & useUrduMagicContext)

| Property | Type | Description | | :--- | :--- | :--- | | currentLanguage | 'en' \| 'ur' \| 'roman' | Active language code. | | switchLang | (lang: LangMode) => void | Function to switch the website language. | | translate | (text: string, target: LangMode) => Promise<string> | Translation helper function. | | toUrdu | (text: string) => string | Roman Urdu to Urdu script transliteration. | | toRoman | (text: string) => string | Urdu script to Roman Urdu transliteration. | | isTranslating | boolean | true while DOM translation mutations are processing. | | isReady | boolean | true once dictionary and fonts are loaded in memory. | | error | string \| null | Error message if initialization encountered an issue. | | instance | UrduMagicInstance \| null | Direct reference to the underlying core instance. |