@vielzeug/lingua 26.11.15 → 26.11.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_template.cjs +1 -1
- package/dist/_template.cjs.map +1 -1
- package/dist/_template.d.ts +4 -1
- package/dist/_template.d.ts.map +1 -1
- package/dist/_template.js +28 -6
- package/dist/_template.js.map +1 -1
- package/dist/i18n.cjs +1 -1
- package/dist/i18n.cjs.map +1 -1
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +2 -0
- package/dist/i18n.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/lingua.cjs +1 -1
- package/dist/lingua.cjs.map +1 -1
- package/dist/lingua.iife.js +1 -1
- package/dist/lingua.iife.js.map +1 -1
- package/dist/lingua.js +43 -9
- package/dist/lingua.js.map +1 -1
- package/dist/ripple.cjs +1 -1
- package/dist/ripple.cjs.map +1 -1
- package/dist/ripple.d.ts +5 -1
- package/dist/ripple.d.ts.map +1 -1
- package/dist/ripple.js +3 -1
- package/dist/ripple.js.map +1 -1
- package/dist/translator.cjs +1 -1
- package/dist/translator.cjs.map +1 -1
- package/dist/translator.d.ts +16 -1
- package/dist/translator.d.ts.map +1 -1
- package/dist/translator.js +25 -17
- package/dist/translator.js.map +1 -1
- package/dist/types.d.ts +23 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/lingua.iife.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lingua.iife.js","names":["error","exports","interpolation","parts","offset","match","value","index","part","values","missing","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","template","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","engine","fallbackLocales","controller","subscribers","disposed","transition","changed","target","effectiveMissing","listener","loadOptions","targetLocale","next","nextLocale","request","subscribeOptions","translateOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["export type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\nexport function renderText(\n parts: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n return parts\n .map((part) => {\n if (typeof part === 'string') return part;\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n return value == null ? missing(part.value) : String(value);\n })\n .join('');\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, SerializedI18n } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n serialized(locale: Locale): SerializedI18n<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n /**\n * Translates a runtime key that is not in the catalog's typed key set. Identical to\n * `translate` at runtime: the key is looked up the same way and a missing key follows\n * the configured `missing` strategy. The one typed escape hatch for keys that arrive\n * as strings, so consumers never cast around the typed surface.\n */\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n const values: Record<string, unknown> =\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n return renderText(template, values, (name) => missingValue(name, key));\n };\n\n return { locale, translate };\n}\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return { locale: engine.locale, translate: engine.translate, translateUnkeyed: engine.translate };\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaMissingCatalogError } from './errors';\nimport { createTranslateEngine, type Translator } from './translator';\nimport type {\n Catalog,\n I18nOptions,\n Locale,\n PluralOptions,\n SerializedI18n,\n SubscribeOptions,\n TranslateOptions,\n} from './types';\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n /** Current locale. Referentially stable until the locale changes, so frameworks can use it directly as a store snapshot. */\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n const fallbackLocales = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(locale: Locale) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildEngine = () => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const effectiveMissing = ready\n ? options.missing\n : (): never => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslateEngine(catalogs.catalogMap(), { ...options, locale, missing: effectiveMissing });\n };\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const notify = (): void => {\n engine = buildEngine();\n\n for (const listener of [...subscribers]) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n let engine = buildEngine();\n\n const instance: I18n<C> = {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return locale;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n serialize() {\n assertLive();\n\n return catalogs.serialized(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n\n return unsubscribe;\n },\n translate: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n translateUnkeyed: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n [Symbol.dispose]: dispose,\n };\n\n return instance;\n}\n"],"mappings":"A,qFAGA,IAAME,EAAgB,8BAEtB,SAAgB,gBAAgB,EAAyB,CACvD,IAAMC,EAAwB,CAAC,EAC3BC,EAAS,EAEb,IAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,EAAG,CACjD,IAAMK,EAAQF,EAAM,OAAS,EAEzBE,EAAQH,GAAQD,EAAM,KAAKG,EAAM,MAAMF,EAAQG,CAAK,CAAC,EAEzDJ,EAAM,KAAK,CAAE,MAAOE,EAAM,EAAG,CAAC,EAC9B,EAASE,EAAQF,EAAM,EAAE,CAAC,MAC5B,CAIA,OAFID,EAASE,EAAM,QAAQH,EAAM,KAAKG,EAAM,MAAMF,CAAM,CAAC,EAElDD,CACT,CAEA,SAAgB,WACd,EACA,EACA,EACQ,CACR,OAAOA,EACJ,IAAK,GAAS,CACb,GAAI,OAAOK,GAAS,SAAU,OAAOA,EAErC,IAAMF,EAAQ,OAAO,OAAOG,EAAQD,EAAK,KAAK,EAAIC,EAAOD,EAAK,OAAS,IAAA,GAEvE,OAAOF,GAAS,KAAOI,EAAQF,EAAK,KAAK,EAAI,OAAOF,CAAK,CAC3D,CAAC,CAAC,CACD,KAAK,EAAE,CACZ,CCrCA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMK,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,oBAAb,cAAyC,WAAY,CACnD,aAAc,CACZ,MAAM,+CAA+C,CACvD,CACF,EAEa,0BAAb,cAA+C,WAAY,CAAC,EAC/C,yBAAb,cAA8C,WAAY,CAAC,EAC9C,8BAAb,cAAmD,WAAY,CAAC,EACnD,0BAAb,cAA+C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AU,EACjCC,EAAU,EAAET,EACZC,EAAU,MAAM,YAAYM,CAAI,EAEtC,WAAW,EACPE,IAAYT,IAEZO,IAASnC,EACP6B,EAAQ,KAAK,QAAQ,GAAG,OAAO,GAKrC,EAASM,EACT,OAAO,GACT,EACA,UAAU,EAAU,EAAkB,CAGpC,GAFA,WAAW,EAEPG,GAAkB,QAAQ,QAAS,UAAa,CAAC,EAErD,IAAM,gBAA0B,CAC9BZ,EAAY,OAAOM,CAAQ,EAC3BM,GAAkB,QAAQ,oBAAoB,QAAS,WAAW,CACpE,EAKA,GAHAA,GAAkB,QAAQ,iBAAiB,QAAS,YAAa,CAAE,KAAM,EAAK,CAAC,EAC/EZ,EAAY,IAAIM,CAAQ,EAEpBM,GAAkB,UACpB,GAAI,CACFN,EAAShC,CAAM,CACjB,MAAgB,CAEhB,CAGF,OAAO,WACT,EACA,WAAY,EAAa,IACvBuB,EAAO,UAAU9B,EAAK8C,CAAgB,EACxC,kBAAmB,EAAa,IAC9BhB,EAAO,UAAU9B,EAAK8C,CAAgB,GACvC,OAAO,SAAU,OAGb,CACT,C"}
|
|
1
|
+
{"version":3,"file":"lingua.iife.js","names":["error","exports","interpolation","parts","offset","match","value","index","part","template","onText","values","missing","onValue","segments","text","out","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","engine","fallbackLocales","controller","subscribers","disposed","transition","changed","target","effectiveMissing","listener","loadOptions","targetLocale","next","nextLocale","request","subscribeOptions","translateOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["import type { Segment } from './types';\n\nexport type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\n/**\n * The single resolution walk shared by `translate()` and `parts()`: a nullish value (missing\n * or `null`/`undefined`) resolves through `missing` as text; every other value reaches\n * `onValue` untouched. One walk keeps the string and segment paths semantically identical\n * while letting `renderText` accumulate without allocating per-part segment objects.\n */\nfunction eachPart(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n onText: (text: string) => void,\n onValue: (name: string, value: unknown) => void,\n): void {\n for (const part of template) {\n if (typeof part === 'string') {\n onText(part);\n\n continue;\n }\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n if (value == null) onText(missing(part.value));\n else onValue(part.value, value);\n }\n}\n\n/** Text segments are never empty (`compileTemplate` only records non-empty runs); value segments may hold `''`. */\nexport function renderSegments<V>(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): readonly Segment<V>[] {\n const segments: Segment<V>[] = [];\n\n eachPart(\n template,\n values,\n missing,\n (text) => segments.push({ type: 'text', value: text }),\n (name, value) => segments.push({ name, type: 'value', value: value as V }),\n );\n\n return segments;\n}\n\nexport function renderText(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n let out = '';\n\n eachPart(\n template,\n values,\n missing,\n (text) => {\n out += text;\n },\n (_name, value) => {\n out += String(value);\n },\n );\n\n return out;\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, SerializedI18n } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n serialized(locale: Locale): SerializedI18n<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderSegments, renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PartsOptions,\n PluralKey,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n /**\n * Translates a runtime key that is not in the catalog's typed key set. Identical to\n * `translate` at runtime: the key is looked up the same way and a missing key follows\n * the configured `missing` strategy. The one typed escape hatch for keys that arrive\n * as strings, so consumers never cast around the typed surface.\n */\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n /**\n * Renders a message as segments for rich content: interpolation values pass through\n * untouched (never stringified or escaped), so framework nodes survive intact.\n * Resolution — plural selection, locale fallback, and the `missing` strategy — is the\n * same code path as `translate`: joining the segments with `String()` reproduces\n * `translate` exactly. A missing key yields a single text segment holding the\n * strategy's output.\n */\n parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];\n parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];\n /** Runtime-key escape hatch for {@link Translator.parts}, mirroring `translateUnkeyed`. */\n partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\n/** Loose parts signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseParts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate; readonly parts: LooseParts } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n return renderText(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n // Both entry points share templateFor + valuesFor + the missing callbacks, so `parts`\n // joined with String() is `translate` by construction, including the quirks consumers\n // rely on (an explicit `count` in `values` overrides the injected one).\n const parts = <V>(key: string, options: PartsOptions<V> | PluralPartsOptions<V> = {}): readonly Segment<V>[] => {\n const template = templateFor(key, options);\n\n if (!template) return [{ type: 'text', value: missingKey(key) }];\n\n return renderSegments<V>(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n return { locale, parts, translate };\n}\n\nconst valuesFor = (options: TranslateOptions | PluralOptions): Record<string, unknown> =>\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return {\n locale: engine.locale,\n parts: engine.parts as Translator<C>['parts'],\n partsUnkeyed: engine.parts as Translator<C>['partsUnkeyed'],\n translate: engine.translate,\n translateUnkeyed: engine.translate,\n };\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaMissingCatalogError } from './errors';\nimport { createTranslateEngine, type Translator } from './translator';\nimport type {\n Catalog,\n I18nOptions,\n Locale,\n PartsOptions,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n SerializedI18n,\n SubscribeOptions,\n TranslateOptions,\n} from './types';\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n /** Current locale. Referentially stable until the locale changes, so frameworks can use it directly as a store snapshot. */\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n const fallbackLocales = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(locale: Locale) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildEngine = () => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const effectiveMissing = ready\n ? options.missing\n : (): never => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslateEngine(catalogs.catalogMap(), { ...options, locale, missing: effectiveMissing });\n };\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const notify = (): void => {\n engine = buildEngine();\n\n for (const listener of [...subscribers]) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n let engine = buildEngine();\n\n const instance: I18n<C> = {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return locale;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n // Delegating through the mutable `engine` is what makes these follow `setLocale()`:\n // `notify()` swaps the engine, and the public slots must pick up the new one.\n parts: (<V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] =>\n engine.parts(key, options)) as I18n<C>['parts'],\n partsUnkeyed: (<V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] =>\n engine.parts(key, options)) as I18n<C>['partsUnkeyed'],\n serialize() {\n assertLive();\n\n return catalogs.serialized(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n\n return unsubscribe;\n },\n translate: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n translateUnkeyed: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n [Symbol.dispose]: dispose,\n };\n\n return instance;\n}\n"],"mappings":"A,qFAKA,IAAME,EAAgB,8BAEtB,SAAgB,gBAAgB,EAAyB,CACvD,IAAMC,EAAwB,CAAC,EAC3BC,EAAS,EAEb,IAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,EAAG,CACjD,IAAMK,EAAQF,EAAM,OAAS,EAEzBE,EAAQH,GAAQD,EAAM,KAAKG,EAAM,MAAMF,EAAQG,CAAK,CAAC,EAEzDJ,EAAM,KAAK,CAAE,MAAOE,EAAM,EAAG,CAAC,EAC9B,EAASE,EAAQF,EAAM,EAAE,CAAC,MAC5B,CAIA,OAFID,EAASE,EAAM,QAAQH,EAAM,KAAKG,EAAM,MAAMF,CAAM,CAAC,EAElDD,CACT,CAQA,SAAS,SACP,EACA,EACA,EACA,EACA,EACM,CACN,IAAK,IAAMK,KAAQC,EAAU,CAC3B,GAAI,OAAOD,GAAS,SAAU,CAC5BE,EAAOF,CAAI,EAEX,QACF,CAEA,IAAMF,EAAQ,OAAO,OAAOK,EAAQH,EAAK,KAAK,EAAIG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AW,EAEJM,EAAS,WAAWhB,CAAM,CACnC,EACA,MAAM,UAAU,EAAY,CAC1B,WAAW,EAEX,IAAMmC,EAAO,gBAAgBC,CAAU,EACjCC,EAAU,EAAET,EACZC,EAAU,MAAM,YAAYM,CAAI,EAEtC,WAAW,EACPE,IAAYT,IAEZO,IAASnC,EACP6B,EAAQ,KAAK,QAAQ,GAAG,OAAO,GAKrC,EAASM,EACT,OAAO,GACT,EACA,UAAU,EAAU,EAAkB,CAGpC,GAFA,WAAW,EAEPG,GAAkB,QAAQ,QAAS,UAAa,CAAC,EAErD,IAAM,gBAA0B,CAC9BZ,EAAY,OAAOM,CAAQ,EAC3BM,GAAkB,QAAQ,oBAAoB,QAAS,WAAW,CACpE,EAKA,GAHAA,GAAkB,QAAQ,iBAAiB,QAAS,YAAa,CAAE,KAAM,EAAK,CAAC,EAC/EZ,EAAY,IAAIM,CAAQ,EAEpBM,GAAkB,UACpB,GAAI,CACFN,EAAShC,CAAM,CACjB,MAAgB,CAEhB,CAGF,OAAO,WACT,EACA,WAAY,EAAa,IACvBuB,EAAO,UAAU7B,EAAK6C,CAAgB,EACxC,kBAAmB,EAAa,IAC9BhB,EAAO,UAAU7B,EAAK6C,CAAgB,GACvC,OAAO,SAAU,OAGb,CACT,C"}
|
package/dist/lingua.js
CHANGED
|
@@ -8,12 +8,34 @@ function compileTemplate(t) {
|
|
|
8
8
|
}
|
|
9
9
|
return r < t.length && n.push(t.slice(r)), n;
|
|
10
10
|
}
|
|
11
|
+
function eachPart(e, t, n, r, i) {
|
|
12
|
+
for (let a of e) {
|
|
13
|
+
if (typeof a == "string") {
|
|
14
|
+
r(a);
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
let e = Object.hasOwn(t, a.value) ? t[a.value] : void 0;
|
|
18
|
+
e == null ? r(n(a.value)) : i(a.value, e);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function renderSegments(e, t, n) {
|
|
22
|
+
let r = [];
|
|
23
|
+
return eachPart(e, t, n, (e) => r.push({
|
|
24
|
+
type: "text",
|
|
25
|
+
value: e
|
|
26
|
+
}), (e, t) => r.push({
|
|
27
|
+
name: e,
|
|
28
|
+
type: "value",
|
|
29
|
+
value: t
|
|
30
|
+
})), r;
|
|
31
|
+
}
|
|
11
32
|
function renderText(e, t, n) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
33
|
+
let r = "";
|
|
34
|
+
return eachPart(e, t, n, (e) => {
|
|
35
|
+
r += e;
|
|
36
|
+
}, (e, t) => {
|
|
37
|
+
r += String(t);
|
|
38
|
+
}), r;
|
|
17
39
|
}
|
|
18
40
|
// src/errors.ts
|
|
19
41
|
var LinguaError = class extends Error {
|
|
@@ -162,20 +184,30 @@ function createTranslateEngine(e, t = {}) {
|
|
|
162
184
|
return n.message.forms.get(r) ?? n.message.forms.get("other");
|
|
163
185
|
}, translate = (e, t = {}) => {
|
|
164
186
|
let n = templateFor(e, t);
|
|
165
|
-
return n ? renderText(n,
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
187
|
+
return n ? renderText(n, valuesFor(t), (t) => missingValue(t, e)) : missingKey(e);
|
|
188
|
+
}, parts = (e, t = {}) => {
|
|
189
|
+
let n = templateFor(e, t);
|
|
190
|
+
return n ? renderSegments(n, valuesFor(t), (t) => missingValue(t, e)) : [{
|
|
191
|
+
type: "text",
|
|
192
|
+
value: missingKey(e)
|
|
193
|
+
}];
|
|
169
194
|
};
|
|
170
195
|
return {
|
|
171
196
|
locale: n,
|
|
197
|
+
parts,
|
|
172
198
|
translate
|
|
173
199
|
};
|
|
174
200
|
}
|
|
201
|
+
var valuesFor = (e) => "count" in e ? {
|
|
202
|
+
count: e.count,
|
|
203
|
+
...e.values
|
|
204
|
+
} : e.values ?? {};
|
|
175
205
|
function createTranslator(e, t) {
|
|
176
206
|
let n = createTranslateEngine(/* @__PURE__ */ new Map([[canonicalLocale(t?.locale ?? "en"), compileCatalog(e)]]), t);
|
|
177
207
|
return {
|
|
178
208
|
locale: n.locale,
|
|
209
|
+
parts: n.parts,
|
|
210
|
+
partsUnkeyed: n.parts,
|
|
179
211
|
translate: n.translate,
|
|
180
212
|
translateUnkeyed: n.translate
|
|
181
213
|
};
|
|
@@ -230,6 +262,8 @@ function createI18n(e) {
|
|
|
230
262
|
get locale() {
|
|
231
263
|
return a;
|
|
232
264
|
},
|
|
265
|
+
parts: ((e, t) => c.parts(e, t)),
|
|
266
|
+
partsUnkeyed: ((e, t) => c.parts(e, t)),
|
|
233
267
|
serialize() {
|
|
234
268
|
return assertLive(), s.serialized(a);
|
|
235
269
|
},
|
package/dist/lingua.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lingua.js","names":["error","interpolation","parts","offset","match","value","index","part","values","missing","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","template","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","engine","fallbackLocales","controller","subscribers","disposed","transition","changed","target","effectiveMissing","listener","loadOptions","targetLocale","next","nextLocale","request","subscribeOptions","translateOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["export type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\nexport function renderText(\n parts: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n return parts\n .map((part) => {\n if (typeof part === 'string') return part;\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n return value == null ? missing(part.value) : String(value);\n })\n .join('');\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, SerializedI18n } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n serialized(locale: Locale): SerializedI18n<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n /**\n * Translates a runtime key that is not in the catalog's typed key set. Identical to\n * `translate` at runtime: the key is looked up the same way and a missing key follows\n * the configured `missing` strategy. The one typed escape hatch for keys that arrive\n * as strings, so consumers never cast around the typed surface.\n */\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n const values: Record<string, unknown> =\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n return renderText(template, values, (name) => missingValue(name, key));\n };\n\n return { locale, translate };\n}\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return { locale: engine.locale, translate: engine.translate, translateUnkeyed: engine.translate };\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaMissingCatalogError } from './errors';\nimport { createTranslateEngine, type Translator } from './translator';\nimport type {\n Catalog,\n I18nOptions,\n Locale,\n PluralOptions,\n SerializedI18n,\n SubscribeOptions,\n TranslateOptions,\n} from './types';\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n /** Current locale. Referentially stable until the locale changes, so frameworks can use it directly as a store snapshot. */\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n const fallbackLocales = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(locale: Locale) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildEngine = () => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const effectiveMissing = ready\n ? options.missing\n : (): never => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslateEngine(catalogs.catalogMap(), { ...options, locale, missing: effectiveMissing });\n };\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const notify = (): void => {\n engine = buildEngine();\n\n for (const listener of [...subscribers]) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n let engine = buildEngine();\n\n const instance: I18n<C> = {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return locale;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n serialize() {\n assertLive();\n\n return catalogs.serialized(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n\n return unsubscribe;\n },\n translate: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n translateUnkeyed: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n [Symbol.dispose]: dispose,\n };\n\n return instance;\n}\n"],"mappings":";AAGA,IAAMC,IAAgB;AAEtB,SAAgB,gBAAgB,GAAyB;CACvD,IAAMC,IAAwB,CAAC,GAC3BC,IAAS;CAEb,KAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,GAAG;EACjD,IAAMK,IAAQF,EAAM,SAAS;EAK7B,AAHIE,IAAQH,KAAQD,EAAM,KAAKG,EAAM,MAAMF,GAAQG,CAAK,CAAC,GAEzDJ,EAAM,KAAK,EAAE,OAAOE,EAAM,GAAG,CAAC,GAC9B,IAASE,IAAQF,EAAM,EAA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kB,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,GAAK,CAAC,GAC/EZ,EAAY,IAAIM,CAAQ,GAEpBM,GAAkB,WACpB,IAAI;IACF,EAAStC,CAAM;GACjB,QAAgB,CAEhB;GAGF,OAAO;EACT;EACA,YAAY,GAAa,MACvBuB,EAAO,UAAU9B,GAAK8C,CAAgB;EACxC,mBAAmB,GAAa,MAC9BhB,EAAO,UAAU9B,GAAK8C,CAAgB;GACvC,OAAO,UAAU;CAGb;AACT"}
|
|
1
|
+
{"version":3,"file":"lingua.js","names":["error","interpolation","parts","offset","match","value","index","part","template","values","onText","missing","onValue","segments","text","out","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","engine","fallbackLocales","controller","subscribers","disposed","transition","changed","target","effectiveMissing","listener","loadOptions","targetLocale","next","nextLocale","request","subscribeOptions","translateOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["import type { Segment } from './types';\n\nexport type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\n/**\n * The single resolution walk shared by `translate()` and `parts()`: a nullish value (missing\n * or `null`/`undefined`) resolves through `missing` as text; every other value reaches\n * `onValue` untouched. One walk keeps the string and segment paths semantically identical\n * while letting `renderText` accumulate without allocating per-part segment objects.\n */\nfunction eachPart(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n onText: (text: string) => void,\n onValue: (name: string, value: unknown) => void,\n): void {\n for (const part of template) {\n if (typeof part === 'string') {\n onText(part);\n\n continue;\n }\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n if (value == null) onText(missing(part.value));\n else onValue(part.value, value);\n }\n}\n\n/** Text segments are never empty (`compileTemplate` only records non-empty runs); value segments may hold `''`. */\nexport function renderSegments<V>(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): readonly Segment<V>[] {\n const segments: Segment<V>[] = [];\n\n eachPart(\n template,\n values,\n missing,\n (text) => segments.push({ type: 'text', value: text }),\n (name, value) => segments.push({ name, type: 'value', value: value as V }),\n );\n\n return segments;\n}\n\nexport function renderText(\n template: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n let out = '';\n\n eachPart(\n template,\n values,\n missing,\n (text) => {\n out += text;\n },\n (_name, value) => {\n out += String(value);\n },\n );\n\n return out;\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, SerializedI18n } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n serialized(locale: Locale): SerializedI18n<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderSegments, renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PartsOptions,\n PluralKey,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n /**\n * Translates a runtime key that is not in the catalog's typed key set. Identical to\n * `translate` at runtime: the key is looked up the same way and a missing key follows\n * the configured `missing` strategy. The one typed escape hatch for keys that arrive\n * as strings, so consumers never cast around the typed surface.\n */\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n /**\n * Renders a message as segments for rich content: interpolation values pass through\n * untouched (never stringified or escaped), so framework nodes survive intact.\n * Resolution — plural selection, locale fallback, and the `missing` strategy — is the\n * same code path as `translate`: joining the segments with `String()` reproduces\n * `translate` exactly. A missing key yields a single text segment holding the\n * strategy's output.\n */\n parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];\n parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];\n /** Runtime-key escape hatch for {@link Translator.parts}, mirroring `translateUnkeyed`. */\n partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\n/** Loose parts signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseParts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate; readonly parts: LooseParts } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n return renderText(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n // Both entry points share templateFor + valuesFor + the missing callbacks, so `parts`\n // joined with String() is `translate` by construction, including the quirks consumers\n // rely on (an explicit `count` in `values` overrides the injected one).\n const parts = <V>(key: string, options: PartsOptions<V> | PluralPartsOptions<V> = {}): readonly Segment<V>[] => {\n const template = templateFor(key, options);\n\n if (!template) return [{ type: 'text', value: missingKey(key) }];\n\n return renderSegments<V>(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n return { locale, parts, translate };\n}\n\nconst valuesFor = (options: TranslateOptions | PluralOptions): Record<string, unknown> =>\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return {\n locale: engine.locale,\n parts: engine.parts as Translator<C>['parts'],\n partsUnkeyed: engine.parts as Translator<C>['partsUnkeyed'],\n translate: engine.translate,\n translateUnkeyed: engine.translate,\n };\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaMissingCatalogError } from './errors';\nimport { createTranslateEngine, type Translator } from './translator';\nimport type {\n Catalog,\n I18nOptions,\n Locale,\n PartsOptions,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n SerializedI18n,\n SubscribeOptions,\n TranslateOptions,\n} from './types';\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n /** Current locale. Referentially stable until the locale changes, so frameworks can use it directly as a store snapshot. */\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n const fallbackLocales = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(locale: Locale) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildEngine = () => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const effectiveMissing = ready\n ? options.missing\n : (): never => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslateEngine(catalogs.catalogMap(), { ...options, locale, missing: effectiveMissing });\n };\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const notify = (): void => {\n engine = buildEngine();\n\n for (const listener of [...subscribers]) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n let engine = buildEngine();\n\n const instance: I18n<C> = {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return locale;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n // Delegating through the mutable `engine` is what makes these follow `setLocale()`:\n // `notify()` swaps the engine, and the public slots must pick up the new one.\n parts: (<V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] =>\n engine.parts(key, options)) as I18n<C>['parts'],\n partsUnkeyed: (<V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] =>\n engine.parts(key, options)) as I18n<C>['partsUnkeyed'],\n serialize() {\n assertLive();\n\n return catalogs.serialized(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n\n return unsubscribe;\n },\n translate: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n translateUnkeyed: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n [Symbol.dispose]: dispose,\n };\n\n return instance;\n}\n"],"mappings":";AAKA,IAAMC,IAAgB;AAEtB,SAAgB,gBAAgB,GAAyB;CACvD,IAAMC,IAAwB,CAAC,GAC3BC,IAAS;CAEb,KAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,GAAG;EACjD,IAAMK,IAAQF,EAAM,SAAS;EAK7B,AAHIE,IAAQH,KAAQD,EAAM,KAAKG,EAAM,MAAMF,GAAQG,CAAK,CAAC,GAEzDJ,EAAM,KAAK,EAAE,OAAOE,EAAM,GAAG,CAAC,GAC9B,IAASE,IAAQF,EAAM,EAAE,CAAC;CAC5B;CAIA,OAFID,IAASE,EAAM,UAAQH,EAAM,KAAKG,EAAM,MAAMF,CAAM,CAAC,GAElDD;AACT;AAQA,SAAS,SACP,GACA,GACA,GACA,GACA,GACM;CACN,KAAK,IAAMK,KAAQC,GAAU;EAC3B,IAAI,OAAOD,KAAS,UAAU;GAC5B,EAAOA,CAAI;GAEX;EACF;EAEA,IAAMF,IAAQ,OAAO,OAAOI,GAAQF,EAAK,KAAK,IAAIE,EAAOF,EAAK,SAAS,KAAA;EAEvE,AAAIF,KAAS,OAAMK,EAAOC,EAAQJ,EAAK,KAAK,CAAC,IACxCK,EAAQL,EAAK,OAAOF,CAAK;CAChC;AACF;AAGA,SAAgB,eACd,GACA,GACA,GACuB;CACvB,IAAMQ,IAAyB,CAAC;CAUhC,OARA,SACEL,GACAC,GACAE,IACC,MAASE,EAAS,KAAK;EAAE,MAAM;EAAQ,OAAOC;CAAK,CAAC,IACpD,GAAM,MAAUD,EAAS,KAAK;EAAE;EAAM,MAAM;EAAgB;CAAW,CAAC,CAC3E,GAEOA;AACT;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KAKrC,IAASM,GACT,OAAO;EACT;EACA,UAAU,GAAU,GAAkB;GAGpC,IAFA,WAAW,GAEPG,GAAkB,QAAQ,SAAS,aAAa,CAAC;GAErD,IAAM,oBAA0B;IAE9B,AADAZ,EAAY,OAAOM,CAAQ,GAC3BM,GAAkB,QAAQ,oBAAoB,SAAS,WAAW;GACpE;GAKA,IAHAA,GAAkB,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,GAAK,CAAC,GAC/EZ,EAAY,IAAIM,CAAQ,GAEpBM,GAAkB,WACpB,IAAI;IACF,EAAStC,CAAM;GACjB,QAAgB,CAEhB;GAGF,OAAO;EACT;EACA,YAAY,GAAa,MACvBuB,EAAO,UAAU7B,GAAK6C,CAAgB;EACxC,mBAAmB,GAAa,MAC9BhB,EAAO,UAAU7B,GAAK6C,CAAgB;GACvC,OAAO,UAAU;CAGb;AACT"}
|
package/dist/ripple.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");function createReactiveI18n(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.getSnapshot(),subscribe:e=>t.subscribe(()=>e())}),translate=(e,r)=>(n.value,t.translate(e,r)),translateUnkeyed=(e,r)=>(n.value,t.translateUnkeyed(e,r));return{i18n:t,locale:n,translate,translateUnkeyed}}exports.createReactiveI18n=createReactiveI18n;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");function createReactiveI18n(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.getSnapshot(),subscribe:e=>t.subscribe(()=>e())}),translate=(e,r)=>(n.value,t.translate(e,r)),translateUnkeyed=(e,r)=>(n.value,t.translateUnkeyed(e,r)),parts=(e,r)=>(n.value,t.partsUnkeyed(e,r));return{i18n:t,locale:n,parts,partsUnkeyed:parts,translate,translateUnkeyed}}exports.createReactiveI18n=createReactiveI18n;
|
|
2
2
|
//# sourceMappingURL=ripple.cjs.map
|
package/dist/ripple.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ripple.cjs","names":["fromSubscribable","_vielzeug_ripple","locale","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type {
|
|
1
|
+
{"version":3,"file":"ripple.cjs","names":["fromSubscribable","_vielzeug_ripple","locale","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type {\n Catalog,\n Locale,\n PartsOptions,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n TranslateOptions,\n} from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Render a text or plural key as rich segments; re-evaluates whenever the locale changes. */\n readonly parts: Translator<C>['parts'];\n /** Render a runtime key outside the typed key set as rich segments; re-evaluates on locale changes. */\n readonly partsUnkeyed: <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n readonly translate: Translator<C>['translate'];\n /** Translate a runtime key outside the typed key set; re-evaluates whenever the locale changes. */\n readonly translateUnkeyed: (key: string, options?: TranslateOptions | PluralOptions) => string;\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. The bridge's\n * `translate` reads the reactive {@link ReactiveI18n.locale} first, so any binding built on\n * it re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.getSnapshot(),\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n const translate = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translate(key as never, options as never);\n };\n\n const translateUnkeyed = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translateUnkeyed(key, options);\n };\n\n const parts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] => {\n void locale.value;\n return i18n.partsUnkeyed<V>(key, options);\n };\n\n return {\n i18n,\n locale,\n parts: parts as ReactiveI18n<C>['parts'],\n partsUnkeyed: parts,\n translate: translate as ReactiveI18n<C>['translate'],\n translateUnkeyed,\n };\n}\n"],"mappings":"A,qGAsCA,SAAgB,mBAAsC,EAAgC,CACpF,IAAME,GAAA,EAASF,EAAAA,iBAAAA,CAAyB,CACtC,gBAAmBG,EAAK,YAAY,EACpC,UAAY,GAAaA,EAAK,cAAgBC,EAAS,CAAC,CAC1D,CAAC,EAEK,WAAa,EAAa,KAC9BF,EAAY,MACLC,EAAK,UAAUE,EAAcC,CAAgB,GAGhD,kBAAoB,EAAa,KACrCJ,EAAY,MACLC,EAAK,iBAAiBE,EAAKC,CAAO,GAGrC,OAAY,EAAa,KAC7BJ,EAAY,MACLC,EAAK,aAAgBE,EAAKC,CAAO,GAG1C,MAAO,CACL,OACA,SACO,MACP,aAAc,MACH,UACX,gBACF,CACF,C"}
|
package/dist/ripple.d.ts
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { type Readable } from '@vielzeug/ripple';
|
|
2
2
|
import type { I18n } from './i18n';
|
|
3
3
|
import type { Translator } from './translator';
|
|
4
|
-
import type { Catalog, Locale, PluralOptions, TranslateOptions } from './types';
|
|
4
|
+
import type { Catalog, Locale, PartsOptions, PluralOptions, PluralPartsOptions, Segment, TranslateOptions } from './types';
|
|
5
5
|
/** A lingua instance mirrored into ripple readables so templates react to locale changes. */
|
|
6
6
|
export interface ReactiveI18n<C extends Catalog> {
|
|
7
7
|
/** The underlying instance for imperative work (`setLocale`, `load`, disposal). */
|
|
8
8
|
readonly i18n: I18n<C>;
|
|
9
9
|
/** Reactive locale: reading it inside a computed/template registers the dependency. */
|
|
10
10
|
readonly locale: Readable<Locale>;
|
|
11
|
+
/** Render a text or plural key as rich segments; re-evaluates whenever the locale changes. */
|
|
12
|
+
readonly parts: Translator<C>['parts'];
|
|
13
|
+
/** Render a runtime key outside the typed key set as rich segments; re-evaluates on locale changes. */
|
|
14
|
+
readonly partsUnkeyed: <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];
|
|
11
15
|
/** Translate a text or plural key; re-evaluates whenever the locale changes. */
|
|
12
16
|
readonly translate: Translator<C>['translate'];
|
|
13
17
|
/** Translate a runtime key outside the typed key set; re-evaluates whenever the locale changes. */
|
package/dist/ripple.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ripple.d.ts","sourceRoot":"","sources":["../src/ripple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"ripple.d.ts","sourceRoot":"","sources":["../src/ripple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EACV,OAAO,EACP,MAAM,EACN,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,OAAO,EACP,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB,6FAA6F;AAC7F,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,OAAO;IAC7C,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACvB,uFAAuF;IACvF,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAClC,8FAA8F;IAC9F,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACvC,uGAAuG;IACvG,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC,CAAC,CAAC,KAAK,SAAS,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IACpH,gFAAgF;IAChF,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IAC/C,mGAAmG;IACnG,QAAQ,CAAC,gBAAgB,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,aAAa,KAAK,MAAM,CAAC;CAChG;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CA6BpF"}
|
package/dist/ripple.js
CHANGED
|
@@ -4,10 +4,12 @@ function createReactiveI18n(t) {
|
|
|
4
4
|
let n = e({
|
|
5
5
|
getSnapshot: () => t.getSnapshot(),
|
|
6
6
|
subscribe: (e) => t.subscribe(() => e())
|
|
7
|
-
}), translate = (e, r) => (n.value, t.translate(e, r)), translateUnkeyed = (e, r) => (n.value, t.translateUnkeyed(e, r));
|
|
7
|
+
}), translate = (e, r) => (n.value, t.translate(e, r)), translateUnkeyed = (e, r) => (n.value, t.translateUnkeyed(e, r)), parts = (e, r) => (n.value, t.partsUnkeyed(e, r));
|
|
8
8
|
return {
|
|
9
9
|
i18n: t,
|
|
10
10
|
locale: n,
|
|
11
|
+
parts,
|
|
12
|
+
partsUnkeyed: parts,
|
|
11
13
|
translate,
|
|
12
14
|
translateUnkeyed
|
|
13
15
|
};
|
package/dist/ripple.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ripple.js","names":["locale","fromSubscribable","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type {
|
|
1
|
+
{"version":3,"file":"ripple.js","names":["locale","fromSubscribable","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type {\n Catalog,\n Locale,\n PartsOptions,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n TranslateOptions,\n} from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Render a text or plural key as rich segments; re-evaluates whenever the locale changes. */\n readonly parts: Translator<C>['parts'];\n /** Render a runtime key outside the typed key set as rich segments; re-evaluates on locale changes. */\n readonly partsUnkeyed: <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n readonly translate: Translator<C>['translate'];\n /** Translate a runtime key outside the typed key set; re-evaluates whenever the locale changes. */\n readonly translateUnkeyed: (key: string, options?: TranslateOptions | PluralOptions) => string;\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. The bridge's\n * `translate` reads the reactive {@link ReactiveI18n.locale} first, so any binding built on\n * it re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.getSnapshot(),\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n const translate = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translate(key as never, options as never);\n };\n\n const translateUnkeyed = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translateUnkeyed(key, options);\n };\n\n const parts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[] => {\n void locale.value;\n return i18n.partsUnkeyed<V>(key, options);\n };\n\n return {\n i18n,\n locale,\n parts: parts as ReactiveI18n<C>['parts'],\n partsUnkeyed: parts,\n translate: translate as ReactiveI18n<C>['translate'],\n translateUnkeyed,\n };\n}\n"],"mappings":";;AAsCA,SAAgB,mBAAsC,GAAgC;CACpF,IAAMA,IAASC,EAAyB;EACtC,mBAAmBC,EAAK,YAAY;EACpC,YAAY,MAAaA,EAAK,gBAAgBC,EAAS,CAAC;CAC1D,CAAC,GAEK,aAAa,GAAa,OAC9BH,EAAY,OACLE,EAAK,UAAUE,GAAcC,CAAgB,IAGhD,oBAAoB,GAAa,OACrCL,EAAY,OACLE,EAAK,iBAAiBE,GAAKC,CAAO,IAGrC,SAAY,GAAa,OAC7BL,EAAY,OACLE,EAAK,aAAgBE,GAAKC,CAAO;CAG1C,OAAO;EACL;EACA;EACO;EACP,cAAc;EACH;EACX;CACF;AACF"}
|
package/dist/translator.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_catalog.cjs");require("./_dev.cjs");const t=require("./_locale.cjs"),n=require("./_template.cjs"),r=require("./errors.cjs");function resolveMissing(e,t){if(e===`throw`)throw t.name?new r.LinguaMissingValueError(`Missing interpolation value "${t.name}" for key "${t.key}" in locale "${t.locale}".`):new r.LinguaMissingKeyError(`Missing translation key "${t.key}" in locale "${t.locale}".`);return typeof e==`function`?e(t):t.name?`{${t.name}}`:t.key}function createTranslateEngine(e,i={}){let a=t.canonicalLocale(i.locale??`en`),o=(Array.isArray(i.fallback)?i.fallback:i.fallback?[i.fallback]:[]).map(t.canonicalLocale),s=t.localeChain(a,o),c=i.missing,missingKey=e=>resolveMissing(c,{key:e,locale:a}),missingValue=(e,t)=>resolveMissing(c,{key:t,locale:a,name:e}),resolve=t=>{for(let n of s){let r=e.get(n)?.get(t);if(r)return{locale:n,message:r}}},templateFor=(e,n)=>{let i=resolve(e);if(!i)return;if(i.message.kind===`text`)return`count`in n?void 0:i.message.template;if(!(`count`in n)||!Number.isFinite(n.count)){if(`count`in n)throw new r.LinguaInvalidPluralCountError("`count` must be a finite number.");return}let a=t.pluralCategory(i.locale,n.count,n.ordinal??!1);return i.message.forms.get(a)??i.message.forms.get(`other`)},translate=(e,t={})=>{let r=templateFor(e,t);
|
|
1
|
+
const e=require("./_catalog.cjs");require("./_dev.cjs");const t=require("./_locale.cjs"),n=require("./_template.cjs"),r=require("./errors.cjs");function resolveMissing(e,t){if(e===`throw`)throw t.name?new r.LinguaMissingValueError(`Missing interpolation value "${t.name}" for key "${t.key}" in locale "${t.locale}".`):new r.LinguaMissingKeyError(`Missing translation key "${t.key}" in locale "${t.locale}".`);return typeof e==`function`?e(t):t.name?`{${t.name}}`:t.key}function createTranslateEngine(e,i={}){let a=t.canonicalLocale(i.locale??`en`),o=(Array.isArray(i.fallback)?i.fallback:i.fallback?[i.fallback]:[]).map(t.canonicalLocale),s=t.localeChain(a,o),c=i.missing,missingKey=e=>resolveMissing(c,{key:e,locale:a}),missingValue=(e,t)=>resolveMissing(c,{key:t,locale:a,name:e}),resolve=t=>{for(let n of s){let r=e.get(n)?.get(t);if(r)return{locale:n,message:r}}},templateFor=(e,n)=>{let i=resolve(e);if(!i)return;if(i.message.kind===`text`)return`count`in n?void 0:i.message.template;if(!(`count`in n)||!Number.isFinite(n.count)){if(`count`in n)throw new r.LinguaInvalidPluralCountError("`count` must be a finite number.");return}let a=t.pluralCategory(i.locale,n.count,n.ordinal??!1);return i.message.forms.get(a)??i.message.forms.get(`other`)},translate=(e,t={})=>{let r=templateFor(e,t);return r?n.renderText(r,valuesFor(t),t=>missingValue(t,e)):missingKey(e)},parts=(e,t={})=>{let r=templateFor(e,t);return r?n.renderSegments(r,valuesFor(t),t=>missingValue(t,e)):[{type:`text`,value:missingKey(e)}]};return{locale:a,parts,translate}}var valuesFor=e=>`count`in e?{count:e.count,...e.values}:e.values??{};function createTranslator(n,r){let i=createTranslateEngine(new Map([[t.canonicalLocale(r?.locale??`en`),e.compileCatalog(n)]]),r);return{locale:i.locale,parts:i.parts,partsUnkeyed:i.parts,translate:i.translate,translateUnkeyed:i.translate}}exports.createTranslateEngine=createTranslateEngine,exports.createTranslator=createTranslator;
|
|
2
2
|
//# sourceMappingURL=translator.cjs.map
|
package/dist/translator.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translator.cjs","names":["LinguaMissingValueError","LinguaMissingKeyError","canonicalLocale","localeChain","LinguaInvalidPluralCountError","pluralCategory","renderText","compileCatalog","require__catalog","require__locale","require__template","require_errors","strategy","info","locale","options","fallback","chain","missing","candidate","message","catalogs","key","found","category","template","
|
|
1
|
+
{"version":3,"file":"translator.cjs","names":["LinguaMissingValueError","LinguaMissingKeyError","canonicalLocale","localeChain","LinguaInvalidPluralCountError","pluralCategory","renderText","renderSegments","compileCatalog","require__catalog","require__locale","require__template","require_errors","strategy","info","locale","options","fallback","chain","missing","candidate","message","catalogs","key","found","category","template","name","engine","catalog"],"sources":["../src/translator.ts"],"sourcesContent":["import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderSegments, renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PartsOptions,\n PluralKey,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n /**\n * Translates a runtime key that is not in the catalog's typed key set. Identical to\n * `translate` at runtime: the key is looked up the same way and a missing key follows\n * the configured `missing` strategy. The one typed escape hatch for keys that arrive\n * as strings, so consumers never cast around the typed surface.\n */\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n /**\n * Renders a message as segments for rich content: interpolation values pass through\n * untouched (never stringified or escaped), so framework nodes survive intact.\n * Resolution — plural selection, locale fallback, and the `missing` strategy — is the\n * same code path as `translate`: joining the segments with `String()` reproduces\n * `translate` exactly. A missing key yields a single text segment holding the\n * strategy's output.\n */\n parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];\n parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];\n /** Runtime-key escape hatch for {@link Translator.parts}, mirroring `translateUnkeyed`. */\n partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\n/** Loose parts signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseParts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate; readonly parts: LooseParts } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n return renderText(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n // Both entry points share templateFor + valuesFor + the missing callbacks, so `parts`\n // joined with String() is `translate` by construction, including the quirks consumers\n // rely on (an explicit `count` in `values` overrides the injected one).\n const parts = <V>(key: string, options: PartsOptions<V> | PluralPartsOptions<V> = {}): readonly Segment<V>[] => {\n const template = templateFor(key, options);\n\n if (!template) return [{ type: 'text', value: missingKey(key) }];\n\n return renderSegments<V>(template, valuesFor(options), (name) => missingValue(name, key));\n };\n\n return { locale, parts, translate };\n}\n\nconst valuesFor = (options: TranslateOptions | PluralOptions): Record<string, unknown> =>\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return {\n locale: engine.locale,\n parts: engine.parts as Translator<C>['parts'],\n partsUnkeyed: engine.parts as Translator<C>['partsUnkeyed'],\n translate: engine.translate,\n translateUnkeyed: engine.translate,\n };\n}\n"],"mappings":"A,gJAmDA,SAAS,eAAe,EAAuC,EAA2B,CACxF,GAAIa,IAAa,QACf,MAAMC,EAAK,KACP,IAAId,EAAAA,wBACF,gCAAgCc,EAAK,KAAK,aAAaA,EAAK,IAAI,eAAeA,EAAK,OAAO,GAC7F,EACA,IAAIb,EAAAA,sBAAsB,4BAA4Ba,EAAK,IAAI,eAAeA,EAAK,OAAO,GAAG,EAcnG,OAXI,OAAOD,G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c,CACzF,IAAME,EAAW,YAAYH,EAAKP,CAAO,EAIzC,OAFKU,EAEEpB,EAAAA,WAAWoB,EAAU,UAAUV,CAAO,EAAI,GAAS,aAAaW,EAAMJ,CAAG,CAAC,EAF3D,WAAWA,CAAG,CAGtC,EAKM,OAAY,EAAa,EAAmD,CAAC,IAA6B,CAC9G,IAAMG,EAAW,YAAYH,EAAKP,CAAO,EAIzC,OAFKU,EAEEnB,EAAAA,eAAkBmB,EAAU,UAAUV,CAAO,EAAI,GAAS,aAAaW,EAAMJ,CAAG,CAAC,EAFlE,CAAC,CAAE,KAAM,OAAQ,MAAO,WAAWA,CAAG,CAAE,CAAC,CAGjE,EAEA,MAAO,CAAE,SAAQ,MAAO,SAAU,CACpC,CAEA,IAAM,UAAa,GACjB,UAAWP,EAAU,CAAE,MAAOA,EAAQ,MAAO,GAAGA,EAAQ,MAAO,EAAKA,EAAQ,QAAU,CAAC,EASzF,SAAgB,iBAAoC,EAAY,EAA4C,CAC1G,IAAMY,EAAS,sBACb,IAAI,IAAI,CAAC,CAAC1B,EAAAA,gBAAgBc,GAAS,QAAU,IAAI,EAAGR,EAAAA,eAAeqB,CAAO,CAAC,CAAC,CAAC,EAC7Eb,CACF,EAEA,MAAO,CACL,OAAQY,EAAO,OACf,MAAOA,EAAO,MACd,aAAcA,EAAO,MACrB,UAAWA,EAAO,UAClB,iBAAkBA,EAAO,SAC3B,CACF,C"}
|
package/dist/translator.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type CompiledCatalog } from './_catalog';
|
|
2
|
-
import type { Catalog, Locale, MissingStrategy, PluralKey, PluralOptions, TextKey, TranslateOptions, TranslatorOptions } from './types';
|
|
2
|
+
import type { Catalog, Locale, MissingStrategy, PartsOptions, PluralKey, PluralOptions, PluralPartsOptions, Segment, TextKey, TranslateOptions, TranslatorOptions } from './types';
|
|
3
3
|
export type Translator<C extends Catalog = Catalog> = {
|
|
4
4
|
readonly locale: Locale;
|
|
5
5
|
translate(key: TextKey<C>, options?: TranslateOptions): string;
|
|
@@ -11,13 +11,28 @@ export type Translator<C extends Catalog = Catalog> = {
|
|
|
11
11
|
* as strings, so consumers never cast around the typed surface.
|
|
12
12
|
*/
|
|
13
13
|
translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;
|
|
14
|
+
/**
|
|
15
|
+
* Renders a message as segments for rich content: interpolation values pass through
|
|
16
|
+
* untouched (never stringified or escaped), so framework nodes survive intact.
|
|
17
|
+
* Resolution — plural selection, locale fallback, and the `missing` strategy — is the
|
|
18
|
+
* same code path as `translate`: joining the segments with `String()` reproduces
|
|
19
|
+
* `translate` exactly. A missing key yields a single text segment holding the
|
|
20
|
+
* strategy's output.
|
|
21
|
+
*/
|
|
22
|
+
parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];
|
|
23
|
+
parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];
|
|
24
|
+
/** Runtime-key escape hatch for {@link Translator.parts}, mirroring `translateUnkeyed`. */
|
|
25
|
+
partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];
|
|
14
26
|
};
|
|
15
27
|
/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */
|
|
16
28
|
export type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;
|
|
29
|
+
/** Loose parts signature implemented by the engine; public overloads restrict keys per catalog type. */
|
|
30
|
+
export type LooseParts = <V>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>) => readonly Segment<V>[];
|
|
17
31
|
/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */
|
|
18
32
|
export declare function createTranslateEngine(catalogs: ReadonlyMap<Locale, CompiledCatalog>, options?: InternalOptions): {
|
|
19
33
|
readonly locale: Locale;
|
|
20
34
|
readonly translate: LooseTranslate;
|
|
35
|
+
readonly parts: LooseParts;
|
|
21
36
|
};
|
|
22
37
|
type InternalOptions = {
|
|
23
38
|
readonly fallback?: Locale | readonly Locale[];
|