@rivinia/i18n 0.4.0 → 0.6.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/CHANGELOG.md +131 -0
- package/README.md +96 -13
- package/cli/rivinia-i18n-keys.mjs +267 -32
- package/fesm2022/rivinia-i18n-http-loader.impl-sLjTazQZ.mjs +20 -0
- package/fesm2022/rivinia-i18n-http-loader.impl-sLjTazQZ.mjs.map +1 -0
- package/fesm2022/rivinia-i18n-remote-loader.impl-DE90KQn_.mjs +19 -0
- package/fesm2022/rivinia-i18n-remote-loader.impl-DE90KQn_.mjs.map +1 -0
- package/fesm2022/rivinia-i18n.mjs +822 -432
- package/fesm2022/rivinia-i18n.mjs.map +1 -1
- package/package.json +22 -1
- package/types/rivinia-i18n.d.ts +128 -84
- package/fesm2022/rivinia-i18n-http-loader.impl--BRii7w1.mjs +0 -17
- package/fesm2022/rivinia-i18n-http-loader.impl--BRii7w1.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs +0 -18
- package/fesm2022/rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs +0 -11
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs +0 -16
- package/fesm2022/rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/models/loaders.ts","../../../projects/i18n/src/lib/utils/i18n-utils.ts","../../../projects/i18n/src/lib/utils/cookies.ts","../../../projects/i18n/src/lib/utils/icu.ts","../../../projects/i18n/src/lib/models/i18n-config.ts","../../../projects/i18n/src/lib/utils/loader-context.ts","../../../projects/i18n/src/lib/services/view-transition.service.ts","../../../projects/i18n/src/lib/services/rivinia-i18n.ts","../../../projects/i18n/src/lib/providers/provide-i18n.ts","../../../projects/i18n/src/lib/pipes/translate.pipe.ts"],"sourcesContent":["/**\n * Platform facts a loader needs to build a fetchable URL.\n *\n * `baseUrl` mirrors `document.baseURI`: on the browser it is the document's\n * own base, on the server it is the document's `<base href>` resolved against\n * the incoming request. It always describes a DIRECTORY-like base the way the\n * browser sees it (a `<base href=\"/app/\">` keeps its trailing slash; a\n * `<base href=\"/app\">` does not, exactly as in the browser).\n */\nexport interface LoaderContext {\n /** Absolute base URL for relative dictionary paths. */\n readonly baseUrl: string;\n /** `true` when the application renders on the server (SSR / prerender). */\n readonly isServer: boolean;\n}\n\n/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L, context?: LoaderContext): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service. `context` lets a descriptor pick a\n * platform-specific implementation (e.g. filesystem on the server).\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(context?: LoaderContext): Promise<TranslationLoader<L>>;\n}\n\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { JsonLoader } = await import('../services/json-loader.impl');\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('../services/http-loader.impl');\n return new HttpLoader(options);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('../services/remote-loader.impl');\n return new RemoteLoader(options);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L, context?: LoaderContext) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from '../models/i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n // NOTE: 'cookie' resolves to null on purpose — cookies need request/document\n // context, so the service handles that strategy itself (server REQUEST\n // header, browser document.cookie). See RiviniaI18n storage methods.\n if (strategy === 'none' || strategy === 'cookie') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids, in order.\n * For each browser entry (highest preference first) tries the exact tag, then\n * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n const base = tag.split(/[-_]/)[0];\n if (base && base !== tag) {\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n }\n return null;\n}\n\n/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:\n * the service supplies the header (server `REQUEST`) or `document.cookie`\n * (browser); these functions only parse and serialize.\n */\n\n/** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */\nexport function parseCookie(header: string | null | undefined, name: string): string | null {\n if (!header) return null;\n const prefix = `${name}=`;\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n try {\n return decodeURIComponent(trimmed.slice(prefix.length));\n } catch {\n return trimmed.slice(prefix.length);\n }\n }\n }\n return null;\n}\n\n/** Serializes a language cookie (Lax, root path, one year). */\nexport function serializeCookie(\n name: string,\n value: string,\n options?: { secure?: boolean },\n): string {\n const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;\n return options?.secure ? `${base}; Secure` : base;\n}\n\n/**\n * Decides whether the language cookie gets `Secure`: only on `https:`, never\n * on `localhost` (dev TLS included — `Secure` there buys nothing and risks\n * silent persistence loss). Pure and SSR-safe: unknown locations → `false`.\n * The server never writes cookies regardless (app-owned responses).\n */\nexport function shouldSecureCookie(\n location: { protocol?: string; hostname?: string } | null | undefined,\n): boolean {\n try {\n if (!location) return false;\n if (location.protocol !== 'https:') return false;\n if (location.hostname === 'localhost') return false;\n return true;\n } catch {\n return false;\n }\n}\n","import type { TranslateParams } from '../models/i18n-types';\n\n/**\n * Minimal ICU MessageFormat (MF1) subset: `{name}` interpolation,\n * `{n, plural, …}` (with `offset:`), `{n, selectordinal, …}`, `{x, select, …}`,\n * `#` inside plural-style arguments, `{n, number[, style]}`, `{d, date[, style]}`,\n * and nesting. Categories resolve via the native `Intl.PluralRules(locale)` —\n * Arabic gets all six forms (zero/one/two/few/many/other) with zero extra\n * dependencies.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{count, plural, offset:1 =0 {none} one {you and # other} other {you and # others}}`\n * - `{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{amount, number}`, `{ratio, number, percent}`, `{count, number, integer}`,\n * `{price, number, ::currency/USD}`\n * - `{day, date}`, `{day, date, short|medium|long|full}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n *\n * Offset semantics follow ICU (ICU4J `PluralFormat`): an explicit `=N` matches\n * the RAW argument value, the plural category is selected with\n * `value - offset`, and `#` renders `value - offset` in the locale's digits.\n *\n * Unsupported or malformed constructs never throw: the raw `{…}` segment is\n * returned as-is and parsing continues after it.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n): string {\n return parseMessage(template, 0, template.length, params, locale, null).text;\n}\n\ninterface Parsed {\n text: string;\n /** Index of the closing `}` (or `end` when the level ran out). */\n next: number;\n ok: boolean;\n}\n\n/** The nearest plural-style argument, for `#`. */\ninterface PluralScope {\n readonly value: number;\n readonly offset: number;\n}\n\nfunction parseMessage(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n plural: PluralScope | null,\n): Parsed {\n let out = '';\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') {\n const arg = parseArgument(src, i, end, params, locale, plural);\n if (!arg.ok) return { text: out + src.slice(i, end), next: end, ok: true };\n out += arg.text;\n i = arg.next;\n } else if (ch === '}') {\n return { text: out, next: i, ok: true };\n } else if (ch === '#' && plural !== null) {\n out += formatNumberValue(plural.value - plural.offset, locale, undefined) ?? '#';\n i++;\n } else {\n out += ch;\n i++;\n }\n }\n return { text: out, next: i, ok: true };\n}\n\nfunction parseArgument(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n outerPlural: PluralScope | null,\n): Parsed {\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return { text: src.slice(start, end), next: end, ok: true };\n if (src[i] === '}') {\n const value = params[name.word];\n const rendered =\n value === undefined || value === null || name.word === ''\n ? src.slice(start, i + 1)\n : String(value);\n return { text: rendered, next: i + 1, ok: true };\n }\n if (src[i] !== ',' || name.word === '') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n\n if (type.word === 'number' || type.word === 'date') {\n const formatted = formatTypedArgument(src, start, i, end, type.word, params[name.word], locale);\n return formatted ?? rawSegment(src, start, end);\n }\n\n if (i >= end || src[i] !== ',') return { text: src.slice(start, end), next: end, ok: true };\n if (\n type.word !== 'plural' &&\n type.word !== 'selectordinal' &&\n type.word !== 'select'\n ) {\n return rawSegment(src, start, end);\n }\n i++;\n const numeric = type.word === 'select' ? null : toFiniteNumber(params[name.word]);\n const ordinal = type.word === 'selectordinal';\n const branches = new Map<string, string>();\n let offset = 0;\n i = skipSpaces(src, i, end);\n let closed = false;\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '}') {\n closed = true;\n break;\n }\n if (type.word !== 'select') {\n const offsetClause = readOffset(src, i, end);\n if (offsetClause) {\n offset = offsetClause.value;\n i = offsetClause.next;\n continue;\n }\n }\n const sel = readSelector(src, i, end);\n if (sel.selector === null) return rawSegment(src, start, end);\n i = skipSpaces(src, sel.next, end);\n if (i >= end || src[i] !== '{') {\n return rawSegment(src, start, end);\n }\n // Bodies render immediately: '#' binds to THIS plural's number, or to an\n // outer plural when nested (select inherits, nested plural overrides).\n const scope: PluralScope | null =\n numeric !== null ? { value: numeric, offset } : outerPlural;\n const body = parseMessage(src, i + 1, end, params, locale, scope);\n branches.set(sel.selector, body.text);\n i = body.next + 1;\n }\n if (!closed) return { text: src.slice(start, end), next: end, ok: true };\n if (type.word === 'select') {\n const raw = params[name.word];\n const key = raw === undefined || raw === null ? '' : String(raw);\n return { text: branches.get(key) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n }\n if (numeric === null) return { text: branches.get('other') ?? '', next: i + 1, ok: true };\n // Explicit `=N` matches the RAW value; the category sees `value - offset`.\n const exact = branches.get(`=${numeric}`);\n if (exact !== undefined) return { text: exact, next: i + 1, ok: true };\n let category: string;\n try {\n category = pluralRules(locale, ordinal).select(numeric - offset);\n } catch {\n category = 'other';\n }\n return { text: branches.get(category) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n}\n\n/**\n * `{n, number[, style]}` and `{d, date[, style]}`. Returns `null` when the\n * construct is unsupported (missing/invalid value, unknown style), so the\n * caller can emit the raw segment.\n */\nfunction formatTypedArgument(\n src: string,\n start: number,\n i: number,\n end: number,\n kind: 'number' | 'date',\n value: unknown,\n locale: string,\n): Parsed | null {\n let style: string | undefined;\n if (i < end && src[i] === '}') {\n style = undefined;\n } else if (i < end && src[i] === ',') {\n const word = readWord(src, i + 1, end);\n const after = skipSpaces(src, word.next, end);\n if (after >= end || src[after] !== '}') return null;\n style = word.word;\n i = after;\n } else {\n return null;\n }\n\n const text =\n kind === 'number'\n ? formatNumberValue(value, locale, style)\n : formatDateValue(value, locale, style);\n if (text === null) return null;\n return { text, next: i + 1, ok: true };\n}\n\n/**\n * Reads `offset:<number>`. Only plural-style arguments accept it (ICU grammar:\n * before the selectors).\n */\nfunction readOffset(\n src: string,\n i: number,\n end: number,\n): { value: number; next: number } | null {\n const start = skipSpaces(src, i, end);\n if (!src.startsWith('offset:', start)) return null;\n let j = start + 'offset:'.length;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j === digits) return null;\n const value = Number(src.slice(digits, j));\n if (!Number.isFinite(value)) return null;\n return { value, next: j };\n}\n\nfunction toFiniteNumber(value: string | number | boolean | Date | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && /\\s/.test(src[i])) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n while (j < end && /[^\\s,}]+/.test(src[j])) j++;\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '=') {\n let j = i + 1;\n if (j < end && src[j] === '-') j++;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j < end && src[j] === '.' && j + 1 < end && /[0-9]/.test(src[j + 1])) {\n j++;\n while (j < end && /[0-9]/.test(src[j])) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n\n/** The raw `{…}` segment (balanced braces), so parsing can continue after it. */\nfunction rawSegment(src: string, start: number, end: number): Parsed {\n let depth = 0;\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') depth++;\n else if (ch === '}') {\n depth--;\n if (depth === 0) return { text: src.slice(start, i + 1), next: i + 1, ok: true };\n }\n i++;\n }\n return { text: src.slice(start, end), next: end, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// Intl caching. The parser runs on every render, so formatter construction is\n// memoized; the maps are bounded so a long-lived app cannot grow without limit.\n// ---------------------------------------------------------------------------\n\nconst CACHE_LIMIT = 40;\nconst numberFormats = new Map<string, Intl.NumberFormat>();\nconst dateFormats = new Map<string, Intl.DateTimeFormat>();\nconst pluralRulesByLocale = new Map<string, Intl.PluralRules>();\n\nfunction memo<T>(map: Map<string, T>, key: string, create: () => T): T {\n const hit = map.get(key);\n if (hit !== undefined) return hit;\n const created = create();\n if (map.size >= CACHE_LIMIT) map.clear();\n map.set(key, created);\n return created;\n}\n\nfunction pluralRules(locale: string, ordinal: boolean): Intl.PluralRules {\n const key = `${ordinal ? 'o' : 'c'}|${locale}`;\n return memo(pluralRulesByLocale, key, () =>\n new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined),\n );\n}\n\nfunction formatNumberValue(\n value: unknown,\n locale: string,\n style: string | undefined,\n): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n const options = numberOptions(style);\n if (options === null) return null;\n try {\n const key = `${locale}|${JSON.stringify(options)}`;\n return memo(numberFormats, key, () => new Intl.NumberFormat(locale, options)).format(value);\n } catch {\n return null;\n }\n}\n\nfunction numberOptions(style: string | undefined): Intl.NumberFormatOptions | null {\n if (style === undefined) return {};\n if (style === 'percent') return { style: 'percent' };\n if (style === 'integer') return { maximumFractionDigits: 0 };\n if (style.startsWith('::currency/')) {\n const code = style.slice('::currency/'.length);\n if (/^[A-Za-z]{3}$/.test(code)) {\n return { style: 'currency', currency: code.toUpperCase() };\n }\n }\n return null;\n}\n\nconst DATE_STYLES = new Set(['short', 'medium', 'long', 'full']);\n\nfunction formatDateValue(\n value: unknown,\n locale: string,\n style: string | undefined,\n): string | null {\n const date = toDate(value);\n if (date === null) return null;\n if (style !== undefined && !DATE_STYLES.has(style)) return null;\n const options: Intl.DateTimeFormatOptions =\n style === undefined ? {} : { dateStyle: style as 'short' | 'medium' | 'long' | 'full' };\n try {\n const key = `${locale}|${style ?? ''}`;\n return memo(dateFormats, key, () => new Intl.DateTimeFormat(locale, options)).format(date);\n } catch {\n return null;\n }\n}\n\n/** A `Date` (any realm) or epoch milliseconds; nothing else is a date. */\nfunction toDate(value: unknown): Date | null {\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n if (Object.prototype.toString.call(value) === '[object Date]') {\n const date = value as Date;\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n","import { InjectionToken } from '@angular/core';\nimport type { Language, StorageStrategy, SwitchStrategy, ViewTransitionConfig } from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\nimport type { MissingKeyEvent } from './missing-key';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n /**\n * Language used when a key is absent from the current dictionary. Must be\n * one of `languages`. The fallback dictionary is loaded silently (it never\n * drives `loadingState`), and its messages are rendered with the fallback\n * language's locale — an English plural template keeps English plural rules.\n */\n readonly fallbackLanguage?: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `i18n/{language}.json` layout (files in `public/i18n/`, served from the\n * site root). Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Called when `translate()` cannot resolve a key (absent from the current\n * dictionary, from the fallback dictionary, and with no `defaultValue`).\n * Fires once per key per session. When set, the default console warning is\n * suppressed.\n */\n readonly onMissingKey?: (event: MissingKeyEvent<T>) => void;\n /**\n * Log a `console.warn` (once per key) for unresolved keys.\n * @default isDevMode() && !onMissingKey\n */\n readonly warnOnMissingKey?: boolean;\n /**\n * Load the initial language during provider setup (before first paint).\n * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps\n * that call `loadTranslations` themselves).\n * @default true\n */\n readonly preload?: boolean;\n /**\n * Inline per-language dictionaries. Seeded before any network load (zero\n * network + SSR-safe first paint); a successful loader response still wins.\n */\n readonly translations?: Partial<Record<T, Record<string, unknown>>>;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>('RIVINIA_I18N_CONFIG');\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import type { LoaderContext } from '../models/loaders';\n\n/**\n * Builds the loader context ONCE per application.\n *\n * Browser: `document.baseURI` — the exact base the browser uses for relative\n * `fetch()` URLs.\n *\n * Server: the document's `<base href>` resolved against the incoming request\n * URL, mirroring `document.baseURI` semantics (a relative `<base href=\"./\">`\n * resolves against the request path, not the origin). Without a `<base>`\n * element the origin is used, because the conventional layout serves\n * `public/` at the site root.\n *\n * Never throws: an unparsable request URL or base falls back to the\n * document's own base URI.\n */\nexport function createLoaderContext(request: Request | null, doc: Document): LoaderContext {\n const documentBase = readBaseUri(doc);\n if (!request) {\n return { baseUrl: documentBase, isServer: false };\n }\n\n const requestUrl = parseUrl(request.url);\n const baseHref = readBaseHref(doc);\n\n if (baseHref) {\n const resolved = resolveUrl(baseHref, requestUrl?.href ?? documentBase);\n if (resolved) return { baseUrl: resolved, isServer: true };\n }\n if (requestUrl) {\n return { baseUrl: `${requestUrl.origin}/`, isServer: true };\n }\n return { baseUrl: documentBase, isServer: true };\n}\n\nfunction readBaseUri(doc: Document): string {\n // Domino (the SSR DOM) does not implement `baseURI` and THROWS\n // `NotYetImplemented` on the property read rather than returning\n // `undefined`. Reading it unguarded made constructing the service throw\n // during server rendering, which killed the whole SSR bootstrap — jsdom\n // implements `baseURI`, so no browser-environment test could see it\n // (measured 2026-10-28, projects/i18n-e2e).\n try {\n const uri = (doc as { baseURI?: string } | null)?.baseURI;\n if (typeof uri === 'string' && uri.length > 0) return uri;\n } catch {\n // No usable base URI on this platform; the request/base-href path wins.\n }\n return '/';\n}\n\nfunction readBaseHref(doc: Document): string | null {\n try {\n const element = doc.querySelector?.('base[href]');\n const href = element?.getAttribute('href')?.trim();\n return href ? href : null;\n } catch {\n return null;\n }\n}\n\nfunction parseUrl(value: string | undefined): URL | null {\n if (!value) return null;\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction resolveUrl(value: string, base: string): string | null {\n try {\n return new URL(value, base).href;\n } catch {\n return null;\n }\n}\n","import { DOCUMENT, Service, inject } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _doc = inject(DOCUMENT);\n\n run(callback: () => void): void {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n if (typeof doc.startViewTransition === 'function') {\n doc.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import {\n DOCUMENT,\n PendingTasks,\n REQUEST,\n Service,\n TransferState,\n computed,\n effect,\n inject,\n isDevMode,\n makeStateKey,\n signal,\n type Signal,\n type StateKey,\n} from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from '../models/i18n-config';\nimport type { Direction } from '../models/i18n-types';\nimport type { Language } from '../models/i18n-types';\nimport type { StorageStrategy } from '../models/i18n-types';\nimport type { TranslateParams } from '../models/i18n-types';\nimport type { Translation } from '../models/i18n-types';\nimport type { TranslationLoader } from '../models/loaders';\nimport type { LoaderContext } from '../models/loaders';\nimport type { MissingKeyEvent } from '../models/missing-key';\nimport type { RegisteredI18nKey } from '../models/typed-keys';\nimport { jsonLoader } from '../models/loaders';\nimport { createLoaderContext } from '../utils/loader-context';\nimport { browserLanguages, detectBrowserLanguage, safeGetItem, safeSetItem } from '../utils/i18n-utils';\nimport { parseCookie, serializeCookie, shouldSecureCookie } from '../utils/cookies';\nimport { formatIcu } from '../utils/icu';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _storageKey = this._config.storageKey ?? DEFAULT_STORAGE_KEY;\n private readonly _storageStrategy: StorageStrategy =\n this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY;\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n /** Validated once; `null` means no fallback chain. */\n private readonly _fallbackId: L | null = this._config.fallbackLanguage ?? null;\n /**\n * Injected (not global) document: the dir/lang effect renders on the\n * server too, avoiding an RTL first-paint shift on hydration.\n * Declared before any field initializer that reads storage.\n */\n private readonly _doc = inject(DOCUMENT);\n /** Present only on the server: used for cookie reads + transfer writes. */\n private readonly _request = inject(REQUEST, { optional: true });\n private readonly _transfer = inject(TransferState, { optional: true });\n\n /**\n * Platform facts for loaders, built once: `REQUEST` + `<base href>` on the\n * server, `document.baseURI` in the browser. This is what makes the default\n * loader work under SSR instead of fetching a relative URL Node cannot parse.\n */\n readonly loaderContext: LoaderContext = createLoaderContext(this._request ?? null, this._doc);\n\n private readonly _currentLanguageId = signal<L>(this._resolveInitialLanguage());\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n private readonly _loadedTranslations = signal<Record<string, unknown>>({});\n /**\n * The fallback dictionary, kept separate from `_loadedTranslations` (which\n * always mirrors the VISIBLE language). A signal so `t()`'s computed\n * re-evaluates when the fallback arrives.\n */\n private readonly _fallbackDict = signal<Record<string, unknown> | null>(null);\n /**\n * Explicit loader wins; otherwise the conventional JSON layout\n * (`i18n/{language}.json` — files in `public/i18n/`, served from the site\n * root — unless the consumer overrides the path).\n * The descriptor still code-splits: the fetch implementation loads only on\n * first resolve.\n */\n private readonly _getLoader = (\n context: LoaderContext,\n ): Promise<TranslationLoader<L>> =>\n this._config.loader\n ? this._config.loader.resolve(context)\n : (jsonLoader().resolve(context) as Promise<TranslationLoader<L>>);\n private _resolvedLoader: TranslationLoader<L> | null = null;\n private readonly _translationsCache = new Map<L, Record<string, unknown>>();\n /**\n * Per-language generation, bumped by `reload()`. A load captures the\n * generation before its request and discards the response when it moved:\n * a stale dictionary can never reach the cache or the signals.\n */\n private readonly _generations = new Map<L, number>();\n private readonly _inflight = new Map<\n L,\n Promise<{ data: Record<string, unknown>; ok: boolean }>\n >();\n /**\n * Out-of-order safety: a response reaches the visible signals only when it\n * belongs to the currently intended language (`_currentLanguageId()`).\n * Everything else stays cached. (A monotonic request token used to guard\n * this, but it over-constrained legitimate same-language loads.)\n */\n private _applyCount = 0;\n private _initialized = false;\n private readonly _tasks = inject(PendingTasks, { optional: true });\n\n readonly languageChanged = computed<L>(() => this._currentLanguageId());\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._loadingState.asReadonly();\n readonly loadingError = this._loadingError.asReadonly();\n readonly isLoading = computed(() => this._loadingState() === 'loading');\n\n private readonly _ready = signal(false);\n /**\n * True once the initial language content is available (inline seed and/or\n * initial load settled) — or immediately when `preload: false` skips setup\n * loading. Gate first-paint skeletons on this, not on `isLoading`.\n */\n readonly ready = this._ready.asReadonly();\n\n /**\n * Missing-key reporting. `warnOnMissingKey` defaults to dev-mode warnings\n * unless the consumer supplied a handler (then the handler owns reporting).\n */\n private readonly _warnOnMissingKey: boolean =\n this._config.warnOnMissingKey ??\n (isDevMode() && this._config.onMissingKey === undefined);\n private readonly _missingKeys = signal<readonly string[]>([]);\n private readonly _reportedMissingKeys = new Set<string>();\n private readonly _pendingMissingKeys: string[] = [];\n private _missingFlushQueued = false;\n\n /**\n * Keys that could not be resolved from the current dictionary, the fallback\n * dictionary, or a `defaultValue`, in the order they were first looked up.\n * Published in a microtask because `t()` is a `computed` and Angular forbids\n * signal writes inside a computation.\n */\n readonly missingKeys = this._missingKeys.asReadonly();\n\n /** Resets the report (and the once-per-key dedupe), e.g. after a fix. */\n clearMissingKeys(): void {\n this._reportedMissingKeys.clear();\n this._pendingMissingKeys.length = 0;\n this._missingKeys.set([]);\n }\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error(\n '[rivinia/i18n] At least one language must be provided in the languages array.',\n );\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n if (this._fallbackId !== null && !this._config.languages.some((l) => l.id === this._fallbackId)) {\n throw new Error(\n `[rivinia/i18n] fallbackLanguage \"${this._fallbackId}\" must be one of the configured language IDs.`,\n );\n }\n\n effect(() => {\n const id = this._currentLanguageId();\n this._writeStored(id);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n const lang = this.currentLanguageObject();\n const root = this._doc.documentElement;\n if (!root) return;\n root.dir = lang.dir;\n root.lang = lang.id;\n });\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n /**\n * Runs the provider-setup loading: seeds inline dictionaries, then loads\n * the initial language (unless `preload: false`). Called automatically by\n * the `provideRiviniaI18n` app initializer; call manually only when driving\n * setup yourself. Idempotent. Never rejects (load failures land on\n * `loadingError`/`onLoadError`, inline seeds are preserved).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n const done = this._tasks?.add();\n try {\n const current = this._currentLanguageId();\n const fallback = this._fallbackId;\n const hasFallback = fallback !== null && fallback !== current;\n const preload = this._config.preload ?? true;\n\n const transferred = this.readTransfer(current);\n if (transferred) {\n this._translationsCache.set(current, transferred);\n this._loadedTranslations.set(transferred);\n } else {\n const inline = this._config.translations?.[current];\n if (inline) {\n // Instant paint without touching the cache: the refresh below still\n // runs, so a successful loader response wins; on failure the seed\n // stays visible and the error surfaces on loadingState/onLoadError.\n this._loadedTranslations.set(inline);\n }\n }\n\n let fallbackTransferred: Record<string, unknown> | null = null;\n if (hasFallback) {\n fallbackTransferred = this.readTransfer(fallback);\n if (fallbackTransferred) {\n this._translationsCache.set(fallback, fallbackTransferred);\n this._fallbackDict.set(fallbackTransferred);\n }\n }\n\n const loads: Array<Promise<unknown>> = [];\n if (!transferred && preload) {\n loads.push(this._loadTranslations(current));\n }\n if (hasFallback && !fallbackTransferred && preload) {\n loads.push(this._loadTranslations(fallback, { silent: true, background: true }));\n }\n await Promise.all(loads);\n } finally {\n this._ready.set(true);\n done?.();\n }\n }\n\n translate(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;\n translate(key: RegisteredI18nKey, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: RegisteredI18nKey | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n return this._resolveKeyText(keyOrTranslations, defaultValue, params);\n }\n const currentId = this._currentLanguageId();\n const fallbackId = this._fallbackId;\n return (\n keyOrTranslations[currentId] ??\n (fallbackId !== null ? keyOrTranslations[fallbackId] : undefined) ??\n Object.values(keyOrTranslations)[0] ??\n ''\n );\n }\n\n /**\n * A `computed` over the same resolution chain as `translate()` — for\n * component fields (`readonly title = i18n.t('home.title')`), not for\n * calling from a template expression on every change detection.\n *\n * A function `params` is invoked inside the computation, so the signals it\n * reads are tracked and a change re-renders the text.\n */\n t(key: RegisteredI18nKey): Signal<string>;\n t(key: RegisteredI18nKey, params: TranslateParams | (() => TranslateParams)): Signal<string>;\n t(\n key: RegisteredI18nKey,\n defaultValue: string,\n params?: TranslateParams | (() => TranslateParams),\n ): Signal<string>;\n t(\n key: RegisteredI18nKey,\n defaultValueOrParams?: string | TranslateParams | (() => TranslateParams),\n maybeParams?: TranslateParams | (() => TranslateParams),\n ): Signal<string> {\n const defaultValue =\n typeof defaultValueOrParams === 'string' ? defaultValueOrParams : undefined;\n const paramsSource =\n typeof defaultValueOrParams === 'string' ? maybeParams : defaultValueOrParams;\n return computed(() => {\n const params = typeof paramsSource === 'function' ? paramsSource() : paramsSource;\n return this._resolveKeyText(key, defaultValue, params);\n });\n }\n\n private _resolveKeyText(\n key: RegisteredI18nKey,\n defaultValue: string | undefined,\n params: TranslateParams | undefined,\n ): string {\n const resolved = this._lookupKey(key);\n if (resolved !== undefined) {\n return this.render(resolved.text, params, resolved.locale);\n }\n if (defaultValue === undefined) {\n this._reportMissingKey(key);\n }\n const fallback = defaultValue ?? key;\n return params ? this.render(fallback, params, this.locale()) : fallback;\n }\n\n loadedTranslations = this._loadedTranslations.asReadonly();\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n return (await this._loadTranslations(languageId, opts)).data;\n }\n\n /**\n * Invalidates cached dictionaries and reloads them from the loader.\n *\n * - `reload()` — refreshes the current language (and the fallback, when\n * configured) and drops every OTHER cached dictionary, so the next switch\n * refetches. Resolves `true` when the current language loaded.\n * - `reload(lang)` — refreshes one language. If it is the current one it is\n * applied; otherwise it is only re-cached (and refreshed in the fallback\n * slot when it is the fallback).\n *\n * The visible dictionary stays on screen until the fresh one arrives\n * (stale-while-revalidate), so a reload never flashes raw keys.\n *\n * Never rejects: failures land on `loadingState`, `loadingError` and\n * `onLoadError` exactly like `loadTranslations`.\n */\n reload(languageId?: L): Promise<boolean> {\n if (languageId !== undefined) {\n if (!this._languages().some((l) => l.id === languageId)) {\n return Promise.resolve(false);\n }\n this._invalidate(languageId);\n return this._reloadOne(languageId);\n }\n\n const currentId = this._currentLanguageId();\n const fallbackId = this._fallbackId;\n\n for (const cachedId of [...this._translationsCache.keys()]) {\n if (cachedId !== currentId && cachedId !== fallbackId) {\n this._translationsCache.delete(cachedId);\n }\n }\n // Every language is superseded, so any response already in flight for a\n // dictionary this reload does not refetch is dropped instead of cached.\n for (const language of this._languages()) {\n this._invalidate(language.id);\n }\n\n const currentLoad = this._reloadOne(currentId);\n if (fallbackId !== null && fallbackId !== currentId) {\n void this._reloadOne(fallbackId);\n }\n return currentLoad;\n }\n\n private _reloadOne(languageId: L): Promise<boolean> {\n return this._loadTranslations(languageId, {\n force: true,\n // A dictionary that is not on screen must not drive loadingState.\n background: languageId !== this._currentLanguageId(),\n }).then((result) => result.ok);\n }\n\n private _generationOf(languageId: L): number {\n return this._generations.get(languageId) ?? 0;\n }\n\n private _invalidate(languageId: L): void {\n this._generations.set(languageId, this._generationOf(languageId) + 1);\n }\n\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash.\n * A failed load aborts: language, direction and dictionary stay untouched. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n const { ok } = await this._loadTranslations(id, { silent: true });\n if (!ok) return;\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language locale (cached Intl). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this.numberFormatter(options).format(value);\n }\n\n /** Date/time formatting bound to the current language locale (cached Intl). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this.dateTimeFormatter(options).format(value);\n }\n\n /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */\n readonly locale = computed<string>(() => {\n return this.currentLanguageObject().locale ?? this._currentLanguageId();\n });\n\n private readonly _formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();\n\n private numberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat {\n const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.NumberFormat | undefined;\n if (!formatter) {\n formatter = new Intl.NumberFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private dateTimeFormatter(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.DateTimeFormat | undefined;\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._applyCount++;\n\n const apply = () => this._currentLanguageId.set(id);\n const vt = this._config.viewTransition;\n const useTransition =\n vt?.enabled &&\n (!vt.skipInitialTransition || this._applyCount > 1) &&\n this._viewTransition != null;\n\n if (useTransition) {\n vt!.onViewTransitionCreated?.({ language: id, direction: lang.dir });\n this._viewTransition!.run(apply);\n } else {\n apply();\n }\n\n if (!opts?.skipLoad) {\n void this._loadTranslations(id);\n this._ensureFallback();\n }\n }\n\n private render(template: string, params: TranslateParams | undefined, locale: string): string {\n if (!params) return template;\n if (!template.includes('{')) return template;\n try {\n return formatIcu(template, params, locale);\n } catch {\n return template;\n }\n }\n\n /**\n * Current dictionary first, then the fallback dictionary. The returned\n * locale belongs to the dictionary the text came from: an English plural\n * template borrowed by an Arabic UI must use English plural rules.\n */\n private _lookupKey(key: string): { text: string; locale: string } | undefined {\n const currentValue = this._resolveKey(this._loadedTranslations(), key);\n if (currentValue !== undefined) {\n return { text: currentValue, locale: this.locale() };\n }\n const fallbackId = this._fallbackId;\n if (fallbackId === null || fallbackId === this._currentLanguageId()) return undefined;\n const fallbackDict =\n this._fallbackDict() ?? this._config.translations?.[fallbackId] ?? null;\n if (!fallbackDict) return undefined;\n const fallbackValue = this._resolveKey(fallbackDict, key);\n if (fallbackValue === undefined) return undefined;\n return { text: fallbackValue, locale: this._localeOf(fallbackId) };\n }\n\n private _localeOf(languageId: L): string {\n return this._languages().find((l) => l.id === languageId)?.locale ?? languageId;\n }\n\n /** Loads the fallback in the background when it is not cached yet. */\n private _ensureFallback(): void {\n const fallbackId = this._fallbackId;\n if (fallbackId === null || fallbackId === this._currentLanguageId()) return;\n if (this._hasDictionary(fallbackId)) return;\n void this._loadTranslations(fallbackId, { silent: true, background: true });\n }\n\n private _hasDictionary(languageId: L): boolean {\n return (\n this._translationsCache.has(languageId) ||\n this._config.translations?.[languageId] !== undefined\n );\n }\n\n /**\n * Records a key no dictionary could resolve. Once per key per session; the\n * signal write is deferred to a microtask so `t()` can stay a pure\n * `computed` (Angular forbids signal writes inside a computation).\n */\n private _reportMissingKey(key: string): void {\n // Before the current language has a dictionary, every key would be a false\n // positive — the load is still in flight, or it failed and there is\n // nothing to look a key up in.\n if (!this._hasDictionary(this._currentLanguageId())) return;\n if (this._reportedMissingKeys.has(key)) return;\n this._reportedMissingKeys.add(key);\n\n const language = this._currentLanguageId();\n const fallbackLanguage = this._fallbackId;\n const event: MissingKeyEvent<L> =\n fallbackLanguage === null ? { key, language } : { key, language, fallbackLanguage };\n\n this._pendingMissingKeys.push(key);\n this._queueMissingFlush();\n this._config.onMissingKey?.(event);\n\n if (this._warnOnMissingKey) {\n console.warn(\n `[rivinia/i18n] Missing key \"${key}\" for language \"${language}\"` +\n (fallbackLanguage === null\n ? '.'\n : ` (fallback \"${fallbackLanguage}\" has no value either).`),\n );\n }\n }\n\n private _queueMissingFlush(): void {\n if (this._missingFlushQueued) return;\n this._missingFlushQueued = true;\n queueMicrotask(() => {\n this._missingFlushQueued = false;\n const pending = this._pendingMissingKeys.splice(0);\n if (pending.length === 0) return;\n this._missingKeys.update((current) => [...current, ...pending]);\n });\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean; background?: boolean; force?: boolean },\n ): Promise<{ data: Record<string, unknown>; ok: boolean }> {\n // A dictionary only ever reaches the visible signals when it belongs to\n // the currently intended language. Anything else (slow out-of-order\n // responses, explicit preloads of other languages) stays cached.\n const current = (): boolean => languageId === this._currentLanguageId();\n // Background loads (the fallback dictionary) must never drive\n // `loadingState`/`loadingError`: the visible language is what the UI needs.\n const background = opts?.background === true;\n\n // `force` is the reload path: the cache must not answer it, and a load\n // already in flight for the same language is superseded, not joined.\n if (!opts?.force) {\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(cached);\n }\n if (languageId === this._fallbackId) {\n this._fallbackDict.set(cached);\n }\n return { data: cached, ok: true };\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n }\n\n if (!background) this._loadingState.set('loading');\n\n // Captured before the request: `reload()` bumps it, which makes this\n // response stale even if it arrives later.\n const generation = this._generationOf(languageId);\n\n let task!: Promise<{ data: Record<string, unknown>; ok: boolean }>;\n task = (async () => {\n const stale = (): boolean => this._generationOf(languageId) !== generation;\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._getLoader(this.loaderContext);\n }\n const translations = await this._resolvedLoader.load(languageId, this.loaderContext);\n\n // A superseded response touches nothing: no cache, no transfer state,\n // no signals, no error reporting.\n if (stale()) return { data: {}, ok: false };\n\n this._translationsCache.set(languageId, translations);\n this.writeTransfer(languageId, translations);\n\n if (languageId === this._fallbackId && !current()) {\n this._fallbackDict.set(translations);\n }\n\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return { data: translations, ok: true };\n } catch (error) {\n if (stale()) return { data: {}, ok: false };\n if (!background && current()) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return { data: {}, ok: false };\n } finally {\n // Only the owner of the in-flight slot may clear it (a reload may have\n // replaced this entry with a newer request).\n if (this._inflight.get(languageId) === task) {\n this._inflight.delete(languageId);\n if (\n !background &&\n this._inflight.size === 0 &&\n this._loadingState() === 'loading'\n ) {\n this._loadingState.set('idle');\n }\n }\n }\n })();\n\n this._inflight.set(languageId, task);\n return task;\n }\n\n /**\n * Reads the persisted language. Cookie strategy: server reads the request\n * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.\n * Everything else delegates to the SSR-safe storage helpers.\n */\n private _readStored(): string | null {\n if (this._storageStrategy === 'cookie') {\n const header = this._request?.headers.get('cookie') ?? null;\n if (header !== null) return parseCookie(header, this._storageKey);\n try {\n return parseCookie(this._doc.cookie, this._storageKey);\n } catch {\n return null;\n }\n }\n return safeGetItem(this._storageKey, this._storageStrategy);\n }\n\n /** Persists the language. Server never writes (response cookies are app-owned). */\n private _writeStored(id: L): void {\n if (this._storageStrategy === 'cookie') {\n if (this._request) return;\n try {\n const location = (\n this._doc as unknown as { location?: { protocol?: string; hostname?: string } }\n )?.location;\n this._doc.cookie = serializeCookie(this._storageKey, id, {\n secure: shouldSecureCookie(location),\n });\n } catch {\n // Best-effort persistence.\n }\n return;\n }\n safeSetItem(this._storageKey, id, this._storageStrategy);\n }\n\n private transferKey(languageId: L): StateKey<Record<string, unknown>> {\n return makeStateKey<Record<string, unknown>>(`rivinia.i18n.dict.${languageId}`);\n }\n\n /** Consumes server-rendered dictionaries so the client never refetches. */\n private readTransfer(languageId: L): Record<string, unknown> | null {\n const transfer = this._transfer;\n if (!transfer) return null;\n const key = this.transferKey(languageId);\n if (!transfer.hasKey(key)) return null;\n const dict = transfer.get(key, null);\n transfer.remove(key);\n return dict;\n }\n\n /** Stores freshly loaded dictionaries for hydration (server only). */\n private writeTransfer(languageId: L, dict: Record<string, unknown>): void {\n if (!this._request) return;\n this._transfer?.set(this.transferKey(languageId), dict);\n }\n\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = path\n .split('.')\n .reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object' ? (acc as Record<string, unknown>)[segment] : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n\n private _resolveInitialLanguage(): L {\n const stored = this._readStored();\n if (stored && this._config.languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._config.detectBrowser) {\n const detected = detectBrowserLanguage(\n this._config.languages.map((l) => l.id),\n browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._config.defaultLanguage;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import {\n EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from '../models/i18n-config';\nimport { RiviniaI18n } from '../services/rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n * Also registers an app initializer that loads the initial language before\n * first paint (opt out with `preload: false`).\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: RIVINIA_I18N_CONFIG, useValue: config },\n provideAppInitializer(() => {\n const i18n = inject(RiviniaI18n) as RiviniaI18n<string>;\n return i18n.initialize();\n }),\n ]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */\nexport function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L> {\n return inject(RiviniaI18n) as unknown as RiviniaI18n<L>;\n}\n\n/**\n * Binds a config and its typed accessors together so `L` is inferred once\n * from the configuration instead of being lost at the injection site.\n *\n * @example\n * ```ts\n * export const i18n = defineRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * });\n * // app.config.ts\n * providers: [i18n.provide()]\n * // anywhere (typed 'ar' | 'en'):\n * const lang = i18n.inject();\n * ```\n */\nexport function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {\n readonly config: RiviniaI18nConfig<L>;\n provide: () => EnvironmentProviders;\n inject: () => RiviniaI18n<L>;\n} {\n return {\n config,\n provide: () => provideRiviniaI18n(config),\n inject: () => injectRiviniaI18n<L>(),\n };\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from '../services/rivinia-i18n';\nimport type { TranslateParams } from '../models/i18n-types';\nimport type { Translation } from '../models/i18n-types';\nimport type { RegisteredI18nKey } from '../models/typed-keys';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code — or `t()`, which returns a\n * signal a template can read without re-running the pipe.\n */\n@Pipe({\n name: 'rTranslate',\n pure: false,\n})\nexport class RTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;\n transform(key: RegisteredI18nKey, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: RegisteredI18nKey | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as RegisteredI18nKey,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAkCA,SAAgB,WAAW,SAA2B;CACpD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAQA,SAAgB,WAAW,SAA0B;CACnD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAOA,SAAgB,aAAa,SAA4B;CACvD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,IAAI,aAAa,OAAO;CACjC,EACD;AACH;AAGA,SAAgB,aACd,MAAgF;CAEhF,OAAO,EACL,MAAM,UAAO;EACX,OAAO,EAAE,K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P,QACA,OAAuB;CAEvB,IAAI,UAAU,OAAO,WAAW,UAC9B,OAAO,EAAE,QAAQ,OAAM;CAEzB,OAAO;EAAE,cAAc;EAAQ,QAAQ;CAAK;AAC9C;AC3vBA,SAAgB,mBACd,QAA4B;CAE5B,OAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAqB,UAAU;CAAM,GAChD,4BAA2B;EAEzB,OADa,OAAO,WACb,CAAA,CAAK,WAAU;CACxB,CAAC,CACF,CAAA;AACH;AAGA,SAAgB,oBAAiB;CAC/B,OAAO,OAAO,WAAW;AAC3B;AAqBA,SAAgB,kBAAoC,QAA4B;CAK9E,OAAO;EACL;EACA,eAAe,mBAAmB,MAAM;EACxC,cAAc,kBAAiB;CAChC;AACH;ACrDA,IAAa,iBAAb,MAAa,eAAc;CACR,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAd,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAd,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAc,YAAA,CAAA;EAJ1B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,MAAM;EACP,CAAA"}
|
|
1
|
+
{"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/models/load-error.ts","../../../projects/i18n/src/lib/utils/loader-url.ts","../../../projects/i18n/src/lib/services/json-loader.impl.ts","../../../projects/i18n/src/lib/models/loaders.ts","../../../projects/i18n/src/lib/utils/i18n-utils.ts","../../../projects/i18n/src/lib/utils/cookies.ts","../../../projects/i18n/src/lib/utils/icu.ts","../../../projects/i18n/src/lib/models/i18n-config.ts","../../../projects/i18n/src/lib/utils/loader-context.ts","../../../projects/i18n/src/lib/services/document-direction-applier.ts","../../../projects/i18n/src/lib/services/dictionary-store.ts","../../../projects/i18n/src/lib/services/language-storage.ts","../../../projects/i18n/src/lib/services/missing-key-reporter.ts","../../../projects/i18n/src/lib/services/message-formatter.ts","../../../projects/i18n/src/lib/services/view-transition.service.ts","../../../projects/i18n/src/lib/services/rivinia-i18n.ts","../../../projects/i18n/src/lib/providers/provide-i18n.ts","../../../projects/i18n/src/lib/pipes/rv-translate.pipe.ts"],"sourcesContent":["/**\n * A dictionary request that reached the network and failed.\n *\n * `statusText` is empty on HTTP/2 (measured: Chrome reports an empty string\n * for a 404 over h2), so the message carries the numeric status instead.\n * Passed to `RiviniaI18nConfig.onLoadError`.\n */\nexport class RiviniaLoadError extends Error {\n readonly url: string;\n readonly status: number;\n readonly language: string;\n\n constructor(url: string, status: number, language: string, options?: { cause?: unknown }) {\n super(`[rivinia/i18n] Failed to load '${url}' (HTTP ${status})`, options);\n this.name = 'RiviniaLoadError';\n this.url = url;\n this.status = status;\n this.language = language;\n }\n}\n","import type { LoaderContext } from '../models/loaders';\n\n/**\n * Resolves a loader URL for the current platform.\n *\n * The browser already resolves a relative `fetch()` URL against\n * `document.baseURI`, so the string is passed through untouched (a consumer's\n * `fetch` mock keeps seeing the same URL it always saw). On the server there\n * is no document, so a relative URL is resolved against `context.baseUrl`.\n *\n * Absolute URLs are never rewritten, and a base that cannot be parsed leaves\n * the input unchanged — a loader must not throw while building a URL.\n */\nexport function resolveLoaderUrl(url: string, context?: LoaderContext): string {\n if (!context?.isServer) return url;\n try {\n return new URL(url, context.baseUrl).href;\n } catch {\n return url;\n }\n}\n","import type { LoaderContext, TranslationLoader } from '../models/loaders';\nimport { RiviniaLoadError } from '../models/load-error';\nimport { resolveLoaderUrl } from '../utils/loader-url';\n\nconst DEFAULT_BASE_PATH = 'i18n';\n\nexport class JsonLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options?: { path?: string }) {}\n\n async load(language: L, context?: LoaderContext): Promise<Record<string, unknown>> {\n const basePath = this._options?.path ?? DEFAULT_BASE_PATH;\n const url = resolveLoaderUrl(`${basePath}/${language}.json`, context);\n const response = await fetch(url);\n if (!response.ok) {\n throw new RiviniaLoadError(url, response.status, language);\n }\n return response.json();\n }\n}\n","import { JsonLoader } from '../services/json-loader.impl';\nimport { RiviniaLoadError } from './load-error';\nimport { resolveLoaderUrl } from '../utils/loader-url';\n\nfunction loadError(url: string, status: number, language: string): Error {\n return new RiviniaLoadError(url, status, language);\n}\n\n/**\n * Platform facts a loader needs to build a fetchable URL.\n *\n * `baseUrl` mirrors `document.baseURI`: on the browser it is the document's\n * own base, on the server it is the document's `<base href>` resolved against\n * the incoming request. It always describes a DIRECTORY-like base the way the\n * browser sees it (a `<base href=\"/app/\">` keeps its trailing slash; a\n * `<base href=\"/app\">` does not, exactly as in the browser).\n */\nexport interface LoaderContext {\n /** Absolute base URL for relative dictionary paths. */\n readonly baseUrl: string;\n /** `true` when the application renders on the server (SSR / prerender). */\n readonly isServer: boolean;\n}\n\n/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L, context?: LoaderContext): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service. `context` lets a descriptor pick a\n * platform-specific implementation (e.g. filesystem on the server).\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(context?: LoaderContext): Promise<TranslationLoader<L>>;\n}\n\n/**\n * The conventional `i18n/{language}.json` loader, and the service's default.\n * Deliberately NOT code-split: it runs in the app initializer, so a lazy chunk\n * would add two script round-trips (loader + its URL helper) before the first\n * dictionary fetch. `httpLoader`/`remoteLoader` stay lazy — they are opt-in.\n */\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('../services/http-loader.impl');\n // The runtime helpers travel as arguments so the lazy chunk imports no\n // module the main bundle already has; a shared import would make the\n // bundler emit an extra initial chunk.\n return new HttpLoader(options, resolveLoaderUrl, loadError);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('../services/remote-loader.impl');\n return new RemoteLoader(options, resolveLoaderUrl, loadError);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L, context?: LoaderContext) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from '../models/i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n // NOTE: 'cookie' resolves to null on purpose — cookies need request/document\n // context, so the service handles that strategy itself (server REQUEST\n // header, browser document.cookie). See RiviniaI18n storage methods.\n if (strategy === 'none' || strategy === 'cookie') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids, in order.\n * For each browser entry (highest preference first) tries the exact tag, then\n * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n * @internal May move to an `@rivinia/i18n/internal` entry point before 1.0.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n const base = tag.split(/[-_]/)[0];\n if (base && base !== tag) {\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n }\n return null;\n}\n\n/**\n * Browser language list, `undefined` off-browser (SSR-safe input for detection).\n * @internal May move to an `@rivinia/i18n/internal` entry point before 1.0.\n */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:\n * the service supplies the header (server `REQUEST`) or `document.cookie`\n * (browser); these functions only parse and serialize.\n */\n\n/**\n * Extracts a cookie value by name from a `Cookie` header or `document.cookie`.\n * @internal Exported for the package's own SSR tests; may move to an\n * `@rivinia/i18n/internal` entry point before 1.0.\n */\nexport function parseCookie(header: string | null | undefined, name: string): string | null {\n if (!header) return null;\n const prefix = `${name}=`;\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n try {\n return decodeURIComponent(trimmed.slice(prefix.length));\n } catch {\n return trimmed.slice(prefix.length);\n }\n }\n }\n return null;\n}\n\n/**\n * Serializes a language cookie (Lax, root path, one year).\n * @internal Exported for the package's own SSR tests; may move to an\n * `@rivinia/i18n/internal` entry point before 1.0.\n */\nexport function serializeCookie(\n name: string,\n value: string,\n options?: { secure?: boolean },\n): string {\n const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;\n return options?.secure ? `${base}; Secure` : base;\n}\n\n/**\n * Decides whether the language cookie gets `Secure`: only on `https:`, never\n * on `localhost` (dev TLS included — `Secure` there buys nothing and risks\n * silent persistence loss). Pure and SSR-safe: unknown locations → `false`.\n * The server never writes cookies regardless (app-owned responses).\n */\nexport function shouldSecureCookie(\n location: { protocol?: string; hostname?: string } | null | undefined,\n): boolean {\n try {\n if (!location) return false;\n if (location.protocol !== 'https:') return false;\n if (location.hostname === 'localhost') return false;\n return true;\n } catch {\n return false;\n }\n}\n","import type { TranslateParams } from '../models/i18n-types';\n\n/**\n * Tolerant hooks for one render. `onMissingParam` fires for each named\n * argument that the message needs but `params` does not provide; the\n * placeholder is still rendered unchanged.\n */\nexport interface IcuFormatOptions {\n readonly onMissingParam?: (name: string) => void;\n}\n\n/**\n * Minimal ICU MessageFormat (MF1) subset: `{name}` interpolation,\n * `{n, plural, …}` (with `offset:`), `{n, selectordinal, …}`, `{x, select, …}`,\n * `#` inside plural-style arguments, `{n, number[, style]}`, `{d, date[, style]}`,\n * nesting, and ICU apostrophe quoting.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{count, plural, offset:1 =0 {none} one {you and # other} other {you and # others}}`\n * - `{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{amount, number}`, `{ratio, number, percent}`, `{count, number, integer}`,\n * `{price, number, ::currency/USD}`\n * - `{day, date}`, `{day, date, short|medium|long|full}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n * - `''` → one apostrophe; `'{'…'}'` quotes a literal brace\n *\n * Offset semantics follow ICU (ICU4J `PluralFormat`): an explicit `=N` matches\n * the RAW argument value, the plural category is selected with\n * `value - offset`, and `#` renders `value - offset` in the locale's digits.\n *\n * Templates are compiled once into an AST and cached (bounded LRU), so a\n * template rendered on every change-detection pass is not re-parsed.\n *\n * Unsupported or malformed constructs never throw: the raw `{…}` segment is\n * returned as-is and parsing continues after it.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n options?: IcuFormatOptions,\n): string {\n return renderMessage(compile(template), params, locale, options);\n}\n\n// ---------------------------------------------------------------------------\n// AST\n// ---------------------------------------------------------------------------\n\ntype Node =\n | { readonly type: 'text'; readonly value: string }\n | { readonly type: 'param'; readonly name: string; readonly raw: string }\n | { readonly type: 'hash' }\n | {\n readonly type: 'number' | 'date';\n readonly name: string;\n readonly style: string | undefined;\n readonly raw: string;\n }\n | {\n readonly type: 'plural';\n readonly name: string;\n readonly ordinal: boolean;\n readonly offset: number;\n readonly branches: ReadonlyMap<string, readonly Node[]>;\n /** `=N` selectors pre-parsed once, so a render allocates no key string. */\n readonly exacts: ReadonlyMap<number, readonly Node[]>;\n }\n | {\n readonly type: 'select';\n readonly name: string;\n readonly branches: ReadonlyMap<string, readonly Node[]>;\n }\n | { readonly type: 'raw'; readonly value: string };\n\ninterface Compiled {\n readonly nodes: readonly Node[];\n}\n\n/** 500 templates covers any realistic app; a long-lived tab stays bounded. */\nconst COMPILE_LIMIT = 500;\nconst compiled = new Map<string, Compiled>();\n\nfunction compile(template: string): Compiled {\n // No LRU refresh on a hit: the two extra Map writes per render cost more\n // than the marginal eviction accuracy of a FIFO bound buys.\n const hit = compiled.get(template);\n if (hit !== undefined) return hit;\n const parsed = parseNodes(template, 0, template.length, false);\n const message: Compiled = { nodes: parsed.nodes };\n if (compiled.size >= COMPILE_LIMIT) {\n const oldest = compiled.keys().next();\n if (!oldest.done) compiled.delete(oldest.value);\n }\n compiled.set(template, message);\n return message;\n}\n\n// ---------------------------------------------------------------------------\n// Parser\n// ---------------------------------------------------------------------------\n\ninterface ParsedNodes {\n readonly nodes: readonly Node[];\n /** Index of the closing `}` (or `end` when the level ran out). */\n readonly next: number;\n readonly closed: boolean;\n}\n\ntype ArgumentResult =\n | { readonly node: Node; readonly next: number; readonly rest?: false }\n /** Malformed construct: the rest of this level is literal text. */\n | { readonly node?: never; readonly next: number; readonly rest: true };\n\nfunction parseNodes(src: string, start: number, end: number, inPlural: boolean): ParsedNodes {\n const nodes: Node[] = [];\n let buffer = '';\n const flush = (): void => {\n if (buffer !== '') {\n nodes.push({ type: 'text', value: buffer });\n buffer = '';\n }\n };\n\n let i = start;\n while (i < end) {\n const ch = src.charCodeAt(i);\n if (ch === 123 /* { */) {\n flush();\n const arg = parseArgument(src, i, end, inPlural);\n if (arg.rest) {\n nodes.push({ type: 'text', value: src.slice(i, end) });\n return { nodes, next: end, closed: false };\n }\n nodes.push(arg.node);\n i = arg.next;\n continue;\n }\n if (ch === 125 /* } */) {\n flush();\n return { nodes, next: i, closed: true };\n }\n if (ch === 35 /* # */ && inPlural) {\n flush();\n nodes.push({ type: 'hash' });\n i++;\n continue;\n }\n if (ch === 39 /* ' */) {\n const after = i + 1 < end ? src.charCodeAt(i + 1) : -1;\n if (after === 39) {\n buffer += \"'\";\n i += 2;\n continue;\n }\n if (after === 123 || after === 125 || (inPlural && after === 35)) {\n // Quoted literal: `'{'` … `'}'`; an unterminated quote runs to the end.\n let j = i + 1;\n while (j < end && src.charCodeAt(j) !== 39) j++;\n buffer += src.slice(i + 1, j);\n i = j < end ? j + 1 : end;\n continue;\n }\n buffer += \"'\";\n i++;\n continue;\n }\n buffer += src[i];\n i++;\n }\n flush();\n return { nodes, next: i, closed: false };\n}\n\nfunction parseArgument(src: string, start: number, end: number, inPlural: boolean): ArgumentResult {\n const rest = (): ArgumentResult => ({ rest: true, next: end });\n\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return rest();\n if (src.charCodeAt(i) === 125 /* } */) {\n return {\n node: { type: 'param', name: name.word, raw: src.slice(start, i + 1) },\n next: i + 1,\n };\n }\n if (src.charCodeAt(i) !== 44 /* , */ || name.word === '') return rest();\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n\n if (type.word === 'number' || type.word === 'date') {\n return parseTyped(src, start, i, end, type.word, name.word);\n }\n\n if (i >= end || src.charCodeAt(i) !== 44 /* , */) return rest();\n if (type.word !== 'plural' && type.word !== 'selectordinal' && type.word !== 'select') {\n return rawNode(src, start, end);\n }\n\n const branchPlural = type.word !== 'select';\n i++;\n const branches = new Map<string, readonly Node[]>();\n const exacts = new Map<number, readonly Node[]>();\n let offset = 0;\n i = skipSpaces(src, i, end);\n let closed = false;\n\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src.charCodeAt(i) === 125 /* } */) {\n closed = true;\n break;\n }\n if (branchPlural) {\n const offsetClause = readOffset(src, i, end);\n if (offsetClause) {\n offset = offsetClause.value;\n i = offsetClause.next;\n continue;\n }\n }\n const selector = readSelector(src, i, end);\n if (selector.selector === null) return rawNode(src, start, end);\n i = skipSpaces(src, selector.next, end);\n if (i >= end || src.charCodeAt(i) !== 123 /* { */) {\n return rawNode(src, start, end);\n }\n // A plural body binds `#` to its own number; a select inherits the\n // nearest enclosing plural (or none, where `#` stays literal).\n const body = parseNodes(src, i + 1, end, branchPlural || inPlural);\n branches.set(selector.selector, body.nodes);\n if (selector.selector.charCodeAt(0) === 61 /* = */) {\n const exact = Number(selector.selector.slice(1));\n if (Number.isFinite(exact)) exacts.set(exact, body.nodes);\n }\n i = body.next + 1;\n }\n if (!closed) return rest();\n\n if (type.word === 'select') {\n return { node: { type: 'select', name: name.word, branches }, next: i + 1 };\n }\n return {\n node: {\n type: 'plural',\n name: name.word,\n ordinal: type.word === 'selectordinal',\n offset,\n branches,\n exacts,\n },\n next: i + 1,\n };\n}\n\n/**\n * `{n, number[, style]}` and `{d, date[, style]}`. Unsupported shapes become a\n * raw balanced segment, exactly like the previous parser.\n */\nfunction parseTyped(\n src: string,\n start: number,\n i: number,\n end: number,\n kind: 'number' | 'date',\n name: string,\n): ArgumentResult {\n let style: string | undefined;\n let raw: string;\n if (i < end && src.charCodeAt(i) === 125 /* } */) {\n style = undefined;\n raw = src.slice(start, i + 1);\n return { node: { type: kind, name, style, raw }, next: i + 1 };\n }\n if (i >= end || src.charCodeAt(i) !== 44 /* , */) return rawNode(src, start, end);\n const word = readWord(src, i + 1, end);\n const after = skipSpaces(src, word.next, end);\n if (after >= end || src.charCodeAt(after) !== 125 /* } */) {\n return rawNode(src, start, end);\n }\n style = word.word;\n raw = src.slice(start, after + 1);\n return { node: { type: kind, name, style, raw }, next: after + 1 };\n}\n\nfunction rawNode(src: string, start: number, end: number): ArgumentResult {\n const segment = rawSegment(src, start, end);\n return { node: { type: 'raw', value: segment.text }, next: segment.next };\n}\n\n/**\n * Reads `offset:<number>`. Only plural-style arguments accept it (ICU grammar:\n * before the selectors).\n */\nfunction readOffset(\n src: string,\n i: number,\n end: number,\n): { value: number; next: number } | null {\n const start = skipSpaces(src, i, end);\n if (src.startsWith('offset:', start)) {\n let j = start + 'offset:'.length;\n const digits = j;\n while (j < end && isDigit(src.charCodeAt(j))) j++;\n if (j === digits) return null;\n const value = Number(src.slice(digits, j));\n if (!Number.isFinite(value)) return null;\n return { value, next: j };\n }\n return null;\n}\n\nfunction isSpace(ch: number): boolean {\n return ch === 32 || (ch >= 9 && ch <= 13) || ch === 0x00a0;\n}\n\nfunction isDigit(ch: number): boolean {\n return ch >= 48 && ch <= 57;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && isSpace(src.charCodeAt(i))) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n // `{` starts the branch body: `one{# item}` must read the selector as `one`,\n // not `one{# item`. Whitespace, `,`, `{` and `}` end a word.\n while (j < end) {\n const ch = src.charCodeAt(j);\n if (isSpace(ch) || ch === 44 || ch === 123 || ch === 125) break;\n j++;\n }\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src.charCodeAt(i) === 61 /* = */) {\n let j = i + 1;\n if (j < end && src.charCodeAt(j) === 45 /* - */) j++;\n const digits = j;\n while (j < end && isDigit(src.charCodeAt(j))) j++;\n if (j < end && src.charCodeAt(j) === 46 /* . */ && j + 1 < end && isDigit(src.charCodeAt(j + 1))) {\n j++;\n while (j < end && isDigit(src.charCodeAt(j))) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n\n/** The raw `{…}` segment (balanced braces), so parsing can continue after it. */\nfunction rawSegment(src: string, start: number, end: number): { text: string; next: number } {\n let depth = 0;\n let i = start;\n while (i < end) {\n const ch = src.charCodeAt(i);\n if (ch === 123 /* { */) depth++;\n else if (ch === 125 /* } */) {\n depth--;\n if (depth === 0) return { text: src.slice(start, i + 1), next: i + 1 };\n }\n i++;\n }\n return { text: src.slice(start, end), next: end };\n}\n\n// ---------------------------------------------------------------------------\n// Renderer\n// ---------------------------------------------------------------------------\n\ninterface RenderContext {\n readonly params: TranslateParams;\n readonly locale: string;\n /** The nearest plural-style argument, for `#`. Swapped on the stack. */\n plural: { readonly value: number; readonly offset: number } | null;\n readonly options: IcuFormatOptions | undefined;\n}\n\nfunction renderMessage(\n message: Compiled,\n params: TranslateParams,\n locale: string,\n options: IcuFormatOptions | undefined,\n): string {\n return renderNodes(message.nodes, { params, locale, plural: null, options });\n}\n\nfunction renderNodes(nodes: readonly Node[], ctx: RenderContext): string {\n let out = '';\n for (const node of nodes) {\n switch (node.type) {\n case 'text':\n out += node.value;\n break;\n case 'raw':\n out += node.value;\n break;\n case 'hash':\n out +=\n ctx.plural === null\n ? '#'\n : (formatNumberValue(ctx.plural.value - ctx.plural.offset, ctx.locale, undefined) ??\n '#');\n break;\n case 'param': {\n const value = ctx.params[node.name];\n if (value === undefined || value === null || node.name === '') {\n if (node.name !== '') ctx.options?.onMissingParam?.(node.name);\n out += node.raw;\n } else {\n out += String(value);\n }\n break;\n }\n case 'number': {\n const value = ctx.params[node.name];\n reportMissing(ctx, node.name, value);\n out += formatNumberValue(value, ctx.locale, node.style) ?? node.raw;\n break;\n }\n case 'date': {\n const value = ctx.params[node.name];\n reportMissing(ctx, node.name, value);\n out += formatDateValue(value, ctx.locale, node.style) ?? node.raw;\n break;\n }\n case 'plural': {\n const value = ctx.params[node.name];\n const numeric = toFiniteNumber(value);\n reportMissing(ctx, node.name, value);\n let branch: readonly Node[] | undefined;\n if (numeric !== null) {\n branch = node.exacts.get(numeric);\n if (branch === undefined) {\n branch = node.branches.get(selectCategory(numeric - node.offset, node.ordinal, ctx.locale));\n }\n if (branch === undefined) branch = node.branches.get('other');\n } else {\n branch = node.branches.get('other');\n }\n if (branch !== undefined) {\n const saved = ctx.plural;\n ctx.plural = numeric !== null ? { value: numeric, offset: node.offset } : saved;\n out += renderNodes(branch, ctx);\n ctx.plural = saved;\n }\n break;\n }\n case 'select': {\n const value = ctx.params[node.name];\n reportMissing(ctx, node.name, value);\n const key = value === undefined || value === null ? '' : String(value);\n const branch = node.branches.get(key) ?? node.branches.get('other');\n if (branch) out += renderNodes(branch, ctx);\n break;\n }\n }\n }\n return out;\n}\n\nfunction reportMissing(ctx: RenderContext, name: string, value: unknown): void {\n if (value === undefined || value === null) ctx.options?.onMissingParam?.(name);\n}\n\nfunction selectCategory(value: number, ordinal: boolean, locale: string): string {\n const key = `${ordinal ? 1 : 0}|${locale}|${value}`;\n const hit = pluralCategories.get(key);\n if (hit !== undefined) return hit;\n let category: string;\n try {\n category = pluralRules(locale, ordinal).select(value);\n } catch {\n category = 'other';\n }\n if (pluralCategories.size >= CACHE_LIMIT) pluralCategories.clear();\n pluralCategories.set(key, category);\n return category;\n}\n\nfunction toFiniteNumber(value: string | number | boolean | Date | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Intl caching\n// ---------------------------------------------------------------------------\n\nconst CACHE_LIMIT = 40;\nconst numberFormats = new Map<string, Intl.NumberFormat>();\nconst dateFormats = new Map<string, Intl.DateTimeFormat>();\nconst pluralRulesByLocale = new Map<string, Intl.PluralRules>();\n/** `Intl.PluralRules.select` is the hottest call; counts repeat constantly. */\nconst pluralCategories = new Map<string, string>();\n/** `Intl.NumberFormat.format` is not free; `#` re-renders the same counts. */\nconst formattedNumbers = new Map<string, string>();\nconst FORMATTED_NUMBERS_LIMIT = 1000;\n\nfunction memo<T>(map: Map<string, T>, key: string, create: () => T): T {\n const hit = map.get(key);\n if (hit !== undefined) return hit;\n const created = create();\n if (map.size >= CACHE_LIMIT) map.clear();\n map.set(key, created);\n return created;\n}\n\nfunction pluralRules(locale: string, ordinal: boolean): Intl.PluralRules {\n const key = `${ordinal ? 'o' : 'c'}|${locale}`;\n return memo(pluralRulesByLocale, key, () =>\n new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined),\n );\n}\n\nfunction formatNumberValue(\n value: unknown,\n locale: string,\n style: string | undefined,\n): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n let key: string;\n let options: Intl.NumberFormatOptions;\n if (style === undefined) {\n // `#` inside a plural takes this path on every render: keep it allocation-free.\n key = `${locale}|`;\n options = {};\n } else {\n const resolved = numberOptions(style);\n if (resolved === null) return null;\n key = `${locale}|${style}`;\n options = resolved;\n }\n const cacheKey = `${key}${value}`;\n const cached = formattedNumbers.get(cacheKey);\n if (cached !== undefined) return cached;\n try {\n const text = memo(numberFormats, key, () => new Intl.NumberFormat(locale, options)).format(value);\n if (formattedNumbers.size >= FORMATTED_NUMBERS_LIMIT) formattedNumbers.clear();\n formattedNumbers.set(cacheKey, text);\n return text;\n } catch {\n return null;\n }\n}\n\nfunction numberOptions(style: string | undefined): Intl.NumberFormatOptions | null {\n if (style === undefined) return {};\n if (style === 'percent') return { style: 'percent' };\n if (style === 'integer') return { maximumFractionDigits: 0 };\n if (style.startsWith('::currency/')) {\n const code = style.slice('::currency/'.length);\n if (/^[A-Za-z]{3}$/.test(code)) {\n return { style: 'currency', currency: code.toUpperCase() };\n }\n }\n return null;\n}\n\nconst DATE_STYLES = new Set(['short', 'medium', 'long', 'full']);\n/** ISO-8601 calendar date or date-time (requires a `T`/space between them). */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})?$/;\n\nfunction formatDateValue(\n value: unknown,\n locale: string,\n style: string | undefined,\n): string | null {\n const date = toDate(value);\n if (date === null) return null;\n if (style !== undefined && !DATE_STYLES.has(style)) return null;\n const options: Intl.DateTimeFormatOptions =\n style === undefined ? {} : { dateStyle: style as 'short' | 'medium' | 'long' | 'full' };\n try {\n const key = `${locale}|${style ?? ''}`;\n return memo(dateFormats, key, () => new Intl.DateTimeFormat(locale, options)).format(date);\n } catch {\n return null;\n }\n}\n\n/**\n * A `Date` (any realm), epoch milliseconds, or a strict ISO-8601 string.\n * Date-only strings are read as a local calendar date, so `2026-10-28` never\n * renders as the 27th in a negative UTC offset.\n */\nfunction toDate(value: unknown): Date | null {\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n if (typeof value === 'string') {\n if (ISO_DATE.test(value)) {\n const [year, month, day] = value.split('-').map(Number);\n const date = new Date(year, month - 1, day);\n return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day\n ? date\n : null;\n }\n if (ISO_DATE_TIME.test(value)) {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n }\n if (Object.prototype.toString.call(value) === '[object Date]') {\n const date = value as Date;\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n\n","import { InjectionToken } from '@angular/core';\nimport type { Language, StorageStrategy, SwitchStrategy, ViewTransitionConfig } from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\nimport type { MissingKeyEvent, MissingParamEvent } from './missing-key';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n /**\n * Language used when a key is absent from the current dictionary. Must be\n * one of `languages`. The fallback dictionary is loaded silently (it never\n * drives `loadingState`), and its messages are rendered with the fallback\n * language's locale — an English plural template keeps English plural rules.\n */\n readonly fallbackLanguage?: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `i18n/{language}.json` layout (files in `public/i18n/`, served from the\n * site root). Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Called when `translate()` cannot resolve a key (absent from the current\n * dictionary, from the fallback dictionary, and with no `defaultValue`).\n * Fires once per key per session. When set, the default console warning is\n * suppressed.\n */\n readonly onMissingKey?: (event: MissingKeyEvent<T>) => void;\n /**\n * Log a `console.warn` (once per key) for unresolved keys.\n * @default isDevMode() && !onMissingKey\n */\n readonly warnOnMissingKey?: boolean;\n /**\n * Called once per (key, param) pair when a message needs a named argument\n * that `params` does not provide. The placeholder is still rendered\n * unchanged. Delivered from a microtask, like `onMissingKey`.\n */\n readonly onMissingParam?: (event: MissingParamEvent<T>) => void;\n /**\n * Log a `console.warn` (once per key/param pair) for missing arguments.\n * @default isDevMode() && !onMissingParam\n */\n readonly warnOnMissingParam?: boolean;\n /**\n * Persist the language to storage/cookie after a user-initiated switch\n * (`setLanguage`, `toggle`, `next`, `previous`, `setLanguageAsync`). The\n * initial language is never written, so a cookie is only set once the user\n * actually chooses a language.\n * @default true\n */\n readonly persist?: boolean;\n /**\n * Load the initial language during provider setup (before first paint).\n * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps\n * that call `loadTranslations` themselves).\n * @default true\n */\n readonly preload?: boolean;\n /**\n * Inline per-language dictionaries. Seeded before any network load (zero\n * network + SSR-safe first paint); a successful loader response still wins.\n */\n readonly translations?: Partial<Record<T, Record<string, unknown>>>;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>('RIVINIA_I18N_CONFIG');\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import type { LoaderContext } from '../models/loaders';\n\n/**\n * Builds the loader context ONCE per application.\n *\n * Browser: `document.baseURI` — the exact base the browser uses for relative\n * `fetch()` URLs.\n *\n * Server: the document's `<base href>` resolved against the incoming request\n * URL, mirroring `document.baseURI` semantics (a relative `<base href=\"./\">`\n * resolves against the request path, not the origin). Without a `<base>`\n * element the origin is used, because the conventional layout serves\n * `public/` at the site root.\n *\n * Never throws: an unparsable request URL or base falls back to the\n * document's own base URI.\n */\nexport function createLoaderContext(request: Request | null, doc: Document): LoaderContext {\n const documentBase = readBaseUri(doc);\n if (!request) {\n return { baseUrl: documentBase, isServer: false };\n }\n\n const requestUrl = parseUrl(request.url);\n const baseHref = readBaseHref(doc);\n\n if (baseHref) {\n const resolved = resolveUrl(baseHref, requestUrl?.href ?? documentBase);\n if (resolved) return { baseUrl: resolved, isServer: true };\n }\n if (requestUrl) {\n return { baseUrl: `${requestUrl.origin}/`, isServer: true };\n }\n return { baseUrl: documentBase, isServer: true };\n}\n\nfunction readBaseUri(doc: Document): string {\n // Domino (the SSR DOM) does not implement `baseURI` and THROWS\n // `NotYetImplemented` on the property read rather than returning\n // `undefined`. Reading it unguarded made constructing the service throw\n // during server rendering, which killed the whole SSR bootstrap — jsdom\n // implements `baseURI`, so no browser-environment test could see it\n // (measured 2026-10-28, projects/i18n-e2e).\n try {\n const uri = (doc as { baseURI?: string } | null)?.baseURI;\n if (typeof uri === 'string' && uri.length > 0) return uri;\n } catch {\n // No usable base URI on this platform; the request/base-href path wins.\n }\n return '/';\n}\n\nfunction readBaseHref(doc: Document): string | null {\n try {\n const element = doc.querySelector?.('base[href]');\n const href = element?.getAttribute('href')?.trim();\n return href ? href : null;\n } catch {\n return null;\n }\n}\n\nfunction parseUrl(value: string | undefined): URL | null {\n if (!value) return null;\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction resolveUrl(value: string, base: string): string | null {\n try {\n return new URL(value, base).href;\n } catch {\n return null;\n }\n}\n","import { effect } from '@angular/core';\nimport type { Language, ViewTransitionConfig, ViewTransitionInfo } from '../models/i18n-types';\nimport type { ViewTransitionService } from './view-transition.service';\n\nexport interface DocumentDirectionApplierDeps {\n readonly document: Document;\n readonly viewTransition: ViewTransitionService | null;\n readonly config: ViewTransitionConfig | undefined;\n}\n\n/**\n * Keeps `<html dir/lang>` in step with the language and optionally wraps the\n * switch in a view transition. The document is the injected one, so this runs\n * on the server too (RIV-11: `locale ?? id`, ids are not valid tags).\n */\nexport class DocumentDirectionApplier<L extends string = string> {\n private _applyCount = 0;\n\n constructor(private readonly _deps: DocumentDirectionApplierDeps) {}\n\n /** Must be called from an injection context (the facade's constructor). */\n install(language: () => Language<L>): void {\n effect(() => this.applyDirection(language()));\n }\n\n applyDirection(language: Language<L>): void {\n const root = this._deps.document.documentElement;\n if (!root) return;\n root.dir = language.dir;\n root.lang = language.locale ?? language.id;\n }\n\n /** The transition is skipped until the second switch when asked to. */\n apply(language: Language<L>, callback: () => void): void {\n const config = this._deps.config;\n const service = this._deps.viewTransition;\n this._applyCount++;\n const useTransition =\n config?.enabled && (!config.skipInitialTransition || this._applyCount > 1) && service != null;\n\n if (!useTransition) {\n callback();\n return;\n }\n const info: ViewTransitionInfo = { language: language.id, direction: language.dir };\n config.onViewTransitionCreated?.(info);\n service.run(callback);\n }\n}\n","import {\n signal,\n makeStateKey,\n type Signal,\n type StateKey,\n type TransferState,\n} from '@angular/core';\nimport type { LoaderContext, TranslationLoader } from '../models/loaders';\n\nexport interface DictionaryStoreDeps<L extends string> {\n /** Resolves the configured loader, or the conventional JSON one. */\n readonly loader: (context: LoaderContext) => Promise<TranslationLoader<L>>;\n readonly loaderContext: LoaderContext;\n /** Present only on the server: transfer state is written there alone. */\n readonly request: { readonly headers: { get(name: string): string | null } } | null;\n readonly transfer: TransferState | null;\n readonly onLoadError?: (languageId: L, error: unknown) => void;\n /** The intended language right now; decides where a response lands. */\n readonly currentLanguage: () => L;\n readonly fallbackLanguage: L | null;\n readonly languageIds: () => readonly L[];\n /** A dictionary supplied inline in the config counts as present. */\n readonly hasInline: (languageId: L) => boolean;\n}\n\ninterface LoadResult {\n data: Record<string, unknown>;\n ok: boolean;\n error?: unknown;\n}\n\n/**\n * Owns every dictionary: the cache, the shared in-flight request, reload\n * generations, TransferState, the loading counter, and the visible and\n * fallback slots. RIV-02 lives here: one fetch serves every caller, and each\n * caller decides whether to APPLY after the await, against current state.\n */\nexport class DictionaryStore<L extends string> {\n private readonly _visible = signal<Record<string, unknown>>({});\n /**\n * The fallback dictionary, kept separate from `_visible` (which always\n * mirrors the VISIBLE language). A signal so `t()`'s computed re-evaluates\n * when the fallback arrives.\n */\n private readonly _fallbackDict = signal<Record<string, unknown> | null>(null);\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n private readonly _cache = new Map<L, Record<string, unknown>>();\n /**\n * Per-language generation, bumped by `reload()`. A load captures the\n * generation before its request and discards the response when it moved:\n * a stale dictionary can never reach the cache or the signals.\n */\n private readonly _generations = new Map<L, number>();\n private readonly _inflight = new Map<L, Promise<LoadResult>>();\n /** Non-background loads in flight; `loadingState` follows this count. */\n private _loadingCount = 0;\n private _resolvedLoader: TranslationLoader<L> | null = null;\n\n readonly visible: Signal<Record<string, unknown>> = this._visible.asReadonly();\n readonly fallback: Signal<Record<string, unknown> | null> = this._fallbackDict.asReadonly();\n readonly loadingState: Signal<'idle' | 'loading' | 'error'> = this._loadingState.asReadonly();\n readonly loadingError: Signal<unknown> = this._loadingError.asReadonly();\n\n constructor(private readonly _deps: DictionaryStoreDeps<L>) {}\n\n has(languageId: L): boolean {\n return this._cache.has(languageId) || this._deps.hasInline(languageId);\n }\n\n /** Marks the language visible without caching (the inline seed). */\n seedVisible(data: Record<string, unknown>): void {\n this._visible.set(data);\n }\n\n /** A transferred dictionary: it belongs in the cache and in its slot. */\n adoptTransferred(languageId: L, data: Record<string, unknown>): void {\n this._cache.set(languageId, data);\n this._apply(languageId, data);\n }\n\n consumeTransfer(languageId: L): Record<string, unknown> | null {\n const transfer = this._deps.transfer;\n if (!transfer) return null;\n const key = this._transferKey(languageId);\n if (!transfer.hasKey(key)) return null;\n const dict = transfer.get(key, null);\n transfer.remove(key);\n return dict;\n }\n\n async load(\n languageId: L,\n opts?: { background?: boolean; force?: boolean },\n ): Promise<{ data: Record<string, unknown>; ok: boolean }> {\n // Background loads (the fallback dictionary) must never drive\n // `loadingState`/`loadingError`: the visible language is what the UI needs.\n const background = opts?.background === true;\n\n // `force` is the reload path: the cache must not answer it, and a load\n // already in flight for the same language is superseded, not joined.\n if (!opts?.force) {\n const cached = this._cache.get(languageId);\n if (cached) {\n this._apply(languageId, cached);\n return { data: cached, ok: true };\n }\n }\n\n // One FETCH is shared by every caller; the decision to APPLY is made by\n // each caller after the await, against the state at resolution time. A\n // caller must never inherit another caller's `background` flag\n // (RIV-02: a background fallback load joined by an explicit switch).\n let task = opts?.force ? undefined : this._inflight.get(languageId);\n if (!task) {\n // Captured before the request: `reload()` bumps it, which makes this\n // response stale even if it arrives later.\n task = this._fetch(languageId, this._generationOf(languageId));\n this._inflight.set(languageId, task);\n }\n\n if (!background) {\n this._loadingCount++;\n this._loadingState.set('loading');\n }\n\n try {\n const result = await task;\n if (result.ok) {\n this._apply(languageId, result.data);\n } else if (\n !background &&\n result.error !== undefined &&\n languageId === this._deps.currentLanguage()\n ) {\n this._loadingError.set(result.error);\n this._loadingState.set('error');\n }\n return { data: result.data, ok: result.ok };\n } finally {\n if (!background) {\n this._loadingCount = Math.max(0, this._loadingCount - 1);\n if (this._loadingCount === 0 && this._loadingState() === 'loading') {\n this._loadingState.set('idle');\n }\n }\n }\n }\n\n /**\n * Invalidates cached dictionaries and reloads them from the loader.\n *\n * - `reload()` — refreshes the current language (and the fallback, when\n * configured) and drops every OTHER cached dictionary, so the next switch\n * refetches. Resolves `true` when the current language loaded.\n * - `reload(lang)` — refreshes one language. If it is the current one it is\n * applied; otherwise it is only re-cached (and refreshed in the fallback\n * slot when it is the fallback).\n *\n * The visible dictionary stays on screen until the fresh one arrives\n * (stale-while-revalidate), so a reload never flashes raw keys.\n */\n reload(languageId?: L): Promise<boolean> {\n if (languageId !== undefined) {\n if (!this._deps.languageIds().includes(languageId)) {\n return Promise.resolve(false);\n }\n this._invalidate(languageId);\n return this._reloadOne(languageId);\n }\n\n const currentId = this._deps.currentLanguage();\n const fallbackId = this._deps.fallbackLanguage;\n\n for (const cachedId of [...this._cache.keys()]) {\n if (cachedId !== currentId && cachedId !== fallbackId) {\n this._cache.delete(cachedId);\n }\n }\n // Every language is superseded, so any response already in flight for a\n // dictionary this reload does not refetch is dropped instead of cached.\n for (const language of this._deps.languageIds()) {\n this._invalidate(language);\n }\n\n const currentLoad = this._reloadOne(currentId);\n if (fallbackId !== null && fallbackId !== currentId) {\n void this._reloadOne(fallbackId);\n }\n return currentLoad;\n }\n\n /** Loads the fallback in the background when it is not cached yet. */\n ensureFallback(): void {\n const fallbackId = this._deps.fallbackLanguage;\n if (fallbackId === null || fallbackId === this._deps.currentLanguage()) return;\n if (this.has(fallbackId)) return;\n void this.load(fallbackId, { background: true });\n }\n\n private _reloadOne(languageId: L): Promise<boolean> {\n return this.load(languageId, {\n force: true,\n // A dictionary that is not on screen must not drive loadingState.\n background: languageId !== this._deps.currentLanguage(),\n }).then((result) => result.ok);\n }\n\n /**\n * A dictionary reaches the visible signals only when its language is\n * current at resolution time; a fallback dictionary fills the fallback slot.\n * Everything else stays cached for the next switch.\n */\n private _apply(languageId: L, data: Record<string, unknown>): void {\n if (languageId === this._deps.currentLanguage()) {\n this._visible.set(data);\n this._loadingError.set(null);\n // A cached dictionary answers without a load, so the `finally` that\n // normally clears `loading` never runs. Without this, switching away\n // from a failed language to a cached one leaves loadingState 'error'\n // even though the UI is fully translated.\n if (this._loadingCount === 0 && this._loadingState() === 'error') {\n this._loadingState.set('idle');\n }\n }\n if (languageId === this._deps.fallbackLanguage) {\n this._fallbackDict.set(data);\n }\n }\n\n /** Fetch + cache + transfer. Shared by every caller; never applies. */\n private _fetch(languageId: L, generation: number): Promise<LoadResult> {\n let task!: Promise<LoadResult>;\n task = (async () => {\n const stale = (): boolean => this._generationOf(languageId) !== generation;\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._deps.loader(this._deps.loaderContext);\n }\n const translations = await this._resolvedLoader.load(languageId, this._deps.loaderContext);\n\n // A superseded response touches nothing: no cache, no transfer state,\n // no signals, no error reporting.\n if (stale()) return { data: {}, ok: false };\n\n this._cache.set(languageId, translations);\n this._writeTransfer(languageId, translations);\n return { data: translations, ok: true };\n } catch (error) {\n if (stale()) return { data: {}, ok: false };\n // Once per failed fetch, however many callers joined it.\n this._deps.onLoadError?.(languageId, error);\n return { data: {}, ok: false, error };\n } finally {\n // Only the owner of the in-flight slot may clear it (a reload may have\n // replaced this entry with a newer request).\n if (this._inflight.get(languageId) === task) {\n this._inflight.delete(languageId);\n }\n }\n })();\n return task;\n }\n\n private _generationOf(languageId: L): number {\n return this._generations.get(languageId) ?? 0;\n }\n\n private _invalidate(languageId: L): void {\n this._generations.set(languageId, this._generationOf(languageId) + 1);\n }\n\n private _transferKey(languageId: L): StateKey<Record<string, unknown>> {\n return makeStateKey<Record<string, unknown>>(`rivinia.i18n.dict.${languageId}`);\n }\n\n /** Stores freshly loaded dictionaries for hydration (server only). */\n private _writeTransfer(languageId: L, dict: Record<string, unknown>): void {\n if (!this._deps.request) return;\n this._deps.transfer?.set(this._transferKey(languageId), dict);\n }\n}\n","import type { Language, StorageStrategy } from '../models/i18n-types';\nimport { parseCookie, serializeCookie, shouldSecureCookie } from '../utils/cookies';\nimport { detectBrowserLanguage, safeGetItem, safeSetItem } from '../utils/i18n-utils';\n\nexport interface LanguageStorageDeps<L extends string> {\n readonly key: string;\n readonly strategy: StorageStrategy;\n readonly languages: () => readonly Language<L>[];\n readonly defaultLanguage: L;\n readonly detectBrowser: boolean;\n readonly document: Document;\n /** Present only on the server; carries the request `Cookie` header. */\n readonly request: { readonly headers: { get(name: string): string | null } } | null;\n /** `false` means the app owns persistence (RIV-17). */\n readonly persist: boolean;\n readonly browserLanguages: () => readonly string[] | undefined;\n}\n\n/**\n * Reads and writes the persisted language and decides the initial one.\n * Cookie strategy: server reads the request `Cookie` header (no hydration\n * mismatch), browser reads `document.cookie`; the server never writes.\n */\nexport class LanguageStorage<L extends string> {\n constructor(private readonly _deps: LanguageStorageDeps<L>) {}\n\n read(): string | null {\n if (this._deps.strategy === 'cookie') {\n const header = this._deps.request?.headers.get('cookie') ?? null;\n if (header !== null) return parseCookie(header, this._deps.key);\n try {\n return parseCookie(this._deps.document.cookie, this._deps.key);\n } catch {\n return null;\n }\n }\n return safeGetItem(this._deps.key, this._deps.strategy);\n }\n\n /** Persists the language. Server never writes (response cookies are app-owned). */\n write(id: L): void {\n if (this._deps.strategy === 'cookie') {\n if (this._deps.request) return;\n try {\n const location = (\n this._deps.document as unknown as { location?: { protocol?: string; hostname?: string } }\n )?.location;\n this._deps.document.cookie = serializeCookie(this._deps.key, id, {\n secure: shouldSecureCookie(location),\n });\n } catch {\n // Best-effort persistence.\n }\n return;\n }\n safeSetItem(this._deps.key, id, this._deps.strategy);\n }\n\n /** Explicit switches only (RIV-17): no write when storage already agrees. */\n persistAfterSwitch(id: L): void {\n if (!this._deps.persist) return;\n if (this.read() === id) return;\n this.write(id);\n }\n\n /** Stored id → browser detection → configured default. */\n resolveInitialLanguage(): L {\n const stored = this.read();\n const languages = this._deps.languages();\n if (stored && languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._deps.detectBrowser) {\n const detected = detectBrowserLanguage(\n languages.map((l) => l.id),\n this._deps.browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._deps.defaultLanguage;\n }\n}\n","import { signal, type Signal } from '@angular/core';\nimport type { MissingKeyEvent, MissingParamEvent } from '../models/missing-key';\n\nexport interface MissingKeyReporterDeps<L extends string> {\n /** Read when the event is created; the facade supplies it untracked. */\n readonly language: () => L;\n readonly fallbackLanguage: L | null;\n /** A key is not \"missing\" while its language has no dictionary yet. */\n readonly hasDictionary: (language: L) => boolean;\n readonly onMissingKey?: (event: MissingKeyEvent<L>) => void;\n readonly onMissingParam?: (event: MissingParamEvent<L>) => void;\n readonly warnOnMissingKey: boolean;\n readonly warnOnMissingParam: boolean;\n}\n\n/**\n * Records unresolved keys and absent message arguments once per session and\n * publishes them from a microtask: `t()` is a `computed`, and both the signal\n * write and the user callback must stay outside the computation (RIV-05).\n */\nexport class MissingKeyReporter<L extends string> {\n private readonly _missingKeys = signal<readonly string[]>([]);\n private readonly _reportedKeys = new Set<string>();\n private readonly _pendingKeys: string[] = [];\n private readonly _pendingKeyEvents: MissingKeyEvent<L>[] = [];\n private _keyFlushQueued = false;\n\n /** Dedupe key: `key` + NUL + `param`, so neither part can collide. */\n private readonly _reportedParams = new Set<string>();\n private readonly _pendingParamEvents: MissingParamEvent<L>[] = [];\n private _paramFlushQueued = false;\n\n readonly missingKeys: Signal<readonly string[]> = this._missingKeys.asReadonly();\n\n constructor(private readonly _deps: MissingKeyReporterDeps<L>) {}\n\n reportKey(key: string): void {\n // Before the current language has a dictionary, every key would be a false\n // positive — the load is still in flight, or it failed and there is\n // nothing to look a key up in.\n if (!this._deps.hasDictionary(this._deps.language())) return;\n if (this._reportedKeys.has(key)) return;\n this._reportedKeys.add(key);\n\n const language = this._deps.language();\n const fallbackLanguage = this._deps.fallbackLanguage;\n this._pendingKeys.push(key);\n this._pendingKeyEvents.push(\n fallbackLanguage === null ? { key, language } : { key, language, fallbackLanguage },\n );\n this._queueKeyFlush();\n\n if (this._deps.warnOnMissingKey) {\n console.warn(\n `[rivinia/i18n] Missing key \"${key}\" for language \"${language}\"` +\n (fallbackLanguage === null\n ? '.'\n : ` (fallback \"${fallbackLanguage}\" has no value either).`),\n );\n }\n }\n\n reportParam(key: string, param: string): void {\n const dedupe = `${key}\\u0000${param}`;\n if (this._reportedParams.has(dedupe)) return;\n this._reportedParams.add(dedupe);\n\n const language = this._deps.language();\n this._pendingParamEvents.push({ key, param, language });\n this._queueParamFlush();\n\n if (this._deps.warnOnMissingParam) {\n console.warn(\n `[rivinia/i18n] Missing parameter \"${param}\" for key \"${key}\" ` +\n `and language \"${language}\"; the placeholder was kept.`,\n );\n }\n }\n\n /** Resets the report (and the once-per-key dedupe), e.g. after a fix. */\n clearKeys(): void {\n this._reportedKeys.clear();\n this._pendingKeys.length = 0;\n this._pendingKeyEvents.length = 0;\n this._missingKeys.set([]);\n }\n\n /** Resets the missing-parameter dedupe, e.g. after adding the argument. */\n clearParams(): void {\n this._reportedParams.clear();\n this._pendingParamEvents.length = 0;\n }\n\n private _queueKeyFlush(): void {\n if (this._keyFlushQueued) return;\n this._keyFlushQueued = true;\n queueMicrotask(() => {\n this._keyFlushQueued = false;\n const pending = this._pendingKeys.splice(0);\n if (pending.length === 0) return;\n this._missingKeys.update((current) => [...current, ...pending]);\n // The handler runs here, not inside `t()`'s computation: it may write a\n // signal, and a signal write inside a computed throws NG0600.\n const events = this._pendingKeyEvents.splice(0);\n for (const event of events) this._deps.onMissingKey?.(event);\n });\n }\n\n private _queueParamFlush(): void {\n if (this._paramFlushQueued) return;\n this._paramFlushQueued = true;\n queueMicrotask(() => {\n this._paramFlushQueued = false;\n const events = this._pendingParamEvents.splice(0);\n for (const event of events) this._deps.onMissingParam?.(event);\n });\n }\n}\n","import type { TranslateParams } from '../models/i18n-types';\nimport { formatIcu } from '../utils/icu';\n\n/** Same 40-entry ceiling as the `formatIcu` caches; evicts LRU, they flush. */\nconst FORMATTER_CACHE_LIMIT = 40;\n\nexport interface MessageFormatterDeps {\n /** Read on every call so a language switch reaches the next render. */\n readonly locale: () => string;\n /** `key` is the dictionary key being rendered, for the error message. */\n readonly onMissingParam?: (key: string, name: string) => void;\n}\n\n/**\n * Renders dictionary text: the ICU subset plus memoized `Intl` formatters.\n * Plain class on purpose (D50): constructed by the facade, never injected.\n */\nexport class MessageFormatter {\n private readonly _formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();\n\n constructor(\n private readonly _deps: MessageFormatterDeps,\n private readonly _capacity: number = FORMATTER_CACHE_LIMIT,\n ) {}\n\n /** Test seam for the bound; not part of any public surface. */\n get cachedFormatterCount(): number {\n return this._formatters.size;\n }\n\n render(\n template: string,\n params: TranslateParams | undefined,\n locale: string,\n key: string,\n ): string {\n // Apostrophe quoting is message syntax, so `''` collapses even when the\n // caller passed no params; everything else keeps the no-params fast path\n // (a plural template without values must stay raw, not pick `other`).\n const quoting = template.includes(\"'\");\n if (params === undefined && !quoting) return template;\n if (!quoting && !template.includes('{')) return template;\n try {\n return formatIcu(template, params ?? {}, locale, {\n onMissingParam: (name) => this._deps.onMissingParam?.(key, name),\n });\n } catch {\n return template;\n }\n }\n\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this._numberFormatter(options).format(value);\n }\n\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this._dateTimeFormatter(options).format(value);\n }\n\n private _numberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat {\n const locale = this._deps.locale();\n const key = `n|${locale}|${JSON.stringify(options ?? null)}`;\n return this._memo(key, () => new Intl.NumberFormat(locale, options)) as Intl.NumberFormat;\n }\n\n private _dateTimeFormatter(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const locale = this._deps.locale();\n const key = `d|${locale}|${JSON.stringify(options ?? null)}`;\n return this._memo(key, () => new Intl.DateTimeFormat(locale, options)) as Intl.DateTimeFormat;\n }\n\n /** Least-recently-used eviction; a hit moves the entry to the fresh end. */\n private _memo(key: string, create: () => Intl.NumberFormat | Intl.DateTimeFormat): object {\n const cached = this._formatters.get(key);\n if (cached) {\n this._formatters.delete(key);\n this._formatters.set(key, cached);\n return cached;\n }\n const created = create();\n if (this._formatters.size >= this._capacity) {\n const oldest = this._formatters.keys().next().value;\n if (oldest !== undefined) this._formatters.delete(oldest);\n }\n this._formatters.set(key, created);\n return created;\n }\n}\n","import { DOCUMENT, Service, inject } from '@angular/core';\n\n/**\n * Progressive-enhancement wrapper around the View Transition API.\n * @internal Driven by `RiviniaI18n`; consumers configure\n * `viewTransition` instead of injecting this service.\n */\n@Service()\nexport class ViewTransitionService {\n private readonly _doc = inject(DOCUMENT);\n\n run(callback: () => void): void {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n if (typeof doc.startViewTransition === 'function') {\n doc.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import {\n DOCUMENT,\n PendingTasks,\n REQUEST,\n Service,\n TransferState,\n computed,\n inject,\n isDevMode,\n signal,\n untracked,\n type Signal,\n} from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from '../models/i18n-config';\nimport type { Direction } from '../models/i18n-types';\nimport type { Language } from '../models/i18n-types';\nimport type { TranslateParams } from '../models/i18n-types';\nimport type { Translation } from '../models/i18n-types';\nimport type { TranslationLoader } from '../models/loaders';\nimport type { LoaderContext } from '../models/loaders';\nimport type { MissingKeyEvent, MissingParamEvent } from '../models/missing-key';\nimport type { RegisteredI18nKey } from '../models/typed-keys';\nimport { jsonLoader } from '../models/loaders';\nimport { createLoaderContext } from '../utils/loader-context';\nimport { browserLanguages } from '../utils/i18n-utils';\nimport { DocumentDirectionApplier } from './document-direction-applier';\nimport { DictionaryStore } from './dictionary-store';\nimport { LanguageStorage } from './language-storage';\nimport { MissingKeyReporter } from './missing-key-reporter';\nimport { MessageFormatter } from './message-formatter';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n /** Validated once; `null` means no fallback chain. */\n private readonly _fallbackId: L | null = this._config.fallbackLanguage ?? null;\n /**\n * Injected (not global) document: the dir/lang effect renders on the\n * server too, avoiding an RTL first-paint shift on hydration.\n * Declared before any field initializer that reads storage.\n */\n private readonly _doc = inject(DOCUMENT);\n /** Present only on the server: used for cookie reads + transfer writes. */\n private readonly _request = inject(REQUEST, { optional: true });\n private readonly _transfer = inject(TransferState, { optional: true });\n\n private readonly _direction = new DocumentDirectionApplier<L>({\n document: this._doc,\n viewTransition: this._viewTransition,\n config: this._config.viewTransition,\n });\n\n /**\n * Platform facts for loaders, built once: `REQUEST` + `<base href>` on the\n * server, `document.baseURI` in the browser. This is what makes the default\n * loader work under SSR instead of fetching a relative URL Node cannot parse.\n */\n readonly loaderContext: LoaderContext = createLoaderContext(this._request ?? null, this._doc);\n\n /** Declared before the storage collaborator: it reads this during setup. */\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n\n private readonly _languageStorage = new LanguageStorage<L>({\n key: this._config.storageKey ?? DEFAULT_STORAGE_KEY,\n strategy: this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY,\n languages: () => this._languages(),\n defaultLanguage: this._config.defaultLanguage,\n detectBrowser: this._config.detectBrowser ?? false,\n document: this._doc,\n request: this._request ?? null,\n // Writes reach storage/cookies only after an explicit switch (RIV-17).\n persist: this._config.persist ?? true,\n browserLanguages,\n });\n\n private readonly _currentLanguageId = signal<L>(\n this._languageStorage.resolveInitialLanguage(),\n );\n\n private readonly _store = new DictionaryStore<L>({\n // Explicit loader wins; otherwise the conventional JSON layout\n // (`i18n/{language}.json`, served from the site root) unless the consumer\n // overrides the path. The descriptor still code-splits: the fetch\n // implementation loads only on first resolve.\n loader: (context) =>\n this._config.loader\n ? this._config.loader.resolve(context)\n : (jsonLoader().resolve(context) as Promise<TranslationLoader<L>>),\n loaderContext: this.loaderContext,\n request: this._request ?? null,\n transfer: this._transfer,\n onLoadError: this._config.onLoadError,\n currentLanguage: () => this._currentLanguageId(),\n fallbackLanguage: this._fallbackId,\n languageIds: () => this._languages().map((l) => l.id),\n hasInline: (languageId) => this._config.translations?.[languageId] !== undefined,\n });\n\n private _initialized = false;\n private readonly _tasks = inject(PendingTasks, { optional: true });\n\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._store.loadingState;\n readonly loadingError = this._store.loadingError;\n readonly isLoading = computed(() => this._store.loadingState() === 'loading');\n\n private readonly _ready = signal(false);\n /**\n * True once the initial language content is available (inline seed and/or\n * initial load settled) — or immediately when `preload: false` skips setup\n * loading. Gate first-paint skeletons on this, not on `isLoading`.\n */\n readonly ready = this._ready.asReadonly();\n\n /**\n * Missing-key reporting. `warnOnMissingKey` defaults to dev-mode warnings\n * unless the consumer supplied a handler (then the handler owns reporting).\n */\n private readonly _missingKeyReporter = new MissingKeyReporter<L>({\n language: () => this._currentLanguageId(),\n fallbackLanguage: this._fallbackId,\n hasDictionary: (language) => this._hasDictionary(language),\n onMissingKey: this._config.onMissingKey,\n onMissingParam: this._config.onMissingParam,\n warnOnMissingKey:\n this._config.warnOnMissingKey ??\n (isDevMode() && this._config.onMissingKey === undefined),\n warnOnMissingParam:\n this._config.warnOnMissingParam ??\n (isDevMode() && this._config.onMissingParam === undefined),\n });\n\n /**\n * Keys that could not be resolved from the current dictionary, the fallback\n * dictionary, or a `defaultValue`, in the order they were first looked up.\n * Published in a microtask because `t()` is a `computed` and Angular forbids\n * signal writes inside a computation.\n */\n readonly missingKeys = this._missingKeyReporter.missingKeys;\n\n /** Resets the report (and the once-per-key dedupe), e.g. after a fix. */\n clearMissingKeys(): void {\n this._missingKeyReporter.clearKeys();\n }\n\n /** Resets the missing-parameter dedupe, e.g. after adding the argument. */\n clearMissingParams(): void {\n this._missingKeyReporter.clearParams();\n }\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error(\n '[rivinia/i18n] At least one language must be provided in the languages array.',\n );\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n if (this._fallbackId !== null && !this._config.languages.some((l) => l.id === this._fallbackId)) {\n throw new Error(\n `[rivinia/i18n] fallbackLanguage \"${this._fallbackId}\" must be one of the configured language IDs.`,\n );\n }\n\n if (this._autoApplyDirection) {\n this._direction.install(() => this.currentLanguageObject());\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n /**\n * Runs the provider-setup loading: seeds inline dictionaries, then loads\n * the initial language (unless `preload: false`). Called automatically by\n * the `provideRiviniaI18n` app initializer; call manually only when driving\n * setup yourself. Idempotent. Never rejects (load failures land on\n * `loadingError`/`onLoadError`, inline seeds are preserved).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n const done = this._tasks?.add();\n try {\n const current = this._currentLanguageId();\n const fallback = this._fallbackId;\n const hasFallback = fallback !== null && fallback !== current;\n const preload = this._config.preload ?? true;\n\n const transferred = this._store.consumeTransfer(current);\n if (transferred) {\n this._store.adoptTransferred(current, transferred);\n } else {\n const inline = this._config.translations?.[current];\n if (inline) {\n // Instant paint without touching the cache: the refresh below still\n // runs, so a successful loader response wins; on failure the seed\n // stays visible and the error surfaces on loadingState/onLoadError.\n this._store.seedVisible(inline);\n }\n }\n\n let fallbackTransferred: Record<string, unknown> | null = null;\n if (hasFallback) {\n fallbackTransferred = this._store.consumeTransfer(fallback);\n if (fallbackTransferred) {\n this._store.adoptTransferred(fallback, fallbackTransferred);\n }\n }\n\n const loads: Array<Promise<unknown>> = [];\n if (!transferred && preload) {\n loads.push(this._store.load(current));\n }\n if (hasFallback && !fallbackTransferred && preload) {\n loads.push(this._store.load(fallback, { background: true }));\n }\n await Promise.all(loads);\n } finally {\n this._ready.set(true);\n done?.();\n }\n }\n\n translate(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;\n translate(key: RegisteredI18nKey, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: RegisteredI18nKey | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n return this._resolveKeyText(keyOrTranslations, defaultValue, params);\n }\n const currentId = this._currentLanguageId();\n const fallbackId = this._fallbackId;\n return (\n keyOrTranslations[currentId] ??\n (fallbackId !== null ? keyOrTranslations[fallbackId] : undefined) ??\n Object.values(keyOrTranslations)[0] ??\n ''\n );\n }\n\n /**\n * A `computed` over the same resolution chain as `translate()` — for\n * component fields (`readonly title = i18n.t('home.title')`), not for\n * calling from a template expression on every change detection.\n *\n * A function `params` is invoked inside the computation, so the signals it\n * reads are tracked and a change re-renders the text.\n */\n t(key: RegisteredI18nKey): Signal<string>;\n t(key: RegisteredI18nKey, params: TranslateParams | (() => TranslateParams)): Signal<string>;\n t(\n key: RegisteredI18nKey,\n defaultValue: string,\n params?: TranslateParams | (() => TranslateParams),\n ): Signal<string>;\n t(\n key: RegisteredI18nKey,\n defaultValueOrParams?: string | TranslateParams | (() => TranslateParams),\n maybeParams?: TranslateParams | (() => TranslateParams),\n ): Signal<string> {\n const defaultValue =\n typeof defaultValueOrParams === 'string' ? defaultValueOrParams : undefined;\n const paramsSource =\n typeof defaultValueOrParams === 'string' ? maybeParams : defaultValueOrParams;\n return computed(() => {\n const params = typeof paramsSource === 'function' ? paramsSource() : paramsSource;\n return this._resolveKeyText(key, defaultValue, params);\n });\n }\n\n private _resolveKeyText(\n key: RegisteredI18nKey,\n defaultValue: string | undefined,\n params: TranslateParams | undefined,\n ): string {\n const resolved = this._lookupKey(key);\n if (resolved !== undefined) {\n return this.render(resolved.text, params, resolved.locale, key);\n }\n if (defaultValue === undefined) {\n // Reporting reads language signals; keep those reads out of `t()`'s\n // dependency set (the dictionary/locale reads above already track it).\n untracked(() => this._reportMissingKey(key));\n }\n const fallback = defaultValue ?? key;\n return params ? this.render(fallback, params, this.locale(), key) : fallback;\n }\n\n readonly loadedTranslations = this._store.visible;\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(languageId: L): Promise<Record<string, unknown>> {\n return (await this._store.load(languageId)).data;\n }\n\n /**\n * Invalidates cached dictionaries and reloads them from the loader.\n *\n * - `reload()` — refreshes the current language (and the fallback, when\n * configured) and drops every OTHER cached dictionary, so the next switch\n * refetches. Resolves `true` when the current language loaded.\n * - `reload(lang)` — refreshes one language. If it is the current one it is\n * applied; otherwise it is only re-cached (and refreshed in the fallback\n * slot when it is the fallback).\n *\n * The visible dictionary stays on screen until the fresh one arrives\n * (stale-while-revalidate), so a reload never flashes raw keys.\n *\n * Never rejects: failures land on `loadingState`, `loadingError` and\n * `onLoadError` exactly like `loadTranslations`.\n */\n reload(languageId?: L): Promise<boolean> {\n return this._store.reload(languageId);\n }\n\n /**\n * Flips between the first two configured languages. Documentation and\n * templates commonly place it next to `next()`/`previous()`, so it warns in\n * dev mode when more than two languages are configured — use the cycling\n * methods there.\n */\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n if (langs.length > 2 && isDevMode()) {\n console.warn(\n '[rivinia/i18n] toggle() only flips the first two languages; ' +\n 'use next()/previous() when more than two are configured.',\n );\n }\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash.\n * A failed load aborts: language, direction and dictionary stay untouched. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n const { ok } = await this._store.load(id);\n if (!ok) return;\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language locale (cached Intl). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this._messageFormatter.formatNumber(value, options);\n }\n\n /** Date/time formatting bound to the current language locale (cached Intl). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this._messageFormatter.formatDate(value, options);\n }\n\n /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */\n readonly locale = computed<string>(() => {\n return this.currentLanguageObject().locale ?? this._currentLanguageId();\n });\n\n private readonly _messageFormatter = new MessageFormatter({\n locale: () => this.locale(),\n onMissingParam: (key, name) => untracked(() => this._reportMissingParam(key, name)),\n });\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._direction.apply(lang, () => this._currentLanguageId.set(id));\n\n if (!opts?.skipLoad) {\n void this._store.load(id);\n this._store.ensureFallback();\n }\n\n // Explicit switch only (RIV-17): the initial language is never written.\n this._languageStorage.persistAfterSwitch(id);\n }\n\n private render(\n template: string,\n params: TranslateParams | undefined,\n locale: string,\n key: string,\n ): string {\n return this._messageFormatter.render(template, params, locale, key);\n }\n\n /**\n * Current dictionary first, then the fallback dictionary. The returned\n * locale belongs to the dictionary the text came from: an English plural\n * template borrowed by an Arabic UI must use English plural rules.\n */\n private _lookupKey(key: string): { text: string; locale: string } | undefined {\n const currentValue = this._resolveKey(this._store.visible(), key);\n if (currentValue !== undefined) {\n return { text: currentValue, locale: this.locale() };\n }\n const fallbackId = this._fallbackId;\n if (fallbackId === null || fallbackId === this._currentLanguageId()) return undefined;\n const fallbackDict =\n this._store.fallback() ?? this._config.translations?.[fallbackId] ?? null;\n if (!fallbackDict) return undefined;\n const fallbackValue = this._resolveKey(fallbackDict, key);\n if (fallbackValue === undefined) return undefined;\n return { text: fallbackValue, locale: this._localeOf(fallbackId) };\n }\n\n private _localeOf(languageId: L): string {\n return this._languages().find((l) => l.id === languageId)?.locale ?? languageId;\n }\n\n private _hasDictionary(languageId: L): boolean {\n return this._store.has(languageId);\n }\n\n /**\n * Records a key no dictionary could resolve. Once per key per session; the\n * reporter defers the signal write so `t()` can stay a pure `computed`.\n */\n private _reportMissingKey(key: string): void {\n this._missingKeyReporter.reportKey(key);\n }\n\n /**\n * Mirrors `_reportMissingKey` for absent message arguments. The output keeps\n * the placeholder; this only records/warns, once per (key, param) pair. The\n * hook is deferred to a microtask for the same NG0600 reason.\n */\n private _reportMissingParam(key: string, param: string): void {\n this._missingKeyReporter.reportParam(key, param);\n }\n\n /**\n * Exact key first, then the nested walk. Exports from some tools keep the\n * dot in the key (`{ \"app.title\": \"x\" }`); on a collision the flat key wins.\n */\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = Object.prototype.hasOwnProperty.call(obj, path)\n ? obj[path]\n : path\n .split('.')\n .reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object'\n ? (acc as Record<string, unknown>)[segment]\n : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import {\n EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from '../models/i18n-config';\nimport { RiviniaI18n } from '../services/rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n * Also registers an app initializer that loads the initial language before\n * first paint (opt out with `preload: false`).\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n *\n * @example\n * ```ts\n * const AR = { id: 'ar', nativeName: 'العربية', dir: 'rtl' };\n * const EN = { id: 'en', nativeName: 'English', dir: 'ltr' };\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [AR, EN],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: RIVINIA_I18N_CONFIG, useValue: config },\n provideAppInitializer(() => {\n const i18n = inject(RiviniaI18n) as RiviniaI18n<string>;\n return i18n.initialize();\n }),\n ]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */\nexport function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L> {\n return inject(RiviniaI18n) as unknown as RiviniaI18n<L>;\n}\n\n/**\n * Binds a config and its typed accessors together so `L` is inferred once\n * from the configuration instead of being lost at the injection site.\n *\n * @example\n * ```ts\n * export const i18n = defineRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * });\n * // app.config.ts\n * providers: [i18n.provide()]\n * // anywhere (typed 'ar' | 'en'):\n * const lang = i18n.inject();\n * ```\n */\nexport function defineRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): {\n readonly config: RiviniaI18nConfig<L>;\n provide: () => EnvironmentProviders;\n inject: () => RiviniaI18n<L>;\n} {\n return {\n config,\n provide: () => provideRiviniaI18n(config),\n inject: () => injectRiviniaI18n<L>(),\n };\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from '../services/rivinia-i18n';\nimport type { TranslateParams } from '../models/i18n-types';\nimport type { Translation } from '../models/i18n-types';\nimport type { RegisteredI18nKey } from '../models/typed-keys';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code — or `t()`, which returns a\n * signal a template can read without re-running the pipe.\n */\n@Pipe({\n name: 'rvTranslate',\n pure: false,\n})\nexport class RvTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;\n transform(key: RegisteredI18nKey, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: RegisteredI18nKey | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as RegisteredI18nKey,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAOA,IAAa,mBAAb,cAAsC,MAAK;CAChC;CACA;CACA;CAET,YAAY,KAAa,QAAgB,UAAkB,SAA6B;EACtF,MAAM,kCAAkC,IAAG,UAAW,OAAM,IAAK,OAAO;EACxE,KAAK,OAAO;EACZ,KAAK,MAAM;EACX,KAAK,SAAS;EACd,KAAK,WAAW;CAClB;AACD;ACND,SAAgB,iBAAiB,KAAa,SAAuB;CACnE,IAAI,CAAC,SAAS,UAAU,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EzB,OADa,OAAO,WACb,CAAA,CAAK,WAAU;CACxB,CAAC,CACF,CAAA;AACH;AAGA,SAAgB,oBAAiB;CAC/B,OAAO,OAAO,WAAW;AAC3B;AAqBA,SAAgB,kBACd,QAA4B;CAM5B,OAAO;EACL;EACA,eAAe,mBAAmB,MAAM;EACxC,cAAc,kBAAiB;CAChC;AACH;ACjEA,IAAa,kBAAb,MAAa,gBAAe;CACT,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAe,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAf,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAe,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAf,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAe,YAAA,CAAA;EAJ3B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,MAAM;EACP,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rivinia/i18n",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Headless Angular language manager: signals, RTL, SSR-safe loaders, fallback language, missing-key reporting, ICU plurals, typed keys.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"angular",
|
|
@@ -11,6 +11,22 @@
|
|
|
11
11
|
"typescript"
|
|
12
12
|
],
|
|
13
13
|
"license": "MIT",
|
|
14
|
+
"author": "abdelfattahqandil21 <abdelfattahqandil21@gmail.com>",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/abdelfattahqandil21-oss/Revinia.git",
|
|
18
|
+
"directory": "projects/i18n"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/abdelfattahqandil21-oss/Revinia/tree/main/projects/i18n#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/abdelfattahqandil21-oss/Revinia/issues"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": "^22.22.3 || ^24.15.0 || >=26.0.0"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
14
30
|
"bin": {
|
|
15
31
|
"rivinia-i18n-keys": "./cli/rivinia-i18n-keys.mjs"
|
|
16
32
|
},
|
|
@@ -18,6 +34,11 @@
|
|
|
18
34
|
"@angular-devkit/schematics": "^22.0.0",
|
|
19
35
|
"@angular/core": "^22.0.0"
|
|
20
36
|
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"@angular-devkit/schematics": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
21
42
|
"sideEffects": false,
|
|
22
43
|
"schematics": "./schematics/collection.json",
|
|
23
44
|
"module": "fesm2022/rivinia-i18n.mjs",
|