langsys-js-typescript 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/locale.ts","../src/signal.ts","../src/logger.ts","../src/api.ts","../src/persist.ts","../src/stores.ts","../src/interpolate.ts","../src/translations.ts","../src/langsys-app.ts","../src/utils.ts","../src/content-block.ts","../src/translate.ts","../src/richtext.ts","../src/phrase.ts","../src/index.ts"],"names":["config","IntlMessageFormat","branch","t","initialTranslations","x","c","a","b","d","i"],"mappings":";;;;;AAqBO,SAAS,mBAAmB,MAAA,EAAwB;AACvD,EAAA,IAAI,CAAC,MAAA,IAAU,OAAO,MAAA,KAAW,UAAU,OAAO,MAAA;AAClD,EAAA,MAAM,UAAU,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,MAAM,GAAG,CAAA;AAC/C,EAAA,IAAI;AACA,IAAA,MAAM,CAAC,SAAS,CAAA,GAAI,IAAA,CAAK,oBAAoB,OAAO,CAAA;AACpD,IAAA,OAAO,SAAA,IAAa,OAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AAEJ,IAAA,OAAO,QACF,KAAA,CAAM,GAAG,EACT,GAAA,CAAI,CAAC,MAAM,CAAA,KAAM;AACd,MAAA,IAAI,CAAA,KAAM,CAAA,EAAG,OAAO,IAAA,CAAK,WAAA,EAAY;AACrC,MAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA,CAAK,CAAC,CAAA,CAAE,WAAA,EAAY,GAAI,IAAA,CAAK,KAAA,CAAM,CAAC,EAAE,WAAA,EAAY;AAChF,MAAA,IAAI,IAAA,CAAK,WAAW,CAAA,IAAK,SAAA,CAAU,KAAK,IAAI,CAAA,EAAG,OAAO,IAAA,CAAK,WAAA,EAAY;AACvE,MAAA,OAAO,KAAK,WAAA,EAAY;AAAA,IAC5B,CAAC,CAAA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UAAA,EAAY,CAAC,IAAA,CAAK,MAAM,GAAG,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,QAAA,IAAY,MAAS,CAAA;AAAA,EAC1F;AAAA,EAEQ,OAAA,GAAgB;AACpB,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAElB,IAAA,MAAM,GAAA,GAAM,WAAW,YAAA,CAAa,MAAA,CAAO,KAAK,MAAA,EAAQ,IAAA,CAAK,QAAQ,CAAA,IAAK,IAAA,CAAK,MAAA;AAC/E,IAAA,MAAM,MAAA,GAAS,EAAE,GAAG,IAAA,CAAK,MAAA,EAAQ,GAAG,iBAAA,CAAkB,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA,EAAE;AACzE,IAAA,MAAM,WAAW,WAAA,CAAY,GAAA,EAAK,MAAA,EAAQ,qBAAA,CAAsB,KAAK,CAAA;AACrE,IAAA,MAAM,KAAA,GAAQ,aAAa,QAAA,EAAU,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA,CAAK,iBAAiB,QAAQ,CAAA;AAEpF,IAAA,IAAA,CAAK,IAAA,CAAK,eAAA,CAAgB,GAAG,KAAK,CAAA;AAAA,EACtC;AACJ;;;ACnDO,IAAM,CAAA,IAAgB,CAAC,MAAA,EAAA,GAAmB,IAAA,KAA4B;AAIzE,EAAA,OAAQ,UAAA,CAAY,YAAA,CAAa,CAAA,CAAkC,MAAA,EAAQ,GAAG,IAAI,CAAA;AACtF,CAAA;AAEO,IAAM,OAAA,GAAU,WAAY,YAAA,CAAa","file":"index.js","sourcesContent":["/**\n * Locale-identifier handling, CLDR/BCP 47 flavored. Everything here rides on\n * the platform's native `Intl` — no bundled locale data.\n *\n * The SDK's convention: canonicalize once at every input boundary (init\n * config, user-locale store emissions, detectPreferredLocale, API routes) and\n * treat the canonical string as the identity everywhere downstream — cache\n * keys, equality checks, and the wire format all use it.\n */\n\n/**\n * Canonicalize a locale identifier to BCP 47 canonical form (the form CLDR\n * data is keyed by): language lowercase, script Titlecase, region uppercase —\n * `en-us` → `en-US`, `zh-hant-tw` → `zh-Hant-TW`. Underscores are accepted\n * and converted (`en_US` → `en-US`). Legacy aliases are resolved (`iw` → `he`,\n * `in` → `id`).\n *\n * Structurally invalid tags fall back to best-effort manual casing rather\n * than throwing, so a bad config value degrades to a failed catalog lookup\n * instead of a crash.\n */\nexport function canonicalizeLocale(locale: string): string {\n if (!locale || typeof locale !== 'string') return locale;\n const cleaned = locale.trim().replace(/_/g, '-');\n try {\n const [canonical] = Intl.getCanonicalLocales(cleaned);\n return canonical ?? cleaned;\n } catch {\n // Not a valid BCP 47 tag — apply canonical casing per subtag shape.\n return cleaned\n .split('-')\n .map((part, i) => {\n if (i === 0) return part.toLowerCase();\n if (part.length === 4) return part[0].toUpperCase() + part.slice(1).toLowerCase();\n if (part.length === 2 || /^\\d{3}$/.test(part)) return part.toUpperCase();\n return part.toLowerCase();\n })\n .join('-');\n }\n}\n\n/**\n * The `language-script` key of a locale after CLDR likely-subtags expansion\n * (`Intl.Locale.maximize()`): `zh` → `zh-Hans`, `zh-TW` → `zh-Hant`,\n * `sr` → `sr-Cyrl`. Two locales with the same key are mutually intelligible\n * at the script level; two with different keys must not fall back to each\n * other (a `zh-Hant` reader must never receive a `zh-Hans` catalog).\n *\n * Returns `null` when the tag can't be parsed — callers should treat that\n * as \"no match\" rather than guessing.\n */\nexport function maximizedLangScript(locale: string): string | null {\n try {\n const max = new Intl.Locale(canonicalizeLocale(locale)).maximize();\n return `${max.language}-${max.script ?? ''}`;\n } catch {\n return null;\n }\n}\n","/**\n * Tiny framework-agnostic reactive value holder — our replacement for a\n * Svelte `Writable<T>`. The shape is deliberately similar so the mental\n * model is identical: subscribe/set/update/get.\n *\n * Usage:\n * const locale = createSignal('en-us');\n * locale.subscribe((v) => console.log('locale is now', v));\n * locale.set('fr-fr');\n * locale.get(); // 'fr-fr'\n *\n * Subscribe is called synchronously with the current value on registration\n * (same semantics as a Svelte store).\n */\nexport type Subscriber<T> = (value: T) => void;\nexport type Unsubscriber = () => void;\nexport type Updater<T> = (value: T) => T;\n\nexport interface Signal<T> {\n /** Register a subscriber; it's called immediately with the current value. Returns an unsubscribe function. */\n subscribe(run: Subscriber<T>): Unsubscriber;\n /** Set the value and notify subscribers. */\n set(value: T): void;\n /** Update the value via a function and notify subscribers. */\n update(fn: Updater<T>): void;\n /** Read the current value without subscribing. */\n get(): T;\n}\n\nexport function createSignal<T>(initial: T): Signal<T> {\n let value: T = initial;\n const subscribers = new Set<Subscriber<T>>();\n\n const subscribe = (run: Subscriber<T>): Unsubscriber => {\n subscribers.add(run);\n run(value);\n return () => {\n subscribers.delete(run);\n };\n };\n\n const set = (next: T): void => {\n if (Object.is(value, next)) return;\n value = next;\n for (const run of subscribers) run(value);\n };\n\n const update = (fn: Updater<T>): void => {\n set(fn(value));\n };\n\n const get = (): T => value;\n\n return { subscribe, set, update, get };\n}\n\n/** Synchronously read a Signal's value. Mirrors svelte's `get(store)`. */\nexport function getValue<T>(signal: Signal<T>): T {\n return signal.get();\n}\n","/**\n * Lightweight debug logger. Styled in browsers (via %c), plain text in Node.\n * Replaces the pre-existing `echo` module from the Svelte SDK with a simpler,\n * SSR-safe equivalent.\n */\n\nconst STYLES = {\n log: 'display:inline-block;background:rgb(239,239,244);color:black;font-weight:bold;padding:3px 7px;border-radius:3px',\n warn: 'display:inline-block;background:gold;color:black;font-weight:bold;padding:3px 7px;border-radius:3px',\n error: 'display:inline-block;background:#e0005a;color:#fff;font-weight:bold;padding:3px 7px;border-radius:3px',\n};\n\nconst supportsStyle = typeof window !== 'undefined';\n\nfunction emit(level: 'log' | 'warn' | 'error', label: string, args: unknown[]) {\n // Browsers render %c style. Node just gets the plain string.\n if (supportsStyle) {\n // eslint-disable-next-line no-console\n console[level](`%c${label}`, STYLES[level], ...args);\n } else {\n // eslint-disable-next-line no-console\n console[level](`[${label}]`, ...args);\n }\n}\n\nexport class Logger {\n debugEnabled: boolean;\n\n constructor(debugEnabled = false) {\n this.debugEnabled = debugEnabled;\n }\n\n log(...args: unknown[]) {\n if (!this.debugEnabled) return;\n emit('log', 'Langsys Debug', args);\n }\n\n warn(...args: unknown[]) {\n emit('warn', 'Langsys Warning', args);\n }\n\n error(...args: unknown[]) {\n emit('error', 'Langsys Error', args);\n }\n}\n\nexport const logger = new Logger(false);\n","import { canonicalizeLocale } from './locale.js';\nimport { createSignal } from './signal.js';\nimport type { HttpResponse, ResponseObject } from './types/api.js';\nimport type { iLangsysConfig } from './types/config.js';\nimport { logger } from './logger.js';\n\ntype Method = 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT';\n\nclass LangsysAppAPIClass {\n private apiurl = 'https://api.langsys.dev/api';\n public config: iLangsysConfig;\n private headers: { 'Content-Type': string; 'x-Authorization': string; 'X-Langsys-Capabilities': string };\n\n constructor() {\n this.config = {\n projectid: '',\n key: '',\n sUserLocale: createSignal(''),\n baseLocale: 'en',\n };\n this.headers = {\n 'Content-Type': 'application/json; charset=utf-8',\n 'x-Authorization': this.config.key,\n // Declare ICU MessageFormat rendering so the server sends raw ICU\n // (plural/select) instead of flat-template downgrades. Pre-ICU\n // builds omit this header and keep receiving flat strings.\n 'X-Langsys-Capabilities': 'icu',\n };\n }\n\n public setup(config: iLangsysConfig) {\n if (config?.key && config?.projectid) {\n this.config = config;\n this.headers['x-Authorization'] = this.config.key;\n }\n }\n\n /** Optional hook to point the client at a different API host. */\n public setBaseUrl(url: string) {\n this.apiurl = url.replace(/\\/$/, '');\n }\n\n public async validate(config: iLangsysConfig) {\n this.setup(config);\n return await this.get('authorize-project/[projectid]');\n }\n\n public async getTranslations(locale: string) {\n // The CLDR-compliant backend keys catalogs by canonical BCP 47 tags.\n return await this.get('translations', { project_id: this.config.projectid, locale: canonicalizeLocale(locale) });\n }\n\n /**\n * Register phrases and/or content blocks via the current unified endpoint.\n * Each item carries `type: 'phrase' | 'content_block'`. Replaces the\n * deprecated `projects/{id}/tokens` and `projects/{id}/content-blocks` routes.\n */\n public async createTranslatableItems(items: Array<Record<string, unknown>>) {\n return await this.post('translatable-items', {\n project_id: this.config.projectid,\n translatable_items: items,\n });\n }\n\n public async post(path: string, data: Record<string, unknown> = {}) {\n return await this.send('POST', path, data);\n }\n public async get(path: string, data: Record<string, unknown> = {}) {\n return await this.send('GET', path, data);\n }\n public async delete(path: string, data: Record<string, unknown> = {}) {\n return await this.send('DELETE', path, data);\n }\n public async patch(path: string, data: Record<string, unknown> = {}) {\n return await this.send('PATCH', path, data);\n }\n public async put(path: string, data: Record<string, unknown> = {}) {\n return await this.send('PUT', path, data);\n }\n\n private async send(method: Method, path: string, data: Record<string, unknown> = {}): Promise<ResponseObject> {\n if (!this.config.projectid || !this.config.key) {\n return {\n status: false,\n errors: ['Missing projectid or API key in configuration'],\n http: {\n status: 0,\n statusText: 'Configuration Error',\n url: `${this.apiurl}/${path}`,\n data: JSON.stringify(data),\n },\n };\n }\n\n // API calls should not include a leading slash.\n if (path.startsWith('/')) path = path.substring(1);\n\n // Replace [projectid] token with the actual configured projectid.\n if (path.includes('/[projectid]')) {\n path = path.replaceAll('/[projectid]', `/${this.config.projectid}`);\n }\n\n try {\n const querystring =\n method === 'GET'\n ? '?' + new URLSearchParams(data as Record<string, string>).toString()\n : '';\n\n const query = await fetch(`${this.apiurl}/${path}${querystring === '?' ? '' : querystring}`, {\n headers: this.headers,\n method,\n body: method === 'GET' ? undefined : JSON.stringify(data),\n });\n\n const responseData = (await query.json()) as ResponseObject;\n const http: HttpResponse = {\n status: query.status,\n statusText: query.statusText,\n url: query.url,\n data: JSON.stringify(data),\n };\n responseData.http = http;\n\n if (!query.ok) {\n logger.warn('LangsysAppAPI failed to query', responseData);\n return {\n status: false,\n errors: [`HTTP ${query.status}: ${query.statusText}`],\n data: responseData,\n http,\n };\n }\n\n return responseData;\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';\n logger.error('LangsysAppAPI Error:', errorMessage);\n logger.error('Request details:', {\n method,\n url: `${this.apiurl}/${path}`,\n data,\n });\n return {\n status: false,\n errors: ['Error communicating with API Server', errorMessage],\n http: {\n status: 0,\n statusText: 'Network Error',\n url: `${this.apiurl}/${path}`,\n data: JSON.stringify(data),\n },\n };\n }\n }\n}\n\nexport const LangsysAppAPI = new LangsysAppAPIClass();\nexport default LangsysAppAPI;\n","import { createSignal, type Signal } from './signal.js';\n\n/**\n * Create a Signal whose value is persisted to localStorage (when available).\n * Falls back to in-memory behavior during SSR or when storage is unavailable\n * or quota-exceeded. Stored value is JSON-encoded.\n */\nexport function persist<T>(key: string, initial: T): Signal<T> {\n const storage = getSafeStorage();\n let seed = initial;\n\n if (storage) {\n try {\n const raw = storage.getItem(key);\n if (raw !== null) seed = JSON.parse(raw) as T;\n } catch {\n // Corrupt value; fall through to initial.\n }\n }\n\n const signal = createSignal<T>(seed);\n\n if (storage) {\n signal.subscribe((value) => {\n try {\n storage.setItem(key, JSON.stringify(value));\n } catch {\n // Quota / serialization failure — silently keep going; in-memory stays authoritative.\n }\n });\n }\n\n return signal;\n}\n\nfunction getSafeStorage(): Storage | null {\n if (typeof window === 'undefined') return null;\n try {\n const s = window.localStorage;\n // Some browsers throw on access in private-mode iframes.\n s.getItem('__langsys_probe__');\n return s;\n } catch {\n return null;\n }\n}\n","import { createSignal } from './signal.js';\nimport { persist } from './persist.js';\nimport type { iCategories } from './types/translations.js';\nimport type { iLangsysConfig } from './types/config.js';\n\nconst initialTranslations: iCategories = {\n __uncategorized__: {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n },\n};\n\nexport const sTranslations = persist<iCategories>('translations', initialTranslations);\n\nexport const currentlyLoadedLocale = createSignal<string>('');\n\nexport const config: iLangsysConfig = {\n projectid: '',\n key: '',\n sUserLocale: createSignal<string>(''),\n baseLocale: 'en',\n debug: false,\n key_type: 'read',\n};\n","import { IntlMessageFormat } from 'intl-messageformat';\nimport { logger } from './logger.js';\n\n/**\n * Detects ICU MessageFormat syntax in a translation string.\n *\n * - Matches `{var, plural, …}`, `{var, select, …}`, `{var, selectordinal, …}`,\n * `{var, number, …}`, `{var, date, …}`, `{var, time, …}`.\n * - Also matches the style-less forms `{var, number}`, `{var, date}`,\n * `{var, time}` — valid ICU with the locale-default style.\n * - Doesn't match plain interpolation slots like `{name}` or `{count}`.\n *\n * Exported because the Translation Manager UI needs the same detection logic\n * to decide whether to render a plural-slot editor vs. a single text field.\n */\nexport function isICU(template: string): boolean {\n return ICU_PATTERN.test(template);\n}\n\n// `[,}]` after the keyword: a style argument may follow (`{n, number, ::…}`)\n// or the argument may close immediately (`{n, number}` — locale-default style).\nconst ICU_PATTERN = /\\{[^{}]+,\\s*(plural|select|selectordinal|number|date|time)\\s*[,}]/;\n\n/**\n * Normalize `%name%` markup placeholders to canonical `{name}`.\n *\n * Framework compilers consume bare `{name}` written in markup before the DOM\n * walker ever sees it (Svelte compiles it to an expression; JSX evaluates it),\n * so DOM content accepts `%name%` as a collision-free authoring escape.\n * Normalization runs at every markup capture boundary (content-block\n * tokenizer, `Translate` original-value snapshots, `Phrase` encoding), so the\n * catalog, the wire, and translators only ever see the canonical `{name}`\n * form — and plain `{name}` keeps working for vanilla-HTML authors.\n *\n * Keys must be identifiers (`[A-Za-z_][A-Za-z0-9_]*`), so literal `%` in\n * prose (\"20% off\", \"50% to 60%\") can't match. `t()` phrases are JS strings\n * with no compiler collision and stay `{name}`-only.\n */\nexport function normalizeMarkupPlaceholders(text: string): string {\n return text.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, '{$1}');\n}\n\n/** Escape a params key for literal use inside a RegExp. */\nfunction escapeForRegExp(key: string): string {\n return key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Params keys that have NO matching placeholder in `texts`.\n *\n * Texts are expected in canonical form (post-`normalizeMarkupPlaceholders`),\n * so a key counts as used when it appears as `{key}` or as the argument of an\n * ICU slot (`{key, plural, …}`). Surrounding whitespace is tolerated.\n */\nexport function findUnusedParamKeys(texts: string[], params: Record<string, unknown> | undefined): string[] {\n if (!params) return [];\n const keys = Object.keys(params);\n if (!keys.length || !texts.length) return keys;\n\n const haystack = texts.join('\u0000');\n return keys.filter((key) => !new RegExp(`\\\\{\\\\s*${escapeForRegExp(key)}\\\\s*[,}]`).test(haystack));\n}\n\n/**\n * Debug-time warning for the single most common markup-interpolation mistake:\n * writing `{name}` instead of `%name%` inside `<Translate>`/`<Phrase>` content.\n *\n * We can't see the mistake directly — Svelte and JSX substitute `{name}` at\n * compile time, so the SDK only ever receives the already-substituted text.\n * But the fingerprint is unmistakable: params were supplied and NONE of their\n * keys survive as placeholders in the captured content. Left undetected this\n * fails silently (the base locale still looks right), so it's worth naming\n * explicitly.\n *\n * Only emits when debug logging is on — silent in production.\n */\nexport function warnUnmatchedParams(\n source: string,\n texts: string[],\n params: Record<string, unknown> | undefined,\n context?: string,\n): void {\n if (!logger.debugEnabled) return;\n\n const unused = findUnusedParamKeys(texts, params);\n if (!unused.length) return;\n\n const keyList = unused.map((key) => `%${key}%`).join(', ');\n // Framework-neutral wording: the brace spelling that gets eaten differs by\n // framework (Svelte/JSX consume `{key}`, Vue consumes `{{ key }}`), and the\n // SDK has no idea which one it's running under.\n logger.warn(\n `${source} received params with no matching placeholder in its content: ${keyList}.` +\n ` If you wrote {${unused[0]}} or {{ ${unused[0]} }} in markup, your framework's template` +\n ` compiler substituted it before Langsys saw the text — write %${unused[0]}% instead.` +\n (context ? ` [${context}]` : ''),\n );\n}\n\n/**\n * Substitute placeholders in a translated string with values from `params`.\n *\n * Two paths:\n * - ICU MessageFormat (target string contains `{var, plural|select|…, …}`):\n * parsed and formatted via `intl-messageformat`, which knows every\n * target locale's plural rules (Arabic's 6 categories, Russian's 4,\n * etc.) and gender-select branches.\n * - Simple `{name}` interpolation: cheap regex replacement. Unknown\n * placeholders are left untouched so missing data is visible to the\n * developer rather than silently rendering empty strings. Number and\n * Date values are formatted per the target locale's CLDR rules\n * (`Intl.NumberFormat` / `Intl.DateTimeFormat`) — pass numbers as\n * strings to opt out (e.g. IDs and codes that must not get grouping\n * separators).\n *\n * Malformed ICU falls through to simple interpolation rather than throwing,\n * so the developer sees a broken-but-visible string instead of a runtime crash.\n * Backend-side validation in langsys-ai is supposed to prevent this — the\n * fall-through is defense in depth.\n *\n * `locale` is required for ICU formatting (drives plural-rule selection).\n * Falls back to `'en'` if absent — simple-interpolation path ignores it.\n */\nexport function interpolate(\n template: string,\n params: Record<string, unknown>,\n locale?: string,\n): string {\n if (isICU(template)) {\n const resolved = locale || 'en';\n // A null value does NOT throw — `intl-messageformat` coerces it (null\n // becomes 0, so `{count, plural…}` renders \"0 items\"). That would make a\n // bug indistinguishable from valid data: a real empty cart and a failure\n // to pass the count would render identically. So null is routed straight\n // to recovery, where it is treated as missing — matching langsys-php,\n // which tests this explicitly. A genuine 0 is untouched and still\n // renders \"0 items\".\n const hasNullParam = !!params && Object.values(params).some((value) => value === null);\n if (!hasNullParam) {\n try {\n return new IntlMessageFormat(template, resolved).format(params) as string;\n } catch {\n // fall through to recovery below\n }\n }\n {\n // A missing argument throws. Recover the sentence rather than\n // dumping ICU source to the page — see `_recoverMissingArgs`.\n try {\n // `.ast` is typed private but is the parsed message the library\n // formats from, and `IntlMessageFormat` accepts an AST in place\n // of a string. Reaching for it avoids taking a second runtime\n // dependency on the parser just to re-parse what's already\n // parsed. Guarded: anything unexpected falls through to the\n // simple path, which is the pre-0.6.4 behavior.\n const ast = (new IntlMessageFormat(template, resolved) as unknown as { ast?: unknown }).ast;\n if (!Array.isArray(ast)) return simpleInterpolate(template, params, locale);\n const recovered = _recoverMissingArgs(JSON.parse(JSON.stringify(ast)) as IcuNode[], params);\n return new IntlMessageFormat(recovered as never, resolved).format(params) as string;\n } catch {\n return simpleInterpolate(template, params, locale);\n }\n }\n }\n return simpleInterpolate(template, params, locale);\n}\n\n/** ICU AST node types we care about (from `@formatjs/icu-messageformat-parser`). */\nconst ICU_LITERAL = 0;\nconst ICU_ARGUMENT = 1;\nconst ICU_NUMBER = 2;\nconst ICU_DATE = 3;\nconst ICU_TIME = 4;\nconst ICU_SELECT = 5;\nconst ICU_PLURAL = 6;\nconst ICU_POUND = 7;\nconst ICU_TAG = 8;\n\ninterface IcuNode {\n type: number;\n value?: string;\n options?: Record<string, { value: IcuNode[] }>;\n children?: IcuNode[];\n}\n\n/**\n * Rewrite an ICU AST so a MISSING argument degrades gracefully instead of\n * taking the whole message down.\n *\n * Why this is reachable without any caller mistake: langsys-ai's ICU promoter\n * can *introduce* a select argument the source phrase never had — a plain\n * `{name}` becomes `{name_gender, select, …}` in gendered target locales. The\n * application cannot supply `name_gender`; it doesn't exist in the phrase the\n * developer wrote, and nothing tells them the target grew one. Every app\n * translating into a gendered locale hits this.\n *\n * The recovery, agreed with `langsys-php` so a shared catalog can't render two\n * different sentences for the same input:\n *\n * - **`select`** → take the `other` branch. Recoverable: `other` is exactly\n * what an unknown gender should render, so the sentence comes out correct.\n * - **`plural`** → take the `other` branch, rendering `#` as `{argName}`.\n * Nothing can be inferred for a count, so this is only made less bad: the\n * sentence survives with a visible gap.\n * - **plain arguments** (`{name}`, `{n, number}`, dates) → render as\n * `{argName}`, matching the simple path's rule that unknown keys stay\n * visible rather than blanking.\n *\n * Elements whose argument IS supplied are left untouched and recursed into, so\n * a missing argument nested inside a satisfied branch is still recovered.\n * `plural`/`select` without an `other` branch is malformed ICU — left alone, so\n * it falls through to the simple path as before.\n */\nfunction _recoverMissingArgs(nodes: IcuNode[], params: Record<string, unknown>): IcuNode[] {\n const out: IcuNode[] = [];\n\n for (const node of nodes) {\n const name = node.value;\n // `null` counts as missing, matching the simple path where a present-\n // but-null value is left visible rather than rendered as 0 or \"null\".\n const value = name !== undefined && name in params ? params[name] : undefined;\n const supplied = value !== undefined && value !== null;\n\n if (node.type === ICU_TAG) {\n out.push({ ...node, children: _recoverMissingArgs(node.children ?? [], params) });\n continue;\n }\n\n if (node.type === ICU_SELECT || node.type === ICU_PLURAL) {\n if (supplied) {\n const options: Record<string, { value: IcuNode[] }> = {};\n for (const [key, branch] of Object.entries(node.options ?? {})) {\n options[key] = { value: _recoverMissingArgs(branch.value, params) };\n }\n out.push({ ...node, options });\n continue;\n }\n const other = node.options?.other;\n if (!other) {\n out.push(node); // malformed — let the simple path handle it\n continue;\n }\n const branch = _recoverMissingArgs(other.value, params);\n // `#` has no count to render, so show the argument name instead.\n out.push(\n ...branch.map((child) =>\n child.type === ICU_POUND ? { type: ICU_LITERAL, value: `{${name}}` } : child,\n ),\n );\n continue;\n }\n\n if (\n !supplied &&\n (node.type === ICU_ARGUMENT ||\n node.type === ICU_NUMBER ||\n node.type === ICU_DATE ||\n node.type === ICU_TIME)\n ) {\n out.push({ type: ICU_LITERAL, value: `{${name}}` });\n continue;\n }\n\n out.push(node);\n }\n\n return out;\n}\n\nfunction simpleInterpolate(template: string, params: Record<string, unknown>, locale?: string): string {\n // The `[^{},]` character class excludes `{`, `}`, and `,` from placeholder\n // names so we don't accidentally consume ICU-shaped slots that somehow\n // routed through this path (e.g. malformed ICU after fall-through).\n return template.replace(/\\{([^{},]+)\\}/g, (match, rawKey: string) => {\n const key = rawKey.trim();\n if (!(key in params)) return match;\n const value = params[key];\n if (value === undefined || value === null) return match;\n // CLDR-formatted output for numbers and dates, mirroring what the ICU\n // defaults (`{n, number}`, `{d, date}` → medium) would produce. The\n // try/catch guards against invalid locale tags — fall back to the\n // locale-blind rendering rather than throwing mid-render.\n if (value instanceof Date) {\n try {\n return new Intl.DateTimeFormat(locale || 'en', { dateStyle: 'medium' }).format(value);\n } catch {\n return value.toISOString();\n }\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n try {\n return new Intl.NumberFormat(locale || 'en').format(value);\n } catch {\n return String(value);\n }\n }\n return String(value);\n });\n}\n","import { LangsysAppAPI } from './api.js';\nimport { interpolate } from './interpolate.js';\nimport { canonicalizeLocale } from './locale.js';\nimport { Logger } from './logger.js';\nimport { createSignal, type Signal } from './signal.js';\nimport { currentlyLoadedLocale, sTranslations } from './stores.js';\nimport type { ResponseObject } from './types/api.js';\nimport type { iLangsysConfig } from './types/config.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { iCategories, iTranslations } from './types/translations.js';\n\ninterface iTokenUpdate {\n projectid: string;\n category: string;\n token: string;\n}\n\nfunction isObject(test: unknown): test is Record<string, unknown> {\n return typeof test === 'object' && !Array.isArray(test) && test !== null;\n}\nfunction sameToken(a: iTokenUpdate, b: iTokenUpdate): boolean {\n return a.projectid === b.projectid && a.category === b.category && a.token === b.token;\n}\n\n/**\n * Lifecycle for app translations:\n * - on-miss: any `t(cat, phrase)` whose phrase isn't in the catalog is\n * queued as a \"missing token\" and (with write keys) flushed to the API.\n * - locale changes trigger `change()` which fetches and replaces.\n * - consumers can `subscribe(fn)` to react to translation snapshots.\n * - frameworks subscribe to `tSignal` (which re-emits a fresh `TFunction`\n * every time translations or the loaded locale change) so reactive\n * templates re-render automatically.\n */\nexport class Translations {\n private config: iLangsysConfig;\n private locale: string;\n private lastLoaded: Record<string, number> = {};\n private missingTokens: iTokenUpdate[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private flushScheduled = false;\n private isFirstClientRun = true;\n private readyResolve: () => void = () => {};\n private readyPromise: Promise<void> = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n public debug: Logger;\n\n /** Reactive holder for the current translation function. Re-emits on every catalog/locale change. */\n public tSignal: Signal<TFunction>;\n\n constructor(config: iLangsysConfig) {\n this.config = config;\n this.debug = new Logger(!!config.debug);\n this.locale = canonicalizeLocale(config.baseLocale || '');\n\n this.tSignal = createSignal<TFunction>(this.buildTFn());\n sTranslations.subscribe(() => this.tSignal.set(this.buildTFn()));\n currentlyLoadedLocale.subscribe(() => this.tSignal.set(this.buildTFn()));\n\n if (config.key && config.projectid) this.setup(config);\n }\n\n /**\n * Resolves once the first `getTranslations` call has completed (or\n * immediately if no fetch is configured). Callers that need to read\n * `sTranslations` before issuing a write — e.g. the `Translate` DOM\n * class deciding whether to POST a content block — should await this\n * to avoid acting on an empty cache during the cold-start race.\n */\n public ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /** Current translation function. Reads fresh state on every call. */\n public get t(): TFunction {\n return this.tSignal.get();\n }\n\n /** Subscribe to translation snapshot changes. Fires immediately with the current value. */\n public subscribe(run: (value: iCategories) => void) {\n return sTranslations.subscribe(run);\n }\n\n /**\n * Content-block-keyed lookup used by the DOM `Translate` class.\n * Returns the per-token translation inside a content block, or `null` if\n * either the content block or the inner token is missing. Never registers\n * a missing token — the DOM class manages its own lifecycle via content blocks.\n */\n public lookupContent(category: string, customId: string, token: string): string | null {\n const cats = sTranslations.get();\n const lookupCat = category || '__uncategorized__';\n const contentData = cats[lookupCat]?.[customId];\n if (!contentData || typeof contentData !== 'object') return null;\n const value = (contentData as unknown as Record<string, string>)[token];\n return typeof value === 'string' ? value : null;\n }\n\n /**\n * Raw stored translation for a phrase, without interpolation or\n * missing-token registration. Returns null when no (non-empty) translation\n * is cached. Used by the `Phrase` rich-text handler, which needs the\n * un-interpolated template (it supplies its own markup-token values).\n */\n public lookup(phrase: string, category: string): string | null {\n const cats = sTranslations.get();\n const lookupCat = category || '__uncategorized__';\n const value = cats[lookupCat]?.[phrase];\n return typeof value === 'string' && value.length > 0 ? value : null;\n }\n\n private buildTFn(): TFunction {\n // Single runtime body covers both overload shapes. Position 2 is the\n // discriminator: string ⇒ category, object ⇒ params (no category).\n // t(phrase) → category='', params=undefined\n // t(phrase, {params...}) → category='', params={params}\n // t(phrase, 'Category') → category='Category', params=undefined\n // t(phrase, 'Category', {params...}) → category='Category', params={params}\n const fn = ((phrase: string, ...rest: unknown[]): string => {\n const category = typeof rest[0] === 'string' ? rest[0] : '';\n const params = (typeof rest[0] === 'object' ? rest[0] : rest[1]) as Record<string, unknown> | undefined;\n\n const cats = sTranslations.get();\n // '__uncategorized__' is a server-internal bucket name used only\n // in GET /translations responses to group null-category phrases.\n // We normalize to it for the local cats lookup (so we read from\n // the same bucket the server writes to), but we MUST NOT leak\n // the sentinel back into the missingToken queue — that queue\n // feeds the POST wire payload, and clients are not allowed to\n // send the reserved sentinel as a category.\n const lookupCat = category || '__uncategorized__';\n const value = cats[lookupCat]?.[phrase];\n\n let translated: string;\n if (typeof value === 'string' && value.length > 0) {\n this.debug.log('TRANSLATION FOUND', [lookupCat, phrase, value]);\n translated = value;\n } else {\n this.missingToken(category, phrase);\n translated = phrase;\n }\n\n return params ? interpolate(translated, params, currentlyLoadedLocale.get()) : translated;\n }) as TFunction;\n return fn;\n }\n\n private missingToken(category: string, token: string | undefined | null) {\n if (token === undefined || token === null) {\n return this.debug.warn(`Received undefined or null token for category: ${category}`);\n }\n\n if (this.config.key_type !== 'write') {\n this.debug.log(`Skipping missing token collection (API key is ${this.config.key_type || 'unknown'}):`, {\n category,\n token,\n });\n return;\n }\n\n // Skip content-block id lookups (32-hex md5 strings).\n if (/^[0-9a-f]{32}$/.test(token)) return;\n if (token === 'toJSON') {\n this.debug.error(`Received toJSON as token ${category}:${token}`, token);\n return;\n }\n if (token === '') {\n this.debug.warn('Received empty token', token);\n return;\n }\n\n const missingToken: iTokenUpdate = { category, token, projectid: this.config.projectid };\n if (!this.missingTokens.some((t) => sameToken(t, missingToken))) {\n this.debug.log('MISSING TOKEN LOOKUP FAILED', [missingToken, [...this.missingTokens], { ...sTranslations.get() }]);\n this.missingTokens.push(missingToken);\n this.scheduleTokenFlush();\n }\n }\n\n private scheduleTokenFlush() {\n const strategy = this.config.ssrTokenStrategy || 'client';\n const isSSR = typeof window === 'undefined';\n\n if (isSSR) {\n switch (strategy) {\n case 'server':\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.updateTokens().then(() => {\n this.flushScheduled = false;\n });\n });\n }\n break;\n\n case 'auto':\n if (this.missingTokens.length <= 5 && !this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.updateTokens().then(() => {\n this.flushScheduled = false;\n });\n });\n }\n break;\n\n case 'client':\n default:\n this.debug.log('SSR: Queuing tokens for client-side transmission');\n break;\n }\n } else {\n // Client — flush immediately on first discovery, then let the 3s timer take over.\n if (!this.flushScheduled && !this.timer) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.updateTokens().then(() => {\n this.flushScheduled = false;\n });\n });\n }\n }\n }\n\n public setup(config: iLangsysConfig) {\n this.config = config;\n if (!this.config.projectid || !this.config.key) return;\n\n if (this.config.debug) this.debug.debugEnabled = this.config.debug;\n if (config.baseLocale) this.locale = canonicalizeLocale(config.baseLocale);\n\n this.debug.log('TRANSLATION SETUP INITIATED', this.config);\n\n if (typeof window !== 'undefined') {\n if (this.isFirstClientRun && this.missingTokens.length > 0) {\n this.isFirstClientRun = false;\n const strategy = this.config.ssrTokenStrategy || 'client';\n if (strategy === 'client' || (strategy === 'auto' && this.missingTokens.length > 5)) {\n this.debug.log(`Post-hydration: Flushing ${this.missingTokens.length} SSR-collected tokens`);\n queueMicrotask(() => this.updateTokens());\n }\n }\n\n if (this.timer) clearInterval(this.timer);\n this.timer = setInterval(() => this.updateTokens(), 3000);\n this.debug.log('UPDATE TOKEN INTERVAL', this.timer);\n } else {\n const strategy = this.config.ssrTokenStrategy || 'client';\n this.debug.log(`SSR environment detected - using '${strategy}' token strategy`);\n }\n }\n\n /**\n * Record that a locale's catalog is already present without fetching —\n * e.g. after an SSR handoff seeds `sTranslations` + `currentlyLoadedLocale`.\n * This primes the same `lastLoaded` cache `change()` consults, so the first\n * settle for that locale is a cache hit (no redundant fetch) while every\n * later switch *to* it still flows through `change()` normally.\n */\n public markLoaded(locale: string): void {\n if (!locale) return;\n locale = canonicalizeLocale(locale);\n this.locale = locale;\n this.lastLoaded[locale] = new Date().getTime() / 1000;\n // A seeded catalog counts as \"ready\": the cache hit above means no\n // fetch will ever fire to resolve the promise, and content-block /\n // Phrase consumers awaiting ready() would otherwise hang forever.\n this.readyResolve();\n }\n\n /**\n * React to a user-locale change. Fetches translations if we haven't\n * loaded this locale within the last 60s (or if forced).\n */\n public async change(locale: string, force = false, skipFetch = false): Promise<boolean> {\n if (!locale) return false;\n if (!this.config.projectid || !this.config.key) return false;\n // Canonical form is the cache identity — `en-us` and `en-US` must hit\n // the same `lastLoaded` entry and compare equal to `this.locale`.\n locale = canonicalizeLocale(locale);\n\n if (skipFetch) {\n this.debug.log('Using pre-fetched translations for locale', locale);\n this.locale = locale;\n this.lastLoaded[locale] = new Date().getTime() / 1000;\n this.readyResolve();\n return true;\n }\n\n const now = new Date().getTime() / 1000;\n if (\n !force &&\n locale === this.locale &&\n this.lastLoaded[locale] &&\n Math.abs(this.lastLoaded[locale] - now) < 60\n ) {\n return false;\n }\n\n this.debug.log('Locale change detected!', locale);\n this.locale = locale;\n await this.getTranslations();\n return true;\n }\n\n private async updateTokens(): Promise<boolean> {\n if (!this.missingTokens.length) return false;\n if (!this.config.projectid || !this.config.key) return false;\n if (this.config.key_type !== 'write') {\n this.debug.log(`Skipping token updates (API key is ${this.config.key_type || 'unknown'})`);\n return false;\n }\n\n if (typeof window === 'undefined') {\n this.debug.log(`Sending ${this.missingTokens.length} tokens from SSR`);\n }\n\n const currentData = sTranslations.get();\n this.missingTokens = this.missingTokens.filter((tokenObj) => {\n tokenObj.projectid = this.config.projectid;\n // The server response keys null-category phrases under\n // '__uncategorized__', so map empty client-side category to that\n // bucket for the dedup check only. The queue itself keeps the\n // original (possibly empty) category for the wire payload.\n const lookupCat = tokenObj.category || '__uncategorized__';\n if (lookupCat in currentData && tokenObj.token in currentData[lookupCat]) {\n this.debug.log('Missing token already exists! Skipping:', {\n category: tokenObj.category,\n token: tokenObj.token,\n existing: currentData[lookupCat][tokenObj.token],\n });\n return false;\n }\n return true;\n });\n\n if (!this.missingTokens.length) return false;\n\n this.debug.log('CREATE MISSING TOKENS', this.missingTokens);\n try {\n // Wire boundary: empty category → null. '__uncategorized__' is\n // server-internal and is rejected as a client input.\n const phraseItems = this.missingTokens.map((tokenObj) => ({\n type: 'phrase',\n phrase: tokenObj.token,\n category: tokenObj.category || null,\n }));\n\n // /translatable-items caps each request (default 200 items); chunk so\n // a page registering many new phrases at once never overflows it.\n const BATCH_SIZE = 200;\n for (let offset = 0; offset < phraseItems.length; offset += BATCH_SIZE) {\n const response: ResponseObject = await LangsysAppAPI.createTranslatableItems(\n phraseItems.slice(offset, offset + BATCH_SIZE),\n );\n if (!response.status) {\n if (response.errors) {\n this.debug.log('TOKEN UPDATE FAIL', this.missingTokens);\n this.debug.error('Error updating project tokens', response.errors);\n }\n return false;\n }\n }\n\n this.missingTokens.forEach((tokenObj) => {\n // Same bucket normalization as the dedup check: write into\n // the cats bucket that matches the server response shape.\n const lookupCat = tokenObj.category || '__uncategorized__';\n if (!currentData[lookupCat]) {\n currentData[lookupCat] = {\n __category__: lookupCat,\n __symbol__: lookupCat,\n } as iTranslations;\n }\n currentData[lookupCat][tokenObj.token] = tokenObj.token;\n currentData[lookupCat]['__category__'] = lookupCat;\n });\n sTranslations.set({ ...currentData });\n this.missingTokens = [];\n return true;\n } catch (err) {\n this.debug.log('CREATE MISSING TOKEN FAILURE', this.missingTokens);\n this.debug.error('Error updating project tokens', err);\n return false;\n }\n }\n\n private async getTranslations(): Promise<void> {\n if (!LangsysAppAPI.config.projectid && this.config.projectid) {\n LangsysAppAPI.setup(this.config);\n }\n\n const response: ResponseObject = await LangsysAppAPI.getTranslations(this.locale);\n this.debug.log('GET TRANSLATIONS API RESPONSE', response);\n if (response.errors) {\n this.debug.error('Error', response.errors[0]);\n this.readyResolve();\n return;\n }\n\n const trans = response.data as iCategories;\n\n if (!isObject(trans['__uncategorized__'])) {\n trans['__uncategorized__'] = {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n } as iTranslations;\n }\n\n for (const cat of Object.keys(trans)) {\n trans[cat]['__category__'] = cat;\n }\n\n this.debug.log('GET TRANSLATIONS ' + this.locale, trans);\n\n sTranslations.set(trans);\n // Small delay so consumers see translations + locale updates on the same tick.\n setTimeout(() => currentlyLoadedLocale.set(this.locale), 100);\n this.lastLoaded[this.locale] = new Date().getTime() / 1000;\n this.readyResolve();\n }\n}\n\nexport default Translations;\n","import { LangsysAppAPI } from './api.js';\nimport { canonicalizeLocale, maximizedLangScript } from './locale.js';\nimport { Logger } from './logger.js';\nimport { config as configStore, currentlyLoadedLocale, sTranslations } from './stores.js';\nimport { Translations } from './translations.js';\nimport type { ResponseObject } from './types/api.js';\nimport type { iLangsysConfig, iLangsysInitConfig } from './types/config.js';\nimport type { iCountryDialCode, iCountryList } from './types/countries.js';\nimport type { iCurrencyList } from './types/currencies.js';\nimport type { iLocaleData, iLocaleDefault, iLocaleFlat } from './types/locales.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { iTranslations } from './types/translations.js';\n\nclass LangsysAppClass {\n private config: iLangsysConfig;\n\n public Translations: Translations;\n public translationsLoadingPromise: Promise<unknown> = Promise.resolve();\n\n private locales: Record<string, iLocaleData[]> = {};\n\n private countries: iCountryList = [];\n private countriesLocale = '';\n\n private dialCodes: iCountryDialCode[] = [];\n private dialCodesLocale = '';\n\n private currencies: iCurrencyList = [];\n private currenciesLocale = '';\n\n public debug: Logger;\n\n constructor() {\n this.config = configStore;\n this.debug = new Logger(!!this.config.debug);\n this.Translations = new Translations(this.config);\n }\n\n /** Current translation function. Reads fresh state on every call. */\n public get t(): TFunction {\n return this.Translations.t;\n }\n\n public async refresh() {\n const locale = this.config.sUserLocale.get();\n this.locales = {};\n return this.Translations.change(locale, true);\n }\n\n /**\n * Initialize Langsys. Configuration must include at least `projectid`,\n * `key`, and `UserLocaleStore` (anything satisfying `LocaleSource` — see\n * its docstring for framework-specific adapters).\n */\n public async init(initConfig: iLangsysInitConfig): Promise<ResponseObject> {\n const projectid = initConfig.projectid;\n const key = initConfig.key;\n const UserLocaleStore = initConfig.UserLocaleStore;\n let baseLocale = initConfig.baseLocale || 'en';\n const debug = initConfig.debug || false;\n const emulateFailureToLoad = initConfig.emulateFailureToLoad || false;\n const ssrTokenStrategy = initConfig.ssrTokenStrategy || 'client';\n const initialTranslations = initConfig.initialTranslations;\n const initialTranslationsLocale = initConfig.initialTranslationsLocale;\n\n this.debug.debugEnabled = debug;\n\n if (debug && initialTranslations) {\n this.debug.log('SSR initial translations config:', {\n hasInitialTranslations: !!initialTranslations,\n initialTranslationsLocale,\n categoriesProvided: initialTranslations ? Object.keys(initialTranslations).length : 0,\n categories: initialTranslations ? Object.keys(initialTranslations) : [],\n });\n }\n\n if (!projectid) {\n this.debug.error('LangsysApp.init missing projectid in configuration object!');\n return { status: false, errors: ['Missing projectid'] };\n }\n if (!key) {\n this.debug.error('LangsysApp.init missing API key in configuration object!');\n return { status: false, errors: ['Missing API key'] };\n }\n if (!UserLocaleStore?.subscribe || typeof UserLocaleStore.get !== 'function') {\n this.debug.error(\n \"LangsysApp.init missing UserLocaleStore — pass any object satisfying LocaleSource (get + subscribe). createSignal('en-US') works if you have nothing of your own.\"\n );\n return { status: false, errors: ['Missing UserLocaleStore'] };\n }\n\n // BCP 47 canonical form (`en-US`, `zh-Hant-TW`) — the CLDR-compliant\n // backend and every internal cache key use this as the identity.\n baseLocale = canonicalizeLocale(baseLocale);\n\n if (!emulateFailureToLoad) {\n this.config = {\n projectid,\n key,\n sUserLocale: UserLocaleStore,\n baseLocale,\n debug,\n ssrTokenStrategy,\n };\n // Keep the exported config singleton in sync (used by Translate + API).\n Object.assign(configStore, this.config);\n }\n\n const validateResponse = await LangsysAppAPI.validate(this.config);\n\n if (validateResponse.status && validateResponse.data) {\n const authData = validateResponse.data as { key_type?: 'read' | 'write' };\n if (authData.key_type) {\n this.config.key_type = authData.key_type;\n configStore.key_type = authData.key_type;\n this.debug.log('API Key Type:', this.config.key_type);\n }\n }\n\n // Seed the translations store if initial data is provided (SSR handoff).\n if (initialTranslations && initialTranslationsLocale) {\n if (!initialTranslations['__uncategorized__']) {\n initialTranslations['__uncategorized__'] = {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n } as iTranslations;\n }\n for (const cat of Object.keys(initialTranslations)) {\n initialTranslations[cat]['__category__'] = cat;\n }\n sTranslations.set(initialTranslations);\n currentlyLoadedLocale.set(initialTranslationsLocale);\n this.debug.log('Populated sTranslations with initial data for locale:', initialTranslationsLocale);\n }\n\n this.Translations.setup(this.config);\n\n // The SSR handoff already populated the stores for this locale, so prime\n // the fetch cache (after setup, which would otherwise reset this.locale).\n // The first settle for this locale is then a cache hit — no redundant\n // fetch — while switching *back* to it later still flows through\n // change() and rebuilds the t-signal. (Do NOT gate change() on a\n // \"skip fetch\" flag here: it would otherwise stay armed and silently\n // skip every return to the initial locale.)\n if (initialTranslations && initialTranslationsLocale) {\n this.Translations.markLoaded(initialTranslationsLocale);\n }\n\n // Prefetch and wire up reactive locale change handling. The store\n // emits whatever the app put in it — canonicalize here so downstream\n // caches and API routes only ever see BCP 47 canonical form.\n this.config.sUserLocale.subscribe((rawLocale) => {\n if (!validateResponse.status) return;\n const locale = canonicalizeLocale(rawLocale);\n this.getLocalesData(locale);\n this.debug.log('SUBSCRIBING TO USER LOCALE STORE');\n this.translationsLoadingPromise = this.Translations.change(locale, false);\n });\n\n return validateResponse;\n }\n\n public async getDialCodes(inLocale?: string): Promise<iCountryDialCode[]> {\n const locale = this.resolveLocale(inLocale);\n if (this.dialCodes.length && this.dialCodesLocale === locale) return this.dialCodes;\n\n const route = `countries/dial-codes/${locale}`;\n const response = await LangsysAppAPI.get(route);\n if (response.errors || !response.status) {\n this.debug.error('LangsysApp.getDialCodes failed: ' + route);\n return [];\n }\n this.dialCodes = response.data as iCountryDialCode[];\n this.dialCodesLocale = locale;\n return this.dialCodes;\n }\n\n public async getCurrencies(inLocale?: string): Promise<iCurrencyList> {\n const locale = this.resolveLocale(inLocale);\n if (this.currencies.length && this.currenciesLocale === locale) return this.currencies;\n\n const route = `currencies/${locale}`;\n const response = await LangsysAppAPI.get(route);\n if (response.errors || !response.status) {\n this.debug.error('LangsysApp.getCurrencies failed: ' + route);\n return [];\n }\n this.currencies = response.data as iCurrencyList;\n this.currenciesLocale = locale;\n return this.currencies;\n }\n\n public async getCountries(inLocale?: string): Promise<iCountryList> {\n const locale = this.resolveLocale(inLocale);\n if (this.countries.length && this.countriesLocale === locale) return this.countries;\n\n const route = `countries/${locale}`;\n const response = await LangsysAppAPI.get(route);\n if (response.errors || !response.status) {\n this.debug.error('LangsysApp.getCountries failed: ' + route);\n return [];\n }\n this.countries = response.data as iCountryList;\n this.countriesLocale = locale;\n return this.countries;\n }\n\n public async getCountryName(forCountryCode: string, inLocale?: string): Promise<string> {\n if (!forCountryCode) return '';\n const locale = this.resolveLocale(inLocale);\n if (!this.countries.length || this.countriesLocale !== locale) await this.getCountries(inLocale);\n\n const country = this.countries.find((c) => c.code.toLowerCase() === forCountryCode.toLowerCase())?.label;\n if (!country) this.debug.warn('getCountryName failed to match', forCountryCode);\n return country || forCountryCode;\n }\n\n public async getCurrencyName(forCurrencyCode: string, inLocale?: string): Promise<string> {\n if (!forCurrencyCode) return '';\n const locale = this.resolveLocale(inLocale);\n if (!this.currencies.length || this.currenciesLocale !== locale) await this.getCurrencies(inLocale);\n\n const currency = this.currencies.find((c) => c.code?.toLowerCase() === forCurrencyCode.toLowerCase())?.name;\n if (!currency) this.debug.warn('getCurrencyName failed to match', forCurrencyCode);\n return currency || forCurrencyCode;\n }\n\n public async getLocalesFormat(\n format: '' | 'flat' | 'data' = '',\n inLocale?: string\n ): Promise<iLocaleDefault | iLocaleFlat[] | iLocaleData[]> {\n const locale = this.resolveLocale(inLocale);\n const route = `locales/${locale}` + (format ? `/${format}` : '');\n const response = await LangsysAppAPI.get(route);\n if (response.errors || !response.status) {\n this.debug.error(response.errors, response.status, response);\n this.debug.error('LangsysApp.getLocales failed: ' + route);\n return format === 'flat' ? [] : format === 'data' ? [] : {};\n }\n switch (format) {\n case 'flat':\n return response.data as iLocaleFlat[];\n case 'data':\n return response.data as iLocaleData[];\n default:\n return response.data as iLocaleDefault;\n }\n }\n\n public async getLocalesFlat(inLocale?: string): Promise<iLocaleFlat[]> {\n return (await this.getLocalesFormat('flat', inLocale)) as iLocaleFlat[];\n }\n\n public async getLocalesData(inLocale?: string, forceRefresh = false): Promise<iLocaleData[]> {\n const locale = this.resolveLocale(inLocale);\n if (this.locales?.[locale]?.length && !forceRefresh) return this.locales[locale];\n this.locales[locale] = (await this.getLocalesFormat('data', inLocale)) as iLocaleData[];\n return this.locales[locale];\n }\n\n public async getLocales(inLocale?: string): Promise<iLocaleDefault> {\n return (await this.getLocalesFormat('', inLocale)) as iLocaleDefault;\n }\n\n public async getLocaleNameWithLookup(forLocale: string, shortName = false, inLocale?: string): Promise<string> {\n if (!forLocale) return '';\n const locale = this.resolveLocale(inLocale);\n await this.getLocalesData(locale);\n return this.getLocaleName(forLocale, shortName, locale);\n }\n\n public getLocaleName(forLocale: string, shortName = false, inLocale?: string): string {\n const locale = this.resolveLocale(inLocale);\n const target = canonicalizeLocale(forLocale).toLowerCase();\n let name = '';\n this.locales[locale]?.every((loc) => {\n if (loc.code.toLowerCase() === target) {\n name = shortName ? loc.lang_name : loc.locale_name;\n return false;\n }\n return true;\n });\n if (!name) this.debug.warn('getLocaleNameWithLookup failed to match', forLocale);\n return name;\n }\n\n /** @deprecated use `getLocaleNameWithLookup` or `getLocaleName` */\n public async getLanguageName(forLocale: string, shortName = false, inLocale?: string): Promise<string> {\n return this.getLocaleNameWithLookup(forLocale, shortName, inLocale);\n }\n\n /**\n * Detects the end-user's preferred locale.\n *\n * - In browsers, uses `navigator.languages` with fallback to `navigator.language`.\n * - In SSR environments, parses the `Accept-Language` header.\n */\n public detectPreferredLocale(\n acceptLanguageHeader?: string | null,\n supportedLocales?: string[]\n ): string | false {\n const userLocales = this.getUserLanguagePreferences(acceptLanguageHeader);\n if (userLocales.length === 0) return false;\n\n if (supportedLocales && supportedLocales.length > 0) {\n const bestMatch = this.findBestLocaleMatch(userLocales, supportedLocales);\n if (bestMatch) return bestMatch;\n }\n\n return canonicalizeLocale(userLocales[0]);\n }\n\n private getUserLanguagePreferences(acceptLanguageHeader?: string | null): string[] {\n if (acceptLanguageHeader) {\n try {\n return this.parseAcceptLanguageHeader(acceptLanguageHeader);\n } catch (error) {\n this.debug.warn('Failed to parse Accept-Language header:', error);\n }\n }\n\n if (typeof navigator !== 'undefined') {\n if (navigator.languages && navigator.languages.length > 0) {\n return Array.from(navigator.languages);\n }\n if (navigator.language) return [navigator.language];\n }\n\n return [];\n }\n\n private parseAcceptLanguageHeader(header: string): string[] {\n if (!header || typeof header !== 'string' || header.trim() === '') return [];\n\n try {\n return header\n .split(',')\n .map((part) => {\n const trimmed = part.trim();\n if (!trimmed || trimmed === '*') return null;\n const [localePart, qPart] = trimmed.split(';q=');\n const locale = localePart?.trim();\n const q = qPart ? parseFloat(qPart) : 1.0;\n if (!locale || isNaN(q) || q <= 0 || q > 1) return null;\n return { locale, q };\n })\n .filter((item): item is { locale: string; q: number } => item !== null)\n .sort((a, b) => b.q - a.q)\n .map((item) => item.locale);\n } catch (error) {\n this.debug.warn('Error parsing Accept-Language header:', error);\n return [];\n }\n }\n\n private findBestLocaleMatch(userLocales: string[], supportedLocales: string[]): string | null {\n if (!userLocales.length || !supportedLocales.length) return null;\n\n const supported = supportedLocales.map((l) => canonicalizeLocale(l));\n\n // Pass 1: exact match in canonical form.\n for (const userLocale of userLocales) {\n const user = canonicalizeLocale(userLocale);\n if (supported.includes(user)) return user;\n }\n\n // Pass 2: same language + script after CLDR likely-subtags expansion\n // (`zh-TW` → zh-Hant, bare `zh` → zh-Hans), region ignored. This is\n // deliberately NOT bare-language truncation: a zh-Hant-TW user must\n // fall through unmatched rather than land on a zh/zh-Hans catalog.\n for (const userLocale of userLocales) {\n const userKey = maximizedLangScript(userLocale);\n if (!userKey) continue;\n const match = supported.find((s) => maximizedLangScript(s) === userKey);\n if (match) return match;\n }\n\n return null;\n }\n\n /**\n * Resolve the effective locale for a data-fetching helper: explicit\n * argument, else the user's current locale, else the base locale —\n * always in BCP 47 canonical form so cache keys and API routes agree.\n */\n private resolveLocale(inLocale?: string): string {\n return canonicalizeLocale(inLocale || this.config.sUserLocale.get() || this.config.baseLocale);\n }\n}\n\nexport const LangsysApp = new LangsysAppClass();\nexport type { LangsysAppClass };\n","export const isEmpty = (data: unknown): boolean => {\n if (typeof data === 'number' || typeof data === 'boolean') return false;\n if (typeof data === 'undefined' || data === null) return true;\n if (typeof (data as { length?: number }).length !== 'undefined') {\n return (data as { length: number }).length === 0;\n }\n if (typeof data === 'object') return Object.keys(data as object).length === 0;\n return false;\n};\n\nexport function structuredCloneShim<T>(obj: T): T {\n if (typeof structuredClone === 'function') return structuredClone(obj);\n\n const clone = <V>(o: V): V => {\n if (typeof o !== 'object' || o === null) return o;\n if (Array.isArray(o)) return o.map((item) => clone(item)) as unknown as V;\n const out: Record<string, unknown> = {};\n for (const key in o as object) {\n if (Object.prototype.hasOwnProperty.call(o, key)) {\n out[key] = clone((o as Record<string, unknown>)[key]);\n }\n }\n return out as V;\n };\n return clone(obj);\n}\n\n/**\n * Encode a string to a \"byte string\" — one character per UTF-8 byte, each\n * ≤ 0xFF. The MD5 core packs `charCodeAt` values into byte lanes and takes\n * `length * 8` as the message bit-length, both of which are only correct when\n * every character IS a single byte. Running this first is what makes `md5`\n * agree with a standard UTF-8 MD5 for non-ASCII input.\n */\nfunction toUtf8ByteString(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let out = '';\n // Chunked to avoid blowing the argument limit on very large content blocks.\n for (let i = 0; i < bytes.length; i += 8192) {\n out += String.fromCharCode(...bytes.subarray(i, i + 8192));\n }\n return out;\n}\n\n/**\n * MD5 of a string, matching a standard UTF-8 MD5 for all input.\n *\n * Content-block `custom_id`s are derived from this, so it's a wire identity —\n * see `generateCustomId`. Before 0.6.0 this packed UTF-16 code units directly\n * into byte lanes, which agreed with a real MD5 only for ASCII: non-ASCII\n * input both diverged from every other Langsys SDK and could collide (a\n * character's high byte was OR-ed into the neighbouring lane, vanishing\n * whenever that lane already carried those bits — so `éa` and `ǩa` hashed\n * alike). `md5Legacy` preserves the old behavior for migration lookups only.\n */\nexport function md5(inputString: string) {\n if (typeof inputString !== 'string') inputString = JSON.stringify(inputString);\n return md5Core(toUtf8ByteString(inputString));\n}\n\n/**\n * The pre-0.6.0 MD5, retained ONLY so existing content blocks stay resolvable:\n * ids minted by an older SDK are keyed by this. Lookup-only — never register\n * new content under it, or the colliding-id population keeps growing.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function md5Legacy(inputString: string) {\n if (typeof inputString !== 'string') inputString = JSON.stringify(inputString);\n return md5Core(inputString);\n}\n\n// prettier-ignore\nfunction md5Core(inputString: string) {\n const hc = '0123456789abcdef';\n function rh(n: number) { let j, s = ''; for (j = 0; j <= 3; j++) s += hc.charAt((n >> (j * 8 + 4)) & 0x0F) + hc.charAt((n >> (j * 8)) & 0x0F); return s; }\n function ad(x: number, y: number) { const l = (x & 0xFFFF) + (y & 0xFFFF); const m = (x >> 16) + (y >> 16) + (l >> 16); return (m << 16) | (l & 0xFFFF); }\n function rl(n: number, c: number) { return (n << c) | (n >>> (32 - c)); }\n function cm(q: number, a: number, b: number, x: number, s: number, t: number) { return ad(rl(ad(ad(a, q), ad(x, t)), s), b); }\n function ff(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm((b & c) | ((~b) & d), a, b, x, s, t); }\n function gg(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm((b & d) | (c & (~d)), a, b, x, s, t); }\n function hh(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm(b ^ c ^ d, a, b, x, s, t); }\n function ii(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm(c ^ (b | (~d)), a, b, x, s, t); }\n function sb(x: string) {\n let i; const nblk = ((x.length + 8) >> 6) + 1; const blks = new Array(nblk * 16); for (i = 0; i < nblk * 16; i++) blks[i] = 0;\n for (i = 0; i < x.length; i++) blks[i >> 2] |= x.charCodeAt(i) << ((i % 4) * 8);\n blks[i >> 2] |= 0x80 << ((i % 4) * 8); blks[nblk * 16 - 2] = x.length * 8; return blks;\n }\n let i, x = sb('' + inputString), a = 1732584193, b = -271733879, c = -1732584194, d = 271733878, olda, oldb, oldc, oldd;\n for (i = 0; i < x.length; i += 16) {\n olda = a; oldb = b; oldc = c; oldd = d;\n a = ff(a, b, c, d, x[i + 0], 7, -680876936); d = ff(d, a, b, c, x[i + 1], 12, -389564586); c = ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = ff(b, c, d, a, x[i + 3], 22, -1044525330); a = ff(a, b, c, d, x[i + 4], 7, -176418897); d = ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = ff(c, d, a, b, x[i + 6], 17, -1473231341); b = ff(b, c, d, a, x[i + 7], 22, -45705983); a = ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = ff(d, a, b, c, x[i + 9], 12, -1958414417); c = ff(c, d, a, b, x[i + 10], 17, -42063); b = ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = ff(a, b, c, d, x[i + 12], 7, 1804603682); d = ff(d, a, b, c, x[i + 13], 12, -40341101); c = ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = ff(b, c, d, a, x[i + 15], 22, 1236535329); a = gg(a, b, c, d, x[i + 1], 5, -165796510); d = gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = gg(c, d, a, b, x[i + 11], 14, 643717713); b = gg(b, c, d, a, x[i + 0], 20, -373897302); a = gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = gg(d, a, b, c, x[i + 10], 9, 38016083); c = gg(c, d, a, b, x[i + 15], 14, -660478335); b = gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = gg(a, b, c, d, x[i + 9], 5, 568446438); d = gg(d, a, b, c, x[i + 14], 9, -1019803690); c = gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = gg(b, c, d, a, x[i + 8], 20, 1163531501); a = gg(a, b, c, d, x[i + 13], 5, -1444681467); d = gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = gg(c, d, a, b, x[i + 7], 14, 1735328473); b = gg(b, c, d, a, x[i + 12], 20, -1926607734); a = hh(a, b, c, d, x[i + 5], 4, -378558);\n d = hh(d, a, b, c, x[i + 8], 11, -2022574463); c = hh(c, d, a, b, x[i + 11], 16, 1839030562); b = hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = hh(a, b, c, d, x[i + 1], 4, -1530992060); d = hh(d, a, b, c, x[i + 4], 11, 1272893353); c = hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = hh(b, c, d, a, x[i + 10], 23, -1094730640); a = hh(a, b, c, d, x[i + 13], 4, 681279174); d = hh(d, a, b, c, x[i + 0], 11, -358537222);\n c = hh(c, d, a, b, x[i + 3], 16, -722521979); b = hh(b, c, d, a, x[i + 6], 23, 76029189); a = hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = hh(d, a, b, c, x[i + 12], 11, -421815835); c = hh(c, d, a, b, x[i + 15], 16, 530742520); b = hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = ii(a, b, c, d, x[i + 0], 6, -198630844); d = ii(d, a, b, c, x[i + 7], 10, 1126891415); c = ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = ii(b, c, d, a, x[i + 5], 21, -57434055); a = ii(a, b, c, d, x[i + 12], 6, 1700485571); d = ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = ii(c, d, a, b, x[i + 10], 15, -1051523); b = ii(b, c, d, a, x[i + 1], 21, -2054922799); a = ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = ii(d, a, b, c, x[i + 15], 10, -30611744); c = ii(c, d, a, b, x[i + 6], 15, -1560198380); b = ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = ii(a, b, c, d, x[i + 4], 6, -145523070); d = ii(d, a, b, c, x[i + 11], 10, -1120210379); c = ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = ii(b, c, d, a, x[i + 9], 21, -343485551); a = ad(a, olda); b = ad(b, oldb); c = ad(c, oldc); d = ad(d, oldd);\n }\n return rh(a) + rh(b) + rh(c) + rh(d);\n}\n","/**\n * Framework-agnostic content-block helpers.\n *\n * The DOM-mutating `Translate` class in `translate.ts` is one consumer of\n * these — it walks a live element, tokenizes it, registers the content\n * block, and mutates the same element in place. That model fits Svelte\n * and vanilla JS, where the SDK genuinely owns the DOM node.\n *\n * For React/Vue/Angular wrappers, mutating the DOM directly is an anti-\n * pattern — those frameworks own their rendered output. Wrappers should\n * import the helpers below to handle the framework-agnostic parts (token\n * discovery, content-block registration, dedup against the local cache)\n * and render translated content through their framework's native means.\n *\n * Wrapper pattern:\n *\n * 1. After mount, grab the rendered DOM via the framework's ref/binding.\n * 2. `const { tokens, content } = tokenizeElement(el);`\n * 3. `const customId = generateCustomId(category, tokens);`\n * 4. `if (!isContentBlockKnown(category, customId)) {`\n * ` await registerContentBlock({ custom_id: customId, category, content, tokens, label });`\n * `}`\n * 5. Subscribe to `sTranslations` + `currentlyLoadedLocale`; on change,\n * look up each token via `Translations.lookupContent(category, customId, token)`\n * and render via your framework's templating.\n */\n\nimport { LangsysAppAPI } from './api.js';\nimport { normalizeMarkupPlaceholders } from './interpolate.js';\nimport { logger } from './logger.js';\nimport { config as configStore, sTranslations } from './stores.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { iTranslations } from './types/translations.js';\nimport { md5, md5Legacy } from './utils.js';\n\n/**\n * HTML attributes whose values should be harvested for translation.\n *\n * `langsys-php` harvests a superset of this list. The overlap is deliberate,\n * the difference is not accidental: standard attributes carrying user-visible\n * text belong in both SDKs, because on SSR handoff an attribute only one side\n * harvests is translated by that side and left untranslated by the other — a\n * coverage hole rather than a conflict. Framework-convention attributes\n * (Bootstrap `data-bs-*`, Rails `data-confirm`, and similar) are deliberately\n * NOT mirrored: they're written by server-rendered templates, and a JS app\n * renders those strings through its own components instead.\n */\nexport const TRANSLATABLE_ATTRIBUTES = [\n 'placeholder',\n 'alt',\n 'title',\n 'label', // <option>, <optgroup>, <track> — the text a user reads in the picker\n 'aria-label',\n 'aria-placeholder',\n 'aria-description',\n 'aria-valuetext', // the spoken value of a slider/meter\n 'aria-roledescription',\n 'data-error',\n 'data-error-message',\n 'data-validation-message',\n 'data-invalid-message',\n 'data-required-message',\n 'data-pattern-message',\n];\n\n/**\n * Attributes that mark a subtree as a self-managed \"keep-together\" phrase,\n * which the block tokenizer must skip rather than split at tag boundaries.\n *\n * Two spellings, because two SDKs mark the same thing:\n * - `data-ls-phrase` — set by this SDK's framework `<Phrase>` components.\n * - `data-langsys-phrase` — `langsys-php`'s author-facing marker, which\n * survives into `translatePage()` output.\n *\n * The distinction is invisible in normal use, but on SSR handoff there is only\n * ONE DOM: a page rendered by PHP and then hydrated by a JS SDK is walked by\n * both implementations, so this tokenizer has to recognise PHP's marker or it\n * re-tokenizes a subtree PHP deliberately kept whole. Recognising both is\n * additive — `data-langsys-phrase` never appears in DOM our components emit.\n */\nexport const PHRASE_MARKER_ATTRS = ['data-ls-phrase', 'data-langsys-phrase'] as const;\n\n/**\n * True when an element opts out of translation entirely — it and its subtree\n * are skipped by the tokenizer.\n *\n * Mirrors `langsys-php`'s `HtmlParser::isTranslationExcluded()` exactly:\n * - `translate=\"no\"` — the HTML standard attribute, matched case-insensitively.\n * - `data-notrans` — PHP's author-facing alias, for hosts whose templating\n * strips unknown bare attributes or where `translate` collides with another\n * tool. Presence is intent; an explicit `\"false\"`/`\"0\"` opts out of the\n * opt-out, compared after trimming.\n *\n * Honoring PHP's alias matters for the same reason as the phrase marker: on SSR\n * handoff there is ONE DOM, and content an author marked \"do not translate\"\n * must not be extracted and registered by whichever SDK happens to walk it.\n *\n * Both this and `isPhraseMarked` trim before comparing. They briefly differed\n * — PHP's phrase check predated the trim its exclusion check gained — and the\n * gap was resolved by asking rather than tidying: mirror exactly, flag the\n * wart, let the owner decide. Divergence-by-tidying is the same failure class\n * as divergence-by-oversight, just better intentioned.\n */\nexport function isTranslationExcluded(element: Element): boolean {\n if ((element.getAttribute('translate') ?? '').toLowerCase() === 'no') return true;\n if (!element.hasAttribute('data-notrans')) return false;\n const value = (element.getAttribute('data-notrans') ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n}\n\n/**\n * True when an element is marked as a self-managed phrase by either SDK.\n *\n * Presence alone means intent, like any boolean HTML attribute — but an\n * explicit `=\"false\"` or `=\"0\"` opts OUT, compared after trimming. Mirrors\n * `langsys-php`'s `isPhraseMarked()` exactly (same method name in both SDKs,\n * so the correspondence is checkable at a glance). Without the opt-out we\n * would skip a subtree the author had deliberately un-marked, and it would\n * then be translated by neither SDK.\n */\nexport function isPhraseMarked(element: Element): boolean {\n return PHRASE_MARKER_ATTRS.some((attr) => {\n if (!element.hasAttribute(attr)) return false;\n const value = (element.getAttribute(attr) ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n });\n}\n\nexport const VALUE_TRANSLATABLE_ELEMENTS = ['button'];\nexport const VALUE_TRANSLATABLE_INPUT_TYPES = ['submit', 'button'];\n\n/**\n * Semantic CSS properties captured on the cloned content so translators\n * in the Translation Manager see the content styled the way end-users do.\n */\nexport const SEMANTIC_STYLE_PROPERTIES = [\n 'font-size', 'font-weight', 'font-style', 'font-variant', 'line-height',\n 'letter-spacing', 'word-spacing', 'text-align', 'text-decoration',\n 'text-transform', 'text-indent', 'text-shadow', 'white-space', '-webkit-font-smoothing',\n 'color', 'background-color', 'background-image', 'background-position',\n 'background-size', 'background-repeat',\n 'border', 'border-top', 'border-right', 'border-bottom', 'border-left',\n 'border-radius', 'border-color', 'border-width', 'border-style',\n 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',\n 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',\n 'box-shadow', 'opacity', 'filter',\n 'display', 'visibility', 'list-style', 'list-style-type',\n 'cursor',\n];\n\n/**\n * Compute the deterministic content-block id from a `(category, tokens)` pair.\n *\n * JSON-stringifies the tuple so each token is unambiguously delimited\n * (the previous `tokens.join('-')` was collision-prone for tokens\n * containing a hyphen, e.g. `'e-mail'`).\n *\n * Pure function — same inputs always produce the same id. Exported so\n * framework wrappers can compute the id themselves before deciding\n * whether to call `registerContentBlock`.\n */\nexport function generateCustomId(category: string, tokens: string[]): string {\n return md5(JSON.stringify([category, tokens]));\n}\n\n/**\n * The id this block would have had before the 0.6.0 MD5 fix.\n *\n * **Lookup only — never register under this.** Blocks registered by an older\n * SDK are keyed by it, so `Translate` falls back to it when the corrected id\n * misses, which keeps existing translations resolving instead of orphaning\n * them. Registering under it would keep minting ids from a hash that both\n * diverges across SDKs and can collide.\n *\n * Note the collision is a property of the FINAL hashed string, not the phrase:\n * `JSON.stringify` shifts every character's offset, so the same phrase pair can\n * collide standalone and not collide here — and changing `category` moves every\n * character into different lanes. Always reason at this level, not at `md5()`.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function generateLegacyCustomId(category: string, tokens: string[]): string {\n return md5Legacy(JSON.stringify([category, tokens]));\n}\n\n/**\n * True iff the local translations cache already has the content block\n * for the given `(category, customId)` — meaning the backend knows about\n * it and there's no need to re-register.\n *\n * The cache is keyed under `'__uncategorized__'` for null/empty categories,\n * matching the convention the server uses in its GET /translations response.\n */\nexport function isContentBlockKnown(category: string, customId: string): boolean {\n const cats = sTranslations.get();\n const lookupCat = category || '__uncategorized__';\n const cbData = cats[lookupCat]?.[customId];\n return typeof cbData === 'object' && cbData !== null;\n}\n\n/**\n * POST a content block to the backend, then stamp its custom_id into the\n * local translations cache so subsequent mounts in this session — and\n * subsequent reloads, since the cache is persisted — skip the POST.\n *\n * Mirrors the standalone-phrase path's cache writeback semantics. Respects\n * `key_type === 'write'`: read-only keys silently no-op (resolves with\n * `{ status: true }` so the caller can still render the cached translation).\n *\n * Errors are logged via the SDK's logger and returned as `{ status: false }`\n * — never thrown. Callers can decide whether to surface to UI or swallow.\n */\nexport async function registerContentBlock(\n contentBlock: iContentBlock,\n): Promise<{ status: boolean; errors?: unknown[] }> {\n if (configStore.key_type !== 'write') {\n if (configStore.debug) {\n logger.log(`Skipping content block save (API key is ${configStore.key_type || 'unknown'})`);\n }\n return { status: true };\n }\n\n try {\n const response = await LangsysAppAPI.createTranslatableItems([\n {\n type: 'content_block',\n custom_id: contentBlock.custom_id,\n category: contentBlock.category,\n content: contentBlock.content,\n label: contentBlock.label,\n phrases: contentBlock.tokens.map((phrase) => ({ phrase })),\n },\n ]);\n if (!response.status) {\n logger.error('Could not save content block', response.errors);\n return { status: false, errors: response.errors as unknown[] | undefined };\n }\n _writeKnownContentBlockToCache(contentBlock.category, contentBlock.custom_id);\n return { status: true };\n } catch (err) {\n logger.error('Could not save content block', err);\n return { status: false, errors: [err] };\n }\n}\n\n/**\n * Walk an `HTMLElement`, collecting tokens for translation and producing a\n * cloned-and-stylized snapshot of its outerHTML for the Translation Manager.\n *\n * Tokens harvested:\n * - text-node content (whitespace-normalized, trimmed)\n * - translatable attribute values (`placeholder`, `alt`, `title`, `aria-*`, etc.)\n * - button/input/select value text\n *\n * Skips subtrees marked with `translate=\"no\"`.\n *\n * The returned `content` is a string snapshot — the live element is not\n * mutated. Computed semantic styles (color, font, spacing, etc.) are inlined\n * onto the clone so translators see content styled the way end-users do.\n *\n * Requires that `element` is mounted in the document so `getComputedStyle`\n * can read its style. For SSR / pre-mount callers, the style capture step\n * silently no-ops and the snapshot is plain (without inlined styles).\n */\nexport function tokenizeElement(element: HTMLElement): { tokens: string[]; content: string } {\n const tokens: string[] = [];\n const clone = element.cloneNode(true) as HTMLElement;\n _walkForTokens(element, Array.from(clone.childNodes), tokens, [], false, true);\n return { tokens, content: normalizeMarkupPlaceholders(clone.outerHTML) };\n}\n\n/**\n * The token list this element would have produced before 0.6.3, when every\n * `<option>`'s text was harvested twice — once by a `<select>` special case and\n * again by the ordinary text-node walk.\n *\n * **Lookup only.** Content blocks registered by an older SDK are keyed by an id\n * derived from this list, so `Translate` falls back to it when the corrected id\n * misses; without that, every block containing a `<select>` would silently\n * re-key and lose its translations on upgrade. Registration always uses the\n * corrected list, so the legacy-keyed population can only shrink.\n *\n * Skips the computed-style capture that `tokenizeElement` performs — this is a\n * cache-key computation, not a snapshot for translators.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function legacyTokenizeElement(element: HTMLElement): string[] {\n const tokens: string[] = [];\n const clone = element.cloneNode(true) as HTMLElement;\n _walkForTokens(element, Array.from(clone.childNodes), tokens, [], true, false);\n return tokens;\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nfunction _writeKnownContentBlockToCache(category: string, customId: string): void {\n const lookupCat = category || '__uncategorized__';\n sTranslations.update((current) => {\n if (!current[lookupCat]) {\n current[lookupCat] = {\n __category__: lookupCat,\n __symbol__: lookupCat,\n } as iTranslations;\n }\n (current[lookupCat] as unknown as Record<string, unknown>)[customId] = {};\n return { ...current };\n });\n}\n\nfunction _walkForTokens(\n liveRoot: HTMLElement,\n cloneNodes: ChildNode[],\n tokens: string[],\n indices: number[],\n duplicateSelectOptions: boolean,\n applyStyles: boolean,\n): void {\n cloneNodes.forEach((node, index) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n if (isTranslationExcluded(el)) return;\n // A <Phrase> subtree is its own self-managed rich phrase — skip it\n // here so the content block doesn't tokenize its inner text.\n if (isPhraseMarked(el)) return;\n }\n\n if (applyStyles && node.hasChildNodes()) {\n _applyStylesToClone(liveRoot, node as HTMLElement, [...indices, index]);\n }\n\n if (node.nodeType === Node.ELEMENT_NODE) {\n _tokenizeAttributes(node as HTMLElement, tokens, duplicateSelectOptions);\n }\n\n const contentToken = node.nodeValue?.replace(/\\s+/g, ' ').trim();\n if (node.nodeType === Node.TEXT_NODE && contentToken) {\n tokens.push(normalizeMarkupPlaceholders(contentToken));\n return;\n }\n\n if (!node.hasChildNodes()) return;\n _walkForTokens(liveRoot, Array.from(node.childNodes), tokens, [...indices, index], duplicateSelectOptions, applyStyles);\n });\n}\n\nfunction _tokenizeAttributes(element: HTMLElement, tokens: string[], duplicateSelectOptions: boolean): void {\n const tagName = element.tagName.toLowerCase();\n\n if (tagName === 'img') {\n const img = element as HTMLImageElement;\n if (img.src) element.setAttribute('src', img.src);\n }\n\n for (const attr of TRANSLATABLE_ATTRIBUTES) {\n const value = element.getAttribute(attr)?.trim();\n if (value) tokens.push(normalizeMarkupPlaceholders(value));\n }\n\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tagName)) {\n const value = element.getAttribute('value')?.trim();\n if (value) tokens.push(normalizeMarkupPlaceholders(value));\n }\n\n if (tagName === 'input') {\n const inputType = element.getAttribute('type')?.toLowerCase();\n if (inputType && VALUE_TRANSLATABLE_INPUT_TYPES.includes(inputType)) {\n const value = element.getAttribute('value')?.trim();\n if (value) tokens.push(normalizeMarkupPlaceholders(value));\n }\n }\n\n // <option> text is NOT harvested here in the current path: it arrives via\n // the ordinary text-node walk, since `<option>` cannot contain elements.\n // Doing both pushed every option's text TWICE, changing the token list and\n // therefore the block's `custom_id`. langsys-php reached the same\n // conclusion earlier — their `extractSelectOptions()` is an empty stub\n // with a comment saying so — and their token lists are the reference.\n //\n // The duplicate is reproduced ONLY for `legacyTokenizeElement`, so blocks\n // registered before 0.6.3 stay resolvable. `<optgroup label>` reaches us\n // through TRANSLATABLE_ATTRIBUTES either way.\n if (duplicateSelectOptions && tagName === 'select') {\n const options = element.querySelectorAll('option');\n options.forEach((option) => {\n const optionText = option.textContent?.trim();\n if (optionText) tokens.push(normalizeMarkupPlaceholders(optionText));\n });\n }\n}\n\nfunction _applyStylesToClone(liveRoot: HTMLElement, cloneNode: HTMLElement, indices: number[]): void {\n if (typeof window === 'undefined') return;\n const domNode = _findNode(Array.from(liveRoot.childNodes), indices);\n if (!domNode) return;\n\n const tagName = (domNode as HTMLElement).tagName.toLowerCase();\n const reference = document.createElement(tagName);\n reference.style.visibility = 'hidden';\n reference.style.position = 'absolute';\n document.body.appendChild(reference);\n\n const computed = window.getComputedStyle(domNode as HTMLElement);\n const defaults = window.getComputedStyle(reference);\n\n for (const prop of SEMANTIC_STYLE_PROPERTIES) {\n const value = computed.getPropertyValue(prop);\n const defaultValue = defaults.getPropertyValue(prop);\n if (value && value !== defaultValue) {\n cloneNode.style.setProperty(prop, value);\n }\n }\n\n document.body.removeChild(reference);\n cloneNode.removeAttribute('class');\n}\n\nfunction _findNode(nodes: ChildNode[], indices: number[]): Element | undefined {\n let currentNode: Node | undefined = nodes[indices[0]];\n for (let i = 1; i < indices.length; i++) {\n if (!currentNode || !currentNode.hasChildNodes()) return undefined;\n currentNode = Array.from(currentNode.childNodes)[indices[i]];\n }\n return currentNode as Element;\n}\n","import {\n generateCustomId,\n isContentBlockKnown,\n isPhraseMarked,\n isTranslationExcluded,\n legacyTokenizeElement,\n registerContentBlock,\n generateLegacyCustomId,\n tokenizeElement,\n TRANSLATABLE_ATTRIBUTES,\n VALUE_TRANSLATABLE_ELEMENTS,\n VALUE_TRANSLATABLE_INPUT_TYPES,\n} from './content-block.js';\nimport { interpolate, normalizeMarkupPlaceholders, warnUnmatchedParams } from './interpolate.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { currentlyLoadedLocale, config as configStore } from './stores.js';\nimport type { Unsubscriber } from './signal.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\nimport { isEmpty } from './utils.js';\n\n/** Options for the `Translate` class. Matches the Svelte component's props. */\nexport interface TranslateOptions {\n /** Optional category under which tokens are registered. Helps translators disambiguate. */\n category?: string;\n /** Optional stable id for the content block. If omitted, we hash category+tokens. */\n custom_id?: string;\n /** Optional human-readable label shown in the Translation Manager. */\n label?: string;\n /**\n * Interpolation params — `{name}`, `{count}`, etc. Same single-brace syntax\n * as `t()`, and what you write in plain DOM. In a framework component's\n * markup write `%name%` / `%count%` instead: Svelte and JSX consume\n * `{name}` at compile time (Vue consumes `{{ name }}`), and `%name%` is\n * normalized back to `{name}` at capture.\n */\n params?: Record<string, ParamPrimitive>;\n}\n\ntype iNode = Node & { originalNodeValue?: string | null };\ntype iElement = HTMLElement & { originalAttributes?: Record<string, string> };\n\n/**\n * Wrap a DOM element and manage translation for its contents.\n *\n * const el = document.querySelector('#hero');\n * new Translate(el, { category: 'Home' });\n *\n * The first-pass tokenizes text nodes and translatable attributes; if the\n * content is a single text run, it's treated as a plain token. For HTML\n * content, a \"content block\" is registered so translators see the content\n * with the same visual structure users see.\n *\n * Call `.destroy()` to stop reacting to locale changes.\n */\nexport class Translate {\n private element: HTMLElement;\n private options: TranslateOptions;\n private tokens: string[] = [];\n private parseComplete = false;\n private isTokenizing = false;\n private lastTranslatedLocale = '';\n private custom_id: string;\n private unsubscribeLocale: Unsubscriber | null = null;\n /** Sorted params key-set already checked, so value-only updates don't re-warn. */\n private checkedParamKeys: string | null = null;\n\n constructor(element: HTMLElement, options: TranslateOptions = {}) {\n this.element = element;\n this.options = { ...options };\n this.custom_id = options.custom_id || '';\n\n // First pass: tokenize + save + translate.\n void this.tokenizeContent();\n\n // React to locale changes.\n this.unsubscribeLocale = currentlyLoadedLocale.subscribe((locale) => {\n if (locale && this.parseComplete) this.translateUpdate(locale);\n });\n }\n\n /** Update interpolation params (e.g. a changed count) and re-render. Mirrors `Phrase.setParams`. */\n public setParams(params: Record<string, ParamPrimitive> | undefined): void {\n this.options.params = params;\n // Checked independently of `parseComplete` — tokens are known before\n // content-block registration settles, and params can change during\n // that window.\n this.checkParams();\n if (!this.parseComplete) return;\n this.lastTranslatedLocale = '';\n const locale = currentlyLoadedLocale.get();\n if (locale) this.translateUpdate(locale);\n }\n\n /** Stop reacting to locale changes. Safe to call multiple times. */\n public destroy() {\n if (this.unsubscribeLocale) {\n this.unsubscribeLocale();\n this.unsubscribeLocale = null;\n }\n }\n\n private translateUpdate(currentLocale: string) {\n if (!this.element?.innerHTML || !this.parseComplete) return;\n if (this.lastTranslatedLocale === currentLocale) return;\n\n const { category = '' } = this.options;\n\n if (this.tokens.length === 1) {\n this.element.innerText = this.applyParams(LangsysApp.Translations.t(this.tokens[0], category));\n } else {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentLocale;\n }\n }\n\n private async tokenizeContent(): Promise<boolean> {\n if (this.isTokenizing) return false;\n if (!this.element || !this.element.childNodes.length) {\n this.parseComplete = true;\n this.isTokenizing = false;\n return false;\n }\n\n this.isTokenizing = true;\n\n // Framework-agnostic tokenization + style-snapshot lives in\n // content-block.ts. We store the clone locally only because the\n // existing translate() DOM-mutator references it for content-block\n // detection (`this.tokens` drives the single-vs-multi branch below).\n const { tokens, content } = tokenizeElement(this.element);\n this.tokens = tokens;\n this.checkParams();\n\n const { category = '' } = this.options;\n\n if (this.tokens.length === 1) {\n this.element.innerText = this.applyParams(LangsysApp.Translations.t(this.tokens[0], category));\n } else {\n const contentBlock: iContentBlock = {\n custom_id: '',\n category,\n label: this.options.label,\n content,\n tokens: this.tokens,\n };\n await this.handleContentBlock(contentBlock);\n }\n\n this.parseComplete = true;\n this.isTokenizing = false;\n return true;\n }\n\n private async handleContentBlock(contentBlock: iContentBlock) {\n const derivedId = isEmpty(this.custom_id);\n if (derivedId) {\n this.custom_id = generateCustomId(contentBlock.category, contentBlock.tokens);\n }\n contentBlock.custom_id = this.custom_id;\n\n // Wait for the first GET /translations to settle before deciding whether\n // to POST — otherwise on a cold cache the lookup misses and we'd POST\n // every CB on every first visit even when the backend already has it.\n await LangsysApp.Translations.ready();\n\n if (isContentBlockKnown(contentBlock.category, this.custom_id)) {\n // Backend already has this block — translate locally, no POST.\n if (this.tokens.length > 1 && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n return;\n }\n\n // Migration fallback: resolve blocks registered by older SDKs so their\n // translations keep working instead of orphaning. Two things have moved\n // the id, so there are three historical shapes to try:\n //\n // corrected md5 + corrected tokens → current (tried above)\n // corrected md5 + legacy tokens → registered by 0.6.0–0.6.2\n // legacy md5 + legacy tokens → registered before 0.6.0\n //\n // (legacy md5 + corrected tokens never existed — the token fix came\n // after the hash fix.) LOOKUP ONLY: registration below always uses the\n // corrected id, so the legacy-keyed population can only shrink.\n // Skipped for a caller-supplied custom_id, since nothing was derived.\n if (derivedId) {\n const legacyTokens = legacyTokenizeElement(this.element);\n const candidates = [\n generateCustomId(contentBlock.category, legacyTokens),\n generateLegacyCustomId(contentBlock.category, legacyTokens),\n ];\n for (const candidate of candidates) {\n if (candidate === this.custom_id) continue;\n if (!isContentBlockKnown(contentBlock.category, candidate)) continue;\n this.custom_id = candidate;\n if (this.tokens.length > 1 && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n return;\n }\n }\n\n // Fire-and-forget: registerContentBlock handles its own errors via\n // the logger. We don't await here because the DOM render path below\n // doesn't depend on the POST completing — translations are looked up\n // from sTranslations on every render, which updates reactively when\n // the GET response arrives.\n void registerContentBlock(contentBlock);\n\n if (this.tokens.length > 1 && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n }\n\n private translate(nodes: iNode[]) {\n const currentLocale = currentlyLoadedLocale.get();\n // With params, the base locale still needs a pass — placeholders must\n // be interpolated even when no translation lookup will hit.\n if (\n currentLocale === configStore.baseLocale &&\n (this.lastTranslatedLocale === '' || this.lastTranslatedLocale === configStore.baseLocale) &&\n isEmpty(this.options.params)\n ) {\n return;\n }\n\n nodes.forEach((node) => {\n if (node?.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n if (isTranslationExcluded(element)) return;\n // A <Phrase> subtree manages its own rendering — don't recurse.\n if (isPhraseMarked(element)) return;\n this.translateAttributes(node as iElement);\n }\n\n if (node?.nodeType !== Node.TEXT_NODE) {\n if (!node?.hasChildNodes()) return;\n this.translate(Array.from(node.childNodes));\n return;\n }\n\n if (isEmpty(node.nodeValue?.trim())) return;\n\n if (isEmpty(node.originalNodeValue)) {\n // Snapshot in canonical placeholder form so lookups, replaces,\n // and interpolation all operate on `{key}`.\n node.originalNodeValue = normalizeMarkupPlaceholders(node.nodeValue!);\n }\n\n const contentToken = node.originalNodeValue?.replace(/\\s+/g, ' ').trim();\n if (!contentToken) return;\n\n const translation = this.getTranslation(contentToken);\n\n if (translation && contentToken && node.originalNodeValue) {\n // Replacer fn so `$`-patterns in translations/params stay literal.\n const resolved = this.applyParams(translation);\n node.nodeValue = node.originalNodeValue.replace(contentToken, () => resolved);\n } else if (node.originalNodeValue) {\n node.nodeValue = this.applyParams(node.originalNodeValue);\n }\n });\n }\n\n private getTranslation(token: string): string | null {\n if (!token) return null;\n const { category = '' } = this.options;\n return LangsysApp.Translations.lookupContent(category, this.custom_id, token);\n }\n\n /**\n * Debug-time check that every supplied param has a placeholder to land in.\n * Re-runs only when the key SET changes — a changing `count` value must not\n * re-warn on every render.\n */\n private checkParams(): void {\n // Before tokenization there's nothing to match against — every key\n // would look unused. Skip without recording, so the check still runs\n // once tokens exist.\n if (!this.tokens.length) return;\n\n const { params, category = '' } = this.options;\n const signature = params ? Object.keys(params).sort().join(',') : '';\n if (signature === this.checkedParamKeys) return;\n this.checkedParamKeys = signature;\n\n warnUnmatchedParams('<Translate>', this.tokens, params, category || undefined);\n }\n\n /**\n * Interpolate `{name}`-style params into a resolved text, matching `t()`:\n * unknown keys fall through untouched, and the untranslated fallback is\n * interpolated too. No-op when no params were supplied.\n */\n private applyParams(text: string): string {\n const { params } = this.options;\n if (isEmpty(params)) return text;\n return interpolate(text, params!, currentlyLoadedLocale.get());\n }\n\n private translateAttributes(element: iElement) {\n const tagName = element.tagName.toLowerCase();\n if (!element.originalAttributes) element.originalAttributes = {};\n\n for (const attr of TRANSLATABLE_ATTRIBUTES) {\n this.translateAttribute(element, attr);\n }\n\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tagName)) {\n this.translateAttribute(element, 'value');\n }\n\n if (tagName === 'input') {\n const inputType = element.getAttribute('type')?.toLowerCase();\n if (inputType && VALUE_TRANSLATABLE_INPUT_TYPES.includes(inputType)) {\n this.translateAttribute(element, 'value');\n }\n }\n\n if (tagName === 'select') {\n const options = element.querySelectorAll('option');\n options.forEach((option) => {\n const optionEl = option as iElement;\n if (!optionEl.originalAttributes) optionEl.originalAttributes = {};\n if (optionEl.originalAttributes['textContent'] === undefined) {\n optionEl.originalAttributes['textContent'] = normalizeMarkupPlaceholders(option.textContent || '');\n }\n const originalText = optionEl.originalAttributes['textContent'].trim();\n if (originalText) {\n const translation = this.getTranslation(originalText);\n option.textContent = this.applyParams(translation || optionEl.originalAttributes['textContent']);\n }\n });\n }\n }\n\n private translateAttribute(element: iElement, attr: string) {\n const currentValue = element.getAttribute(attr);\n if (!currentValue) return;\n\n if (element.originalAttributes![attr] === undefined) {\n element.originalAttributes![attr] = normalizeMarkupPlaceholders(currentValue);\n }\n\n const originalValue = element.originalAttributes![attr].trim();\n if (!originalValue) return;\n\n const translation = this.getTranslation(originalValue);\n if (translation) element.setAttribute(attr, this.applyParams(translation));\n else element.setAttribute(attr, this.applyParams(element.originalAttributes![attr]));\n }\n\n}\n\nexport default Translate;\n","/**\n * Rich-text (markup-bearing) phrase encoding for the `<Phrase>` artifact.\n *\n * The problem: a phrase like `You have {n} <strong>reviews</strong>` must stay\n * ONE phrase (so pluralization sees `{n}` next to `reviews`), but we must NOT\n * send the SPA's real markup — and especially not framework-internal scoped-CSS\n * classes (`svelte-a1b2c3`, Vue scoped hashes) — to the translator. Those\n * classes get mangled, and worse they change on every build, which would make\n * the phrase key drift and silently re-translate everything.\n *\n * The approach: replace each inline element with a pair of neutral MARKUP\n * TOKENS — `{m0o}` ... `{m0c}` (markup, slot 0, open/close). These are ordinary\n * ICU placeholders: valid MessageFormat argument names, so plural/select still\n * parse, and the model treats them like `{n}` — it preserves them and PLACES\n * them around the translated word (which is what fixes reordering languages,\n * e.g. `<span>White</span> House` -> `Casa <span>Blanca</span>`).\n *\n * The real DOM elements never leave the SDK. At render time we resolve the\n * translation, substitute each markup token with a private-use SENTINEL char\n * (transient — never sent anywhere), then reconstitute the DOM by wrapping the\n * sentinel-delimited spans in the ORIGINAL framework-owned elements. Scoped CSS\n * survives because we reuse the real element; the phrase key is stable because\n * the wire form only ever contains `{m0o}`/`{m0c}`, never build-specific hashes.\n */\n\n// Private-use (PUA) sentinel delimiters, written via char codes so no literal\n// PUA characters live in the source. Brace-free so ICU MessageFormat treats a\n// substituted sentinel as literal text. They exist only transiently at render —\n// never registered, never sent over the wire (the wire form uses {mNo}/{mNc}).\n// open(i) = U+E000 <i> U+E001\n// close(i) = U+E002 <i> U+E003\nimport { normalizeMarkupPlaceholders } from './interpolate.js';\n\nconst SENT_OPEN_START = String.fromCharCode(0xe000);\nconst SENT_OPEN_END = String.fromCharCode(0xe001);\nconst SENT_CLOSE_START = String.fromCharCode(0xe002);\nconst SENT_CLOSE_END = String.fromCharCode(0xe003);\n\n/** Matches an open marker (group 1 = slot index) or a close marker (group 2 = slot index). */\nconst SENT_SCAN = /\\uE000(\\d+)\\uE001|\\uE002(\\d+)\\uE003/g;\n\n/** A captured inline element: a shallow clone (tag + attributes, no children). */\nexport interface RichSlot {\n /** Shallow clone of the original element — preserves tag, class, href, etc. */\n template: HTMLElement;\n}\n\nexport interface EncodedRichText {\n /**\n * The phrase string with inline elements replaced by `{mNo}`...`{mNc}` markup\n * tokens. This is what gets registered + sent for translation.\n */\n phrase: string;\n /** Captured inline elements, indexed by markup-token slot number. */\n slots: RichSlot[];\n}\n\n/**\n * Walk an element's subtree and produce the encoded phrase + captured slots.\n *\n * Text nodes contribute their (whitespace-collapsed) text. Each child element\n * becomes a markup-token pair wrapping its recursively-encoded contents, and a\n * shallow clone of the element is captured as a slot. Nesting is preserved.\n */\nexport function encodeRichText(root: HTMLElement): EncodedRichText {\n const slots: RichSlot[] = [];\n const phrase = _encodeNodes(Array.from(root.childNodes), slots);\n // `%key%` → `{key}` so the registered phrase carries the canonical\n // placeholder form (framework compilers eat bare `{key}` in markup).\n // The `{mNo}`/`{mNc}` markup tokens are generated brace-form and are\n // untouched by the normalization.\n return { phrase: normalizeMarkupPlaceholders(phrase.replace(/\\s+/g, ' ').trim()), slots };\n}\n\nfunction _encodeNodes(nodes: ChildNode[], slots: RichSlot[]): string {\n let out = '';\n for (const node of nodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n out += node.nodeValue ?? '';\n continue;\n }\n if (node.nodeType !== Node.ELEMENT_NODE) continue;\n\n const element = node as HTMLElement;\n const index = slots.length;\n slots.push({ template: element.cloneNode(false) as HTMLElement });\n out += `{m${index}o}` + _encodeNodes(Array.from(element.childNodes), slots) + `{m${index}c}`;\n }\n return out;\n}\n\n/**\n * The param values to feed alongside the user's params when resolving a rich\n * phrase. Each markup token maps to its sentinel pair so the resolved string\n * carries machine-findable delimiters for reconstitution.\n */\nexport function markupTokenValues(slotCount: number): Record<string, string> {\n const values: Record<string, string> = {};\n for (let i = 0; i < slotCount; i++) {\n values[`m${i}o`] = `${SENT_OPEN_START}${i}${SENT_OPEN_END}`;\n values[`m${i}c`] = `${SENT_CLOSE_START}${i}${SENT_CLOSE_END}`;\n }\n return values;\n}\n\n/**\n * Rebuild DOM nodes from a resolved string containing sentinel-delimited spans.\n *\n * The original (framework-owned) elements are reused as wrappers — so scoped\n * CSS classes / attributes survive — with the translated text placed inside.\n *\n * Robust to model mistakes: if sentinels are unbalanced (a tag dropped or a\n * stray close), we fall back to a single plain-text node (markers stripped) —\n * \"lose the markup, keep the meaning\" rather than throw.\n */\nexport function reconstitute(resolved: string, slots: RichSlot[], doc: Document = document): Node[] {\n const root = doc.createDocumentFragment();\n const stack: Node[] = [root];\n const top = () => stack[stack.length - 1];\n\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n SENT_SCAN.lastIndex = 0;\n\n try {\n while ((match = SENT_SCAN.exec(resolved)) !== null) {\n const text = resolved.slice(lastIndex, match.index);\n if (text) top().appendChild(doc.createTextNode(text));\n lastIndex = SENT_SCAN.lastIndex;\n\n const isOpen = match[1] !== undefined;\n const slotIndex = Number(isOpen ? match[1] : match[2]);\n\n if (isOpen) {\n const slot = slots[slotIndex];\n if (!slot) throw new Error('unknown markup slot');\n const el = slot.template.cloneNode(false) as HTMLElement;\n top().appendChild(el);\n stack.push(el);\n } else {\n if (stack.length <= 1) throw new Error('unbalanced close');\n stack.pop();\n }\n }\n\n const tail = resolved.slice(lastIndex);\n if (tail) top().appendChild(doc.createTextNode(tail));\n\n if (stack.length !== 1) throw new Error('unbalanced open');\n } catch {\n // Degrade gracefully: strip every marker and return plain text.\n return [doc.createTextNode(stripSentinels(resolved))];\n }\n\n return Array.from(root.childNodes);\n}\n\n/** Remove any sentinel markers from a string, leaving the bare text. */\nexport function stripSentinels(value: string): string {\n return value.replace(SENT_SCAN, '');\n}\n","import { interpolate, warnUnmatchedParams } from './interpolate.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { encodeRichText, markupTokenValues, reconstitute, type RichSlot } from './richtext.js';\nimport type { Unsubscriber } from './signal.js';\nimport { currentlyLoadedLocale, sTranslations } from './stores.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\n\n/** Attribute marker the `Translate` tokenizer uses to skip a `<Phrase>` subtree. */\nexport const PHRASE_MARKER_ATTR = 'data-ls-phrase';\n\nexport interface PhraseOptions {\n /** Category the phrase registers under (disambiguation for translators). */\n category?: string;\n /**\n * Interpolation params — `{n}` for pluralization, `{name}`, etc.\n *\n * Those are the canonical spellings, and what you write in plain DOM. In a\n * framework component's markup write `%n%` / `%name%` instead: Svelte and\n * JSX consume `{n}` at compile time (Vue consumes `{{ n }}`), and `%n%` is\n * normalized back to `{n}` at capture.\n */\n params?: Record<string, ParamPrimitive>;\n}\n\n/**\n * DOM handler for a markup-bearing \"rich\" phrase (`<Phrase>`).\n *\n * Wraps an element whose inner content is ONE translatable phrase even though\n * it contains inline markup. On mount it encodes the subtree to a single phrase\n * string with neutral `{mNo}`/`{mNc}` markup tokens (the real elements stay in\n * the SDK — see richtext.ts), registers it, and renders the translation by\n * reconstituting the original elements around the translated text. Re-renders\n * on locale change and whenever params change.\n *\n * new Phrase(el, { category: 'ProductCard', params: { n: reviewCount } });\n */\nexport class Phrase {\n private host: HTMLElement;\n private category: string;\n private params: Record<string, ParamPrimitive>;\n private phrase = '';\n private slots: RichSlot[] = [];\n private unsubscribers: Unsubscriber[] = [];\n private ready = false;\n /** Sorted params key-set already checked, so value-only updates don't re-warn. */\n private checkedParamKeys: string | null = null;\n\n constructor(host: HTMLElement, options: PhraseOptions = {}) {\n this.host = host;\n this.category = options.category ?? '';\n this.params = options.params ?? {};\n\n void this._init();\n\n // Re-render on locale switch AND when translations arrive (async MT may\n // land this phrase's translation after mount, same as the reactive `t`\n // store). subscribe fires immediately; the `ready` guard suppresses the\n // pre-init call.\n const rerender = () => {\n if (this.ready) this._render();\n };\n this.unsubscribers.push(currentlyLoadedLocale.subscribe(rerender));\n this.unsubscribers.push(sTranslations.subscribe(rerender));\n }\n\n /** Update interpolation params (e.g. a changed count) and re-render. */\n public setParams(params: Record<string, ParamPrimitive> | undefined): void {\n this.params = params ?? {};\n // Checked independently of `ready` — the phrase is encoded before\n // registration settles, and params can change during that window.\n this._checkParams();\n if (!this.ready) return;\n this._render();\n }\n\n /** Stop reacting to locale/translation changes. Safe to call multiple times. */\n public destroy(): void {\n this.unsubscribers.forEach((unsub) => unsub());\n this.unsubscribers = [];\n }\n\n private async _init(): Promise<void> {\n if (!this.host || !this.host.childNodes.length) {\n this.ready = true;\n return;\n }\n\n const { phrase, slots } = encodeRichText(this.host);\n this.phrase = phrase;\n this.slots = slots;\n this._checkParams();\n\n // Register the phrase (triggers the missing-token POST on a cache miss).\n // We ignore t()'s interpolated return — Phrase renders itself so it can\n // supply the markup-token sentinel values and reconstitute real elements.\n await LangsysApp.Translations.ready();\n LangsysApp.Translations.t(this.phrase, this.category);\n\n this.ready = true;\n this._render();\n }\n\n /**\n * Debug-time check that every supplied param has a placeholder to land in.\n * Re-runs only when the key SET changes — a changing `n` value must not\n * re-warn on every render.\n */\n private _checkParams(): void {\n // Before encoding there's nothing to match against — skip without\n // recording, so the check still runs once the phrase exists.\n if (!this.phrase) return;\n\n const signature = Object.keys(this.params).sort().join(',');\n if (signature === this.checkedParamKeys) return;\n this.checkedParamKeys = signature;\n\n warnUnmatchedParams('<Phrase>', [this.phrase], this.params, this.category || undefined);\n }\n\n private _render(): void {\n if (!this.phrase) return;\n\n const raw = LangsysApp.Translations.lookup(this.phrase, this.category) ?? this.phrase;\n const params = { ...this.params, ...markupTokenValues(this.slots.length) };\n const resolved = interpolate(raw, params, currentlyLoadedLocale.get());\n const nodes = reconstitute(resolved, this.slots, this.host.ownerDocument ?? document);\n\n this.host.replaceChildren(...nodes);\n }\n}\n\nexport default Phrase;\n","/**\n * Langsys SDK — framework-agnostic TypeScript\n *\n * Realtime continuous translations with automatic token discovery for any\n * web app. The public translation surface is `t(phrase, category?, params?)`\n * — the phrase itself is the lookup key (and the source-language default).\n * Frameworks subscribe to `tSignal` for reactive re-renders.\n */\n\n// Public singletons and classes\nexport { LangsysApp } from './langsys-app.js';\nexport { Translations } from './translations.js';\nexport { Translate, type TranslateOptions } from './translate.js';\nexport { Phrase, PHRASE_MARKER_ATTR, type PhraseOptions } from './phrase.js';\nexport {\n encodeRichText,\n reconstitute,\n markupTokenValues,\n stripSentinels,\n type RichSlot,\n type EncodedRichText,\n} from './richtext.js';\nexport { LangsysAppAPI } from './api.js';\n\n// Content-block helpers (framework-agnostic — for React/Vue/Angular/other\n// wrappers that own their own DOM rendering and only need the registration\n// + dedup primitives, not the Svelte/vanilla in-place DOM mutator).\nexport {\n generateCustomId,\n generateLegacyCustomId,\n isContentBlockKnown,\n isPhraseMarked,\n isTranslationExcluded,\n legacyTokenizeElement,\n PHRASE_MARKER_ATTRS,\n registerContentBlock,\n tokenizeElement,\n} from './content-block.js';\n\n// Reactive primitives\nexport { createSignal, getValue, type Signal, type Subscriber, type Unsubscriber, type Updater } from './signal.js';\nexport { persist } from './persist.js';\n\n// Stores (advanced usage — direct subscription to translations / locale)\nexport { sTranslations, currentlyLoadedLocale } from './stores.js';\n\n// Logger\nexport { Logger, logger } from './logger.js';\n\n// Utility exports\nexport { md5, md5Legacy, isEmpty } from './utils.js';\nexport { findUnusedParamKeys, interpolate, isICU, normalizeMarkupPlaceholders } from './interpolate.js';\nexport { canonicalizeLocale } from './locale.js';\n\n// Type re-exports\nexport type { ResponseObject as iLangsysResponse } from './types/api.js';\nexport type { iLangsysConfig, iLangsysInitConfig, LocaleSource } from './types/config.js';\nexport type { iContentBlock } from './types/content-block.js';\nexport type { iCountry, iCountryDialCode, iCountryList } from './types/countries.js';\nexport type { iCurrency, iCurrencyList } from './types/currencies.js';\nexport type { iLanguageName, iLocaleData, iLocaleDefault, iLocaleFlat } from './types/locales.js';\nexport type { iProject } from './types/project.js';\nexport type {\n ExtractParamKeys,\n ParamPrimitive,\n ParamsFor,\n TArgs,\n TFunction,\n TranslationParams,\n} from './types/translation-fn.js';\nexport type { iCategories, iTranslations } from './types/translations.js';\n\n// Convenience exports — `t` is a stable function that delegates to the\n// LangsysApp singleton (reads fresh state on every call). `tSignal` is the\n// reactive primitive frameworks bind to.\nimport { LangsysApp as _LangsysApp } from './langsys-app.js';\nimport type { TFunction } from './types/translation-fn.js';\n\nexport const t: TFunction = ((phrase: string, ...rest: unknown[]): string => {\n // Forward all args verbatim; the underlying TFunction implementation\n // handles the (phrase) / (phrase, params) / (phrase, category) /\n // (phrase, category, params) overload discrimination at runtime.\n return (_LangsysApp.Translations.t as (...a: unknown[]) => string)(phrase, ...rest);\n}) as TFunction;\n\nexport const tSignal = _LangsysApp.Translations.tSignal;\n"]}
1
+ {"version":3,"sources":["../src/logger.ts","../src/locale.ts","../src/signal.ts","../src/utils.ts","../src/persist.ts","../src/stores.ts","../src/scope-context.ts","../src/api.ts","../src/server-messages.ts","../src/snapshot.ts","../src/discovery.ts","../src/identity.ts","../src/interpolate.ts","../src/var-markers.ts","../src/content-block.ts","../src/richtext.ts","../src/served-source.ts","../src/notices.ts","../src/var-names.ts","../src/teardown.ts","../src/legacy-value.ts","../src/legacy-keys.ts","../src/translations.ts","../src/langsys-app.ts","../src/hosts.ts","../src/phrase.ts","../src/translate.ts","../src/block-tree.ts","../src/request-scope.ts","../src/index.ts"],"names":["clone","key","x","c","a","b","t","d","i","storage","config","document","t2","IntlMessageFormat","branch","text","node","children","settled","stack","el","pending","isRecord","value","view","served","initialTranslations","list","held","shared","targets","resolved","parent","id","lookup","token","element"],"mappings":";;;;;AAMA,IAAM,MAAA,GAAS;AAAA,EACX,GAAA,EAAK,iHAAA;AAAA,EACL,IAAA,EAAM,qGAAA;AAAA,EACN,KAAA,EAAO;AACX,CAAA;AAcA,SAAS,aAAA,GAAyB;AAM9B,EAAA,IAAI;AACA,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,KAAA;AAC1C,IAAA,OAAO,EAAE,OAAO,SAAA,KAAc,WAAA,IAAe,UAAU,OAAA,KAAY,aAAA,CAAA;AAAA,EACvE,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,KAAA;AAAA,EACX;AACJ;AAEA,SAAS,IAAA,CAAK,KAAA,EAAiC,KAAA,EAAe,IAAA,EAAiB;AAE3E,EAAA,IAAI,eAAc,EAAG;AAEjB,IAAA,OAAA,CAAQ,KAAK,EAAE,CAAA,EAAA,EAAK,KAAK,IAAI,MAAA,CAAO,KAAK,CAAA,EAAG,GAAG,IAAI,CAAA;AAAA,EACvD,CAAA,MAAO;AAEH,IAAA,OAAA,CAAQ,KAAK,CAAA,CAAE,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAA,EAAK,GAAG,IAAI,CAAA;AAAA,EACxC;AACJ;AAEO,IAAM,SAAN,MAAa;AAAA,EAGhB,WAAA,CAAY,eAAe,KAAA,EAAO;AAC9B,IAAA,IAAA,CAAK,YAAA,GAAe,YAAA;AAAA,EACxB;AAAA,EAEA,OAAO,IAAA,EAAiB;AACpB,IAAA,IAAI,CAAC,KAAK,YAAA,EAAc;AACxB,IAAA,IAAA,CAAK,KAAA,EAAO,iBAAiB,IAAI,CAAA;AAAA,EACrC;AAAA,EAEA,QAAQ,IAAA,EAAiB;AACrB,IAAA,IAAA,CAAK,MAAA,EAAQ,mBAAmB,IAAI,CAAA;AA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B,OAAO,QAAQ;AAQ5C,IAAM,aAAA,GAAgB,CAAC,KAAA,KAC1B,UAAA,CAAY,cAAc,KAAK","file":"index.js","sourcesContent":["/**\n * Lightweight debug logger. Styled in browsers (via %c), plain text in Node.\n * Replaces the pre-existing `echo` module from the Svelte SDK with a simpler,\n * SSR-safe equivalent.\n */\n\nconst STYLES = {\n log: 'display:inline-block;background:rgb(239,239,244);color:black;font-weight:bold;padding:3px 7px;border-radius:3px',\n warn: 'display:inline-block;background:gold;color:black;font-weight:bold;padding:3px 7px;border-radius:3px',\n error: 'display:inline-block;background:#e0005a;color:#fff;font-weight:bold;padding:3px 7px;border-radius:3px',\n};\n\n/**\n * React Native defines `window`, so a bare `typeof window` check treats it as a\n * browser — and its console does not render `%c`, so every line comes out as a\n * literal \"%cLangsys Debug\" followed by an unrendered CSS string. Nothing\n * breaks, so nothing reports it; it just looks broken forever.\n * `navigator.product === 'ReactNative'` is the standard discriminator.\n *\n * Evaluated per call rather than once at module load: this module is commonly\n * imported before a host finishes installing its globals, and a value latched\n * at import time cannot be corrected afterwards — nor observed by a test,\n * which is how the browser branch would go unverified.\n */\nfunction supportsStyle(): boolean {\n // Guarded because the probe itself can throw. A host that wraps `globalThis`\n // in a Proxy to assert DOM-freeness — which is how the `/pure` subpath is\n // tested, and how some sandboxes are built — makes `typeof window` raise\n // rather than return 'undefined'. A logger that throws because it looked for\n // a browser is worse than a logger that prints plainly.\n try {\n if (typeof window === 'undefined') return false;\n return !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative');\n } catch {\n return false;\n }\n}\n\nfunction emit(level: 'log' | 'warn' | 'error', label: string, args: unknown[]) {\n // Browsers render %c style. Node just gets the plain string.\n if (supportsStyle()) {\n // eslint-disable-next-line no-console\n console[level](`%c${label}`, STYLES[level], ...args);\n } else {\n // eslint-disable-next-line no-console\n console[level](`[${label}]`, ...args);\n }\n}\n\nexport class Logger {\n debugEnabled: boolean;\n\n constructor(debugEnabled = false) {\n this.debugEnabled = debugEnabled;\n }\n\n log(...args: unknown[]) {\n if (!this.debugEnabled) return;\n emit('log', 'Langsys Debug', args);\n }\n\n warn(...args: unknown[]) {\n emit('warn', 'Langsys Warning', args);\n }\n\n error(...args: unknown[]) {\n emit('error', 'Langsys Error', args);\n }\n}\n\nexport const logger = new Logger(false);\n","import { logger } from './logger.js';\n/**\n * Locale-identifier handling, CLDR/BCP 47 flavored. Everything here rides on\n * the platform's native `Intl` — no bundled locale data.\n *\n * The SDK's convention: normalise once at every input boundary (init config,\n * user-locale store emissions, detectPreferredLocale, API routes) and treat the\n * normalised string as the identity everywhere downstream — cache keys,\n * equality checks, and the wire format all use it.\n *\n * That form is LOWERCASE `xx-yy` (`en-us`, `zh-hant-tw`). It is what every\n * locale in the backend's database already is — script subtags included, stored\n * `az-cyrl` / `bs-latn` — and what the API's request middleware produces. It is\n * therefore the only form guaranteed to behave identically on a route that does\n * NOT mount that middleware, and the routes most likely to miss it are the\n * legacy ones carrying the oldest clients: exactly the clients least likely to\n * send a canonical form. Sending lowercase costs nothing; relying on a\n * normalisation we cannot see, cannot version, and will not be told about when\n * a route stops mounting it does.\n *\n * This does not weaken CLDR handling. `Intl` canonicalises its own input, so\n * `new Intl.Locale('zh-tw').maximize()` still yields `zh-Hant-TW` whether the\n * input was cased or not — likely-subtags matching is unaffected by the form we\n * hold. Validity is a separate axis from casing, which is why the invalid-tag\n * warning below is retained unchanged.\n */\n\n/** A locale's language, script and region subtags, ahead of its variants and extensions. */\nconst LANGUAGE_SCRIPT_REGION = /^(?:[a-z]{2,3}|[a-z]{5,8})(?:-[a-z]{4})?(?:-(?:[a-z]{2}|\\d{3}))?(?=-|$)/i;\n\n/**\n * Normalise a locale identifier to the SDK's single internal form: lowercase\n * `xx-yy` — `en-US` → `en-us`, `zh-Hant-TW` → `zh-hant-tw`. Underscores are\n * accepted and converted (`en_US` → `en-us`). Legacy aliases in the language,\n * script and region are resolved through `Intl.getCanonicalLocales` (`iw` → `he`,\n * `in-ID` → `id-id`, `sh-BA` → `sr-latn-ba`) BEFORE casing is flattened —\n * lowercasing first would lose them, since the alias table is keyed on canonical\n * tags.\n *\n * Variants and extensions are kept as written, lowercased: `en-US-POSIX` is\n * `en-us-posix`. The API's locale codes are ICU locale ids (`en_US_POSIX`), and\n * BCP 47 canonicalisation rewrites some of their variants into a code the API\n * does not hold (`POSIX` becomes the extension `-u-va-posix`).\n *\n * Structurally invalid tags fall back to lowercasing rather than throwing, so a\n * bad config value degrades to a failed catalog lookup instead of a crash — and\n * warns, because that failure is otherwise indistinguishable from a legitimately\n * untranslated locale.\n */\nexport function canonicalizeLocale(locale: string): string {\n if (!locale || typeof locale !== 'string') return locale;\n const cleaned = locale.trim().replace(/_/g, '-');\n try {\n // The whole tag is validated, then only its language, script and region are\n // canonicalised. A valid tag always starts with a language subtag.\n Intl.getCanonicalLocales(cleaned);\n const [head] = LANGUAGE_SCRIPT_REGION.exec(cleaned)!;\n return (Intl.getCanonicalLocales(head)[0] + cleaned.slice(head.length)).toLowerCase();\n } catch {\n // Not a valid BCP 47 tag. The return value cannot signal this — a\n // best-effort cased string is indistinguishable from a successfully\n // canonicalized one, so a typo'd config locale degrades to a silent\n // failed catalog lookup: the app renders base language, which is\n // exactly what a legitimately-untranslated locale looks like. Say so\n // when debug is on, since nothing downstream can.\n if (logger.debugEnabled) logger.warn(\n `\"${locale}\" is not a valid BCP 47 locale tag. Falling back to lowercasing it as-is,` +\n ` which will very likely miss the catalog and render base language with no other symptom.`,\n );\n // Lowercase anyway so the identity stays consistent — an invalid tag\n // must still compare equal to itself across boundaries.\n return cleaned.toLowerCase();\n }\n}\n\n/**\n * The `language-script` key of a locale after CLDR likely-subtags expansion\n * (`Intl.Locale.maximize()`): `zh` → `zh-Hans`, `zh-TW` → `zh-Hant`,\n * `sr` → `sr-Cyrl`. Two locales with the same key are mutually intelligible\n * at the script level; two with different keys must not fall back to each\n * other (a `zh-Hant` reader must never receive a `zh-Hans` catalog).\n *\n * Returns `null` when the tag can't be parsed — callers should treat that\n * as \"no match\" rather than guessing.\n */\nexport function maximizedLangScript(locale: string): string | null {\n try {\n const max = new Intl.Locale(canonicalizeLocale(locale)).maximize();\n // Intl canonicalises its own input, so the lowercase form we hold\n // maximises identically to a cased one. Lowercased for the same reason\n // everything else is: one internal form, compared only against itself.\n return `${max.language}-${max.script ?? ''}`.toLowerCase();\n } catch {\n return null;\n }\n}\n","/**\n * Tiny framework-agnostic reactive value holder — our replacement for a\n * Svelte `Writable<T>`. The shape is deliberately similar so the mental\n * model is identical: subscribe/set/update/get.\n *\n * Usage:\n * const locale = createSignal('en-us');\n * locale.subscribe((v) => console.log('locale is now', v));\n * locale.set('fr-fr');\n * locale.get(); // 'fr-fr'\n *\n * Subscribe is called synchronously with the current value on registration\n * (same semantics as a Svelte store).\n */\nexport type Subscriber<T> = (value: T) => void;\nexport type Unsubscriber = () => void;\nexport type Updater<T> = (value: T) => T;\n\nexport interface Signal<T> {\n /** Register a subscriber; it's called immediately with the current value. Returns an unsubscribe function. */\n subscribe(run: Subscriber<T>): Unsubscriber;\n /** Set the value and notify subscribers. */\n set(value: T): void;\n /** Update the value via a function and notify subscribers. */\n update(fn: Updater<T>): void;\n /** Read the current value without subscribing. */\n get(): T;\n}\n\nexport function createSignal<T>(initial: T): Signal<T> {\n let value: T = initial;\n const subscribers = new Set<Subscriber<T>>();\n\n const subscribe = (run: Subscriber<T>): Unsubscriber => {\n subscribers.add(run);\n run(value);\n return () => {\n subscribers.delete(run);\n };\n };\n\n const set = (next: T): void => {\n // IDENTITY IS THE CHANGE SIGNAL. This guard is what makes\n // `Translations.tSignal` require a FRESH `TFunction` per emit — see\n // `translations.ts` where it is minted. Memoize that closure and this\n // line silently swallows every emit: no subscriber fires, and every\n // binding renders stale text with a correct catalog in the store.\n // Pinned by `tfunction-identity.test.ts`.\n if (Object.is(value, next)) return;\n value = next;\n for (const run of subscribers) run(value);\n };\n\n const update = (fn: Updater<T>): void => {\n set(fn(value));\n };\n\n const get = (): T => value;\n\n return { subscribe, set, update, get };\n}\n\n/** Synchronously read a Signal's value. Mirrors svelte's `get(store)`. */\nexport function getValue<T>(signal: Signal<T>): T {\n return signal.get();\n}\n","export const isEmpty = (data: unknown): boolean => {\n if (typeof data === 'number' || typeof data === 'boolean') return false;\n if (typeof data === 'undefined' || data === null) return true;\n if (typeof (data as { length?: number }).length !== 'undefined') {\n return (data as { length: number }).length === 0;\n }\n if (typeof data === 'object') return Object.keys(data as object).length === 0;\n return false;\n};\n\nexport function structuredCloneShim<T>(obj: T): T {\n if (typeof structuredClone === 'function') return structuredClone(obj);\n\n const clone = <V>(o: V): V => {\n if (typeof o !== 'object' || o === null) return o;\n if (Array.isArray(o)) return o.map((item) => clone(item)) as unknown as V;\n const out: Record<string, unknown> = {};\n for (const key in o as object) {\n if (Object.prototype.hasOwnProperty.call(o, key)) {\n out[key] = clone((o as Record<string, unknown>)[key]);\n }\n }\n return out as V;\n };\n return clone(obj);\n}\n\n/**\n * Encode a string to a \"byte string\" — one character per UTF-8 byte, each\n * ≤ 0xFF. The MD5 core packs `charCodeAt` values into byte lanes and takes\n * `length * 8` as the message bit-length, both of which are only correct when\n * every character IS a single byte. Running this first is what makes `md5`\n * agree with a standard UTF-8 MD5 for non-ASCII input.\n */\nfunction toUtf8ByteString(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let out = '';\n // Chunked to avoid blowing the argument limit on very large content blocks.\n for (let i = 0; i < bytes.length; i += 8192) {\n out += String.fromCharCode(...bytes.subarray(i, i + 8192));\n }\n return out;\n}\n\n/**\n * MD5 of a string, matching a standard UTF-8 MD5 for all input.\n *\n * Content-block `custom_id`s are derived from this, so it's a wire identity —\n * see `generateCustomId`. Before 0.6.0 this packed UTF-16 code units directly\n * into byte lanes, which agreed with a real MD5 only for ASCII: non-ASCII\n * input both diverged from every other Langsys SDK and could collide (a\n * character's high byte was OR-ed into the neighbouring lane, vanishing\n * whenever that lane already carried those bits — so `éa` and `ǩa` hashed\n * alike). `md5Legacy` preserves the old behavior for migration lookups only.\n */\nexport function md5(inputString: string) {\n if (typeof inputString !== 'string') inputString = JSON.stringify(inputString);\n return md5Core(toUtf8ByteString(inputString));\n}\n\n/**\n * The pre-0.6.0 MD5, retained ONLY so existing content blocks stay resolvable:\n * ids minted by an older SDK are keyed by this. Lookup-only — never register\n * new content under it, or the colliding-id population keeps growing.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function md5Legacy(inputString: string) {\n if (typeof inputString !== 'string') inputString = JSON.stringify(inputString);\n return md5Core(inputString);\n}\n\n// prettier-ignore\nfunction md5Core(inputString: string) {\n const hc = '0123456789abcdef';\n function rh(n: number) { let j, s = ''; for (j = 0; j <= 3; j++) s += hc.charAt((n >> (j * 8 + 4)) & 0x0F) + hc.charAt((n >> (j * 8)) & 0x0F); return s; }\n function ad(x: number, y: number) { const l = (x & 0xFFFF) + (y & 0xFFFF); const m = (x >> 16) + (y >> 16) + (l >> 16); return (m << 16) | (l & 0xFFFF); }\n function rl(n: number, c: number) { return (n << c) | (n >>> (32 - c)); }\n function cm(q: number, a: number, b: number, x: number, s: number, t: number) { return ad(rl(ad(ad(a, q), ad(x, t)), s), b); }\n function ff(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm((b & c) | ((~b) & d), a, b, x, s, t); }\n function gg(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm((b & d) | (c & (~d)), a, b, x, s, t); }\n function hh(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm(b ^ c ^ d, a, b, x, s, t); }\n function ii(a: number, b: number, c: number, d: number, x: number, s: number, t: number) { return cm(c ^ (b | (~d)), a, b, x, s, t); }\n function sb(x: string) {\n let i; const nblk = ((x.length + 8) >> 6) + 1; const blks = new Array(nblk * 16); for (i = 0; i < nblk * 16; i++) blks[i] = 0;\n for (i = 0; i < x.length; i++) blks[i >> 2] |= x.charCodeAt(i) << ((i % 4) * 8);\n blks[i >> 2] |= 0x80 << ((i % 4) * 8); blks[nblk * 16 - 2] = x.length * 8; return blks;\n }\n let i, x = sb('' + inputString), a = 1732584193, b = -271733879, c = -1732584194, d = 271733878, olda, oldb, oldc, oldd;\n for (i = 0; i < x.length; i += 16) {\n olda = a; oldb = b; oldc = c; oldd = d;\n a = ff(a, b, c, d, x[i + 0], 7, -680876936); d = ff(d, a, b, c, x[i + 1], 12, -389564586); c = ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = ff(b, c, d, a, x[i + 3], 22, -1044525330); a = ff(a, b, c, d, x[i + 4], 7, -176418897); d = ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = ff(c, d, a, b, x[i + 6], 17, -1473231341); b = ff(b, c, d, a, x[i + 7], 22, -45705983); a = ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = ff(d, a, b, c, x[i + 9], 12, -1958414417); c = ff(c, d, a, b, x[i + 10], 17, -42063); b = ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = ff(a, b, c, d, x[i + 12], 7, 1804603682); d = ff(d, a, b, c, x[i + 13], 12, -40341101); c = ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = ff(b, c, d, a, x[i + 15], 22, 1236535329); a = gg(a, b, c, d, x[i + 1], 5, -165796510); d = gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = gg(c, d, a, b, x[i + 11], 14, 643717713); b = gg(b, c, d, a, x[i + 0], 20, -373897302); a = gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = gg(d, a, b, c, x[i + 10], 9, 38016083); c = gg(c, d, a, b, x[i + 15], 14, -660478335); b = gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = gg(a, b, c, d, x[i + 9], 5, 568446438); d = gg(d, a, b, c, x[i + 14], 9, -1019803690); c = gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = gg(b, c, d, a, x[i + 8], 20, 1163531501); a = gg(a, b, c, d, x[i + 13], 5, -1444681467); d = gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = gg(c, d, a, b, x[i + 7], 14, 1735328473); b = gg(b, c, d, a, x[i + 12], 20, -1926607734); a = hh(a, b, c, d, x[i + 5], 4, -378558);\n d = hh(d, a, b, c, x[i + 8], 11, -2022574463); c = hh(c, d, a, b, x[i + 11], 16, 1839030562); b = hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = hh(a, b, c, d, x[i + 1], 4, -1530992060); d = hh(d, a, b, c, x[i + 4], 11, 1272893353); c = hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = hh(b, c, d, a, x[i + 10], 23, -1094730640); a = hh(a, b, c, d, x[i + 13], 4, 681279174); d = hh(d, a, b, c, x[i + 0], 11, -358537222);\n c = hh(c, d, a, b, x[i + 3], 16, -722521979); b = hh(b, c, d, a, x[i + 6], 23, 76029189); a = hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = hh(d, a, b, c, x[i + 12], 11, -421815835); c = hh(c, d, a, b, x[i + 15], 16, 530742520); b = hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = ii(a, b, c, d, x[i + 0], 6, -198630844); d = ii(d, a, b, c, x[i + 7], 10, 1126891415); c = ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = ii(b, c, d, a, x[i + 5], 21, -57434055); a = ii(a, b, c, d, x[i + 12], 6, 1700485571); d = ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = ii(c, d, a, b, x[i + 10], 15, -1051523); b = ii(b, c, d, a, x[i + 1], 21, -2054922799); a = ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = ii(d, a, b, c, x[i + 15], 10, -30611744); c = ii(c, d, a, b, x[i + 6], 15, -1560198380); b = ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = ii(a, b, c, d, x[i + 4], 6, -145523070); d = ii(d, a, b, c, x[i + 11], 10, -1120210379); c = ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = ii(b, c, d, a, x[i + 9], 21, -343485551); a = ad(a, olda); b = ad(b, oldb); c = ad(c, oldc); d = ad(d, oldd);\n }\n return rh(a) + rh(b) + rh(c) + rh(d);\n}\n","import { createSignal, type Signal } from './signal.js';\nimport { structuredCloneShim } from './utils.js';\n\n/**\n * Minimal synchronous storage contract for `persist` — structurally a subset of\n * the DOM `Storage` interface, so `localStorage` satisfies it as-is.\n *\n * Synchronous on purpose: `persist` seeds its signal during module\n * initialization, so an async backend could not be read in time. React Native\n * apps inject a synchronous adapter (MMKV, or an in-memory mirror of\n * AsyncStorage hydrated at startup) via `setPersistStorage`.\n */\nexport interface PersistStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n /** Optional. Used to drop superseded keys; absent on minimal adapters. */\n removeItem?(key: string): void;\n}\n\ninterface PersistEntry {\n hydrate: (storage: PersistStorage) => void;\n}\n\n/** Every signal `persist` has created, so a late `setPersistStorage` can hydrate them. */\nconst registry: PersistEntry[] = [];\n\nlet injectedStorage: PersistStorage | null = null;\n\n/**\n * Inject the storage backend used by every `persist` signal — those created\n * afterwards AND those that already exist.\n *\n * Re-hydrating the existing ones is the point, not a nicety: the catalog store\n * is built at module load, long before a React Native app can hand us MMKV, so\n * an injection that only applied going forward would apply to none of the\n * signals anyone cares about.\n *\n * Pass `null` to drop the injection and return to auto-detection.\n */\nexport function setPersistStorage(storage: PersistStorage | null): void {\n injectedStorage = storage;\n if (!storage) {\n // Re-probe on the next access. Auto-detection is memoized, and a caller\n // returning to it has usually changed the environment underneath us.\n browserStorage = undefined;\n return;\n }\n for (const entry of registry) entry.hydrate(storage);\n}\n\n/**\n * Create a Signal whose value is persisted to storage when one is available: an\n * injected `PersistStorage` first, else `localStorage`. Falls back to in-memory\n * behaviour during SSR, or when storage is unavailable or quota-exceeded.\n * Stored value is JSON-encoded.\n *\n * `legacyKey` is READ but never written, so a renamed key migrates its cache on\n * first load instead of silently dropping it. A host app that downgrades the\n * SDK still finds its old value where it left it.\n *\n * DO NOT persist `writeEnabled`, `autoDiscovery`, or any other session\n * capability. \"Cache it like translations for a faster warm start\" is the\n * obvious next optimization and it is wrong twice over:\n *\n * 1. A persisted value is restored SYNCHRONOUSLY at module init, so the client\n * would mount with a concrete capability while the server rendered from\n * `undefined` — a hydration mismatch on every consumer, not just the ones\n * that resolve auth before first render.\n * 2. Write capability is per-session and IP-dependent: the same key answers\n * differently from different networks, and a grant makes it per-user.\n * Persisting it caches one session's answer across later sessions on a\n * shared device — the same unsoundness as caching it on an SSR singleton.\n *\n * Translations are safe to persist because they are project-scoped content, not\n * a permission decision. Capability is re-derived from the server every time.\n */\nexport function persist<T>(key: string, initial: T, legacyKey?: string): Signal<T> {\n const storage = activeStorage();\n let seed = initial;\n\n if (storage) {\n const stored = readStored(storage, key, legacyKey);\n if (stored !== undefined) seed = stored as T;\n }\n\n const signal = createSignal<T>(seed);\n\n // Resolved per write rather than captured: a signal created before\n // `setPersistStorage` must still write to the injected backend afterwards.\n signal.subscribe((value) => {\n const target = activeStorage();\n if (!target) return;\n try {\n target.setItem(key, JSON.stringify(value));\n } catch {\n // Quota / serialization failure — keep going; in-memory stays authoritative.\n }\n });\n\n registry.push({\n hydrate: (target) => {\n const stored = readStored(target, key, legacyKey);\n if (stored !== undefined) signal.set(stored as T);\n },\n });\n\n return signal;\n}\n\n/**\n * A persisted signal whose storage key is not known at module-init time.\n *\n * `persist` reads its key immediately, which is wrong for anything scoped by\n * identity the SDK does not have yet. The translation catalog is keyed by\n * project AND locale (CACHE-1), and neither exists until `init()` has run — so\n * reading at module load means restoring *some* catalog and serving it before\n * anyone can tell whether it belongs to this project or this language.\n *\n * This variant touches storage only once `scope()` supplies the identity:\n *\n * - Before the first `scope()`: nothing is read and nothing is written. The\n * signal holds whatever it was created with, so an SSR handoff that seeded\n * it is preserved.\n * - `scope(s)` with data stored under `s`: adopt it.\n * - `scope(s)` with nothing stored, and a PREVIOUS scope was set: reset to\n * `initial`. Leaving the old scope's value in place is the bug — it is how\n * project A's catalog gets served to project B. The reset is not written:\n * `initial` is no catalog, and stored under `s` it would be read back as\n * that scope's catalog after a fetch for it failed or was superseded\n * (CACHE-2). Only a value set afterwards is persisted.\n * - `scope(s)` with nothing stored and no previous scope: leave the signal\n * alone, so an SSR-seeded catalog survives.\n * - `scope(null)`: stop persisting.\n */\nexport function persistScoped<T>(\n keyPrefix: string,\n initial: T,\n supersedes: string[] = []\n): { signal: Signal<T>; scope: (scope: string | null) => void } {\n const signal = createSignal<T>(initial);\n let currentKey: string | null = null;\n let everScoped = false;\n // Did somebody write to this signal BEFORE any scope existed? That is the\n // SSR handoff: `init()` seeds the catalog from the server payload, and only\n // then does `change()` scope the cache. Such a value is authoritative — it\n // came from this request, for this locale — and must beat anything stored.\n let seededBeforeScope = false;\n let emissions = 0;\n // Set while `scope()` resets the signal, so the reset value is not persisted.\n let resetting = false;\n\n signal.subscribe((value) => {\n emissions += 1;\n // `subscribe` fires immediately with the current value, so emission 1\n // is creation, not a write.\n if (!everScoped && emissions > 1) seededBeforeScope = true;\n if (!currentKey || resetting) return;\n const target = activeStorage();\n if (!target) return;\n try {\n target.setItem(currentKey, JSON.stringify(value));\n } catch {\n // Quota / serialization failure — in-memory stays authoritative.\n }\n });\n\n const scope = (next: string | null): void => {\n const key = next === null ? null : `${keyPrefix}:${next}`;\n if (key === currentKey) return;\n\n const storage = activeStorage();\n const stored = key && storage ? readStored(storage, key) : undefined;\n const hadScope = everScoped;\n\n currentKey = key;\n if (key !== null) everScoped = true;\n\n // An SSR handoff outranks the store on the FIRST scoping, whether or\n // not something is stored. Adopting the stored copy here was a\n // regression: the server just rendered this page with a fresh catalog,\n // and `markLoaded` primes the 60s cache-hit so no corrective fetch\n // fires — so a returning visitor to an SSR app would be served last\n // session's strings for the whole session. Persist the fresh value\n // instead, so the next load starts from it.\n if (!hadScope && seededBeforeScope && key !== null) {\n const target = activeStorage();\n if (target) {\n try {\n target.setItem(key, JSON.stringify(signal.get()));\n } catch {\n // Quota — in-memory stays authoritative.\n }\n }\n return;\n }\n\n if (stored !== undefined) {\n signal.set(stored as T);\n return;\n }\n // Nothing stored for the new scope. Clear only if we are LEAVING a\n // scope — otherwise this is the first scoping and there is nothing to\n // discard.\n if (hadScope && key !== null) {\n resetting = true;\n try {\n signal.set(structuredCloneShim(initial));\n } finally {\n resetting = false;\n }\n }\n };\n\n // Drop the unscoped keys this replaces, once, when identity first arrives.\n // They can never be read again, and a stale catalog left in localStorage\n // forever is the kind of thing nobody goes looking for.\n if (supersedes.length) {\n const drop = () => {\n const storage = activeStorage();\n if (!storage?.removeItem) return;\n for (const k of supersedes) {\n try {\n if (storage.getItem(k) !== null) storage.removeItem(k);\n } catch {\n // Unreadable storage — nothing to clean.\n }\n }\n };\n const originalScope = scope;\n return {\n signal,\n scope: (next) => {\n originalScope(next);\n if (next !== null) drop();\n },\n };\n }\n\n return { signal, scope };\n}\n\n/** Current key first, then the legacy one. `undefined` means \"nothing usable stored\". */\nfunction readStored(storage: PersistStorage, key: string, legacyKey?: string): unknown {\n for (const candidate of legacyKey ? [key, legacyKey] : [key]) {\n try {\n const raw = storage.getItem(candidate);\n if (raw !== null) return JSON.parse(raw);\n } catch {\n // Corrupt or unreadable — try the next candidate, else fall through\n // to the caller's initial value.\n }\n }\n return undefined;\n}\n\nfunction activeStorage(): PersistStorage | null {\n return injectedStorage ?? getSafeStorage();\n}\n\n/** `undefined` = not probed yet; `null` = probed and unusable. */\nlet browserStorage: Storage | null | undefined;\n\nfunction getSafeStorage(): Storage | null {\n // Memoized because this now runs on every persisted write rather than once\n // at creation.\n if (browserStorage !== undefined) return browserStorage;\n\n // React Native defines `window` (an alias of `global`) but not\n // `window.localStorage`, so the PROBE below — not the typeof check — is what\n // routes RN to in-memory, or to an injected PersistStorage.\n if (typeof window === 'undefined') return (browserStorage = null);\n try {\n const s = window.localStorage;\n // Some browsers throw on access in private-mode iframes.\n s.getItem('__langsys_probe__');\n return (browserStorage = s ?? null);\n } catch {\n return (browserStorage = null);\n }\n}\n","import { createSignal, type Signal } from './signal.js';\nimport { persistScoped } from './persist.js';\nimport type { iCategories } from './types/translations.js';\nimport type { iLangsysConfig } from './types/config.js';\n\nconst initialTranslations: iCategories = {\n __uncategorized__: {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n },\n};\n\n/**\n * The translation catalog, cached in localStorage for a warm start.\n *\n * Keyed by PROJECT and LOCALE (CACHE-1), and hydrated only once `init()` knows\n * both. The key used to be a bare `translations` with neither, which meant a\n * page load restored whatever catalog was there and served it before anything\n * could check whose it was: a visitor who used the app in French saw French\n * until the English fetch landed, and two projects sharing an origin\n * overwrote and then served each other's content. Both failed silently.\n *\n * `persist` cannot express this because it reads its key at module load, and\n * neither project nor locale exists then — see `persistScoped`.\n *\n * The two superseded keys are removed when identity first arrives; they can\n * never be read again, and a stale catalog sitting in localStorage forever is\n * not something anyone goes looking for.\n */\nconst catalogCache = persistScoped<iCategories>('langsys:translations', initialTranslations, [\n 'translations',\n 'langsys:translations',\n]);\n\n/**\n * The request scope the current code renders in, as the two signals below need\n * it (SRV-7). Registered by `scope-context.ts`, so this module imports nothing\n * from the scope and has no cycle.\n */\nlet activeScopeView: () => { catalog: iCategories; locale: string } | undefined = () => undefined;\n\n/** @internal Called once by `scope-context.ts`. */\nexport function _followRequestScope(resolver: () => { catalog: iCategories; locale: string } | undefined): void {\n activeScopeView = resolver;\n}\n\n/**\n * A page signal whose reads follow the active request scope. `get()`, and the\n * synchronous first emission of `subscribe(run)`, answer with the scope's value:\n * a Svelte `$store` read on a server IS a subscription, so the first emission is\n * the read. Later emissions, and `set` and `update`, are the page's.\n */\nfunction followScope<T>(page: Signal<T>, pick: (scope: { catalog: iCategories; locale: string }) => T): Signal<T> {\n return {\n ...page,\n get: () => {\n const scope = activeScopeView();\n return scope ? pick(scope) : page.get();\n },\n subscribe: (run) => {\n const scope = activeScopeView();\n if (!scope) return page.subscribe(run);\n let first = true;\n return page.subscribe((value) => {\n if (first) {\n first = false;\n run(pick(scope));\n return;\n }\n run(value);\n });\n },\n };\n}\n\n/**\n * The catalog. Inside a request scope `get()` answers with the scope's catalog,\n * as `t()` does, so a binding that reads the catalog through this signal on a\n * server renders the visitor's, never another request's. `set`, `update` and\n * `subscribe` are the page's.\n */\nexport const sTranslations: Signal<iCategories> = followScope(catalogCache.signal, (scope) => scope.catalog);\n\n/** The page's own catalog, whatever scope is current: for the page's flush and write-back. */\nexport const pageCatalog = (): iCategories => catalogCache.signal.get();\n\n/**\n * Point the catalog cache at a `<projectid>:<locale>` scope. Called by `init()`\n * as soon as it holds both, and by `Translations.change()` before a fetch, so a\n * hit warms and a miss simply misses — never serves another scope's catalog.\n */\nexport const scopeCatalogCache = catalogCache.scope;\n\n/**\n * Whether the client has credentials (WIRE-4): `undefined` until `init()` runs, `false` when\n * `init()` was refused for a missing project id, API key or locale store, `true` once it\n * accepted them. `LangsysApp.isConfigured()` reports it.\n */\nexport const configured = createSignal<boolean | undefined>(undefined);\n\n/** The scope a project and locale's catalog is cached, fetched and failure-tracked under (CACHE-1). */\nexport const catalogScopeOf = (projectid: string, locale: string): string => `${projectid}:${locale}`;\n\nconst pageLocaleSignal = createSignal<string>('');\n\n/**\n * The locale the catalog is for. Inside a request scope `get()` answers with the\n * scope's locale (SRV-7), for the same reason as `sTranslations`.\n */\nexport const currentlyLoadedLocale: Signal<string> = followScope(pageLocaleSignal, (scope) => scope.locale);\n\n/** The page's own loaded locale, whatever scope is current. */\nexport const pageLocale = (): string => pageLocaleSignal.get();\n\nexport const config: iLangsysConfig = {\n projectid: '',\n key: '',\n sUserLocale: createSignal<string>(''),\n baseLocale: 'en',\n debug: false,\n key_type: 'read',\n};\n\n/**\n * Server-computed write capability for THIS session. The single source of\n * truth for every write decision — never infer it from `key_type`, which\n * cannot express `ip_write` (read-only everywhere except from allow-listed\n * IPs, which is exactly how the discovery renderer registers content).\n *\n * Tri-state, and the three states are genuinely distinct:\n * - `undefined` — not yet authorized. HOLD: neither register nor hint.\n * Collapsing this to `false` would drop every miss that lands before\n * `validate()` resolves and fire a spurious discovery hint for it.\n * - `true` — register missing tokens (never hint).\n * - `false` — never attempt a write (no 403 churn); hint instead.\n *\n * Refreshed from `authorize-project` at init and from every catalog fetch.\n *\n * BROWSER-AUTHORITATIVE: only ever written when `window` exists. Write\n * capability is per-session (it varies by requester IP and by write grant),\n * while this module is a process-wide singleton — in a long-lived SSR server\n * shared across every request and every user, caching one request's answer\n * here would apply it to every later visitor. Under SSR it stays `undefined`,\n * which is the honest answer rather than a leaked one.\n */\nexport const writeEnabled = createSignal<boolean | undefined>(undefined);\n\n/**\n * Whether the most recent catalog fetch FAILED (WIRE-4). While true, the catalog\n * cannot tell a miss from a hit, so nothing may be recorded against it: no\n * registration queued or sent, no content block registered, no discovery miss.\n * Cleared by the next catalog that actually arrives, fetched or seeded.\n *\n * Internal, and deliberately not exported from the package: it describes the state\n * of `sTranslations`, which is equally module-global, and a binding has no decision\n * to make with it.\n */\nexport const catalogUnavailable = createSignal<boolean>(false);\n\n/**\n * Whether this API key is permitted to report page URLs for content discovery.\n *\n * A POLICY, not a capability — deliberately independent of `writeEnabled`, and\n * the two must not be collapsed. `writeEnabled` answers \"can this session write\n * from here\"; this answers \"may this key report at all\". The canonical public\n * website is `writeEnabled: false` **and** `autoDiscovery: true` — read-only,\n * and permitted to report — which is exactly the case a single merged flag\n * would break.\n *\n * It exists because the SDK cannot tell whether it is running on a public\n * website. A mobile app holding a read key would otherwise report \"page URLs\"\n * that are not pages, and no heuristic settles it — our own URL heuristic is\n * already defeated by a routerless SPA. Beyond that, a customer may simply not\n * want visitors' page paths leaving the browser, whatever the SDK infers.\n *\n * Plain boolean rather than the tri-state `writeEnabled` uses, and false until\n * known. That is only safe because it is evaluated where the report is SENT\n * rather than where the miss is recorded: by then authorization has long since\n * resolved, and if it somehow hasn't, not reporting is the correct conservative\n * default. Checked at collection time instead, false-until-known would silently\n * drop early misses for keys that do permit reporting.\n */\nexport const autoDiscovery = createSignal<boolean | undefined>(undefined);\n\n/**\n * Project setting: while true, a miss is recorded only when the loaded locale IS the\n * base locale. It gates BOTH lanes — the registration queue and the discovery hint.\n *\n * The catalog is keyed by source text, and a server SDK renders a page in the visitor's\n * language, so every string in that page is a translation. Without this, a write-enabled\n * session browsing in Spanish files Spanish sentences as new SOURCE phrases, and a\n * read-only one hints a localized URL, which sends the renderer to the same translated\n * text. Legacy servers already send translated text and cannot be made to stop.\n *\n * Delivered in the handshake — `authorize-project` beside `key_type`, and the catalog\n * envelope beside `words` — and honoured with no local override, so there is one source\n * of truth. Absent or non-boolean means off, which is also the state until a backend\n * ships the field. A PROJECT setting rather than a key-derived one like `autoDiscovery`,\n * so it is the same answer for every key on the project.\n *\n * Off by default because it has a real cost: with it on, an English fallback appearing on\n * a localized page is no longer discovered from that page.\n */\nexport const discoveryBaseLocaleOnly = createSignal<boolean>(false);\n\n/**\n * Server-authoritative cap on items per `/translatable-items` request, from\n * `langsys_settings.translatable_items.batch_limit` on the authorization\n * response. Never hardcode it: if the server lowers its limit, an SDK sending\n * its own idea of a batch has every oversized request rejected, and those\n * phrases are never registered — silently, for every writing session.\n *\n * The default matches the server's own default so behaviour is unchanged\n * against a backend that doesn't send it.\n */\nexport const batchLimit = createSignal<number>(200);\n\n/**\n * Advanced by `notifyNavigation()` (HINT-13). The core's own DOM classes subscribe to it and\n * re-enter their lookup, as a re-render would, while their host is attached to the document.\n * Bindings need nothing from it: the same call publishes a fresh `t` through `tSignal`.\n */\nexport const navigationEpoch = createSignal<number>(0);\n\n/**\n * Record the server's write decision. No-ops during SSR — see the\n * browser-authoritative note on `writeEnabled`.\n */\nexport function setWriteEnabled(value: boolean | undefined): void {\n if (typeof window === 'undefined') return;\n if (typeof value !== 'boolean') return;\n if (writeEnabled.get() !== value) writeEnabled.set(value);\n}\n","import type { ApiCredentials } from './api.js';\nimport { _followRequestScope, pageCatalog } from './stores.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { iCategories } from './types/translations.js';\n\n/**\n * Which request scope, if any, the current code runs in (spec SRV-7).\n *\n * Kept apart from `request-scope.ts` so the modules that read the catalog —\n * `t()`, the content-block lookups, registration — can ask \"which catalog?\"\n * without importing the scope's implementation, which imports them.\n */\n\n/** What the core needs from an active scope. */\nexport interface ActiveScope {\n readonly locale: string;\n readonly catalog: iCategories;\n /** What the scope's requests send under (SRV-2); undefined for a scope given none, which sends under the module-wide ones. */\n readonly credentials: ApiCredentials | undefined;\n /** `t()` inside the scope: reads the scope's catalog and records the scope's misses. */\n t(phrase: string, ...rest: unknown[]): string;\n /** Hold a content block for the scope's flush after the response. */\n recordBlock(block: iContentBlock): void;\n /** Remember a block the scope rendered, for its seed. */\n recordRendered(block: { customId: string; category: string; tokens: string[]; shape: 'phrase' | 'block'; content?: string; register?: false }): void;\n}\n\n/** The ambient-context shape `AsyncLocalStorage` has, so the core never imports `node:async_hooks`. */\nexport interface ScopeStorage {\n getStore(): unknown;\n run<R>(store: unknown, fn: () => R): R;\n /** Makes a store current for the rest of the async context; needed only by `scope.enter()`. */\n enterWith?(store: unknown): void;\n}\n\nlet storage: ScopeStorage | null = null;\n/** Without a storage, `run` nests synchronously: only code that finishes inside `fn` sees the scope. */\nconst stack: ActiveScope[] = [];\n\n/**\n * Hand the core an `AsyncLocalStorage` (or anything of its shape), so a scope\n * entered with `scope.run()` stays current across `await` inside the render.\n * Pass `null` to go back to synchronous nesting.\n *\n * The storage is opt-in, and what it guarantees depends on the host's async\n * model: under zone.js, for one, promises do not carry it across concurrent\n * renders. A binding may instead carry the scope through its own dependency\n * injection, one scope per request, and read `scope.t` and the scope's values\n * directly, with no storage at all.\n */\nexport function setRequestScopeStorage(value: ScopeStorage | null): void {\n storage = value;\n}\n\n/** The scope the current code runs in, or undefined outside every scope. */\nexport function activeScope(): ActiveScope | undefined {\n const stored = storage?.getStore() as ActiveScope | undefined;\n return stored ?? stack[stack.length - 1];\n}\n\n/**\n * Make `scope` current for the rest of the current async context. Needs a\n * storage with `enterWith`: there is no synchronous fallback, since the context\n * outlives any stack frame. `enterWith` binds the store to the current async\n * resource, so it holds only in the continuation that performs the render,\n * never past the return of a function the host awaits (see `RequestScope.enter`).\n */\nexport function enterScope(scope: ActiveScope): void {\n if (!storage?.enterWith) {\n throw new Error(\n 'scope.enter() needs an AsyncLocalStorage: call setRequestScopeStorage(new AsyncLocalStorage()) once at startup, or wrap the render in scope.run().'\n );\n }\n storage.enterWith(scope);\n}\n\n/** Run `fn` with `scope` current, and return what `fn` returns: a promise stays a promise. */\nexport function runInScope<R>(scope: ActiveScope, fn: () => R): R {\n if (storage) return storage.run(scope, fn);\n stack.push(scope);\n try {\n return fn();\n } finally {\n stack.pop();\n }\n}\n\n/** Run `fn` outside every scope, as the page does: for work a scope hands to the page's lanes. */\nexport function runOutsideScopes<R>(fn: () => R): R {\n return storage ? storage.run(undefined, fn) : fn();\n}\n\n/** The catalog the current code reads: its scope's, or the page's. */\nexport function activeCatalog(): iCategories {\n return activeScope()?.catalog ?? pageCatalog();\n}\n\n// `sTranslations.get()` and `currentlyLoadedLocale.get()` follow the scope too.\n_followRequestScope(() => activeScope());\n","import { canonicalizeLocale } from './locale.js';\nimport { createSignal } from './signal.js';\nimport type { HttpResponse, ResponseObject } from './types/api.js';\nimport type { iLangsysConfig, WriteGrant } from './types/config.js';\nimport { logger } from './logger.js';\nimport { activeScope } from './scope-context.js';\n\ntype Method = 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT';\n\n/**\n * The client has no credentials (WIRE-4): `init()` was refused for a missing project id,\n * API key or locale store, or was never called. An explicit write throws this rather than\n * sending, and so does `t()` under `requireCredentials`. A read renders source text instead,\n * and a call whose result reports a skipped write resolves skipped with reason\n * `not-configured`, since a component reaches it and a component path never throws.\n */\nexport class LangsysConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LangsysConfigurationError';\n }\n}\n\n/**\n * What a request sends under (SRV-2): a project id and API key, with the write grant that\n * goes with them. The module-wide ones are what `init()` set; a request scope may carry\n * its own.\n */\nexport interface ApiCredentials {\n readonly projectid: string;\n readonly key: string;\n readonly writeGrant?: WriteGrant;\n}\n\nexport interface SendOptions {\n /**\n * Let the request outlive the page that started it (`fetch` keepalive).\n * Used for the teardown flush, where the document is being torn down and a\n * normal request would be cancelled with it.\n *\n * NOT `navigator.sendBeacon`, which is the usual answer to this problem but\n * cannot carry custom headers — our authorization is `x-Authorization`, so\n * a beacon would be rejected. `keepalive` supports headers and survives\n * teardown; the trade is a ~64KB body cap across in-flight keepalive\n * requests, which is why the teardown path chunks conservatively.\n */\n keepalive?: boolean;\n /**\n * Send under these credentials. Without them a request sends under those of the\n * request scope the calling code runs in, and outside every scope under the\n * module-wide ones (SRV-2). The page's own lanes pass the module-wide ones, so a page\n * request that starts inside a scope's async context still goes out under the page's key.\n */\n credentials?: ApiCredentials;\n}\n\nclass LangsysAppAPIClass {\n private apiurl = 'https://api.langsys.dev/api';\n public config: iLangsysConfig;\n\n constructor() {\n this.config = {\n projectid: '',\n key: '',\n sUserLocale: createSignal(''),\n baseLocale: 'en',\n };\n }\n\n public setup(config: iLangsysConfig) {\n if (config?.key && config?.projectid) {\n this.config = config;\n }\n }\n\n /** Forget the credentials: `init()` was refused for missing ones, so nothing may send under old ones. */\n public clearCredentials(): void {\n this.config = { ...this.config, projectid: '', key: '', writeGrant: undefined };\n }\n\n /** True when the module-wide credentials carry a write grant (in either form). */\n public hasWriteGrant(): boolean {\n return !!this.config.writeGrant;\n }\n\n /** The module-wide credentials `init()` set: the page's, and a scope's that was given none. */\n public moduleCredentials(): ApiCredentials {\n return this.config;\n }\n\n /** What a request made now sends under, unless it names its own (SRV-2): the active scope's, else the module-wide ones. */\n public currentCredentials(): ApiCredentials {\n return activeScope()?.credentials ?? this.config;\n }\n\n /**\n * Resolve the write grant a request sends with, calling the consumer's provider\n * if that is the configured form.\n *\n * The result is deliberately NOT cached — not here, not on the config\n * singleton. Grants are ~5 minute JWTs and per-user, while this client is\n * a process-wide singleton; in a long-lived SSR server one cached token\n * would be attached to every later user's requests. Resolving per request\n * is also what lets the host app refresh by simply returning a new token.\n */\n private async resolveWriteGrant(credentials: ApiCredentials): Promise<string | null> {\n const grant = credentials.writeGrant;\n if (!grant) return null;\n try {\n const token = typeof grant === 'function' ? await grant() : grant;\n return typeof token === 'string' && token.length > 0 ? token : null;\n } catch (err) {\n // A throwing provider must not take the request down with it —\n // the session simply proceeds without a grant (read-only).\n logger.warn('LangsysAppAPI: writeGrant provider threw; sending request without a grant', err);\n return null;\n }\n }\n\n /** Build request headers fresh per call. Never memoized — see `resolveWriteGrant`. */\n private async buildHeaders(credentials: ApiCredentials): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json; charset=utf-8',\n 'x-Authorization': credentials.key,\n // Declare ICU MessageFormat rendering so the server sends raw ICU\n // (plural/select) instead of flat-template downgrades. Pre-ICU\n // builds omit this header and keep receiving flat strings.\n 'X-Langsys-Capabilities': 'icu',\n };\n\n // Sent on every request, not just writes: the grant is what the server\n // uses to compute `write_enabled`, which comes back on\n // `authorize-project` and on every catalog fetch.\n const grant = await this.resolveWriteGrant(credentials);\n if (grant) headers['X-Write-Grant'] = grant;\n\n return headers;\n }\n\n /** Optional hook to point the client at a different API host. */\n public setBaseUrl(url: string) {\n this.apiurl = url.replace(/\\/$/, '');\n }\n\n public async validate(config: iLangsysConfig) {\n this.setup(config);\n return await this.get('authorize-project/[projectid]', {}, { credentials: this.config });\n }\n\n public async getTranslations(locale: string, opts: SendOptions = {}) {\n const credentials = opts.credentials ?? this.currentCredentials();\n // The CLDR-compliant backend keys catalogs by canonical BCP 47 tags.\n return await this.get('translations', { project_id: credentials.projectid, locale: canonicalizeLocale(locale) }, { ...opts, credentials });\n }\n\n /**\n * Register phrases and/or content blocks via the current unified endpoint.\n * Each item carries `type: 'phrase' | 'content_block'`. Replaces the\n * deprecated `projects/{id}/tokens` and `projects/{id}/content-blocks` routes.\n */\n public async createTranslatableItems(items: Array<Record<string, unknown>>, opts: SendOptions = {}) {\n const credentials = opts.credentials ?? this.currentCredentials();\n return await this.post(\n 'translatable-items',\n {\n project_id: credentials.projectid,\n translatable_items: items,\n },\n { ...opts, credentials },\n );\n }\n\n /**\n * Report that a page appears to contain unregistered content, so the\n * discovery renderer can visit it from an allow-listed IP and register\n * what it finds.\n *\n * URL only — never a phrase payload. This is the read-only lane: anonymous\n * callers can say \"look here\", never \"store this\". Answers 204 whether or\n * not the hint is acted on, deliberately so it can't be used as an oracle\n * for key validity or registration state. No `project_id`: the key already\n * resolves to exactly one project server-side.\n */\n public async postDiscoveryHint(pageUrl: string, opts: SendOptions = {}) {\n return await this.post('discovery/hint', { page_url: pageUrl }, opts);\n }\n\n public async post(path: string, data: Record<string, unknown> = {}, opts: SendOptions = {}) {\n return await this.send('POST', path, data, opts);\n }\n public async get(path: string, data: Record<string, unknown> = {}, opts: SendOptions = {}) {\n return await this.send('GET', path, data, opts);\n }\n public async delete(path: string, data: Record<string, unknown> = {}, opts: SendOptions = {}) {\n return await this.send('DELETE', path, data, opts);\n }\n public async patch(path: string, data: Record<string, unknown> = {}, opts: SendOptions = {}) {\n return await this.send('PATCH', path, data, opts);\n }\n public async put(path: string, data: Record<string, unknown> = {}, opts: SendOptions = {}) {\n return await this.send('PUT', path, data, opts);\n }\n\n private async send(\n method: Method,\n path: string,\n data: Record<string, unknown> = {},\n opts: SendOptions = {},\n ): Promise<ResponseObject> {\n // Resolved before anything is awaited, so the request goes out under the scope that\n // made it however the renders around it interleave (SRV-2).\n const credentials = opts.credentials ?? this.currentCredentials();\n if (!credentials.projectid || !credentials.key) {\n // WIRE-4: an explicit write without credentials is a programming error and says\n // so. A read answers with the error envelope below and never throws.\n if (method !== 'GET') {\n throw new LangsysConfigurationError(\n `Langsys is not configured: cannot ${method} ${path} without a project id and an API key. Call LangsysApp.init() with both first.`\n );\n }\n return {\n status: false,\n errors: ['Missing projectid or API key in configuration'],\n http: {\n status: 0,\n statusText: 'Configuration Error',\n url: `${this.apiurl}/${path}`,\n data: JSON.stringify(data),\n },\n };\n }\n\n // API calls should not include a leading slash.\n if (path.startsWith('/')) path = path.substring(1);\n\n // Replace [projectid] token with the project id the request sends under.\n if (path.includes('/[projectid]')) {\n path = path.replaceAll('/[projectid]', `/${credentials.projectid}`);\n }\n\n try {\n const querystring =\n method === 'GET'\n ? '?' + new URLSearchParams(data as Record<string, string>).toString()\n : '';\n\n const query = await fetch(`${this.apiurl}/${path}${querystring === '?' ? '' : querystring}`, {\n headers: await this.buildHeaders(credentials),\n method,\n body: method === 'GET' ? undefined : JSON.stringify(data),\n keepalive: opts.keepalive || undefined,\n });\n\n // 204 is a real success shape here — `discovery/hint` always answers\n // 204 with a genuinely empty body and no content-type header at all,\n // so parse on status rather than sniffing for JSON. An unconditional\n // .json() would throw on it.\n const responseData: ResponseObject =\n query.status === 204 || query.headers.get('content-length') === '0'\n ? { status: query.ok }\n : ((await query.json()) as ResponseObject);\n const http: HttpResponse = {\n status: query.status,\n statusText: query.statusText,\n url: query.url,\n data: JSON.stringify(data),\n };\n responseData.http = http;\n\n if (!query.ok) {\n logger.warn('LangsysAppAPI failed to query', responseData);\n return {\n status: false,\n errors: [`HTTP ${query.status}: ${query.statusText}`],\n data: responseData,\n http,\n };\n }\n\n return responseData;\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';\n logger.error('LangsysAppAPI Error:', errorMessage);\n logger.error('Request details:', {\n method,\n url: `${this.apiurl}/${path}`,\n data,\n });\n return {\n status: false,\n errors: ['Error communicating with API Server', errorMessage],\n http: {\n status: 0,\n statusText: 'Network Error',\n url: `${this.apiurl}/${path}`,\n data: JSON.stringify(data),\n },\n };\n }\n }\n}\n\nexport const LangsysAppAPI = new LangsysAppAPIClass();\nexport default LangsysAppAPI;\n","/**\n * Server messages (spec MSG family): the entries a server attaches to its\n * framework's own error response, and how a client finds and renders them.\n *\n * What translation needs is small: the `template` — the framework's own\n * sentence, unfilled, with the field's label written in — and the `params`\n * that fill its `{name}` markers. `message` is the template already filled, the\n * fallback a client shows when it cannot look the template up. Everything else\n * is the framework's and passes through unchanged: `field` in the framework's\n * own path format (a dotted string, Pydantic's `loc` array), and `code`, the\n * framework's own identifier for the failure (Laravel's rule name, Pydantic's\n * error `type`, Django's `code`), or none. The error body is the framework's\n * too, so where the entries sit and what their pieces are called are the\n * app's configuration.\n *\n * Everything here is pure except `renderServerMessage`, which renders through\n * `t()`; that one is exported from the main entry only.\n */\n\n/** One server message entry (MSG-1), in the SDK's own piece names. */\nexport interface ServerMessage {\n template?: string;\n params?: Record<string, unknown>;\n message?: string;\n /** The field, in the framework's own path format, unchanged. */\n field?: unknown;\n /** The framework's own identifier for the failure, unchanged. Absent where the framework has none. */\n code?: unknown;\n}\n\n/** The piece names an app's entries use, where they differ from the SDK's. */\nexport type ServerMessagePieces = Partial<Record<'template' | 'params' | 'message' | 'field' | 'code', string>>;\n\n/** Where the entries sit in a response body (MSG-1). One of `key` or `resolver` is required. */\nexport interface ResolveServerMessagesOptions {\n /**\n * The dotted path the server attached the entries under, beside the\n * framework's own error body — Laravel's package default is `langsys_errors`.\n */\n key?: string;\n /** Maps a body to entries itself, for an app whose failures are carried some other way. */\n resolver?: (body: unknown) => unknown;\n /** The entries' piece names, when the server was configured with names of its own. */\n pieces?: ServerMessagePieces;\n}\n\n/** The category templates are registered and rendered under unless configured otherwise (MSG-6). */\nexport const DEFAULT_SERVER_MESSAGE_CATEGORY = 'Errors';\n\n/**\n * A marker is a lowercase snake_case name in braces (MSG-3). `{Name}`, `{ min }`\n * and `{1x}` are not markers and are never filled. Byte-compatible with the\n * server's grammar: the server fills `message` from the template with it, and a\n * client that disagreed about what a marker is would fill a different sentence.\n */\nconst MARKER = /\\{([a-z][a-z0-9_]*)\\}/g;\n\n/** The marker names in a template, once each, in the order they first appear. */\nexport function templateMarkers(template: string): string[] {\n if (typeof template !== 'string' || template === '') return [];\n const names: string[] = [];\n for (const match of template.matchAll(MARKER)) {\n if (!names.includes(match[1]!)) names.push(match[1]!);\n }\n return names;\n}\n\n/**\n * Fill a template's markers from params (MSG-4). A marker with no param stays\n * as its literal marker rather than going blank, so a missing value is visible\n * instead of producing a sentence that reads as complete. A structure is never\n * printed into the sentence; its marker stays too.\n */\nexport function fillTemplate(template: string, params: Record<string, unknown> = {}): string {\n return String(template).replace(MARKER, (marker, name: string) => {\n if (!Object.prototype.hasOwnProperty.call(params, name)) return marker;\n const value = params[name];\n // `typeof null` is 'object', so null keeps its marker here too.\n if (value === undefined || typeof value === 'object' || typeof value === 'function') return marker;\n return String(value);\n });\n}\n\n/**\n * An entry from its wire form, or null when it is not one. An entry needs a\n * `template` to look up or a `message` to show; either is a string. `params`\n * is kept when it is an object; `field` and `code` pass through as they are.\n */\nexport function toServerMessage(value: unknown, pieces: ServerMessagePieces = {}): ServerMessage | null {\n if (!isRecord(value)) return null;\n const read = (piece: keyof ServerMessagePieces) => value[pieces[piece] ?? piece];\n const template = read('template');\n const message = read('message');\n const params = read('params');\n const field = read('field');\n const code = read('code');\n const hasTemplate = typeof template === 'string';\n const hasMessage = typeof message === 'string';\n if (!hasTemplate && !hasMessage) return null;\n\n return {\n ...(hasTemplate ? { template } : {}),\n ...(isRecord(params) ? { params } : {}),\n ...(hasMessage ? { message } : {}),\n ...(field !== undefined && field !== null && field !== '' ? { field } : {}),\n ...(code !== undefined && code !== null ? { code } : {}),\n };\n}\n\n/**\n * The entries a response carries, found where the app's configuration says\n * they are (MSG-1). The body is the framework's own and is never searched by\n * shape: `key` names the dotted path the server attached the entries under,\n * and `resolver` maps the body to entries itself. Throws when neither is given,\n * since there is nowhere to look. `pieces` renames the entries' pieces.\n *\n * Accepts the decoded body or its JSON text, and never changes the body.\n * Unreadable JSON, or a key the body does not carry, resolves to no entries:\n * this runs in an error path already.\n */\nexport function resolveServerMessages(body: unknown, options: ResolveServerMessagesOptions): ServerMessage[] {\n const { key, resolver, pieces } = options ?? {};\n if (typeof resolver !== 'function' && (typeof key !== 'string' || key === '')) {\n throw new TypeError(\n 'resolveServerMessages needs to know where the entries sit: pass { key } with the path your server attaches them under (Laravel: \"langsys_errors\"), or { resolver }.'\n );\n }\n\n if (typeof body === 'string') {\n try {\n body = JSON.parse(body);\n } catch {\n return [];\n }\n }\n\n const found = typeof resolver === 'function' ? resolver(body) : dig(body, key!);\n return toItems(found)\n .map((item) => toServerMessage(item, pieces))\n .filter((entry): entry is ServerMessage => entry !== null);\n}\n\n/** A list of entries, a single entry, or a field → entries map, as items. */\nfunction toItems(found: unknown): unknown[] {\n if (Array.isArray(found)) return found;\n if (!isRecord(found)) return [];\n const values = Object.values(found);\n return values.every((value) => Array.isArray(value)) && values.length > 0 ? values.flat() : [found];\n}\n\nfunction dig(body: unknown, path: string): unknown {\n let node = body;\n for (const segment of path.split('.')) {\n if (typeof node !== 'object' || node === null || !Object.prototype.hasOwnProperty.call(node, segment)) {\n return undefined;\n }\n node = (node as Record<string, unknown>)[segment];\n }\n return node;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Catalog snapshots (spec SNAP family): one file format every Langsys SDK\n * writes and reads, so a snapshot exported by any core loads in any other.\n *\n * A snapshot is the flat catalog (`GET /translations`) for chosen locales and\n * categories, carried as a file so a first render, a mobile bundle or an\n * offline session has translations with no network call. It is a cache, never\n * a source: Langsys produces it, a checksum over its canonical serialisation\n * catches an edited one, and the refresh path is a new export.\n *\n * Everything here is pure. Seeding a loaded snapshot into the SDK is\n * `LangsysApp.loadSnapshot`, on the main entry.\n */\n\n/** The `format` member every snapshot carries. */\nexport const SNAPSHOT_FORMAT = 'langsys-catalog-snapshot';\n\n/** The only `version` this SDK reads and writes. */\nexport const SNAPSHOT_VERSION = 1;\n\n/** A category's flat entries as `GET /translations` returns them: phrase → translation or null, or a block id → its phrase map. */\nexport type SnapshotCategory = Record<string, string | null | Record<string, string | null>>;\n\n/** locale → category → entries. A category the locale does not hold is absent; one it holds empty is `{}`. */\nexport type SnapshotCatalog = Record<string, Record<string, SnapshotCategory>>;\n\n/** The members the checksum covers. */\nexport interface SnapshotPayload {\n project_id: string;\n /** UTC, `YYYY-MM-DDTHH:MM:SSZ`. */\n generated_at: string;\n base_locale: string;\n /** Lowercase `xx-yy`, sorted ascending. */\n locales: string[];\n /** Sorted ascending. */\n categories: string[];\n catalog: SnapshotCatalog;\n}\n\n/** A whole snapshot document. */\nexport interface CatalogSnapshot extends SnapshotPayload {\n format: typeof SNAPSHOT_FORMAT;\n version: typeof SNAPSHOT_VERSION;\n /** `sha256:` and the lowercase hex digest of the canonical serialisation of the payload. */\n checksum: string;\n}\n\n/** Why a snapshot was refused. */\nexport type SnapshotRefusal = 'not-json' | 'format' | 'version' | 'missing-member' | 'checksum';\n\n/** Thrown when a snapshot cannot be loaded. `reason` names why; the message says what to do. */\nexport class SnapshotError extends Error {\n constructor(\n message: string,\n readonly reason: SnapshotRefusal\n ) {\n super(message);\n this.name = 'SnapshotError';\n }\n}\n\nconst PAYLOAD_MEMBERS = ['project_id', 'generated_at', 'base_locale', 'locales', 'categories', 'catalog'] as const;\n\n/**\n * The canonical serialisation the checksum is taken over, byte for byte the\n * same in every SDK:\n *\n * - strings escaped as CID-1 serialises them — `\"`, `\\` and U+0000–U+001F only,\n * everything else (`/`, non-ASCII, U+2028) raw — which is `JSON.stringify`'s\n * own string escaping;\n * - no whitespace;\n * - object members sorted by key in Unicode code point order. Neither\n * `Object.keys` order (integer-like keys first) nor the default `sort()`\n * (UTF-16 code units, which puts a key above U+FFFF before one in\n * U+E000–U+FFFF) is that order, so both are avoided;\n * - a map is `{}` even when empty; `null` is `null`.\n */\nexport function canonicalSnapshotJson(value: unknown): string {\n if (value === null) return 'null';\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'number' || typeof value === 'boolean') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalSnapshotJson).join(',')}]`;\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).filter((key) => record[key] !== undefined).sort(compareCodePoints);\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalSnapshotJson(record[key])}`).join(',')}}`;\n }\n throw new TypeError(`A snapshot cannot hold a ${typeof value}.`);\n}\n\n/** `sha256:` and the lowercase hex SHA-256 of the canonical serialisation of the payload members. */\nexport function snapshotChecksum(payload: SnapshotPayload): string {\n const hashed: Record<string, unknown> = {};\n for (const member of PAYLOAD_MEMBERS) hashed[member] = payload[member];\n return 'sha256:' + sha256Hex(canonicalSnapshotJson(hashed));\n}\n\n/**\n * Build a snapshot document from catalogs already fetched — the writing half,\n * for an export tool. `catalogs` is locale → the catalog `GET /translations`\n * returned; only the chosen categories are kept, and a category a locale does\n * not hold stays absent for that locale. Locales are lowercased; both lists are\n * sorted.\n */\nexport function buildSnapshot(options: {\n projectId: string;\n baseLocale: string;\n catalogs: Record<string, Record<string, SnapshotCategory>>;\n categories: string[];\n generatedAt?: Date;\n}): CatalogSnapshot {\n const categories = [...new Set(options.categories.map(String))].sort(compareCodePoints);\n const catalog: SnapshotCatalog = {};\n for (const [locale, categoriesForLocale] of Object.entries(options.catalogs)) {\n const kept: Record<string, SnapshotCategory> = {};\n for (const category of categories) {\n if (Object.prototype.hasOwnProperty.call(categoriesForLocale, category)) kept[category] = categoriesForLocale[category]!;\n }\n catalog[locale.toLowerCase()] = kept;\n }\n const payload: SnapshotPayload = {\n project_id: String(options.projectId),\n generated_at: (options.generatedAt ?? new Date()).toISOString().replace(/\\.\\d{3}Z$/, 'Z'),\n base_locale: options.baseLocale.toLowerCase(),\n locales: Object.keys(catalog).sort(compareCodePoints),\n categories,\n catalog,\n };\n return { format: SNAPSHOT_FORMAT, version: SNAPSHOT_VERSION, ...payload, checksum: snapshotChecksum(payload) };\n}\n\n/**\n * Read a snapshot from its JSON text or parsed document, refusing — with an\n * error naming the reason — a different `format`, an unsupported `version`, a\n * missing member, or a checksum the contents no longer match. The file may be\n * any JSON encoding of the document; the checksum is recomputed from the\n * canonical serialisation, never compared against the file's bytes.\n */\nexport function parseSnapshot(input: string | unknown): CatalogSnapshot {\n let document: unknown = input;\n if (typeof input === 'string') {\n try {\n document = JSON.parse(input);\n } catch {\n throw new SnapshotError('This is not a Langsys catalog snapshot: it is not JSON.', 'not-json');\n }\n }\n if (typeof document !== 'object' || document === null || Array.isArray(document)) {\n throw new SnapshotError('This is not a Langsys catalog snapshot: it is not a JSON object.', 'not-json');\n }\n const doc = document as Record<string, unknown>;\n\n if (doc.format !== SNAPSHOT_FORMAT) {\n throw new SnapshotError(`This is not a Langsys catalog snapshot: its format is ${JSON.stringify(doc.format)}, not \"${SNAPSHOT_FORMAT}\".`, 'format');\n }\n if (doc.version !== SNAPSHOT_VERSION) {\n throw new SnapshotError(`This snapshot is version ${JSON.stringify(doc.version)}; this SDK reads version ${SNAPSHOT_VERSION}. Export it again.`, 'version');\n }\n for (const member of [...PAYLOAD_MEMBERS, 'checksum']) {\n if (!Object.prototype.hasOwnProperty.call(doc, member)) {\n throw new SnapshotError(`This snapshot has no \"${member}\". Export it again.`, 'missing-member');\n }\n }\n if (doc.checksum !== snapshotChecksum(doc as unknown as SnapshotPayload)) {\n throw new SnapshotError(\n 'This snapshot was changed after it was exported: its checksum does not match. A snapshot is a cache and is never edited; export it again.',\n 'checksum'\n );\n }\n return doc as unknown as CatalogSnapshot;\n}\n\n/** Compare two strings by Unicode code point, which is UTF-8 byte order. */\nfunction compareCodePoints(a: string, b: string): number {\n const ia = a[Symbol.iterator]();\n const ib = b[Symbol.iterator]();\n for (;;) {\n const ca = ia.next();\n const cb = ib.next();\n if (ca.done || cb.done) return ca.done && cb.done ? 0 : ca.done ? -1 : 1;\n const diff = ca.value.codePointAt(0)! - cb.value.codePointAt(0)!;\n if (diff !== 0) return diff;\n }\n}\n\n/**\n * SHA-256 of a string's UTF-8 bytes, synchronously. Loading a snapshot is\n * synchronous by contract (SNAP-2) and the platform's digest is async, so the\n * hash is computed here — FIPS 180-4, no dependency.\n */\nexport function sha256Hex(text: string): string {\n const bytes = new TextEncoder().encode(text);\n const length = bytes.length;\n const blocks = Math.ceil((length + 9) / 64);\n const words = new Uint32Array(blocks * 16);\n for (let i = 0; i < length; i++) words[i >> 2]! |= bytes[i]! << (24 - (i % 4) * 8);\n words[length >> 2]! |= 0x80 << (24 - (length % 4) * 8);\n // The bit length, as a 64-bit big-endian integer in the last two words.\n words[words.length - 2] = Math.floor((length * 8) / 0x100000000);\n words[words.length - 1] = (length * 8) >>> 0;\n\n const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const w = new Uint32Array(64);\n for (let block = 0; block < words.length; block += 16) {\n for (let t = 0; t < 16; t++) w[t] = words[block + t]!;\n for (let t = 16; t < 64; t++) {\n const s0 = rotr(w[t - 15]!, 7) ^ rotr(w[t - 15]!, 18) ^ (w[t - 15]! >>> 3);\n const s1 = rotr(w[t - 2]!, 17) ^ rotr(w[t - 2]!, 19) ^ (w[t - 2]! >>> 10);\n w[t] = (w[t - 16]! + s0 + w[t - 7]! + s1) >>> 0;\n }\n let [a, b, c, d, e, f, g, hh] = [h[0]!, h[1]!, h[2]!, h[3]!, h[4]!, h[5]!, h[6]!, h[7]!];\n for (let t = 0; t < 64; t++) {\n const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t]! + w[t]!) >>> 0;\n const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;\n hh = g;\n g = f;\n f = e;\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) >>> 0;\n }\n h[0] = (h[0]! + a) >>> 0;\n h[1] = (h[1]! + b) >>> 0;\n h[2] = (h[2]! + c) >>> 0;\n h[3] = (h[3]! + d) >>> 0;\n h[4] = (h[4]! + e) >>> 0;\n h[5] = (h[5]! + f) >>> 0;\n h[6] = (h[6]! + g) >>> 0;\n h[7] = (h[7]! + hh) >>> 0;\n }\n return Array.from(h, (word) => word.toString(16).padStart(8, '0')).join('');\n}\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits));\n}\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n","import { LangsysAppAPI } from './api.js';\nimport { logger } from './logger.js';\nimport { autoDiscovery, sTranslations, writeEnabled } from './stores.js';\n\n/**\n * Content-discovery hint lane.\n *\n * A public API key shipped in browser JS is extractable, so public keys are\n * read-only and the server decides per session whether writing is allowed. A\n * read-only session that finds unregistered content therefore can't register\n * it — instead it tells the server *where* to look, and our discovery renderer\n * loads that URL from an allow-listed IP where the very same SDK code path is\n * write-enabled and registers what it finds.\n *\n * The two lanes are mutually exclusive, and that is the loop-prevention\n * mechanism rather than a suppression flag: a write-enabled session registers\n * and structurally cannot hint, so the renderer can never hint at itself.\n *\n * Hints carry a URL and nothing else — never a phrase payload. Anonymous\n * callers can say \"look here\", never \"store this\".\n *\n * Everything here is browser-only. Under SSR there is no `window` and no\n * `sessionStorage`, and a server render would fire hints from the origin\n * server's single IP — concentrating the herd this module exists to disperse.\n */\n\n/** Jitter bounds. Spreads arrival in time so a hot page can't spike the rate limiter. */\nconst HINT_MIN_DELAY_MS = 5_000;\nexport const HINT_MAX_DELAY_MS = 30_000;\n\n/**\n * Per-URL cap on remembered misses. These are only ever read locally, for the\n * opportunistic recheck below — they are never sent — so a bound costs nothing\n * and keeps a long-lived SPA session from growing without limit.\n */\nconst MAX_TRACKED_MISSES_PER_URL = 200;\n\nconst SESSION_KEY_PREFIX = 'langsys:hinted:';\n\ninterface TrackedMiss {\n category: string;\n phrase: string;\n}\n\ninterface PendingHint {\n /** URL captured when the FIRST miss for this page was recorded. */\n url: string;\n misses: TrackedMiss[];\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Keyed by captured URL, NOT one global queue. A client-side router swaps\n * routes without remounting the app or resetting module state, so one process\n * accumulates misses across many routes; batching them into a single hint would\n * attribute every one of them to whichever URL happened to be current.\n */\nconst pending = new Map<string, PendingHint>();\n\n/** Set on 429 — the server is asking us to stop, so we stop for the session. */\nlet hintsDisabledForSession = false;\n\n/** `sessionStorage` throws on ACCESS in Safari private mode and sandboxed iframes. */\nfunction getSafeSessionStorage(): Storage | null {\n if (typeof window === 'undefined') return null;\n try {\n const s = window.sessionStorage;\n s.getItem('__langsys_probe__');\n return s;\n } catch {\n return null;\n }\n}\n\nfunction alreadyHinted(url: string): boolean {\n const storage = getSafeSessionStorage();\n if (!storage) return false;\n try {\n return storage.getItem(SESSION_KEY_PREFIX + url) !== null;\n } catch {\n return false;\n }\n}\n\nfunction markHinted(url: string): void {\n const storage = getSafeSessionStorage();\n if (!storage) return;\n try {\n storage.setItem(SESSION_KEY_PREFIX + url, '1');\n } catch {\n // Quota or a hostile storage implementation — worst case we hint twice.\n }\n}\n\n/**\n * Canonical form for the hint URL and for the per-session dedup key.\n *\n * Without this, one campaign-tagged share link becomes N distinct URLs and\n * defeats both our per-session dedup and the server's per-URL dedup. The\n * server normalizes authoritatively too — it has to, since it can't stop an\n * old SDK build from sending raw hrefs.\n *\n * This tracking list matches `HintUrl::normalize()`, and must keep matching it.\n * NORMALIZATION is the half that has to be identical on every leg: its output\n * IS the dedup key and the renderer's target, so divergence there hands the\n * renderer a URL the page never had, or splits one page across two keys.\n *\n * The credential rule below is the other half, and it obeys a DIFFERENT\n * contract. It is a boolean gate on an unmodified URL — a URL that passes is\n * byte-identical whatever matched, so the legs cannot disagree about bytes,\n * only about which of them declines. That makes the effective guard the UNION\n * of every leg's predicate, and makes STRICTER SAFE: a leg that declines more\n * loses discovery on those pages and corrupts nothing. Do not carry\n * \"never stricter\" across from normalization to here. It would forbid the\n * server from covering a case the SDK misses, which is precisely the\n * protection that matters most — an SDK build already deployed will never\n * update, and the server is the only leg standing in front of it.\n */\n/**\n * Every `utm_*` param, matched by prefix rather than enumerated. An enumerated\n * list kept missing ones that exist in the wild (`utm_id`,\n * `utm_source_platform`, `utm_creative_format`), and each miss fragments the\n * dedup window into one render per campaign variant — silent, and paid per\n * link. Mirrors the server's `TRACKING_PREFIX`.\n */\nconst TRACKING_PREFIX = 'utm_';\n\nconst TRACKING_PARAMS = new Set([\n 'gclid',\n 'fbclid',\n 'msclkid',\n 'mc_cid',\n 'mc_eid',\n 'ref',\n 'ref_src',\n]);\n\n/**\n * Query parameters that must never leave the browser in a report.\n *\n * This is a stronger requirement than the tracking denylist above, and for a\n * different reason. A reported URL is not merely *stored* — the discovery\n * renderer **visits it**. So a capability in a query string is not a privacy\n * leak, it is a replay: a magic-link or single-use token would be exercised by\n * our own infrastructure, potentially consuming it before the user clicks, or\n * causing the renderer to load a page as that user.\n *\n * It is also persisted: the server stores the URL it was sent, so a token that\n * survives this function lands in a database in plaintext.\n *\n * Matched as substrings because the risky names are endlessly re-spelled\n * (`token`, `access_token`, `csrfToken`), against a name with `-` and `_`\n * removed so every spelling of one word collapses onto one entry. Without that\n * normalization `api_key` matched while `api-key` and `x-api-key` sailed\n * through — the two commonest real spellings of the exact thing this list\n * exists to catch.\n *\n * A match drops the WHOLE report rather than the param; see `normalizeHintUrl`.\n * Because a matching param is therefore never transmitted, over-inclusion costs\n * one page's discovery instead of leaking a credential — the cheap direction to\n * be wrong in, on a denylist that is incomplete by construction.\n */\nconst SENSITIVE_PARAM_FRAGMENTS = [\n 'token',\n 'secret',\n 'password',\n 'passwd',\n 'apikey',\n 'authoriz',\n 'session',\n 'signature',\n 'credential',\n 'email',\n 'oauth',\n 'authcode',\n 'accesscode',\n];\n\n/**\n * Short words that are credentials on their own but appear inside ordinary\n * routing params, so they are matched WHOLE rather than as substrings: `sig`\n * is a signature while `design` is not, `auth` is a credential while `author`\n * is a blog filter.\n *\n * `key` and `code` are deliberately NOT here, and were removed after being\n * here. Both are ordinary selectors on exactly the content-bearing pages\n * discovery exists to find — `?key=pricing` picks a tab, `?code=US` a country,\n * `?code=SAVE20` a coupon — so treating them as credentials made those pages\n * permanently undiscoverable while every status still reported success. The\n * OAuth authorization code stays covered by co-occurrence instead of by name;\n * see `OAUTH_STATE_MARKERS`.\n */\nconst SENSITIVE_PARAM_EXACT = new Set(['sig', 'auth', 'otp', 'nonce']);\n\n/**\n * `code` is the OAuth authorization code only when an OAuth state parameter\n * rides along with it; alone it is a route. Requiring the pair covers the real\n * callback without destroying `?code=US`.\n */\nconst OAUTH_STATE_MARKERS = new Set(['state', 'sessionstate']);\n\n/**\n * Separator-insensitive param name: `api-key`, `api_key` and `apiKey` all\n * become `apikey`. Checked against the routing names this list must leave\n * alone — `country_code` becomes `countrycode`, matching neither an exact\n * entry nor a fragment, and `product_code`/`postcode` likewise.\n */\nfunction normalizeParamName(key: string): string {\n return key.toLowerCase().replace(/[-_]/g, '');\n}\n\n/**\n * Query-style parameter names carried in the FRAGMENT, which `searchParams`\n * cannot see. Two real shapes hide credentials there:\n *\n * - `#/callback?code=x&state=y` — a hash-router route with a query tail.\n * - `#access_token=xyz&token_type=bearer` — the OAuth implicit flow, which\n * has no `?` at all. A parser that only looks after a `?` misses this one\n * silently, so the whole fragment is treated as the pair list when no `?`\n * is present.\n *\n * A segment without `=` is not a pair and is ignored — otherwise `#/pricing`,\n * `#section` and an anchor like `#contact-email` would be read as parameter\n * names, and the last of those would decline a perfectly ordinary page for a\n * value that does not exist.\n */\nfunction fragmentParamNames(hash: string): string[] {\n const body = hash.startsWith('#') ? hash.slice(1) : hash;\n if (!body) return [];\n\n const q = body.indexOf('?');\n const pairs = q >= 0 ? body.slice(q + 1) : body;\n\n const names: string[] = [];\n for (const pair of pairs.split('&')) {\n const eq = pair.indexOf('=');\n if (eq <= 0) continue;\n const raw = pair.slice(0, eq);\n try {\n names.push(decodeURIComponent(raw));\n } catch {\n names.push(raw);\n }\n }\n return names;\n}\n\nfunction isSensitiveParam(normalized: string): boolean {\n if (SENSITIVE_PARAM_EXACT.has(normalized)) return true;\n return SENSITIVE_PARAM_FRAGMENTS.some((f) => normalized.includes(f));\n}\n\nexport function normalizeHintUrl(href: string): string | null {\n try {\n const url = new URL(href);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;\n\n url.protocol = url.protocol.toLowerCase();\n url.hostname = url.hostname.toLowerCase();\n\n // A credential-shaped param declines the WHOLE report rather than being\n // stripped from it. Stripping produces a URL that is no longer the page\n // the miss came from: the renderer visits a different page and registers\n // what it finds there, and pages distinguished only by that param\n // collapse onto one dedup key — both silently, with every status\n // reporting success. Declining is the honest failure. The page goes\n // undiscovered, and nothing wrong is registered in its name.\n //\n // Considered and rejected: redacting the value (a page's\n // distinguishability by a param IS that param's value, so it cannot be\n // hidden and preserved at once) and hashing it (identical wrong-render\n // for route params, unbounded hint cardinality for the per-user\n // credentials that actually match here, and a byte-exact cross-language\n // hashing contract to maintain forever). Declining needs no agreement\n // between the legs at all — each independently arrives at \"no report\".\n //\n // Runs BEFORE any mutation below, so no path can return a URL that was\n // partially stripped on the way to being declined.\n //\n // The fragment half looks redundant on this leg and is not: the\n // normalization below already drops `#access_token=…`, so a reader may\n // conclude the browser cannot leak it and delete this check. On the\n // SERVER leg the same check is the only protection there is — the raw\n // URL reaches persistence before normalization — so deleting it here\n // unmirrors the legs and leaves the rule resting on one implementation.\n const queryNames = [...url.searchParams.keys()];\n const names = [...queryNames, ...fragmentParamNames(url.hash)];\n // Everything at or past this index came out of the fragment.\n const firstFragmentIndex = queryNames.length;\n const normalized = names.map((name) => normalizeParamName(name));\n const isOAuthCallback =\n normalized.includes('code') && normalized.some((n) => OAUTH_STATE_MARKERS.has(n));\n\n for (const [i, n] of normalized.entries()) {\n if (isSensitiveParam(n) || (isOAuthCallback && n === 'code')) {\n // Local only, and the param NAME as the page actually spells it\n // — never its value. Nothing leaves the browser. Declining in\n // silence would be undiscoverable by construction: a developer\n // looking at the one page that never gets translated has no way\n // to find out why. This is the only answer they can get.\n // Naming WHERE it was found, not just what: a developer told\n // \"query parameter access_token\" while looking at a URL whose\n // query string is empty learns to distrust the notice, and the\n // fragment is the half they are least likely to check.\n const where = i >= firstFragmentIndex ? 'fragment' : 'query string';\n logger.log(\n `Discovery hint declined: the page URL carries a credential-shaped parameter (\"${names[i] ?? n}\") in its ${where}, so this page is not reported for translation. Remove the parameter from the URL if it is not a credential, or expect this page to need translating by hand.`,\n );\n return null;\n }\n }\n\n // Fragment-vs-route, not hash-vs-no-hash. `#pricing` is an anchor into\n // the current page and carries no routing information. `#/pricing` is\n // the entire route under HashRouter / Vue hash mode / Angular useHash —\n // stripping it collapses every route in such an app onto one key, so\n // per-session dedup would fire once for the whole application and the\n // single hint would point at the bare origin.\n //\n // `#!/…` is the older hashbang spelling (Angular 1, Vue hash mode) and\n // is equally load-bearing. Bare `#`, `#/` and `#!/` carry no route, so\n // they're dropped — keeping them would make `example.com/#/` a\n // different dedup key from `example.com/` for the same page. The\n // renderer applies the same rule on its side.\n if (!/^#!?\\/.+/.test(url.hash)) url.hash = '';\n\n for (const key of queryNames) {\n const k = key.toLowerCase();\n if (k.startsWith(TRACKING_PREFIX) || TRACKING_PARAMS.has(k)) {\n url.searchParams.delete(key);\n }\n }\n // Stable ordering so ?a=1&b=2 and ?b=2&a=1 dedup to one key.\n url.searchParams.sort();\n\n return url.toString();\n } catch {\n return null;\n }\n}\n\n/** Key-presence test. `in` walks the prototype chain — `'toString' in {}` is true. */\nfunction isKnownPhrase(category: string, phrase: string): boolean {\n const bucket = sTranslations.get()[category || '__uncategorized__'];\n return !!bucket && Object.prototype.hasOwnProperty.call(bucket, phrase);\n}\n\n/**\n * Note a catalog miss for the page currently being viewed.\n *\n * Safe to call on every miss: it captures the URL, dedups per session, and\n * decides nothing. The lane choice happens when the timer fires.\n */\nexport function recordMissForDiscovery(category: string, phrase: string): void {\n // Covers RSC render, static generation at build time, and ISR revalidation\n // in one bail — none of which have a client seam to guard instead.\n if (typeof window === 'undefined') return;\n if (hintsDisabledForSession) return;\n\n // Captured HERE, at miss time — never read at fire time. A client-side\n // route change does not remount the app or reset this module, and the\n // jitter window is 5-30s, so reading `location` when the timer fires would\n // routinely report the page the user navigated TO rather than the page that\n // produced the miss. The renderer would then load a URL that doesn't\n // contain the content, find nothing, and the loop would silently no-op.\n // Optional-chained deliberately: this runs inside every `t()` miss, so an\n // unusual environment shape (a partial `window` in a test harness or an\n // embedded runtime) must degrade to \"no hint\" rather than throw out of the\n // caller's render.\n const href = window.location?.href;\n if (!href) return;\n const url = normalizeHintUrl(href);\n if (!url) return;\n\n if (alreadyHinted(url)) return;\n\n const existing = pending.get(url);\n if (existing) {\n if (\n existing.misses.length < MAX_TRACKED_MISSES_PER_URL &&\n !existing.misses.some((m) => m.category === category && m.phrase === phrase)\n ) {\n existing.misses.push({ category, phrase });\n }\n return;\n }\n\n const delay = HINT_MIN_DELAY_MS + Math.random() * (HINT_MAX_DELAY_MS - HINT_MIN_DELAY_MS);\n const entry: PendingHint = {\n url,\n misses: [{ category, phrase }],\n timer: setTimeout(() => void flushHint(url), delay),\n };\n // Never keep a Node event loop alive for a hint (jsdom/test runners).\n (entry.timer as unknown as { unref?: () => void }).unref?.();\n pending.set(url, entry);\n}\n\nasync function flushHint(url: string): Promise<void> {\n const entry = pending.get(url);\n if (!entry) return;\n pending.delete(url);\n\n if (hintsDisabledForSession) return;\n\n // Mutual exclusion with the write lane. `true` means this session registers\n // its own misses and must never hint; `undefined` means authorization never\n // resolved, and hinting on an unknown state would report pages on behalf of\n // a session that may well have been write-enabled. Drop — a later miss\n // re-records once the state is known.\n if (writeEnabled.get() !== false) return;\n\n // Policy check, at the SEND site rather than the record site. Deliberate:\n // every producer feeding this lane — `t()` misses and unregistered content\n // blocks — passes through here, so one decision point covers all of them\n // and the next producer added doesn't have to remember. Evaluating it at\n // record time instead would also make \"false until known\" unsafe, silently\n // dropping early misses for keys that DO permit reporting.\n //\n // Independent of writeEnabled: the canonical public site is read-only AND\n // permitted to report, so these are two questions, never one.\n if (autoDiscovery.get() !== true) {\n // Debug level, not a warning. The severity tracks who chose the\n // condition, and this one was chosen deliberately by the person who\n // would receive the warning — so warning every session trains exactly\n // the wrong person to ignore warnings. The integrator is a different\n // audience, which is why the line exists at all: invisible by default,\n // reachable when someone goes looking. It says WHY rather than what,\n // so that search terminates at the answer instead of another question.\n logger.log('Discovery reporting is not permitted for this API key (auto_discovery disabled) — not sending');\n return;\n }\n\n // Opportunistic only: if a newer catalog happened to arrive during the\n // jitter (locale change, app-initiated refresh), everything we saw may now\n // be registered and the hint is pointless. We deliberately do NOT fetch in\n // order to check — a catalog GET runs the best-translations procedure over\n // the whole project, which is orders of magnitude more expensive than the\n // 204 it would be trying to avoid. Server-side dedup already collapses the\n // herd; this is a free win when it happens and nothing when it doesn't.\n if (entry.misses.every((m) => isKnownPhrase(m.category, m.phrase))) {\n markHinted(url);\n return;\n }\n\n // Fire-and-forget by design: one hint per URL per session, no retry, no\n // backoff, and no record of the outcome. Content that structurally can't be\n // discovered by a render — bare `t()` in a Server Component, which produces\n // inert HTML with no marker and no client-side call — must not be able to\n // generate a growing failure state here.\n markHinted(url);\n\n try {\n // The page's report, under the page's key, though its timer may run in a scope's async context (SRV-2).\n const response = await LangsysAppAPI.postDiscoveryHint(url, { credentials: LangsysAppAPI.moduleCredentials() });\n if (response.http?.status === 429) {\n hintsDisabledForSession = true;\n for (const stale of pending.values()) clearTimeout(stale.timer);\n pending.clear();\n logger.log('Discovery hints rate-limited; disabled for this session');\n }\n } catch (err) {\n // Inside a timer callback there is no caller to reject to — an\n // unhandled rejection here would surface in the customer's app.\n logger.warn('Discovery hint failed', err);\n }\n}\n\n/** Test/teardown hook — drops pending timers and re-enables hinting. */\nexport function _resetDiscoveryState(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n hintsDisabledForSession = false;\n}\n","import { md5, md5Legacy } from './utils.js';\n\n/**\n * The IDENTITY CONTRACT — everything that decides a `custom_id`, with no DOM\n * and no module-scope side effects, so it can be imported from a server, a\n * worker or a build script.\n *\n * It lives apart from `content-block.ts` because that module reaches the API\n * client, the discovery lane and the persisted stores; importing it to hash a\n * string pulled a network client and a storage probe along. `langsys-js-server`\n * was sed-extracting these functions out of a published tarball under\n * `@ts-nocheck` for exactly that reason — a copy that silently predates every\n * id rule changed since. Re-exported by `content-block.ts`, so nothing that\n * already imports from there needs to move.\n *\n * Reachable as the `langsys-js-typescript/pure` subpath. Nothing here may touch\n * `window`, `document`, `navigator` or storage, at import time or on any call\n * path — `tests/pure-subpath.test.ts` enforces that under a trapping global.\n */\n\n/**\n * HTML attributes whose values should be harvested for translation.\n *\n * THE LIST IS NOW IDENTICAL TO `langsys-php`'s, all twenty-seven, in its order.\n *\n * It used to be a subset of fifteen, and this docstring used to argue that the\n * framework-convention attributes (Bootstrap `data-bs-*`, Rails `data-confirm`)\n * were deliberately not mirrored because a JS app renders those strings through\n * its own components. That reasoning is superseded and was left standing beside\n * the list that contradicted it — the twelve below are exactly the attributes it\n * said would never appear here.\n *\n * The reason it was wrong: on an SSR handoff the two SDKs tokenize the SAME\n * markup, so an attribute only one side harvests produces a different token\n * array and therefore a different `custom_id` for identical content. That is not\n * a coverage hole to be argued about, it is a split identity.\n *\n * ORDER IS IDENTITY. `custom_id` hashes the token array, and where an element\n * carries several of these the list order decides the sequence. The same set in\n * a different order agrees on every single-attribute element and diverges on\n * exactly the ones nobody notices, so the twelve are APPENDED — inserting would\n * have re-keyed every block using one of the original fifteen.\n */\nexport const TRANSLATABLE_ATTRIBUTES = [\n 'placeholder',\n 'alt',\n 'title',\n 'label', // <option>, <optgroup>, <track> — the text a user reads in the picker\n 'aria-label',\n 'aria-placeholder',\n 'aria-description',\n 'aria-valuetext', // the spoken value of a slider/meter\n 'aria-roledescription',\n 'data-error',\n 'data-error-message',\n 'data-validation-message',\n 'data-invalid-message',\n 'data-required-message',\n 'data-pattern-message',\n // The 12 below converge on langsys-php's list, verified against\n // `src/Html/HtmlParser.php` rather than taken on report. ORDER IS IDENTITY:\n // `custom_id` hashes the token array, so these must stay appended in PHP's\n // order — reordering them silently re-keys every block using one.\n 'data-confirm', // Rails-style confirmation dialogs\n 'data-tooltip',\n 'data-title',\n 'data-content',\n 'data-original-title', // Bootstrap 4 tooltip/popover\n 'data-bs-title', // Bootstrap 5\n 'data-bs-content',\n 'data-loading-text',\n 'data-success-message',\n 'data-warning-message',\n 'data-empty-message',\n 'data-placeholder', // editors that shadow the native attribute\n];\n\n/**\n * Elements holding code, inert content, or content no implementation can agree\n * on. Measured before this existed: `<style>.plan{color:#fff}</style>`\n * registered `.plan{color:#fff}` as a translatable phrase, and\n * `<script>window.dataLayer.push(1)</script>` registered the statement. Both\n * were then sent for machine translation.\n *\n * `<noscript>` IS HERE ON A REVERSAL, and the reasoning is worth keeping because\n * the obvious answer is the wrong one. An earlier reading excluded it from this\n * list: its text renders to a real visitor whenever scripting is off, so\n * skipping it would leave a visitor-visible sentence permanently untranslated.\n * That premise is true, and it does not survive two questions.\n *\n * - WHO COULD TRANSLATE IT. With scripting off, a browser SDK is not running,\n * so it can translate nothing on that page — including this.\n * - WHAT THE TOKEN ACTUALLY IS. With scripting ENABLED, the spec's default, a\n * parser makes a `noscript` body RAW TEXT rather than markup. Chromium and\n * parse5 both yield the single token `<p>Enable JavaScript</p>`. Registering\n * that sends MARKUP to machine translation, which is this family's own\n * failure mode arriving through the rule meant to prevent it.\n *\n * And the implementations could not be made to agree cheaply. The axis is the\n * parser's scripting flag, not browser-versus-server: Chromium and parse5 agree\n * because parse5 defaults to scripting enabled, while PHP's libxml2 has no such\n * flag and parses the children as elements. `happy-dom` and `jsdom` behave like\n * libxml2, so a lane measuring in a test environment reproduces a\n * browser-versus-server split that does not exist.\n *\n * `<template>` is named as intent and is NOT a vector HERE: its content lives on\n * `HTMLTemplateElement.content`, so a walker over `childNodes` never reaches it\n * and omitting it from this list changes nothing in a DOM or in parse5 — two\n * lanes measured that independently. It is load-bearing elsewhere, which is why\n * it stays named: libxml2 puts `<template>` children in the ordinary tree, so a\n * PHP or Ruby walker that omitted it registers the template's text, and Ruby\n * measured exactly that leak. 8.0.1 states the split rather than calling the\n * exclusion free.\n *\n * `<math>` is notation, not prose. Translating a variable name or an operator\n * corrupts the expression instead of localising it, and before this exclusion\n * `<p>Area <math><mi>x</mi><mo>+</mo><mn>2</mn></math> units</p>` tokenized to\n * `['Area','x','+','2','units']` — the operator and the bare variable registered\n * as translatable phrases and sent for machine translation. Added by spec 8.0.1\n * after v8 shipped without it.\n *\n * `<svg>` IS DELIBERATELY ABSENT and must stay absent. It is the exclusion people\n * expect that is wrong: an `<svg><text>` renders visible words to a reader, so its\n * text is translated like any other. 8.0.1 states that behaviourally because the\n * structural reading — \"walk `<svg>` as a block\" — regressed the commonest markup\n * there is when PHP implemented it: treating svg as a block dropped the PARENT's\n * direct text, so `<p>Click <svg><path/></svg> to continue</p>` registered nothing\n * and every icon-bearing heading, link and list item lost its words. Adding `svg`\n * here would reproduce that, which is what `tokenizer-convergence` now pins.\n */\nexport const NON_TRANSLATABLE_ELEMENTS = ['script', 'style', 'template', 'noscript', 'math'];\n\n/**\n * True when an element opts out of translation entirely — it and its subtree\n * are skipped by the tokenizer.\n *\n * Mirrors `langsys-php`'s `HtmlParser::isTranslationExcluded()` exactly:\n * - `translate=\"no\"` — the HTML standard attribute, matched case-insensitively.\n * - `data-notrans` — PHP's author-facing alias, for hosts whose templating\n * strips unknown bare attributes or where `translate` collides with another\n * tool. Presence is intent; an explicit `\"false\"`/`\"0\"` opts out of the\n * opt-out, compared after trimming.\n *\n * Honoring PHP's alias matters for the same reason as the phrase marker: on SSR\n * handoff there is ONE DOM, and content an author marked \"do not translate\"\n * must not be extracted and registered by whichever SDK happens to walk it.\n *\n * Both this and `isPhraseMarked` trim before comparing. They briefly differed\n * — PHP's phrase check predated the trim its exclusion check gained — and the\n * gap was resolved by asking rather than tidying: mirror exactly, flag the\n * wart, let the owner decide. Divergence-by-tidying is the same failure class\n * as divergence-by-oversight, just better intentioned.\n */\nexport function isTranslationExcluded(element: AttributeReader): boolean {\n if ((element.getAttribute('translate') ?? '').toLowerCase() === 'no') return true;\n if (!element.hasAttribute('data-notrans')) return false;\n const value = (element.getAttribute('data-notrans') ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n}\n\n/** The element shape the exclusion reads: the DOM's, or a tree view's. */\nexport interface AttributeReader {\n readonly tagName: string;\n getAttribute(name: string): string | null;\n hasAttribute(name: string): boolean;\n}\n\n/**\n * Whether an element is opaque in a rich phrase (TOK-1): an author's own exclusion,\n * or code and notation. It is one markup pair with nothing between, `{mNo}{mNc}`,\n * whatever it holds, so no text or value inside it enters the phrase, and it renders\n * its source content as given.\n */\nexport function isOpaqueInPhrase(element: AttributeReader): boolean {\n return isTranslationExcluded(element) || NON_TRANSLATABLE_ELEMENTS.includes(element.tagName.toLowerCase());\n}\n\n/**\n * THE definition. `phrase.ts` re-exports this rather than restating it — the\n * literal used to appear in both files, so renaming one side left the other\n * silently stale: the tokenizer would stop recognising the marker `Phrase`\n * emits and would re-tokenize a subtree that manages itself.\n */\nexport const PHRASE_MARKER_ATTR = 'data-ls-phrase';\n\n/** PHP's spelling. Recognised so a catalog shared with langsys-php round-trips. */\nexport const PHRASE_MARKER_ATTR_LEGACY = 'data-langsys-phrase';\n\nexport const PHRASE_MARKER_ATTRS = [PHRASE_MARKER_ATTR, PHRASE_MARKER_ATTR_LEGACY] as const;\n\n/**\n * Marker the `Translate` host element carries, holding the resolved\n * `custom_id` of the block rendered inside it.\n *\n * Mirrors how a `Phrase` host carries `PHRASE_MARKER_ATTR`, and exists so a\n * server-rendered page can be read back: the id is otherwise derivable only by\n * re-running the tokenizer over the same subtree, which a reader that only has\n * the HTML cannot do identically.\n */\nexport const CONTENT_BLOCK_MARKER_ATTR = 'data-ls-contentblock';\n\n/** PHP's spelling, accepted on read for the same reason the phrase marker's is. */\nexport const CONTENT_BLOCK_MARKER_ATTR_LEGACY = 'data-langsys-contentblock';\n\nexport const CONTENT_BLOCK_MARKER_ATTRS = [\n CONTENT_BLOCK_MARKER_ATTR,\n CONTENT_BLOCK_MARKER_ATTR_LEGACY,\n] as const;\n\n/**\n * A producer's statement that text inside this element is ALREADY RESOLVED: rendered by\n * a server SDK in the visitor's language, not authored as source. A reader records no\n * miss for it — neither a registration nor a discovery hint — because the catalog is\n * keyed by source text and this is a translation.\n *\n * Distinct from the identity markers on purpose, and agreed that way with the PHP and\n * Laravel lanes. A MARK stamp answers \"which block is this\", and a stamped block inside a\n * resolved scope keeps its id and still translates on a later render; this attribute says\n * only \"never treated as source\". It is also not `translate=\"no\"`, which tells a browser\n * not to machine-translate and would block a legitimate later render.\n *\n * The value is the locale it was resolved into, canonical lowercase, and is informational:\n * presence decides. A bare attribute means the same, because a binding writing it into a\n * layout often does not know the locale at that point. `=\"false\"` and `=\"0\"` opt a subtree\n * back out, the convention `isPhraseMarked` already uses in both SDKs; `=\"no\"` and\n * `=\"off\"` are NOT opt-outs under that shared rule.\n */\nexport const RESOLVED_MARKER_ATTR = 'data-ls-resolved';\n\n/** PHP's spelling, accepted on read for the same reason the other markers' is (MARK-2). */\nexport const RESOLVED_MARKER_ATTR_LEGACY = 'data-langsys-resolved';\n\nexport const RESOLVED_MARKER_ATTRS = [RESOLVED_MARKER_ATTR, RESOLVED_MARKER_ATTR_LEGACY] as const;\n\n/**\n * Canonical form of one token's text, applied identically to a TEXT NODE and to\n * an ATTRIBUTE VALUE.\n *\n * It used to differ: text nodes collapsed internal whitespace while attributes\n * were only trimmed. So the same authored sentence produced two different ids\n * depending on where it sat —\n *\n * <p>A long\\n description</p> -> \"A long description\"\n * <img alt=\"A long\\n description\"> -> \"A long\\n description\"\n *\n * — which also put this SDK and `langsys-php` on different ids for the same\n * markup. One function now, used by both, so \"the same content yields the same\n * id\" is true by construction rather than by two call sites agreeing.\n *\n * `\\s` in JavaScript already covers U+00A0, so a non-breaking space collapses\n * like any other whitespace without special handling. The C0 controls are\n * removed first (`stripC0Controls`), so VT and FF never reach the collapse.\n */\nexport function normalizeTokenText(value: string): string {\n return stripC0Controls(value).replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Remove the 28 C0 control characters TOK-2 deletes before anything collapses:\n * U+0001–U+0008, U+000B, U+000C and U+000E–U+001F. Applied to every string that becomes an\n * id input or a catalog key — text nodes, translatable attributes, `t()` keys — on register\n * and on lookup alike, and first: strip, then collapse, then trim.\n *\n * Removed rather than mapped to a space, because that is the only treatment every parser can\n * agree with: libxml2 before 2.14 deletes these from DOM text before any SDK code runs, while\n * libxml2 2.14+, parse5 and happy-dom keep them. So VT and FF, which are also in the collapse\n * set, are deleted here before the collapse can see them: `a` VT `b` is `ab`, not `a b`.\n *\n * TAB, LF and CR are not in the set; they reach the collapse and become one space. NUL, U+007F\n * and the C1 range, U+0085 included, are kept.\n */\nexport function stripC0Controls(value: string): string {\n return value.replace(/[\\u0001-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '');\n}\n\n/**\n * Normalize `%name%` markup placeholders to canonical `{name}`.\n *\n * Framework compilers consume bare `{name}` written in markup before the DOM\n * walker ever sees it (Svelte compiles it to an expression; JSX evaluates it),\n * so DOM content accepts `%name%` as a collision-free authoring escape.\n * Normalization runs at every markup capture boundary (content-block\n * tokenizer, `Translate` original-value snapshots, `Phrase` encoding), so the\n * catalog, the wire, and translators only ever see the canonical `{name}`\n * form — and plain `{name}` keeps working for vanilla-HTML authors.\n *\n * Keys must be identifiers (`[A-Za-z_][A-Za-z0-9_]*`), so literal `%` in\n * prose (\"20% off\", \"50% to 60%\") can't match. `t()` phrases are JS strings\n * with no compiler collision and stay `{name}`-only.\n *\n * It lives HERE, beside `normalizeTokenText`, because it decides a stored key:\n * every capture boundary runs it, so the same authored content must pass through\n * the same rewrite in every SDK or the key splits. It was in `interpolate.ts`,\n * which is where the RENDER-time counterpart belongs, and where its docstring\n * had drifted onto `adoptPercentPlaceholders` — two functions with one doc\n * between them. `interpolate.ts` re-exports it, so no importer moves.\n */\nexport function normalizeMarkupPlaceholders(text: string): string {\n return text.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, '{$1}');\n}\n\n/**\n * Compute the deterministic content-block id from a `(category, tokens)` pair.\n *\n * JSON-stringifies the tuple so each token is unambiguously delimited\n * (the previous `tokens.join('-')` was collision-prone for tokens\n * containing a hyphen, e.g. `'e-mail'`).\n *\n * Pure function — same inputs always produce the same id. Exported so\n * framework wrappers can compute the id themselves before deciding\n * whether to call `registerContentBlock`.\n */\nexport function generateCustomId(category: string, tokens: string[]): string {\n // Coalesce at runtime, not just in the type. This is public API, so an\n // untyped or plain-JS caller can pass `undefined` — which serializes to\n // `[null, …]` and yields an id no wire path ever stores. Every shipping\n // caller already coalesces; this enforces \"no-category is '', never null\"\n // at the reference implementation rather than merely documenting it.\n //\n // `generateLegacyCustomId` deliberately does NOT do this: it must reproduce\n // what was actually stored, including ids an untyped caller produced.\n return md5(canonicalContentBlockJson(category, tokens));\n}\n\n/**\n * The exact string whose UTF-8 bytes are hashed to produce a `custom_id`.\n *\n * Extracted so the cross-implementation assertion can compare the SAME bytes\n * the id function hashes, rather than a second expression that happens to look\n * the same. The PHP lane found four separate sites re-deriving their\n * serialization, one of them inside the test that was supposed to be checking\n * it — a parallel reimplementation agrees with itself, and would keep agreeing\n * after this function changed.\n *\n * Deliberately NOT re-exported from `src/index.ts`: this is the reference\n * implementation's internals, not public API. `generateCustomId` is the\n * contract.\n */\n/**\n * CID-2's input prohibition, applied where the value enters the hash.\n *\n * No-category is `''` — never `null`, never `undefined`, and never the\n * `'__uncategorized__'` sentinel. That sentinel is a CACHE-LOOKUP namespace: it\n * names the bucket an uncategorised phrase lives in inside `sTranslations`, and\n * it is a natural thing for a caller to have in hand. Hashing it produces an id\n * no wire path stores.\n *\n * Found by comparing ids against `langsys-php` over a shared fixture: tokens\n * byte-identical, ids different, because PHP normalised the sentinel and this\n * SDK did not. PHP was conformant and this side was not. No internal caller ever\n * passed it — `Translate` destructures `const { category = '' }` — so no stored\n * id changes; the hole was in the public export, and `/pure` had just widened\n * the audience for it.\n */\nfunction hashableCategory(category: string): string {\n return !category || category === '__uncategorized__' ? '' : category;\n}\n\nexport function canonicalContentBlockJson(category: string, tokens: string[]): string {\n return JSON.stringify([hashableCategory(category), tokens]);\n}\n\n/**\n * The id this block would have had before the 0.6.0 MD5 fix.\n *\n * **Lookup only — never register under this.** Blocks registered by an older\n * SDK are keyed by it, so `Translate` falls back to it when the corrected id\n * misses, which keeps existing translations resolving instead of orphaning\n * them. Registering under it would keep minting ids from a hash that both\n * diverges across SDKs and can collide.\n *\n * Note the collision is a property of the FINAL hashed string, not the phrase:\n * `JSON.stringify` shifts every character's offset, so the same phrase pair can\n * collide standalone and not collide here — and changing `category` moves every\n * character into different lanes. Always reason at this level, not at `md5()`.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function generateLegacyCustomId(category: string, tokens: string[]): string {\n return md5Legacy(JSON.stringify([category, tokens]));\n}\n\n/**\n * One node of a rich-phrase tree, in the host-neutral shape `encodeRichPhrase`\n * walks.\n *\n * `{ text }` carries a text node's value VERBATIM — uncollapsed, untrimmed,\n * because collapse runs once over the assembled string and not per node (see\n * `encodeRichPhrase`). An element contributes its `children` plus an opaque\n * `payload` handed straight back in `slots`, so a host keeps its own node handle\n * without this module knowing what one is.\n *\n * Anything that is NEITHER text nor element — a comment, a CDATA section, a\n * processing instruction — must contribute NO text and NO slot. The DOM adapter\n * drops them outright.\n *\n * Measured, because the obvious wording here was wrong: mapping one to\n * `{ text: '' }` is HARMLESS (`'a' + '' + 'b'` is still `'ab'`), so an adapter may\n * do that freely. What splits the key is mapping it to its own DATA\n * (`a<!-- note -->b` becoming `'a note b'`) or giving it a slot (`'a{m0o}{m0c}b'`,\n * which also shifts every later slot index). Those two are the mistakes worth\n * naming; \"must be omitted\" overstates the rule.\n */\nexport type RichTextNode<T> =\n | { readonly text: string }\n /** A marked value (VAR-3): its placeholder, `{NAME}`, never its text. */\n | { readonly param: string }\n | { readonly children: readonly RichTextNode<T>[]; readonly payload: T };\n\nexport interface EncodedRichPhrase<T> {\n /** The phrase string: the lookup key, and therefore the identity. */\n phrase: string;\n /** Each element's `payload`, in the order its markup token was assigned. */\n slots: T[];\n}\n\n/**\n * The `<Phrase>` identity rule, with no DOM in it.\n *\n * `<Phrase>` keys by a STRING, not by a token array and not by a `custom_id`:\n * inline elements become neutral `{mNo}`/`{mNc}` markup-token pairs and the\n * whole thing collapses to one sentence, which is then the catalog key. So this\n * string is as load-bearing as `generateCustomId`'s output, and a second\n * implementation of it re-keys every rich phrase the moment the two drift —\n * silently, as a cache miss and a re-registration rather than an error.\n *\n * That is why it is here and generic over the host's node type: `langsys-js-server`\n * renders `<Phrase>` from parse5 nodes and was otherwise going to write its own\n * encoder. The DOM adapter is `encodeRichText` in `richtext.ts`, which is now\n * nothing but a node-shape mapping over this function.\n *\n * Three details are identity and every adapter has to match them:\n *\n * 1. **Slot indices are assigned in pre-order**, parent before its children,\n * which is why `slots` comes back from here rather than being built by the\n * caller's walk. An adapter that numbered its own slots would have to\n * independently reproduce this order, and a nested phrase is where it would\n * not.\n * 2. **Whitespace collapses ONCE, over the assembled string**, markup tokens\n * included — never per text node. `<p>a <em> b</em></p>` keeps the space\n * before `b` inside the markers; a per-node trim moves it outside them and\n * changes the key. This is the same mistake the attribute path made against\n * the text path, which is what split `custom_id` between this SDK and PHP.\n * 3. **`%name%` normalizes after the collapse**, not before. The two orders\n * happen to agree today (an identifier cannot contain whitespace, so no\n * collapse creates or destroys a match) — stated because \"it doesn't matter\"\n * is not something a second implementation can verify, while \"this order\" is.\n *\n * The whitespace collapse is `normalizeTokenText`, deliberately SHARED with the\n * token path so the disputed set (U+FEFF, U+0085, U+180E — see CONFORMANCE) has\n * one definition to change when the spec rules. That sharing is about the\n * whitespace set only: COALESCING adjacent text nodes stays opposite between the\n * two paths, on purpose, and `content-block.ts` says so from its side.\n */\nexport function encodeRichPhrase<T>(nodes: readonly RichTextNode<T>[]): EncodedRichPhrase<T> {\n const slots: T[] = [];\n const assembled = _encodeRichNodes(nodes, slots);\n return { phrase: normalizeMarkupPlaceholders(normalizeTokenText(assembled)), slots };\n}\n\nfunction _encodeRichNodes<T>(nodes: readonly RichTextNode<T>[], slots: T[]): string {\n let out = '';\n for (const node of nodes) {\n if ('text' in node) {\n out += node.text;\n continue;\n }\n if ('param' in node) {\n out += `{${node.param}}`;\n continue;\n }\n // Index taken and payload pushed BEFORE recursing: pre-order.\n const index = slots.length;\n slots.push(node.payload);\n out += `{m${index}o}` + _encodeRichNodes(node.children, slots) + `{m${index}c}`;\n }\n return out;\n}\n\nconst UNCATEGORIZED_SLOT = '__uncategorized__';\n\nfunction sameTokenList(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((token, i) => token === b[i]);\n}\n\n/**\n * CID-3: every historical id a block with this content could be stored under.\n * LOOKUP ONLY. Never register or emit any of these.\n *\n * The authoritative list is the fleet's shared legacy fixture (vendored as\n * `tests/fixtures/legacy-custom-id-reference.json`, blob dc555646), and every row\n * of it must resolve. That takes three families of shape:\n *\n * 1. the corrected hash over the PRE-FIX token list, which the published JS SDK\n * registered from 0.6.0 to 0.6.2, before the duplicated `<option>` fix;\n * 2. the JS code-unit hash (`generateLegacyCustomId`, which does not coalesce its\n * category), which published JS SDKs registered before 0.6.0;\n * 3. the PHP pipe-join form, `md5` over `[slot, ...phrases].join('|')`.\n *\n * An uncategorised block could have been written under several spellings of its\n * category. Python lists the code-unit hash under `''` and `'__uncategorized__'`;\n * PHP lists it under `''` and a genuine `null` from an untyped JS caller. The\n * fixture has a row for each, and the spec test is that every row resolves, so this\n * takes the UNION rather than either SDK's subset. The pipe-join form covers `''`\n * and `'__uncategorized__'`, which is all PHP ever wrote. Every extra candidate is\n * safe because none is attached without the CID-4 content check.\n *\n * Most likely first, de-duplicated, and never including the current id.\n */\nexport function historicalCustomIds(\n category: string | null | undefined,\n tokens: readonly string[],\n legacyTokens: readonly string[] = tokens\n): string[] {\n const uncategorised =\n category === null || category === undefined || category === '' || category === UNCATEGORIZED_SLOT;\n const named = uncategorised ? '' : (category as string);\n const codeUnitSlots: Array<string | null> = uncategorised ? ['', UNCATEGORIZED_SLOT, null] : [named];\n const pipeSlots: string[] = uncategorised ? ['', UNCATEGORIZED_SLOT] : [named];\n const differ = !sameTokenList(tokens, legacyTokens);\n const lists: ReadonlyArray<readonly string[]> = differ ? [legacyTokens, tokens] : [tokens];\n\n const ids: string[] = [];\n if (differ) ids.push(generateCustomId(named, [...legacyTokens]));\n for (const list of lists) {\n for (const slot of codeUnitSlots) {\n ids.push(generateLegacyCustomId(slot as string, [...list]));\n }\n }\n for (const list of lists) {\n for (const slot of pipeSlots) {\n ids.push(md5([slot, ...list].join('|')));\n }\n }\n const current = generateCustomId(named, [...tokens]);\n return [...new Set(ids)].filter((id) => id !== current);\n}\n\n/**\n * CID-4: whether a block found under a historical id holds THIS block's content.\n *\n * None of the historical id spaces is injective. The UTF-16 packing loses a byte at\n * every fourth position, and joining on an unescaped delimiter loses the field\n * boundary, so an id alone does not identify a block, and attaching on the id being\n * present can file one block's translations under another.\n *\n * Compared as normalised for hashing, not as stored: a phrase stored by an older SDK\n * may carry whitespace or a `%name%` spelling that today's tokenizer canonicalises,\n * and a raw comparison would decline those correct matches. Compared as SETS, which\n * the rule allows where the representation has lost order, and the catalog returns a\n * block as a map keyed by source phrase. A set still defeats every collision mode,\n * since each is a collision over DIFFERING content. Matches langsys-python.\n */\nexport function blockContentMatches(storedPhrases: Iterable<string>, tokens: readonly string[]): boolean {\n const canonical = (phrase: string) => normalizeMarkupPlaceholders(normalizeTokenText(phrase));\n const stored = new Set(Array.from(storedPhrases, canonical));\n const current = new Set(tokens.map(canonical));\n if (stored.size !== current.size) return false;\n for (const phrase of stored) if (!current.has(phrase)) return false;\n return true;\n}\n\n","import { IntlMessageFormat } from 'intl-messageformat';\nimport { normalizeMarkupPlaceholders } from './identity.js';\nimport { logger } from './logger.js';\n\n/**\n * Re-exported, not defined here: the CAPTURE-time rewrite is an identity rule\n * and lives in `identity.ts` with the other one. Kept on this module's surface\n * because eight call sites and both entry points import it from here.\n */\nexport { normalizeMarkupPlaceholders };\n\n/**\n * Detects ICU MessageFormat syntax in a translation string.\n *\n * - Matches `{var, plural, …}`, `{var, select, …}`, `{var, selectordinal, …}`,\n * `{var, number, …}`, `{var, date, …}`, `{var, time, …}`.\n * - Also matches the style-less forms `{var, number}`, `{var, date}`,\n * `{var, time}` — valid ICU with the locale-default style.\n * - Doesn't match plain interpolation slots like `{name}` or `{count}`.\n *\n * Exported because the Translation Manager UI needs the same detection logic\n * to decide whether to render a plural-slot editor vs. a single text field.\n */\nexport function isICU(template: string): boolean {\n return ICU_PATTERN.test(template);\n}\n\n// `[,}]` after the keyword: a style argument may follow (`{n, number, ::…}`)\n// or the argument may close immediately (`{n, number}` — locale-default style).\nconst ICU_PATTERN = /\\{[^{}]+,\\s*(plural|select|selectordinal|number|date|time)\\s*[,}]/;\n\n/**\n * Accept `%name%` at RENDER time, not only at capture time.\n *\n * `normalizeMarkupPlaceholders` has always converted `%name%` to `{name}` where\n * content is captured, because Svelte and JSX consume a bare `{name}` in markup\n * and `%name%` is what an author can actually type there. But nothing applied it\n * on the way out, so a translation stored with `%name%` rendered the percent\n * signs to the reader verbatim: `interpolate('Hi %name%', { name: 'Ada' })`\n * returned `'Hi %name%'`.\n *\n * Conversion is CONDITIONAL on the key being supplied, which matters: a blanket\n * rewrite would treat any `%word%` as a placeholder, so `'Save 20% %off%'` or\n * prose containing `%s` patterns could be mangled into a `{…}` that then renders\n * as a literal brace expression. Requiring a matching param means a string is\n * only reinterpreted when the caller demonstrably meant it as a placeholder.\n */\nfunction adoptPercentPlaceholders(template: string, params: Record<string, unknown>): string {\n if (!template.includes('%') || !params) return template;\n return template.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (whole, name: string) =>\n Object.prototype.hasOwnProperty.call(params, name) ? `{${name}}` : whole\n );\n}\n\n\n/** Keys `%name%` can carry — the same shape `adoptPercentPlaceholders` matches. */\nconst IDENTIFIER_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** `name_gender` → `name`: the gender companion of a placeholder (see `findUnusedParamKeys`). */\nconst GENDER_COMPANION = /^(.+)_gender$/;\n\n/** Escape a params key for literal use inside a RegExp. */\nfunction escapeForRegExp(key: string): string {\n return key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Params keys that have NO matching placeholder in `texts`.\n *\n * A key counts as used when it appears as `{key}`, as the argument of an ICU\n * slot (`{key, plural, …}`), or as `%key%`. Surrounding whitespace is tolerated\n * in the brace forms.\n *\n * BOTH SPELLINGS, because `interpolate` resolves both. It used to accept the\n * brace forms only, on the stated assumption that texts arrive canonical\n * (post-`normalizeMarkupPlaceholders`). That held for the two internal callers\n * and still does — `<Translate>` normalizes its tokens at capture and\n * `<Phrase>`'s string comes out of `encodeRichText` already rewritten — but it\n * stopped being true of the function itself once `interpolate` began adopting\n * `%name%` at render time. A caller passing a raw stored translation then got\n * `name` reported unused for a param that renders perfectly, and\n * `warnUnmatchedParams` told them to \"write %name% instead\" — which is what they\n * had written. This predicate and `adoptPercentPlaceholders` have to agree about\n * what a placeholder is; they are two halves of one rule.\n *\n * The percent spelling is accepted only for keys that are IDENTIFIERS, matching\n * `adoptPercentPlaceholders` exactly. A key like `a.b` never resolves from\n * `%a.b%` — accepting it here would suppress a warning that is correct.\n *\n * A `<name>_gender` key counts as used wherever `name` is a placeholder. Langsys\n * promotes a plain `{name}` to `{name_gender, select, …}` in gendered target\n * locales, so an app passes the gender beside the value (`GenderParamsFor` types\n * it), and the source text a caller checks never names it. Only a placeholder's\n * companion: `team_gender` with no `{team}` in the text is still reported.\n */\nexport function findUnusedParamKeys(texts: string[], params: Record<string, unknown> | undefined): string[] {\n if (!params) return [];\n const keys = Object.keys(params);\n if (!keys.length || !texts.length) return keys;\n\n // The separator is a literal NUL, written as an ESCAPE and never as the byte\n // itself. A raw 0x00 in a source file makes git classify it as binary: no\n // diff, no blame, no 3-way merge, and every change to this file becomes\n // invisible to review while still shipping. It hid here once already.\n const haystack = texts.join('\\0');\n const isPlaceholder = (key: string): boolean => {\n const escaped = escapeForRegExp(key);\n const percent = IDENTIFIER_KEY.test(key) ? `|%${escaped}%` : '';\n return new RegExp(`\\\\{\\\\s*${escaped}\\\\s*[,}]${percent}`).test(haystack);\n };\n return keys.filter((key) => {\n if (isPlaceholder(key)) return false;\n const genderOf = GENDER_COMPANION.exec(key)?.[1];\n return !(genderOf && isPlaceholder(genderOf));\n });\n}\n\n/**\n * Debug-time warning for the single most common markup-interpolation mistake:\n * writing `{name}` instead of `%name%` inside `<Translate>`/`<Phrase>` content.\n *\n * We can't see the mistake directly — Svelte and JSX substitute `{name}` at\n * compile time, so the SDK only ever receives the already-substituted text.\n * But the fingerprint is unmistakable: params were supplied and NONE of their\n * keys survive as placeholders in the captured content. Left undetected this\n * fails silently (the base locale still looks right), so it's worth naming\n * explicitly.\n *\n * Only emits when debug logging is on — silent in production.\n */\nexport function warnUnmatchedParams(\n source: string,\n texts: string[],\n params: Record<string, unknown> | undefined,\n context?: string,\n): void {\n if (!logger.debugEnabled) return;\n\n const unused = findUnusedParamKeys(texts, params);\n if (!unused.length) return;\n\n const keyList = unused.map((key) => `%${key}%`).join(', ');\n // Framework-neutral wording: the brace spelling that gets eaten differs by\n // framework (Svelte/JSX consume `{key}`, Vue consumes `{{ key }}`), and the\n // SDK has no idea which one it's running under.\n logger.warn(\n `${source} received params with no matching placeholder in its content: ${keyList}.` +\n ` If you wrote {${unused[0]}} or {{ ${unused[0]} }} in markup, your framework's template` +\n ` compiler substituted it before Langsys saw the text — write %${unused[0]}% instead.` +\n (context ? ` [${context}]` : ''),\n );\n}\n\n/**\n * Substitute placeholders in a translated string with values from `params`.\n *\n * Two paths:\n * - ICU MessageFormat (target string contains `{var, plural|select|…, …}`):\n * parsed and formatted via `intl-messageformat`, which knows every\n * target locale's plural rules (Arabic's 6 categories, Russian's 4,\n * etc.) and gender-select branches.\n * - Simple `{name}` interpolation: cheap regex replacement. Unknown\n * placeholders are left untouched so missing data is visible to the\n * developer rather than silently rendering empty strings. Number and\n * Date values are formatted per the target locale's CLDR rules\n * (`Intl.NumberFormat` / `Intl.DateTimeFormat`) — pass numbers as\n * strings to opt out (e.g. IDs and codes that must not get grouping\n * separators).\n *\n * Malformed ICU falls through to simple interpolation rather than throwing,\n * so the developer sees a broken-but-visible string instead of a runtime crash.\n * Backend-side validation in langsys-ai is supposed to prevent this — the\n * fall-through is defense in depth.\n *\n * `locale` is required for ICU formatting (drives plural-rule selection).\n * Falls back to `'en'` if absent — simple-interpolation path ignores it.\n *\n * `params` may be omitted, and behaves as an empty map: a select or plural renders\n * its `other` branch (ICU-1). Omitting it used to throw a TypeError inside recovery.\n *\n * `options` routes the two notices to the caller instead of this module's logger,\n * for a host with a logger of its own — a server with a per-instance debug\n * setting, where this module's process-wide logger is the wrong switch. See\n * `InterpolateOptions`.\n */\nexport function interpolate(\n template: string,\n params: Record<string, unknown> = {},\n locale?: string,\n options: InterpolateOptions = {},\n): string {\n template = adoptPercentPlaceholders(template, params);\n\n if (isICU(template)) {\n const resolved = locale || 'en';\n // A null value does NOT throw — `intl-messageformat` coerces it (null\n // becomes 0, so `{count, plural…}` renders \"0 items\"). That would make a\n // bug indistinguishable from valid data: a real empty cart and a failure\n // to pass the count would render identically. So null is routed straight\n // to recovery, where it is treated as missing — matching langsys-php,\n // which tests this explicitly. A genuine 0 is untouched and still\n // renders \"0 items\".\n const hasNullParam = !!params && Object.values(params).some((value) => value === null);\n let formatterError: unknown;\n if (!hasNullParam) {\n try {\n return formatIcu(new IntlMessageFormat(template, resolved), params, resolved);\n } catch (error) {\n formatterError = error;\n }\n }\n // `.ast` is typed private but is the parsed message the library formats\n // from, and `IntlMessageFormat` accepts an AST in place of a string.\n // Reaching for it avoids taking a second runtime dependency on the\n // parser just to re-parse what's already parsed. A phrase that does not\n // parse has no branches to select, so it takes the simple path.\n let ast: unknown;\n try {\n ast = (new IntlMessageFormat(template, resolved) as unknown as { ast?: unknown }).ast;\n } catch {\n return simpleInterpolate(template, params, locale);\n }\n if (!Array.isArray(ast)) return simpleInterpolate(template, params, locale);\n\n // A missing argument throws. Recover the sentence rather than dumping\n // ICU source to the page — see `_recoverMissingArgs`.\n const defaulted: string[] = [];\n const recovered = _recoverMissingArgs(JSON.parse(JSON.stringify(ast)) as IcuNode[], params, defaulted);\n if (defaulted.length) {\n if (options.onDefaulted) options.onDefaulted([...new Set(defaulted)], template, resolved);\n else noteDefaultedArgs(template, resolved, defaulted);\n }\n if (defaulted.length || formatterError === undefined) {\n try {\n return formatIcu(new IntlMessageFormat(recovered as never, resolved), params, resolved);\n } catch (error) {\n formatterError = error;\n }\n }\n\n // Nothing was missing, or the recovered message still would not format:\n // the formatter itself failed on this phrase (ICU-6). Render it without\n // the formatter, and say so at every log level.\n if (options.onFormatterFailure) options.onFormatterFailure(formatterError, template, resolved);\n else noteFormatterFailure(template, resolved, formatterError);\n return renderWithoutFormatter(ast as IcuNode[], params, resolved);\n }\n return simpleInterpolate(template, params, locale);\n}\n\n/**\n * The argument names `interpolate` would default for these params (ICU-4): each\n * `select`, `plural` or plain argument the template uses and `params` does not\n * supply (`null` counts as not supplied), once each, in the order the recovery\n * meets them. Empty for a plain template or one that does not parse.\n *\n * The same walk `interpolate` recovers with, so a host that emits the notice\n * through its own logger names exactly the arguments the render defaulted.\n */\nexport function defaultedArguments(template: string, params: Record<string, unknown> = {}, locale = 'en'): string[] {\n template = adoptPercentPlaceholders(template, params);\n if (!isICU(template)) return [];\n let ast: unknown;\n try {\n ast = (new IntlMessageFormat(template, locale) as unknown as { ast?: unknown }).ast;\n } catch {\n return [];\n }\n if (!Array.isArray(ast)) return [];\n const defaulted: string[] = [];\n _recoverMissingArgs(JSON.parse(JSON.stringify(ast)) as IcuNode[], params, defaulted);\n return [...new Set(defaulted)];\n}\n\n/**\n * Where `interpolate` reports what it recovered from. Each handler, when given,\n * replaces this module's logger for that notice and is called on EVERY\n * occurrence: gating and deduplication are then the caller's, so a host applies\n * its own debug switch and its own `(template, locale)` dedupe. What the core\n * logger does, and what a handler should reproduce:\n *\n * - `onDefaulted` (ICU-4): a missing argument was recovered with its neutral\n * branch. Debug level only; names every defaulted argument, once each, and the\n * locale.\n * - `onFormatterFailure` (ICU-6): the formatter failed and the SDK's own branch\n * selection rendered the phrase. At every log level, naming the phrase, the\n * locale and the error.\n */\nexport interface InterpolateOptions {\n onDefaulted?: (names: string[], template: string, locale: string) => void;\n onFormatterFailure?: (error: unknown, template: string, locale: string) => void;\n}\n\n/** ICU AST node types we care about (from `@formatjs/icu-messageformat-parser`). */\nconst ICU_LITERAL = 0;\nconst ICU_ARGUMENT = 1;\nconst ICU_NUMBER = 2;\nconst ICU_DATE = 3;\nconst ICU_TIME = 4;\nconst ICU_SELECT = 5;\nconst ICU_PLURAL = 6;\nconst ICU_POUND = 7;\nconst ICU_TAG = 8;\n\ninterface IcuNode {\n type: number;\n value?: string;\n options?: Record<string, { value: IcuNode[] }>;\n children?: IcuNode[];\n offset?: number;\n pluralType?: 'cardinal' | 'ordinal';\n}\n\n/**\n * Rewrite an ICU AST so a MISSING argument degrades gracefully instead of\n * taking the whole message down.\n *\n * Why this is reachable without any caller mistake: langsys-ai's ICU promoter\n * can *introduce* a select argument the source phrase never had — a plain\n * `{name}` becomes `{name_gender, select, …}` in gendered target locales. An\n * application may pass `name_gender` beside `name`, and most never do: the\n * argument appears nowhere in the phrase the developer wrote, and few apps know\n * the user's gender. Every app translating into a gendered locale hits this.\n *\n * The recovery, agreed with `langsys-php` so a shared catalog can't render two\n * different sentences for the same input:\n *\n * - **`select`** → take the `other` branch. Recoverable: `other` is exactly\n * what an unknown gender should render, so the sentence comes out correct.\n * - **`plural`** → take the `other` branch, rendering `#` as `{argName}`.\n * Nothing can be inferred for a count, so this is only made less bad: the\n * sentence survives with a visible gap.\n * - **plain arguments** (`{name}`, `{n, number}`, dates) → render as\n * `{argName}`, matching the simple path's rule that unknown keys stay\n * visible rather than blanking.\n *\n * Elements whose argument IS supplied are left untouched and recursed into, so\n * a missing argument nested inside a satisfied branch is still recovered.\n * `plural`/`select` without an `other` branch is malformed ICU — left alone, so\n * it falls through to the simple path as before.\n */\n/**\n * Templates already reported on, keyed by template+locale.\n *\n * Recovery is silent by design in production — that is the whole point — but\n * silence is also what makes the argument undiscoverable: it does not appear in\n * the source phrase, so a developer has no way to learn that `{name}` became\n * `{name_gender, select, …}` in Spanish and that their app could be supplying\n * it. Debug mode is the one place they can be told. Deduped because this runs\n * on every render of every string.\n */\nconst notifiedDefaults = new Set<string>();\n\nfunction noteDefaultedArgs(template: string, locale: string, names: string[]): void {\n if (!logger.debugEnabled) return;\n\n const key = `${locale}\\0${template}`;\n if (notifiedDefaults.has(key)) return;\n notifiedDefaults.add(key);\n\n const unique = [...new Set(names)];\n logger.warn(\n `Interpolation defaulted ${unique.length === 1 ? 'argument' : 'arguments'} ${unique\n .map((n) => `\"${n}\"`)\n .join(', ')} while rendering a '${locale}' string. The translated phrase asks for ` +\n `${unique.length === 1 ? 'it' : 'them'} but the source phrase does not, which is normal — a gendered ` +\n `target locale can introduce an argument the source never had. The neutral branch was used. Pass ` +\n `${unique.length === 1 ? 'the value' : 'the values'} in \\`params\\` if your app knows ${unique.length === 1 ? 'it' : 'them'}.`\n );\n}\n\nfunction _recoverMissingArgs(\n nodes: IcuNode[],\n params: Record<string, unknown>,\n defaulted: string[]\n): IcuNode[] {\n const out: IcuNode[] = [];\n\n for (const node of nodes) {\n const name = node.value;\n // `null` counts as missing, matching the simple path where a present-\n // but-null value is left visible rather than rendered as 0 or \"null\".\n const value = name !== undefined && name in params ? params[name] : undefined;\n const supplied = value !== undefined && value !== null;\n\n if (node.type === ICU_TAG) {\n out.push({ ...node, children: _recoverMissingArgs(node.children ?? [], params, defaulted) });\n continue;\n }\n\n if (node.type === ICU_SELECT || node.type === ICU_PLURAL) {\n if (supplied) {\n const options: Record<string, { value: IcuNode[] }> = {};\n for (const [key, branch] of Object.entries(node.options ?? {})) {\n options[key] = { value: _recoverMissingArgs(branch.value, params, defaulted) };\n }\n out.push({ ...node, options });\n continue;\n }\n const other = node.options?.other;\n if (!other) {\n out.push(node); // malformed — let the simple path handle it\n continue;\n }\n if (name) defaulted.push(name);\n const branch = _recoverMissingArgs(other.value, params, defaulted);\n // `#` has no count to render, so show the argument name instead.\n out.push(\n ...branch.map((child) =>\n child.type === ICU_POUND ? { type: ICU_LITERAL, value: `{${name}}` } : child,\n ),\n );\n continue;\n }\n\n if (\n !supplied &&\n (node.type === ICU_ARGUMENT ||\n node.type === ICU_NUMBER ||\n node.type === ICU_DATE ||\n node.type === ICU_TIME)\n ) {\n if (name) defaulted.push(name);\n out.push({ type: ICU_LITERAL, value: `{${name}}` });\n continue;\n }\n\n out.push(node);\n }\n\n return out;\n}\n\n/** Templates whose formatter failure has been reported, keyed by template+locale. */\nconst notifiedFailures = new Set<string>();\n\n/**\n * A formatter failure warns whether or not debug logging is on, unlike the\n * defaulted-argument notice above: a missing argument is normal, while a phrase\n * the formatter cannot render is a defect somebody has to fix. Deduped per\n * (template, locale) because this runs on every render.\n */\nfunction noteFormatterFailure(template: string, locale: string, error: unknown): void {\n const key = `${locale}\\0${template}`;\n if (notifiedFailures.has(key)) return;\n notifiedFailures.add(key);\n\n const reason = error instanceof Error ? error.message : String(error);\n logger.warn(\n `The message formatter failed on a '${locale}' phrase, so it was rendered by the SDK's own branch ` +\n `selection. Fix the phrase: ${JSON.stringify(template)}. Formatter error: ${reason}`\n );\n}\n\n/**\n * Render a parsed ICU message without the formatter (ICU-6), the way\n * `_recoverMissingArgs` treats a missing argument: each `select` or `plural`\n * takes the branch for its supplied value and the construct itself is dropped,\n * supplied values are filled in, and an unsupplied one stays visible as\n * `{argName}`. Never returns the raw construct.\n *\n * Plural branch order is ICU's: an exact `=N` on the value first, then the\n * value's CLDR category in the render locale (after the offset), then `other`.\n */\nfunction renderWithoutFormatter(nodes: IcuNode[], params: Record<string, unknown>, locale: string, pound?: number | string): string {\n let out = '';\n for (const node of nodes) {\n const name = node.value;\n const value = name !== undefined && params && name in params ? params[name] : undefined;\n const supplied = value !== undefined && value !== null;\n\n switch (node.type) {\n case ICU_LITERAL:\n out += node.value ?? '';\n break;\n case ICU_POUND:\n out += pound === undefined ? '#' : typeof pound === 'string' ? pound : formatScalar(pound, locale);\n break;\n case ICU_TAG:\n out += `<${name}>${renderWithoutFormatter(node.children ?? [], params, locale, pound)}</${name}>`;\n break;\n case ICU_SELECT: {\n const options = node.options ?? {};\n const branch = (supplied ? options[String(value)] : undefined) ?? options.other;\n out += branch ? renderWithoutFormatter(branch.value, params, locale, pound) : `{${name}}`;\n break;\n }\n case ICU_PLURAL: {\n const options = node.options ?? {};\n const count = supplied ? Number(value) : NaN;\n if (Number.isNaN(count)) {\n const other = options.other;\n // `#` has no count to render, so show the argument name instead.\n out += other ? renderWithoutFormatter(other.value, params, locale, `{${name}}`) : `{${name}}`;\n break;\n }\n const adjusted = count - (node.offset ?? 0);\n let branch = options[`=${count}`];\n if (!branch) {\n try {\n branch = options[new Intl.PluralRules(locale, { type: node.pluralType ?? 'cardinal' }).select(adjusted)];\n } catch {\n // no CLDR rules for this locale: `other` below\n }\n }\n branch = branch ?? options.other;\n out += branch ? renderWithoutFormatter(branch.value, params, locale, adjusted) : `{${name}}`;\n break;\n }\n default:\n // Plain, number, date and time arguments.\n out += supplied ? formatScalar(value, locale) : `{${name}}`;\n }\n }\n return out;\n}\n\n/**\n * An ICU message formatted to one string. When a plain argument is neither a string nor a\n * number (a Date, or `true`), the formatter returns its parts instead, or that one value\n * when it is the whole output, and it writes `false` as nothing. So a boolean goes in as\n * `true` or `false`, and any value that is not a string is written as the simple path\n * writes it (`formatScalar`).\n */\nfunction formatIcu(message: IntlMessageFormat, params: Record<string, unknown>, locale: string): string {\n const scalars = Object.fromEntries(Object.entries(params ?? {}).map(([name, value]) => [name, typeof value === 'boolean' ? String(value) : value]));\n const out: unknown = message.format(scalars as never);\n if (typeof out === 'string') return out;\n return Array.isArray(out) ? out.map((part) => (typeof part === 'string' ? part : formatScalar(part, locale))).join('') : formatScalar(out, locale);\n}\n\n/** A supplied value as the simple path renders it: CLDR numbers and medium dates. */\nfunction formatScalar(value: unknown, locale: string): string {\n try {\n if (value instanceof Date) return new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(value);\n if (typeof value === 'number' || typeof value === 'bigint') return new Intl.NumberFormat(locale).format(value);\n } catch {\n // an invalid locale tag: the locale-blind rendering below\n }\n return value instanceof Date ? value.toISOString() : String(value);\n}\n\nfunction simpleInterpolate(template: string, params: Record<string, unknown>, locale?: string): string {\n // The `[^{},]` character class excludes `{`, `}`, and `,` from placeholder\n // names so we don't accidentally consume ICU-shaped slots that somehow\n // routed through this path (e.g. malformed ICU after fall-through).\n return template.replace(/\\{([^{},]+)\\}/g, (match, rawKey: string) => {\n const key = rawKey.trim();\n if (!(key in params)) return match;\n const value = params[key];\n if (value === undefined || value === null) return match;\n // CLDR-formatted output for numbers and dates, mirroring what the ICU\n // defaults (`{n, number}`, `{d, date}` → medium) would produce. The\n // try/catch guards against invalid locale tags — fall back to the\n // locale-blind rendering rather than throwing mid-render.\n if (value instanceof Date) {\n try {\n return new Intl.DateTimeFormat(locale || 'en', { dateStyle: 'medium' }).format(value);\n } catch {\n return value.toISOString();\n }\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n try {\n return new Intl.NumberFormat(locale || 'en').format(value);\n } catch {\n return String(value);\n }\n }\n return String(value);\n });\n}\n","import { encodeRichPhrase, isOpaqueInPhrase, normalizeMarkupPlaceholders, normalizeTokenText, type AttributeReader, type RichTextNode } from './identity.js';\nimport { interpolate, isICU } from './interpolate.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\n\n/**\n * Value markers (spec VAR-3): how an emitter tells a reader which printed text\n * was a variable, and what it was called, so the reader registers a placeholder\n * instead of one phrase per value (VAR-1).\n *\n * <p>Hello <!--ls:name-->Ana<!--/ls-->, welcome back</p>\n * <p>Hello <span data-ls-param=\"name\">Ana</span>, welcome back</p>\n * [{ text: 'Hello ' }, { comment: 'ls:name' }, { text: 'Ana' }, { comment: '/ls' }, { text: ', welcome back' }]\n *\n * all read as the one token `Hello {name}, welcome back`, with param `name` =\n * `Ana`. The value is text only: an element inside the pair voids the marker,\n * and its comments then split text as any comment does.\n *\n * Within one parent, the text on both sides of a marker, and every marker in\n * between, merge into one run. Everything without a marker splits exactly as\n * before, so no id derived from unmarked markup changes.\n */\n\n/** The attribute form's attribute, for an emitter that cannot write comments. */\nexport const VAR_PARAM_ATTR = 'data-ls-param';\n\n/** A placeholder name (VAR-2's grammar). */\nconst NAME = /^[a-z][a-z0-9_]*$/;\nconst OPEN = /^ls:([a-z][a-z0-9_]*)$/;\nconst CLOSE = '/ls';\n\nconst ELEMENT = 1;\nconst TEXT = 3;\nconst COMMENT = 8;\n\n/** What the grouping reads from a node: the DOM's shape, or a tree view's. */\nexport interface MarkerNode {\n nodeType: number;\n nodeValue: string | null;\n childNodes: ArrayLike<MarkerNode>;\n getAttribute?(name: string): string | null;\n}\n\n/** A marked value: its name, the text nodes holding the value, and the nodes that mark it. */\nexport interface VarMarker<N> {\n name: string;\n value: N[];\n /** The nodes that are the marker itself: a comment pair, or the `data-ls-param` element. */\n frame: N[];\n}\n\nexport type RunPart<N> = { text: N } | { marker: VarMarker<N> };\n\n/** One merged run: text nodes and markers, in order, holding at least one marker. */\nexport interface VarRun<N> {\n parts: RunPart<N>[];\n}\n\nexport type RunItem<N> = { node: N } | { run: VarRun<N> };\n\n/** The name an element marks as a value (`data-ls-param`, holding text only), or null when it is no marker. */\nexport function paramElementName(node: MarkerNode): string | null {\n if (node.nodeType !== ELEMENT || !node.getAttribute) return null;\n const name = node.getAttribute(VAR_PARAM_ATTR)?.trim();\n if (!name || !NAME.test(name)) return null;\n return Array.from(node.childNodes).every((child) => child.nodeType === TEXT) ? name : null;\n}\n\n/** The marker starting at `children[i]`, and the index after it; null when there is none there. */\nfunction markerAt<N extends MarkerNode>(children: readonly N[], i: number): { marker: VarMarker<N>; next: number } | null {\n const node = children[i]!;\n if (node.nodeType === COMMENT) {\n const open = OPEN.exec((node.nodeValue ?? '').trim());\n if (!open) return null;\n const value: N[] = [];\n let j = i + 1;\n while (j < children.length && children[j]!.nodeType === TEXT) value.push(children[j++]!);\n const close = children[j];\n // Anything but text before the close voids the pair (an element inside, or no close).\n if (!close || close.nodeType !== COMMENT || (close.nodeValue ?? '').trim() !== CLOSE) return null;\n return { marker: { name: open[1]!, value, frame: [node, close] }, next: j + 1 };\n }\n const name = paramElementName(node);\n if (name !== null) return { marker: { name, value: Array.from(node.childNodes) as N[], frame: [node] }, next: i + 1 };\n return null;\n}\n\n/**\n * A parent's children as items: each run of text and markers that holds a\n * marker, and every other node as itself. Adjacent text with no marker among it\n * stays separate nodes, as the walks have always seen it.\n */\nexport function groupRuns<N extends MarkerNode>(children: ArrayLike<N>): RunItem<N>[] {\n const list = Array.from(children);\n const items: RunItem<N>[] = [];\n let parts: RunPart<N>[] = [];\n const flush = () => {\n if (parts.some((part) => 'marker' in part)) items.push({ run: { parts } });\n else for (const part of parts) items.push({ node: (part as { text: N }).text });\n parts = [];\n };\n for (let i = 0; i < list.length; i++) {\n const node = list[i]!;\n if (node.nodeType === TEXT) {\n parts.push({ text: node });\n continue;\n }\n const found = markerAt(list, i);\n if (found) {\n parts.push({ marker: found.marker });\n i = found.next - 1;\n continue;\n }\n flush();\n items.push({ node });\n }\n flush();\n return items;\n}\n\n/** A run's text, with `{NAME}` for each marker; `text` reads a text node (its original, where one is kept). */\nexport function runSource<N extends MarkerNode>(run: VarRun<N>, text: (node: N) => string = (n) => n.nodeValue ?? ''): string {\n return run.parts.map((part) => ('text' in part ? text(part.text) : `{${part.marker.name}}`)).join('');\n}\n\n/** The siblings a run spans, in order: its text nodes, and each marker's own nodes with the value between. */\nexport function runNodes<N extends MarkerNode>(run: VarRun<N>): N[] {\n return run.parts.flatMap((part) => {\n if ('text' in part) return [part.text];\n const [open, close] = part.marker.frame;\n return close ? [open!, ...part.marker.value, close] : [open!];\n });\n}\n\n/** A run's token, normalised as a text node's token is. Empty when the run holds only whitespace and markers. */\nexport function runToken<N extends MarkerNode>(run: VarRun<N>, text?: (node: N) => string): string {\n return normalizeMarkupPlaceholders(normalizeTokenText(runSource(run, text)));\n}\n\n/** Whether a run has no text of its own: only markers, and whitespace. */\nexport function isMarkerOnly<N extends MarkerNode>(run: VarRun<N>, text: (node: N) => string = (n) => n.nodeValue ?? ''): boolean {\n return run.parts.every((part) => 'marker' in part || !normalizeTokenText(text(part.text)));\n}\n\n/** The value each marker carries, by name: the text it holds now. */\nexport function runValues<N extends MarkerNode>(run: VarRun<N>, value: (node: N) => string = (n) => n.nodeValue ?? ''): Record<string, string> {\n const values: Record<string, string> = {};\n for (const part of run.parts) {\n if ('marker' in part && !(part.marker.name in values)) {\n values[part.marker.name] = normalizeTokenText(part.marker.value.map(value).join(''));\n }\n }\n return values;\n}\n\n/**\n * The text each node of a run shows for `template` (the run's translation, or its\n * source): what to write into each text node, and into each marked value's nodes.\n *\n * In place when the template keeps every marker's placeholder exactly once, in\n * the markers' order, and is not ICU: the text between the markers goes into the\n * text nodes between them, and the value nodes keep the value, so a framework's\n * later update to them stays live. Otherwise the whole sentence, with the values\n * interpolated, goes into the run's first text node, and every other text node\n * and value node is emptied; a later value update then needs a re-render.\n *\n * `params` are the caller's; a marker's value is its param only when the caller\n * does not name that param itself. A param the caller names is written into the\n * value's nodes, in place as in a whole sentence.\n */\nexport function renderRun<N extends MarkerNode>(\n run: VarRun<N>,\n template: string,\n params: Record<string, ParamPrimitive>,\n locale: string,\n source: { text: (node: N) => string; value: (marker: VarMarker<N>) => string }\n): Array<[N, string]> {\n const groups: N[][] = [[]];\n const markers: VarMarker<N>[] = [];\n for (const part of run.parts) {\n if ('text' in part) groups[groups.length - 1]!.push(part.text);\n else {\n markers.push(part.marker);\n groups.push([]);\n }\n }\n const texts = groups.flat();\n const leadOf = (node: N | undefined) => (node ? /^\\s*/.exec(source.text(node))![0] : '');\n const trailOf = (node: N | undefined) => (node ? /\\s*$/.exec(source.text(node))![0] : '');\n const lastGroup = groups[groups.length - 1]!;\n // The run's own outer whitespace stays where it was, as a text node's does.\n const edge = (i: number, segment: string) =>\n (i === 0 ? leadOf(groups[0]![0]) : '') + segment + (i === groups.length - 1 ? trailOf(lastGroup[lastGroup.length - 1]) : '');\n\n const segments = splitAtMarkers(template, markers.map((m) => m.name));\n const inPlace = segments !== null && segments.every((segment, i) => groups[i]!.length > 0 || segment === '');\n const writes: Array<[N, string]> = [];\n if (inPlace) {\n segments!.forEach((segment, i) => {\n groups[i]!.forEach((node, k) => writes.push([node, k === 0 ? edge(i, interpolate(segment, params, locale)) : '']));\n });\n for (const marker of markers) {\n const node = marker.value[0];\n if (!node) continue;\n if (marker.name in params) {\n // The caller names the param itself, so it is the value shown (VAR-3).\n const text = interpolate(`{${marker.name}}`, params, locale);\n marker.value.forEach((n, k) => writes.push([n, k === 0 ? text : '']));\n } else if (!marker.value.map((n) => n.nodeValue ?? '').join('')) {\n // A value an earlier whole-sentence render emptied is shown again.\n writes.push([node, source.value(marker)]);\n }\n }\n return writes;\n }\n const values: Record<string, ParamPrimitive> = {};\n for (const marker of markers) if (!(marker.name in values)) values[marker.name] = source.value(marker);\n const whole = interpolate(template, { ...values, ...params }, locale);\n const first = texts[0];\n if (!first) return writes;\n const text = leadOf(first) + whole + trailOf(texts[texts.length - 1]);\n for (const node of texts) writes.push([node, node === first ? text : '']);\n for (const marker of markers) for (const node of marker.value) writes.push([node, '']);\n return writes;\n}\n\n/** The template's text between the markers' placeholders, or null unless each appears once, in order, outside ICU. */\nfunction splitAtMarkers(template: string, names: string[]): string[] | null {\n if (isICU(template) || new Set(names).size !== names.length) return null;\n const segments: string[] = [];\n let rest = template;\n for (const name of names) {\n const token = `{${name}}`;\n const at = rest.indexOf(token);\n if (at < 0 || rest.indexOf(token, at + token.length) >= 0) return null;\n segments.push(rest.slice(0, at));\n rest = rest.slice(at + token.length);\n }\n segments.push(rest);\n // A placeholder of a marker must not also appear in an earlier segment.\n if (segments.some((segment) => names.some((name) => segment.includes(`{${name}}`)))) return null;\n return segments;\n}\n\n/**\n * A rich phrase's nodes (`encodeRichPhrase`), reading value markers: each marked\n * value is its `{NAME}` placeholder, its value goes into `values`, and a comment\n * that marks nothing is dropped. Every other element is a markup slot. An element\n * opaque in a phrase (`isOpaqueInPhrase`) is a slot with nothing inside, and nothing\n * in it is read (TOK-1). `payload` is told whether its element is opaque.\n *\n * `exclude: false` walks into opaque elements, as the reader did before TOK-1 bound\n * this path: the earlier key a phrase holding one was registered under (`earlierRichPhrase`).\n *\n * With `marker`, each marked value is a markup slot holding its placeholder, with\n * `marker`'s payload: how a phrase served as its source renders inside its markers.\n */\nexport function toRichNodes<N extends MarkerNode, T>(\n children: ArrayLike<N>,\n payload: (element: N, opaque: boolean) => T,\n values: Record<string, string> = {},\n exclude = true,\n marker?: (marker: VarMarker<N>) => T\n): RichTextNode<T>[] {\n const out: RichTextNode<T>[] = [];\n for (const item of groupRuns(children)) {\n if ('run' in item) {\n for (const part of item.run.parts) {\n if ('text' in part) out.push({ text: part.text.nodeValue ?? '' });\n else {\n out.push(marker ? { children: [{ param: part.marker.name }], payload: marker(part.marker) } : { param: part.marker.name });\n if (!(part.marker.name in values)) {\n values[part.marker.name] = normalizeTokenText(part.marker.value.map((node) => node.nodeValue ?? '').join(''));\n }\n }\n }\n continue;\n }\n const node = item.node;\n if (node.nodeType === TEXT) out.push({ text: node.nodeValue ?? '' });\n else if (node.nodeType === ELEMENT) {\n const opaque = isOpaqueInPhrase(node as unknown as AttributeReader);\n const children = opaque && exclude ? [] : toRichNodes(node.childNodes as ArrayLike<N>, payload, values, exclude, marker);\n out.push({ children, payload: payload(node, opaque) });\n }\n }\n return out;\n}\n\n/**\n * The key a phrase holding an opaque element was registered under before TOK-1 bound\n * this path, with its slots and values, or null when it holds none and so has one key.\n * Lookup only: a phrase renders a translation found under it and registers only its\n * current key.\n */\nexport function earlierRichPhrase<N extends MarkerNode, T>(\n children: ArrayLike<N>,\n payload: (element: N, opaque: boolean) => T\n): { phrase: string; slots: T[]; values: Record<string, string> } | null {\n let holds = false;\n const values: Record<string, string> = {};\n const nodes = toRichNodes(children, (element, opaque) => ((holds ||= opaque), payload(element, opaque)), values, false);\n return holds ? { ...encodeRichPhrase(nodes), values } : null;\n}\n","/**\n * Framework-agnostic content-block helpers.\n *\n * The DOM-mutating `Translate` class in `translate.ts` is one consumer of\n * these — it walks a live element, tokenizes it, registers the content\n * block, and mutates the same element in place. That model fits Svelte\n * and vanilla JS, where the SDK genuinely owns the DOM node.\n *\n * For React/Vue/Angular wrappers, mutating the DOM directly is an anti-\n * pattern — those frameworks own their rendered output. Wrappers should\n * import the helpers below to handle the framework-agnostic parts (token\n * discovery, content-block registration, dedup against the local cache)\n * and render translated content through their framework's native means.\n *\n * Wrapper pattern:\n *\n * 1. After mount, grab the rendered DOM via the framework's ref/binding.\n * 2. `const { tokens, content } = tokenizeElement(el);`\n * 3. `const customId = generateCustomId(category, tokens);`\n * 4. `if (!isContentBlockKnown(category, customId)) {`\n * ` await registerContentBlock({ custom_id: customId, category, content, tokens, label });`\n * `}`\n * 5. Subscribe to `sTranslations` + `currentlyLoadedLocale`; on change,\n * look up each token via `Translations.lookupContent(category, customId, token)`\n * and render via your framework's templating.\n */\n\nimport { LangsysAppAPI, type ApiCredentials } from './api.js';\nimport { activeCatalog, activeScope } from './scope-context.js';\nimport { recordMissForDiscovery } from './discovery.js';\nimport { normalizeMarkupPlaceholders } from './interpolate.js';\nimport { canonicalizeLocale } from './locale.js';\nimport { logger } from './logger.js';\nimport { catalogUnavailable, config as configStore, configured, currentlyLoadedLocale, discoveryBaseLocaleOnly, sTranslations, writeEnabled } from './stores.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { iTranslations } from './types/translations.js';\nimport { groupRuns, isMarkerOnly, runNodes, runSource, runToken, runValues, type MarkerNode, type RunItem, type VarRun } from './var-markers.js';\nimport {\n blockContentMatches,\n CONTENT_BLOCK_MARKER_ATTRS,\n isTranslationExcluded,\n NON_TRANSLATABLE_ELEMENTS,\n normalizeTokenText,\n PHRASE_MARKER_ATTRS,\n RESOLVED_MARKER_ATTRS,\n TRANSLATABLE_ATTRIBUTES,\n} from './identity.js';\n\n/**\n * The identity contract now lives in `identity.ts`, which has no DOM and no\n * module-scope side effects so a server can import it. Re-exported here because\n * this was its address for several releases and every binding imports from it.\n */\nexport {\n canonicalContentBlockJson,\n CONTENT_BLOCK_MARKER_ATTR,\n CONTENT_BLOCK_MARKER_ATTR_LEGACY,\n CONTENT_BLOCK_MARKER_ATTRS,\n generateCustomId,\n generateLegacyCustomId,\n isTranslationExcluded,\n NON_TRANSLATABLE_ELEMENTS,\n normalizeTokenText,\n PHRASE_MARKER_ATTR,\n PHRASE_MARKER_ATTR_LEGACY,\n PHRASE_MARKER_ATTRS,\n RESOLVED_MARKER_ATTR,\n RESOLVED_MARKER_ATTR_LEGACY,\n RESOLVED_MARKER_ATTRS,\n TRANSLATABLE_ATTRIBUTES,\n} from './identity.js';\n\n\n/**\n * Attributes that mark a subtree as a self-managed \"keep-together\" phrase,\n * which the block tokenizer must skip rather than split at tag boundaries.\n *\n * Two spellings, because two SDKs mark the same thing:\n * - `data-ls-phrase` — set by this SDK's framework `<Phrase>` components.\n * - `data-langsys-phrase` — `langsys-php`'s author-facing marker, which\n * survives into `translatePage()` output.\n *\n * The distinction is invisible in normal use, but on SSR handoff there is only\n * ONE DOM: a page rendered by PHP and then hydrated by a JS SDK is walked by\n * both implementations, so this tokenizer has to recognise PHP's marker or it\n * re-tokenizes a subtree PHP deliberately kept whole. Recognising both is\n * additive — `data-langsys-phrase` never appears in DOM our components emit.\n */\n\n\n/**\n * True when an element is marked as a self-managed phrase by either SDK.\n *\n * Presence alone means intent, like any boolean HTML attribute — but an\n * explicit `=\"false\"` or `=\"0\"` opts OUT, compared after trimming. Mirrors\n * `langsys-php`'s `isPhraseMarked()` exactly (same method name in both SDKs,\n * so the correspondence is checkable at a glance). Without the opt-out we\n * would skip a subtree the author had deliberately un-marked, and it would\n * then be translated by neither SDK.\n */\nexport function isPhraseMarked(element: Element): boolean {\n return PHRASE_MARKER_ATTRS.some((attr) => {\n if (!element.hasAttribute(attr)) return false;\n const value = (element.getAttribute(attr) ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n });\n}\n\n/**\n * True when an element is a content-block host: it carries `data-ls-contentblock` or PHP's\n * `data-langsys-contentblock` with any value other than `false` or `0` (MARK-3). A stamped id\n * and a bare declaration both count; `false` and `0` opt out, trimmed and case-insensitive —\n * the convention every marker attribute in the fleet shares.\n *\n * Such an element is a unit of its own, so an enclosing walk excises it (MARK-4): it\n * contributes no tokens to the enclosing block, the enclosing render does not write into it,\n * and it does not count toward the enclosing unit's single text node.\n */\nexport function isContentBlockMarked(element: Element): boolean {\n return readContentBlockMarker(element) !== null;\n}\n\n/** What a content-block marker says (MARK-3), or null for no marker or an opt-out. */\nexport type ContentBlockMarker = { kind: 'declaration' } | { kind: 'identity'; id: string };\n\n/** The values that declare a block rather than name one. No md5 `custom_id` is one of these words. */\nconst DECLARATION_VALUES = ['', 'true', '1', 'yes'];\n\n/**\n * Read a content-block marker in either spelling (MARK-2, MARK-3), its value\n * trimmed and compared case-insensitively:\n *\n * - bare, empty, `true`, `1` or `yes` declares a block: register this element as\n * one block under the id its tokens derive;\n * - `false` or `0` opts out, and the element is ordinary markup (null);\n * - anything else is an identity: the `custom_id` a renderer stamped (MARK-1),\n * under which the host renders and registers nothing.\n *\n * The canonical spelling is read first, and an opted-out spelling does not hide\n * the other one.\n */\nexport function readContentBlockMarker(element: Element): ContentBlockMarker | null {\n for (const attr of CONTENT_BLOCK_MARKER_ATTRS) {\n if (!element.hasAttribute(attr)) continue;\n const value = (element.getAttribute(attr) ?? '').trim();\n const lower = value.toLowerCase();\n if (lower === 'false' || lower === '0') continue;\n return DECLARATION_VALUES.includes(lower) ? { kind: 'declaration' } : { kind: 'identity', id: value };\n }\n return null;\n}\n\n/** The attributes a nested host names its own category with, canonical first. */\nexport const CATEGORY_MARKER_ATTRS = ['data-ls-category', 'data-langsys-category'];\n\n/** A host's own category, from `data-ls-category` (or `data-langsys-category`), or null. */\nexport function hostCategory(element: Element): string | null {\n for (const attr of CATEGORY_MARKER_ATTRS) {\n const value = element.getAttribute(attr);\n if (value !== null) return value.trim();\n }\n return null;\n}\n\n/**\n * True when an element sits inside a scope a producer marked as already resolved.\n *\n * Inherited, and the NEAREST marked ancestor decides — so a document marked at `<html>`\n * can be opted back out of on a subtree with `=\"false\"` or `=\"0\"`. That inheritance is\n * what makes the attribute usable at all on the paths that need it: text a server printed\n * inline has no element of its own to carry a marker, so the only place a producer can\n * state the fact is an ancestor it does own, usually the document root.\n *\n * Both spellings are read (MARK-2), and the first marked ancestor's value decides even if\n * an outer one disagrees.\n */\nexport function isInResolvedScope(element: Element | null | undefined): boolean {\n let el: Element | null = element ?? null;\n while (el) {\n for (const attr of RESOLVED_MARKER_ATTRS) {\n if (!el.hasAttribute(attr)) continue;\n const value = (el.getAttribute(attr) ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n }\n el = el.parentElement;\n }\n return false;\n}\n\nexport const VALUE_TRANSLATABLE_ELEMENTS = ['button'];\nexport const VALUE_TRANSLATABLE_INPUT_TYPES = ['submit', 'button'];\n\n/**\n * Semantic CSS properties captured on the cloned content so translators\n * in the Translation Manager see the content styled the way end-users do.\n */\nexport const SEMANTIC_STYLE_PROPERTIES = [\n 'font-size', 'font-weight', 'font-style', 'font-variant', 'line-height',\n 'letter-spacing', 'word-spacing', 'text-align', 'text-decoration',\n 'text-transform', 'text-indent', 'text-shadow', 'white-space', '-webkit-font-smoothing',\n 'color', 'background-color', 'background-image', 'background-position',\n 'background-size', 'background-repeat',\n 'border', 'border-top', 'border-right', 'border-bottom', 'border-left',\n 'border-radius', 'border-color', 'border-width', 'border-style',\n 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',\n 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',\n 'box-shadow', 'opacity', 'filter',\n 'display', 'visibility', 'list-style', 'list-style-type',\n 'cursor',\n];\n\n\n/**\n * True iff the local translations cache already has the content block\n * for the given `(category, customId)` — meaning the backend knows about\n * it and there's no need to re-register.\n *\n * The cache is keyed under `'__uncategorized__'` for null/empty categories,\n * matching the convention the server uses in its GET /translations response.\n */\nexport function isContentBlockKnown(category: string, customId: string): boolean {\n const cats = activeCatalog();\n const lookupCat = category || '__uncategorized__';\n const cbData = cats[lookupCat]?.[customId];\n return typeof cbData === 'object' && cbData !== null;\n}\n\n/**\n * Resolve a content block under a historical id, verified on content.\n *\n * Walks `candidates` (from `historicalCustomIds`, most likely first) and returns the\n * first id whose stored block holds this block's phrases. A stored block whose\n * phrases differ is a collision, not a match, and is declined. A block cached by\n * this session's own registration is `{}` with no phrases to compare, so it can\n * never be verified and is declined as well.\n *\n * The failure direction is deliberate (CID-4): a false positive attaches the wrong\n * text, while a false negative silently restores nothing and looks like \"this block\n * had no legacy id\". So both outcomes are logged when debug is on, matching\n * langsys-python.\n */\nexport function resolveHistoricalBlockId(\n category: string,\n candidates: readonly string[],\n tokens: readonly string[]\n): string | null {\n const bucket = activeCatalog()[category || '__uncategorized__'] as unknown as Record<string, unknown> | undefined;\n if (!bucket) return null;\n for (const id of candidates) {\n const stored = bucket[id];\n if (typeof stored !== 'object' || stored === null) continue;\n if (!blockContentMatches(Object.keys(stored), tokens)) {\n if (configStore.debug) {\n logger.log(\n `Historical content-block id ${id} resolved to a block whose phrases differ; declining it ` +\n 'rather than attaching to the wrong text.'\n );\n }\n continue;\n }\n if (configStore.debug) {\n logger.log(\n `Content block resolved under a historical id (${id}). Its translations still apply; it is never ` +\n 're-keyed and never registered under that id.'\n );\n }\n return id;\n }\n return null;\n}\n\n/**\n * Why a registration did not reach the server, or did not take (REG-10).\n *\n * - `not-configured`: the client has no credentials, so nothing can be sent\n * (WIRE-4);\n * - `not-write-enabled`: the session may not write, so the block was handed to\n * the discovery lane instead;\n * - `catalog-unavailable`: the catalog fetch failed, so an unknown block cannot\n * be told from a registered one (WIRE-4);\n * - `base-locale-gate`: the project registers only at its base locale (GATE-9);\n * - `deferred`: the block was found inside a request scope, which holds it for its\n * flush after the response (SRV-3, SRV-7);\n * - `client-strategy`: the SSR token strategy leaves collection to the client\n * (SSR-1), or a write grant made capability per-user (SSR-2);\n * - `refused`: the server answered the request with a failure;\n * - `failed`: the request did not complete.\n */\nexport type RegistrationReason =\n | 'not-configured'\n | 'not-write-enabled'\n | 'catalog-unavailable'\n | 'base-locale-gate'\n | 'deferred'\n | 'client-strategy'\n | 'refused'\n | 'failed';\n\n/**\n * What a registration did. Success only when the server stored the block. A\n * write skipped on purpose is `{ status: false, skipped: true, reason }`, and one\n * that failed is `{ status: false, reason, errors }`, so a caller can tell them\n * apart and neither reads as success.\n */\nexport type RegistrationResult =\n | { status: true }\n | { status: false; skipped: true; reason: 'not-configured' | 'not-write-enabled' | 'catalog-unavailable' | 'base-locale-gate' | 'deferred' | 'client-strategy' }\n | { status: false; skipped?: false; reason: 'refused' | 'failed'; errors?: unknown[] };\n\n/** Resolves once the session's write capability is known: `writeEnabled` is true or false. */\nfunction capabilityKnown(): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n let unsubscribe: (() => void) | null = null;\n unsubscribe = writeEnabled.subscribe((value) => {\n if (value === undefined || settled) return;\n settled = true;\n resolve();\n queueMicrotask(() => unsubscribe?.());\n });\n });\n}\n\n/** Each block's registration request while it is unanswered, by the credentials it went out under, its category and its id. */\nconst registrationsInFlight = new Map<string, Promise<RegistrationResult>>();\n\n/**\n * POST a content block to the backend, then stamp its custom_id into the local\n * translations cache, so later mounts in this session, and later reloads since\n * the cache is persisted, skip the POST.\n *\n * A block has one request in flight at a time under one set of credentials\n * (REG-7). A call for a block whose request has not answered yet resolves with\n * that request's result and sends nothing: a binding calls `registerBlock` on\n * every change `t` goes through, and a page load makes several of those before\n * the first request returns. Once it answers, the block is known, or, refused or\n * failed, may be sent again. A request answers only for the project and key it\n * went out under, so a call under others, after a re-init, sends its own.\n *\n * One behaviour on every path (REG-10): never throws, always logs, and never\n * reports success for work that did not happen. A skipped write returns a\n * non-success result naming its reason.\n */\nexport async function registerContentBlock(contentBlock: iContentBlock): Promise<RegistrationResult> {\n // WIRE-4: a client without credentials reports the skipped write rather than throwing,\n // because a component reaches this and a component path never throws.\n // A scope with credentials of its own is configured whatever the module is (SRV-2).\n const scope = activeScope();\n if (configured.get() === false && !scope?.credentials) return { status: false, skipped: true, reason: 'not-configured' };\n\n // Inside a request scope (SRV-7) nothing is sent on the request path: the scope holds\n // the block and its close() decides, after the response, whether to send it (SRV-3).\n if (scope) {\n scope.recordBlock(contentBlock);\n return { status: false, skipped: true, reason: 'deferred' };\n }\n\n // WIRE-4. After a failed catalog fetch every block looks unregistered, because\n // there is no catalog to find it in. Registering on that basis re-POSTs blocks\n // the backend already holds, on every page an outage touches. Record nothing,\n // on either lane: a discovery miss for a block that may well be registered is\n // the same mistake made read-only.\n if (catalogUnavailable.get()) {\n if (configStore.debug) {\n logger.log('Skipping content block registration: the catalog fetch failed, so an unknown block cannot be told from a registered one', {\n custom_id: contentBlock.custom_id,\n });\n }\n return { status: false, skipped: true, reason: 'catalog-unavailable' };\n }\n\n // GATE-9 on the content-block path, as on the `t()` miss path: with the project setting\n // on, a block is neither registered nor reported unless the loaded locale is the base\n // locale. Before the first catalog publishes, the locale being requested stands in.\n if (discoveryBaseLocaleOnly.get()) {\n const loaded = currentlyLoadedLocale.get() || canonicalizeLocale(configStore.sUserLocale?.get() ?? '');\n if (loaded !== canonicalizeLocale(configStore.baseLocale || '')) {\n if (configStore.debug) {\n logger.log('Skipping content block: discovery is limited to the base locale', { custom_id: contentBlock.custom_id, loaded });\n }\n return { status: false, skipped: true, reason: 'base-locale-gate' };\n }\n }\n\n // GATE-2: in the browser, a capability not known yet is not a refusal. A block\n // mounted before `init()` answers (a hydrated page seeds its catalog, which\n // settles `ready()`, and components mount before the app initialises) waits for\n // the server's answer, then decides every gate again. Under SSR the signal is\n // never written, and the SSR strategies decide there.\n if (writeEnabled.get() === undefined && typeof window !== 'undefined' && !LangsysAppAPI.hasWriteGrant()) {\n await capabilityKnown();\n return registerContentBlock(contentBlock);\n }\n\n // Server-computed capability, never inferred from `key_type`. This is the\n // lane the discovery renderer depends on most: it exists for dynamic\n // content, which is disproportionately content blocks rather than bare\n // `t()` calls, and it runs with an `ip_write` key that a\n // `key_type === 'write'` test would have rejected outright.\n if (writeEnabled.get() !== true) {\n // Hand the page to the discovery lane instead of dropping it.\n //\n // Without this, a page whose untranslated content lives entirely in\n // multi-token `Translate` blocks is invisible to discovery: those\n // tokens resolve through `lookupContent`, which registers nothing, so\n // they never reach `t()` and never reach the miss recorder. The block\n // was only discovered when some unrelated `t()` call happened to miss\n // on the same page — and content blocks are disproportionately what the\n // renderer exists to find, so the gap was worst where it mattered most.\n //\n // Carries no phrase payload: the recorder takes the block's identity\n // only to dedup, and the hint itself is URL-only.\n recordMissForDiscovery(contentBlock.category, contentBlock.custom_id);\n\n if (configStore.debug) {\n logger.log('Skipping content block save (session is not write-enabled)', {\n writeEnabled: writeEnabled.get(),\n key_type: configStore.key_type || 'unknown',\n });\n }\n return { status: false, skipped: true, reason: 'not-write-enabled' };\n }\n\n const credentials = LangsysAppAPI.moduleCredentials();\n const key = [credentials.projectid, credentials.key, contentBlock.category, contentBlock.custom_id].join('\\0');\n const inFlight = registrationsInFlight.get(key);\n if (inFlight) return inFlight;\n const request = sendContentBlock(contentBlock, credentials).finally(() => registrationsInFlight.delete(key));\n registrationsInFlight.set(key, request);\n return request;\n}\n\n/** The registration request itself: success only once the server stored the block, under the credentials it went out under. */\nasync function sendContentBlock(contentBlock: iContentBlock, credentials: ApiCredentials): Promise<RegistrationResult> {\n try {\n // The page's lane, under the page's key (SRV-2): a scope holds its blocks for close().\n const response = await LangsysAppAPI.createTranslatableItems(\n [\n {\n type: 'content_block',\n custom_id: contentBlock.custom_id,\n category: contentBlock.category,\n content: contentBlock.content,\n label: contentBlock.label,\n phrases: contentBlock.tokens.map((phrase) => ({ phrase })),\n },\n ],\n { credentials }\n );\n if (!response.status) {\n logger.error('Could not save content block', response.errors);\n return { status: false, reason: 'refused', errors: response.errors as unknown[] | undefined };\n }\n // The answer is the project's that the request went out under. After a re-init under\n // others, the catalog held now is theirs, and they do not hold the block.\n const current = LangsysAppAPI.moduleCredentials();\n if (current.projectid === credentials.projectid && current.key === credentials.key) _writeKnownContentBlockToCache(contentBlock.category, contentBlock.custom_id);\n return { status: true };\n } catch (err) {\n logger.error('Could not save content block', err);\n return { status: false, reason: 'failed', errors: [err] };\n }\n}\n\n/**\n * Walk an `HTMLElement`, collecting tokens for translation and producing a\n * cloned-and-stylized snapshot of its content for the Translation Manager.\n *\n * Tokens harvested:\n * - text-node content (whitespace-normalized, trimmed)\n * - translatable attribute values (`placeholder`, `alt`, `title`, `aria-*`, etc.)\n * - button/input/select value text\n *\n * Skips subtrees marked with `translate=\"no\"`.\n *\n * The returned `content` is a string snapshot of the element's children, as the\n * tree path registers a block's nodes: the host is the unit, not part of its\n * content. The live element is not mutated. Computed semantic styles (color,\n * font, spacing, etc.) are inlined onto the clone so translators see content\n * styled the way end-users do. It holds no value and no nested unit's content\n * (`scrubContent`).\n *\n * Requires that `element` is mounted in the document so `getComputedStyle`\n * can read its style. For SSR / pre-mount callers, the style capture step\n * silently no-ops and the snapshot is plain (without inlined styles).\n */\nexport function tokenizeElement(element: HTMLElement): { tokens: string[]; content: string; vars: UnitVars } {\n const tokens: string[] = [];\n const vars: UnitVars = { values: {}, runs: [], markerOnly: [] };\n const clone = element.cloneNode(true) as HTMLElement;\n _walkForTokens(element, Array.from(clone.childNodes), tokens, [], false, true, undefined, vars);\n scrubContent(clone.childNodes as unknown as ArrayLike<MarkerNode>, {\n empty: (host) => (host as unknown as Element).replaceChildren(),\n replace: (_siblings, nodes, text) => {\n const first = nodes[0] as unknown as ChildNode;\n first.parentNode!.insertBefore(first.ownerDocument!.createTextNode(text), first);\n for (const node of nodes) (node as unknown as ChildNode).remove();\n },\n });\n return { tokens, content: normalizeMarkupPlaceholders(clone.innerHTML), vars };\n}\n\n/** How `scrubContent` edits a copy of a unit's content, on the DOM or on a tree's view. */\nexport interface ContentEdits<N> {\n /** Remove an element's children. */\n empty(host: N): void;\n /** Put one text node holding `text` where `nodes`, consecutive among `siblings`, are. */\n replace(siblings: ArrayLike<N>, nodes: N[], text: string): void;\n}\n\n/**\n * Rewrite a copy of a unit's content into the `content` it registers with. Each\n * marked run becomes one text node, the run's text with `{NAME}` where each value\n * was, the marker and the value gone, whichever form marked it and wherever it\n * sits, inside a `translate=\"no\"` element included (VAR-1, VAR-3). A nested\n * phrase or block host keeps its element and attributes and loses its content\n * (MARK-4): it is a unit of its own, and what it shows is rendered, with its own\n * values.\n */\nexport function scrubContent<N extends MarkerNode>(nodes: ArrayLike<N>, edit: ContentEdits<N>): void {\n for (const item of groupRuns(nodes)) {\n if ('run' in item) {\n edit.replace(nodes, runNodes(item.run), runSource(item.run));\n continue;\n }\n if (item.node.nodeType !== ELEMENT_NODE) continue;\n const element = item.node as unknown as Element;\n if (isPhraseMarked(element) || isContentBlockMarked(element)) edit.empty(item.node);\n else scrubContent(item.node.childNodes as ArrayLike<N>, edit);\n }\n}\n\n/**\n * The token list this element would have produced before 0.6.3, when every\n * `<option>`'s text was harvested twice — once by a `<select>` special case and\n * again by the ordinary text-node walk.\n *\n * **Lookup only.** Content blocks registered by an older SDK are keyed by an id\n * derived from this list, so `Translate` falls back to it when the corrected id\n * misses; without that, every block containing a `<select>` would silently\n * re-key and lose its translations on upgrade. Registration always uses the\n * corrected list, so the legacy-keyed population can only shrink.\n *\n * Skips the computed-style capture that `tokenizeElement` performs — this is a\n * cache-key computation, not a snapshot for translators.\n *\n * @deprecated Migration aid; will be removed once catalogs have been rebased.\n */\nexport function legacyTokenizeElement(element: HTMLElement): string[] {\n const tokens: string[] = [];\n const clone = element.cloneNode(true) as HTMLElement;\n _walkForTokens(element, Array.from(clone.childNodes), tokens, [], true, false);\n return tokens;\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nfunction _writeKnownContentBlockToCache(category: string, customId: string): void {\n const lookupCat = category || '__uncategorized__';\n sTranslations.update((current) => {\n if (!current[lookupCat]) {\n current[lookupCat] = {\n __category__: lookupCat,\n __symbol__: lookupCat,\n } as iTranslations;\n }\n // The record says only that the server holds the block. A catalog published while the\n // request was out, a locale switch's, may already hold it with its translations, and\n // the record never replaces them.\n const bucket = current[lookupCat] as unknown as Record<string, unknown>;\n if (typeof bucket[customId] === 'object' && bucket[customId] !== null) return current;\n bucket[customId] = {};\n return { ...current };\n });\n}\n\n/**\n * IDENTITY CONTRACT — one token per text node. Do not coalesce.\n *\n * `generateCustomId` hashes `JSON.stringify([category, tokens])`, so the\n * ARITY of the token array is load-bearing, not just its concatenated text.\n * Three adjacent text nodes and one merged node with the same characters are\n * DIFFERENT content blocks.\n *\n * That makes \"merge adjacent text nodes before tokenizing\" — a `normalize()`\n * call, or a textual comment-strip that closes the gap between two runs — a\n * breaking change to a wire value shared by every Langsys SDK, disguised as a\n * tidy-up. It reviews well, passes any test that asserts on rendered output,\n * and silently re-keys every catalog in existence.\n *\n * Frameworks routinely split one authored sentence across several text nodes,\n * and — this is the part that makes the contract unconditional — **each one\n * gets there by a different route.** React renders `Hello {name}!` as three\n * nodes separated by `<!-- -->` comments that survive hydration (measured\n * here, `tests/content-block-identity.test.ts`). Svelte does NOT split on\n * interpolation — a contiguous run compiles to one text node updated via\n * `set_text` — but reaches the same exposure through block constructs, where\n * `{#each}` splits a run into separate nodes (measured by the Svelte\n * binding, not re-run here). Vue's mechanism is not known.\n *\n * So do not scope this contract to a framework, and do not conclude from one\n * binding's behaviour that coalescing is safe \"for the others\". Checking only\n * interpolation in Svelte would say Svelte is unaffected; checking `{#each}`\n * says otherwise. The invariant is about the token array, not about any\n * renderer.\n *\n * The comment handling below is part of the same contract. A comment is\n * neither `TEXT_NODE` nor `ELEMENT_NODE`, so the walk steps over it\n * structurally while leaving the text either side as separate nodes. Skip\n * comments by walking, never by regexing the HTML.\n *\n * SCOPE — this governs `_walkForTokens` and nothing else. The SDK has TWO\n * identity mechanisms with deliberately OPPOSITE text handling:\n *\n * `_walkForTokens` (Translate / content-block path) one token per text\n * node, never coalesced. Arity is identity.\n * `encodeRichText` (Phrase path, `src/richtext.ts`) adjacent text nodes\n * ARE concatenated and whitespace collapsed, into one phrase string.\n * That string is the key — there is no token array and no `custom_id`\n * on that path at all.\n *\n * Coalescing is the bug here and the requirement there. State the scope,\n * because the realistic failure is not someone getting `<Phrase>` wrong on\n * its own terms — it is someone who has just READ this contract finding\n * `encodeRichText` concatenating adjacent text, recognising it as the exact\n * defect they were warned about, and \"fixing\" it. A rule memorable enough to\n * be worth writing down is memorable enough to be misapplied to the wrong\n * path.\n *\n * Pinned by `tests/content-block-identity.test.ts`, which is mutation-checked:\n * adding `clone.normalize()` to `tokenizeElement` turns three of those tests\n * red. If you are here because one of them failed, the pinned literal is not\n * the thing to update — see `generateLegacyCustomId` for what an id change\n * actually costs.\n */\n/**\n * Whether an element and everything inside it are left out of the unit being\n * walked: an author's `translate=\"no\"` or `data-notrans`, code and notation\n * (`NON_TRANSLATABLE_ELEMENTS`), a phrase host (its own rich phrase) and a nested\n * content-block host (a unit of its own, MARK-4).\n *\n * The one predicate for \"not this unit's text\". The tokenizer skips these, and\n * so must every question asked about the same unit afterwards — whether its one\n * token is its one text node (TOK-6), where a translation is written — or the\n * two disagree about the unit's shape and it registers under the wrong one.\n */\nexport function isExcisedFromUnit(el: Element): boolean {\n return (\n isTranslationExcluded(el) ||\n NON_TRANSLATABLE_ELEMENTS.includes(el.tagName.toLowerCase()) ||\n isPhraseMarked(el) ||\n isContentBlockMarked(el)\n );\n}\n\n// Node types by number, not `Node.*`: the walk runs on a server too, over trees\n// shaped like the DOM (see `block-tree.ts`), where there is no `Node` global.\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n\n/** The node shape the walks need: the DOM's, or a tree's that imitates it. */\nexport interface WalkNode {\n nodeType: number;\n nodeValue: string | null;\n childNodes: ArrayLike<WalkNode>;\n hasChildNodes(): boolean;\n}\n\n/**\n * The tokens of a unit's content, with no DOM required: `nodes` are the unit's\n * children, DOM nodes or anything shaped like them. The same walk as\n * `tokenizeElement`, without the style snapshot, so a tree and the DOM it\n * mirrors yield the same tokens and the same id.\n */\nexport function tokenizeNodes(nodes: ArrayLike<WalkNode>, duplicateSelectOptions = false): string[] {\n const tokens: string[] = [];\n _walkForTokens(null as unknown as HTMLElement, Array.from(nodes) as unknown as ChildNode[], tokens, [], duplicateSelectOptions, false);\n return tokens;\n}\n\n/** What the walk learns from value markers (VAR-3), alongside the tokens. */\nexport interface UnitVars {\n /** Each marker's value, by name: the params the unit renders with, unless the caller names them. */\n values: Record<string, string>;\n /** The indices of tokens that are marked runs. */\n runs: number[];\n /** The indices of tokens made only of markers, with no text of their own. */\n markerOnly: number[];\n}\n\n/**\n * The tokens of a unit and what its value markers say (VAR-3): the same walk as\n * `tokenizeNodes`, reporting which tokens came from marked runs and each\n * marker's value.\n */\nexport function tokenizeUnit(nodes: ArrayLike<WalkNode>): { tokens: string[]; vars: UnitVars } {\n const tokens: string[] = [];\n const vars: UnitVars = { values: {}, runs: [], markerOnly: [] };\n _walkForTokens(null as unknown as HTMLElement, Array.from(nodes) as unknown as ChildNode[], tokens, [], false, false, undefined, vars);\n return { tokens, vars };\n}\n\n/** A unit made only of markers has no text of its own, and registers nothing (VAR-3). */\nexport function isMarkerOnlyUnit(tokens: readonly string[], vars: UnitVars): boolean {\n return tokens.length > 0 && vars.markerOnly.length === tokens.length;\n}\n\n/** Where a unit's token sits: a text node, an attribute of an element, or a marked run (VAR-3). */\nexport type TokenSlot =\n | { node: Node; attr?: undefined; run?: undefined }\n | { node: Element; attr: string; run?: undefined }\n | { node: Node; run: VarRun<Node>; attr?: undefined };\n\n/**\n * The places a unit's tokens come from, one per token and in token order: the\n * same walk as `tokenizeNodes`, so the i-th slot holds the i-th token. What lets\n * a reader pair a block's served text with the source tokens it was rendered from.\n */\nexport function tokenSlots(nodes: ArrayLike<Node>): TokenSlot[] {\n const slots: TokenSlot[] = [];\n _walkForTokens(null as unknown as HTMLElement, Array.from(nodes) as ChildNode[], [], [], false, false, slots);\n return slots;\n}\n\n/**\n * The unit's one non-whitespace text node, or null when it has none or more\n * than one (TOK-6). What the tokenizer leaves out of the unit (`isExcisedFromUnit`)\n * is not the unit's text, so it neither counts nor is searched.\n */\nexport function findSingleTextNode<N extends WalkNode>(root: { childNodes: ArrayLike<N> }): N | null {\n let found: N | null = null;\n const walk = (parent: { childNodes: ArrayLike<N> }): boolean => {\n for (const child of Array.from(parent.childNodes)) {\n if (child.nodeType === TEXT_NODE) {\n if (normalizeTokenText(child.nodeValue ?? '')) {\n if (found) return false;\n found = child;\n }\n } else if (child.nodeType === ELEMENT_NODE && isExcisedFromUnit(child as unknown as Element)) {\n continue;\n } else if (!walk(child as unknown as { childNodes: ArrayLike<N> })) {\n return false;\n }\n }\n return true;\n };\n return walk(root) ? found : null;\n}\n\nfunction _walkForTokens(\n liveRoot: HTMLElement,\n cloneNodes: ChildNode[],\n tokens: string[],\n indices: number[],\n duplicateSelectOptions: boolean,\n applyStyles: boolean,\n slots?: TokenSlot[],\n vars?: UnitVars,\n): void {\n for (const item of groupRuns(cloneNodes as unknown as MarkerNode[]) as unknown as RunItem<ChildNode>[]) {\n if ('run' in item) {\n // A marked run is one token, `{NAME}` in place of each value (VAR-3).\n const token = runToken(item.run);\n if (vars) {\n if (isMarkerOnly(item.run)) vars.markerOnly.push(tokens.length);\n vars.runs.push(tokens.length);\n vars.values = { ...runValues(item.run), ...vars.values };\n }\n tokens.push(token);\n const first = item.run.parts[0]!;\n slots?.push({ node: 'text' in first ? first.text : first.marker.frame[0]!, run: item.run as unknown as VarRun<Node> });\n continue;\n }\n const node = item.node;\n const index = cloneNodes.indexOf(node);\n if (node.nodeType === ELEMENT_NODE) {\n // Code and notation are never prose (`<style>`, `<script>` and `<math>`\n // content was registered and machine-translated before this), a phrase\n // host is its own rich phrase, and a nested block host is its own unit,\n // whose words would otherwise register in both blocks. See\n // `isExcisedFromUnit` and `NON_TRANSLATABLE_ELEMENTS`.\n if (isExcisedFromUnit(node as HTMLElement)) continue;\n }\n\n if (applyStyles && node.hasChildNodes()) {\n _applyStylesToClone(liveRoot, node as HTMLElement, [...indices, index]);\n }\n\n if (node.nodeType === ELEMENT_NODE) {\n _tokenizeAttributes(node as HTMLElement, tokens, duplicateSelectOptions, slots);\n }\n\n const contentToken = node.nodeValue ? normalizeTokenText(node.nodeValue) : undefined;\n if (node.nodeType === TEXT_NODE && contentToken) {\n tokens.push(normalizeMarkupPlaceholders(contentToken));\n slots?.push({ node });\n continue;\n }\n\n if (!node.hasChildNodes()) continue;\n _walkForTokens(liveRoot, Array.from(node.childNodes), tokens, [...indices, index], duplicateSelectOptions, applyStyles, slots, vars);\n }\n}\n\nfunction _tokenizeAttributes(element: HTMLElement, tokens: string[], duplicateSelectOptions: boolean, slots?: TokenSlot[]): void {\n const tagName = element.tagName.toLowerCase();\n\n // On a clone only: `tokenSlots` walks the live DOM, which a token read never writes.\n if (tagName === 'img' && !slots) {\n const img = element as HTMLImageElement;\n if (img.src) element.setAttribute('src', img.src);\n }\n\n // `normalizeTokenText`, not `.trim()`. Attributes used to keep their\n // internal whitespace while text nodes collapsed theirs, so the same\n // authored sentence produced two different ids depending on where it sat —\n // and put this SDK on different ids from langsys-php for the same markup.\n const push = (attr: string) => {\n const value = normalizeTokenText(element.getAttribute(attr) ?? '');\n if (!value) return;\n tokens.push(normalizeMarkupPlaceholders(value));\n slots?.push({ node: element, attr });\n };\n for (const attr of TRANSLATABLE_ATTRIBUTES) push(attr);\n\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tagName)) push('value');\n\n if (tagName === 'input') {\n const inputType = element.getAttribute('type')?.toLowerCase();\n if (inputType && VALUE_TRANSLATABLE_INPUT_TYPES.includes(inputType)) push('value');\n }\n\n // <option> text is NOT harvested here in the current path: it arrives via\n // the ordinary text-node walk, since `<option>` cannot contain elements.\n // Doing both pushed every option's text TWICE, changing the token list and\n // therefore the block's `custom_id`. langsys-php reached the same\n // conclusion earlier — their `extractSelectOptions()` is an empty stub\n // with a comment saying so — and their token lists are the reference.\n //\n // The duplicate is reproduced ONLY for `legacyTokenizeElement`, so blocks\n // registered before 0.6.3 stay resolvable. `<optgroup label>` reaches us\n // through TRANSLATABLE_ATTRIBUTES either way.\n if (duplicateSelectOptions && tagName === 'select') {\n const options = element.querySelectorAll('option');\n options.forEach((option) => {\n const optionText = normalizeTokenText(option.textContent ?? '');\n if (optionText) tokens.push(normalizeMarkupPlaceholders(optionText));\n });\n }\n}\n\nfunction _applyStylesToClone(liveRoot: HTMLElement, cloneNode: HTMLElement, indices: number[]): void {\n if (typeof window === 'undefined') return;\n const domNode = _findNode(Array.from(liveRoot.childNodes), indices);\n if (!domNode) return;\n\n // The defaults are a bare element of the same tag, carrying no style of its own:\n // a hidden or positioned reference would differ from every element on the\n // properties it sets (`visibility`, and `display`, which absolute positioning\n // turns to `block`), so each would be inlined everywhere. Its container is\n // `display: none`, which keeps it out of the layout and leaves its own computed\n // `display` and `visibility` the tag's defaults.\n const tagName = (domNode as HTMLElement).tagName.toLowerCase();\n const container = document.createElement('div');\n container.style.display = 'none';\n const reference = container.appendChild(document.createElement(tagName));\n document.body.appendChild(container);\n\n const computed = window.getComputedStyle(domNode as HTMLElement);\n const defaults = window.getComputedStyle(reference);\n\n for (const prop of SEMANTIC_STYLE_PROPERTIES) {\n const value = computed.getPropertyValue(prop);\n const defaultValue = defaults.getPropertyValue(prop);\n if (value && value !== defaultValue) {\n cloneNode.style.setProperty(prop, value);\n }\n }\n\n document.body.removeChild(container);\n cloneNode.removeAttribute('class');\n}\n\nfunction _findNode(nodes: ChildNode[], indices: number[]): Element | undefined {\n let currentNode: Node | undefined = nodes[indices[0]];\n for (let i = 1; i < indices.length; i++) {\n if (!currentNode || !currentNode.hasChildNodes()) return undefined;\n currentNode = Array.from(currentNode.childNodes)[indices[i]];\n }\n return currentNode as Element;\n}\n","/**\n * Rich-text (markup-bearing) phrase encoding for the `<Phrase>` artifact.\n *\n * The problem: a phrase like `You have {n} <strong>reviews</strong>` must stay\n * ONE phrase (so pluralization sees `{n}` next to `reviews`), but we must NOT\n * send the SPA's real markup — and especially not framework-internal scoped-CSS\n * classes (`svelte-a1b2c3`, Vue scoped hashes) — to the translator. Those\n * classes get mangled, and worse they change on every build, which would make\n * the phrase key drift and silently re-translate everything.\n *\n * The approach: replace each inline element with a pair of neutral MARKUP\n * TOKENS — `{m0o}` ... `{m0c}` (markup, slot 0, open/close). These are ordinary\n * ICU placeholders: valid MessageFormat argument names, so plural/select still\n * parse, and the model treats them like `{n}` — it preserves them and PLACES\n * them around the translated word (which is what fixes reordering languages,\n * e.g. `<span>White</span> House` -> `Casa <span>Blanca</span>`).\n *\n * The real DOM elements never leave the SDK. At render time we resolve the\n * translation, substitute each markup token with a private-use SENTINEL char\n * (transient — never sent anywhere), then reconstitute the DOM by wrapping the\n * sentinel-delimited spans in the ORIGINAL framework-owned elements. Scoped CSS\n * survives because we reuse the real element; the phrase key is stable because\n * the wire form only ever contains `{m0o}`/`{m0c}`, never build-specific hashes.\n */\n\n// Private-use (PUA) sentinel delimiters, written via char codes so no literal\n// PUA characters live in the source. Brace-free so ICU MessageFormat treats a\n// substituted sentinel as literal text. They exist only transiently at render —\n// never registered, never sent over the wire (the wire form uses {mNo}/{mNc}).\n// open(i) = U+E000 <i> U+E001\n// close(i) = U+E002 <i> U+E003\nimport { encodeRichPhrase, isOpaqueInPhrase, isTranslationExcluded, NON_TRANSLATABLE_ELEMENTS } from './identity.js';\nimport { interpolate } from './interpolate.js';\nimport { earlierRichPhrase, paramElementName, toRichNodes, type MarkerNode } from './var-markers.js';\n\nconst SENT_OPEN_START = String.fromCharCode(0xe000);\nconst SENT_OPEN_END = String.fromCharCode(0xe001);\nconst SENT_CLOSE_START = String.fromCharCode(0xe002);\nconst SENT_CLOSE_END = String.fromCharCode(0xe003);\n\n/** Matches an open marker (group 1 = slot index) or a close marker (group 2 = slot index). */\nconst SENT_SCAN = /\\uE000(\\d+)\\uE001|\\uE002(\\d+)\\uE003/g;\n\n/** A captured inline element: a shallow clone (tag + attributes, no children). */\nexport interface RichSlot {\n /** Shallow clone of the original element — preserves tag, class, href, etc. */\n template: HTMLElement;\n /**\n * For an element opaque in the phrase (TOK-1), the element itself: it renders its\n * own content as given, so reconstitution moves it rather than a copy, and what a\n * framework renders inside it stays the framework's.\n */\n source?: HTMLElement;\n}\n\nexport interface EncodedRichText {\n /**\n * The phrase string with inline elements replaced by `{mNo}`...`{mNc}` markup\n * tokens. This is what gets registered + sent for translation.\n */\n phrase: string;\n /** Captured inline elements, indexed by markup-token slot number. */\n slots: RichSlot[];\n /** Each marked value, by name (VAR-3): the params the phrase renders with, unless the caller names them. */\n values: Record<string, string>;\n /**\n * For a phrase holding an opaque element, the key it was registered under before\n * TOK-1 bound this path, with that key's slots and values: looked up on a miss for\n * `phrase`, never registered.\n */\n earlier?: { phrase: string; slots: RichSlot[]; values: Record<string, string> };\n}\n\n/**\n * Walk an element's subtree and produce the encoded phrase + captured slots.\n *\n * Text nodes contribute their (whitespace-collapsed) text. Each child element\n * becomes a markup-token pair wrapping its recursively-encoded contents, and a\n * shallow clone of the element is captured as a slot. Nesting is preserved.\n *\n * COALESCING ADJACENT TEXT NODES IS CORRECT HERE — do not \"fix\" it.\n *\n * `_encodeNodes` concatenates adjacent text nodes and this function collapses\n * whitespace, producing ONE phrase string. That string is the lookup key:\n * `Phrase` calls `Translations.t(phrase, category)` and never computes a\n * `custom_id`. A sentence must survive the round trip whole — that is the\n * entire reason `<Phrase>` exists, since splitting `Based on {n}\n * <strong>reviews</strong>` into fragments makes correct agreement impossible\n * in languages with more than two plural forms.\n *\n * The `_walkForTokens` contract in `content-block.ts` says the OPPOSITE, for\n * the content-block path, where token-array arity is identity. Both are right\n * for their own path. If you arrived here from that comment intending to make\n * this consistent with it, the paths are not meant to agree.\n *\n * Pinned by `tests/content-block-identity.test.ts` (\"Phrase path\"), which\n * fails if this coalescing is removed.\n */\nexport function encodeRichText(root: HTMLElement): EncodedRichText {\n // The encoding itself — slot numbering, whitespace collapse, `%name%`\n // normalization — is `encodeRichPhrase` in `identity.ts`, shared with every\n // host that renders `<Phrase>`. What is left here is the only DOM-shaped\n // part: turning child nodes into the host-neutral shape it walks.\n //\n // Split because the phrase string IS the catalog key. `langsys-js-server`\n // renders `<Phrase>` from parse5 nodes and had no way to import this, so the\n // alternative was a second encoder, and two encoders of one key drift into a\n // silent re-registration rather than an error.\n const values: Record<string, string> = {};\n // Shallow clone: tag + attributes, no children. Preserves the framework's\n // scoped-CSS class, which is the whole point of reusing the real element at\n // reconstitution. A marked value is its placeholder, and its value a param (VAR-3).\n // An opaque element keeps itself as its source (TOK-1).\n const slotOf = (element: MarkerNode, opaque: boolean): RichSlot => {\n const live = element as unknown as HTMLElement;\n return opaque ? { template: live.cloneNode(false) as HTMLElement, source: live } : { template: live.cloneNode(false) as HTMLElement };\n };\n const children = root.childNodes as unknown as ArrayLike<MarkerNode>;\n const { phrase, slots } = encodeRichPhrase(toRichNodes(children, slotOf, values));\n const earlier = earlierRichPhrase(children, slotOf);\n return earlier ? { phrase, slots, values, earlier } : { phrase, slots, values };\n}\n\n\n/**\n * The param values to feed alongside the user's params when resolving a rich\n * phrase. Each markup token maps to its sentinel pair so the resolved string\n * carries machine-findable delimiters for reconstitution.\n */\nexport function markupTokenValues(slotCount: number): Record<string, string> {\n const values: Record<string, string> = {};\n for (let i = 0; i < slotCount; i++) {\n values[`m${i}o`] = `${SENT_OPEN_START}${i}${SENT_OPEN_END}`;\n values[`m${i}c`] = `${SENT_CLOSE_START}${i}${SENT_CLOSE_END}`;\n }\n return values;\n}\n\n/**\n * A rich phrase interpolated with its markup tokens as sentinels (`markupTokenValues`).\n * In an ICU phrase an apostrophe before `{` quotes, so a token can come out as written;\n * it is read as its sentinel too, so its element renders and no `{mNo}` reaches the page.\n */\nexport function interpolateRich(template: string, params: Record<string, unknown>, slotCount: number, locale: string): string {\n const tokens = markupTokenValues(slotCount);\n const resolved = interpolate(template, { ...params, ...tokens }, locale);\n return resolved.replace(/\\{(m\\d+[oc])\\}/g, (whole, token: string) => tokens[token] ?? whole);\n}\n\n/**\n * Rebuild DOM nodes from a resolved string containing sentinel-delimited spans.\n *\n * The original (framework-owned) elements are reused as wrappers — so scoped\n * CSS classes / attributes survive — with the translated text placed inside.\n *\n * Robust to model mistakes: if sentinels are unbalanced (a tag dropped or a\n * stray close), we fall back to a single plain-text node (markers stripped) —\n * \"lose the markup, keep the meaning\" rather than throw.\n */\n/**\n * Split a resolved string into its text runs and markup-token opens and closes,\n * or null when they do not nest. The one reading of the sentinels, shared by\n * `applyInPlace` and `reconstitute`.\n */\nexport function splitSentinels(resolved: string): Array<{ text: string } | { open: number } | { close: number }> | null {\n const parts: Array<{ text: string } | { open: number } | { close: number }> = [];\n let depth = 0;\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n const scan = new RegExp(SENT_SCAN.source, 'g');\n while ((match = scan.exec(resolved)) !== null) {\n const text = resolved.slice(lastIndex, match.index);\n if (text) parts.push({ text });\n lastIndex = scan.lastIndex;\n if (match[1] !== undefined) {\n parts.push({ open: Number(match[1]) });\n depth++;\n } else {\n if (depth === 0) return null;\n parts.push({ close: Number(match[2]) });\n depth--;\n }\n }\n const tail = resolved.slice(lastIndex);\n if (tail) parts.push({ text: tail });\n return depth === 0 ? parts : null;\n}\n\n/**\n * Write a resolved rich phrase into the host's EXISTING nodes, when its markup\n * skeleton is the host's: the same elements, in the same nesting and order.\n * Each text run goes into the host's text node at its place, and a text node the\n * translation has nothing for is emptied. Returns false, touching nothing, when\n * the skeleton differs (a translation that reorders, adds or drops inline\n * markup), and the caller then rebuilds the host.\n *\n * In place, because a reactive framework holds references to the nodes it\n * rendered: replacing them leaves every later update writing to a detached node\n * that is no longer on the page. Only a structural change has to replace them,\n * and then those later updates are lost, which is the cost of the reorder.\n *\n * `slotOf` names the markup slot each element renders. Without it, an element's\n * slot is its place among the host's elements, which holds only while the host\n * shows the source's order: after a translation that reorders its markup, or over\n * a served translation, the elements' places are not their slots.\n */\nexport function applyInPlace(host: Node, resolved: string, slotOf?: (element: Element) => number | undefined): boolean {\n const parts = splitSentinels(resolved);\n if (!parts) return false;\n const writes: Array<[Node, string]> = [];\n let next = 0;\n let slot = 0;\n const walk = (parent: Node): boolean => {\n for (const child of Array.from(parent.childNodes)) {\n if (child.nodeType === 3) {\n const part = parts[next];\n if (part && 'text' in part) {\n writes.push([child, part.text]);\n next++;\n } else {\n writes.push([child, '']);\n }\n } else if (child.nodeType === 1 && paramElementName(child as unknown as MarkerNode) !== null) {\n // A marked value (VAR-3) is no slot: its value is in the resolved text.\n for (const text of Array.from(child.childNodes)) writes.push([text, '']);\n } else if (child.nodeType === 1) {\n const open = parts[next];\n const place = slot++;\n const index = slotOf ? slotOf(child as Element) : place;\n if (!open || !('open' in open) || open.open !== index) return false;\n next++;\n // An opaque element (TOK-1) shows its source content as given: nothing in\n // it is written, and its pair holds nothing.\n if (!isOpaqueInPhrase(child as Element) && !walk(child)) return false;\n const close = parts[next];\n if (!close || !('close' in close) || close.close !== index) return false;\n next++;\n }\n }\n return true;\n };\n if (!walk(host) || next !== parts.length) return false;\n for (const [node, text] of writes) if (node.nodeValue !== text) node.nodeValue = text;\n return true;\n}\n\nexport function reconstitute(\n resolved: string,\n slots: RichSlot[],\n doc: Document = document,\n onElement?: (element: HTMLElement, slot: number) => void\n): Node[] {\n const root = doc.createDocumentFragment();\n const stack: Node[] = [root];\n const top = () => stack[stack.length - 1];\n\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n SENT_SCAN.lastIndex = 0;\n const moved = new Set<HTMLElement>();\n\n try {\n while ((match = SENT_SCAN.exec(resolved)) !== null) {\n const text = resolved.slice(lastIndex, match.index);\n if (text) top().appendChild(doc.createTextNode(text));\n lastIndex = SENT_SCAN.lastIndex;\n\n const isOpen = match[1] !== undefined;\n const slotIndex = Number(isOpen ? match[1] : match[2]);\n\n if (isOpen) {\n const slot = slots[slotIndex];\n if (!slot) throw new Error('unknown markup slot');\n if (slot.source) {\n // Opaque (TOK-1): the element itself, its content as given, and whatever\n // a translation put inside its pair dropped.\n const el = moved.has(slot.source) ? (slot.source.cloneNode(true) as HTMLElement) : slot.source;\n moved.add(slot.source);\n onElement?.(el, slotIndex);\n top().appendChild(el);\n stack.push(doc.createDocumentFragment());\n continue;\n }\n const el = slot.template.cloneNode(false) as HTMLElement;\n onElement?.(el, slotIndex);\n top().appendChild(el);\n stack.push(el);\n } else {\n if (stack.length <= 1) throw new Error('unbalanced close');\n stack.pop();\n }\n }\n\n const tail = resolved.slice(lastIndex);\n if (tail) top().appendChild(doc.createTextNode(tail));\n\n if (stack.length !== 1) throw new Error('unbalanced open');\n } catch {\n // Degrade gracefully: strip every marker and return plain text.\n return [doc.createTextNode(stripSentinels(resolved))];\n }\n\n return Array.from(root.childNodes);\n}\n\n/**\n * An opaque element's text with each `{name}` or `%name%` the caller passes as a param\n * filled in, as plain text (TOK-1): a string, number or boolean as it prints, with no ICU\n * and no formatting. The key never holds it. Anything else, an unfilled placeholder\n * included, stays as written.\n */\nexport function fillOpaqueText(text: string, params: Readonly<Record<string, unknown>>): string {\n return text.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}|%([A-Za-z_][A-Za-z0-9_]*)%/g, (whole, braced?: string, percent?: string) => {\n const name = (braced ?? percent)!;\n const value = Object.prototype.hasOwnProperty.call(params, name) ? params[name] : undefined;\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : whole;\n });\n}\n\n/**\n * Whether an opaque element's text takes the caller's params: an author's own exclusion\n * does, code never (`<script>`, `<style>` and the rest of TOK-1's list, at any depth).\n */\nexport function takesParams(element: Element): boolean {\n return isTranslationExcluded(element) && !NON_TRANSLATABLE_ELEMENTS.includes(element.tagName.toLowerCase());\n}\n\n/** Each text node's text as the page gave it, and as `fillOpaque` last wrote it. */\nconst opaqueTexts = new WeakMap<Node, { original: string; written: string }>();\n\n/**\n * Fill the caller's params into the text of each opaque slot's element (`fillOpaqueText`),\n * always from the text the page gave it: a text the framework has rewritten since is its\n * new original. Code inside is left as it is.\n */\nexport function fillOpaque(slots: readonly RichSlot[], params: Readonly<Record<string, unknown>>): void {\n const visit = (parent: Node): void => {\n for (const child of Array.from(parent.childNodes)) {\n if (child.nodeType === 1) {\n if (!NON_TRANSLATABLE_ELEMENTS.includes((child as Element).tagName.toLowerCase())) visit(child);\n continue;\n }\n if (child.nodeType !== 3) continue;\n const seen = opaqueTexts.get(child);\n const original = seen && child.nodeValue === seen.written ? seen.original : child.nodeValue ?? '';\n const written = fillOpaqueText(original, params);\n if (child.nodeValue !== written) child.nodeValue = written;\n opaqueTexts.set(child, { original, written });\n }\n };\n for (const slot of slots) if (slot.source && takesParams(slot.source)) visit(slot.source);\n}\n\n/** Remove any sentinel markers from a string, leaving the bare text. */\nexport function stripSentinels(value: string): string {\n return value.replace(SENT_SCAN, '');\n}\n","import type { SeededBlock, SeededPhrase } from './block-tree.js';\nimport { tokenSlots, type TokenSlot } from './content-block.js';\nimport { normalizeMarkupPlaceholders, normalizeTokenText } from './identity.js';\nimport { interpolate } from './interpolate.js';\nimport { interpolateRich, splitSentinels } from './richtext.js';\nimport { runToken, type MarkerNode, type VarRun } from './var-markers.js';\nimport { logger } from './logger.js';\nimport { activeCatalog } from './scope-context.js';\nimport { currentlyLoadedLocale } from './stores.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\n\n/**\n * The source behind text a server already translated (SRV-4, GATE-10).\n *\n * A host a server rendered from the catalog carries the translation, not the\n * source, and the catalog is keyed by source. A client that read the DOM's text\n * as the key would render every later locale from the served one. So the DOM\n * classes over such a host take the source from where the server left it: the\n * scope's seed, which a binding hands over with `registerBlock(seededBlock)`\n * after `init()`, or, failing that, the catalog entry the served text was\n * rendered from. Never from the DOM.\n */\n\nconst seeded = new Map<string, SeededBlock>();\nconst collectedPhrases = new Set<string>();\n/**\n * Blocks sent for registration on this page, by the path that sent them: a seed\n * entry, or a mounted unit (the `Translate` over a host, a tree binding's\n * `registerBlock` over nodes). Each path skips what the OTHER sent; a unit\n * mounted again still registers as it always has.\n */\nconst handledBlocks = { seed: new Set<string>(), mount: new Set<string>() };\nlet warnedUnrecovered = false;\n\n/** Keep a seeded block's source tokens, by id, for the host that renders it. */\nexport function rememberSeededBlock(block: SeededBlock): void {\n if (block?.customId && Array.isArray(block.tokens)) seeded.set(block.customId, block);\n}\n\n/** Keep that the server's scope sends this phrase itself. */\nexport function rememberSeededPhrase(phrase: SeededPhrase): void {\n if (phrase?.collected && typeof phrase.phrase === 'string') collectedPhrases.add(`${phrase.category ?? ''}\\0${phrase.phrase}`);\n}\n\n/** Whether the server's scope sends this phrase itself, so the client never records it for registration. */\nexport function isServerCollectedPhrase(category: string, phrase: string): boolean {\n return collectedPhrases.has(`${category ?? ''}\\0${phrase}`);\n}\n\n/** A block sent for registration by `via`, so the other path over the same block does not send it again. */\nexport function markBlockHandled(customId: string, via: 'seed' | 'mount'): void {\n handledBlocks[via].add(customId);\n}\n\n/** Whether `by` already sent this block. */\nexport function isBlockHandled(customId: string, by: 'seed' | 'mount'): boolean {\n return handledBlocks[by].has(customId);\n}\n\n/** Whether the server's scope sends this block itself, so the client never registers it. */\nexport function isServerCollected(customId: string): boolean {\n return seeded.get(customId)?.collected === true;\n}\n\n/** Test seam: forget every seeded block, and the warning given. */\nexport function _resetSeededBlocks(): void {\n seeded.clear();\n collectedPhrases.clear();\n handledBlocks.seed.clear();\n handledBlocks.mount.clear();\n warnedUnrecovered = false;\n}\n\n/** Said once: a served host whose source could not be recovered keeps its served text. */\nexport function warnUnrecoveredSource(): void {\n if (warnedUnrecovered) return;\n warnedUnrecovered = true;\n logger.warn(\n 'A server-rendered block has no source to render other locales from: register the scope seed with registerBlock(seededBlock) after init(). It keeps the text it was served with.'\n );\n}\n\nconst served = (value: string) => normalizeTokenText(normalizeMarkupPlaceholders(value));\n\n/** What a slot holds now: the served token; a marked run's with `{NAME}` for each value (VAR-3). */\nfunction servedToken(slot: TokenSlot): string {\n if (slot.run) return runToken(slot.run as unknown as VarRun<MarkerNode>);\n return served(slot.attr ? (slot.node as Element).getAttribute(slot.attr) ?? '' : slot.node.nodeValue ?? '');\n}\n\n/**\n * The source token behind each of a block's slots, in slot order, or null when\n * they cannot all be recovered. From the seed when it holds the block with as\n * many tokens as the DOM has slots; else from the catalog entry under the id,\n * where exactly one source renders, with these params, as each slot's text:\n * translated, or as itself, since a block can be served in its source.\n */\nexport function recoverBlockSources(\n root: { childNodes: ArrayLike<Node> },\n customId: string,\n category: string,\n params: Record<string, ParamPrimitive>\n): { slots: TokenSlot[]; sources: string[] } | null {\n const slots = tokenSlots(root.childNodes);\n if (slots.length === 0) return null;\n const seed = seeded.get(customId);\n if (seed && seed.tokens.length === slots.length) return { slots, sources: [...seed.tokens] };\n\n const entry = activeCatalog()[category || '__uncategorized__']?.[customId];\n if (!entry || typeof entry !== 'object') return null;\n const locale = currentlyLoadedLocale.get();\n const rendered = Object.entries(entry as unknown as Record<string, unknown>)\n .filter(([key]) => !key.startsWith('__'))\n .flatMap(([key, value]) => {\n // As rendered with the params, and as written: a marked run is served with its\n // placeholders in place of the values it marks.\n const forms = (text: string) => [served(interpolate(text, params, locale)), served(text)];\n const texts = [...forms(key), ...(typeof value === 'string' && value ? forms(value) : [])];\n return [...new Set(texts)].map((text) => ({ key, text }));\n });\n const sources: string[] = [];\n for (const slot of slots) {\n const text = servedToken(slot);\n const keys = new Set(rendered.filter((r) => r.text === text).map((r) => r.key));\n if (keys.size !== 1) return null;\n sources.push([...keys][0]!);\n }\n return { slots, sources };\n}\n\n/** A resolved rich phrase's text alone: markup gone, whitespace collapsed. */\nconst textOf = (value: string) =>\n normalizeTokenText(value.replace(/\\uE000\\d+\\uE001|\\uE002\\d+\\uE003/g, ' ').replace(/\\{m\\d+[oc]\\}/g, ' '));\n\n/**\n * The source phrase behind a served rich phrase, and, for each source markup\n * slot, which served slot holds its element; or null unless exactly one source in\n * the category renders, with these params, as the served text with as many\n * inline elements. A translation may reorder its markup, so the served elements\n * are mapped back to the source's slots by the order the translation opens them.\n */\nexport function recoverPhraseSource(\n servedPhrase: string,\n slotCount: number,\n category: string,\n params: Record<string, ParamPrimitive>\n): { phrase: string; order: number[] } | null {\n const bucket = activeCatalog()[category || '__uncategorized__'];\n if (!bucket || typeof bucket !== 'object') return null;\n const locale = currentlyLoadedLocale.get();\n const target = textOf(servedPhrase);\n const found: Array<{ phrase: string; order: number[] }> = [];\n for (const [key, value] of Object.entries(bucket as unknown as Record<string, unknown>)) {\n if (key.startsWith('__') || (value !== null && typeof value === 'object')) continue;\n if ((key.match(/\\{m\\d+o\\}/g) ?? []).length !== slotCount) continue;\n // Translated, or as itself: a phrase can be served in its source.\n const texts = typeof value === 'string' && value ? [value, key] : [key];\n for (const text of texts) {\n const resolved = interpolateRich(text, params, slotCount, locale);\n if (textOf(resolved) !== target) continue;\n const parts = splitSentinels(resolved);\n const order = parts?.flatMap((part) => ('open' in part ? [part.open] : [])) ?? [];\n if (order.length !== slotCount) continue;\n if (!found.some((f) => f.phrase === key)) found.push({ phrase: key, order });\n break;\n }\n }\n return found.length === 1 ? found[0]! : null;\n}\n","import { logger } from './logger.js';\n\n/**\n * Debug notices: said once per process per reason, at debug level, and nothing\n * with debug off.\n *\n * A notice raised before `init()` is held, because debug is not known yet: a\n * component rendering before the app calls `init()` (a child's setup runs before\n * its layout's mount) would otherwise lose it. `init()` settles the queue: the\n * held notices are said when it turns debug on, and dropped when it does not.\n */\n\nconst said = new Set<string>();\nconst held = new Map<string, string>();\nlet settled = false;\n\n/** Say `message` once for `key`, at debug level; before `init()`, hold it until debug is known. */\nexport function debugNotice(key: string, message: string): void {\n if (said.has(key)) return;\n if (!settled) {\n if (!held.has(key)) held.set(key, message);\n return;\n }\n if (!logger.debugEnabled) return;\n said.add(key);\n logger.log(message);\n}\n\n/** Called by `init()` once it has set debug: say what was held, or drop it. */\nexport function settleNotices(): void {\n settled = true;\n const pending = [...held];\n held.clear();\n for (const [key, message] of pending) debugNotice(key, message);\n}\n\n/** Test seam: forget what was said and held, and wait for `init()` again. */\nexport function _resetNotices(): void {\n said.clear();\n held.clear();\n settled = false;\n}\n\n/** The reasons `register: false` or a binding may name, with what the notice says for each. */\nconst UNREGISTERED: Record<string, string> = {\n 'register-false': 'A <Translate> or <Phrase> was created with `register: false`: it renders from the catalog and registers nothing (VAR-7).',\n};\n\n/**\n * Report, as a debug notice once per process per reason, that a unit registers\n * nothing because the text it holds came from a variable that cannot be named\n * (VAR-7): `register: false` on a DOM class, or a binding without its build-time\n * transform. Its catalogued translations still render. The reason names the cause,\n * such as the transform to enable.\n */\nexport function warnUnregistered(reason: string): void {\n debugNotice(\n `unregistered\\0${reason}`,\n UNREGISTERED[reason] ??\n `A <Translate> or <Phrase> registers nothing (${reason}): it holds a value from a variable that cannot be named without the build-time transform, so it renders from the catalog only (VAR-7).`\n );\n}\n","/**\n * Placeholder names from source expressions (spec VAR-2). A name matches\n * `[a-z][a-z0-9_]*`, so it is a valid ICU argument, and it is derived the same way\n * by every SDK, because the name is part of the phrase: two SDKs naming the same\n * expression differently register two phrases.\n *\n * Expressions are given as a language-neutral shape, the one the shared naming\n * vectors (`var-naming-vectors.json`) use, so a binding maps its own AST onto it.\n */\n\n/** An expression that produced a value, as the naming rules see it. */\nexport type ExpressionShape =\n | { identifier: string }\n | { member: string[] }\n | { call: { callee: string; args: ExpressionShape[] } }\n | { other: 'binary' | 'conditional' | 'template' | 'computed' | 'call-multi' | string };\n\n/** One value in a phrase: its expression, and the name the developer wrote, if any. */\nexport interface NamedExpression {\n shape: ExpressionShape;\n /** An explicit name always wins. */\n explicit?: string;\n}\n\nconst GRAMMAR = /^[a-z][a-z0-9_]*$/;\n/** `<Phrase>`'s markup tokens. */\nconst RESERVED = /^m\\d+[oc]$/;\nconst COUNT = new Set(['length', 'size', 'count']);\nconst VALUE = new Set(['value', 'current']);\n\n/** A segment in snake_case, within the grammar, or null when nothing of it survives. */\nexport function snakeCase(segment: string): string | null {\n const snake = segment\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n .toLowerCase()\n .replace(/[^a-z0-9_]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^[^a-z]+/, '')\n .replace(/_+$/, '');\n return snake && GRAMMAR.test(snake) ? snake : null;\n}\n\n/** The name an expression derives on its own, and the segment before it, for a collision's prefix. */\nfunction derive(shape: ExpressionShape): { name: string; prev: string | null } | null {\n if ('identifier' in shape) {\n const name = snakeCase(shape.identifier);\n return name ? { name, prev: null } : null;\n }\n if ('member' in shape) {\n const segments = shape.member;\n if (segments.length === 0) return null;\n const last = segments[segments.length - 1]!;\n if (segments.length >= 2 && (COUNT.has(last) || VALUE.has(last))) {\n const base = snakeCase(segments[segments.length - 2]!);\n if (!base) return null;\n const prev = segments.length >= 3 ? snakeCase(segments[segments.length - 3]!) : null;\n return { name: COUNT.has(last) ? `${base}_count` : base, prev };\n }\n const name = snakeCase(last);\n if (!name) return null;\n return { name, prev: segments.length >= 2 ? snakeCase(segments[segments.length - 2]!) : null };\n }\n if ('call' in shape) {\n return shape.call.args.length === 1 ? derive(shape.call.args[0]!) : null;\n }\n return null;\n}\n\nconst key = (shape: ExpressionShape) => JSON.stringify(shape);\n\n/**\n * Whether a shape identifies its expression, so that an equal shape is the same\n * expression. An `other` shape, anywhere in it, does not: `a + b` and `c * d` are both\n * `{ other: 'binary' }`, and so are the arguments of `fmt(a + b)` and `fmt(c * d)`. Nor\n * does a call whose callee cannot be spelled (`''`): `getA()(n)` and `getB()(n)` are\n * both a call over `n`.\n */\nfunction identifies(shape: ExpressionShape): boolean {\n if ('call' in shape) return shape.call.callee !== '' && shape.call.args.every(identifies);\n return !('other' in shape);\n}\n\n/**\n * The placeholder name of each value in one phrase, in order (VAR-2):\n *\n * - an explicit name wins;\n * - an identifier is itself in snake_case; a member chain its last segment; a\n * chain ending in `length`, `size` or `count` the segment before plus `_count`;\n * one ending in `value` or `current` the segment before; a call with one\n * argument the argument's name;\n * - the same expression twice is the same placeholder, where the shape identifies\n * it: two shapes containing `other` are two placeholders, however equal;\n * - names that collide are prefixed with their previous segment, then suffixed\n * `_2`, `_3`, and a reserved name (`m0o`) counts as taken;\n * - anything else is `value`, `value_2`, ….\n */\nexport function derivePlaceholderNames(expressions: readonly NamedExpression[]): string[] {\n const names: Array<string | null> = expressions.map((e) => (e.explicit ? snakeCase(e.explicit) ?? e.explicit : null));\n const taken = new Set(names.filter((n): n is string => n !== null));\n const derived = expressions.map((e, i) => (names[i] === null ? derive(e.shape) : null));\n\n // The same expression is one placeholder: its later occurrences take the first's name.\n // Only a shape that identifies its expression can be the same as another.\n const firstOf = new Map<string, number>();\n const sameAs = expressions.map((e, i) => {\n if (names[i] !== null || !identifies(e.shape)) return i;\n const k = key(e.shape);\n if (!firstOf.has(k)) firstOf.set(k, i);\n return firstOf.get(k)!;\n });\n\n // Derived names wanted by more than one distinct expression, or taken already, collide.\n const wanted = new Map<string, number[]>();\n derived.forEach((d, i) => {\n if (d && sameAs[i] === i) wanted.set(d.name, [...(wanted.get(d.name) ?? []), i]);\n });\n const claim = (name: string): string => {\n let candidate = name;\n for (let n = 2; taken.has(candidate) || RESERVED.test(candidate); n++) candidate = `${name}_${n}`;\n taken.add(candidate);\n return candidate;\n };\n for (let i = 0; i < expressions.length; i++) {\n if (names[i] !== null || sameAs[i] !== i) continue;\n const d = derived[i];\n if (!d) continue;\n const collides = (wanted.get(d.name)?.length ?? 0) > 1 || taken.has(d.name) || RESERVED.test(d.name);\n names[i] = claim(collides && d.prev ? `${d.prev}_${d.name}` : d.name);\n }\n for (let i = 0; i < expressions.length; i++) {\n if (names[i] === null && sameAs[i] === i) names[i] = claim('value');\n }\n return expressions.map((_, i) => names[sameAs[i]!]!);\n}\n","/**\n * A host's own \"the app is going away\" signal, for runtimes with no `document` to listen to.\n *\n * In a browser the core flushes queued registrations itself, on `visibilitychange → hidden` and\n * `pagehide` (REG-3). React Native defines `window` but has no `document`, so those listeners\n * cannot exist there, and anything still queued when the app is backgrounded or killed would be\n * lost. `setTeardownSignal` lets the host supply the signal instead: the React Native binding\n * adapts `AppState` leaving `active`, and the core keeps the send.\n *\n * Same shape as `setPersistStorage`: a module-level injection that reaches every `Translations`\n * instance, those set up before it and after.\n */\n\n/**\n * Subscribe `fire` to the host's teardown signal and return a function that unsubscribes it.\n * The core calls `fire` nothing else: firing it runs the ordinary teardown flush.\n */\nexport type TeardownSubscribe = (fire: () => void) => (() => void) | void;\n\nconst targets = new Set<() => void>();\nlet release: (() => void) | null = null;\n\n/**\n * Inject the host's teardown signal, replacing any previous one. The previous subscription is\n * released first, so a re-injection — React Native's Fast Refresh, a test — never leaves two\n * live subscriptions that would flush twice. `null` releases the current one and injects none.\n *\n * Fire it once per departure, edge-triggered, as the app leaves the foreground: the flush sends\n * what is queued, and firing again while nothing is queued sends nothing.\n */\nexport function setTeardownSignal(subscribe: TeardownSubscribe | null): void {\n const previous = release;\n release = null;\n previous?.();\n if (!subscribe) return;\n const unsubscribe = subscribe(() => {\n for (const flush of targets) flush();\n });\n release = typeof unsubscribe === 'function' ? unsubscribe : null;\n}\n\n/** Register a flush to run when the injected signal fires. Returns its unregistration. */\nexport function _registerTeardownFlush(flush: () => void): () => void {\n targets.add(flush);\n return () => {\n targets.delete(flush);\n };\n}\n","/**\n * Legacy i18n values to Langsys/ICU source text (spec MIG-4).\n *\n * A migrated app keeps its source-language file and its keys; a key's value\n * becomes the registered phrase after this conversion. The conversion decides\n * the phrase, so it is identity: every JS entry point — the browser `t()`\n * mode, a server `t()`, a vue-i18n or i18next bridge — converts through these\n * functions, never a copy of them.\n *\n * Placeholders convert the same way whatever the file's format. Plurals\n * convert by the format the file declares, because frameworks read the same\n * characters differently: vue-i18n reserves `|`, i18next pairs suffixed keys.\n * The conversion preserves the source framework's own selection. Anything a\n * format does not recognise comes back exactly as written, with `recognised`\n * false and the reason in `issue`, so it registers verbatim and is reported\n * rather than silently mangled.\n */\n\n/** The formats a file can declare anywhere in the fleet (MIG-7). */\nexport const LEGACY_FORMATS = ['laravel', 'vue-i18n', 'i18next', 'gettext', 'rails-i18n', 'plain'] as const;\n\n/** The formats this core reads (MIG-7). Any other configured format is refused at load. */\nexport const SUPPORTED_LEGACY_FORMATS = ['i18next', 'vue-i18n', 'plain'] as const;\n\nexport type LegacyFormat = (typeof SUPPORTED_LEGACY_FORMATS)[number];\n\n/** A converted value. `text` is the phrase to register; when `recognised` is false it is the value as written. */\nexport interface LegacyConversion {\n text: string;\n recognised: boolean;\n issue: string | null;\n}\n\n/** CLDR plural categories, in ICU's customary order. */\nexport const PLURAL_CATEGORIES = ['zero', 'one', 'two', 'few', 'many', 'other'] as const;\n\n/**\n * Every placeholder spelling the fleet converts, scanned left to right in one\n * pass so a `%%` is consumed before its second `%` can start another match.\n * The spellings that carry formatting `{name}` cannot express, and positional\n * `%s`, are matched so they can be refused rather than half-converted.\n */\nconst PLACEHOLDER =\n /%%|%\\{([A-Za-z_][A-Za-z0-9_]*)\\}|%\\(([A-Za-z_][A-Za-z0-9_]*)\\)[sd]|%\\([A-Za-z_][A-Za-z0-9_]*\\)[-+ #0-9.]*[a-zA-Z]|%<[A-Za-z_][A-Za-z0-9_]*>[-+ #0-9.]*[a-zA-Z]|%(?:\\.\\d+)?[sdif](?![A-Za-z])|\\{\\{\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}|(?<![\\w:]):([a-z][a-z0-9_]*)/g;\n\n/** Laravel's `:Name` / `:NAME` upper-case the value, which `{name}` cannot express. */\nconst CASE_TRANSFORM = /(?<![\\w:]):[A-Z][A-Za-z0-9_]*/;\n\nclass Unconvertible extends Error {}\n\n/**\n * Convert a value under a format.\n *\n * `plain` converts placeholders and nothing else; a `|` in it is text, so such\n * a value is returned verbatim and reported. `vue-i18n` reads any `|` as a\n * plural selected by count. `i18next` has no in-string plural — its plurals are\n * suffix-paired keys, see `convertLegacyPluralForms` — so a `|` is reported.\n */\nexport function convertLegacyValue(value: string, format: LegacyFormat = 'plain'): LegacyConversion {\n value = String(value);\n\n if (CASE_TRANSFORM.test(value)) {\n return unrecognised(value, 'uses a case-transforming placeholder (:Name or :NAME), which ICU cannot express');\n }\n\n if (!value.includes('|')) return convertPlaceholders(value);\n\n if (format === 'vue-i18n') return convertVuePipes(value);\n\n return unrecognised(\n value,\n format === 'i18next'\n ? 'holds a \"|\", which i18next does not read as a plural'\n : 'holds a \"|\" in a file with no plural format declared; declare the file\\'s format to convert it'\n );\n}\n\n/**\n * One ICU plural from forms keyed by CLDR category — i18next's `key_one` /\n * `key_other` (and its older `key` / `key_plural` pair, as `one` / `other`).\n * i18next selects by locale, so the forms keep their CLDR categories.\n */\nexport function convertLegacyPluralForms(forms: Partial<Record<(typeof PLURAL_CATEGORIES)[number], string>>): LegacyConversion {\n const raw = PLURAL_CATEGORIES.filter((c) => forms[c] !== undefined)\n .map((c) => forms[c])\n .join(' | ');\n if (forms.other === undefined) return unrecognised(raw, 'is a plural with no \"other\" form');\n\n const branches: Array<[string, string]> = [];\n for (const category of PLURAL_CATEGORIES) {\n const text = forms[category];\n if (text === undefined) continue;\n if (CASE_TRANSFORM.test(text)) {\n return unrecognised(raw, 'uses a case-transforming placeholder (:Name or :NAME), which ICU cannot express');\n }\n branches.push([category, text]);\n }\n return plural(branches, raw);\n}\n\n/** A JS entry point that can receive legacy text (MIG-2). */\nexport type LegacyEntryPoint = 't' | 'vue-i18n' | 'i18next';\n\n/**\n * Convert the text a call passed when it is not a key — a literal miss\n * (MIG-2) — by the entry point that received it, not by any file: the text is\n * written in the calling framework's syntax.\n *\n * Langsys `t()` converts nothing; its argument is already Langsys syntax. A\n * vue-i18n `$t` or i18next `t` bridge converts under its own format's row.\n */\nexport function convertLegacyCall(text: string, entryPoint: LegacyEntryPoint): LegacyConversion {\n if (entryPoint === 't') return { text: String(text), recognised: true, issue: null };\n if (entryPoint === 'vue-i18n' || entryPoint === 'i18next') return convertLegacyValue(text, entryPoint);\n throw new Error(`Unknown entry point \"${String(entryPoint)}\"; expected t, vue-i18n or i18next`);\n}\n\n/**\n * vue-i18n reserves `|` and selects by count, not by locale: with two forms, 1\n * picks the first and anything else the second; with three, 0, 1, then the\n * rest. Exact values keep that selection in every source language, where CLDR\n * `one` would not (in French it covers 0).\n */\nfunction convertVuePipes(value: string): LegacyConversion {\n const segments = value.split('|').map((s) => s.trim());\n if (segments.length === 2) return plural([['=1', segments[0]!], ['other', segments[1]!]], value);\n if (segments.length === 3) return plural([['=0', segments[0]!], ['=1', segments[1]!], ['other', segments[2]!]], value);\n return unrecognised(value, `is a vue-i18n plural with ${segments.length} forms; only 2 or 3 map to ICU`);\n}\n\n/**\n * `{count, plural, <branches>}` with one space between parts, exact branches\n * first as given, then the CLDR categories in order — the string is the\n * phrase's identity, so it has exactly one spelling. The number inside a branch\n * is ICU's `#`, never `{count}`: some ICU builds accept `{count}` in a branch\n * of its own plural and then fail to format it.\n */\nfunction plural(branches: Array<[string, string]>, raw: string): LegacyConversion {\n const parts: string[] = [];\n for (const [selector, text] of branches) {\n const converted = convertPlaceholders(text);\n if (!converted.recognised) return unrecognised(raw, converted.issue!);\n parts.push(`${selector} {${converted.text.replace(/\\{(?:count|n)\\}/g, '#')}}`);\n }\n return { text: `{count, plural, ${parts.join(' ')}}`, recognised: true, issue: null };\n}\n\nfunction convertPlaceholders(value: string): LegacyConversion {\n try {\n const text = value.replace(PLACEHOLDER, (match, rails?: string, python?: string, braces?: string, laravel?: string) => {\n if (match === '%%') return '%';\n const name = rails ?? python ?? braces ?? laravel;\n if (name !== undefined) return `{${name}}`;\n throw new Unconvertible(\n match.startsWith('%(') || match.startsWith('%<')\n ? `uses a formatted placeholder (${match}), which {name} cannot express`\n : `uses a positional placeholder (${match}), which names no argument`\n );\n });\n return { text, recognised: true, issue: null };\n } catch (error) {\n if (error instanceof Unconvertible) return unrecognised(value, error.message);\n throw error;\n }\n}\n\nfunction unrecognised(value: string, issue: string): LegacyConversion {\n return { text: value, recognised: false, issue };\n}\n","import {\n convertLegacyPluralForms,\n convertLegacyValue,\n LEGACY_FORMATS,\n PLURAL_CATEGORIES,\n SUPPORTED_LEGACY_FORMATS,\n type LegacyConversion,\n type LegacyFormat,\n} from './legacy-value.js';\n\n/**\n * Legacy i18n keys resolved against an app's kept source-language files\n * (spec MIG-2, MIG-5, MIG-7).\n *\n * Pure and fs-free: each file is passed already parsed, as `{ name, format?,\n * namespace?, data }`, so the browser `t()` mode and a server `t()` read one\n * configuration through one resolver and register one phrase per key.\n *\n * - **Formats.** This core reads `i18next`, `vue-i18n` and `plain`, all JSON. A\n * file with no declared format is `plain`. A file declaring any other format,\n * or whose name marks it as another ecosystem's (`.php`, `.yml`, `.po`,\n * `.mo`), is refused when the resolver is built, with an error naming the\n * format and the file.\n * - **Lookup.** A key is read as written first, then by dotted path. The first\n * configured file that holds it answers, and a key held by more than one file\n * is reported by `duplicates()`.\n * - **Category.** A key shaped like a path (`checkout.submit`) contributes its\n * first segment; a file with a `namespace` answers only keys under it\n * (`checkout.submit` in a file with namespace `checkout`) and contributes the\n * namespace. A sentence used as its own key has none.\n * - **Plurals.** In an `i18next` file, suffix-paired keys (`items_one`,\n * `items_other`, or the older `items` / `items_plural`) resolve together as\n * one plural under their base key.\n */\n\n/** One configured source file. `data` is its parsed JSON object. */\nexport interface LegacyKeyFile {\n /** The file's path or name, as errors and reports should name it. */\n name: string;\n /** `i18next`, `vue-i18n` or `plain`. Defaults to `plain`. */\n format?: string;\n /** When set, the file answers only keys prefixed `namespace.`, and the namespace is their category. */\n namespace?: string;\n data: unknown;\n}\n\n/** A key the files hold, converted. */\nexport interface LegacyKeyHit extends LegacyConversion {\n /** The phrase to register: the converted value, or the value as written when not `recognised`. */\n phrase: string;\n /** The category the key contributes, or null for none (MIG-5). */\n category: string | null;\n key: string;\n /** The file that answered. */\n file: string;\n}\n\n/** What cannot be migrated as it stands, for a listing command (MIG-4, MIG-7). */\nexport interface LegacyKeyProblem {\n file: string;\n key: string | null;\n issue: string;\n fix: string;\n}\n\nexport interface LegacyKeys {\n /** The key's converted source value, or null when no file holds it (the MIG-2 miss). */\n resolve(key: string): LegacyKeyHit | null;\n /** Keys held by more than one file, with those files in configured order; the first answers. */\n duplicates(): Record<string, string[]>;\n /** Every value that converts to nothing recognised, and every file that is not a JSON object. */\n problems(): LegacyKeyProblem[];\n}\n\n/** Thrown when the configuration names a file this core cannot read (MIG-7). */\nexport class LegacyFormatError extends Error {\n constructor(\n message: string,\n readonly file: string,\n readonly format: string\n ) {\n super(message);\n this.name = 'LegacyFormatError';\n }\n}\n\ninterface NormalizedFile {\n name: string;\n format: LegacyFormat;\n namespace: string | null;\n data: Record<string, unknown> | null;\n}\n\ntype PluralForms = Partial<Record<(typeof PLURAL_CATEGORIES)[number], string>>;\n\n/** The format another ecosystem's file type implies, so it is refused by name rather than read as JSON. */\nconst FOREIGN_EXTENSIONS: Record<string, string> = {\n php: 'laravel',\n yml: 'rails-i18n',\n yaml: 'rails-i18n',\n po: 'gettext',\n mo: 'gettext',\n};\n\n/**\n * Build a resolver over configured files. Throws `LegacyFormatError` for a file\n * this core does not read — never silently, since a skipped file would turn\n * every one of its keys into a literal phrase named after the key.\n */\nexport function createLegacyKeys(files: LegacyKeyFile[]): LegacyKeys {\n const normalized = files.map(normalize);\n\n return {\n resolve(key) {\n if (typeof key !== 'string' || key === '') return null;\n for (const file of normalized) {\n const found = lookup(file, key);\n if (!found) continue;\n const converted = convert(found.value, file.format);\n return { ...converted, phrase: converted.text, category: found.category, key, file: file.name };\n }\n return null;\n },\n\n duplicates() {\n const seen: Record<string, string[]> = {};\n for (const file of normalized) {\n for (const key of Object.keys(leaves(file))) (seen[key] ??= []).push(file.name);\n }\n return Object.fromEntries(Object.entries(seen).filter(([, names]) => names.length > 1));\n },\n\n problems() {\n const problems: LegacyKeyProblem[] = [];\n for (const file of normalized) {\n if (file.data === null) {\n problems.push({ file: file.name, key: null, issue: 'is not a JSON object', fix: 'pass the parsed contents of the file' });\n continue;\n }\n for (const [key, value] of Object.entries(leaves(file))) {\n const converted = convert(value, file.format);\n if (!converted.recognised) {\n problems.push({\n file: file.name,\n key,\n issue: converted.issue!,\n fix: \"rewrite the value as Langsys source text, or declare the file's format\",\n });\n }\n }\n }\n return problems;\n },\n };\n}\n\nfunction normalize(file: LegacyKeyFile): NormalizedFile {\n const name = String(file?.name ?? '');\n const extension = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';\n\n if (extension === 'mo') {\n const po = name.slice(0, -3) + '.po';\n throw new LegacyFormatError(\n `The legacy file ${name} is a compiled gettext catalog. gettext reads .po only (${po}), and gettext is not a format this core reads; it reads ${SUPPORTED_LEGACY_FORMATS.join(', ')}.`,\n name,\n 'gettext'\n );\n }\n\n const declared = file?.format;\n const format = declared ?? FOREIGN_EXTENSIONS[extension] ?? 'plain';\n if (!(SUPPORTED_LEGACY_FORMATS as readonly string[]).includes(format)) {\n const known = (LEGACY_FORMATS as readonly string[]).includes(format);\n throw new LegacyFormatError(\n `The legacy file ${name} is in the ${known ? '' : 'unknown '}format \"${format}\", which this core does not read. It reads ${SUPPORTED_LEGACY_FORMATS.join(', ')}.`,\n name,\n format\n );\n }\n\n const data = isRecord(file?.data) ? file.data : null;\n return { name, format: format as LegacyFormat, namespace: file?.namespace ? String(file.namespace) : null, data };\n}\n\nfunction lookup(file: NormalizedFile, key: string): { value: string | PluralForms; category: string | null } | null {\n if (!file.data) return null;\n const pairs = file.format === 'i18next';\n\n if (file.namespace !== null) {\n if (!key.startsWith(file.namespace + '.')) return null;\n const value = valueAt(file.data, key.slice(file.namespace.length + 1).split('.'), pairs);\n return value === null ? null : { value, category: file.namespace };\n }\n\n if (!key.includes('.')) {\n // Read through the pairing, so an i18next plural base (`items` for\n // `items_one`, `item` for `item_plural`) resolves as its plural.\n const value = valueAt(file.data, [key], pairs);\n return value === null ? null : { value, category: null };\n }\n\n const flat = file.data[key];\n if (typeof flat === 'string') return { value: flat, category: looksLikeAPath(key) ? key.slice(0, key.indexOf('.')) : null };\n\n const value = valueAt(file.data, key.split('.'), pairs);\n return value === null ? null : { value, category: key.slice(0, key.indexOf('.')) };\n}\n\n/** A string at a path, or — in an i18next file — plural forms when the key is suffix-paired. */\nfunction valueAt(data: Record<string, unknown>, segments: string[], pairs: boolean): string | PluralForms | null {\n const last = segments.pop()!;\n let container: unknown = data;\n for (const segment of segments) {\n if (!isRecord(container) || !(segment in container)) return null;\n container = container[segment];\n }\n if (!isRecord(container)) return null;\n\n if (pairs) {\n const forms: PluralForms = {};\n for (const category of PLURAL_CATEGORIES) {\n const value = container[`${last}_${category}`];\n if (typeof value === 'string') forms[category] = value;\n }\n if (Object.keys(forms).length > 0) return forms;\n const singular = container[last];\n const pluralForm = container[`${last}_plural`];\n if (typeof singular === 'string' && typeof pluralForm === 'string') return { one: singular, other: pluralForm };\n }\n\n const value = container[last];\n return typeof value === 'string' ? value : null;\n}\n\n/** Every leaf by its full key: strings, and — in an i18next file — plural forms under their base key. */\nfunction leaves(file: NormalizedFile): Record<string, string | PluralForms> {\n const out: Record<string, string | PluralForms> = {};\n if (!file.data) return out;\n const prefix = file.namespace !== null ? file.namespace + '.' : '';\n collect(file.data, prefix, out, file.format === 'i18next');\n return out;\n}\n\nconst SUFFIXES = [...PLURAL_CATEGORIES.map((c) => `_${c}`), '_plural'];\n\nfunction collect(node: Record<string, unknown>, prefix: string, out: Record<string, string | PluralForms>, pairs: boolean): void {\n for (const [key, value] of Object.entries(node)) {\n if (isRecord(value)) {\n collect(value, `${prefix}${key}.`, out, pairs);\n continue;\n }\n if (typeof value !== 'string') continue;\n\n if (pairs) {\n const suffix = SUFFIXES.find((s) => key.endsWith(s) && key.length > s.length);\n if (suffix) {\n const base = key.slice(0, -suffix.length);\n const forms = valueAt(node, [base], true);\n if (forms !== null && typeof forms !== 'string') {\n out[prefix + base] = forms;\n continue;\n }\n }\n }\n if (!(prefix + key in out)) out[prefix + key] = value;\n }\n}\n\nfunction convert(value: string | PluralForms, format: LegacyFormat): LegacyConversion {\n return typeof value === 'string' ? convertLegacyValue(value, format) : convertLegacyPluralForms(value);\n}\n\n/** A flat key names a category only when it is shaped like a key path; a sentence used as its own key has none. */\nfunction looksLikeAPath(key: string): boolean {\n return /^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)+$/.test(key);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import { LangsysAppAPI, type LangsysConfigurationError } from './api.js';\nimport { recordMissForDiscovery } from './discovery.js';\nimport { isServerCollectedPhrase } from './served-source.js';\nimport { warnUnregistered } from './notices.js';\nimport { derivePlaceholderNames } from './var-names.js';\nimport { _registerTeardownFlush } from './teardown.js';\nimport { stripC0Controls } from './identity.js';\nimport { interpolate } from './interpolate.js';\nimport { activeCatalog, activeScope } from './scope-context.js';\nimport { createLegacyKeys, type LegacyKeyFile, type LegacyKeys } from './legacy-keys.js';\nimport { canonicalizeLocale } from './locale.js';\nimport { Logger, logger } from './logger.js';\nimport { createSignal, type Signal } from './signal.js';\nimport { batchLimit, catalogScopeOf, catalogUnavailable, pageCatalog, pageLocale, currentlyLoadedLocale, discoveryBaseLocaleOnly, navigationEpoch, scopeCatalogCache, setWriteEnabled, sTranslations, writeEnabled } from './stores.js';\nimport type { ResponseObject } from './types/api.js';\nimport type { iLangsysConfig } from './types/config.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { iCategories, iTranslations } from './types/translations.js';\n\ninterface iTokenUpdate {\n projectid: string;\n category: string;\n token: string;\n}\n\n/**\n * `'auto'` SSR strategy: flush from the server while the queue is at or below\n * this size. Above it, `'auto'` defers to the client — which cannot receive the\n * queue across a real process boundary (see `shouldQueueForWrite`), so we also\n * stop collecting at that point rather than retaining tokens nothing will send.\n */\nexport const AUTO_SSR_FLUSH_THRESHOLD = 5;\n\n/**\n * Client-side flush debounce. Long enough that a burst of misses from one\n * render coalesces into a single POST, short enough that late-arriving content\n * is still registered inside the discovery renderer's post-scroll grace window.\n */\nexport const CLIENT_FLUSH_DEBOUNCE_MS = 400;\n\n/** Backstop period. Only runs while something is queued — see `ensureBackstop`. */\nconst BACKSTOP_INTERVAL_MS = 3000;\n\n/**\n * Exponential backoff for a failing registration endpoint.\n *\n * A failed send leaves its batch queued so it can be retried — but the 3s\n * interval then retries unconditionally, so a persistently failing server\n * (a misconfigured CSRF rule, an outage, an expired key) gets a request every\n * 3 seconds for as long as the page is open, with the payload growing as new\n * misses accumulate. That is the same client-side amplification this feature's\n * hint lane goes to some length to prevent, on the lane that never got it.\n */\nexport const RETRY_BACKOFF_BASE_MS = 3_000;\nconst RETRY_BACKOFF_MAX_MS = 300_000;\n\n/**\n * CACHE-2's window after the `failures`th failed read in a row of one catalog pair, or of one\n * reference list and display locale (REF-1): 3s, 6s, 12s … capped at 5 minutes.\n */\nexport function failureWindowMs(failures: number): number {\n return Math.min(RETRY_BACKOFF_BASE_MS * 2 ** (failures - 1), RETRY_BACKOFF_MAX_MS);\n}\n\nfunction isObject(test: unknown): test is Record<string, unknown> {\n return typeof test === 'object' && !Array.isArray(test) && test !== null;\n}\nfunction sameToken(a: iTokenUpdate, b: iTokenUpdate): boolean {\n return a.projectid === b.projectid && a.category === b.category && a.token === b.token;\n}\n\n/**\n * Lifecycle for app translations:\n * - on-miss: any `t(cat, phrase)` whose phrase isn't in the catalog is\n * queued as a \"missing token\" and (with write keys) flushed to the API.\n * - locale changes trigger `change()` which fetches and replaces.\n * - consumers can `subscribe(fn)` to react to translation snapshots.\n * - frameworks subscribe to `tSignal` (which re-emits a fresh `TFunction`\n * every time translations or the loaded locale change) so reactive\n * templates re-render automatically.\n */\n/**\n * OBS-1 — say once, above debug level, when a key that is supposed to write\n * cannot write from here.\n *\n * Module-scope so the ONE latch is shared by both channels that learn about\n * capability: `authorize-project` at init, and the envelope on every catalog\n * fetch. Two latches would let the same condition be announced twice, and a\n * latch on only one channel is how the mid-session transition went silent.\n *\n * Only for a key type EXPECTED to write. A `read` key resolving read-only is\n * correct, not a misconfiguration, and warning on every ordinary site is how\n * this becomes the notice everyone silences — taking the `ip_write` case with\n * it. Latched on the OUTCOME, so a change in the answer speaks again while a\n * repeat of the same answer stays quiet.\n */\nlet capabilityNoticeSignature: string | null = null;\n\nexport function noticeUnusableWriteCapability(enabled: boolean, keyType: string | undefined): void {\n const signature = `${keyType ?? 'unknown'}:${enabled}`;\n if (signature === capabilityNoticeSignature) return;\n capabilityNoticeSignature = signature;\n\n if (enabled || (keyType !== 'write' && keyType !== 'ip_write')) return;\n\n logger.warn(\n `Langsys: this session cannot write. The key is '${keyType}', but the server's answer did not ` +\n `make this request write-enabled — so missing phrases will NOT be registered and nothing ` +\n `will appear in the Translation Manager. For an 'ip_write' key this usually means the address ` +\n `is not allow-listed; otherwise supply a write grant via LangsysApp.setWriteGrant(). Page URLs ` +\n `may still be reported for discovery if auto_discovery is enabled for this key.`\n );\n}\n\n/**\n * The write decision a catalog answer carries. The API sends it on every answer, and one\n * without it is not write-enabled, exactly as if it said false (GATE-8). A failed read\n * answers nothing about it, so the decision already held stays.\n */\nexport function answeredWriteDecision(response: { errors?: unknown; write_enabled?: unknown }): boolean | undefined {\n if (typeof response.write_enabled === 'boolean') return response.write_enabled;\n return response.errors ? undefined : false;\n}\n\n/** Test seam — the latch is module state and must not leak between cases. */\nexport function _resetCapabilityNotice(): void {\n capabilityNoticeSignature = null;\n}\n\n/**\n * SSR-2: when a configured write grant stops a server render from collecting, say so,\n * outside debug.\n *\n * The degradation itself was already right. Under a grant, write capability is\n * per-user, and a process-wide server queue cannot carry it, so `shouldQueueForWrite`\n * refuses to collect and the browser collects after hydration instead. But it did\n * that with a silent `return false`, and the only trace was a debug-gated log. A\n * production site that configured a grant lost server-side collection without a\n * word, and the rule's title says the degradation is loud.\n *\n * Latched ONCE per process. The cause is the process's configuration, not any\n * particular miss, so repeating it on every miss would be noise, and noise is how a\n * warning gets silenced. It fires only for a strategy that would otherwise have\n * collected; under `'client'` nothing was degraded.\n */\nlet ssrGrantNoticeGiven = false;\n\nexport function noticeSsrGrantDegradation(strategy: string): void {\n if (ssrGrantNoticeGiven) return;\n ssrGrantNoticeGiven = true;\n logger.warn(\n `Langsys: a write grant is configured, so this server render does not collect missing phrases ` +\n `(ssrTokenStrategy '${strategy}' is degraded to 'client'). Under a grant, write capability is ` +\n `per-user and a process-wide server queue cannot carry it, so missing phrases are collected in the ` +\n `browser after hydration instead.`\n );\n}\n\n/** Where `t()` reads and records: the page's state, or a request scope's (SRV-7). */\nexport interface CatalogView {\n catalog(): iCategories;\n locale(): string;\n miss(category: string, key: string, onlyForRegistration: boolean): void;\n fromSnapshot(): boolean;\n}\n\n/** Test seam — module state, and must not leak between cases. */\nexport function _resetSsrGrantNotice(): void {\n ssrGrantNoticeGiven = false;\n}\n\nexport class Translations {\n private config: iLangsysConfig;\n private locale: string;\n private lastLoaded: Record<string, number> = {};\n private missingTokens: iTokenUpdate[] = [];\n /** Phrases already reported under REG-11, so the warning fires once each. */\n private warnedEllipsis = new Set<string>();\n /** The legacy-key mode (MIG-1): null unless configured, and then `t()` does no key lookup at all. */\n private legacyKeys: LegacyKeys | null = null;\n private warnedLegacy = new Set<string>();\n private timer: ReturnType<typeof setInterval> | null = null;\n /**\n * Catalog fetches still in flight. While any is, queued tokens are held: the flush\n * deduplicates against the catalog, and the catalog being fetched is not there yet.\n */\n private catalogFetchesInFlight = 0;\n /**\n * The published catalog is a snapshot, not the live catalog (SNAP-2). Lookups\n * read it, but registration is decided only against the live catalog\n * (REG-13), so until one arrives every phrase is queued and the queue is held.\n */\n private catalogFromSnapshot = false;\n /**\n * CACHE-2: a failed catalog fetch, remembered per project and locale. Until `retryAt` a\n * lookup for that pair renders source text and nothing is fetched. The window follows\n * REG-8's clock on the read side: 3s, doubling on each consecutive failure to 5 minutes,\n * cleared by the first success. Held on this instance, so it lasts the page session in a\n * browser and the life of the server object on a server, and is never written anywhere.\n */\n private catalogFailures = new Map<string, { failures: number; retryAt: number }>();\n /** CACHE-2: a catalog request in flight per project and locale, shared by concurrent fetches. */\n private catalogRequests = new Map<string, Promise<boolean>>();\n private flushScheduled = false;\n private updateInFlight = false;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private consecutiveFailures = 0;\n /** Epoch ms before which no send may be attempted. See RETRY_BACKOFF_*. */\n private retryNotBefore = 0;\n private teardownInstalled = false;\n /** Unregisters this instance from an injected teardown signal (`setTeardownSignal`). */\n private releaseTeardownFlush: (() => void) | null = null;\n private isFirstClientRun = true;\n /** Process-level write decision for the SSR lane. See `canWrite`. */\n private ssrWriteEnabled: boolean | undefined = undefined;\n /** Thrown by `t()` when `init()` was refused for missing credentials under `requireCredentials`. */\n private credentialsError: LangsysConfigurationError | null = null;\n private readyResolve: () => void = () => {};\n private readyPromise: Promise<void> = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n public debug: Logger;\n\n /** Reactive holder for the current translation function. Re-emits on every catalog/locale change. */\n public tSignal: Signal<TFunction>;\n\n constructor(config: iLangsysConfig) {\n this.config = config;\n this.debug = new Logger(!!config.debug);\n this.locale = canonicalizeLocale(config.baseLocale || '');\n\n // A FRESH closure per emit, and that is a contract, not an accident.\n // `Signal.set` drops a value that is `Object.is`-equal to the current\n // one (`signal.ts`), so identity IS the change signal every binding\n // subscribes to. Memoizing `buildTFn` — the obvious optimization, since\n // the closure body never varies — makes every `set` a no-op: no\n // subscriber fires, nothing throws, and every consumer renders stale\n // text while the correct catalog sits in the store.\n //\n // The closure reads `sTranslations` at CALL time, so a stable reference\n // would still return fresh values to anyone who called it. That is what\n // makes the failure so quiet: `t()` is right, and nobody re-renders to\n // ask it. Pinned by `tfunction-identity.test.ts`.\n this.tSignal = createSignal<TFunction>(this.buildTFn());\n sTranslations.subscribe(() => this.tSignal.set(this.buildTFn()));\n currentlyLoadedLocale.subscribe(() => this.tSignal.set(this.buildTFn()));\n\n // Misses collected before authorization resolved (or before a write\n // grant arrived) are held, not dropped — flush them the moment the\n // session turns out to be write-enabled.\n writeEnabled.subscribe((enabled) => {\n if (!this.missingTokens.length) return;\n if (enabled === true) {\n this.scheduleTokenFlush();\n } else if (enabled === false && !LangsysAppAPI.hasWriteGrant()) {\n // Authorization came back read-only and no grant can change\n // that, so these can never be sent. They were recorded by the\n // discovery lane when they missed, so releasing them loses\n // nothing and keeps a long-lived session from holding a queue\n // that will never drain.\n this.debug.log(`Releasing ${this.missingTokens.length} held tokens (session is read-only)`);\n this.missingTokens = [];\n // Nothing will ever be queued again on this session, so the\n // backstop has nothing left to back up. Without this it keeps\n // ticking every 3s for the life of the page: `updateTokens`\n // returns early on an empty queue, before reaching the disarm.\n this.stopBackstop();\n }\n });\n\n if (config.key && config.projectid) this.setup(config);\n }\n\n /**\n * Resolves once the first `getTranslations` call has completed (or\n * immediately if no fetch is configured). Callers that need to read\n * `sTranslations` before issuing a write — e.g. the `Translate` DOM\n * class deciding whether to POST a content block — should await this\n * to avoid acting on an empty cache during the cold-start race.\n */\n public ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Resolve `ready()` without a catalog, for the paths where none is coming:\n * `init` refused the config, or authorization failed.\n *\n * `Phrase` and `Translate` both await this gate before rendering, so\n * leaving it pending on those paths is not a degraded mode — it is a\n * permanent blank render, with no error, on the commonest misconfigurations\n * there are. Settling makes them fall back to their source text, which is\n * what an SDK that cannot reach its backend should show.\n *\n * Idempotent. A later successful load still updates the stores and\n * re-renders every subscriber.\n */\n public settle(): void {\n this.readyResolve();\n }\n\n /**\n * WIRE-4: `init()` was refused for missing credentials. Reads render source through the\n * catalog-failed path, so no miss is recorded and nothing is sent; and the capability\n * settles as not writable, so nothing waits on it, and the read-only release drops what\n * an earlier render queued, since it can never be sent. With `requireCredentials`, `t()`\n * throws `error`.\n */\n public markUnconfigured(error: LangsysConfigurationError, requireCredentials: boolean): void {\n this.credentialsError = requireCredentials ? error : null;\n this.settleNotWritable();\n catalogUnavailable.set(true);\n this.settle();\n }\n\n /**\n * Under `requireCredentials`, throw the configuration error while the client is\n * unconfigured (WIRE-4). `t()` calls it, and so does `Translate`'s render, whose\n * multi-phrase blocks never reach `t()`.\n */\n public assertConfigured(): void {\n if (this.credentialsError) throw this.credentialsError;\n }\n\n /** `init()` accepted credentials: undo an earlier refusal, so the first catalog decides afresh. */\n public markConfigured(): void {\n if (this.credentialsError === null && !catalogUnavailable.get()) return;\n this.credentialsError = null;\n catalogUnavailable.set(false);\n }\n\n /**\n * The capability is known to be \"no\": the client has no credentials, or authorization was\n * refused. Without this a block registration waiting for the capability would wait forever.\n */\n public settleNotWritable(): void {\n setWriteEnabled(false);\n if (typeof window === 'undefined') this.ssrWriteEnabled = false;\n }\n\n /**\n * A route change re-enters the SDK (HINT-13). Call it from the router's after-navigation\n * hook. It publishes a fresh `t` through `tSignal` — the same dependency a locale change\n * advances — so a component bound to `t` re-renders its mounted nodes, and each miss is\n * recorded at the URL the page is now on. The core's own `Translate` and `Phrase` re-enter\n * too, but only while their host is attached to the document, so an instance left\n * undestroyed on a removed node records nothing.\n *\n * It sends nothing itself. What follows is the ordinary miss path: one report per URL,\n * the jitter, the decline rules, GATE-9 and GATE-10 all apply, and a phrase already queued\n * or registered is not queued again. Calling it twice for the same URL reports nothing more.\n */\n public notifyNavigation(): void {\n navigationEpoch.set(navigationEpoch.get() + 1);\n this.tSignal.set(this.buildTFn());\n }\n\n /** Current translation function. Reads fresh state on every call. */\n public get t(): TFunction {\n return this.tSignal.get();\n }\n\n /** Subscribe to translation snapshot changes. Fires immediately with the current value. */\n public subscribe(run: (value: iCategories) => void) {\n return sTranslations.subscribe(run);\n }\n\n /**\n * Content-block-keyed lookup used by the DOM `Translate` class.\n * Returns the per-token translation inside a content block, or `null` if\n * either the content block or the inner token is missing. Never registers\n * a missing token — the DOM class manages its own lifecycle via content blocks.\n */\n public lookupContent(category: string, customId: string, token: string): string | null {\n const cats = activeCatalog();\n const lookupCat = category || '__uncategorized__';\n const contentData = cats[lookupCat]?.[customId];\n if (!contentData || typeof contentData !== 'object') return null;\n const value = (contentData as unknown as Record<string, string>)[token];\n return typeof value === 'string' ? value : null;\n }\n\n /**\n * Raw stored translation for a phrase, without interpolation or\n * missing-token registration. Returns null when no (non-empty) translation\n * is cached. Used by the `Phrase` rich-text handler, which needs the\n * un-interpolated template (it supplies its own markup-token values).\n */\n public lookup(phrase: string, category: string): string | null {\n const cats = activeCatalog();\n const lookupCat = category || '__uncategorized__';\n // The catalog key never carries a C0 control (TOK-2), on lookup as on register.\n const value = cats[lookupCat]?.[stripC0Controls(phrase)];\n return typeof value === 'string' && value.length > 0 ? value : null;\n }\n\n private buildTFn(): TFunction {\n // Single runtime body covers both overload shapes. Position 2 is the\n // discriminator: string ⇒ category, object ⇒ params (no category).\n // t(phrase) → category='', params=undefined\n // t(phrase, {params...}) → category='', params={params}\n // t(phrase, 'Category') → category='Category', params=undefined\n // t(phrase, 'Category', {params...}) → category='Category', params={params}\n const fn = ((phrase: string, ...rest: unknown[]): string => {\n // Inside a request scope (SRV-7), the scope's catalog and miss collection,\n // never the page's: the page's state is shared by every render in the process.\n const scope = activeScope();\n // A scope with credentials of its own is configured whatever the module is (SRV-2).\n if (!scope?.credentials) this.assertConfigured();\n if (scope) return scope.t(phrase, ...rest);\n return this.renderWith(this.pageView, phrase, rest);\n }) as TFunction;\n return fn;\n }\n\n /** The page's catalog, locale and miss queue: what `t()` uses outside every request scope. */\n private readonly pageView: CatalogView = {\n catalog: () => pageCatalog(),\n locale: () => pageLocale(),\n miss: (category, key, onlyForRegistration) => this.missingToken(category, key, onlyForRegistration),\n fromSnapshot: () => this.catalogFromSnapshot,\n };\n\n /**\n * The body of `t()` over a catalog view: the page's, or a request scope's\n * (SRV-7). One implementation, so a scope looks up, converts legacy keys,\n * strips C0 controls and interpolates exactly as the page does, and differs\n * only in whose catalog it reads and whose misses it records.\n */\n public renderWith(view: CatalogView, phrase: string, rest: unknown[]): string {\n // A tagged template, t`Hello ${{ name }}`: each value named by its object's one key\n // becomes a placeholder with the value as its param (VAR-1, VAR-2). A value that\n // cannot be named is rendered but never registered (VAR-7).\n if (isTemplateStrings(phrase)) {\n const tagged = fromTaggedTemplate(phrase, rest);\n if (tagged.phrase === null) {\n warnUnregistered('tagged-template');\n return tagged.text;\n }\n phrase = tagged.phrase;\n rest = [tagged.params];\n }\n let category = typeof rest[0] === 'string' ? rest[0] : '';\n const params = (typeof rest[0] === 'object' ? rest[0] : rest[1]) as Record<string, unknown> | undefined;\n\n // In the legacy-key mode the argument is resolved as a key first (MIG-2):\n // a hit becomes the key's converted source value, never the key string.\n if (this.legacyKeys) ({ phrase, category } = this.resolveLegacyKey(phrase, category));\n\n const cats = view.catalog();\n // '__uncategorized__' is a server-internal bucket name used only\n // in GET /translations responses to group null-category phrases.\n // We normalize to it for the local cats lookup (so we read from\n // the same bucket the server writes to), but we MUST NOT leak\n // the sentinel back into the missingToken queue — that queue\n // feeds the POST wire payload, and clients are not allowed to\n // send the reserved sentinel as a category.\n const lookupCat = category || '__uncategorized__';\n const bucket = cats[lookupCat];\n\n // KEY PRESENCE, not truthiness. Three states, and the middle one is\n // common rather than exotic:\n // 1. key absent — never seen. A genuine miss.\n // 2. key present, value null — registered, translation still being\n // produced by MT (a minute or two).\n // 3. key present, non-empty — translated.\n // States 2 and 3 both render the source-text fallback, but only\n // state 1 may register/report. Collapsing 2 into 1 would make every\n // visitor during the MT window re-report content that was already\n // registered — worst on exactly the projects with the most\n // untranslated content, which is the amplification this design\n // exists to prevent.\n //\n // `hasOwnProperty` rather than `in`: the catalog comes from\n // JSON.parse and so inherits Object.prototype, and `in` walks the\n // chain — `t('toString')` and `t('constructor')` would read as\n // already-known and never register.\n // The catalog key is the phrase with TOK-2's C0 controls removed, on lookup and on\n // registration alike. What renders when there is no translation is the phrase as\n // the caller wrote it: the strip governs identity, not output.\n const key = stripC0Controls(phrase);\n const known = !!bucket && Object.prototype.hasOwnProperty.call(bucket, key);\n const value = known ? bucket[key] : undefined;\n\n let translated: string;\n if (typeof value === 'string' && value.length > 0) {\n this.debug.log('TRANSLATION FOUND', [lookupCat, phrase, value]);\n translated = value;\n } else {\n if (!known) view.miss(category, key, false);\n translated = phrase;\n }\n // A phrase the snapshot holds is not yet known to the live catalog. It is\n // queued for registration without a discovery report, and the flush,\n // held until the live catalog arrives, drops it there if it is present.\n if (known && view.fromSnapshot()) view.miss(category, key, true);\n\n // Interpolated with or without params. Returning early without them\n // rendered a select or plural as its raw source, where ICU-1 renders the\n // `other` branch and ICU-3 shows `{count}` in place of a `#` with no count.\n // Plain text, braces included, comes back exactly as written.\n return interpolate(translated, params ?? {}, view.locale());\n }\n\n /**\n * Turn on the legacy-key mode with the app's kept source-language files, or\n * turn it off with null (MIG-1). Throws `LegacyFormatError` for a file this\n * core does not read (MIG-7), before anything resolves through it.\n */\n public setLegacyKeys(files: LegacyKeyFile[] | null | undefined): void {\n this.legacyKeys = files && files.length > 0 ? createLegacyKeys(files) : null;\n this.warnedLegacy.clear();\n }\n\n /**\n * A key hit is the key's converted value, and the key's namespace is the\n * category unless the call passed one (MIG-3, MIG-5). A miss is the argument\n * as literal source text, which Langsys `t()` does not convert (MIG-2), and\n * is noted at debug so a mistyped or removed key is visible (MIG-6). A value\n * the conversion does not recognise registers as written and warns at every\n * log level, naming the file and the key (MIG-4).\n */\n private resolveLegacyKey(arg: string, category: string): { phrase: string; category: string } {\n const hit = this.legacyKeys!.resolve(arg);\n if (!hit) {\n if (logger.debugEnabled && this.warnOnce(`miss\\0${arg}`)) {\n logger.warn(`\"${arg}\" is not a key in the legacy source files, so it registers as literal source text.`);\n }\n return { phrase: arg, category };\n }\n if (!hit.recognised && this.warnOnce(`value\\0${hit.file}\\0${hit.key}`)) {\n logger.warn(`The legacy key \"${hit.key}\" in ${hit.file} ${hit.issue}, so its value registers exactly as written.`);\n }\n return { phrase: hit.phrase, category: category || hit.category || '' };\n }\n\n private warnOnce(key: string): boolean {\n if (this.warnedLegacy.has(key)) return false;\n this.warnedLegacy.add(key);\n return true;\n }\n\n /**\n * Record a miss on the page's lanes, as `t()` outside every scope does: for a\n * request scope rebuilt from a seed on the client (`scopeFromSeed`), whose\n * render's misses belong to the page.\n */\n public recordPageMiss(category: string, token: string): void {\n this.missingToken(category, token);\n }\n\n private missingToken(category: string, token: string | undefined | null, onlyForRegistration = false) {\n if (token === undefined || token === null) {\n return this.debug.warn(`Received undefined or null token for category: ${category}`);\n }\n\n // No id-shape test here (REG-12). A block is recognised by structure: its catalog\n // value is a nested map, which `t()` counts as known by key presence, so a stored\n // block never reaches this method, and no caller hands `t()` a custom id (core,\n // bindings and JS Server searched). A `/^[0-9a-f]{32}$/` guard used to sit here,\n // and with the structure in hand it could only reject a legitimate phrase that\n // happens to look like a hash.\n if (token === 'toJSON') {\n this.debug.error(`Received toJSON as token ${category}:${token}`, token);\n return;\n }\n if (token === '') {\n this.debug.warn('Received empty token', token);\n return;\n }\n\n // NOTE: no write-capability check here. It used to live at this line as\n // `key_type !== 'write'`, which cannot express the current model — an\n // `ip_write` key is read-only everywhere except from allow-listed IPs,\n // and the discovery renderer relies on running this exact, unmodified\n // path from such an IP. Worse, gating COLLECTION means a `t()` call\n // landing before `validate()` resolves is dropped forever. The decision\n // now happens at the flush site, so pre-authorization misses are held\n // rather than discarded, and the lane is chosen once it's actually known.\n //\n // REG-11 — an ellipsis in the phrase itself is usually upstream\n // truncation: the truncated form gets translated and stored, never\n // matches the full paragraph, and the paragraph later registers as a\n // second phrase. Catalog pollution plus double translation spend.\n //\n // WARN ONLY, deliberately. A blanket skip has real false positives —\n // \"Loading…\", \"Saving…\", \"Please wait…\" are legitimate phrases — and\n // silently refusing to register them would create a NEW silent failure,\n // which is the class this whole surface exists to remove. The spec\n // permits suppression only on a second signal (a longer catalog entry\n // sharing the prefix); that is not implemented here, so nothing is\n // skipped. Note CSS truncation needs no handling: `text-overflow` and\n // `-webkit-line-clamp` clip visually and leave the DOM text complete.\n // Deduped per phrase, and debug-level per the rule text. Undeduped it\n // fires on every miss of the same string — and on a read-only session\n // the phrase never becomes known, so `Loading…` warns on every render\n // for the life of the page. A diagnostic that spams is a diagnostic\n // people turn off.\n if (this.debug.debugEnabled && !this.warnedEllipsis.has(token) && /(?:…|\\.\\.\\.)\\s*$/.test(token)) {\n this.warnedEllipsis.add(token);\n this.debug.warn(\n `Langsys: phrase ends in an ellipsis — \"${token}\". If this is upstream truncation, the ` +\n `shortened form will be translated and stored, and the full text will later register as a ` +\n `separate phrase. Register the untruncated string if you can. Registering anyway.`\n );\n }\n\n // WIRE-4. Without a catalog a miss cannot be told from a hit, and treating a\n // failed fetch as \"everything is unknown\" re-registers phrases that already\n // exist: every outage becomes a write storm, on exactly the paths that were\n // already failing. Record nothing, including the discovery miss, since a hint\n // for content the catalog may hold is the same mistake on the read-only lane.\n // A successful fetch rebuilds `t`, so reactive consumers re-render and miss\n // again, and a genuine miss is recorded then.\n if (catalogUnavailable.get()) {\n this.debug.log('Not recording a miss: the catalog fetch failed, so a miss cannot be told from a hit', { category, token });\n return;\n }\n\n // The base-locale gate, a project setting delivered in the handshake. On a page a\n // server SDK rendered in another language every string is a translation, so\n // registering one files a Spanish sentence as a SOURCE phrase, and hinting sends\n // the renderer to a localized URL to find the same text. Both lanes, so neither\n // happens. The loaded locale is empty until the first catalog publishes, so the\n // locale being fetched stands in for it.\n if (discoveryBaseLocaleOnly.get()) {\n const loaded = currentlyLoadedLocale.get() || this.locale;\n if (loaded !== canonicalizeLocale(this.config.baseLocale || '')) {\n this.debug.log('Not recording a miss: discovery is limited to the base locale', { category, token, loaded });\n return;\n }\n }\n\n // Recorded before the queue dedup below: the discovery lane keys on the\n // URL the miss occurred on, and a phrase already queued from an earlier\n // route must not suppress the record for the page being viewed now.\n if (!onlyForRegistration) recordMissForDiscovery(category, token);\n\n // The server's request scope sends this phrase itself after the response (its\n // seed says so, SSR-1/SSR-2), so queueing it here would register it twice.\n if (isServerCollectedPhrase(category, token)) {\n this.debug.log('Not queueing for registration: the server registers this phrase', { category, token });\n return;\n }\n\n // Discovery has it; only hold it for registration if that queue can\n // actually drain. See `shouldQueueForWrite`.\n if (!this.shouldQueueForWrite()) {\n this.debug.log('Not queueing for registration (no reachable flush path)', { category, token });\n return;\n }\n\n const missingToken: iTokenUpdate = { category, token, projectid: this.config.projectid };\n if (!this.missingTokens.some((t) => sameToken(t, missingToken))) {\n this.debug.log('MISSING TOKEN LOOKUP FAILED', [missingToken, [...this.missingTokens], { ...sTranslations.get() }]);\n this.missingTokens.push(missingToken);\n this.scheduleTokenFlush();\n }\n }\n\n /**\n * Whether this session may write. The single decision point for the write\n * lane — never infer capability from `key_type`.\n *\n * In the browser the server-computed signal is authoritative, and `undefined`\n * (not yet authorized) correctly holds rather than writing or hinting.\n *\n * Under SSR the signal is deliberately never written (it is a process-wide\n * singleton and write capability is per-session), so we fall back to the\n * value the last catalog fetch reported for THIS process. That is only sound\n * while capability depends on the server's IP alone, which is constant for\n * the process. A configured write grant makes it per-user instead, so the\n * server lane is unsafe and we degrade to flushing after hydration — where\n * the decision is per-user and correct.\n */\n /** Whether this session may write now, by the same decision the flush makes (see `canWrite`). */\n public mayWrite(): boolean {\n return this.canWrite();\n }\n\n private canWrite(): boolean {\n if (typeof window !== 'undefined') return writeEnabled.get() === true;\n if (LangsysAppAPI.hasWriteGrant()) return false;\n return this.ssrWriteEnabled === true;\n }\n\n /**\n * Record the server's write decision from an `authorize-project` or catalog\n * response. Browser: updates the shared signal. Server: keeps a\n * process-level copy used only when no grant is configured (see `canWrite`).\n *\n * `keyType` is the key type the same response describes. The authorization path\n * passes it, because it runs before `init()` hands this instance the new config:\n * reading `this.config` there would describe the PREVIOUS init's key on a re-init.\n */\n public applyWriteEnabled(value: boolean | undefined, keyType: string | undefined = this.config.key_type): void {\n if (typeof value !== 'boolean') return;\n setWriteEnabled(value);\n if (typeof window === 'undefined') this.ssrWriteEnabled = value;\n // OBS-1 reaches BOTH capability channels. This one runs on every\n // catalog fetch — which is why it exists: capability can change without\n // a re-init, and an `ip_write` key whose address drops off the\n // allow-list mid-session is exactly the silent failure OBS-1 names. The\n // notice was previously wired only to `authorize-project`, so that\n // transition said nothing at all.\n noticeUnusableWriteCapability(value, keyType);\n }\n\n /**\n * Whether a miss is worth holding in the REGISTRATION queue. Distinct from\n * `canWrite()`, which decides whether to send: this decides whether keeping\n * it could ever lead to a send.\n *\n * What happens to a declined miss differs by arm, and the difference is\n * load-bearing rather than incidental:\n *\n * - In the BROWSER the discovery lane has already recorded it, so the page\n * is still reported and nothing is lost.\n * - Under SSR it is recorded NOWHERE — `recordMissForDiscovery` bails\n * without a `window`. The safety net there is that the client re-runs\n * `t()` after hydration and re-collects, which covers content rendered\n * on both sides and does NOT cover content that only ever executes\n * server-side. That gap is real and documented rather than closed.\n *\n * Two ways a queue becomes undrainable:\n *\n * SSR under `'client'` — the queue is meant to be flushed after hydration\n * by `setup()`, but that reads the BROWSER's instance of this module. The\n * push happened in the Node process's instance. Under real SSR (Next,\n * Remix, Astro) those are different objects in different processes, and no\n * channel carries tokens client-ward — `initialTranslations` goes the other\n * way. So the tokens are silently dropped AND retained forever, since the\n * 3s drain timer only exists in the browser branch of `setup()`. In a\n * long-lived server that plateaus at \"every phrase the app has ever\n * server-rendered\", held live and never sent. Declining to collect makes\n * the limitation explicit instead of silent: server-side discovery requires\n * `ssrTokenStrategy: 'server'`.\n *\n * Browser, definitively read-only — `writeEnabled` is `false` and no grant\n * is configured, so no path exists by which this session becomes writable.\n * (`undefined` still queues: capability isn't known yet and those misses\n * must be held, not dropped. A configured grant also queues, since one\n * arriving flips the session write-enabled.)\n */\n private shouldQueueForWrite(): boolean {\n if (typeof window === 'undefined') {\n // A configured grant makes the SSR write lane unusable — `canWrite`\n // refuses it, because capability is then per-user and this queue is\n // process-wide. Collecting anyway rebuilds precisely the\n // undrainable plateau this method exists to prevent: nothing here\n // can ever send it, and the `writeEnabled` release path can't fire\n // either, since that signal is never written server-side. The\n // degradation to the client lane is real, so the server instance\n // must also stop collecting — not just stop sending.\n const strategy = this.config.ssrTokenStrategy || 'client';\n if (LangsysAppAPI.hasWriteGrant()) {\n if (strategy !== 'client') noticeSsrGrantDegradation(strategy);\n return false;\n }\n if (strategy === 'server') return true;\n if (strategy === 'auto') {\n // Past the threshold 'auto' defers to a client that can't receive it.\n return this.missingTokens.length < AUTO_SSR_FLUSH_THRESHOLD;\n }\n return false;\n }\n\n if (writeEnabled.get() === false && !LangsysAppAPI.hasWriteGrant()) return false;\n return true;\n }\n\n private scheduleTokenFlush() {\n const strategy = this.config.ssrTokenStrategy || 'client';\n const isSSR = typeof window === 'undefined';\n\n if (isSSR) {\n switch (strategy) {\n case 'server':\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => void this.updateTokens());\n }\n break;\n\n case 'auto':\n if (this.missingTokens.length <= AUTO_SSR_FLUSH_THRESHOLD && !this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => void this.updateTokens());\n }\n break;\n\n case 'client':\n default:\n this.debug.log('SSR: Queuing tokens for client-side transmission');\n break;\n }\n } else {\n // Client — debounce briefly so a burst of misses coalesces into one\n // POST, then send. It used to wait for the next 3s interval tick\n // (the immediate path was gated on `!this.timer`, so it only ever\n // ran before setup() installed the timer), which meant any content\n // rendering after init was held for up to 3s. That is fatal for\n // late-arriving content: the discovery renderer grants roughly 4s\n // after its scroll phase, so an up-to-3s hold left about 1s of real\n // budget, and anything past it was recorded and then destroyed with\n // the page. Lazy-loaded and streamed content — precisely what the\n // renderer exists to discover — is the common case for that.\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.updateTokens();\n }, CLIENT_FLUSH_DEBOUNCE_MS);\n }\n\n // Arm the backstop only now that something is actually queued.\n this.ensureBackstop();\n }\n }\n\n /**\n * Start the backstop interval if it isn't already running.\n *\n * Demand-driven deliberately. It used to start in `setup()` and run for the\n * life of the page whether or not anything was ever queued — a wakeup every\n * three seconds forever, for a queue that is empty almost all of the time.\n * That is a battery and background-work cost on mobile, and React Native\n * takes this same branch because it defines `window`.\n *\n * The tick disarms itself once the queue drains; the next miss re-arms it\n * through `scheduleTokenFlush`. While sends keep failing the queue stays\n * non-empty and the interval keeps running, which is the case a backstop\n * exists for.\n */\n private ensureBackstop(): void {\n if (this.timer) return;\n this.timer = setInterval(() => void this.updateTokens(), BACKSTOP_INTERVAL_MS);\n this.debug.log('UPDATE TOKEN INTERVAL', this.timer);\n }\n\n private stopBackstop(): void {\n if (!this.timer) return;\n clearInterval(this.timer);\n this.timer = null;\n }\n\n /**\n * Stop background work. Queued tokens stay queued, and further discovery\n * re-arms the backstop — this releases the timer, it does not discard work.\n */\n public destroy(): void {\n this.stopBackstop();\n this.releaseTeardownFlush?.();\n this.releaseTeardownFlush = null;\n }\n\n /**\n * Send whatever is still queued while the page is going away.\n *\n * Even with the debounce there is always a window where a miss is queued\n * and the document is torn down — a tab closing, a client-side navigation,\n * or the discovery renderer finishing its grace period. A normal request is\n * cancelled with the document; `keepalive` survives it.\n *\n * Deliberately NOT `navigator.sendBeacon`, the usual answer here: it cannot\n * set custom headers, and our authorization is `x-Authorization`, so every\n * beacon would be rejected.\n *\n * Fire-and-forget with no local bookkeeping — the page is leaving, so there\n * is no \"after\" in which a cache write or queue mutation could matter, and\n * skipping them keeps this off the critical path of teardown.\n */\n private flushOnTeardown(): void {\n if (!this.missingTokens.length) return;\n this.debug.log(`Teardown flush: sending ${this.missingTokens.length} queued tokens with keepalive`);\n\n // The ordinary flush path, only with keepalive — NOT a bespoke\n // fire-and-forget send. `visibilitychange → hidden` also fires on a\n // plain tab switch, where the page does not go away; a send that\n // skipped the bookkeeping would leave everything queued and the 3s\n // backstop would re-send it all on return. Reusing the normal path\n // means the queue is cleared and the catalog updated exactly as usual\n // when the page survives, and when it genuinely dies the request is\n // already dispatched and the unrun bookkeeping costs nothing.\n void this.updateTokens(true);\n }\n\n /**\n * `visibilitychange → hidden` is the reliable teardown signal; `pagehide`\n * backs it up. `unload`/`beforeunload` are deliberately not used — they are\n * unreliable on mobile and block bfcache.\n */\n private installTeardownFlush(): void {\n // Registered with an injected teardown signal on every host, before the document\n // check: a host with no `document` — React Native — has no other way to flush.\n // Re-registered after `destroy()` released it; the document listeners below are\n // installed once per instance, so a second setup never doubles them.\n if (!this.releaseTeardownFlush) this.releaseTeardownFlush = _registerTeardownFlush(() => this.flushOnTeardown());\n if (this.teardownInstalled) return;\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n this.teardownInstalled = true;\n\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') this.flushOnTeardown();\n });\n window.addEventListener('pagehide', () => this.flushOnTeardown());\n }\n\n public setup(config: iLangsysConfig) {\n this.config = config;\n if (!this.config.projectid || !this.config.key) return;\n\n if (this.config.debug) this.debug.debugEnabled = this.config.debug;\n if (config.baseLocale) this.locale = canonicalizeLocale(config.baseLocale);\n\n this.debug.log('TRANSLATION SETUP INITIATED', this.config);\n\n if (typeof window !== 'undefined') {\n if (this.isFirstClientRun && this.missingTokens.length > 0) {\n this.isFirstClientRun = false;\n const strategy = this.config.ssrTokenStrategy || 'client';\n if (strategy === 'client' || (strategy === 'auto' && this.missingTokens.length > 5)) {\n this.debug.log(`Post-hydration: Flushing ${this.missingTokens.length} SSR-collected tokens`);\n queueMicrotask(() => this.updateTokens());\n }\n }\n\n this.installTeardownFlush();\n\n // Backstop only — the debounce in scheduleTokenFlush is what\n // actually sends. This catches anything a failed send left queued,\n // and runs only while there IS something queued: a fresh setup\n // re-arms it iff a backlog survived (an SSR handoff, or a previous\n // setup on this instance).\n this.stopBackstop();\n if (this.missingTokens.length) this.ensureBackstop();\n } else {\n const strategy = this.config.ssrTokenStrategy || 'client';\n this.debug.log(`SSR environment detected - using '${strategy}' token strategy`);\n }\n }\n\n /**\n * Record that a locale's catalog is already present without fetching —\n * e.g. after an SSR handoff seeds `sTranslations` + `currentlyLoadedLocale`.\n * This primes the same `lastLoaded` cache `change()` consults, so the first\n * settle for that locale is a cache hit (no redundant fetch) while every\n * later switch *to* it still flows through `change()` normally.\n */\n public markLoaded(locale: string): void {\n if (!locale) return;\n locale = canonicalizeLocale(locale);\n this.locale = locale;\n this.lastLoaded[locale] = new Date().getTime() / 1000;\n this.catalogFromSnapshot = false;\n catalogUnavailable.set(false);\n // A seeded catalog counts as \"ready\": the cache hit above means no\n // fetch will ever fire to resolve the promise, and content-block /\n // Phrase consumers awaiting ready() would otherwise hang forever.\n this.readyResolve();\n }\n\n /**\n * A catalog is present for rendering, but it is not the catalog of record:\n * a snapshot (SNAP-3). Unlike `markLoaded` nothing is recorded as fetched,\n * so the next settle for the locale still fetches the catalog and replaces\n * it. What waits on `ready()` renders from it now.\n */\n public markSeeded(): void {\n this.catalogFromSnapshot = true;\n catalogUnavailable.set(false);\n this.readyResolve();\n }\n\n /**\n * React to a user-locale change. Fetches translations if we haven't\n * loaded this locale within the last 60s (or if forced).\n */\n public async change(locale: string, force = false, skipFetch = false): Promise<boolean> {\n if (!locale) return false;\n if (!this.config.projectid || !this.config.key) return false;\n // Canonical form is the cache identity — `en-us` and `en-US` must hit\n // the same `lastLoaded` entry and compare equal to `this.locale`.\n locale = canonicalizeLocale(locale);\n\n // Point the cache at this project+locale BEFORE anything reads or\n // writes the catalog. A hit warms the start; a miss simply misses.\n // Previously the cache was keyed by neither, so a page load restored\n // whatever was stored and served it until a fetch replaced it.\n scopeCatalogCache(this.catalogScope(locale));\n\n if (skipFetch) {\n this.debug.log('Using pre-fetched translations for locale', locale);\n catalogUnavailable.set(false);\n this.locale = locale;\n this.lastLoaded[locale] = new Date().getTime() / 1000;\n this.readyResolve();\n return true;\n }\n\n const now = new Date().getTime() / 1000;\n if (\n !force &&\n locale === this.locale &&\n this.lastLoaded[locale] &&\n Math.abs(this.lastLoaded[locale] - now) < 60\n ) {\n return false;\n }\n\n this.debug.log('Locale change detected!', locale);\n this.locale = locale;\n const scope = this.catalogScope(locale);\n\n // CACHE-2: inside the window after a failure, keep rendering source text for this pair\n // and fetch nothing, so an outage is not paid again on every locale emission. An\n // explicit refresh (`force`) is a deliberate request rather than a lookup, and still\n // goes out.\n const failure = this.catalogFailures.get(scope);\n if (!force && failure && Date.now() < failure.retryAt) {\n this.debug.log('Catalog fetch skipped: the last one for this project and locale failed', {\n scope,\n retryInMs: failure.retryAt - Date.now(),\n });\n this.markCatalogUnavailable();\n return false;\n }\n\n let request = this.catalogRequests.get(scope);\n if (!request) {\n request = this.fetchCatalog(scope).finally(() => this.catalogRequests.delete(scope));\n this.catalogRequests.set(scope, request);\n }\n this.catalogFetchesInFlight += 1;\n try {\n await request;\n } finally {\n this.catalogFetchesInFlight -= 1;\n }\n // Tokens held while the catalog was in flight can be checked against it now.\n // Without this they would wait for the next backstop tick, and SSR has no\n // backstop at all.\n if (this.missingTokens.length && !catalogUnavailable.get()) this.scheduleTokenFlush();\n return true;\n }\n\n /** The project and locale a catalog belongs to: its cache key, request key and CACHE-2 pair. */\n private catalogScope(locale: string): string {\n return catalogScopeOf(this.config.projectid, locale);\n }\n\n /** One catalog request for a project and locale, recording the outcome for CACHE-2's window. */\n private async fetchCatalog(scope: string): Promise<boolean> {\n const ok = await this.getTranslations();\n if (ok) {\n this.catalogFailures.delete(scope);\n return true;\n }\n const failures = (this.catalogFailures.get(scope)?.failures ?? 0) + 1;\n this.catalogFailures.set(scope, { failures, retryAt: Date.now() + failureWindowMs(failures) });\n return false;\n }\n\n /**\n * Record a failed send and push the next attempt out exponentially:\n * 3s, 6s, 12s … capped at 5 minutes. Reset on the first success.\n */\n private noteSendFailure(): void {\n this.consecutiveFailures += 1;\n const delay = Math.min(\n RETRY_BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),\n RETRY_BACKOFF_MAX_MS,\n );\n this.retryNotBefore = Date.now() + delay;\n this.debug.log(`Registration send failed (${this.consecutiveFailures}x); next attempt in ${delay}ms`);\n }\n\n private async updateTokens(keepalive = false): Promise<boolean> {\n // The scheduled flush has now started, so release the scheduling latch.\n // `flushScheduled` guards only the window between scheduling and\n // execution — holding it until the POST resolves would swallow the\n // follow-up flush this method schedules in its own `finally`.\n this.flushScheduled = false;\n\n // The 3s interval calls this unconditionally, so without a lock a call\n // can start while a previous one is still awaiting its POST — which\n // re-sends the same tokens (they aren't cleared until the response\n // lands) and makes the \"what did I actually send\" bookkeeping below\n // ill-defined.\n // `keepalive` means this is the teardown flush, and neither of the two\n // guards below applies to it. The in-flight request is about to die\n // with the document and its batch is still queued, so deferring to it\n // loses exactly the work teardown exists to save; and a backoff window\n // is about waiting for a *later* attempt, of which there will be none.\n // Re-sending is safe: registration is idempotent server-side (advisory\n // lock plus ON CONFLICT), so a duplicate costs a request, while\n // deferring costs the content.\n const isTeardown = keepalive;\n\n if (!isTeardown && this.updateInFlight) return false;\n if (!this.missingTokens.length) {\n // Disarm here as well as at the sites that empty the queue. Those\n // are the immediate path; this is the structural one, so a future\n // path that empties the queue without knowing about the backstop\n // cannot leave it spinning.\n this.stopBackstop();\n return false;\n }\n if (!isTeardown && this.retryNotBefore && Date.now() < this.retryNotBefore) return false;\n if (!this.config.projectid || !this.config.key) return false;\n // WIRE-4. Tokens queued before the fetch failed are HELD, not sent: the dedup\n // below filters against the catalog, and there is no catalog to filter against.\n // The next catalog that arrives lifts the hold and the dedup then drops whatever\n // it already holds. Applies to the teardown flush too, which has no dedup either.\n if (catalogUnavailable.get()) {\n this.debug.log('Holding queued tokens: the catalog fetch failed, so they cannot be deduplicated');\n return false;\n }\n // The same hold while a catalog fetch is still in flight. A write-enabled cold\n // visit flushed its first misses after the debounce against a catalog that had\n // not arrived, and POSTed phrases the backend already held whenever the fetch\n // outlasted the debounce (measured at 1s and 5s, not at 300ms). A locale switch\n // has the same window, because the new scope starts empty. Arrival schedules\n // the flush, so nothing waits for the backstop.\n if (this.catalogFetchesInFlight > 0) {\n this.debug.log('Holding queued tokens until the catalog in flight arrives');\n return false;\n }\n // A snapshot is not the catalog of record: deduplicating against it would\n // register nothing it holds and re-register nothing it lacks correctly.\n if (this.catalogFromSnapshot) {\n this.debug.log('Holding queued tokens until the live catalog replaces the snapshot');\n return false;\n }\n if (!this.canWrite()) {\n this.debug.log('Skipping token updates (session is not write-enabled)', {\n writeEnabled: writeEnabled.get(),\n key_type: this.config.key_type || 'unknown',\n });\n return false;\n }\n\n if (typeof window === 'undefined') {\n this.debug.log(`Sending ${this.missingTokens.length} tokens from SSR`);\n }\n\n const currentData = pageCatalog();\n this.missingTokens = this.missingTokens.filter((tokenObj) => {\n tokenObj.projectid = this.config.projectid;\n // The server response keys null-category phrases under\n // '__uncategorized__', so map empty client-side category to that\n // bucket for the dedup check only. The queue itself keeps the\n // original (possibly empty) category for the wire payload.\n const lookupCat = tokenObj.category || '__uncategorized__';\n // hasOwnProperty, not `in` — same prototype-chain hazard as the\n // lookup in `t()`. With `in`, a phrase named `toString` or\n // `constructor` is queued by `t()` (which tests own properties) and\n // then silently filtered out of every send here, so it re-queues\n // forever and is never registered.\n const bucket = currentData[lookupCat];\n if (bucket && Object.prototype.hasOwnProperty.call(bucket, tokenObj.token)) {\n this.debug.log('Missing token already exists! Skipping:', {\n category: tokenObj.category,\n token: tokenObj.token,\n existing: currentData[lookupCat][tokenObj.token],\n });\n return false;\n }\n return true;\n });\n\n if (!this.missingTokens.length) return false;\n\n // Snapshot the batch. Everything below operates on THIS list and never\n // on the live array, because `t()` keeps running during the awaits:\n // a miss recorded mid-flight would otherwise be marked present in the\n // catalog and wiped from the queue without ever having been in a\n // payload — and since it then reads as already-registered, it would\n // never be retried. Silent, permanent loss, and the window is every\n // in-flight POST (a modal opening, a route change, lazy content\n // resolving), worst on a first visit when the catalog is emptiest.\n const batch = [...this.missingTokens];\n let drained = false;\n\n // The teardown flush deliberately doesn't take the lock — it ran past\n // it above, so it must not clear a lock a live request still owns.\n if (!isTeardown) this.updateInFlight = true;\n this.debug.log('CREATE MISSING TOKENS', batch);\n try {\n // Wire boundary: empty category → null. '__uncategorized__' is\n // server-internal and is rejected as a client input.\n const phraseItems = batch.map((tokenObj) => ({\n type: 'phrase',\n phrase: tokenObj.token,\n category: tokenObj.category || null,\n }));\n\n // /translatable-items caps each request (default 200 items); chunk so\n // a page registering many new phrases at once never overflows it.\n // Keepalive requests share a ~64KB budget across everything in\n // flight, well below what 200 phrases can reach — and an oversized\n // keepalive request is rejected by the browser, losing the batch at\n // exactly the moment there is no retry left. So the teardown path\n // really does chunk more conservatively than the normal one, which\n // until now was only claimed in a comment.\n const BATCH_SIZE = isTeardown ? Math.min(50, batchLimit.get()) : batchLimit.get();\n for (let offset = 0; offset < phraseItems.length; offset += BATCH_SIZE) {\n // The page's queue, under the page's key, wherever the flush was scheduled (SRV-2).\n const response: ResponseObject = await LangsysAppAPI.createTranslatableItems(\n phraseItems.slice(offset, offset + BATCH_SIZE),\n { keepalive, credentials: LangsysAppAPI.moduleCredentials() },\n );\n if (!response.status) {\n if (response.errors) {\n this.debug.log('TOKEN UPDATE FAIL', batch);\n this.debug.error('Error updating project tokens', response.errors);\n }\n // Leave the batch queued — a failed send must be retryable.\n this.noteSendFailure();\n return false;\n }\n }\n\n // Re-read: a catalog fetch may have replaced the store while we were\n // in flight, and writing back the pre-await snapshot would clobber it.\n const latest = pageCatalog();\n batch.forEach((tokenObj) => {\n // Same bucket normalization as the dedup check: write into\n // the cats bucket that matches the server response shape.\n const lookupCat = tokenObj.category || '__uncategorized__';\n if (!latest[lookupCat]) {\n latest[lookupCat] = {\n __category__: lookupCat,\n __symbol__: lookupCat,\n } as iTranslations;\n }\n // Known now, with no translation, as the API serves such a phrase (`null`), unless that\n // catalog already holds it: a switch's catalog, published while the request was out,\n // may carry its translation. Known by key presence, it is never sent again; `lookup`\n // reads it as a miss, so an earlier key's translation still renders (TOK-1) and its\n // source is never marked resolved (GATE-10).\n if (!Object.prototype.hasOwnProperty.call(latest[lookupCat], tokenObj.token)) latest[lookupCat][tokenObj.token] = null as unknown as string;\n latest[lookupCat]['__category__'] = lookupCat;\n });\n sTranslations.set({ ...latest });\n\n // Remove exactly what was sent, never `= []`.\n this.missingTokens = this.missingTokens.filter((queued) => !batch.some((s) => sameToken(s, queued)));\n drained = true;\n this.consecutiveFailures = 0;\n this.retryNotBefore = 0;\n return true;\n } catch (err) {\n this.debug.log('CREATE MISSING TOKEN FAILURE', batch);\n this.debug.error('Error updating project tokens', err);\n this.noteSendFailure();\n return false;\n } finally {\n if (!isTeardown) this.updateInFlight = false;\n // Anything recorded during the flush is still queued. The browser's\n // 3s timer would eventually take it, but SSR has no timer at all —\n // without this the remainder would sit unsent for the process's life.\n // Guarded on an actual successful drain, so a persistently failing\n // send retries on the normal cadence rather than spinning here.\n if (drained && this.missingTokens.length) this.scheduleTokenFlush();\n\n // Nothing left to back off for. Placed here rather than on the tick\n // so the debounced send disarms it too — otherwise the interval\n // outlives its queue by up to one full period, every time.\n if (!this.missingTokens.length) this.stopBackstop();\n }\n }\n\n /**\n * WIRE-4: the catalog fetch failed. Settle `ready()` so consumers render their\n * source text, and mark the catalog unusable for deciding what is missing.\n *\n * The second half is the one that needs saying. Measured before it existed, with\n * write capability already granted: a network-failed fetch let `t()` misses queue\n * and POST phrases that were already registered, and a failed locale switch did\n * the same, because the new scope had just reset the catalog to empty.\n */\n private markCatalogUnavailable(): void {\n catalogUnavailable.set(true);\n this.readyResolve();\n }\n\n /**\n * Fetch and publish the catalog for `this.locale`. Resolves false when it could not.\n *\n * The response publishes only while the locale and cache scope it was requested for are\n * still current. A locale change while it is in flight supersedes it, and it is dropped\n * when it lands: published, it would show the previous locale's catalog under the new\n * one, persist it under the new locale's cache key, and stamp the new locale as loaded,\n * so `change()` would not fetch that locale for another 60s. A superseded response still\n * resolves true or false, which `fetchCatalog` records against its own pair (CACHE-2).\n */\n private async getTranslations(): Promise<boolean> {\n if (!LangsysAppAPI.config.projectid && this.config.projectid) {\n LangsysAppAPI.setup(this.config);\n }\n\n const locale = this.locale;\n const scope = this.catalogScope(locale);\n const current = () => locale === this.locale && scope === this.catalogScope(this.locale);\n\n let response: ResponseObject;\n try {\n // The page's catalog, under the page's key, even when the change starts inside a scope (SRV-2).\n response = await LangsysAppAPI.getTranslations(locale, { credentials: LangsysAppAPI.moduleCredentials() });\n } catch (err) {\n // `send()` already turns a network failure into an error envelope, so this\n // is the client itself throwing. Still an expected condition (WIRE-4), and\n // `change()` runs un-awaited from the locale subscription, where a\n // rejection has no caller to land on.\n this.debug.error('Catalog fetch threw', err);\n if (current()) this.markCatalogUnavailable();\n return false;\n }\n this.debug.log('GET TRANSLATIONS API RESPONSE', response);\n\n if (!current()) {\n this.debug.log('Catalog response dropped: the locale changed while it was in flight', {\n requested: locale,\n current: this.locale,\n });\n return !response.errors;\n }\n\n // Envelope-level, alongside `words` / `untranslated_words` — never\n // inside `data`, which IS the category map. Refreshed on every catalog\n // fetch so a capability change (a grant arriving, an IP allow-list\n // edit) is picked up without re-running init.\n this.applyWriteEnabled(answeredWriteDecision(response));\n\n // Project policy, re-read on every fetch so a mid-session flip is picked up\n // without re-running `init()`. A top-level sibling of `data` on both catalog\n // routes, so it never reaches the cache. Absent or non-boolean means off: a\n // server predating the field must not read as having turned it on.\n if (typeof response.discovery_base_locale_only === 'boolean') {\n discoveryBaseLocaleOnly.set(response.discovery_base_locale_only);\n }\n\n if (response.errors) {\n this.debug.error('Error', response.errors[0]);\n this.markCatalogUnavailable();\n return false;\n }\n\n // An empty project serializes `data` as `[]`, not `{}`. Left as an\n // array it would be persisted to localStorage by JSON.stringify with\n // the seeded `__uncategorized__` bucket silently dropped (string\n // properties on arrays don't survive serialization).\n const trans = (isObject(response.data) ? response.data : {}) as iCategories;\n\n if (!isObject(trans['__uncategorized__'])) {\n trans['__uncategorized__'] = {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n } as iTranslations;\n }\n\n // Drop anything in `data` that is not a category object before stamping\n // it. On `/translations` the `data` member IS the category map, so a\n // stray scalar sibling — a legacy envelope answering with\n // `{key_type:'read', ...}`, an error shape, a future field — used to\n // throw here (`Cannot create property '__category__' on string`). This\n // runs inside an un-awaited `change()`, so the rejection was unhandled:\n // it took down the caller's tick rather than degrading, and `npm test`\n // exited non-zero while every test reported passing. `types/api.ts`\n // already warns about exactly this shape.\n for (const cat of Object.keys(trans)) {\n const value: unknown = trans[cat];\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n this.debug.warn(\n `Ignoring non-category member '${cat}' in the /translations payload — expected an object of ` +\n `phrases, got ${Array.isArray(value) ? 'an array' : typeof value}. The catalog is still usable.`\n );\n delete trans[cat];\n continue;\n }\n trans[cat]['__category__'] = cat;\n }\n\n this.debug.log('GET TRANSLATIONS ' + locale, trans);\n\n // Before publishing, so subscribers re-rendering off this catalog record their\n // misses normally.\n catalogUnavailable.set(false);\n this.catalogFromSnapshot = false;\n sTranslations.set(trans);\n // Small delay so consumers see translations + locale updates on the same tick. The\n // locale is the one this catalog was fetched for, even if a switch has begun since.\n setTimeout(() => currentlyLoadedLocale.set(locale), 100);\n this.lastLoaded[locale] = new Date().getTime() / 1000;\n this.readyResolve();\n return true;\n }\n}\n\nexport default Translations;\n\n/** Whether `t` was called as a template tag: its first argument is the template's strings. */\nfunction isTemplateStrings(value: unknown): value is TemplateStringsArray {\n return Array.isArray(value) && Array.isArray((value as unknown as { raw?: unknown }).raw);\n}\n\n/**\n * A tagged template as a phrase and its params. A value written as a one-key\n * object, `${{ name }}`, is named by its key (explicit, VAR-2); any other value\n * cannot be named, and then there is no phrase, only the rendered text.\n */\nfunction fromTaggedTemplate(strings: TemplateStringsArray, values: unknown[]): { phrase: string | null; params: Record<string, unknown>; text: string } {\n const named = values.map((value) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;\n const keys = Object.keys(value);\n return keys.length === 1 ? { key: keys[0]!, value: (value as Record<string, unknown>)[keys[0]!] } : null;\n });\n const shown = named.map((n, i) => String(n ? n.value : values[i]));\n const text = strings.reduce((out, part, i) => out + part + (i < shown.length ? shown[i] : ''), '');\n if (named.some((n) => n === null)) return { phrase: null, params: {}, text };\n const names = derivePlaceholderNames(named.map((n) => ({ shape: { identifier: n!.key }, explicit: n!.key })));\n const params: Record<string, unknown> = {};\n names.forEach((name, i) => (params[name] = named[i]!.value));\n const phrase = strings.reduce((out, part, i) => out + part + (i < names.length ? `{${names[i]}}` : ''), '');\n return { phrase, params, text };\n}\n","import { LangsysAppAPI, LangsysConfigurationError } from './api.js';\nimport { canonicalizeLocale, maximizedLangScript } from './locale.js';\nimport { Logger, logger } from './logger.js';\nimport { autoDiscovery, batchLimit, catalogScopeOf, config as configStore, configured, currentlyLoadedLocale, discoveryBaseLocaleOnly, pageCatalog, pageLocale, scopeCatalogCache, sTranslations } from './stores.js';\nimport { DEFAULT_SERVER_MESSAGE_CATEGORY, fillTemplate, type ServerMessage } from './server-messages.js';\nimport { parseSnapshot, type CatalogSnapshot } from './snapshot.js';\nimport { rememberSeededBlock, rememberSeededPhrase } from './served-source.js';\nimport { settleNotices } from './notices.js';\nimport { activeScope } from './scope-context.js';\nimport type { SeededBlock, SeededPhrase } from './block-tree.js';\nimport { failureWindowMs, Translations } from './translations.js';\nimport type { ResponseObject } from './types/api.js';\nimport type { iLangsysConfig, iLangsysInitConfig, WriteGrant } from './types/config.js';\nimport type { iCountryDialCode, iCountryList } from './types/countries.js';\nimport type { iCurrencyList } from './types/currencies.js';\nimport type { iLocaleData, iLocaleDefault, iLocaleFlat } from './types/locales.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { iCategories, iTranslations } from './types/translations.js';\nimport { structuredCloneShim } from './utils.js';\n\n/**\n * One reference list in one display locale: the list held, the read in flight, or, for each\n * set of credentials a read was sent under, its failures in a row and when it may next send.\n */\ninterface ReferenceListEntry {\n list?: unknown;\n reading?: Promise<unknown>;\n failed?: Map<string, { failures: number; retryAt?: number }>;\n}\n\nclass LangsysAppClass {\n private config: iLangsysConfig;\n\n public Translations: Translations;\n public translationsLoadingPromise: Promise<unknown> = Promise.resolve();\n\n /**\n * The reference lists read so far (REF-1), keyed by list and display locale: a list the API\n * answered is held for the core's lifetime, a read in flight is shared, and a failed read is\n * remembered for CACHE-2's window under the credentials it was sent with. Memory only: on a server the core is the long-lived\n * module, so the hold already outlives the request, and nothing goes to a cache another\n * host reads (CACHE-1).\n */\n private referenceLists = new Map<string, ReferenceListEntry>();\n\n public debug: Logger;\n\n constructor() {\n this.config = configStore;\n this.debug = new Logger(!!this.config.debug);\n this.Translations = new Translations(this.config);\n }\n\n /** Current translation function. Reads fresh state on every call. */\n public get t(): TFunction {\n return this.Translations.t;\n }\n\n /**\n * Supply (or replace) the write grant after `init()` has run.\n *\n * This is for apps whose token only exists once the user logs in — i.e.\n * after the SDK has already booted. It is NOT the refresh path: the token\n * is resolved fresh before every request and never cached, so refresh is a\n * pull. Pass a provider function and let your auth layer decide when to\n * mint; that also makes this safe to call while a request is in flight,\n * since an in-flight request has already resolved its own token.\n *\n * Pass `undefined` to drop the grant (e.g. on logout).\n */\n public async setWriteGrant(grant: WriteGrant | undefined): Promise<void> {\n this.config.writeGrant = grant;\n configStore.writeGrant = grant;\n this.debug.log('Write grant', grant ? 'set' : 'cleared');\n\n // Setting config is not enough: write capability is computed by the\n // SERVER, and it has had no opportunity to re-evaluate this session\n // with (or without) the new `X-Write-Grant` header. Without this\n // re-authorization `writeEnabled` keeps whatever the original auth\n // returned — so a grant supplied after login would never take effect\n // on a stable locale, because nothing else re-derives it.\n if (!this.config.projectid || !this.config.key) return;\n const response = await LangsysAppAPI.validate(this.config);\n if (response.status && response.data) this.applyAuthorization(response.data, 'grant change');\n }\n\n /**\n * Apply an `authorize-project` payload. Shared by `init` and the\n * re-authorization in `setWriteGrant`, so a policy or capability change is\n * picked up identically by both — previously the re-auth path silently\n * ignored `auto_discovery` even though the response carries it.\n */\n private applyAuthorization(data: object, context: string): void {\n const authData = data as {\n key_type?: string;\n write_enabled?: boolean;\n auto_discovery?: boolean;\n discovery_base_locale_only?: boolean;\n langsys_settings?: { translatable_items?: { batch_limit?: number } };\n };\n\n if (authData.key_type) {\n this.config.key_type = authData.key_type;\n configStore.key_type = authData.key_type;\n // Display/debug only — every write decision goes through\n // `writeEnabled`. `key_type` cannot express `ip_write`.\n this.debug.log('API Key Type:', authData.key_type);\n }\n\n // The server decides, from the key, the caller's address and any grant, and says so in\n // `write_enabled`. An answer without it is not write-enabled, exactly as if it said\n // false (GATE-8): read as permission, a missing field would turn the stripped cache\n // into an open gate. Reporting is the policy's alone, so a session read this way\n // reports as any read-only session does (HINT-1).\n const enabled = authData.write_enabled === true;\n if (typeof authData.write_enabled !== 'boolean') {\n this.debug.warn(`The server's answer carried no write_enabled (${context}), so this session is not write-enabled.`);\n }\n this.Translations.applyWriteEnabled(enabled, authData.key_type);\n this.debug.log(`Session write-enabled (${context}):`, enabled);\n\n // Project policy: register and hint only while rendering the base locale. Read\n // here as well as on every catalog fetch, because a read-only session may never\n // fetch a catalog and would otherwise never learn the setting. Absent means off,\n // and no client config can override it — the handshake is the one source of truth.\n if (typeof authData.discovery_base_locale_only === 'boolean') {\n discoveryBaseLocaleOnly.set(authData.discovery_base_locale_only);\n this.debug.log(`Discovery limited to the base locale (${context}):`, authData.discovery_base_locale_only);\n }\n\n // Server-authoritative batch cap. Honour it rather than assuming ours.\n const limit = authData.langsys_settings?.translatable_items?.batch_limit;\n if (typeof limit === 'number' && limit > 0) {\n batchLimit.set(limit);\n this.debug.log(`Batch limit (${context}):`, limit);\n }\n\n // Policy is independent of the capability (see `autoDiscovery`): the canonical public\n // site is write-disabled AND reporting-permitted.\n if (typeof authData.auto_discovery === 'boolean') {\n autoDiscovery.set(authData.auto_discovery);\n this.debug.log(`Discovery reporting permitted (${context}):`, authData.auto_discovery);\n }\n }\n\n /** A route change re-enters the SDK (HINT-13). See `Translations.notifyNavigation`. */\n public notifyNavigation(): void {\n this.Translations.notifyNavigation();\n }\n\n /**\n * Put a catalog in place SYNCHRONOUSLY, with no network and no await.\n *\n * The hydration hand-off primitive: a framework's client entry calls this\n * with the catalog the server already rendered from, before mount, so the\n * first paint has translations instead of source text. `t()` returns the\n * translation on the very next line — there is nothing to await, which is\n * the whole point. `init()` can run afterwards, at its own pace, to\n * authorize and take over refreshes.\n *\n * Does exactly what the `initialTranslations` hand-off inside `init()` does\n * — injects `__uncategorized__`, stamps every `__category__`, publishes the\n * catalog and the locale — because it IS that code now. Two\n * implementations of \"seed a catalog\" would be two sets of rules about what\n * a seeded catalog looks like.\n *\n * Safe to call before `init()`, after it, or both: `init()` will not\n * re-seed a locale that is already seeded, so an SSR payload passed through\n * config cannot clobber a catalog a client entry put there first.\n *\n * `served`, a request scope's `seed()`, hands over what the server rendered\n * before any DOM class mounts: each block's source tokens, which a served\n * translation re-renders from, and which blocks and phrases the server sends\n * itself (`collected`), which the client then never registers. Nothing is\n * registered here; `registerBlock(seededBlock)` after `init()` does that.\n */\n /**\n * The request header that asks the app's own API for the user's language\n * (FRM-6): `{ 'Accept-Language': 'es-es' }` for the locale the user chose,\n * inside a request scope the scope's, else the loaded catalog's. Empty before\n * any locale is known. Spread it into the headers of the app's API calls, so an\n * API that answers per the negotiated language (FRM-5) answers in the user's,\n * not the browser's default.\n */\n public localeHeaders(): Record<string, string> {\n const locale = activeScope()?.locale || this.config?.sUserLocale?.get?.() || currentlyLoadedLocale.get();\n return locale ? { 'Accept-Language': canonicalizeLocale(locale) } : {};\n }\n\n public seedCatalog(\n catalog: iCategories,\n locale: string,\n served?: { blocks?: Record<string, SeededBlock>; phrases?: readonly SeededPhrase[] }\n ): void {\n for (const block of Object.values(served?.blocks ?? {})) rememberSeededBlock(block);\n for (const phrase of served?.phrases ?? []) rememberSeededPhrase(phrase);\n this.publishSeed(catalog, locale);\n // So a later `change()` for this locale is a cache hit rather than a\n // fetch that overwrites what the server already sent, and so\n // `ready()` resolves for consumers that await it before `init`.\n this.Translations.markLoaded(canonicalizeLocale(locale));\n this.debug.log('Seeded catalog for locale', canonicalizeLocale(locale));\n }\n\n /**\n * Load a catalog snapshot (spec SNAP-2) SYNCHRONOUSLY as the preloaded\n * catalog for `locale` — the current user locale by default, else the\n * snapshot's base locale. A first render or an offline session then has\n * its translations with no network call.\n *\n * The snapshot is a cache, never the catalog of record (SNAP-3): once\n * `init()` runs, the catalog is fetched as usual and replaces it, and a\n * phrase the snapshot lacks is found there. With no network the snapshot\n * keeps rendering, and anything it lacks shows its source text.\n *\n * Throws `SnapshotError`, naming the reason, for a file that is not a\n * snapshot, an unsupported version, a missing member, or a checksum the\n * contents no longer match — an edited snapshot is refused, not served.\n * Returns false when the snapshot holds no catalog for the locale.\n */\n public loadSnapshot(snapshot: string | CatalogSnapshot, locale?: string): boolean {\n const parsed = parseSnapshot(snapshot);\n const wanted = canonicalizeLocale(locale || this.config.sUserLocale?.get?.() || parsed.base_locale);\n const catalog = parsed.catalog[wanted];\n if (!catalog) return false;\n this.publishSeed(JSON.parse(JSON.stringify(catalog)) as iCategories, wanted);\n this.Translations.markSeeded();\n this.debug.log('Loaded snapshot catalog for locale', wanted);\n return true;\n }\n\n /** Publish a catalog and its locale — the one set of rules for what a seeded catalog looks like. */\n private publishSeed(catalog: iCategories, locale: string): void {\n const normalizedLocale = canonicalizeLocale(locale);\n\n if (!catalog['__uncategorized__']) {\n catalog['__uncategorized__'] = {\n __category__: '__uncategorized__',\n __symbol__: '__uncategorized__',\n } as iTranslations;\n }\n for (const cat of Object.keys(catalog)) {\n catalog[cat]['__category__'] = cat;\n }\n\n sTranslations.set(catalog);\n currentlyLoadedLocale.set(normalizedLocale);\n }\n\n /**\n * Render a server message entry (spec MSG-5): its `template` through `t()`\n * under the messages category, filled from its `params`. When the catalog\n * holds no translation for the template, the entry's own `message` is shown\n * instead, which is the text the server filled and possibly localised; an\n * entry with no `message` shows its template filled. An entry with no\n * `template` is not looked up and shows its `message`. `message` is never\n * used as a lookup key.\n *\n * The lookup goes through `t()` on a miss too, so the template is recorded\n * like any other missing phrase. A plural in the translation renders from a\n * numeric param through the catalog's ICU, with no ICU written by the caller.\n */\n public renderServerMessage(entry: ServerMessage, category?: string): string {\n if (typeof entry.template !== 'string') return entry.message ?? '';\n const messagesCategory = category || this.config.messagesCategory || DEFAULT_SERVER_MESSAGE_CATEGORY;\n const params = entry.params ?? {};\n const translated = this.Translations.lookup(entry.template, messagesCategory) !== null;\n const t = this.Translations.tSignal.get() as unknown as (\n phrase: string,\n category: string,\n params: Record<string, unknown>\n ) => string;\n const rendered = t(entry.template, messagesCategory, params);\n if (translated) return rendered;\n return entry.message ?? fillTemplate(entry.template, params);\n }\n\n /** Whether a catalog is already published for this locale. */\n private isAlreadySeeded(locale: string): boolean {\n if (pageLocale() !== canonicalizeLocale(locale)) return false;\n const current = pageCatalog();\n // The empty skeleton is not a seeded catalog — it is the initial value.\n return Object.keys(current).some((cat) => cat !== '__uncategorized__' || Object.keys(current[cat]!).length > 2);\n }\n\n /** Read the current locale's catalog again, and the locale data `getLocaleName` reads, on its next load. */\n public async refresh() {\n const locale = this.config.sUserLocale.get();\n for (const key of [...this.referenceLists.keys()]) if (key.startsWith('locales/data\\0')) this.forgetReferenceList(key);\n return this.Translations.change(locale, true);\n }\n\n /**\n * Initialize Langsys. Configuration must include at least `projectid`,\n * `key`, and `UserLocaleStore` (anything satisfying `LocaleSource` — see\n * its docstring for framework-specific adapters).\n */\n /**\n * Whether `init()` accepted a project id, an API key and a locale store (WIRE-4). False\n * before `init()` runs and after one refused for missing credentials. Authorization is a\n * separate question: a configured client whose key the server refuses is still configured.\n */\n public isConfigured(): boolean {\n return configured.get() === true;\n }\n\n /**\n * `init()` without credentials (WIRE-4). Nothing throws here: `t()` renders source text with\n * its params filled, no miss is queued and no request is made, a component's block\n * registration resolves skipped with reason `not-configured`, and an explicit write throws\n * `LangsysConfigurationError`. With `requireCredentials`, `t()` throws it too.\n */\n private refuseUnconfigured(missing: string, errorText: string, requireCredentials: boolean): ResponseObject {\n configured.set(false);\n LangsysAppAPI.clearCredentials();\n // Forgotten on every copy, so nothing an earlier init() set up (a grant change, its\n // locale store's next emission) can hand the old key back to the client.\n const forgotten = { projectid: '', key: '', writeGrant: undefined };\n Object.assign(configStore, forgotten);\n Object.assign(this.config, forgotten);\n this.Translations.markUnconfigured(\n new LangsysConfigurationError(`Langsys is not configured: LangsysApp.init() was called without ${missing}.`),\n requireCredentials\n );\n return { status: false, errors: [errorText] };\n }\n\n public async init(initConfig: iLangsysInitConfig): Promise<ResponseObject> {\n const projectid = initConfig.projectid;\n const key = initConfig.key;\n const UserLocaleStore = initConfig.UserLocaleStore;\n let baseLocale = initConfig.baseLocale || 'en';\n const debug = initConfig.debug || false;\n const emulateFailureToLoad = initConfig.emulateFailureToLoad || false;\n const ssrTokenStrategy = initConfig.ssrTokenStrategy || 'client';\n const initialTranslations = initConfig.initialTranslations;\n const initialTranslationsLocale = initConfig.initialTranslationsLocale;\n const writeGrant = initConfig.writeGrant;\n const requireCredentials = initConfig.requireCredentials === true;\n\n this.debug.debugEnabled = debug;\n\n // The module-scope `logger` singleton is a SEPARATE instance from the\n // per-class `this.debug` loggers, and nothing else ever writes its flag\n // — so anything gated on `logger.debugEnabled` was permanently off.\n // That silently disabled `warnUnmatchedParams` (unmatched `params` keys\n // in `<Translate>`/`<Phrase>`) for every consumer: the feature shipped,\n // typechecked, had tests, and could never fire. `init` is the one place\n // `debug` is resolved, so it is the right place to propagate it.\n logger.debugEnabled = debug;\n // Debug notices raised before this point were held until debug was known.\n settleNotices();\n\n // What a request scope with credentials of its own needs from init() holds whether or\n // not init() has credentials (SRV-2): the API host, set before validate() since\n // authorizing against the default host and then switching is silent, and the strategy.\n if (initConfig.apiUrl) LangsysAppAPI.setBaseUrl(initConfig.apiUrl);\n configStore.ssrTokenStrategy = ssrTokenStrategy;\n\n if (debug && initialTranslations) {\n this.debug.log('SSR initial translations config:', {\n hasInitialTranslations: !!initialTranslations,\n initialTranslationsLocale,\n categoriesProvided: initialTranslations ? Object.keys(initialTranslations).length : 0,\n categories: initialTranslations ? Object.keys(initialTranslations) : [],\n });\n }\n\n // Every early return below leaves the client unconfigured (WIRE-4) and settles the\n // ready() gate. No catalog is coming on these paths, and `Phrase`/`Translate` await\n // that gate before rendering — so leaving it pending renders nothing, forever, with\n // no error, on the commonest misconfigurations there are.\n if (!projectid) {\n this.debug.error('LangsysApp.init missing projectid in configuration object!');\n return this.refuseUnconfigured('a project id', 'Missing projectid', requireCredentials);\n }\n if (!key) {\n this.debug.error('LangsysApp.init missing API key in configuration object!');\n return this.refuseUnconfigured('an API key', 'Missing API key', requireCredentials);\n }\n if (!UserLocaleStore?.subscribe || typeof UserLocaleStore.get !== 'function') {\n this.debug.error(\n \"LangsysApp.init missing UserLocaleStore — pass any object satisfying LocaleSource (get + subscribe). createSignal('en-US') works if you have nothing of your own.\"\n );\n return this.refuseUnconfigured('a locale store', 'Missing UserLocaleStore', requireCredentials);\n }\n configured.set(true);\n this.Translations.markConfigured();\n\n // Lowercase `xx-yy` (`en-us`, `zh-hant-tw`) — the form the backend\n // stores and every internal cache key uses as the identity.\n baseLocale = canonicalizeLocale(baseLocale);\n\n // The legacy-key mode is on only when configured, and a file this core\n // cannot read throws here, before anything resolves through it (MIG-1, MIG-7).\n this.Translations.setLegacyKeys(initConfig.legacyKeys);\n\n if (!emulateFailureToLoad) {\n this.config = {\n projectid,\n key,\n sUserLocale: UserLocaleStore,\n baseLocale,\n debug,\n ssrTokenStrategy,\n writeGrant,\n messagesCategory: initConfig.messagesCategory || DEFAULT_SERVER_MESSAGE_CATEGORY,\n };\n // Keep the exported config singleton in sync (used by Translate + API).\n Object.assign(configStore, this.config);\n\n // Restore this project and locale's cached catalog now, while authorization is\n // in flight, so `t()` renders it during the round trip instead of source text:\n // both halves of the cache key are known here (CACHE-1). The cache holds the\n // catalog and never the write decision (GATE-4), registration still decides\n // only against the live catalog (REG-13), and a refused authorization leaves\n // the restored catalog rendering, as a preloaded snapshot does (CACHE-2). The loaded\n // locale is not set: it names a catalog this session fetched or was handed,\n // and that is what lets `initialTranslations` below replace a stale copy.\n const startLocale = canonicalizeLocale(UserLocaleStore.get() || '');\n if (startLocale) scopeCatalogCache(catalogScopeOf(projectid, startLocale));\n }\n\n // A grant makes write capability per-user, while the SSR write lane can\n // only hold a process-wide decision — so it would apply one user's\n // capability to every later visitor in that Node process. Degrading to\n // the client lane is correct, but silent degradation costs someone an\n // afternoon, so say it out loud.\n if (writeGrant && ssrTokenStrategy !== 'client') {\n this.debug.warn(\n `ssrTokenStrategy '${ssrTokenStrategy}' degrades to 'client' while a writeGrant is configured — ` +\n 'write capability is per-user with a grant, so a server-side decision would leak across ' +\n 'requests. Tokens will flush after hydration instead.'\n );\n }\n\n const validateResponse = await LangsysAppAPI.validate(this.config);\n\n if (validateResponse.status && validateResponse.data) {\n // On this route `data` is not a catalog, so `write_enabled` is a\n // safe sibling of `key_type` inside it (unlike `/translations`,\n // where `data` IS the category map and it must be envelope-level).\n this.applyAuthorization(validateResponse.data, 'init');\n } else {\n // Authorization failed — bad key, wrong host, unreachable server.\n // The locale subscription installed below short-circuits on\n // `!validateResponse.status`, so no catalog will ever load and\n // nothing else would resolve the gate. Nor would anything answer the\n // capability, so it settles as not writable: a block registration\n // waiting on it resolves skipped instead of waiting forever.\n this.Translations.settleNotWritable();\n this.Translations.settle();\n }\n\n // Seed the translations store if initial data is provided (SSR handoff).\n // Same primitive a client entry can call directly before init — see\n // `seedCatalog`. `init` does NOT re-seed a catalog already seeded for\n // this locale, so calling both is safe and order-independent.\n if (initialTranslations && initialTranslationsLocale) {\n if (!this.isAlreadySeeded(initialTranslationsLocale)) {\n this.seedCatalog(initialTranslations, initialTranslationsLocale);\n } else {\n this.debug.log('Catalog already seeded for locale; leaving it', initialTranslationsLocale);\n }\n }\n\n this.Translations.setup(this.config);\n\n // The SSR handoff already populated the stores for this locale, so prime\n // the fetch cache (after setup, which would otherwise reset this.locale).\n // The first settle for this locale is then a cache hit — no redundant\n // fetch — while switching *back* to it later still flows through\n // change() and rebuilds the t-signal. (Do NOT gate change() on a\n // \"skip fetch\" flag here: it would otherwise stay armed and silently\n // skip every return to the initial locale.)\n if (initialTranslations && initialTranslationsLocale) {\n this.Translations.markLoaded(initialTranslationsLocale);\n }\n\n // Prefetch and wire up reactive locale change handling. The store\n // emits whatever the app put in it — canonicalize here so downstream\n // caches and API routes only ever see the lowercase `xx-yy` form.\n this.config.sUserLocale.subscribe((rawLocale) => {\n if (!validateResponse.status) return;\n const locale = canonicalizeLocale(rawLocale);\n // A prefetch for getLocaleName, not the app's first use: a refused re-init under\n // requireCredentials makes the read reject, and nothing here is waiting to hear it.\n this.getLocalesData(locale).catch(() => {});\n this.debug.log('SUBSCRIBING TO USER LOCALE STORE');\n this.translationsLoadingPromise = this.Translations.change(locale, false);\n });\n\n return validateResponse;\n }\n\n /** The countries' dial codes, named in the display locale (REF-1). */\n public async getDialCodes(inLocale?: string): Promise<iCountryDialCode[]> {\n return this.readReferenceList('getDialCodes', 'countries/dial-codes', inLocale, () => []);\n }\n\n /** The currencies, named in the display locale (REF-1). */\n public async getCurrencies(inLocale?: string): Promise<iCurrencyList> {\n return this.readReferenceList('getCurrencies', 'currencies', inLocale, () => []);\n }\n\n /** The countries, named in the display locale (REF-1). */\n public async getCountries(inLocale?: string): Promise<iCountryList> {\n return this.readReferenceList('getCountries', 'countries', inLocale, () => []);\n }\n\n public async getCountryName(forCountryCode: string, inLocale?: string): Promise<string> {\n if (!forCountryCode) return '';\n const countries = await this.readReferenceList<iCountryList>('getCountries', 'countries', inLocale, () => [], { copy: false });\n const country = countries.find((c) => c.code?.toLowerCase() === forCountryCode.toLowerCase())?.label;\n if (!country) this.debug.warn('getCountryName failed to match', forCountryCode);\n return country || forCountryCode;\n }\n\n public async getCurrencyName(forCurrencyCode: string, inLocale?: string): Promise<string> {\n if (!forCurrencyCode) return '';\n const currencies = await this.readReferenceList<iCurrencyList>('getCurrencies', 'currencies', inLocale, () => [], { copy: false });\n const currency = currencies.find((c) => c.code?.toLowerCase() === forCurrencyCode.toLowerCase())?.name;\n if (!currency) this.debug.warn('getCurrencyName failed to match', forCurrencyCode);\n return currency || forCurrencyCode;\n }\n\n /** The locales in one of the API's three forms, named in the display locale (REF-1). */\n public async getLocalesFormat(\n format: '' | 'flat' | 'data' = '',\n inLocale?: string\n ): Promise<iLocaleDefault | iLocaleFlat[] | iLocaleData[]> {\n const method = format === 'flat' ? 'getLocalesFlat' : format === 'data' ? 'getLocalesData' : 'getLocales';\n return this.readReferenceList<iLocaleDefault | iLocaleFlat[] | iLocaleData[]>(\n method,\n 'locales' + (format ? `/${format}` : ''),\n inLocale,\n () => (format ? [] : {}),\n { grouped: !format }\n );\n }\n\n public async getLocalesFlat(inLocale?: string): Promise<iLocaleFlat[]> {\n return (await this.getLocalesFormat('flat', inLocale)) as iLocaleFlat[];\n }\n\n /** `forceRefresh` is an explicit refresh: it reads the list again, held or inside a failure window, and holds what that read answers. */\n public async getLocalesData(inLocale?: string, forceRefresh = false): Promise<iLocaleData[]> {\n if (forceRefresh) this.forgetReferenceList(`locales/data\\0${this.displayLocale(inLocale)}`);\n return (await this.getLocalesFormat('data', inLocale)) as iLocaleData[];\n }\n\n public async getLocales(inLocale?: string): Promise<iLocaleDefault> {\n return (await this.getLocalesFormat('', inLocale)) as iLocaleDefault;\n }\n\n /**\n * Read one reference list in a display locale (REF-1), or answer the one held for it.\n *\n * The display locale is the one given, else the current one, canonical as the core serves\n * it; one not shaped as a locale is refused before anything is sent, since it is written\n * into the request. A locale form is asked for that locale alone and answers that locale's entry,\n * whose key and codes are in the organisation's code format, so it is matched and recoded\n * in WIRE-3's form; a locale the API does not hold answers `empty()`, held like any\n * answer. Nothing here throws but `requireCredentials` (WIRE-4): a refused locale, a failed\n * read and an answer not of the list's shape answer `empty()` with the cause logged, and\n * a failed read is remembered for CACHE-2's window under its credentials, inside which a\n * call under them sends nothing; a call under other credentials still reads, though one made\n * while a read is in flight shares it, whoever sent it.\n * An unconfigured core sends nothing and logs nothing, whatever the display locale,\n * `init()`'s refusal being its one warning. Each caller gets its own copy of a held list,\n * so what one caller does to it never reaches the next; `copy: false` is for the core's own\n * lookups, which only read it.\n */\n private async readReferenceList<T>(\n method: string,\n route: string,\n inLocale: string | undefined,\n empty: () => T,\n opts: { grouped?: boolean; copy?: boolean } = {}\n ): Promise<T> {\n const answer = (list: unknown): T => (opts.copy === false ? list : structuredCloneShim(list)) as T;\n // An unconfigured core answers empty and sends nothing (WIRE-4), whatever a configured\n // scope may have held; a scope's own credentials configure it (SRV-2).\n const credentials = LangsysAppAPI.currentCredentials();\n if (!credentials.projectid || !credentials.key) {\n this.Translations.assertConfigured();\n return empty();\n }\n const locale = this.displayLocale(inLocale);\n if (!isLocaleShaped(locale)) {\n this.debug.warn(`LangsysApp.${method}: \"${locale}\" is not a locale, so no list is read for it.`);\n return empty();\n }\n const key = `${route}\\0${locale}`;\n const held = this.referenceLists.get(key);\n if (held && 'list' in held) return answer(held.list);\n if (held?.reading) {\n const shared = await held.reading;\n return shared === undefined ? empty() : answer(shared);\n }\n // CACHE-2's window is the credentials' own: a read that failed under one key holds back no other key's read.\n const sender = `${credentials.projectid}\\0${credentials.key}`;\n const failed = held?.failed?.get(sender);\n if (failed?.retryAt !== undefined && Date.now() < failed.retryAt) {\n this.debug.log(`LangsysApp.${method}: the last read of ${route} (${locale}) under these credentials failed, so none is sent until`, new Date(failed.retryAt));\n return empty();\n }\n\n const byLocale = route.startsWith('locales');\n const reading = (async (): Promise<unknown> => {\n try {\n const response = byLocale\n ? await LangsysAppAPI.get(route, { 'locales[]': locale, append_target_locales: '0' }, { credentials })\n : await LangsysAppAPI.get(`${route}/${locale}`, {}, { credentials });\n if (response.errors || !response.status) {\n this.debug.error(`LangsysApp.${method} failed: ${route} (${locale}):`, response.errors ?? response.http?.status);\n return undefined;\n }\n const list = byLocale ? localeEntry(response.data, locale, opts.grouped === true, empty) : Array.isArray(response.data) ? response.data : undefined;\n if (list === undefined) {\n this.debug.error(`LangsysApp.${method}: the answer for ${route} (${locale}) is not of the list's shape.`, response.data);\n return undefined;\n }\n return byLocale ? withWire3Codes(list) : list;\n } catch (err) {\n this.debug.error(`LangsysApp.${method} failed: ${route} (${locale}):`, err);\n return undefined;\n }\n })();\n this.referenceLists.set(key, { ...held, reading });\n const list = await reading;\n // An explicit refresh may have started another read meanwhile; only this read's own entry changes.\n if (this.referenceLists.get(key)?.reading === reading) {\n if (list !== undefined) this.referenceLists.set(key, { list });\n else {\n const failures = (failed?.failures ?? 0) + 1;\n const others = new Map(held?.failed);\n this.referenceLists.set(key, { failed: others.set(sender, { failures, retryAt: Date.now() + failureWindowMs(failures) }) });\n }\n }\n return list === undefined ? empty() : answer(list);\n }\n\n /**\n * An explicit refresh of one list and display locale: the held list and every failure\n * window go, so the next call reads. Each credentials' count of failures in a row stays, so\n * a refresh that fails again widens CACHE-2's window as any failure in a row does.\n */\n private forgetReferenceList(key: string): void {\n const failed = this.referenceLists.get(key)?.failed;\n if (failed) this.referenceLists.set(key, { failed: new Map([...failed].map(([sender, { failures }]) => [sender, { failures }])) });\n else this.referenceLists.delete(key);\n }\n\n /**\n * A reference list's display locale (REF-1): the one given, else the current one, each\n * canonical, as the core normalises the locale it serves. The current locale is the one\n * `t()` and the catalog serve, on both profiles: the request scope's, else the store's. So\n * a given `iw-IL` and a store holding `iw-IL` both name their lists in `he-il`.\n */\n private displayLocale(inLocale?: string): string {\n if (inLocale) return wire3Locale(canonicalizeLocale(inLocale));\n const current = activeScope()?.locale || canonicalizeLocale(this.config?.sUserLocale?.get?.() || '') || this.config?.baseLocale || 'en';\n return wire3Locale(current);\n }\n\n public async getLocaleNameWithLookup(forLocale: string, shortName = false, inLocale?: string): Promise<string> {\n if (!forLocale) return '';\n const locale = this.displayLocale(inLocale);\n await this.readReferenceList('getLocalesData', 'locales/data', locale, () => [], { copy: false });\n return this.getLocaleName(forLocale, shortName, locale);\n }\n\n /**\n * Synchronous locale-name lookup against the in-memory locales cache.\n *\n * The cache is only populated once `await getLocalesData(inLocale)` — or\n * any `getLocaleNameWithLookup` call — has settled for that display locale.\n * Called before then this returns `''`, the same value a genuinely unknown\n * locale returns, so the two cases are told apart by the warning rather\n * than by the return value. Use `getLocaleNameWithLookup` when you can\n * await; it loads the data first.\n */\n public getLocaleName(forLocale: string, shortName = false, inLocale?: string): string {\n // Unconfigured, nothing held is answered, as the list calls answer nothing (WIRE-4).\n const credentials = LangsysAppAPI.currentCredentials();\n if (!credentials.projectid || !credentials.key) {\n this.Translations.assertConfigured();\n return '';\n }\n const locale = this.displayLocale(inLocale);\n\n // Distinguished from a lookup miss deliberately. Both return '', and\n // the old warning reported both as a failed match — sending developers\n // to check a locale code that was fine, when the real problem was that\n // nothing had been loaded to check it against.\n const data = this.referenceLists.get(`locales/data\\0${locale}`)?.list as iLocaleData[] | undefined;\n if (!data) {\n this.debug.warn(\n `getLocaleName('${forLocale}') called before locale data for '${locale}' was loaded — ` +\n `run \\`await getLocalesData('${locale}')\\` first, or use \\`await getLocaleNameWithLookup(...)\\` instead.`\n );\n return '';\n }\n\n // The codes are in WIRE-3's form; the core's canonical form also names a legacy alias (`iw`).\n const targets = [wire3Locale(forLocale), canonicalizeLocale(forLocale)];\n const entry = data.find((loc) => targets.includes(wire3Locale(loc.code)));\n const name = entry ? (shortName ? entry.lang_name : entry.locale_name) : '';\n if (!name) this.debug.warn('getLocaleName found no entry matching', forLocale);\n return name;\n }\n\n /** @deprecated use `getLocaleNameWithLookup` or `getLocaleName` */\n public async getLanguageName(forLocale: string, shortName = false, inLocale?: string): Promise<string> {\n return this.getLocaleNameWithLookup(forLocale, shortName, inLocale);\n }\n\n /**\n * Detects the end-user's preferred locale.\n *\n * - In browsers, uses `navigator.languages` with fallback to `navigator.language`.\n * - In SSR environments, parses the `Accept-Language` header.\n *\n * With `supportedLocales`, returns the best CLDR-aware match from that list\n * or `false` when none of the user's preferences are supported — so the\n * documented `detectPreferredLocale(header, supported) || 'en-us'` idiom\n * actually reaches your default. Returning the user's own unsupported\n * locale instead would send the app to fetch a catalog that does not\n * exist, and the caller's `||` would never fire.\n *\n * Without `supportedLocales`, returns the user's first preference in\n * canonical form, or `false` when no preference is detectable.\n */\n public detectPreferredLocale(\n acceptLanguageHeader?: string | null,\n supportedLocales?: string[]\n ): string | false {\n const userLocales = this.getUserLanguagePreferences(acceptLanguageHeader);\n if (userLocales.length === 0) return false;\n\n if (supportedLocales && supportedLocales.length > 0) {\n return this.findBestLocaleMatch(userLocales, supportedLocales) ?? false;\n }\n\n return canonicalizeLocale(userLocales[0]);\n }\n\n private getUserLanguagePreferences(acceptLanguageHeader?: string | null): string[] {\n if (acceptLanguageHeader) {\n try {\n return this.parseAcceptLanguageHeader(acceptLanguageHeader);\n } catch (error) {\n this.debug.warn('Failed to parse Accept-Language header:', error);\n }\n }\n\n if (typeof navigator !== 'undefined') {\n if (navigator.languages && navigator.languages.length > 0) {\n return Array.from(navigator.languages);\n }\n if (navigator.language) return [navigator.language];\n }\n\n return [];\n }\n\n private parseAcceptLanguageHeader(header: string): string[] {\n if (!header || typeof header !== 'string' || header.trim() === '') return [];\n\n try {\n return header\n .split(',')\n .map((part) => {\n const trimmed = part.trim();\n if (!trimmed || trimmed === '*') return null;\n const [localePart, qPart] = trimmed.split(';q=');\n const locale = localePart?.trim();\n const q = qPart ? parseFloat(qPart) : 1.0;\n if (!locale || isNaN(q) || q <= 0 || q > 1) return null;\n return { locale, q };\n })\n .filter((item): item is { locale: string; q: number } => item !== null)\n .sort((a, b) => b.q - a.q)\n .map((item) => item.locale);\n } catch (error) {\n this.debug.warn('Error parsing Accept-Language header:', error);\n return [];\n }\n }\n\n private findBestLocaleMatch(userLocales: string[], supportedLocales: string[]): string | null {\n if (!userLocales.length || !supportedLocales.length) return null;\n\n const supported = supportedLocales.map((l) => canonicalizeLocale(l));\n\n // Pass 1: exact match in canonical form.\n for (const userLocale of userLocales) {\n const user = canonicalizeLocale(userLocale);\n if (supported.includes(user)) return user;\n }\n\n // Pass 2: same language + script after CLDR likely-subtags expansion\n // (`zh-TW` → zh-Hant, bare `zh` → zh-Hans), region ignored. This is\n // deliberately NOT bare-language truncation: a zh-Hant-TW user must\n // fall through unmatched rather than land on a zh/zh-Hans catalog.\n for (const userLocale of userLocales) {\n const userKey = maximizedLangScript(userLocale);\n if (!userKey) continue;\n const match = supported.find((s) => maximizedLangScript(s) === userKey);\n if (match) return match;\n }\n\n return null;\n }\n}\n\nexport const LangsysApp = new LangsysAppClass();\nexport type { LangsysAppClass };\n\n/**\n * Shaped as a locale, in the core's form: REF-1's pattern, letters and digits in hyphenated\n * subtags. A display locale is written into a request path, so anything else (`../projects`,\n * `es/es`, `es?x=1`) is refused unsent.\n */\nfunction isLocaleShaped(locale: string): boolean {\n return typeof locale === 'string' && /^[a-z]{2,8}(?:-[a-z0-9]{1,8})*$/.test(locale);\n}\n\n/**\n * A locale form's list for `locale`, or undefined when the answer is not of its shape. Its\n * `data` is a map keyed by locale, in the organisation's code format, so the key is matched in\n * the core's form; the API writes an empty map as `[]`. A locale the map does not hold is an\n * empty list, and an entry is a list, or for the grouped form a map of lists.\n */\nfunction localeEntry(data: unknown, locale: string, grouped: boolean, empty: () => unknown): unknown {\n if (Array.isArray(data)) return data.length === 0 ? empty() : undefined;\n if (typeof data !== 'object' || data === null) return undefined;\n const found = Object.entries(data).find(([key]) => wire3Locale(key) === locale);\n if (!found) return empty();\n const [, entry] = found;\n if (!grouped) return Array.isArray(entry) ? entry : undefined;\n // The grouped form's empty map is also written as `[]`.\n if (Array.isArray(entry)) return entry.length === 0 ? {} : undefined;\n if (typeof entry !== 'object' || entry === null) return undefined;\n return Object.values(entry).every((entries) => Array.isArray(entries)) ? entry : undefined;\n}\n\n/**\n * WIRE-3's form of a locale identifier: `_` read as `-`, lowercased, and nothing else. It is the\n * form of the API's own codes, so a code a reference list answers keeps the code the API holds.\n */\nfunction wire3Locale(value: unknown): string {\n return typeof value === 'string' ? value.replace(/_/g, '-').toLowerCase() : '';\n}\n\n/** A locale list with every entry's `code` in WIRE-3's form, in the flat or data shape or grouped by language. */\nfunction withWire3Codes(listed: unknown): unknown {\n const recode = (entries: unknown): unknown =>\n Array.isArray(entries)\n ? entries.map((entry) =>\n typeof entry === 'object' && entry !== null && typeof (entry as { code?: unknown }).code === 'string'\n ? { ...entry, code: wire3Locale((entry as { code: string }).code) }\n : entry\n )\n : entries;\n if (Array.isArray(listed)) return recode(listed);\n if (typeof listed !== 'object' || listed === null) return listed;\n return Object.fromEntries(Object.entries(listed).map(([language, entries]) => [language, recode(entries)]));\n}\n","import { logger } from './logger.js';\nimport { activeScope } from './scope-context.js';\n\n/**\n * Which marked hosts already have an instance managing them.\n *\n * A `Translate` or `Phrase` claims its element when it is constructed. An\n * enclosing `Translate` that meets a marked host no instance claims — markup a\n * server rendered, or a vanilla page that marked an element without wrapping\n * it — takes the host over itself (MARK-2, MARK-3), so the host registers as\n * the unit its marker declares instead of never registering at all.\n *\n * An instance an author constructs outranks one a walk created: claiming a host\n * whose claim came from a walk destroys that instance first, so a host is never\n * rendered or registered by two instances at once.\n */\n\ninterface Instance {\n destroy(): void;\n}\n\ninterface Claim {\n instance: Instance;\n /** True when an enclosing walk created the instance, not the author. */\n byWalk: boolean;\n}\n\nconst claims = new WeakMap<Element, Claim>();\n\n/** Record that `instance` manages `host`, replacing an instance a walk created there. */\nexport function claimHost(host: Element, instance: Instance, byWalk = false): void {\n const existing = claims.get(host);\n if (existing && existing.byWalk && existing.instance !== instance) existing.instance.destroy();\n claims.set(host, { instance, byWalk });\n}\n\n/** Drop `instance`'s claim on `host`, if it still holds it. */\nexport function releaseHost(host: Element, instance: Instance): void {\n if (claims.get(host)?.instance === instance) claims.delete(host);\n}\n\nconst warnedInert = new Set<string>();\n\n/**\n * True, warning once per class, when a DOM class is constructed inside a request\n * scope (SRV-7). Its registration and subscriptions would run after the scope\n * has ended, outside it: phrases posted during the request, a block recorded as\n * loose phrases, and a later process emission re-rendering the host. So under a\n * scope it does nothing, and the server renders through `renderBlock` and\n * registers through `registerBlock`.\n */\nexport function inertUnderScope(className: string): boolean {\n if (!activeScope()) return false;\n if (!warnedInert.has(className)) {\n warnedInert.add(className);\n logger.warn(\n `${className} was constructed inside a request scope and does nothing there: render the block with renderBlock() and register it with registerBlock(), which complete inside the scope.`\n );\n }\n return true;\n}\n\n/** Whether an instance manages `host`. */\nexport function isHostManaged(host: Element): boolean {\n return claims.has(host);\n}\n","import { warnUnmatchedParams } from './interpolate.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { isOpaqueInPhrase } from './identity.js';\nimport { applyInPlace, encodeRichText, fillOpaque, interpolateRich, reconstitute, takesParams, type EncodedRichText, type RichSlot } from './richtext.js';\nimport type { Unsubscriber } from './signal.js';\nimport { currentlyLoadedLocale, navigationEpoch, sTranslations } from './stores.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\n\n/**\n * Attribute marker the `Translate` tokenizer uses to skip a `<Phrase>` subtree.\n * Re-exported, never restated: one definition lives in `content-block.ts`,\n * where the tokenizer that has to recognise it also lives.\n */\nexport { PHRASE_MARKER_ATTR } from './content-block.js';\nimport { isInResolvedScope } from './content-block.js';\nimport { claimHost, inertUnderScope, releaseHost } from './hosts.js';\nimport { warnUnregistered } from './notices.js';\nimport { paramElementName, type MarkerNode } from './var-markers.js';\nimport { recoverPhraseSource } from './served-source.js';\n\nexport interface PhraseOptions {\n /** Category the phrase registers under (disambiguation for translators). */\n category?: string;\n /**\n * Interpolation params — `{n}` for pluralization, `{name}`, etc.\n *\n * Those are the canonical spellings, and what you write in plain DOM. In a\n * framework component's markup write `%n%` / `%name%` instead: Svelte and\n * JSX consume `{n}` at compile time (Vue consumes `{{ n }}`), and `%n%` is\n * normalized back to `{n}` at capture.\n */\n params?: Record<string, ParamPrimitive>;\n /**\n * `false` renders from the catalog and registers nothing (VAR-7): for a binding\n * whose phrase holds values from variables it cannot name without its build-time\n * transform. One debug notice says so. Default `true`.\n */\n register?: boolean;\n}\n\n/**\n * DOM handler for a markup-bearing \"rich\" phrase (`<Phrase>`).\n *\n * Wraps an element whose inner content is ONE translatable phrase even though\n * it contains inline markup. On mount it encodes the subtree to a single phrase\n * string with neutral `{mNo}`/`{mNc}` markup tokens (the real elements stay in\n * the SDK — see richtext.ts), registers it, and renders the translation by\n * reconstituting the original elements around the translated text. Re-renders\n * on locale change and whenever params change.\n *\n * new Phrase(el, { category: 'ProductCard', params: { n: reviewCount } });\n */\nexport class Phrase {\n private host: HTMLElement;\n private category: string;\n private params: Record<string, ParamPrimitive>;\n private register: boolean;\n /** Each marked value in the host (VAR-3), by name: params the caller's own override. */\n private values: Record<string, string> = {};\n private phrase = '';\n private slots: RichSlot[] = [];\n /** The key a phrase holding an opaque element was registered under before TOK-1: looked up on a miss, never registered. */\n private earlier: EncodedRichText['earlier'];\n /**\n * A phrase made only of value markers (VAR-3) or of opaque elements (TOK-1) has no\n * text of its own, and registers nothing, on mount or on a navigation.\n */\n private textless = false;\n /** The text of each opaque element that takes params, as the page gave it: where a caller's param can land (TOK-1). */\n private opaqueTexts: string[] = [];\n /**\n * The markup slot each element in the host renders. An element's place is its\n * slot only while the host shows the source's order; a translation that\n * reorders its markup, served or rendered here, moves them.\n */\n private slotOf = new WeakMap<Element, number>();\n /** A served translation whose source phrase is not recovered yet (see `recoverServed`). */\n private servedUnrecovered = false;\n private unsubscribers: Unsubscriber[] = [];\n private ready = false;\n /** Sorted params key-set already checked, so value-only updates don't re-warn. */\n private checkedParamKeys: string | null = null;\n\n /**\n * @param byWalk Internal: set when an enclosing walk creates this instance for\n * a host nothing managed, so an instance the author constructs replaces it.\n */\n constructor(host: HTMLElement, options: PhraseOptions = {}, byWalk = false) {\n this.host = host;\n this.category = options.category ?? '';\n this.params = options.params ?? {};\n this.register = options.register !== false;\n // Under a request scope, see `Translate`: `renderBlock` and `registerBlock` there.\n if (inertUnderScope('Phrase')) return;\n claimHost(host, this, byWalk);\n if (!this.register) warnUnregistered('register-false');\n\n void this._init();\n\n // Re-render on locale switch AND when translations arrive (async MT may\n // land this phrase's translation after mount, same as the reactive `t`\n // store). subscribe fires immediately; the `ready` guard suppresses the\n // pre-init call.\n const rerender = () => {\n if (this.ready) this._render();\n };\n this.unsubscribers.push(currentlyLoadedLocale.subscribe(rerender));\n this.unsubscribers.push(sTranslations.subscribe(rerender));\n\n // HINT-13: after a navigation, look the phrase up again so a miss is recorded at the\n // new URL — only while the host is attached to the document, and never inside a\n // resolved scope. `subscribe` fires once with the current value first.\n let initialNavigation = true;\n this.unsubscribers.push(\n navigationEpoch.subscribe(() => {\n if (initialNavigation) {\n initialNavigation = false;\n return;\n }\n if (!this.ready || !this.phrase || !this.register || this.textless || !this.host.isConnected || isInResolvedScope(this.host)) return;\n LangsysApp.Translations.t(this.phrase, this.category);\n })\n );\n }\n\n /** Update interpolation params (e.g. a changed count) and re-render. */\n public setParams(params: Record<string, ParamPrimitive> | undefined): void {\n this.params = params ?? {};\n // Checked independently of `ready` — the phrase is encoded before\n // registration settles, and params can change during that window.\n this._checkParams();\n if (!this.ready) return;\n this._render();\n }\n\n /** Stop reacting to locale/translation changes. Safe to call multiple times. */\n public destroy(): void {\n this.unsubscribers.forEach((unsub) => unsub());\n this.unsubscribers = [];\n releaseHost(this.host, this);\n }\n\n private async _init(): Promise<void> {\n if (!this.host || !this.host.childNodes.length) {\n this.ready = true;\n return;\n }\n\n const { phrase, slots, values, earlier } = encodeRichText(this.host);\n this.phrase = phrase;\n this.slots = slots;\n this.values = values;\n this.earlier = earlier;\n this.opaqueTexts = slots.flatMap((slot) => (slot.source && takesParams(slot.source) ? [slot.source.textContent ?? ''] : []));\n hostElements(this.host).forEach((element, i) => this.slotOf.set(element, i));\n this._checkParams();\n\n // Register the phrase (triggers the missing-token POST on a cache miss).\n // We ignore t()'s interpolated return — Phrase renders itself so it can\n // supply the markup-token sentinel values and reconstitute real elements.\n await LangsysApp.Translations.ready();\n // WIRE-4: under `requireCredentials` a phrase that registers fails here through\n // `t()`, also when it mounted before a refusing `init()`; one that registers nothing\n // (`register: false`) is a read and never rejects.\n // Not inside a resolved scope: there the host's text is a translation a server\n // produced, and `t()` is the call that would register it as a source phrase.\n // Nor with `register: false` (VAR-7), nor for a phrase with no text of its own.\n this.textless = isOnlyPlaceholders(this.phrase) && (Object.keys(values).length > 0 || slots.some((slot) => slot.source));\n if (isInResolvedScope(this.host)) this.servedUnrecovered = !this.recoverServed();\n else if (this.register && !this.textless) LangsysApp.Translations.t(this.phrase, this.category);\n\n this.ready = true;\n this._render();\n }\n\n /**\n * Debug-time check that every supplied param has a placeholder to land in.\n * Re-runs only when the key SET changes — a changing `n` value must not\n * re-warn on every render.\n */\n private _checkParams(): void {\n // Before encoding there's nothing to match against — skip without\n // recording, so the check still runs once the phrase exists.\n if (!this.phrase) return;\n\n const signature = Object.keys(this.params).sort().join(',');\n if (signature === this.checkedParamKeys) return;\n this.checkedParamKeys = signature;\n\n warnUnmatchedParams('<Phrase>', [this.phrase, ...this.opaqueTexts], this.params, this.category || undefined);\n }\n\n /**\n * Inside a resolved scope the host holds a translation a server served, and the\n * catalog is keyed by source: the source phrase is the one catalog entry that\n * renders as the served text (`recoverPhraseSource`), never the DOM's text. Its\n * elements are mapped to the source's slots by the order the served translation\n * opened them. Until it is recovered the host renders from its served text,\n * which is right for the locale it was served in.\n */\n private recoverServed(): boolean {\n const recovered = recoverPhraseSource(this.phrase, this.slots.length, this.category, this.params);\n if (!recovered) return false;\n const served = this.slots;\n const slots: RichSlot[] = [];\n hostElements(this.host).forEach((element, j) => {\n const source = recovered.order[j]!;\n this.slotOf.set(element, source);\n slots[source] = served[j]!;\n });\n this.phrase = recovered.phrase;\n this.slots = slots;\n return true;\n }\n\n private _render(): void {\n if (!this.phrase) return;\n if (this.servedUnrecovered) this.servedUnrecovered = !this.recoverServed();\n\n const translated = LangsysApp.Translations.lookup(this.phrase, this.category);\n // A miss for the key looks up the one this phrase was registered under before an\n // opaque element was one empty pair (TOK-1), and renders it through that key's slots.\n const earlier = translated === null && this.earlier ? LangsysApp.Translations.lookup(this.earlier.phrase, this.category) : null;\n if (earlier !== null) {\n const { slots, values } = this.earlier!;\n const resolved = interpolateRich(earlier, { ...values, ...this.values, ...this.params }, slots.length, currentlyLoadedLocale.get());\n this.host.replaceChildren(...reconstitute(resolved, slots, this.host.ownerDocument ?? document));\n fillOpaque(slots, this.params);\n return;\n }\n const raw = translated ?? this.phrase;\n const resolved = interpolateRich(raw, { ...this.values, ...this.params }, this.slots.length, currentlyLoadedLocale.get());\n // Into the nodes already there when the translation keeps the markup's shape, so a\n // framework's references to them stay live; rebuilt only when it does not.\n if (!applyInPlace(this.host, resolved, (element) => this.slotOf.get(element))) {\n const nodes = reconstitute(resolved, this.slots, this.host.ownerDocument ?? document, (element, slot) =>\n this.slotOf.set(element, slot)\n );\n this.host.replaceChildren(...nodes);\n }\n // The caller's params land inside an opaque element too, as plain text (TOK-1).\n fillOpaque(this.slots, this.params);\n }\n}\n\n/** A phrase with no text of its own: only placeholders and markup tokens. */\nfunction isOnlyPlaceholders(phrase: string): boolean {\n return !phrase.replace(/\\{[a-z][a-z0-9_]*\\}/g, '').trim();\n}\n\n/**\n * The host's elements in pre-order, the order `encodeRichText` numbers its slots\n * in. A `data-ls-param` element marks a value (VAR-3), and is no slot; an opaque\n * element is a slot with none inside it (TOK-1).\n */\nfunction hostElements(host: Element): Element[] {\n const out: Element[] = [];\n const visit = (parent: Element) => {\n for (const child of Array.from(parent.children)) {\n if (paramElementName(child as unknown as MarkerNode) !== null) continue;\n out.push(child);\n if (!isOpaqueInPhrase(child)) visit(child);\n }\n };\n visit(host);\n return out;\n}\n\nexport default Phrase;\n","import {\n CONTENT_BLOCK_MARKER_ATTR,\n generateCustomId,\n isContentBlockKnown,\n findSingleTextNode,\n isExcisedFromUnit,\n type WalkNode,\n isContentBlockMarked,\n isPhraseMarked,\n readContentBlockMarker,\n hostCategory,\n isInResolvedScope,\n legacyTokenizeElement,\n isMarkerOnlyUnit,\n type UnitVars,\n registerContentBlock,\n resolveHistoricalBlockId,\n tokenizeElement,\n TRANSLATABLE_ATTRIBUTES,\n VALUE_TRANSLATABLE_ELEMENTS,\n VALUE_TRANSLATABLE_INPUT_TYPES,\n} from './content-block.js';\nimport { interpolate, isICU, normalizeMarkupPlaceholders, warnUnmatchedParams } from './interpolate.js';\nimport { historicalCustomIds, normalizeTokenText } from './identity.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { logger } from './logger.js';\nimport { config as configStore, currentlyLoadedLocale, navigationEpoch, sTranslations } from './stores.js';\nimport type { Unsubscriber } from './signal.js';\nimport { claimHost, inertUnderScope, isHostManaged, releaseHost } from './hosts.js';\nimport { Phrase } from './phrase.js';\nimport { isBlockHandled, isServerCollected, markBlockHandled, recoverBlockSources, warnUnrecoveredSource } from './served-source.js';\nimport { debugNotice, warnUnregistered } from './notices.js';\nimport { groupRuns, renderRun, runToken, type MarkerNode, type VarMarker, type VarRun } from './var-markers.js';\nimport { RESOLVED_MARKER_ATTRS } from './identity.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\nimport { isEmpty } from './utils.js';\n\n/** Options for the `Translate` class. Matches the Svelte component's props. */\nexport interface TranslateOptions {\n /** Optional category under which tokens are registered. Helps translators disambiguate. */\n category?: string;\n /** Optional stable id for the content block. If omitted, we hash category+tokens. */\n custom_id?: string;\n /** Optional human-readable label shown in the Translation Manager. */\n label?: string;\n /**\n * Interpolation params — `{name}`, `{count}`, etc. Same single-brace syntax\n * as `t()`, and what you write in plain DOM. In a framework component's\n * markup write `%name%` / `%count%` instead: Svelte and JSX consume\n * `{name}` at compile time (Vue consumes `{{ name }}`), and `%name%` is\n * normalized back to `{name}` at capture.\n */\n params?: Record<string, ParamPrimitive>;\n /**\n * `false` renders from the catalog and registers nothing, on either lane (VAR-7):\n * for a binding whose content holds values from variables it cannot name without\n * its build-time transform. One debug notice says so. Default `true`.\n */\n register?: boolean;\n}\n\ntype iNode = Node & { originalNodeValue?: string | null };\ntype iElement = HTMLElement & { originalAttributes?: Record<string, string> };\n\n/**\n * How long a host's subtree must stay structurally quiet before the content it\n * shows is taken as settled (SRV-5): a lazy child resolving inside the window\n * replaces a loading placeholder before anything registers.\n *\n * Above React's `FALLBACK_THROTTLE_MS` (300), with margin: React keeps a Suspense\n * fallback it has shown on screen for at least 300ms, even when the content is\n * ready sooner, so a shorter window closes on the fallback and keys the block on it.\n */\nconst SETTLE_MS = 500;\n\n/** The id this SDK stamped on each host this session, so our own stamp is never read as a renderer's. */\nconst ownStamps = new WeakMap<Element, string>();\n\n/**\n * Wrap a DOM element and manage translation for its contents.\n *\n * const el = document.querySelector('#hero');\n * new Translate(el, { category: 'Home' });\n *\n * The first-pass tokenizes text nodes and translatable attributes; if the\n * content is a single text run, it's treated as a plain token. For HTML\n * content, a \"content block\" is registered so translators see the content\n * with the same visual structure users see.\n *\n * Call `.destroy()` to stop reacting to locale changes.\n */\nexport class Translate {\n private element: HTMLElement;\n private options: TranslateOptions;\n private tokens: string[] = [];\n private parseComplete = false;\n private isTokenizing = false;\n private lastTranslatedLocale = '';\n private custom_id: string;\n private unsubscribers: Unsubscriber[] = [];\n /** Sorted params key-set already checked, so value-only updates don't re-warn. */\n private checkedParamKeys: string | null = null;\n /** The block this host registered as, kept so a navigation can re-record its miss. */\n private contentBlock: iContentBlock | null = null;\n /**\n * The id a renderer stamped on this host (MARK-3's identity), adopted rather\n * than derived. Such a host renders from the catalog entry under that id, or\n * its source text, and registers nothing.\n */\n private adoptedId: string | null = null;\n /**\n * Whether an adopted host's source tokens have been recovered: its DOM holds\n * the text a server translated, never the source the catalog is keyed by.\n */\n private sourcesRecovered = false;\n /** The locale an adopted host was served in; its served text is right for that locale. */\n private servedLocale = '';\n /** What the unit's value markers say (VAR-3): the runs among its tokens, and their values. */\n private vars: UnitVars = { values: {}, runs: [], markerOnly: [] };\n /** Each marked run's source, by its first node, where it was recovered rather than read. */\n private runSources = new WeakMap<Node, string>();\n /** Each marked run's text nodes as first seen, before any render wrote them. */\n private runOriginals = new WeakMap<Node, string>();\n /** Each marked value as first seen, for a render that emptied it. */\n private markedValues = new WeakMap<Node, string>();\n /** Marked hosts inside this one that no instance managed, taken over by this walk. */\n private takenOver: Array<{ destroy(): void }> = [];\n /**\n * SRV-5: the content captured at mount is provisional. A framework can mount a\n * block showing a placeholder (a Suspense fallback, a lazy child's spinner)\n * and swap in the real content a moment later. An observer watches the host's\n * STRUCTURE (child lists, never text: a value update must not re-key a block);\n * the first registration waits until it has been quiet for `SETTLE_MS`, and a\n * later structural change re-derives the block and registers what it shows.\n */\n private observer: MutationObserver | null = null;\n private settleTimer: ReturnType<typeof setTimeout> | null = null;\n /** Whether the subtree has been quiet for the settle window since mount. */\n private settled = false;\n private settleWaiters: Array<() => void> = [];\n /** A structural change the tokens do not reflect yet. */\n private dirty = false;\n /** Whether the id is derived from the content, and so follows it when it changes. */\n private derivedId = true;\n /** The id this instance last registered under, so a re-key after the window can be reported. */\n private registeredId: string | null = null;\n /** The text this class last wrote into each text node (see `isUnitChange`). */\n private written = new WeakMap<Node, string>();\n /** The whitespace at each end of a single-token unit's text as the page gave it (`writeKeepingEdges`). */\n private edges = new WeakMap<Node, [string, string]>();\n\n /**\n * @param byWalk Internal: set when an enclosing walk creates this instance for\n * a host nothing managed, so an instance the author constructs replaces it.\n */\n constructor(element: HTMLElement, options: TranslateOptions = {}, byWalk = false) {\n this.element = element;\n this.options = { ...options };\n this.custom_id = options.custom_id || '';\n // Under a request scope the render is a server's, and this class's work would\n // finish after the scope has ended: registration and subscriptions belong to\n // `renderBlock` and `registerBlock` there (SRV-7).\n if (inertUnderScope('Translate')) return;\n claimHost(element, this, byWalk);\n if (options.register === false) warnUnregistered('register-false');\n\n // A stamp this SDK did not write names the host's id (MARK-3). Inside a resolved\n // scope, the host itself or its nearest marked ancestor carrying data-ls-resolved,\n // a renderer already rendered the block from the catalog: adopt the id, render\n // under it, register nothing. Outside one, it is the block's id, app-chosen or\n // derived, to render and register under when the catalog lacks it. Our own stamp,\n // on an element re-mounted in the same session, is only the id we derived.\n // The app's own `custom_id`, when it names the stamp, is the same identity: a\n // server rendered the block under it, and the served text is still a translation.\n const marker = readContentBlockMarker(element);\n if (\n marker?.kind === 'identity' &&\n ownStamps.get(element) !== marker.id &&\n (!this.custom_id || this.custom_id === marker.id)\n ) {\n this.custom_id = marker.id;\n if (isInResolvedScope(element)) this.adoptedId = marker.id;\n }\n this.derivedId = !this.custom_id;\n this.observeStructure();\n\n // First pass: tokenize + save + translate.\n void this.tokenizeContent();\n\n // React to locale changes.\n this.unsubscribers.push(\n currentlyLoadedLocale.subscribe((locale) => {\n if (locale && this.parseComplete) this.translateUpdate(locale);\n })\n );\n\n // The catalog changing is a separate event from the locale changing,\n // and only one of them was observed. A same-locale catalog arrival —\n // the first fetch completing, a `refresh()`, a token-flush write-back —\n // replaces `sTranslations` while `currentlyLoadedLocale` keeps its\n // value, so a locale-only subscription sees nothing and the element\n // keeps showing its source text with a correct catalog in the store.\n this.unsubscribers.push(\n sTranslations.subscribe(() => {\n if (!this.parseComplete) return;\n const locale = currentlyLoadedLocale.get();\n if (!locale) return;\n // The guard in translateUpdate short-circuits on an unchanged\n // locale, which is precisely this case — clear it so the walk\n // actually runs.\n this.lastTranslatedLocale = '';\n this.translateUpdate(locale);\n })\n );\n\n // HINT-13. `subscribe` fires once with the current value; only later advances mean\n // a navigation.\n let initialNavigation = true;\n this.unsubscribers.push(\n navigationEpoch.subscribe(() => {\n if (initialNavigation) {\n initialNavigation = false;\n return;\n }\n this.reenterAfterNavigation();\n })\n );\n }\n\n /**\n * HINT-13: after `notifyNavigation()`, re-enter the lookup as a re-render would, so a miss is\n * recorded at the page's new URL — only while the host is attached to the document. An\n * instance whose node was removed but never destroyed stays subscribed, and re-entering it\n * would report the old page's content for the new one.\n */\n private reenterAfterNavigation(): void {\n if (!this.parseComplete || !this.element?.isConnected || this.adoptedId || !this.registers()) return;\n if (this.hasUnreadChange()) return;\n const { category = '' } = this.options;\n if (this.usesSingleTextNodeFastPath()) {\n this.renderSingleToken(category);\n return;\n }\n // A block that is still unknown is recorded again; `registerContentBlock` applies\n // every lane rule. A registered or resolved one records nothing, and a block inside\n // a resolved scope never did.\n if (\n this.contentBlock &&\n !isContentBlockKnown(this.contentBlock.category, this.custom_id) &&\n !isInResolvedScope(this.element) &&\n !isServerCollected(this.custom_id)\n ) {\n void registerContentBlock({ ...this.contentBlock, custom_id: this.custom_id });\n }\n }\n\n /** Update interpolation params (e.g. a changed count) and re-render. Mirrors `Phrase.setParams`. */\n public setParams(params: Record<string, ParamPrimitive> | undefined): void {\n this.options.params = params;\n // Checked independently of `parseComplete` — tokens are known before\n // content-block registration settles, and params can change during\n // that window.\n this.checkParams();\n if (!this.parseComplete) return;\n this.lastTranslatedLocale = '';\n const locale = currentlyLoadedLocale.get();\n if (locale) this.translateUpdate(locale);\n }\n\n /**\n * Watch the host's structure (SRV-5). Not for an adopted host or one in a\n * resolved scope: served content is already what it shows, and registers\n * nothing. Where there is no `MutationObserver`, the content is settled at mount.\n */\n private observeStructure(): void {\n if (this.adoptedId || isInResolvedScope(this.element) || typeof MutationObserver === 'undefined') {\n this.markSettled();\n return;\n }\n this.observer = new MutationObserver((records) => {\n if (!records.some((record) => this.isUnitChange(record))) return;\n this.dirty = true;\n this.armSettle();\n });\n this.observer.observe(this.element, { childList: true, subtree: true, characterData: true });\n this.armSettle();\n }\n\n /**\n * Whether a mutation changes what this unit shows. A changed child list always\n * does. A changed text does only until the window first closes, and only when it\n * is not the text this class wrote: a framework can swap a placeholder's text for\n * its content in place, and what registers is what the block shows when the\n * window closes. After that, a text change is a value update and never re-keys.\n */\n private isUnitChange(record: MutationRecord): boolean {\n if (!this.isUnitStructure(record.target)) return false;\n if (record.type === 'childList') return true;\n return !this.settled && record.target.nodeValue !== this.written.get(record.target);\n }\n\n /**\n * Whether the unit changed since its tokens were read, counting changes the\n * observer has not delivered yet: a framework's swap and a catalog arriving can\n * fall in the same task, before the observer's callback runs.\n */\n private hasUnreadChange(): boolean {\n const pending = this.observer?.takeRecords() ?? [];\n if (pending.some((record) => this.isUnitChange(record))) {\n this.dirty = true;\n this.armSettle();\n }\n return this.dirty;\n }\n\n /** Write a text node, remembering the text, so the observer can tell this write from a framework's. */\n private writeText(node: Node, text: string): void {\n if (node.nodeValue === text) return;\n this.written.set(node, text);\n node.nodeValue = text;\n }\n\n /**\n * Write a unit's one token with the text node's own whitespace kept at each end, as\n * the block path keeps it: beside an excluded element (TOK-1) it is the space between\n * two words. The ends are the page's, so a re-render never adds to them, and a text\n * the framework has rewritten since gives its own.\n */\n private writeKeepingEdges(node: Node, text: string): void {\n const value = node.nodeValue ?? '';\n let edges = this.written.get(node) === value ? this.edges.get(node) : undefined;\n if (!edges) {\n edges = [/^\\s*/.exec(value)![0], /\\s*$/.exec(value)![0]];\n this.edges.set(node, edges);\n }\n this.writeText(node, edges[0] + text + edges[1]);\n }\n\n /**\n * Whether a changed child list belongs to this unit. An excised subtree, and\n * each nested host, is another instance's. An `<option>`'s list is changed only\n * by this class, writing its text.\n */\n private isUnitStructure(target: Node): boolean {\n for (let node: Node | null = target; node && node !== this.element; node = node.parentNode) {\n if (node.nodeType !== Node.ELEMENT_NODE) continue;\n const element = node as Element;\n if (element.localName === 'option' || isExcisedFromUnit(element)) return false;\n }\n return true;\n }\n\n private armSettle(): void {\n if (this.settleTimer) clearTimeout(this.settleTimer);\n this.settleTimer = setTimeout(() => {\n this.settleTimer = null;\n // Read again before settling, so the new read is the one that registers.\n if (this.dirty && this.parseComplete && !this.isTokenizing) void this.rederive();\n this.markSettled();\n }, SETTLE_MS);\n }\n\n private markSettled(): void {\n if (this.settled) return;\n this.settled = true;\n this.settleWaiters.forEach((resolve) => resolve());\n this.settleWaiters = [];\n }\n\n private whenSettled(): Promise<void> {\n if (this.settled) return Promise.resolve();\n return new Promise((resolve) => this.settleWaiters.push(resolve));\n }\n\n /**\n * The block's structure changed after it was read: read it again, under the id\n * its content now derives (an app's or a stamped id stays), stamp it, render it,\n * and register it if unknown. An id already sent for the earlier content stays\n * registered; the core cannot take a registration back.\n */\n private async rederive(): Promise<void> {\n this.dirty = false;\n this.takenOver.forEach((instance) => instance.destroy());\n this.takenOver = [];\n if (this.derivedId) this.custom_id = '';\n this.contentBlock = null;\n this.parseComplete = false;\n this.lastTranslatedLocale = '';\n const before = this.registeredId;\n await this.tokenizeContent();\n // What registered before the change was what the block showed when its window\n // closed: a placeholder, if one was still there. It stays registered; say so,\n // naming both ids (SRV-5).\n if (before && this.custom_id && this.custom_id !== before) {\n debugNotice(\n `rekey\\0${before}`,\n `A <Translate> block registered as ${before} changed its structure after it settled and is now ${this.custom_id}. If ${before} was a placeholder (a Suspense fallback still showing when the settle window closed), it stays registered.`\n );\n }\n }\n\n /** Stop reacting to locale and catalog changes. Safe to call multiple times. */\n public destroy() {\n this.observer?.disconnect();\n this.observer = null;\n if (this.settleTimer) clearTimeout(this.settleTimer);\n this.settleTimer = null;\n this.unsubscribers.forEach((unsub) => unsub());\n this.unsubscribers = [];\n this.takenOver.forEach((instance) => instance.destroy());\n this.takenOver = [];\n releaseHost(this.element, this);\n }\n\n /**\n * Take over every marked host inside this one that no instance manages\n * (MARK-2, MARK-3). The walk excises such a host from this unit (MARK-4), and\n * without an instance of its own it would never register: a phrase host\n * registers whole, as the one string its markup defines, and a block host\n * registers as its own block or, when it carries a stamped id, renders under\n * that id and registers nothing. Excluded subtrees are not entered, and a\n * marked host's own inside is its instance's to walk.\n */\n private takeOverUnmanagedHosts(): void {\n const { params, label } = this.options;\n const visit = (parent: Element) => {\n for (const child of Array.from(parent.children)) {\n // A nested host's own category when it names one (`data-ls-category`).\n const category = hostCategory(child) ?? this.options.category;\n if (isPhraseMarked(child)) {\n if (!isHostManaged(child)) this.takenOver.push(new Phrase(child as HTMLElement, { category, params, register: this.options.register }, true));\n } else if (isContentBlockMarked(child)) {\n if (!isHostManaged(child)) {\n this.takenOver.push(new Translate(child as HTMLElement, { category, params, label, register: this.options.register }, true));\n }\n } else if (!isExcisedFromUnit(child)) {\n visit(child);\n }\n }\n };\n visit(this.element);\n }\n\n private translateUpdate(currentLocale: string) {\n if (!this.element?.innerHTML || !this.parseComplete) return;\n // The tokens were read before a change still waiting to be re-read: rendering\n // them now would write the old content into the nodes that replaced it, and\n // the re-read would then register that. The re-read renders instead (SRV-5).\n if (this.hasUnreadChange()) return;\n if (this.lastTranslatedLocale === currentLocale) return;\n\n const { category = '' } = this.options;\n\n if (this.usesSingleTextNodeFastPath()) {\n this.renderSingleToken(category);\n this.lastTranslatedLocale = currentLocale;\n } else {\n if (!this.recoverServedSources(currentLocale !== this.servedLocale)) return;\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentLocale;\n if (this.adoptedId) this.restampResolvedLocale(currentLocale);\n }\n }\n\n /**\n * An adopted host holds the text a renderer served, a translation when the\n * page was served in another locale, and the catalog is keyed by source. Its\n * source tokens come from the scope's seed, or the catalog entry the served text\n * was rendered from, never from the DOM (SRV-4): each text node and attribute is\n * given its source as the original it renders from. Until they are recovered the\n * host is left as served, which is right for the locale it was served in; a\n * later switch tries again, since a binding may hand the seed over after mount.\n */\n /**\n * An adopted host re-rendered in another locale names that locale in its own\n * resolved marker, so the marker keeps describing the text it holds. A marker\n * with no locale (bare, `true`) is left as it is.\n */\n private restampResolvedLocale(locale: string): void {\n for (const attr of RESOLVED_MARKER_ATTRS) {\n const value = this.element.getAttribute(attr);\n if (value === null) continue;\n if (!['', 'true', '1', 'yes'].includes(value.trim().toLowerCase()) && value !== locale) this.element.setAttribute(attr, locale);\n return;\n }\n }\n\n private recoverServedSources(warn: boolean): boolean {\n if (!this.adoptedId || this.sourcesRecovered) return true;\n const { category = '', params = {} } = this.options;\n const recovered = recoverBlockSources(this.element, this.adoptedId, category, params);\n if (!recovered) {\n if (warn) warnUnrecoveredSource();\n return false;\n }\n recovered.slots.forEach((slot, i) => {\n const source = recovered.sources[i]!;\n if (slot.run) {\n // A marked run's source is its template; its values stay the framework's.\n this.runSources.set(this.runKey(slot.run), source);\n } else if (slot.attr) {\n const element = slot.node as iElement;\n (element.originalAttributes ??= {})[slot.attr] = source;\n } else {\n const node = slot.node as iNode;\n const value = node.nodeValue ?? '';\n node.originalNodeValue = value.match(/^\\s*/)![0] + source + value.match(/\\s*$/)![0];\n }\n });\n this.tokens = recovered.sources;\n this.sourcesRecovered = true;\n this.checkParams();\n return true;\n }\n\n /**\n * Render a single-token block.\n *\n * Prefers the content-block entry: the token may be stored as a block —\n * registered under an explicit `custom_id`, by an older SDK, or seeded\n * server-side — and flat `t()` cannot see inside block entries, so it would\n * report a miss for content that is present. Falls back to `t()`, which\n * also queues the miss for registration.\n */\n private renderSingleToken(category: string): void {\n const token = this.tokens[0];\n const fromBlock = LangsysApp.Translations.lookupContent(category, this.custom_id, token);\n // The params go INTO `t()`, never onto its result. `t()` renders ICU without\n // params too (ICU-1), so a select in its output has already collapsed to\n // `other`, and interpolating that again can no longer choose by the params\n // supplied here: with `{g: 'female'}` it rendered \"They left\".\n const tWithParams = LangsysApp.Translations.t as unknown as (\n phrase: string,\n category: string,\n params: Record<string, unknown>\n ) => string;\n // The producer says text in a resolved scope is already resolved, so it is a\n // translation and not a source phrase: render from the catalog if we happen to\n // hold it, else leave what the server served, and record nothing on either lane.\n // A block the server's scope sends itself is recorded there, never again here;\n // and a unit that does not register records nothing at all (VAR-7).\n const records = this.settled && this.registers() && !isInResolvedScope(this.element) && !isServerCollected(this.custom_id);\n const found = fromBlock !== null && fromBlock !== undefined;\n\n if (this.isSingleRun()) {\n // One sentence with its values (VAR-3): recorded as its template, written\n // around the values the framework owns.\n if (!found && records) {\n tWithParams(token, category, { ...this.vars.values, ...(this.options.params ?? {}) });\n this.registeredId = this.custom_id;\n }\n const run = this.findRun();\n if (run) this.writeRun(run, found ? fromBlock : (LangsysApp.Translations.lookup(token, category) ?? token));\n return;\n }\n\n let resolved: string;\n if (found) {\n resolved = this.applyParams(fromBlock);\n } else if (!records) {\n resolved = this.applyParams(LangsysApp.Translations.lookup(token, category) ?? token);\n } else {\n resolved = tWithParams(token, category, this.options.params ?? {});\n this.registeredId = this.custom_id;\n }\n\n // Write the ONE text node. Never `innerText`, which replaces every\n // child of the host element: a single-token block still commonly wraps\n // its text in markup — `<Translate><p data-testid=\"x\">text</p></Translate>`\n // is the ordinary framework-component shape — and flattening it destroys\n // the wrapper along with any test id, id, ref or framework anchor on it.\n //\n // There is no `innerText` fallback on purpose. Both callers gate on\n // `usesSingleTextNodeFastPath()`, so the node is guaranteed to exist;\n // an unreachable fallback that quietly does the destructive thing is\n // how this defect would come back the next time someone widens the\n // routing. If it is ever null, that is a routing bug and should be\n // visible as one rather than absorbed into a wiped subtree.\n const textNode = this.findSingleTextNode(this.element);\n if (!textNode) {\n logger.warn(\n 'Translate: single-token fast path reached an element with no text node — this is a routing bug, ' +\n 'not a content problem. Leaving the DOM untouched rather than replacing it.'\n );\n return;\n }\n this.writeKeepingEdges(textNode, resolved);\n }\n\n /**\n * Whether the single-token fast path may claim this element.\n *\n * \"One token\" is NOT the same question as \"one text node\", and treating\n * them as one was the defect. A translatable ATTRIBUTE is also a token, and\n * an element carrying only an attribute token — `<img alt=\"…\">`,\n * `<input placeholder=\"…\">` — has no text node anywhere in its subtree. The\n * fast path would then write the translation as the element's text, and the\n * element itself is gone.\n *\n * So the fast path requires an actual text node to write into. Everything\n * else goes to the node-walking path, which already translates attributes\n * in place and recurses, so a token on a nested element is reached too.\n */\n private usesSingleTextNodeFastPath(): boolean {\n // An adopted id is a block's (MARK-1 stamps blocks), and the fast path would\n // register the token as a phrase.\n if (this.adoptedId) return false;\n return this.tokens.length === 1 && (this.findSingleTextNode(this.element) !== null || this.isSingleRun());\n }\n\n /** A unit whose one token is a marked run is a phrase too (VAR-3, TOK-6): one sentence, with its values. */\n private isSingleRun(): boolean {\n return this.tokens.length === 1 && this.vars.runs.includes(0);\n }\n\n /** Whether this unit registers: not with `register: false`, and not when it is made only of markers (VAR-3, VAR-7). */\n private registers(): boolean {\n return this.options.register !== false && !isMarkerOnlyUnit(this.tokens, this.vars);\n }\n\n /**\n * The unique non-whitespace text node under `root`, or `null` when there is\n * none or more than one — in which case the caller falls back to a flat\n * text render, since there is no single place to put the result.\n */\n /**\n * Publish the resolved `custom_id` on the host element.\n *\n * A server-rendered page is otherwise unreadable: the id is derivable only\n * by re-running the tokenizer over the same subtree, which a reader holding\n * just the HTML cannot do identically — and the tokenizer's own rules are\n * what decide it. Stamping it makes the block self-describing, the same way\n * a `Phrase` host already carries `PHRASE_MARKER_ATTR`.\n *\n * Written on every resolution, including when the migration fallback adopts\n * a legacy id, so the attribute always names the id actually in use rather\n * than the one first derived.\n */\n private stampContentBlockMarker(): void {\n if (!this.element || !this.custom_id) return;\n this.element.setAttribute(CONTENT_BLOCK_MARKER_ATTR, this.custom_id);\n ownStamps.set(this.element, this.custom_id);\n }\n\n /** The unit's first marked run, where its single-run token comes from. */\n private findRun(): VarRun<Node> | null {\n const visit = (parent: Node): VarRun<Node> | null => {\n for (const item of groupRuns(parent.childNodes as unknown as ArrayLike<MarkerNode>) as unknown as Array<{ node: Node } | { run: VarRun<Node> }>) {\n if ('run' in item) return item.run;\n if (item.node.nodeType !== Node.ELEMENT_NODE || isExcisedFromUnit(item.node as Element)) continue;\n const found = visit(item.node);\n if (found) return found;\n }\n return null;\n };\n return visit(this.element);\n }\n\n /** The node a run is known by: its first text node or marker. */\n private runKey(run: VarRun<Node>): Node {\n const first = run.parts[0]!;\n return 'text' in first ? first.text : first.marker.frame[0]!;\n }\n\n /** A run text node's text before any render wrote it. */\n private runOriginal(node: Node): string {\n let original = this.runOriginals.get(node);\n if (original === undefined) {\n original = normalizeMarkupPlaceholders(node.nodeValue ?? '');\n this.runOriginals.set(node, original);\n }\n return original;\n }\n\n /** A marked value: the text the framework shows now, or, where a render emptied it, what it showed. */\n private markedValue(marker: VarMarker<Node>): string {\n const key = marker.value[0] ?? marker.frame[0]!;\n const shown = normalizeTokenText(marker.value.map((node) => node.nodeValue ?? '').join(''));\n if (shown) this.markedValues.set(key, shown);\n return shown || (this.markedValues.get(key) ?? '');\n }\n\n /** Write `template` into a marked run, around its values where it can (see `renderRun`). */\n private writeRun(run: VarRun<Node>, template: string): void {\n const writes = renderRun(run as unknown as VarRun<MarkerNode>, template, this.options.params ?? {}, currentlyLoadedLocale.get(), {\n text: (node) => this.runOriginal(node as unknown as Node),\n value: (marker) => this.markedValue(marker as unknown as VarMarker<Node>),\n });\n for (const [node, text] of writes) this.writeText(node as unknown as Node, text);\n }\n\n /** A marked run inside a block: its translation under the block's id, else its source. */\n private translateRun(run: VarRun<Node>): void {\n const source = this.runSources.get(this.runKey(run)) ?? runToken(run as unknown as VarRun<MarkerNode>, (node) => this.runOriginal(node as unknown as Node));\n this.writeRun(run, this.getTranslation(source) ?? source);\n }\n\n private findSingleTextNode(root: Node): Node | null {\n return findSingleTextNode(root as unknown as { childNodes: ArrayLike<Node & WalkNode> });\n }\n\n private async tokenizeContent(): Promise<boolean> {\n if (this.isTokenizing) return false;\n if (!this.element || !this.element.childNodes.length) {\n this.parseComplete = true;\n this.isTokenizing = false;\n return false;\n }\n\n this.isTokenizing = true;\n\n // Framework-agnostic tokenization + style-snapshot lives in\n // content-block.ts. We store the clone locally only because the\n // existing translate() DOM-mutator references it for content-block\n // detection (`this.tokens` drives the single-vs-multi branch below).\n const { tokens, content, vars } = tokenizeElement(this.element);\n this.tokens = tokens;\n this.vars = vars;\n // WIRE-4: under `requireCredentials` an unconfigured client fails loudly here, as a\n // rejected render and never as a throw from the constructor. A multi-phrase block\n // never calls `t()`, so without this it would render source text silently. A block\n // that registers nothing (`register: false`, or only value markers) is a read and\n // never rejects.\n if (this.registers()) {\n try {\n LangsysApp.Translations.assertConfigured();\n } catch (error) {\n this.isTokenizing = false;\n throw error;\n }\n }\n this.checkParams();\n this.takeOverUnmanagedHosts();\n\n const { category = '' } = this.options;\n\n if (this.usesSingleTextNodeFastPath()) {\n // Derive the id even for a single token: without one there is\n // nothing to look the block up BY, so a single-token block stored\n // in the catalog could never be found and would re-register on\n // every visit.\n if (isEmpty(this.custom_id)) {\n this.custom_id = generateCustomId(category, this.tokens);\n }\n this.stampContentBlockMarker();\n this.renderSingleToken(category);\n // Rendered at once, recorded once the content has settled (SRV-5).\n if (!this.settled) {\n void this.whenSettled().then(() => {\n if (!this.dirty && this.usesSingleTextNodeFastPath()) this.renderSingleToken(category);\n });\n }\n } else {\n const contentBlock: iContentBlock = {\n custom_id: '',\n category,\n label: this.options.label,\n content,\n tokens: this.tokens,\n };\n await this.handleContentBlock(contentBlock);\n }\n\n this.parseComplete = true;\n this.isTokenizing = false;\n // The structure changed while this read was in flight: read it again (SRV-5).\n if (this.dirty && this.settled) void this.rederive();\n return true;\n }\n\n private async handleContentBlock(contentBlock: iContentBlock) {\n if (this.adoptedId) {\n // A stamped identity: render from the catalog entry under it, or leave the\n // source text, and register nothing (MARK-3).\n await LangsysApp.Translations.ready();\n if (this.registers()) LangsysApp.Translations.assertConfigured();\n if (this.element) {\n if (this.recoverServedSources(false)) this.translate(Array.from(this.element.childNodes));\n // The host shows this locale either way: rendered now, or as served.\n this.lastTranslatedLocale = this.servedLocale = currentlyLoadedLocale.get();\n }\n return;\n }\n this.contentBlock = contentBlock;\n const derivedId = isEmpty(this.custom_id);\n if (derivedId) {\n this.custom_id = generateCustomId(contentBlock.category, contentBlock.tokens);\n }\n contentBlock.custom_id = this.custom_id;\n this.stampContentBlockMarker();\n\n // Wait for the first GET /translations to settle before deciding whether\n // to POST — otherwise on a cold cache the lookup misses and we'd POST\n // every CB on every first visit even when the backend already has it.\n await LangsysApp.Translations.ready();\n // Again after the wait: a block mounted before `init()` passed the first check,\n // and under `requireCredentials` a refusing `init()` must still reach it (WIRE-4).\n if (this.registers()) LangsysApp.Translations.assertConfigured();\n\n if (isContentBlockKnown(contentBlock.category, this.custom_id)) {\n // Backend already has this block — translate locally, no POST.\n if (!this.usesSingleTextNodeFastPath() && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n return;\n }\n\n // Migration fallback, LOOKUP ONLY (CID-3). A block an older SDK registered\n // is stored under an id this SDK no longer emits, and its translations must\n // keep resolving instead of orphaning. `historicalCustomIds` lists every shape\n // the fleet's shared legacy fixture names; registration below still uses the\n // corrected id, so the legacy-keyed population can only shrink. Skipped for a\n // caller-supplied custom_id, since nothing was derived.\n //\n // A historical hit is attached only when the stored block holds this block's\n // phrases (CID-4). It used to attach on the id being present, and none of these\n // id spaces is injective, so a collision filed this block under a foreign id\n // and it never registered its own content.\n if (derivedId) {\n const candidates = historicalCustomIds(\n contentBlock.category,\n contentBlock.tokens,\n legacyTokenizeElement(this.element)\n ).filter((id) => id !== this.custom_id);\n const resolved = resolveHistoricalBlockId(contentBlock.category, candidates, contentBlock.tokens);\n if (resolved) {\n this.custom_id = resolved;\n // The fallback just changed which id is in use; the attribute\n // must follow, or it names an id nothing resolves under.\n this.stampContentBlockMarker();\n if (!this.usesSingleTextNodeFastPath() && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n return;\n }\n }\n\n // Not `tokens.length > 1`: an attribute-only block has ONE token and\n // still belongs here, and that guard is what would silently skip its\n // render after the routing above sent it down this path.\n if (!this.usesSingleTextNodeFastPath() && this.element) {\n this.translate(Array.from(this.element.childNodes));\n this.lastTranslatedLocale = currentlyLoadedLocale.get();\n }\n\n // SRV-5: register what the host shows once it has settled, never a placeholder\n // it showed at mount. A structural change in the meantime means this read is\n // stale, and the read that follows it registers instead.\n await this.whenSettled();\n if (this.dirty) return;\n\n // Fire-and-forget: registerContentBlock handles its own errors via\n // the logger. We don't await here because the DOM render path below\n // doesn't depend on the POST completing — translations are looked up\n // from sTranslations on every render, which updates reactively when\n // the GET response arrives.\n if (!this.registers()) {\n // `register: false`, or a unit made only of value markers (VAR-7, VAR-3).\n logger.log('Skipping content block registration: this unit registers nothing');\n } else if (isBlockHandled(this.custom_id, 'seed')) {\n // Already sent on this page from the scope's seed.\n logger.log('Skipping content block registration: the seed already sent it');\n } else if (isServerCollected(this.custom_id)) {\n // The server's request scope sends this block itself after the response (its\n // seed says so), so sending it from the client would register it twice.\n logger.log('Skipping content block registration: the server registers this block');\n } else if (isInResolvedScope(this.element)) {\n // The same rule one level up: a block inside a resolved scope holds translated\n // text, so registering it would file a translation as source, and the hint lane\n // inside `registerContentBlock` would report the localized page. Identity is\n // untouched — the marker stamped above still names this block.\n logger.log('Skipping content block registration: the host sits in a resolved scope');\n } else {\n markBlockHandled(this.custom_id, 'mount');\n this.registeredId = this.custom_id;\n void registerContentBlock(contentBlock);\n }\n\n }\n\n private translate(nodes: iNode[]) {\n const currentLocale = currentlyLoadedLocale.get();\n // With params, the base locale still needs a pass — placeholders must\n // be interpolated even when no translation lookup will hit. So does a\n // block carrying ICU without params, which renders its `other` branch\n // rather than its raw source (ICU-1).\n if (\n currentLocale === configStore.baseLocale &&\n (this.lastTranslatedLocale === '' || this.lastTranslatedLocale === configStore.baseLocale) &&\n isEmpty(this.options.params) &&\n !this.tokens.some((token) => isICU(token))\n ) {\n return;\n }\n\n for (const item of groupRuns(nodes as unknown as MarkerNode[]) as unknown as Array<{ node: iNode } | { run: VarRun<Node> }>) {\n if ('run' in item) {\n this.translateRun(item.run);\n continue;\n }\n const node = item.node;\n if (node?.nodeType === Node.ELEMENT_NODE) {\n // Only this unit's text is rendered: what the tokenizer left out, it did\n // not register, and a phrase host or a nested block renders itself.\n if (isExcisedFromUnit(node as HTMLElement)) continue;\n this.translateAttributes(node as iElement);\n // A <select> writes its options' text (`translateAttributes`). Walking into\n // an option after that would take the text just written as its original,\n // and the next locale would render the previous one's.\n if ((node as Element).localName === 'option' && (node as Element).closest('select')) continue;\n }\n\n if (node?.nodeType !== Node.TEXT_NODE) {\n if (!node?.hasChildNodes()) continue;\n this.translate(Array.from(node.childNodes));\n continue;\n }\n\n if (isEmpty(normalizeTokenText(node.nodeValue ?? ''))) continue;\n\n if (isEmpty(node.originalNodeValue)) {\n // Snapshot in canonical placeholder form so lookups, replaces,\n // and interpolation all operate on `{key}`.\n node.originalNodeValue = normalizeMarkupPlaceholders(node.nodeValue!);\n }\n\n // The LOOKUP key, and it must be the key registration derived. Both sides\n // call `normalizeTokenText` so there is one definition of it: a second copy\n // of the same regex agreed today and would not have followed a change.\n const contentToken = node.originalNodeValue ? normalizeTokenText(node.originalNodeValue) : undefined;\n if (!contentToken) continue;\n\n const translation = this.getTranslation(contentToken);\n\n if (translation && contentToken && node.originalNodeValue) {\n // Replacer fn so `$`-patterns in translations/params stay literal.\n const resolved = this.applyParams(translation);\n this.writeText(node, node.originalNodeValue.replace(contentToken, () => resolved));\n } else if (node.originalNodeValue) {\n this.writeText(node, this.applyParams(node.originalNodeValue));\n }\n }\n }\n\n private getTranslation(token: string): string | null {\n if (!token) return null;\n const { category = '' } = this.options;\n return LangsysApp.Translations.lookupContent(category, this.custom_id, token);\n }\n\n /**\n * Debug-time check that every supplied param has a placeholder to land in.\n * Re-runs only when the key SET changes — a changing `count` value must not\n * re-warn on every render.\n */\n private checkParams(): void {\n // Before tokenization there's nothing to match against — every key\n // would look unused. Skip without recording, so the check still runs\n // once tokens exist. An adopted host's tokens are its served text until\n // its source is recovered, and the params are the source's.\n if (!this.tokens.length || (this.adoptedId && !this.sourcesRecovered)) return;\n\n const { params, category = '' } = this.options;\n const signature = params ? Object.keys(params).sort().join(',') : '';\n if (signature === this.checkedParamKeys) return;\n this.checkedParamKeys = signature;\n\n warnUnmatchedParams('<Translate>', this.tokens, params, category || undefined);\n }\n\n /**\n * Interpolate `{name}`-style params into a resolved text, matching `t()`:\n * unknown keys fall through untouched, and the untranslated fallback is\n * interpolated too. Runs without params as well, since a text carrying ICU\n * renders its `other` branch rather than its raw source (ICU-1). Plain text,\n * braces included, comes back exactly as written.\n */\n private applyParams(text: string): string {\n return interpolate(text, this.options.params ?? {}, currentlyLoadedLocale.get());\n }\n\n private translateAttributes(element: iElement) {\n const tagName = element.tagName.toLowerCase();\n if (!element.originalAttributes) element.originalAttributes = {};\n\n for (const attr of TRANSLATABLE_ATTRIBUTES) {\n this.translateAttribute(element, attr);\n }\n\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tagName)) {\n this.translateAttribute(element, 'value');\n }\n\n if (tagName === 'input') {\n const inputType = element.getAttribute('type')?.toLowerCase();\n if (inputType && VALUE_TRANSLATABLE_INPUT_TYPES.includes(inputType)) {\n this.translateAttribute(element, 'value');\n }\n }\n\n if (tagName === 'select') {\n const options = element.querySelectorAll('option');\n options.forEach((option) => {\n const optionEl = option as iElement;\n if (!optionEl.originalAttributes) optionEl.originalAttributes = {};\n if (optionEl.originalAttributes['textContent'] === undefined) {\n optionEl.originalAttributes['textContent'] = normalizeMarkupPlaceholders(option.textContent || '');\n }\n const originalText = normalizeTokenText(optionEl.originalAttributes['textContent']);\n if (originalText) {\n const translation = this.getTranslation(originalText);\n const text = this.applyParams(translation || optionEl.originalAttributes['textContent']);\n // Into the option's own text node when it has just one, so a framework's\n // reference to it stays live; `textContent =` would replace it.\n const only = option.childNodes.length === 1 ? option.firstChild : null;\n if (only && only.nodeType === Node.TEXT_NODE) {\n this.writeText(only, text);\n } else {\n option.textContent = text;\n }\n }\n });\n }\n }\n\n private translateAttribute(element: iElement, attr: string) {\n const currentValue = element.getAttribute(attr);\n if (!currentValue) return;\n\n if (element.originalAttributes![attr] === undefined) {\n element.originalAttributes![attr] = normalizeMarkupPlaceholders(currentValue);\n }\n\n // Lookup key, derived exactly as registration derives the token. It was\n // `.trim()` alone, while TOK-4 made registration collapse internal whitespace,\n // so any attribute value with a line break or doubled space was stored under\n // one key and asked for under another, and never showed its translation.\n // The fallback below still writes the ORIGINAL value, whitespace and all.\n const originalValue = normalizeTokenText(element.originalAttributes![attr]);\n if (!originalValue) return;\n\n const translation = this.getTranslation(originalValue);\n if (translation) element.setAttribute(attr, this.applyParams(translation));\n else element.setAttribute(attr, this.applyParams(element.originalAttributes![attr]));\n }\n\n}\n\nexport default Translate;\n","import {\n CONTENT_BLOCK_MARKER_ATTR,\n RESOLVED_MARKER_ATTR,\n findSingleTextNode,\n isContentBlockKnown,\n isExcisedFromUnit,\n isPhraseMarked,\n readContentBlockMarker,\n hostCategory,\n RESOLVED_MARKER_ATTRS,\n isInResolvedScope,\n registerContentBlock,\n resolveHistoricalBlockId,\n tokenizeNodes,\n tokenizeUnit,\n isMarkerOnlyUnit,\n scrubContent,\n type UnitVars,\n TRANSLATABLE_ATTRIBUTES,\n VALUE_TRANSLATABLE_ELEMENTS,\n VALUE_TRANSLATABLE_INPUT_TYPES,\n type WalkNode,\n} from './content-block.js';\nimport { encodeRichPhrase, generateCustomId, historicalCustomIds, NON_TRANSLATABLE_ELEMENTS, normalizeMarkupPlaceholders, normalizeTokenText } from './identity.js';\nimport { interpolate, isICU } from './interpolate.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { fillOpaqueText, interpolateRich, splitSentinels, stripSentinels, takesParams } from './richtext.js';\nimport { activeCatalog, activeScope } from './scope-context.js';\nimport { isBlockHandled, isServerCollected, markBlockHandled, rememberSeededBlock } from './served-source.js';\nimport { debugNotice } from './notices.js';\nimport { claimHost } from './hosts.js';\nimport { earlierRichPhrase, groupRuns, renderRun, runToken, toRichNodes, type MarkerNode, type RunItem, type VarMarker, type VarRun } from './var-markers.js';\nimport { config as configStore, currentlyLoadedLocale } from './stores.js';\nimport type { CatalogView } from './translations.js';\nimport type { ParamPrimitive } from './types/translation-fn.js';\nimport type { iCategories } from './types/translations.js';\n\n/**\n * Content blocks without a DOM (spec SRV-1, MARK-1, TOK-6): identify, translate\n * and register a `<Translate>` block from a tree, so a framework rendering on a\n * server, or rendering on the client before mount, emits the translated block\n * and its stamped id instead of source text.\n *\n * A tree is the block's content, the children of the host element, as plain\n * nodes. It is walked by the same code as the DOM (`tokenizeNodes`,\n * `findSingleTextNode`, `isExcisedFromUnit`) through a DOM-shaped view of it, so\n * a tree and the DOM it mirrors yield the same tokens, shape and id.\n *\n * `renderBlock` is synchronous and pure over the active catalog: it registers\n * nothing and its output is the same on a server and in the browser for the\n * same catalog, so a client's first render matches what the server sent. A\n * binding registers with `registerBlock`, which touches no DOM.\n */\n\n/**\n * A node of a block's content. Attribute values are strings; `true` is an attribute with no value.\n *\n * `params` on a nested host's element (a phrase host or a content-block declaration) are\n * that unit's own: it renders with them in place of the block's, so a binding names each\n * unit's values on their own (VAR-2) and a nested phrase keys as it does standing alone.\n * A nested host without them renders with the block's.\n */\nexport type BlockNode =\n | { text: string }\n | { comment: string }\n | {\n tag: string;\n attrs?: Readonly<Record<string, string | true>>;\n children?: readonly BlockNode[];\n params?: Readonly<Record<string, ParamPrimitive>>;\n };\n\n/**\n * A node of a rendered block. Every element names, as `source`, the pre-order\n * index of the input element it renders (elements only, counted across the\n * whole input from 0), so a binding can re-attach what the tree cannot carry —\n * handlers, refs, keys — even where a translation reorders inline markup.\n */\nexport type RenderedNode =\n | { text: string }\n | { comment: string }\n | { tag: string; attrs: Record<string, string | true>; children: RenderedNode[]; source: number };\n\nexport type BlockShape = 'phrase' | 'block' | 'empty';\n\nexport interface BlockOptions {\n category?: string;\n params?: Record<string, ParamPrimitive>;\n /** A label for the block in the Translation Manager, as `Translate`'s option. */\n label?: string;\n /**\n * The app's own `custom_id` for the block: rendered under it, and registered\n * under it with its content when the catalog does not hold it, as\n * `Translate`'s `custom_id` option does.\n */\n id?: string;\n /**\n * A `custom_id` to ADOPT: a renderer already rendered this block from the\n * catalog under it (a stamp carried with the resolved marker, MARK-3). Rendered\n * under it, never registered.\n */\n customId?: string;\n /**\n * `registerBlock` only: the host element on the client, whose ancestors decide\n * GATE-10. The walk starts at its parent, since the host itself carries the\n * resolved marker when it was rendered from the catalog.\n */\n host?: Element;\n /** `false` registers nothing, nested hosts included (VAR-7); `renderBlock` ignores it. Default `true`. */\n register?: boolean;\n}\n\nexport interface RenderedBlock {\n shape: BlockShape;\n /** The id the block renders under: derived, a historical id the catalog holds (CID-3), or adopted. Null when empty. */\n customId: string | null;\n nodes: RenderedNode[];\n /**\n * The attributes to set on the host: the block's id (MARK-1), and, when the\n * rendered text is a translation (a locale other than the base), the resolved\n * marker with that locale (GATE-10), so a DOM reader on the client never files\n * the served translation as source. Empty for an empty block.\n */\n hostAttrs: Record<string, string>;\n}\n\n/**\n * A block as a request scope's seed carries it (SRV-4), for a client that cannot\n * recover the block's source from its DOM: `registerBlock` accepts it in place\n * of the source nodes.\n */\nexport interface SeededBlock {\n customId: string;\n category: string;\n tokens: string[];\n shape: 'phrase' | 'block';\n /**\n * The block's content as `registerBlock` over its nodes would send it, for a\n * client that registers it from the seed. Absent wherever no client does: a\n * phrase-shaped entry, a block the scope's catalog holds, a `collected` one and\n * one marked `register: false`. A seeded block without it registers nothing.\n */\n content?: string;\n /**\n * The server's scope sends this block itself at `close()` (the `server`\n * strategy, or `auto` for a short list), so a client never registers it:\n * not from the seed, and not from the `Translate` over its host.\n */\n collected?: boolean;\n /**\n * `false` when a registration over the block's nodes sends nothing, so\n * `registerBlock(seededBlock)` never registers it: a block rendered with\n * `register: false` (VAR-7), at any depth, whose tokens hold values from\n * variables, carried only so a client can re-render the served text; one under\n * an adopted id; one inside a resolved scope, and the blocks nested in either;\n * and a unit of value markers only.\n */\n register?: false;\n}\n\n/**\n * A phrase a request scope's render missed, as its seed carries it: `t()`, a\n * `<Phrase>` host or a single-token block. `collected` as on `SeededBlock`: the\n * scope sends it itself at `close()`, and the client never records it again.\n */\nexport interface SeededPhrase {\n category: string;\n phrase: string;\n collected?: boolean;\n}\n\n/** A request scope's hydration seed (SRV-4): `LangsysApp.seedCatalog(seed.catalog, seed.locale, seed)` on the client. */\nexport interface RequestSeed {\n locale: string;\n catalog: iCategories;\n blocks: Record<string, SeededBlock>;\n phrases: SeededPhrase[];\n}\n\n/** The tokens and shape of a block's content, exactly as `tokenizeElement` and `Translate` decide them for the same markup. */\nexport function tokenizeTree(nodes: readonly BlockNode[]): { tokens: string[]; shape: BlockShape } {\n const root = view(nodes);\n const { tokens, vars } = tokenizeUnit(root);\n return { tokens, shape: shapeOf(root, tokens, false, vars) };\n}\n\n/**\n * Render a block from its content: the translated tree, the id it renders\n * under and the marker to stamp. Synchronous, registers nothing, and reads only\n * the active catalog (a request scope's, or the page's), so the same input and\n * catalog render the same bytes on a server and in the browser.\n *\n * Nested marked hosts are units of their own (MARK-4), rendered in place: a\n * phrase host as its rich phrase, a declared block as its own block (stamped\n * with its id), a stamped one under its id. `translate=\"no\"`, `data-notrans`\n * and code elements are returned as given.\n */\nexport function renderBlock(nodes: readonly BlockNode[], options: BlockOptions = {}): RenderedBlock {\n const root = view(nodes);\n const { tokens, vars } = tokenizeUnit(root);\n const rendered = renderView(root, options);\n // A request scope keeps what it rendered, for its seed (SRV-4), and whether a\n // registration over these nodes sends it, as registerView decides.\n if (rendered.customId && rendered.shape !== 'empty') {\n const registers = options.register !== false && !options.customId && !isMarkerOnlyUnit(tokens, vars);\n activeScope()?.recordRendered({\n customId: rendered.customId,\n category: options.category ?? '',\n tokens,\n shape: rendered.shape,\n ...(!registers ? { register: false as const } : rendered.shape === 'block' ? { content: contentOf(nodes) } : {}),\n });\n }\n return rendered;\n}\n\n/** The notices already given, one per reason. */\n/**\n * Report, as a debug notice once per process per reason, that a binding could\n * not render a block through `renderBlock`. What happens next depends on the\n * reason, and the notice says which:\n *\n * - a framework component in its subtree, a raw-HTML prop, a raw-text element,\n * a suspense placeholder: SRV-1's one sanctioned fallback, not a fault. The\n * block is served as source with no resolved marker and its app-supplied id\n * stamped where it has one, and the client renders and registers it after\n * hydration.\n * - `variable`: the block holds a value from a variable the binding cannot name\n * without its build-time transform, so it renders from the catalog and\n * registers nothing, on the server or the client (VAR-7).\n *\n * The notice is the core's (bindings write no console output of their own). One\n * raised before `init()` is held until debug is known (see `debugNotice`).\n */\nexport function warnUnrenderedBlock(reason: string): void {\n debugNotice(\n `unrendered\\0${reason}`,\n reason === 'variable'\n ? 'A <Translate> block holds a value from a variable that cannot be named without the build-time transform, so it renders from the catalog and registers nothing, on the server or the client (VAR-7).'\n : `A <Translate> block was served as source (${reason}): the binding could not show it to the renderer, so the client renders and registers it after hydration.`\n );\n}\n\n/** The claim on a host a binding renders through the tree path; it has nothing to destroy. */\nconst RENDERED_BY_BINDING = { destroy(): void {} };\n\n/**\n * Register a block for discovery, with no DOM: what `Translate` registers when\n * it mounts, for a framework that owns the host's text nodes and renders\n * through `renderBlock`. A single-token unit records its phrase miss as `t()`\n * does; a block the catalog lacks, under no historical id, registers with its\n * content; an adopted id (`customId`) registers nothing; nested phrase hosts and\n * declared or unresolved-stamped blocks register as their own units. Inside a\n * request scope it is held for `close()`. Fire-and-forget, and never throws\n * synchronously: the returned promise settles once the registration has run.\n *\n * On a server outside every request scope it resolves at once and registers\n * nothing: there is no scope to hold the block for `close()`, and no `init()` to\n * wait for when the client is the one that initialises, so waiting would keep the\n * tree alive for the life of the process. A debug notice says so, once.\n *\n * Under `requireCredentials` an unconfigured client fails loudly here as on the\n * DOM classes (WIRE-4): on the page the promise rejects with\n * `LangsysConfigurationError`, checked again once `init()` has answered, so a\n * block registered before `init()` refuses rejects too. A `register: false` block\n * is a read and never rejects. A binding that leaves the\n * promise unhandled surfaces it. On a server it never rejects, since an unhandled\n * rejection would end a Node process rather than one request, and the request's\n * `t()` throws already.\n *\n * With `host`, the host is the binding's from this call on: an enclosing\n * `Translate` leaves it alone rather than taking it over as an unmanaged marked host.\n *\n * One-shot: it records what the block is now. A binding calls it again on each\n * change `t` goes through — a locale switch, a new catalog, a navigation — as\n * `Translate` re-enters its lookup (HINT-13).\n *\n * The flows it serves: on a server the outermost host renders and registers,\n * and nested declared hosts are covered through its tree. On the client after\n * hydration, the blocks a scope rendered are registered from its seed, one\n * `registerBlock(seededBlock)` per `seed().blocks` entry after `init()`, since\n * the DOM already holds translated text. That loop is for bindings that mount\n * the DOM classes; a binding that renders trees registers each block from its\n * nodes as it renders. Either way a block or phrase the seed marks `collected`\n * is never registered, since the server's scope sends it itself, and neither is a\n * block the seed marks `register: false`, whose tokens hold per-user values.\n */\nexport function registerBlock(input: readonly BlockNode[] | SeededBlock, options: BlockOptions = {}): Promise<void> {\n // The binding renders this host itself: claim it, so an enclosing `Translate`'s walk\n // never takes it over with its own params (MARK-2). Synchronous, before anything else.\n if (options.host) claimHost(options.host, RENDERED_BY_BINDING);\n if (typeof window === 'undefined' && !activeScope()) {\n debugNotice(\n 'register-block\\0no-scope',\n 'registerBlock() was called on a server outside a request scope, so it registered nothing: there is no scope to hold the block for close(). Render and register inside createRequestScope().run(), or register from the client.'\n );\n return Promise.resolve();\n }\n // A `register: false` block, passed as an option or seeded with the flag, is a read:\n // under `requireCredentials` it never rejects (WIRE-4).\n const registers = options.register !== false && (Array.isArray(input) || (input as SeededBlock).register !== false);\n if (registers && !activeScope()) {\n try {\n LangsysApp.Translations.assertConfigured();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n if (!Array.isArray(input)) rememberSeededBlock(input as SeededBlock);\n // GATE-10: text inside a resolved scope is never recorded. The walk starts at the\n // host's PARENT. A host carries data-ls-resolved itself only when it was rendered\n // from the catalog (`hostAttrs`), and then its block is known and registering it is\n // a no-op; counting the host would instead let that client-side stamp silence the\n // re-entry registration HINT-13 asks for on every later `t` change.\n if (options.host && isInResolvedScope(options.host.parentElement)) return Promise.resolve();\n const root = Array.isArray(input) ? view(input) : null;\n const register = () => {\n try {\n if (root) registerView(root, options, input as readonly BlockNode[]);\n else registerSeeded(input as SeededBlock);\n } catch {\n // Registration never takes a render down with it (REG-10).\n }\n };\n // Inside a scope the scope's catalog is in hand. On a page, what is known is decided\n // once the first catalog has settled, as `Translate` decides it: before then every\n // block and phrase looks unknown, and one the catalog holds would be sent.\n if (activeScope()) {\n register();\n return Promise.resolve();\n }\n return LangsysApp.Translations.ready().then(() => {\n if (registers) LangsysApp.Translations.assertConfigured();\n register();\n });\n}\n\n/**\n * A host element's content as a tree: its child nodes as `BlockNode`s, a\n * `<template>`'s content included. For a binding that holds a DOM, on a server\n * or on the client, so no binding walks a DOM of its own to tokenize.\n */\nexport function blockNodesOf(element: { childNodes: ArrayLike<Node> }): BlockNode[] {\n const out: BlockNode[] = [];\n for (const node of Array.from(element.childNodes)) {\n if (node.nodeType === 3) out.push({ text: node.nodeValue ?? '' });\n else if (node.nodeType === 8) out.push({ comment: node.nodeValue ?? '' });\n else if (node.nodeType === 1) {\n const el = node as Element;\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(el.attributes)) attrs[attr.name] = attr.value;\n const content = el.localName === 'template' ? (el as HTMLTemplateElement).content : el;\n out.push({ tag: el.localName, attrs, children: blockNodesOf(content) });\n }\n }\n return out;\n}\n\n/**\n * Write a rendered block into the host's EXISTING nodes: each text node's value,\n * each translatable attribute and each nested host's unit markers (its id and\n * resolved marker, MARK-1, GATE-10), in place, never replacing a node, so a\n * framework's references to them stay live; and, given a whole `RenderedBlock`,\n * its `hostAttrs` on the host. Only when the DOM has the rendered tree's\n * structure: the same nodes in the same places, each element where its `source`\n * says. Otherwise nothing is touched and it returns\n * `{ applied: false, reason: 'structure' }`: a translation that reorders inline\n * markup cannot be applied to nodes a framework owns.\n *\n * With `self`, `element` is the tree's root rather than its parent: the tree was\n * rendered from `[{ tag, attrs, children: blockNodesOf(element) }]`, as a\n * standalone phrase host is (`data-ls-phrase` on the root, at `source` 0), and\n * `element` is matched against its one root node.\n */\nexport function applyRendered(\n element: Element,\n rendered: RenderedBlock | readonly RenderedNode[],\n options: { self?: boolean } = {}\n): { applied: boolean; reason?: 'structure' } {\n const nodes = Array.isArray(rendered) ? (rendered as readonly RenderedNode[]) : (rendered as RenderedBlock).nodes;\n const writes: Array<() => void> = [];\n let preorder = 0;\n const walk = (parent: { childNodes: ArrayLike<Node> }, list: readonly RenderedNode[]): boolean => {\n const children = Array.from(parent.childNodes).filter((n) => n.nodeType === 1 || n.nodeType === 3 || n.nodeType === 8);\n if (children.length !== list.length) return false;\n for (let i = 0; i < list.length; i++) {\n const dom = children[i]!;\n const node = list[i]!;\n if ('text' in node) {\n if (dom.nodeType !== 3) return false;\n if (dom.nodeValue !== node.text) writes.push(() => (dom.nodeValue = node.text));\n } else if ('comment' in node) {\n if (dom.nodeType !== 8) return false;\n } else {\n const el = dom as Element;\n if (dom.nodeType !== 1 || el.localName !== node.tag || node.source !== preorder++) return false;\n for (const [name, value] of Object.entries(node.attrs)) {\n const text = value === true ? '' : value;\n const written = isTranslatableAttribute(el.localName, name, node.attrs) || UNIT_MARKER_ATTRS.includes(name);\n if (written && el.getAttribute(name) !== text) {\n writes.push(() => el.setAttribute(name, text));\n }\n }\n const content = el.localName === 'template' ? (el as HTMLTemplateElement).content : el;\n if (!walk(content, node.children)) return false;\n }\n }\n return true;\n };\n const parent = options.self ? { childNodes: [element] as unknown as ArrayLike<Node> } : element;\n if (!walk(parent, nodes)) return { applied: false, reason: 'structure' };\n for (const write of writes) write();\n if (!Array.isArray(rendered)) {\n for (const [name, value] of Object.entries((rendered as RenderedBlock).hostAttrs)) element.setAttribute(name, value);\n }\n return { applied: true };\n}\n\n/** The markers a render sets on a nested host, and `applyRendered` writes. */\nconst UNIT_MARKER_ATTRS: readonly string[] = [CONTENT_BLOCK_MARKER_ATTR, RESOLVED_MARKER_ATTR];\n\nfunction isTranslatableAttribute(tag: string, name: string, attrs: Record<string, string | true>): boolean {\n if ((TRANSLATABLE_ATTRIBUTES as readonly string[]).includes(name)) return true;\n if (name !== 'value') return false;\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tag)) return true;\n const type = attrs.type;\n return tag === 'input' && typeof type === 'string' && VALUE_TRANSLATABLE_INPUT_TYPES.includes(type.toLowerCase());\n}\n\n/** Serialise a block's content as HTML, for the content snapshot a block registers with. Not identity. */\nexport function serializeTree(nodes: readonly BlockNode[]): string {\n return nodes.map((node) => serializeNode(node)).join('');\n}\n\n// ---------------------------------------------------------------------\n// A DOM-shaped view of a tree, so the DOM's walks run over it unchanged.\n// ---------------------------------------------------------------------\n\nclass ViewText implements WalkNode {\n readonly nodeType = 3;\n readonly childNodes: ViewNode[] = [];\n constructor(public nodeValue: string) {}\n hasChildNodes(): boolean {\n return false;\n }\n get textContent(): string {\n return this.nodeValue;\n }\n}\n\nclass ViewComment implements WalkNode {\n readonly nodeType = 8;\n readonly childNodes: ViewNode[] = [];\n constructor(public nodeValue: string) {}\n hasChildNodes(): boolean {\n return false;\n }\n get textContent(): string {\n return '';\n }\n}\n\nclass ViewElement implements WalkNode {\n readonly nodeType = 1;\n readonly nodeValue = null;\n readonly tagName: string;\n readonly attrs: Map<string, string | true>;\n childNodes: ViewNode[];\n\n constructor(\n tag: string,\n attrs: Readonly<Record<string, string | true>> | undefined,\n children: ViewNode[],\n readonly source: number,\n /** A nested host's own params, from its `BlockNode`. */\n readonly params?: Readonly<Record<string, ParamPrimitive>>\n ) {\n this.tagName = tag.toUpperCase();\n this.attrs = new Map(Object.entries(attrs ?? {}).map(([name, value]) => [name.toLowerCase(), value]));\n this.childNodes = children;\n }\n\n getAttribute(name: string): string | null {\n const value = this.attrs.get(name.toLowerCase());\n return value === undefined ? null : value === true ? '' : value;\n }\n hasAttribute(name: string): boolean {\n return this.attrs.has(name.toLowerCase());\n }\n setAttribute(name: string, value: string): void {\n this.attrs.set(name.toLowerCase(), String(value));\n }\n hasChildNodes(): boolean {\n return this.childNodes.length > 0;\n }\n get textContent(): string {\n return this.childNodes.map((c) => c.textContent).join('');\n }\n /** Only what the legacy select-option walk asks: `option` descendants. */\n querySelectorAll(selector: string): ViewElement[] {\n const out: ViewElement[] = [];\n const visit = (el: ViewElement) => {\n for (const child of el.childNodes) {\n if (!(child instanceof ViewElement)) continue;\n if (child.tagName.toLowerCase() === selector.toLowerCase()) out.push(child);\n visit(child);\n }\n };\n visit(this);\n return out;\n }\n}\n\ntype ViewNode = ViewText | ViewComment | ViewElement;\n\nfunction view(nodes: readonly BlockNode[]): ViewNode[] {\n let next = 0;\n const build = (list: readonly BlockNode[]): ViewNode[] =>\n list.map((node) => {\n if ('text' in node) return new ViewText(node.text);\n if ('comment' in node) return new ViewComment(node.comment);\n const source = next++;\n return new ViewElement(node.tag, node.attrs, build(node.children ?? []), source, node.params);\n });\n return build(nodes);\n}\n\nfunction toRendered(nodes: readonly ViewNode[]): RenderedNode[] {\n return nodes.map((node) => {\n if (node instanceof ViewText) return { text: node.nodeValue };\n if (node instanceof ViewComment) return { comment: node.nodeValue };\n return {\n tag: node.tagName.toLowerCase(),\n attrs: Object.fromEntries(node.attrs),\n children: toRendered(node.childNodes),\n source: node.source,\n };\n });\n}\n\nfunction toBlockNodes(nodes: readonly ViewNode[]): BlockNode[] {\n return toRendered(nodes).map(function strip(node): BlockNode {\n if ('text' in node || 'comment' in node) return node;\n return { tag: node.tag, attrs: node.attrs, children: node.children.map(strip) };\n });\n}\n\n// ---------------------------------------------------------------------\n// Render and register, mirroring `Translate`.\n// ---------------------------------------------------------------------\n\nfunction shapeOf(root: ViewNode[], tokens: string[], adopted: boolean, vars?: UnitVars): BlockShape {\n if (tokens.length === 0) return 'empty';\n // TOK-6, and an adopted id is a block's (MARK-1 stamps blocks).\n if (!adopted && tokens.length === 1 && (findSingleTextNode({ childNodes: root }) !== null || !!vars?.runs.includes(0))) return 'phrase';\n return 'block';\n}\n\n/** `t()`'s lookup without its miss: what `renderBlock` reads, so rendering records nothing. */\nconst readOnlyView = (): CatalogView => ({\n catalog: () => activeCatalog(),\n locale: () => currentlyLoadedLocale.get(),\n miss: () => {},\n fromSnapshot: () => false,\n});\n\n/** The id a block renders under: adopted, derived, or a historical id the catalog verifies (CID-3, CID-4). */\nfunction resolveId(root: ViewNode[], tokens: string[], category: string, adopted: string | undefined): string {\n if (adopted) return adopted;\n const derived = generateCustomId(category, tokens);\n if (isContentBlockKnown(category, derived)) return derived;\n const candidates = historicalCustomIds(category, tokens, tokenizeNodes(root, true)).filter((id) => id !== derived);\n return resolveHistoricalBlockId(category, candidates, tokens) ?? derived;\n}\n\nfunction renderView(root: ViewNode[], options: BlockOptions): RenderedBlock {\n const { category = '', params = {} } = options;\n const { tokens, vars } = tokenizeUnit(root);\n const shape = shapeOf(root, tokens, !!options.customId, vars);\n const locale = currentlyLoadedLocale.get();\n const apply = (text: string) => interpolate(text, params, locale);\n // A marked run renders around its values (VAR-3); the tree is its own source.\n const writeRun = (run: VarRun<ViewNode>, template: string) => {\n const writes = renderRun(run as unknown as VarRun<MarkerNode>, template, params, locale, {\n text: (node) => node.nodeValue ?? '',\n value: (marker) => normalizeTokenText(marker.value.map((node) => node.nodeValue ?? '').join('')),\n });\n for (const [node, text] of writes) (node as unknown as ViewText).nodeValue = text;\n };\n\n renderNestedHosts(root, options);\n\n if (shape === 'empty') return { shape, customId: null, nodes: toRendered(root), hostAttrs: {} };\n // Resolved only when the text served is a translation from the catalog: a block\n // the catalog lacks is served as source, and a client honouring GATE-10 must\n // still discover it.\n const hostAttrs = (id: string, fromCatalog: boolean): Record<string, string> =>\n fromCatalog && locale && locale !== configStore.baseLocale\n ? { [CONTENT_BLOCK_MARKER_ATTR]: id, [RESOLVED_MARKER_ATTR]: locale }\n : { [CONTENT_BLOCK_MARKER_ATTR]: id };\n\n if (shape === 'phrase') {\n // As `Translate.renderSingleToken`: the block entry first, then `t()`'s lookup.\n const id = options.id ?? generateCustomId(category, tokens);\n const token = tokens[0]!;\n const fromBlock = LangsysApp.Translations.lookupContent(category, id, token);\n const inBlock = fromBlock !== null && fromBlock !== undefined;\n const fromPhrases = LangsysApp.Translations.lookup(token, category);\n const run = vars.runs.includes(0) ? findRun(root) : null;\n if (run) writeRun(run, inBlock ? fromBlock : (fromPhrases ?? token));\n else {\n const node = findSingleTextNode({ childNodes: root }) as ViewText;\n // The node's own whitespace stays at each end, as on the block path: beside an\n // excluded element (TOK-1) it is the space between two words.\n const [lead, trail] = [/^\\s*/.exec(node.nodeValue)![0], /\\s*$/.exec(node.nodeValue)![0]];\n node.nodeValue = lead + (inBlock ? apply(fromBlock) : LangsysApp.Translations.renderWith(readOnlyView(), token, [category, params])) + trail;\n }\n const fromCatalog = inBlock || fromPhrases !== null;\n return { shape, customId: id, nodes: toRendered(root), hostAttrs: hostAttrs(id, fromCatalog) };\n }\n\n const id = options.customId ?? options.id ?? resolveId(root, tokens, category, undefined);\n // As `Translate.translate`: at the base locale, with no params and no ICU, the\n // content is left exactly as written.\n const untouched = locale === configStore.baseLocale && Object.keys(params).length === 0 && !tokens.some((t) => isICU(t));\n if (!untouched) translateNodes(root, (token) => LangsysApp.Translations.lookupContent(category, id, token), apply, writeRun);\n return { shape, customId: id, nodes: toRendered(root), hostAttrs: hostAttrs(id, isContentBlockKnown(category, id)) };\n}\n\n/** `Translate.translate` over a view: this unit's text nodes and attributes, never what it excises. */\n/** The first marked run in a unit, outside what it excises. */\nfunction findRun(nodes: ViewNode[]): VarRun<ViewNode> | null {\n for (const item of groupRuns(nodes as unknown as MarkerNode[]) as unknown as RunItem<ViewNode>[]) {\n if ('run' in item) return item.run;\n const node = item.node;\n if (!(node instanceof ViewElement) || isExcisedFromUnit(node as unknown as Element)) continue;\n const found = findRun(node.childNodes);\n if (found) return found;\n }\n return null;\n}\n\nfunction translateNodes(\n nodes: ViewNode[],\n lookup: (token: string) => string | null,\n apply: (text: string) => string,\n writeRun: (run: VarRun<ViewNode>, template: string) => void\n): void {\n for (const item of groupRuns(nodes as unknown as MarkerNode[]) as unknown as RunItem<ViewNode>[]) {\n if ('run' in item) {\n const token = runToken(item.run as unknown as VarRun<MarkerNode>);\n writeRun(item.run, lookup(token) ?? token);\n continue;\n }\n const node = item.node;\n if (node instanceof ViewComment) continue;\n if (node instanceof ViewElement) {\n if (isExcisedFromUnit(node as unknown as Element)) continue;\n translateAttributes(node, lookup, apply);\n translateNodes(node.childNodes, lookup, apply, writeRun);\n continue;\n }\n if (!normalizeTokenText(node.nodeValue)) continue;\n const original = normalizeMarkupPlaceholders(node.nodeValue);\n const token = normalizeTokenText(original);\n if (!token) continue;\n const translation = lookup(token);\n node.nodeValue = translation ? original.replace(token, () => apply(translation)) : apply(original);\n }\n}\n\nfunction translateAttributes(element: ViewElement, lookup: (token: string) => string | null, apply: (text: string) => string): void {\n const tag = element.tagName.toLowerCase();\n const names: string[] = [...TRANSLATABLE_ATTRIBUTES];\n if (VALUE_TRANSLATABLE_ELEMENTS.includes(tag)) names.push('value');\n const inputType = element.getAttribute('type')?.toLowerCase();\n if (tag === 'input' && inputType && VALUE_TRANSLATABLE_INPUT_TYPES.includes(inputType)) names.push('value');\n for (const name of names) {\n const raw = element.getAttribute(name);\n if (raw === null) continue;\n const original = normalizeMarkupPlaceholders(raw);\n const token = normalizeTokenText(original);\n if (!token) continue;\n const translation = lookup(token);\n element.setAttribute(name, apply(translation ?? original));\n }\n}\n\n/**\n * Nested marked hosts, rendered in place (MARK-2, MARK-3, MARK-4). A host's own\n * inside is its own unit's; excluded subtrees and code are left as given.\n */\n/**\n * The options a nested host is its own unit under: its own category when it names\n * one (`data-ls-category`), else the enclosing block's; and, for a stamped id,\n * adoption when the stamp carries the resolved marker, the id to register under\n * when it does not (MARK-3).\n */\nfunction nestedOptions(node: ViewElement, outer: BlockOptions, resolved: boolean): BlockOptions {\n const element = node as unknown as Element;\n const options: BlockOptions = { category: hostCategory(element) ?? outer.category, params: node.params ?? outer.params, label: outer.label };\n const marker = readContentBlockMarker(element);\n if (marker?.kind === 'identity') {\n if (resolvedHere(element, resolved)) options.customId = marker.id;\n else options.id = marker.id;\n }\n return options;\n}\n\n/**\n * Whether an element sits in a resolved scope within the tree (GATE-10, MARK-3):\n * its own resolved marker decides, else its nearest marked ancestor's, which the\n * walk carries down as `inherited`.\n */\nfunction resolvedHere(element: Element, inherited: boolean): boolean {\n for (const attr of RESOLVED_MARKER_ATTRS) {\n if (!element.hasAttribute(attr)) continue;\n const value = (element.getAttribute(attr) ?? '').trim().toLowerCase();\n return value !== 'false' && value !== '0';\n }\n return inherited;\n}\n\nfunction renderNestedHosts(nodes: ViewNode[], options: BlockOptions, resolved = false): void {\n for (const node of nodes) {\n if (!(node instanceof ViewElement)) continue;\n if (isPhraseMarked(node as unknown as Element)) {\n node.childNodes = renderPhraseHost(node, nestedOptions(node, options, resolved));\n continue;\n }\n const marker = readContentBlockMarker(node as unknown as Element);\n if (marker) {\n // Rendered in place: the nested render works on these same view nodes, so\n // every element keeps its `source` in the enclosing input's numbering.\n const nested = nestedOptions(node, options, resolved);\n // As registerNestedHosts decides: a nested block under `register: false`, under an\n // adopted id or inside a resolved scope registers nothing, nor do the blocks in it.\n const registers = options.register !== false && !nested.customId && !resolvedHere(node as unknown as Element, resolved);\n if (!registers) nested.register = false;\n const { tokens, vars } = tokenizeUnit(node.childNodes);\n const markerOnly = isMarkerOnlyUnit(tokens, vars);\n // Read before the render replaces its text, as registration reads it from the source.\n const content = registers && !markerOnly && activeScope() ? contentOf(toBlockNodes(node.childNodes)) : undefined;\n const rendered = renderView(node.childNodes, nested);\n // The nested host is stamped as the outer host is (MARK-1, GATE-10), and a\n // scope keeps it for its seed, so the client recovers its source too.\n // A stamped host keeps the id it carries, in the spelling it carries it.\n for (const [name, value] of Object.entries(rendered.hostAttrs)) {\n if (marker.kind === 'identity' && name === CONTENT_BLOCK_MARKER_ATTR) continue;\n node.setAttribute(name, value);\n }\n if (rendered.customId && rendered.shape !== 'empty') {\n activeScope()?.recordRendered({\n customId: rendered.customId,\n category: nested.category ?? '',\n tokens,\n shape: rendered.shape,\n ...(!registers || markerOnly ? { register: false as const } : rendered.shape === 'block' ? { content } : {}),\n });\n }\n continue;\n }\n if (isExcisedFromUnit(node as unknown as Element)) continue;\n renderNestedHosts(node.childNodes, options, resolvedHere(node as unknown as Element, resolved));\n }\n}\n\n/** What a phrase's markup token stands for when it renders: an element, or a marked value served with its marker. */\ntype PhraseSlot = { element: ViewElement; opaque: boolean } | { marker: VarMarker<ViewNode> };\n\n/** A phrase host's children, rendered as `Phrase._render` renders them, from a view. */\nfunction renderPhraseHost(host: ViewElement, options: BlockOptions): ViewNode[] {\n const { category = '', params = {} } = options;\n const values: Record<string, string> = {};\n const children = host.childNodes as unknown as MarkerNode[];\n const slotOf = (element: MarkerNode, opaque: boolean): PhraseSlot => ({ element: element as unknown as ViewElement, opaque });\n const { phrase, slots: keyed } = encodeRichPhrase(toRichNodes(children, slotOf, values));\n if (!phrase) return host.childNodes;\n let translated = LangsysApp.Translations.lookup(phrase, category);\n let slots = keyed;\n // A miss looks up the key the phrase was registered under before an opaque element\n // was one empty pair (TOK-1), and renders it through that key's slots; never registered.\n const earlier = translated === null ? earlierRichPhrase(children, slotOf) : null;\n const fromEarlier = earlier ? LangsysApp.Translations.lookup(earlier.phrase, category) : null;\n if (earlier && fromEarlier !== null) {\n translated = fromEarlier;\n slots = earlier.slots;\n for (const [name, value] of Object.entries(earlier.values)) if (!(name in values)) values[name] = value;\n }\n const locale = currentlyLoadedLocale.get();\n // A translation from the catalog is marked resolved, as a block's host is, so a\n // client never reads it as the source phrase (GATE-10).\n if (translated !== null && locale && locale !== configStore.baseLocale) host.setAttribute(RESOLVED_MARKER_ATTR, locale);\n let raw = translated ?? phrase;\n // Served as source, a phrase with marked values renders as a translation does, the\n // whole sentence interpolated at once. Each marked value is a markup slot holding its\n // placeholder, so it keeps its marker (VAR-3) and a reader on the client reads it as\n // its placeholder.\n if (translated === null && Object.keys(values).length) {\n ({ phrase: raw, slots } = encodeRichPhrase(toRichNodes(children, slotOf, {}, true, (marker): PhraseSlot => ({ marker: marker as unknown as VarMarker<ViewNode> }))));\n }\n const resolved = interpolateRich(raw, { ...values, ...params }, slots.length, locale);\n const parts = splitSentinels(resolved);\n if (!parts) return [new ViewText(stripSentinels(resolved))];\n\n const top: ViewNode[] = [];\n const stack: ViewNode[][] = [top];\n for (const part of parts) {\n const current = stack[stack.length - 1]!;\n if ('text' in part) current.push(new ViewText(part.text));\n else if ('open' in part) {\n const slot = slots[part.open];\n if (!slot) return [new ViewText(stripSentinels(resolved))];\n if ('marker' in slot) {\n // A marked value: its value as the sentence interpolated it, inside its marker.\n const [open, close] = slot.marker.frame as [ViewNode, ViewNode?];\n if (close) {\n current.push(open);\n stack.push(current);\n } else {\n const element = open as ViewElement;\n const clone = new ViewElement(element.tagName, Object.fromEntries(element.attrs), [], element.source);\n current.push(clone);\n stack.push(clone.childNodes);\n }\n continue;\n }\n const { element, opaque } = slot;\n // Opaque (TOK-1): its source content as given, the caller's params filled into an\n // author's exclusion as plain text, and whatever a translation put inside its pair dropped.\n const shown = !opaque ? [] : takesParams(element as unknown as Element) ? withParams(element.childNodes, params) : element.childNodes;\n const clone = new ViewElement(element.tagName, Object.fromEntries(element.attrs), shown, element.source);\n current.push(clone);\n stack.push(opaque ? [] : clone.childNodes);\n } else {\n stack.pop();\n const slot = slots[part.close];\n const close = slot && 'marker' in slot ? slot.marker.frame[1] : undefined;\n if (close) stack[stack.length - 1]!.push(close);\n }\n }\n return top;\n}\n\n/** Opaque content copied with the caller's params filled into its text (`fillOpaqueText`); code is copied as it is. */\nfunction withParams(nodes: readonly ViewNode[], params: Readonly<Record<string, unknown>>): ViewNode[] {\n return nodes.map((node) => {\n if (node instanceof ViewText) return new ViewText(fillOpaqueText(node.nodeValue, params));\n if (!(node instanceof ViewElement) || NON_TRANSLATABLE_ELEMENTS.includes(node.tagName.toLowerCase())) return node;\n return new ViewElement(node.tagName, Object.fromEntries(node.attrs), withParams(node.childNodes, params), node.source);\n });\n}\n\nfunction registerView(root: ViewNode[], options: BlockOptions, input: readonly BlockNode[]): void {\n const { category = '', label } = options;\n const { tokens, vars } = tokenizeUnit(root);\n const shape = shapeOf(root, tokens, !!options.customId, vars);\n // `register: false` registers nothing (VAR-7), nested hosts included.\n if (options.register === false) return;\n\n registerNestedHosts(root, options);\n\n // A unit made only of value markers has no text of its own (VAR-3).\n if (shape === 'empty' || options.customId || isMarkerOnlyUnit(tokens, vars)) return;\n if (shape === 'phrase') {\n const id = options.id ?? generateCustomId(category, tokens);\n // The server's request scope sends it itself (its seed says so, SSR-1/SSR-2).\n if (isServerCollected(id)) return;\n const fromBlock = LangsysApp.Translations.lookupContent(category, id, tokens[0]!);\n if (fromBlock === null || fromBlock === undefined) {\n (LangsysApp.Translations.t as unknown as (p: string, c: string) => string)(tokens[0]!, category);\n }\n return;\n }\n const id = options.id ?? resolveId(root, tokens, category, undefined);\n if (isContentBlockKnown(category, id) || isServerCollected(id) || isBlockHandled(id, 'seed')) return;\n if (!activeScope()) markBlockHandled(id, 'mount');\n void registerContentBlock({ custom_id: id, category, label, content: contentOf(input), tokens });\n}\n\n/** A unit's `content`: its nodes as HTML, with no value and no nested unit's content (`scrubContent`). */\nfunction contentOf(input: readonly BlockNode[]): string {\n const shown = view(input);\n scrubContent<ViewNode>(shown, {\n empty: (host) => void ((host as ViewElement).childNodes = []),\n replace: (siblings, nodes, text) => {\n const list = siblings as ViewNode[];\n list.splice(list.indexOf(nodes[0]!), nodes.length, new ViewText(text));\n },\n });\n // The scrubbed view, each element written as the input element it views (its\n // `source`), so tag and attribute names keep their case (an SVG's `viewBox`).\n const elements = elementsOf(input);\n const serialize = (views: readonly ViewNode[]): string =>\n views\n .map((seen) => {\n if (seen instanceof ViewText) return escapeText(seen.nodeValue);\n if (seen instanceof ViewComment) return `<!--${seen.nodeValue}-->`;\n return serializeNode(elements[seen.source]!, serialize(seen.childNodes));\n })\n .join('');\n // `%name%` is stored as `{name}`, as the DOM path stores it, so one block has one content string.\n return normalizeMarkupPlaceholders(serialize(shown));\n}\n\n/** A tree's elements in pre-order, the order `view` numbers each one's `source` in. */\nfunction elementsOf(nodes: readonly BlockNode[]): Extract<BlockNode, { tag: string }>[] {\n return nodes.flatMap((node) => ('tag' in node ? [node, ...elementsOf(node.children ?? [])] : []));\n}\n\n/** A seeded block: a phrase records its miss as `t()` does; an unknown block registers under its id. */\nfunction registerSeeded(block: SeededBlock): void {\n const { customId, category, tokens, shape } = block;\n // Collected by the server, already sent from a mount, or rendered with\n // `register: false`, its tokens then holding per-user values (VAR-1, VAR-7).\n if (block.collected || block.register === false || isBlockHandled(customId, 'mount')) return;\n if (shape === 'phrase') {\n const fromBlock = LangsysApp.Translations.lookupContent(category, customId, tokens[0] ?? '');\n if (tokens[0] && (fromBlock === null || fromBlock === undefined)) {\n (LangsysApp.Translations.t as unknown as (p: string, c: string) => string)(tokens[0], category);\n }\n return;\n }\n if (isContentBlockKnown(category, customId)) return;\n // A block registers with its content, which the API requires: a seeded block\n // without it registers nothing, and is not marked as sent.\n if (!block.content) {\n debugNotice(\n 'register-block\\0seeded-without-content',\n `registerBlock() was given a seeded block with no content (\"${customId}\"), so it registered nothing from it. A Translate or a registerBlock() over the block's own nodes registers it as it would with no seed; a request scope's seed() carries the content of each block a client may register.`\n );\n return;\n }\n markBlockHandled(customId, 'seed');\n void registerContentBlock({ custom_id: customId, category, content: block.content, tokens });\n}\n\nfunction registerNestedHosts(nodes: ViewNode[], options: BlockOptions, resolved = false): void {\n for (const node of nodes) {\n if (!(node instanceof ViewElement)) continue;\n const here = resolvedHere(node as unknown as Element, resolved);\n const category = nestedOptions(node, options, resolved).category ?? '';\n if (isPhraseMarked(node as unknown as Element)) {\n const values: Record<string, string> = {};\n const { phrase, slots } = encodeRichPhrase(toRichNodes(node.childNodes as unknown as MarkerNode[], (_element, opaque) => opaque, values));\n // Text inside a resolved scope is never recorded (GATE-10), nor a phrase with no\n // text of its own: only value markers (VAR-3) or opaque elements (TOK-1).\n const textless = !phrase.replace(/\\{[a-z][a-z0-9_]*\\}/g, '').trim() && (Object.keys(values).length > 0 || slots.some(Boolean));\n if (phrase && !here && !textless) (LangsysApp.Translations.t as unknown as (p: string, c: string) => string)(phrase, category);\n continue;\n }\n const marker = readContentBlockMarker(node as unknown as Element);\n if (marker) {\n // A stamp with the resolved marker is adopted and registers nothing; a\n // declaration, or a stamp without it, registers as its own block.\n const nested = nestedOptions(node, options, resolved);\n if (!nested.customId && !here) registerView(node.childNodes, nested, toBlockNodes(node.childNodes));\n continue;\n }\n if (isExcisedFromUnit(node as unknown as Element)) continue;\n registerNestedHosts(node.childNodes, options, here);\n }\n}\n\n// ---------------------------------------------------------------------\n// Serialisation\n// ---------------------------------------------------------------------\n\nconst VOID_ELEMENTS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);\n\n/** One node as HTML; an element's content is `inner` when given, else its children's. */\nfunction serializeNode(node: BlockNode, inner?: string): string {\n if ('text' in node) return escapeText(node.text);\n if ('comment' in node) return `<!--${node.comment}-->`;\n const tag = node.tag.toLowerCase();\n const attrs = Object.entries(node.attrs ?? {})\n .map(([name, value]) => (value === true ? ` ${name}` : ` ${name}=\"${escapeAttr(value)}\"`))\n .join('');\n if (VOID_ELEMENTS.has(tag)) return `<${tag}${attrs}>`;\n return `<${tag}${attrs}>${inner ?? (node.children ?? []).map((child) => serializeNode(child)).join('')}</${tag}>`;\n}\n\nfunction escapeText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;');\n}\n","import { LangsysAppAPI, LangsysConfigurationError, type ApiCredentials } from './api.js';\nimport { registerContentBlock, type RegistrationResult } from './content-block.js';\nimport { rememberSeededBlock, rememberSeededPhrase } from './served-source.js';\nimport { LangsysApp } from './langsys-app.js';\nimport { canonicalizeLocale } from './locale.js';\nimport { activeScope, enterScope, runInScope, runOutsideScopes, type ActiveScope } from './scope-context.js';\nimport { batchLimit, config as configStore } from './stores.js';\nimport { AUTO_SSR_FLUSH_THRESHOLD, answeredWriteDecision, noticeSsrGrantDegradation, type CatalogView } from './translations.js';\nimport type { RequestSeed, SeededBlock } from './block-tree.js';\nimport type { iContentBlock } from './types/content-block.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { iCategories, iTranslations } from './types/translations.js';\n\n/**\n * Request scopes (spec SRV-7): rendering on a server without one visitor's\n * state reaching the next.\n *\n * The core keeps one catalog, one locale and one miss queue in module state,\n * which is right for a page and wrong for a server process rendering for many\n * visitors at once. A scope holds its own: its locale, its view of the catalog,\n * the misses its render records, and the seed its page hands the client. A\n * binding opens one in its framework's request hook, renders inside `run()`,\n * serialises `seed()` into the page, and calls `close()` after the response.\n *\n * A catalog is fetched at most once per request, and shared read-only (frozen)\n * with scopes rendering the same locale under the same credentials within a\n * minute, so a busy locale costs one fetch rather than one per visitor. Nothing a\n * scope writes is visible to another scope or to the page.\n *\n * A scope may carry its own project id and API key (SRV-2), for a process that\n * renders for more than one project: every request the scope makes goes out under\n * them, and a scope given none sends under the module-wide ones `init()` set.\n */\n\nexport interface RequestScopeOptions {\n /** The request's locale, as the framework or SRV-6 resolved it. */\n locale: string;\n /** A catalog already in hand (a snapshot, an upstream fetch); otherwise it is fetched. */\n catalog?: iCategories;\n /** The page's URL, for the records this scope keeps. */\n url?: string;\n /**\n * The project id and API key this scope's requests send under, with the write grant\n * that goes with them (SRV-2): its catalog fetch, its `close()`, and every request a\n * render inside it makes. Without them the scope sends under the module-wide ones.\n * Never part of `seed()`.\n *\n * Its key's write capability is the one its catalog fetch reports, so a scope handed\n * both a catalog and credentials of its own has no answer for its key and sends\n * nothing at `close()`; the client registers what it missed.\n */\n credentials?: ApiCredentials;\n}\n\n/** A phrase a scope's render missed. */\nexport interface ScopeMiss {\n category: string;\n phrase: string;\n}\n\nexport interface RequestScope {\n readonly locale: string;\n /** `t()` over this scope's catalog; its misses are this scope's. */\n readonly t: TFunction;\n /**\n * Run `fn` inside the scope: top-level `t()`, `LangsysApp.t`, `tSignal.get()`,\n * and the lookups and registrations `Translate` and `Phrase` make, resolve to\n * it. Across `await` only once `setRequestScopeStorage` has an\n * `AsyncLocalStorage`; otherwise only code that finishes inside `fn`.\n *\n * The `t` that `tSignal.get()` returns reads the catalog when it is CALLED, not\n * when it was taken: kept and called after `fn` returns, it reads the page's.\n * A host wrapping `t` for its components returns `scope.t`, which is this\n * scope's wherever it is called.\n */\n run<R>(fn: () => R): R;\n /**\n * Make the scope current for the rest of the current async context, where the\n * render cannot be wrapped in `run()`. Requires `setRequestScopeStorage` to\n * have been given an `AsyncLocalStorage`; throws otherwise.\n *\n * It holds only in the continuation that itself performs the render: called\n * inside a function the host awaits and returns from (a Nuxt plugin, a Nitro\n * request hook, an awaited helper), the scope is gone when that function\n * returns, before or after its own `await` alike. So call `enter()` in the\n * function that renders, `run()` everywhere else, and hand the scope to the\n * app through the framework's own injection when the host awaits you.\n */\n enter(): void;\n /**\n * The hydration seed (SRV-4): on the client, `LangsysApp.seedCatalog(seed.catalog,\n * seed.locale, seed)` before hydration. `blocks` names every block the scope\n * rendered through `renderBlock`, by id, with its category, source tokens and\n * shape, for a client that cannot recover a block's source from DOM already\n * holding the translation; hand each to `registerBlock` after `init()`.\n * `phrases` lists the phrases the render missed. A block or phrase the scope\n * sends itself at `close()` is marked `collected`, and the client never\n * registers it.\n */\n seed(): RequestSeed;\n /** The phrases this scope's render missed. */\n misses(): readonly ScopeMiss[];\n /**\n * After the response (SRV-3): send what the render missed, when the key the\n * scope sends under may write and the SSR strategy collects on the server,\n * then stop recording. Resolves what happened; never throws. Calling it\n * again resolves the first result.\n */\n close(): Promise<RegistrationResult>;\n}\n\nconst SHARE_MS = 60_000;\nconst shared = new Map<string, { at: number; catalog: Promise<FetchedCatalog | null> }>();\n\n/**\n * Open a request scope. Resolves once its catalog is in hand: the one passed,\n * one fetched within the last minute for the same credentials and locale, or a\n * fresh fetch. A fetch that fails leaves the scope rendering source text and\n * recording nothing, as the page does while its catalog is unavailable\n * (WIRE-4). Credentials without both a project id and a key reject with\n * `LangsysConfigurationError`, before anything is sent.\n */\nexport async function createRequestScope(options: RequestScopeOptions): Promise<RequestScope> {\n const credentials = options.credentials === undefined ? undefined : checkedCredentials(options.credentials);\n const locale = canonicalizeLocale(options.locale);\n const fetched = options.catalog ? null : await sharedCatalog(locale, credentials);\n const catalog = options.catalog ? freeze(normalizeCatalog(clone(options.catalog))) : (fetched?.catalog ?? null);\n return new Scope(locale, catalog ?? freeze(normalizeCatalog({} as iCategories)), catalog !== null, false, credentials, fetched?.writeEnabled);\n}\n\n/**\n * SRV-2: a scope's own credentials are a project id and a key together. Anything less is\n * refused rather than read as none, since none means the module-wide key, and that is\n * another project's for a host passing a project of its own.\n */\nfunction checkedCredentials(credentials: ApiCredentials): ApiCredentials {\n const { projectid, key, writeGrant } = credentials ?? ({} as Partial<ApiCredentials>);\n if (typeof projectid !== 'string' || !projectid || typeof key !== 'string' || !key) {\n throw new LangsysConfigurationError(\n 'createRequestScope() was given credentials without both a project id and an API key. Pass both, or leave credentials out to send under the module-wide ones.'\n );\n }\n return Object.freeze({ projectid, key, writeGrant });\n}\n\n/**\n * The request scope a server rendered, rebuilt on the client from its seed, at\n * once and synchronously: for a host whose client render must run inside the\n * same scope as the server's (React's hydration render, which reads the server\n * snapshot), and whose provider cannot await. Its `t` reads the seed's catalog\n * in the seed's locale, so the hydration render produces the served text.\n *\n * It sends nothing itself: the server's scope decided at its own `close()`. What\n * its render misses, and the blocks it registers, go to the page's lanes as a\n * render outside any scope would, which skip what the seed marks `collected`\n * (the seed's blocks and phrases are remembered here, as `seedCatalog` remembers\n * them), so under the `client` strategy the client still registers them.\n *\n * A host that wraps `t` for its components returns `scope.t`, never a `t` taken\n * from `tSignal.get()` inside `run()`: that one reads the catalog when it is\n * called, and called later in the render, outside `run()`, it reads the page's.\n */\nexport function scopeFromSeed(seed: RequestSeed): RequestScope {\n for (const block of Object.values(seed.blocks ?? {})) rememberSeededBlock(block);\n for (const phrase of seed.phrases ?? []) rememberSeededPhrase(phrase);\n const scope = new Scope(canonicalizeLocale(seed.locale), freeze(normalizeCatalog(clone(seed.catalog ?? ({} as iCategories)))), true, true);\n for (const block of Object.values(seed.blocks ?? {})) scope.recordRendered(block);\n return scope;\n}\n\n/** The request scope the current code runs in, if any. */\nexport function currentRequestScope(): RequestScope | undefined {\n const scope = activeScope();\n return scope instanceof Scope ? scope : undefined;\n}\n\n/** Forget every shared catalog, so the next scope for each locale fetches afresh. */\nexport function clearSharedCatalogs(): void {\n shared.clear();\n}\n\n/** Test hook: how many catalogs are held for sharing. */\nexport function _sharedCatalogCount(): number {\n return shared.size;\n}\n\nclass Scope implements RequestScope, ActiveScope {\n /**\n * Set in the constructor as a non-enumerable own property, so a host serialising a scope\n * never ships its key, while a Proxy over the scope (a reactive store holding it) still\n * reads it, as it would not a value keyed to the real instance (Design invariant 4a).\n */\n declare readonly credentials: ApiCredentials | undefined;\n private readonly phraseMisses = new Map<string, ScopeMiss>();\n private readonly blockMisses = new Map<string, iContentBlock>();\n private readonly rendered = new Map<string, SeededBlock>();\n private closing: Promise<RegistrationResult> | null = null;\n\n private readonly view: CatalogView = {\n catalog: () => this.catalog,\n locale: () => this.locale,\n miss: (category, key) => {\n if (!this.available || this.closing) return;\n // A scope rebuilt from a seed records on the page's lanes (see `scopeFromSeed`).\n if (this.fromSeed) return LangsysApp.Translations.recordPageMiss(category, key);\n this.phraseMisses.set(`${category}\\0${key}`, { category, phrase: key });\n },\n fromSnapshot: () => false,\n };\n\n readonly t: TFunction = ((phrase: string, ...rest: unknown[]) =>\n LangsysApp.Translations.renderWith(this.view, phrase, rest)) as TFunction;\n\n constructor(\n readonly locale: string,\n readonly catalog: iCategories,\n private readonly available: boolean,\n private readonly fromSeed = false,\n credentials: ApiCredentials | undefined = undefined,\n /** What this scope's own key may do, as its catalog fetch reported (SRV-2). */\n private readonly keyWriteEnabled: boolean | undefined = undefined\n ) {\n Object.defineProperty(this, 'credentials', { value: credentials, enumerable: false });\n }\n\n run<R>(fn: () => R): R {\n return runInScope(this, fn);\n }\n\n enter(): void {\n enterScope(this);\n }\n\n seed(): RequestSeed {\n // A block this scope will send itself at `close()` is marked `collected`, so the\n // client never sends it again (SSR-1, SSR-2): the decision `flush` makes, taken now.\n const collects = this.serverCollects(this.phraseMisses.size + this.blockMisses.size) && this.mayWrite();\n const blocks: Record<string, SeededBlock> = {};\n for (const [id, block] of this.rendered) {\n const held =\n block.shape === 'phrase'\n ? this.phraseMisses.has(`${block.category}\\0${block.tokens[0]}`)\n : this.blockMisses.has(`${block.category}\\0${id}`);\n // A block the scope sends itself, or one its catalog holds, needs no content in the\n // seed: the client never registers it from there.\n const { content: _content, ...withoutContent } = block;\n const entry = this.catalog[block.category || '__uncategorized__']?.[id];\n const known = typeof entry === 'object' && entry !== null;\n blocks[id] = collects && held ? { ...withoutContent, collected: true } : known ? withoutContent : { ...block };\n }\n const phrases = [...this.phraseMisses.values()].map(({ category, phrase }) => (collects ? { category, phrase, collected: true } : { category, phrase }));\n return { locale: this.locale, catalog: clone(this.catalog), blocks: clone(blocks), phrases };\n }\n\n /** SSR-1 and SSR-2: whether the server sends a scope's misses, for a list this long. */\n private serverCollects(count: number): boolean {\n const strategy = configStore.ssrTokenStrategy || 'client';\n // A grant belongs to the key it was issued with: a scope's own, or the module's.\n if (this.credentials?.writeGrant) {\n if (strategy !== 'client') noticeSsrGrantDegradation(strategy);\n return false;\n }\n if (!this.credentials && LangsysAppAPI.hasWriteGrant()) return false;\n return strategy === 'server' || (strategy === 'auto' && count < AUTO_SSR_FLUSH_THRESHOLD);\n }\n\n /** SRV-3 with SRV-2: whether the key this scope sends under may write. */\n private mayWrite(): boolean {\n return this.credentials ? this.keyWriteEnabled === true : LangsysApp.Translations.mayWrite();\n }\n\n /** The credentials this scope's own requests go out under, wherever they are made. */\n private sendsUnder(): ApiCredentials {\n return this.credentials ?? LangsysAppAPI.moduleCredentials();\n }\n\n recordRendered(block: SeededBlock): void {\n this.rendered.set(block.customId, block);\n }\n\n misses(): readonly ScopeMiss[] {\n return [...this.phraseMisses.values()];\n }\n\n recordBlock(block: iContentBlock): void {\n if (!this.available || this.closing) return;\n if (this.fromSeed) {\n // On the page's lane, once the render that holds this scope has returned, and\n // outside it: under an AsyncLocalStorage the task would otherwise run inside this\n // scope again and hand the block straight back.\n queueMicrotask(() => void runOutsideScopes(() => registerContentBlock(block)));\n return;\n }\n this.blockMisses.set(`${block.category}\\0${block.custom_id}`, block);\n }\n\n close(): Promise<RegistrationResult> {\n this.closing ??= this.flush();\n return this.closing;\n }\n\n private async flush(): Promise<RegistrationResult> {\n const items: Array<Record<string, unknown>> = [\n ...[...this.phraseMisses.values()].map((m) => ({ type: 'phrase', phrase: m.phrase, category: m.category || null })),\n ...[...this.blockMisses.values()].map((b) => ({\n type: 'content_block',\n custom_id: b.custom_id,\n category: b.category || null,\n content: b.content,\n label: b.label,\n phrases: b.tokens.map((phrase) => ({ phrase })),\n })),\n ];\n if (items.length === 0) return { status: true };\n\n // SSR-1 and SSR-2: the server collects only under the `server` strategy, or `auto`\n // for a short list, and never when a grant makes capability per-user. Otherwise the\n // client registers these misses itself after hydration.\n if (!this.serverCollects(items.length)) return { status: false, skipped: true, reason: 'client-strategy' };\n // SRV-3: a read-only key pushes nothing.\n if (!this.mayWrite()) return { status: false, skipped: true, reason: 'not-write-enabled' };\n\n try {\n const size = batchLimit.get();\n // Named, not ambient: close() may run inside another scope, or in none (SRV-2).\n const credentials = this.sendsUnder();\n for (let offset = 0; offset < items.length; offset += size) {\n const response = await LangsysAppAPI.createTranslatableItems(items.slice(offset, offset + size), { credentials });\n if (!response.status) return { status: false, reason: 'refused', errors: response.errors as unknown[] | undefined };\n }\n return { status: true };\n } catch (err) {\n return { status: false, reason: 'failed', errors: [err] };\n }\n }\n}\n\n/** A catalog a scope fetched, with the write capability its key was answered with. */\ninterface FetchedCatalog {\n catalog: iCategories;\n writeEnabled: boolean | undefined;\n}\n\n/**\n * The catalog for a locale: shared within the minute if another scope fetched it under the\n * same credentials, else fetched once. Never shared across keys (SRV-2): the write\n * decision that comes back with a catalog is the key's that asked.\n */\nfunction sharedCatalog(locale: string, credentials: ApiCredentials | undefined): Promise<FetchedCatalog | null> {\n const under = credentials ?? LangsysAppAPI.moduleCredentials();\n // A grant changes what the key may write, so a fetch made with one is shared only with scopes holding one.\n const key = `${under.projectid}\\0${under.key}\\0${under.writeGrant ? 'grant' : ''}\\0${locale}`;\n const now = Date.now();\n // Dropped once past the minute, so a process rendering for many projects keeps only the live ones.\n for (const [held, entry] of shared) if (now - entry.at >= SHARE_MS) shared.delete(held);\n const hit = shared.get(key);\n if (hit) return hit.catalog;\n const catalog = fetchCatalog(locale, credentials).then((result) => {\n // A failure is not shared: the next scope tries again.\n if (result === null) shared.delete(key);\n return result;\n });\n shared.set(key, { at: now, catalog });\n return catalog;\n}\n\nasync function fetchCatalog(locale: string, credentials: ApiCredentials | undefined): Promise<FetchedCatalog | null> {\n try {\n const response = await LangsysAppAPI.getTranslations(locale, { credentials: credentials ?? LangsysAppAPI.moduleCredentials() });\n // Under the module-wide key the answer is the process's write capability, as the\n // page's fetch records it. A scope's own key answers for that scope alone.\n if (!credentials) LangsysApp.Translations.applyWriteEnabled(answeredWriteDecision(response));\n if (response.errors) return null;\n return {\n catalog: freeze(normalizeCatalog((isRecord(response.data) ? response.data : {}) as iCategories)),\n writeEnabled: answeredWriteDecision(response),\n };\n } catch {\n return null;\n }\n}\n\n/** The catalog shape the page publishes: an `__uncategorized__` bucket, every category stamped, nothing else. */\nfunction normalizeCatalog(catalog: iCategories): iCategories {\n for (const category of Object.keys(catalog)) {\n if (!isRecord(catalog[category])) delete catalog[category];\n else catalog[category]!.__category__ = category;\n }\n if (!isRecord(catalog.__uncategorized__)) {\n catalog.__uncategorized__ = { __category__: '__uncategorized__', __symbol__: '__uncategorized__' } as iTranslations;\n }\n return catalog;\n}\n\nfunction freeze<T>(value: T): T {\n if (isRecord(value)) {\n for (const child of Object.values(value)) freeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Langsys SDK — framework-agnostic TypeScript\n *\n * Realtime continuous translations with automatic token discovery for any\n * web app. The public translation surface is `t(phrase, category?, params?)`\n * — the phrase itself is the lookup key (and the source-language default).\n * Frameworks subscribe to `tSignal` for reactive re-renders.\n */\n\n// Public singletons and classes\nexport { LangsysApp } from './langsys-app.js';\nexport { Translations } from './translations.js';\nexport { Translate, type TranslateOptions } from './translate.js';\nexport { Phrase, PHRASE_MARKER_ATTR, type PhraseOptions } from './phrase.js';\nexport {\n encodeRichText,\n reconstitute,\n markupTokenValues,\n stripSentinels,\n type RichSlot,\n type EncodedRichText,\n} from './richtext.js';\nexport { LangsysAppAPI, LangsysConfigurationError } from './api.js';\nexport type { ApiCredentials, SendOptions } from './api.js';\n\n// Content-block helpers (framework-agnostic — for React/Vue/Angular/other\n// wrappers that own their own DOM rendering and only need the registration\n// + dedup primitives, not the Svelte/vanilla in-place DOM mutator).\nexport {\n generateCustomId,\n generateLegacyCustomId,\n isContentBlockKnown,\n isPhraseMarked,\n isTranslationExcluded,\n legacyTokenizeElement,\n PHRASE_MARKER_ATTRS,\n registerContentBlock,\n tokenizeElement,\n type RegistrationReason,\n type RegistrationResult,\n} from './content-block.js';\n\n// Marker constants. Every one `/pure` exports is exported here too, with the same\n// value. The content-block set used to be `/pure`-only while the phrase one was here,\n// and a binding importing `CONTENT_BLOCK_MARKER_ATTR` from this entry got `undefined`:\n// its served-bytes assertion then looked for an attribute named \"undefined\" and could\n// not fail (found by the Svelte lane). Pinned by `marker-exports`.\nexport {\n CONTENT_BLOCK_MARKER_ATTR,\n CONTENT_BLOCK_MARKER_ATTR_LEGACY,\n CONTENT_BLOCK_MARKER_ATTRS,\n PHRASE_MARKER_ATTR_LEGACY,\n RESOLVED_MARKER_ATTR,\n RESOLVED_MARKER_ATTR_LEGACY,\n RESOLVED_MARKER_ATTRS,\n} from './identity.js';\n\n// Reactive primitives\nexport { createSignal, getValue, type Signal, type Subscriber, type Unsubscriber, type Updater } from './signal.js';\nexport { persist, setPersistStorage, type PersistStorage } from './persist.js';\nexport { setTeardownSignal, type TeardownSubscribe } from './teardown.js';\nexport {\n applyRendered,\n blockNodesOf,\n registerBlock,\n renderBlock,\n serializeTree,\n tokenizeTree,\n warnUnrenderedBlock,\n type BlockNode,\n type BlockOptions,\n type BlockShape,\n type RenderedBlock,\n type RenderedNode,\n type SeededBlock,\n type SeededPhrase,\n type RequestSeed,\n} from './block-tree.js';\nexport {\n clearSharedCatalogs,\n createRequestScope,\n currentRequestScope,\n scopeFromSeed,\n type RequestScope,\n type RequestScopeOptions,\n type ScopeMiss,\n} from './request-scope.js';\nexport { setRequestScopeStorage, type ScopeStorage } from './scope-context.js';\n// Variables in registered text: the unregistered notice (VAR-7), placeholder names (VAR-2)\n// and the value marker (VAR-3).\nexport { warnUnregistered } from './notices.js';\nexport { derivePlaceholderNames, snakeCase, type ExpressionShape, type NamedExpression } from './var-names.js';\nexport { VAR_PARAM_ATTR } from './var-markers.js';\nexport {\n SNAPSHOT_FORMAT,\n SNAPSHOT_VERSION,\n SnapshotError,\n buildSnapshot,\n canonicalSnapshotJson,\n parseSnapshot,\n snapshotChecksum,\n type CatalogSnapshot,\n type SnapshotCatalog,\n type SnapshotCategory,\n type SnapshotPayload,\n type SnapshotRefusal,\n} from './snapshot.js';\nexport {\n LEGACY_FORMATS,\n SUPPORTED_LEGACY_FORMATS,\n convertLegacyCall,\n convertLegacyPluralForms,\n convertLegacyValue,\n type LegacyConversion,\n type LegacyEntryPoint,\n type LegacyFormat,\n} from './legacy-value.js';\nexport {\n LegacyFormatError,\n createLegacyKeys,\n type LegacyKeyFile,\n type LegacyKeyHit,\n type LegacyKeyProblem,\n type LegacyKeys,\n} from './legacy-keys.js';\nexport {\n DEFAULT_SERVER_MESSAGE_CATEGORY,\n fillTemplate,\n resolveServerMessages,\n templateMarkers,\n toServerMessage,\n type ResolveServerMessagesOptions,\n type ServerMessagePieces,\n type ServerMessage,\n} from './server-messages.js';\n\n// Stores (advanced usage — direct subscription to translations / locale)\n// `writeEnabled` is the server-computed write capability for this session and\n// the single source of truth for every write decision — never infer it from\n// `key_type`. TRI-STATE, and the states must not be collapsed: `undefined` =\n// not yet authorized (hold), `true` = registering, `false` = read-only. It is\n// browser-authoritative — never written during SSR — so it legitimately reads\n// `undefined` on the server and resolves after hydration. Bindings using\n// `useSyncExternalStore` should pin `getServerSnapshot` to `undefined` so the\n// hydration render matches the server markup.\n//\n// `autoDiscovery` is the server-set POLICY for whether this key may report page\n// URLs — deliberately independent of `writeEnabled` and never merged with it.\n// The canonical public site is `writeEnabled: false` AND `autoDiscovery: true`.\nexport { sTranslations, currentlyLoadedLocale, writeEnabled, autoDiscovery } from './stores.js';\n\n// Logger\nexport { Logger, logger } from './logger.js';\n\n// Utility exports\nexport { md5, md5Legacy, isEmpty } from './utils.js';\nexport { defaultedArguments, findUnusedParamKeys, interpolate, isICU, normalizeMarkupPlaceholders, type InterpolateOptions } from './interpolate.js';\nexport { canonicalizeLocale } from './locale.js';\n\n// Type re-exports\nexport type { ResponseObject as iLangsysResponse } from './types/api.js';\nexport type { iLangsysConfig, iLangsysInitConfig, LocaleSource, WriteGrant } from './types/config.js';\nexport type { iContentBlock } from './types/content-block.js';\nexport type { iCountry, iCountryDialCode, iCountryList } from './types/countries.js';\nexport type { iCurrency, iCurrencyList } from './types/currencies.js';\nexport type { iLanguageName, iLocaleData, iLocaleDefault, iLocaleFlat } from './types/locales.js';\nexport type { iProject } from './types/project.js';\nexport type {\n ExtractParamKeys,\n ParamPrimitive,\n ParamsFor,\n TArgs,\n TFunction,\n TranslationParams,\n} from './types/translation-fn.js';\nexport type { iCategories, iTranslations } from './types/translations.js';\n\n// Convenience exports — `t` is a stable function that delegates to the\n// LangsysApp singleton (reads fresh state on every call). `tSignal` is the\n// reactive primitive frameworks bind to.\nimport { LangsysApp as _LangsysApp } from './langsys-app.js';\nimport type { TFunction } from './types/translation-fn.js';\nimport type { WriteGrant as WriteGrantType } from './types/config.js';\nimport type { ServerMessage as ServerMessageType } from './server-messages.js';\n\nexport const t: TFunction = ((phrase: string, ...rest: unknown[]): string => {\n // Forward all args verbatim; the underlying TFunction implementation\n // handles the (phrase) / (phrase, params) / (phrase, category) /\n // (phrase, category, params) overload discrimination at runtime.\n return (_LangsysApp.Translations.t as (...a: unknown[]) => string)(phrase, ...rest);\n}) as TFunction;\n\nexport const tSignal = _LangsysApp.Translations.tSignal;\n\n/**\n * Tell the SDK the route changed (HINT-13). Call it from your router's after-navigation hook,\n * so content that stays mounted across routes — a persistent layout — is looked up again and\n * its misses are recorded for the new URL. Framework bindings wire this for you.\n */\nexport const notifyNavigation = (): void => _LangsysApp.Translations.notifyNavigation();\n\n/**\n * The header that asks your own API for the user's language (FRM-6):\n * `fetch(url, { headers: { ...localeHeaders() } })`. See `LangsysApp.localeHeaders`.\n */\nexport const localeHeaders = (): Record<string, string> => _LangsysApp.localeHeaders();\n\n/**\n * Render a server message entry (MSG-5): its template through `t()` under the\n * messages category, or the entry's `message` when there is no translation.\n * Standalone alias for `LangsysApp.renderServerMessage`.\n */\nexport const renderServerMessage = (entry: ServerMessageType, category?: string): string =>\n _LangsysApp.renderServerMessage(entry, category);\n\n/**\n * Standalone alias for `LangsysApp.setWriteGrant` — supply the write grant\n * after `init()`, e.g. once the user logs in. Not the refresh path: the token\n * is resolved fresh before every request and never cached, so pass a provider\n * function and let your auth layer decide when to mint.\n */\nexport const setWriteGrant = (grant: WriteGrantType | undefined): Promise<void> =>\n _LangsysApp.setWriteGrant(grant);\n"]}