@vielzeug/lingua 1.1.0 → 1.1.2
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/i18n-types.d.ts +250 -0
- package/dist/i18n-types.d.ts.map +1 -0
- package/dist/i18n.cjs +1 -1
- package/dist/i18n.cjs.map +1 -1
- package/dist/i18n.d.ts +3 -246
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +56 -46
- package/dist/i18n.js.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 +1 -1
- package/dist/lingua.js.map +1 -1
- package/package.json +6 -3
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import type { Messages } from './_catalog';
|
|
2
|
+
import type { LocaleSource } from './_catalog-store';
|
|
3
|
+
import type { NamespaceFactory } from './_namespace-store';
|
|
4
|
+
import type { Formatter } from './format';
|
|
5
|
+
export type Locale = string;
|
|
6
|
+
export type Unsubscribe = () => void;
|
|
7
|
+
export type { Messages } from './_catalog';
|
|
8
|
+
export type { Loader, LocaleSource } from './_catalog-store';
|
|
9
|
+
export type { NamespaceFactory } from './_namespace-store';
|
|
10
|
+
export type TranslateVars = Record<string, unknown>;
|
|
11
|
+
/**
|
|
12
|
+
* A snapshot of the i18n instance state at a point in time.
|
|
13
|
+
* Object identity changes on every observable change (locale switch, catalog load).
|
|
14
|
+
* `t` and `tp` are bound to the locale captured in this snapshot.
|
|
15
|
+
*/
|
|
16
|
+
export type I18nSnapshot = {
|
|
17
|
+
readonly locale: Locale;
|
|
18
|
+
/** @security Returns raw, unsanitized strings. Sanitize before `innerHTML` insertion. */
|
|
19
|
+
readonly t: (key: string, vars?: TranslateVars) => string;
|
|
20
|
+
readonly tp: (key: string, count: number, options?: TpOptions) => string;
|
|
21
|
+
};
|
|
22
|
+
/** Shape of the serialised state produced by `serializeI18n()`. Pass to `hydrateI18n()` on the client. */
|
|
23
|
+
export type I18nState = {
|
|
24
|
+
readonly catalogs: Record<Locale, Record<string, string>>;
|
|
25
|
+
readonly locale: Locale;
|
|
26
|
+
};
|
|
27
|
+
export type SubscribeOptions = {
|
|
28
|
+
immediate?: boolean;
|
|
29
|
+
/** AbortSignal — automatically unsubscribes when the signal is aborted. */
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
};
|
|
32
|
+
export type TpOptions = {
|
|
33
|
+
/** Use ordinal plural rules (1st, 2nd, 3rd) instead of cardinal (default: `false`). */
|
|
34
|
+
ordinal?: boolean;
|
|
35
|
+
/** Inject additional interpolation variables alongside the automatically injected `count`. */
|
|
36
|
+
vars?: TranslateVars;
|
|
37
|
+
};
|
|
38
|
+
export type ScopedI18n = {
|
|
39
|
+
/** Intl formatter inherited from the parent instance. Follows locale changes automatically. */
|
|
40
|
+
readonly fmt: Formatter;
|
|
41
|
+
has(key: string): boolean;
|
|
42
|
+
t(key: string, vars?: TranslateVars): string;
|
|
43
|
+
tp(key: string, count: number, options?: TpOptions): string;
|
|
44
|
+
};
|
|
45
|
+
type Depth = [never, 0, 1, 2, 3, 4, 5, 6];
|
|
46
|
+
export type MessageLeafKeys<T, P extends string = '', D extends number = 7> = [D] extends [0] ? never : T extends string ? P : T extends Record<string, unknown> ? {
|
|
47
|
+
[K in string & keyof T]: MessageLeafKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]>;
|
|
48
|
+
}[string & keyof T] : never;
|
|
49
|
+
export type MessageBranchKeys<T, P extends string = '', D extends number = 7> = [D] extends [0] ? never : T extends Record<string, unknown> ? {
|
|
50
|
+
[K in string & keyof T]: T[K] extends string ? never : (P extends '' ? K : `${P}.${K}`) | MessageBranchKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]>;
|
|
51
|
+
}[string & keyof T] : never;
|
|
52
|
+
export type I18nOptions<M extends Messages = Messages> = {
|
|
53
|
+
/** Locale registry. Values can be static message objects or async loaders. */
|
|
54
|
+
catalogs?: Record<Locale, LocaleSource<M>>;
|
|
55
|
+
/** Locale(s) to search when the active locale is missing a key. Subtags are expanded automatically (e.g. `en-US` → `en`). */
|
|
56
|
+
fallback?: Locale | Locale[];
|
|
57
|
+
/** Initial active locale. Defaults to `"en"`. Canonicalized via `Intl.getCanonicalLocales`. */
|
|
58
|
+
locale?: Locale;
|
|
59
|
+
/**
|
|
60
|
+
* Called when a translation key is missing.
|
|
61
|
+
* Defaults to returning the key string.
|
|
62
|
+
*
|
|
63
|
+
* @security The default handler returns `key` verbatim. Do not render the return value as HTML
|
|
64
|
+
* if keys are constructed from untrusted user input.
|
|
65
|
+
*/
|
|
66
|
+
onMissingKey?: (key: string, locale: Locale) => string;
|
|
67
|
+
/**
|
|
68
|
+
* Called when an interpolation variable is missing.
|
|
69
|
+
* Defaults to returning `{varName}`.
|
|
70
|
+
*/
|
|
71
|
+
onMissingVar?: (varName: string, key: string, locale: Locale) => string;
|
|
72
|
+
/**
|
|
73
|
+
* Called when a subscriber callback throws. Defaults to `console.error`.
|
|
74
|
+
* Override in production to route errors to a structured logger rather than the browser console.
|
|
75
|
+
*/
|
|
76
|
+
onSubscriberError?: (error: unknown) => void;
|
|
77
|
+
};
|
|
78
|
+
export type I18n<M extends Messages = Messages> = {
|
|
79
|
+
/** Delegates to `dispose()`. Enables `using` declarations. */
|
|
80
|
+
[Symbol.dispose](): void;
|
|
81
|
+
/** `AbortSignal` aborted when `dispose()` is called. Use to tie external lifetimes to this instance. */
|
|
82
|
+
readonly disposalSignal: AbortSignal;
|
|
83
|
+
/**
|
|
84
|
+
* Disposes this i18n instance: removes all subscribers and clears catalog, loader, and namespace state.
|
|
85
|
+
* After disposal, all mutation methods throw `LinguaDisposedError` and translation methods
|
|
86
|
+
* fall back to `onMissingKey` for every key. Idempotent.
|
|
87
|
+
*/
|
|
88
|
+
dispose(): void;
|
|
89
|
+
/** `true` after `dispose()` has been called. */
|
|
90
|
+
readonly disposed: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Registers a namespace factory and immediately starts loading it for the given locale
|
|
93
|
+
* (defaults to the active locale). Deduplicates concurrent and repeated calls.
|
|
94
|
+
*
|
|
95
|
+
* @remarks
|
|
96
|
+
* Call `registerNamespace()` first if you only want to register without loading.
|
|
97
|
+
* `extend()` is a convenience that does both in one call.
|
|
98
|
+
*
|
|
99
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* await i18n.extend('settings', (locale) =>
|
|
103
|
+
* import(`./locales/${locale}/settings.json`).then((m) => m.default),
|
|
104
|
+
* );
|
|
105
|
+
*/
|
|
106
|
+
extend(ns: string, factory: NamespaceFactory, locale?: Locale): Promise<void>;
|
|
107
|
+
/** Intl formatter bound to this instance's locale. Follows locale changes automatically. */
|
|
108
|
+
readonly fmt: Formatter;
|
|
109
|
+
/**
|
|
110
|
+
* Creates a derived instance that inherits the current catalog snapshot, loaders,
|
|
111
|
+
* namespace registry, and loaded-namespace markers, but has its own locale, fallback chain,
|
|
112
|
+
* and subscribers. Catalog mutations on the fork do not affect the parent.
|
|
113
|
+
*
|
|
114
|
+
* Resolved catalog entries are shared by reference (no template re-compilation), making
|
|
115
|
+
* `fork()` cheap for SSR fork-per-request patterns with large catalogs.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* // SSR: per-request locale without touching the shared instance
|
|
119
|
+
* const reqI18n = i18n.fork({ locale: req.locale });
|
|
120
|
+
*/
|
|
121
|
+
fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M>;
|
|
122
|
+
/** Returns the current snapshot. Object identity changes on every observable change. */
|
|
123
|
+
getSnapshot(): I18nSnapshot;
|
|
124
|
+
/**
|
|
125
|
+
* Extracts a serializable snapshot of all loaded catalogs and the active locale.
|
|
126
|
+
* Pass the result to `hydrateI18n()` on the client.
|
|
127
|
+
*
|
|
128
|
+
* **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet
|
|
129
|
+
* preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.
|
|
130
|
+
*
|
|
131
|
+
* **Warning:** The namespace registry is **not** serialized — factory functions cannot
|
|
132
|
+
* be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace
|
|
133
|
+
* before relying on namespace-patched keys.
|
|
134
|
+
*/
|
|
135
|
+
getState(): I18nState;
|
|
136
|
+
/**
|
|
137
|
+
* Returns all registered locales.
|
|
138
|
+
* - Default (no argument): locales in registration order.
|
|
139
|
+
* - `getSupportedLocales(true)`: sorted in ascending code-point order.
|
|
140
|
+
*/
|
|
141
|
+
getSupportedLocales(sorted?: boolean): Locale[];
|
|
142
|
+
/**
|
|
143
|
+
* Returns `true` if the given key exists in the active fallback chain — either as a leaf
|
|
144
|
+
* string key or as a plural branch (any key under `key.` prefix).
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* i18n.has('inbox') // true for leaf or pipe-plural expanded branch
|
|
148
|
+
* i18n.has('inbox.one') // true for explicit sub-key
|
|
149
|
+
*/
|
|
150
|
+
has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Returns `true` if the catalog for `locale` is fully resolved.
|
|
153
|
+
* Returns `false` for locales registered as async loaders not yet preloaded, and for unknown locales.
|
|
154
|
+
*/
|
|
155
|
+
isLoaded(locale: Locale): boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Returns `true` if the namespace has been fully loaded for the given locale.
|
|
158
|
+
* Returns `false` if it is not registered or not yet loaded for this locale.
|
|
159
|
+
*/
|
|
160
|
+
isNamespaceLoaded(ns: string, locale?: Locale): boolean;
|
|
161
|
+
/**
|
|
162
|
+
* Returns `true` if a namespace factory is registered under the given name.
|
|
163
|
+
*/
|
|
164
|
+
isNamespaceRegistered(ns: string): boolean;
|
|
165
|
+
/**
|
|
166
|
+
* Returns `true` if `locale` is in the known locale registry — either resolved or pending loader.
|
|
167
|
+
* Returns `false` for locales that have never been registered.
|
|
168
|
+
*/
|
|
169
|
+
isRegistered(locale: Locale): boolean;
|
|
170
|
+
/**
|
|
171
|
+
* Loads a previously registered namespace for the given locale (defaults to the active locale).
|
|
172
|
+
* Deduplicates concurrent and repeated calls.
|
|
173
|
+
*
|
|
174
|
+
* @throws `LinguaNamespaceMissingError` if the namespace has not been registered with `registerNamespace()` first.
|
|
175
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
176
|
+
*/
|
|
177
|
+
loadNamespace(ns: string, locale?: Locale): Promise<void>;
|
|
178
|
+
readonly locale: Locale;
|
|
179
|
+
preload(locale: Locale): Promise<void>;
|
|
180
|
+
/**
|
|
181
|
+
* Registers (or replaces) a locale source. If the source is an async loader, it is loaded
|
|
182
|
+
* immediately and this method returns a Promise that resolves when the load is complete.
|
|
183
|
+
* If the source is a static message object, it is synchronously registered and the returned
|
|
184
|
+
* Promise resolves immediately.
|
|
185
|
+
*
|
|
186
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
187
|
+
*/
|
|
188
|
+
register(locale: Locale, source: LocaleSource<M>): Promise<void>;
|
|
189
|
+
/**
|
|
190
|
+
* Registers a namespace factory without loading it. Use `loadNamespace()` to trigger loading,
|
|
191
|
+
* or use `extend()` to register and load in one call.
|
|
192
|
+
*
|
|
193
|
+
* @remarks
|
|
194
|
+
* Re-registering a namespace updates the factory for future loads but does **not** reload
|
|
195
|
+
* the namespace if it is already loaded. The new factory takes effect the next time the
|
|
196
|
+
* namespace marker is cleared (by a `register()` or `restoreState()` call).
|
|
197
|
+
*
|
|
198
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
199
|
+
*/
|
|
200
|
+
registerNamespace(ns: string, factory: NamespaceFactory): void;
|
|
201
|
+
/**
|
|
202
|
+
* Hydrates this instance with pre-loaded state (e.g. from a server-rendered payload).
|
|
203
|
+
*
|
|
204
|
+
* @remarks The namespace registry is **not** included in `I18nState`. After restoring,
|
|
205
|
+
* call `extend()` for each namespace before relying on namespace-patched keys.
|
|
206
|
+
*
|
|
207
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
208
|
+
* @throws `LinguaRestoreError` if the state's locale has no catalog.
|
|
209
|
+
*/
|
|
210
|
+
restoreState(state: I18nState): void;
|
|
211
|
+
/**
|
|
212
|
+
* Returns a scoped translator. All `t()` / `tp()` calls are automatically prefixed with `${prefix}.`.
|
|
213
|
+
* The returned object is memoized — calling `scope(prefix)` with the same string always returns the
|
|
214
|
+
* same reference.
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* const nav = i18n.scope('nav');
|
|
218
|
+
* nav.t('home'); // i18n.t('nav.home')
|
|
219
|
+
* nav.tp('items', 3); // i18n.tp('nav.items', 3)
|
|
220
|
+
*/
|
|
221
|
+
scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n;
|
|
222
|
+
/**
|
|
223
|
+
* Switches the active locale. Loads the locale if it is registered as an async loader.
|
|
224
|
+
* Last concurrent call wins; stale responses are discarded.
|
|
225
|
+
* If loading fails, the active locale is unchanged.
|
|
226
|
+
*
|
|
227
|
+
* @throws `LinguaMissingLocaleError` if the locale is not registered.
|
|
228
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
229
|
+
*/
|
|
230
|
+
setLocale(locale: Locale): Promise<void>;
|
|
231
|
+
/**
|
|
232
|
+
* Subscribes to locale/catalog changes.
|
|
233
|
+
* - `{ immediate: true }`: fires immediately and on every change.
|
|
234
|
+
* - `{ signal }`: unsubscribes when the AbortSignal fires.
|
|
235
|
+
*
|
|
236
|
+
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
237
|
+
*/
|
|
238
|
+
subscribe(callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe;
|
|
239
|
+
/** @security Returns raw, unsanitized strings. Sanitize before `innerHTML` insertion. */
|
|
240
|
+
t(key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string;
|
|
241
|
+
/**
|
|
242
|
+
* Translates a plural branch key. `count` is injected automatically.
|
|
243
|
+
*
|
|
244
|
+
* @throws `LinguaInvalidCountError` if `count` is not finite.
|
|
245
|
+
* @throws `LinguaCountInVarsError` if `options.vars.count` is set.
|
|
246
|
+
* @security Returns raw, unsanitized strings.
|
|
247
|
+
*/
|
|
248
|
+
tp(key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string;
|
|
249
|
+
};
|
|
250
|
+
//# sourceMappingURL=i18n-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"i18n-types.d.ts","sourceRoot":"","sources":["../src/i18n-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE1C,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAC5B,MAAM,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC;AAErC,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC7D,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEpD;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yFAAyF;IACzF,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,aAAa,KAAK,MAAM,CAAC;IAC1D,QAAQ,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,MAAM,EA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,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,WAAW,CAAC;IAC/F,yFAAyF;IACzF,CAAC,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;IACzE;;;;;;OAMG;IACH,EAAE,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;CAC3F,CAAC"}
|
package/dist/i18n.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./format.cjs"),t=require("./_dev.cjs"),n=require("./template.cjs"),r=require("./_catalog.cjs"),i=require("./errors.cjs"),a=require("./_catalog-store.cjs"),o=require("./_chain.cjs"),s=require("./_namespace-store.cjs");function c(e,t,n){let{chain:r,set:i}=o.buildLocaleChain(e,t,n);return{chain:r,chainSet:i,locale:e}}function l(e,t,n,r){let i=[];return!r&&n===0&&i.push(`${e}.zero`),(t!==`zero`||r)&&i.push(`${e}.${t}`),t!==`other`&&i.push(`${e}.other`),i}function u(e){return d(e)}function d(u,f){let p=u??{},m=o.createLocaleCaches(),h=e=>o.canon(e,m),g=Array.isArray(p.fallback)?p.fallback.map(h):p.fallback?[h(p.fallback)]:[],_=!1,v=new AbortController,y=a.createCatalogStore(()=>_),b=s.createNamespaceStore(()=>_),x=c(h(p.locale??`en`),g,m),S=new Set,C=p.onMissingKey??(e=>e),
|
|
1
|
+
const e=require("./format.cjs"),t=require("./_dev.cjs"),n=require("./template.cjs"),r=require("./_catalog.cjs"),i=require("./errors.cjs"),a=require("./_catalog-store.cjs"),o=require("./_chain.cjs"),s=require("./_namespace-store.cjs");function c(e,t,n){let{chain:r,set:i}=o.buildLocaleChain(e,t,n);return{chain:r,chainSet:i,locale:e}}function l(e,t,n,r){let i=[];return!r&&n===0&&i.push(`${e}.zero`),(t!==`zero`||r)&&i.push(`${e}.${t}`),t!==`other`&&i.push(`${e}.other`),i}function u(e){return d(e)}function d(u,f){let p=u??{},m=o.createLocaleCaches(),h=e=>o.canon(e,m),g=Array.isArray(p.fallback)?p.fallback.map(h):p.fallback?[h(p.fallback)]:[],_=!1,v=new AbortController,y=a.createCatalogStore(()=>_),b=s.createNamespaceStore(()=>_),x=c(h(p.locale??`en`),g,m),S=new Set,C=new Set,w=p.onMissingKey??(e=>e),T=p.onMissingVar??(e=>`{${e}}`),E=p.onSubscriberError??(e=>t.error(`subscriber error`,e)),D,O=new Map,k=()=>(D||=e.createFormatter(()=>x.locale),D),A=e=>{for(let t of x.chain){let n=y.resolve(t)?.get(e);if(n!==void 0)return n}},j=e=>{if(A(e)!==void 0)return!0;for(let t of x.chain){let n=y.resolve(t);if(n&&n.prefixes.has(e))return!0}return!1},M=(e,t,r)=>n.renderTemplate(t.compiled,r,e,x.locale,T),N=(e,t)=>{let n=String(e),r=A(n);return r?M(n,r,t):w(n,x.locale)},P=(e,t,n)=>{if(!Number.isFinite(t))throw new i.LinguaInvalidCountError("`count` must be a finite number.");let r=n?.vars,a=n?.ordinal??!1;if(r&&Object.hasOwn(r,`count`))throw new i.LinguaCountInVarsError("`tp` does not allow `vars.count`; `count` is injected automatically.");let s=String(e),c=r?{count:t,...r}:{count:t};for(let e of x.chain){let n=y.resolve(e);if(!n)continue;let r=l(s,o.selectPluralForm(e,t,a,m),t,a);for(let e of r){let t=n.get(e);if(t!==void 0)return M(e,t,c)}}return w(s,x.locale)},F={locale:x.locale,t:N,tp:P},I=()=>{F={locale:x.locale,t:N,tp:P};let e=[...S];for(let t of e)try{t(F)}catch(e){E(e)}};if(y.onChange=e=>{x.chainSet.has(e)&&I()},f?.catalogStore&&y.seedFrom(f.catalogStore.catalogs,f.catalogStore.pendingLoaders),f?.nsStore&&b.seedFrom(f.nsStore),p.catalogs){let e=new Map,t=new Map;for(let[n,i]of Object.entries(p.catalogs)){let a=h(n);if(typeof i==`function`)t.set(a,i);else{let t=new r.CatalogEntry;t.setAll(r.flattenStrings(i)),e.set(a,t)}}y.seedFrom(e,t)}let L=e=>y.preload(h(e)),R=0;return{get disposalSignal(){return v.signal},dispose(){if(!_){_=!0,v.abort();for(let e of[...C])e();C.clear(),S.clear(),y.dispose(),b.dispose(),O.clear()}},get disposed(){return _},extend(e,t,n){i.checkDisposed(_),b.registerNamespace(e,t);let r=n?h(n):x.locale;return b.loadNamespace(e,r,(e,t)=>y.patch(e,t))},get fmt(){return k()},fork(e){return d({fallback:e?.fallback??(g.length>0?g:void 0),locale:e?.locale??x.locale,onMissingKey:e?.onMissingKey??p.onMissingKey,onMissingVar:e?.onMissingVar??p.onMissingVar,onSubscriberError:e?.onSubscriberError??p.onSubscriberError},{catalogStore:y,nsStore:b})},getSnapshot(){return F},getState(){let e={};for(let[t,n]of y.catalogs)e[t]=Object.fromEntries([...n.entries.entries()].map(([e,{message:t}])=>[e,t]));return{catalogs:e,locale:x.locale}},getSupportedLocales(e){let t=[...y.knownLocales()];return e===!0?t.sort():t},has(e){return j(String(e))},isLoaded(e){try{return y.isLoaded(h(e))}catch{return!1}},isNamespaceLoaded(e,t){if(!t)return b.isLoaded(e,x.locale);try{return b.isLoaded(e,h(t))}catch{return!1}},isNamespaceRegistered(e){return b.isRegistered(e)},isRegistered(e){try{return y.isRegistered(h(e))}catch{return!1}},loadNamespace(e,t){let n=t?h(t):x.locale;return b.loadNamespace(e,n,(e,t)=>y.patch(e,t))},get locale(){return x.locale},preload:L,register(e,t){let n=h(e);return y.register(n,t,b)},registerNamespace(e,t){b.registerNamespace(e,t)},restoreState(e){if(i.checkDisposed(_),!Object.hasOwn(e.catalogs,e.locale))throw new i.LinguaRestoreError(`restoreState: locale "${e.locale}" has no catalog in the provided state.`);let t=new Map,n=y.knownLocales();for(let e of n)b.clearLocale(e);for(let[n,i]of Object.entries(e.catalogs)){let e=h(n),a=new r.CatalogEntry;a.setAll(Object.entries(i)),t.set(e,a)}y.dispose(),y.onChange=e=>{x.chainSet.has(e)&&I()},y.seedFrom(t,new Map),x=c(h(e.locale),g,m),D?.clear(),I()},scope(e){let t=String(e),n=O.get(t);if(n)return n;let r={get fmt(){return k()},has:e=>j(`${t}.${e}`),t:(e,n)=>N(`${t}.${e}`,n),tp:(e,n,r)=>P(`${t}.${e}`,n,r)};return O.set(t,r),r},async setLocale(e){i.checkDisposed(_);let t=h(e);if(x.locale===t)return;let n=++R;await L(t),!(_||R!==n)&&(x=c(t,g,m),D?.clear(),I())},subscribe:(e,t)=>{let n=t?.signal,r=()=>{S.delete(e),n?.removeEventListener(`abort`,r),C.delete(r)};if(_)throw new i.LinguaDisposedError;if(n?.aborted)return r;if(t?.immediate===!0)try{e(F)}catch(e){return E(e),r}return S.add(e),n?.addEventListener(`abort`,r,{once:!0}),C.add(r),r},[Symbol.dispose](){this.dispose()},t:N,tp:P}}function f(e){return e.getState()}function p(e,t){e.restoreState(t)}exports.LinguaCountInVarsError=i.LinguaCountInVarsError,exports.LinguaDisposedError=i.LinguaDisposedError,exports.LinguaError=i.LinguaError,exports.LinguaInvalidCountError=i.LinguaInvalidCountError,exports.LinguaInvalidLocaleError=i.LinguaInvalidLocaleError,exports.LinguaMissingLocaleError=i.LinguaMissingLocaleError,exports.LinguaNamespaceMissingError=i.LinguaNamespaceMissingError,exports.LinguaRestoreError=i.LinguaRestoreError,exports.createI18n=u,exports.hydrateI18n=p,exports.serializeI18n=f;
|
|
2
2
|
//# sourceMappingURL=i18n.cjs.map
|
package/dist/i18n.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.cjs","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import { CatalogEntry, type Messages, flattenStrings } from './_catalog';\nimport { type CatalogStore, type Loader, type LocaleSource, createCatalogStore } from './_catalog-store';\nimport { type LocaleCaches, buildLocaleChain, canon, createLocaleCaches, selectPluralForm } from './_chain';\nimport { error as logError } from './_dev';\nimport { type NamespaceFactory, type NamespaceStore, createNamespaceStore } from './_namespace-store';\nimport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaInvalidCountError,\n LinguaRestoreError,\n checkDisposed,\n} from './errors';\nimport { type Formatter, createFormatter } from './format';\nimport { type CompiledTemplate, renderTemplate } from './template';\n\nexport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCountError,\n LinguaInvalidLocaleError,\n LinguaMissingLocaleError,\n LinguaNamespaceMissingError,\n LinguaRestoreError,\n} from './errors';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport type Locale = string;\nexport type Unsubscribe = () => void;\n\nexport type { Messages } from './_catalog';\nexport type { Loader, LocaleSource } from './_catalog-store';\nexport type { NamespaceFactory } from './_namespace-store';\n\nexport type TranslateVars = Record<string, unknown>;\n\n/**\n * A snapshot of the i18n instance state at a point in time.\n * Object identity changes on every observable change (locale switch, catalog load).\n * `t` and `tp` are bound to the locale captured in this snapshot.\n */\nexport type I18nSnapshot = {\n readonly locale: Locale;\n /** @security Returns raw, unsanitized strings. Sanitize before `innerHTML` insertion. */\n readonly t: (key: string, vars?: TranslateVars) => string;\n readonly tp: (key: string, count: number, options?: TpOptions) => string;\n};\n\n/** Shape of the serialised state produced by `serializeI18n()`. Pass to `hydrateI18n()` on the client. */\nexport type I18nState = {\n readonly catalogs: Record<Locale, Record<string, string>>;\n readonly locale: Locale;\n};\n\nexport type SubscribeOptions = {\n immediate?: boolean;\n /** AbortSignal — automatically unsubscribes when the signal is aborted. */\n signal?: AbortSignal;\n};\n\nexport type TpOptions = {\n /** Use ordinal plural rules (1st, 2nd, 3rd) instead of cardinal (default: `false`). */\n ordinal?: boolean;\n /** Inject additional interpolation variables alongside the automatically injected `count`. */\n vars?: TranslateVars;\n};\n\nexport type ScopedI18n = {\n /** Intl formatter inherited from the parent instance. Follows locale changes automatically. */\n readonly fmt: Formatter;\n has(key: string): boolean;\n t(key: string, vars?: TranslateVars): string;\n tp(key: string, count: number, options?: TpOptions): string;\n};\n\n// ─── Key inference ────────────────────────────────────────────────────────────\n// Depth tuple prevents infinite recursion on recursive `Messages` type.\n// Depth 7 covers real-world catalog nesting without measurable TS instantiation cost.\ntype Depth = [never, 0, 1, 2, 3, 4, 5, 6];\n\nexport type MessageLeafKeys<T, P extends string = '', D extends number = 7> = [D] extends [0]\n ? never\n : T extends string\n ? P\n : T extends Record<string, unknown>\n ? { [K in string & keyof T]: MessageLeafKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]> }[string & keyof T]\n : never;\n\nexport type MessageBranchKeys<T, P extends string = '', D extends number = 7> = [D] extends [0]\n ? never\n : T extends Record<string, unknown>\n ? {\n [K in string & keyof T]: T[K] extends string\n ? never\n : (P extends '' ? K : `${P}.${K}`) | MessageBranchKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]>;\n }[string & keyof T]\n : never;\n\n// ─── Config ───────────────────────────────────────────────────────────────────\n\nexport type I18nOptions<M extends Messages = Messages> = {\n /** Locale registry. Values can be static message objects or async loaders. */\n catalogs?: Record<Locale, LocaleSource<M>>;\n /** Locale(s) to search when the active locale is missing a key. Subtags are expanded automatically (e.g. `en-US` → `en`). */\n fallback?: Locale | Locale[];\n /** Initial active locale. Defaults to `\"en\"`. Canonicalized via `Intl.getCanonicalLocales`. */\n locale?: Locale;\n /**\n * Called when a translation key is missing.\n * Defaults to returning the key string.\n *\n * @security The default handler returns `key` verbatim. Do not render the return value as HTML\n * if keys are constructed from untrusted user input.\n */\n onMissingKey?: (key: string, locale: Locale) => string;\n /**\n * Called when an interpolation variable is missing.\n * Defaults to returning `{varName}`.\n */\n onMissingVar?: (varName: string, key: string, locale: Locale) => string;\n /**\n * Called when a subscriber callback throws. Defaults to `console.error`.\n * Override in production to route errors to a structured logger rather than the browser console.\n */\n onSubscriberError?: (error: unknown) => void;\n};\n\n// ─── Public interface ─────────────────────────────────────────────────────────\n\nexport type I18n<M extends Messages = Messages> = {\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n /** `AbortSignal` aborted when `dispose()` is called. Use to tie external lifetimes to this instance. */\n readonly disposalSignal: AbortSignal;\n /**\n * Disposes this i18n instance: removes all subscribers and clears catalog, loader, and namespace state.\n * After disposal, all mutation methods throw `LinguaDisposedError` and translation methods\n * fall back to `onMissingKey` for every key. Idempotent.\n */\n dispose(): void;\n /** `true` after `dispose()` has been called. */\n readonly disposed: boolean;\n /**\n * Registers a namespace factory and immediately starts loading it for the given locale\n * (defaults to the active locale). Deduplicates concurrent and repeated calls.\n *\n * @remarks\n * Call `registerNamespace()` first if you only want to register without loading.\n * `extend()` is a convenience that does both in one call.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n *\n * @example\n * await i18n.extend('settings', (locale) =>\n * import(`./locales/${locale}/settings.json`).then((m) => m.default),\n * );\n */\n extend(ns: string, factory: NamespaceFactory, locale?: Locale): Promise<void>;\n /** Intl formatter bound to this instance's locale. Follows locale changes automatically. */\n readonly fmt: Formatter;\n /**\n * Creates a derived instance that inherits the current catalog snapshot, loaders,\n * namespace registry, and loaded-namespace markers, but has its own locale, fallback chain,\n * and subscribers. Catalog mutations on the fork do not affect the parent.\n *\n * Resolved catalog entries are shared by reference (no template re-compilation), making\n * `fork()` cheap for SSR fork-per-request patterns with large catalogs.\n *\n * @example\n * // SSR: per-request locale without touching the shared instance\n * const reqI18n = i18n.fork({ locale: req.locale });\n */\n fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M>;\n /** Returns the current snapshot. Object identity changes on every observable change. */\n getSnapshot(): I18nSnapshot;\n /**\n * Extracts a serializable snapshot of all loaded catalogs and the active locale.\n * Pass the result to `hydrateI18n()` on the client.\n *\n * **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet\n * preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.\n *\n * **Warning:** The namespace registry is **not** serialized — factory functions cannot\n * be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace\n * before relying on namespace-patched keys.\n */\n getState(): I18nState;\n /**\n * Returns all registered locales.\n * - Default (no argument): locales in registration order.\n * - `getSupportedLocales(true)`: sorted in ascending code-point order.\n */\n getSupportedLocales(sorted?: boolean): Locale[];\n /**\n * Returns `true` if the given key exists in the active fallback chain — either as a leaf\n * string key or as a plural branch (any key under `key.` prefix).\n *\n * @example\n * i18n.has('inbox') // true for leaf or pipe-plural expanded branch\n * i18n.has('inbox.one') // true for explicit sub-key\n */\n has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean;\n /**\n * Returns `true` if the catalog for `locale` is fully resolved.\n * Returns `false` for locales registered as async loaders not yet preloaded, and for unknown locales.\n */\n isLoaded(locale: Locale): boolean;\n /**\n * Returns `true` if the namespace has been fully loaded for the given locale.\n * Returns `false` if it is not registered or not yet loaded for this locale.\n */\n isNamespaceLoaded(ns: string, locale?: Locale): boolean;\n /**\n * Returns `true` if a namespace factory is registered under the given name.\n */\n isNamespaceRegistered(ns: string): boolean;\n /**\n * Returns `true` if `locale` is in the known locale registry — either resolved or pending loader.\n * Returns `false` for locales that have never been registered.\n */\n isRegistered(locale: Locale): boolean;\n /**\n * Loads a previously registered namespace for the given locale (defaults to the active locale).\n * Deduplicates concurrent and repeated calls.\n *\n * @throws `LinguaNamespaceMissingError` if the namespace has not been registered with `registerNamespace()` first.\n * @throws `LinguaDisposedError` if called on a disposed instance.\n */\n loadNamespace(ns: string, locale?: Locale): Promise<void>;\n readonly locale: Locale;\n preload(locale: Locale): Promise<void>;\n /**\n * Registers (or replaces) a locale source. If the source is an async loader, it is loaded\n * immediately and this method returns a Promise that resolves when the load is complete.\n * If the source is a static message object, it is synchronously registered and the returned\n * Promise resolves immediately.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n */\n register(locale: Locale, source: LocaleSource<M>): Promise<void>;\n /**\n * Registers a namespace factory without loading it. Use `loadNamespace()` to trigger loading,\n * or use `extend()` to register and load in one call.\n *\n * @remarks\n * Re-registering a namespace updates the factory for future loads but does **not** reload\n * the namespace if it is already loaded. The new factory takes effect the next time the\n * namespace marker is cleared (by a `register()` or `restoreState()` call).\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n */\n registerNamespace(ns: string, factory: NamespaceFactory): void;\n /**\n * Hydrates this instance with pre-loaded state (e.g. from a server-rendered payload).\n *\n * @remarks The namespace registry is **not** included in `I18nState`. After restoring,\n * call `extend()` for each namespace before relying on namespace-patched keys.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n * @throws `LinguaRestoreError` if the state's locale has no catalog.\n */\n restoreState(state: I18nState): void;\n /**\n * Returns a scoped translator. All `t()` / `tp()` calls are automatically prefixed with `${prefix}.`.\n * The returned object is memoized — calling `scope(prefix)` with the same string always returns the\n * same reference.\n *\n * @example\n * const nav = i18n.scope('nav');\n * nav.t('home'); // i18n.t('nav.home')\n * nav.tp('items', 3); // i18n.tp('nav.items', 3)\n */\n scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n;\n /**\n * Switches the active locale. Loads the locale if it is registered as an async loader.\n * Last concurrent call wins; stale responses are discarded.\n * If loading fails, the active locale is unchanged.\n *\n * @throws `LinguaMissingLocaleError` if the locale is not registered.\n * @throws `LinguaDisposedError` if called on a disposed instance.\n */\n setLocale(locale: Locale): Promise<void>;\n /**\n * Subscribes to locale/catalog changes.\n * - `{ immediate: true }`: fires immediately and on every change.\n * - `{ signal }`: unsubscribes when the AbortSignal fires.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n */\n subscribe(callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe;\n /** @security Returns raw, unsanitized strings. Sanitize before `innerHTML` insertion. */\n t(key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string;\n /**\n * Translates a plural branch key. `count` is injected automatically.\n *\n * @throws `LinguaInvalidCountError` if `count` is not finite.\n * @throws `LinguaCountInVarsError` if `options.vars.count` is set.\n * @security Returns raw, unsanitized strings.\n */\n tp(key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string;\n};\n\n// ─── Locale state ─────────────────────────────────────────────────────────────\n// Replaced atomically on every locale change.\n\ntype LocaleState = {\n readonly chain: readonly Locale[];\n readonly chainSet: ReadonlySet<Locale>;\n readonly locale: Locale;\n};\n\nfunction buildState(locale: Locale, fallback: Locale[], caches: LocaleCaches): LocaleState {\n const { chain, set } = buildLocaleChain(locale, fallback, caches);\n\n return { chain, chainSet: set, locale };\n}\n\n// ─── Plural key priority ──────────────────────────────────────────────────────\n// Cardinal zero: try .zero override first, then CLDR form, then .other as final fallback.\n// Ordinal / non-zero: try CLDR form, then .other as final fallback.\nfunction pluralKeyPriority(base: string, form: string, count: number, ordinal: boolean): string[] {\n const keys: string[] = [];\n\n if (!ordinal && count === 0) keys.push(`${base}.zero`);\n\n if (form !== 'zero' || ordinal) keys.push(`${base}.${form}`);\n\n if (form !== 'other') keys.push(`${base}.other`);\n\n return keys;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/** Overload: explicit type parameter (strict typing) */\nexport function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;\n/** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */\nexport function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;\nexport function createI18n<M extends Messages = Messages>(config?: I18nOptions<M>): I18n<M> {\n return _createI18nImpl<M>(config);\n}\n\n// ─── Internal seed shape ──────────────────────────────────────────────────────\n\ntype I18nSeed<M extends Messages> = {\n catalogStore?: CatalogStore<M>;\n nsStore?: NamespaceStore;\n};\n\nfunction _createI18nImpl<M extends Messages = Messages>(config?: I18nOptions<M>, _seed?: I18nSeed<M>): I18n<M> {\n const cfg: I18nOptions<M> = config ?? {};\n\n // ─── Per-instance caches (no shared module-level state) ───────────────────\n const caches: LocaleCaches = createLocaleCaches();\n\n const canonL = (loc: string) => canon(loc, caches);\n\n const fallback = Array.isArray(cfg.fallback) ? cfg.fallback.map(canonL) : cfg.fallback ? [canonL(cfg.fallback)] : [];\n\n // ─── Disposal ─────────────────────────────────────────────────────────────\n let disposed = false;\n const disposeController = new AbortController();\n\n // ─── Bounded stores ───────────────────────────────────────────────────────\n const catalogStore: CatalogStore<M> = createCatalogStore(() => disposed);\n const nsStore: NamespaceStore = createNamespaceStore(() => disposed);\n\n // ─── Locale state ─────────────────────────────────────────────────────────\n let state: LocaleState = buildState(canonL(cfg.locale ?? 'en'), fallback, caches);\n\n // ─── Subscribers ──────────────────────────────────────────────────────────\n const subscribers = new Set<(snapshot: I18nSnapshot) => void>();\n\n const onMissingKey = cfg.onMissingKey ?? ((key: string) => key);\n const onMissingVar = cfg.onMissingVar ?? ((varName: string) => `{${varName}}`);\n const onSubscriberError = cfg.onSubscriberError ?? ((error: unknown) => logError('subscriber error', error));\n\n // ─── Lazy formatter — avoids Intl overhead for SSR forks that only need t(). ──\n let _fmt: Formatter | undefined;\n\n // ─── Scope cache — stable object references per prefix for reactive framework renders. ──\n const scopeCache = new Map<string, ScopedI18n>();\n\n const getFormatter = (): Formatter => {\n if (!_fmt) _fmt = createFormatter(() => state.locale);\n\n return _fmt;\n };\n\n // ─── Translate helpers ────────────────────────────────────────────────────\n\n // Single-pass entry lookup across the active fallback chain.\n const findEntry = (key: string): { compiled: CompiledTemplate; message: string } | undefined => {\n for (const candidate of state.chain) {\n const found = catalogStore.resolve(candidate)?.get(key);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n };\n\n // Shared by has() and scope().has() — true if `base` exists as a leaf key or a plural branch prefix.\n const hasKey = (base: string): boolean => {\n if (findEntry(base) !== undefined) return true;\n\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n if (catalog.prefixes.has(base)) return true;\n }\n\n return false;\n };\n\n const interpolate = (\n key: string,\n found: { compiled: CompiledTemplate; message: string },\n vars: TranslateVars | undefined,\n ): string => renderTemplate(found.compiled, vars, key, state.locale, onMissingVar);\n\n const translate = (key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string => {\n const base = String(key);\n const found = findEntry(base);\n\n if (!found) return onMissingKey(base, state.locale);\n\n return interpolate(base, found, vars);\n };\n\n const translatePlural = (key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string => {\n if (!Number.isFinite(count)) {\n throw new LinguaInvalidCountError('`count` must be a finite number.');\n }\n\n const vars = options?.vars;\n const ordinal = options?.ordinal ?? false;\n\n if (vars && Object.hasOwn(vars, 'count')) {\n throw new LinguaCountInVarsError('`tp` does not allow `vars.count`; `count` is injected automatically.');\n }\n\n const base = String(key);\n const mergedVars = vars ? { count, ...vars } : { count };\n\n // Walk the fallback chain locale-by-locale, selecting CLDR plural form using each\n // locale's own rules. This ensures cross-locale fallbacks produce grammatically correct forms.\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n const form = selectPluralForm(candidate, count, ordinal, caches);\n const keys = pluralKeyPriority(base, form, count, ordinal);\n\n for (const k of keys) {\n const found = catalog.get(k);\n\n if (found !== undefined) {\n return interpolate(k, found, mergedVars);\n }\n }\n }\n\n return onMissingKey(base, state.locale);\n };\n\n // ─── bump() ───────────────────────────────────────────────────────────────\n // Rebuilds the snapshot and notifies all current subscribers.\n\n let snapshot: I18nSnapshot = {\n locale: state.locale,\n t: translate,\n tp: translatePlural,\n };\n\n const bump = (): void => {\n snapshot = { locale: state.locale, t: translate, tp: translatePlural };\n\n const listeners = [...subscribers];\n\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch (error) {\n onSubscriberError(error);\n }\n }\n };\n\n // ─── Wire catalog store onChange → bump ───────────────────────────────────\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n\n // ─── Seed from parent fork ─────────────────────────────────────────────────\n if (_seed?.catalogStore) {\n catalogStore.seedFrom(_seed.catalogStore.catalogs, _seed.catalogStore.pendingLoaders);\n }\n\n if (_seed?.nsStore) {\n nsStore.seedFrom(_seed.nsStore);\n }\n\n // ─── Initial catalogs from config ─────────────────────────────────────────\n if (cfg.catalogs) {\n const staticEntries = new Map<Locale, CatalogEntry>();\n const loaderEntries = new Map<Locale, Loader<M>>();\n\n for (const [loc, source] of Object.entries(cfg.catalogs)) {\n const normalized = canonL(loc);\n\n if (typeof source === 'function') {\n loaderEntries.set(normalized, source as Loader<M>);\n } else {\n const entry = new CatalogEntry();\n\n entry.setAll(flattenStrings(source as M));\n staticEntries.set(normalized, entry);\n }\n }\n\n // Use seedFrom for zero-overhead init (no bump, no notifications during setup)\n catalogStore.seedFrom(staticEntries, loaderEntries);\n }\n\n // ─── Preload helper ───────────────────────────────────────────────────────\n\n const preload = (loc: Locale): Promise<void> => catalogStore.preload(canonL(loc));\n\n // ─── Monotonic generation counter — last writer wins for concurrent setLocale() ──\n let switchGen = 0;\n\n // ─── Subscribe helper ─────────────────────────────────────────────────────\n\n const subscribeInternal = (callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe => {\n const unsubscribe = (): void => {\n subscribers.delete(callback);\n };\n\n if (disposed) throw new LinguaDisposedError();\n\n if (options?.signal?.aborted) return unsubscribe;\n\n if (options?.immediate === true) {\n try {\n callback(snapshot);\n } catch (error) {\n onSubscriberError(error);\n\n return unsubscribe;\n }\n }\n\n subscribers.add(callback);\n options?.signal?.addEventListener('abort', unsubscribe, { once: true });\n\n return unsubscribe;\n };\n\n // ─── Public object ─────────────────────────────────────────────────────────\n\n return {\n get disposalSignal(): AbortSignal {\n return disposeController.signal;\n },\n\n dispose(): void {\n if (disposed) return;\n\n disposed = true;\n disposeController.abort();\n subscribers.clear();\n catalogStore.dispose();\n nsStore.dispose();\n scopeCache.clear();\n },\n\n get disposed(): boolean {\n return disposed;\n },\n\n extend(ns: string, factory: NamespaceFactory, loc?: Locale): Promise<void> {\n checkDisposed(disposed);\n\n nsStore.registerNamespace(ns, factory);\n\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get fmt(): Formatter {\n return getFormatter();\n },\n\n fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M> {\n return _createI18nImpl(\n {\n fallback: overrides?.fallback ?? (fallback.length > 0 ? fallback : undefined),\n locale: overrides?.locale ?? state.locale,\n onMissingKey: overrides?.onMissingKey ?? cfg.onMissingKey,\n onMissingVar: overrides?.onMissingVar ?? cfg.onMissingVar,\n onSubscriberError: overrides?.onSubscriberError ?? cfg.onSubscriberError,\n },\n {\n catalogStore: catalogStore as CatalogStore<M>,\n nsStore: nsStore as NamespaceStore,\n },\n );\n },\n\n getSnapshot() {\n return snapshot;\n },\n\n getState(): I18nState {\n const catalogsOut: Record<Locale, Record<string, string>> = {};\n\n for (const [loc, entry] of catalogStore.catalogs) {\n catalogsOut[loc] = Object.fromEntries([...entry.entries.entries()].map(([k, { message }]) => [k, message]));\n }\n\n return { catalogs: catalogsOut, locale: state.locale };\n },\n\n getSupportedLocales(sorted?: boolean): Locale[] {\n const locales = [...catalogStore.knownLocales()];\n\n return sorted === true ? locales.sort() : locales;\n },\n\n has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean {\n return hasKey(String(key));\n },\n\n isLoaded(loc: Locale): boolean {\n try {\n return catalogStore.isLoaded(canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceLoaded(ns: string, loc?: Locale): boolean {\n return nsStore.isLoaded(ns, loc ? canonL(loc) : state.locale);\n },\n\n isNamespaceRegistered(ns: string): boolean {\n return nsStore.isRegistered(ns);\n },\n\n isRegistered(loc: Locale): boolean {\n try {\n return catalogStore.isRegistered(canonL(loc));\n } catch {\n return false;\n }\n },\n\n loadNamespace(ns: string, loc?: Locale): Promise<void> {\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get locale(): Locale {\n return state.locale;\n },\n\n preload,\n\n register(loc: Locale, source: LocaleSource<M>): Promise<void> {\n const normalized = canonL(loc);\n\n return catalogStore.register(normalized, source, nsStore);\n },\n\n registerNamespace(ns: string, factory: NamespaceFactory): void {\n nsStore.registerNamespace(ns, factory);\n },\n\n restoreState(st: I18nState): void {\n checkDisposed(disposed);\n\n if (!Object.hasOwn(st.catalogs, st.locale)) {\n throw new LinguaRestoreError(`restoreState: locale \"${st.locale}\" has no catalog in the provided state.`);\n }\n\n const freshEntries = new Map<Locale, CatalogEntry>();\n\n for (const [loc, flatCatalog] of Object.entries(st.catalogs)) {\n const normalized = canonL(loc);\n const entry = new CatalogEntry();\n\n entry.setAll(Object.entries(flatCatalog));\n freshEntries.set(normalized, entry);\n nsStore.clearLocale(normalized);\n }\n\n // Dispose and re-seed the catalog store with the restored entries.\n // onChange is re-wired immediately after dispose.\n catalogStore.dispose();\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n catalogStore.seedFrom(freshEntries, new Map());\n\n const normalized = canonL(st.locale);\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n {\n const pre = String(prefix);\n const cached = scopeCache.get(pre);\n\n if (cached) return cached;\n\n const scoped: ScopedI18n = {\n get fmt() {\n return getFormatter();\n },\n has: (key) => hasKey(`${pre}.${key}`),\n t: (key, vars?) => translate(`${pre}.${key}`, vars),\n tp: (key, count, options?) => translatePlural(`${pre}.${key}`, count, options),\n };\n\n scopeCache.set(pre, scoped);\n\n return scoped;\n },\n\n async setLocale(next: Locale): Promise<void> {\n checkDisposed(disposed);\n\n const normalized = canonL(next);\n\n if (state.locale === normalized) return;\n\n // Monotonic generation counter — last writer wins.\n const gen = ++switchGen;\n\n await preload(normalized);\n\n if (disposed || switchGen !== gen) return;\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n subscribe: subscribeInternal,\n\n [Symbol.dispose](): void {\n this.dispose();\n },\n\n t: translate,\n\n tp: translatePlural,\n };\n}\n\n// ─── SSR standalone helpers ───────────────────────────────────────────────────\n\n/**\n * Serialises the currently loaded catalogs and active locale into a plain object.\n * Pass the result to `hydrateI18n()` on the client.\n *\n * Prefer calling `i18n.getState()` directly — these standalone functions are provided\n * for convenience when you receive a plain `I18n` reference without the full type.\n *\n * **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet\n * preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.\n *\n * **Warning:** The namespace registry is **not** serialized — factory functions cannot\n * be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace\n * before relying on namespace-patched keys.\n */\nexport function serializeI18n(i18n: I18n): I18nState {\n return i18n.getState();\n}\n\n/**\n * Hydrates an i18n instance with pre-loaded state (e.g. from a server-rendered payload).\n *\n * Prefer calling `i18n.restoreState(state)` directly — these standalone functions are\n * provided for convenience.\n *\n * @remarks The namespace registry is **not** included in `I18nState`. After hydrating,\n * call `extend()` for each namespace before relying on namespace-patched keys.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n * @throws `LinguaRestoreError` if the state's locale has no catalog.\n */\nexport function hydrateI18n(i18n: I18n, state: I18nState): void {\n i18n.restoreState(state);\n}\n"],"mappings":"0OAwTA,SAAS,EAAW,EAAgB,EAAoB,EAAmC,CACzF,GAAM,CAAE,QAAO,OAAQ,EAAA,iBAAiB,EAAQ,EAAU,CAAM,EAEhE,MAAO,CAAE,QAAO,SAAU,EAAK,QAAO,CACxC,CAKA,SAAS,EAAkB,EAAc,EAAc,EAAe,EAA4B,CAChG,IAAM,EAAiB,CAAC,EAQxB,MANI,CAAC,GAAW,IAAU,GAAG,EAAK,KAAK,GAAG,EAAK,MAAM,GAEjD,IAAS,QAAU,IAAS,EAAK,KAAK,GAAG,EAAK,GAAG,GAAM,EAEvD,IAAS,SAAS,EAAK,KAAK,GAAG,EAAK,OAAO,EAExC,CACT,CA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EAAY,OAGjC,IAAM,EAAM,EAAE,EAEd,MAAM,EAAQ,CAAU,EAEpB,KAAY,IAAc,KAE9B,EAAQ,EAAW,EAAY,EAAU,CAAM,EAC/C,GAAM,MAAM,EACZ,EAAK,EACP,EAEA,WA3NyB,EAA4C,IAA4C,CACjH,IAAM,MAA0B,CAC9B,EAAY,OAAO,CAAQ,CAC7B,EAEA,GAAI,EAAU,MAAM,IAAI,EAAA,oBAExB,GAAI,GAAS,QAAQ,QAAS,OAAO,EAErC,GAAI,GAAS,YAAc,GACzB,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAGd,OAFA,EAAkB,CAAK,EAEhB,CACT,CAMF,OAHA,EAAY,IAAI,CAAQ,EACxB,GAAS,QAAQ,iBAAiB,QAAS,EAAa,CAAE,KAAM,EAAK,CAAC,EAE/D,CACT,EAsME,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,EAEA,EAAG,EAEH,GAAI,CACN,CACF,CAkBA,SAAgB,EAAc,EAAuB,CACnD,OAAO,EAAK,SAAS,CACvB,CAcA,SAAgB,EAAY,EAAY,EAAwB,CAC9D,EAAK,aAAa,CAAK,CACzB"}
|
|
1
|
+
{"version":3,"file":"i18n.cjs","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import type {\n I18n,\n I18nOptions,\n I18nSnapshot,\n I18nState,\n Locale,\n MessageBranchKeys,\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\n\nimport { CatalogEntry, type Messages, flattenStrings } from './_catalog';\nimport { type CatalogStore, type Loader, type LocaleSource, createCatalogStore } from './_catalog-store';\nimport { type LocaleCaches, buildLocaleChain, canon, createLocaleCaches, selectPluralForm } from './_chain';\nimport { error as logError } from './_dev';\nimport { type NamespaceFactory, type NamespaceStore, createNamespaceStore } from './_namespace-store';\nimport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaInvalidCountError,\n LinguaRestoreError,\n checkDisposed,\n} from './errors';\nimport { type Formatter, createFormatter } from './format';\nimport { type CompiledTemplate, renderTemplate } from './template';\n\nexport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCountError,\n LinguaInvalidLocaleError,\n LinguaMissingLocaleError,\n LinguaNamespaceMissingError,\n LinguaRestoreError,\n} from './errors';\n\nexport type {\n I18n,\n I18nOptions,\n I18nSnapshot,\n I18nState,\n Locale,\n MessageBranchKeys,\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\nexport type { Loader, LocaleSource } from './_catalog-store';\nexport type { Messages } from './_catalog';\nexport type { NamespaceFactory } from './_namespace-store';\n\n// ─── Locale state ─────────────────────────────────────────────────────────────\n// Replaced atomically on every locale change.\n\ntype LocaleState = {\n readonly chain: readonly Locale[];\n readonly chainSet: ReadonlySet<Locale>;\n readonly locale: Locale;\n};\n\nfunction buildState(locale: Locale, fallback: Locale[], caches: LocaleCaches): LocaleState {\n const { chain, set } = buildLocaleChain(locale, fallback, caches);\n\n return { chain, chainSet: set, locale };\n}\n\n// ─── Plural key priority ──────────────────────────────────────────────────────\n// Cardinal zero: try .zero override first, then CLDR form, then .other as final fallback.\n// Ordinal / non-zero: try CLDR form, then .other as final fallback.\nfunction pluralKeyPriority(base: string, form: string, count: number, ordinal: boolean): string[] {\n const keys: string[] = [];\n\n if (!ordinal && count === 0) keys.push(`${base}.zero`);\n\n if (form !== 'zero' || ordinal) keys.push(`${base}.${form}`);\n\n if (form !== 'other') keys.push(`${base}.other`);\n\n return keys;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/** Overload: explicit type parameter (strict typing) */\nexport function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;\n/** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */\nexport function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;\nexport function createI18n<M extends Messages = Messages>(config?: I18nOptions<M>): I18n<M> {\n return _createI18nImpl<M>(config);\n}\n\n// ─── Internal seed shape ──────────────────────────────────────────────────────\n\ntype I18nSeed<M extends Messages> = {\n catalogStore?: CatalogStore<M>;\n nsStore?: NamespaceStore;\n};\n\nfunction _createI18nImpl<M extends Messages = Messages>(config?: I18nOptions<M>, _seed?: I18nSeed<M>): I18n<M> {\n const cfg: I18nOptions<M> = config ?? {};\n\n // ─── Per-instance caches (no shared module-level state) ───────────────────\n const caches: LocaleCaches = createLocaleCaches();\n\n const canonL = (loc: string) => canon(loc, caches);\n\n const fallback = Array.isArray(cfg.fallback) ? cfg.fallback.map(canonL) : cfg.fallback ? [canonL(cfg.fallback)] : [];\n\n // ─── Disposal ─────────────────────────────────────────────────────────────\n let disposed = false;\n const disposeController = new AbortController();\n\n // ─── Bounded stores ───────────────────────────────────────────────────────\n const catalogStore: CatalogStore<M> = createCatalogStore(() => disposed);\n const nsStore: NamespaceStore = createNamespaceStore(() => disposed);\n\n // ─── Locale state ─────────────────────────────────────────────────────────\n let state: LocaleState = buildState(canonL(cfg.locale ?? 'en'), fallback, caches);\n\n // ─── Subscribers ──────────────────────────────────────────────────────────\n const subscribers = new Set<(snapshot: I18nSnapshot) => void>();\n const subscriptionUnsubscribers = new Set<Unsubscribe>();\n\n const onMissingKey = cfg.onMissingKey ?? ((key: string) => key);\n const onMissingVar = cfg.onMissingVar ?? ((varName: string) => `{${varName}}`);\n const onSubscriberError = cfg.onSubscriberError ?? ((error: unknown) => logError('subscriber error', error));\n\n // ─── Lazy formatter — avoids Intl overhead for SSR forks that only need t(). ──\n let _fmt: Formatter | undefined;\n\n // ─── Scope cache — stable object references per prefix for reactive framework renders. ──\n const scopeCache = new Map<string, ScopedI18n>();\n\n const getFormatter = (): Formatter => {\n if (!_fmt) _fmt = createFormatter(() => state.locale);\n\n return _fmt;\n };\n\n // ─── Translate helpers ────────────────────────────────────────────────────\n\n // Single-pass entry lookup across the active fallback chain.\n const findEntry = (key: string): { compiled: CompiledTemplate; message: string } | undefined => {\n for (const candidate of state.chain) {\n const found = catalogStore.resolve(candidate)?.get(key);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n };\n\n // Shared by has() and scope().has() — true if `base` exists as a leaf key or a plural branch prefix.\n const hasKey = (base: string): boolean => {\n if (findEntry(base) !== undefined) return true;\n\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n if (catalog.prefixes.has(base)) return true;\n }\n\n return false;\n };\n\n const interpolate = (\n key: string,\n found: { compiled: CompiledTemplate; message: string },\n vars: TranslateVars | undefined,\n ): string => renderTemplate(found.compiled, vars, key, state.locale, onMissingVar);\n\n const translate = (key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string => {\n const base = String(key);\n const found = findEntry(base);\n\n if (!found) return onMissingKey(base, state.locale);\n\n return interpolate(base, found, vars);\n };\n\n const translatePlural = (key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string => {\n if (!Number.isFinite(count)) {\n throw new LinguaInvalidCountError('`count` must be a finite number.');\n }\n\n const vars = options?.vars;\n const ordinal = options?.ordinal ?? false;\n\n if (vars && Object.hasOwn(vars, 'count')) {\n throw new LinguaCountInVarsError('`tp` does not allow `vars.count`; `count` is injected automatically.');\n }\n\n const base = String(key);\n const mergedVars = vars ? { count, ...vars } : { count };\n\n // Walk the fallback chain locale-by-locale, selecting CLDR plural form using each\n // locale's own rules. This ensures cross-locale fallbacks produce grammatically correct forms.\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n const form = selectPluralForm(candidate, count, ordinal, caches);\n const keys = pluralKeyPriority(base, form, count, ordinal);\n\n for (const k of keys) {\n const found = catalog.get(k);\n\n if (found !== undefined) {\n return interpolate(k, found, mergedVars);\n }\n }\n }\n\n return onMissingKey(base, state.locale);\n };\n\n // ─── bump() ───────────────────────────────────────────────────────────────\n // Rebuilds the snapshot and notifies all current subscribers.\n\n let snapshot: I18nSnapshot = {\n locale: state.locale,\n t: translate,\n tp: translatePlural,\n };\n\n const bump = (): void => {\n snapshot = { locale: state.locale, t: translate, tp: translatePlural };\n\n const listeners = [...subscribers];\n\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch (error) {\n onSubscriberError(error);\n }\n }\n };\n\n // ─── Wire catalog store onChange → bump ───────────────────────────────────\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n\n // ─── Seed from parent fork ─────────────────────────────────────────────────\n if (_seed?.catalogStore) {\n catalogStore.seedFrom(_seed.catalogStore.catalogs, _seed.catalogStore.pendingLoaders);\n }\n\n if (_seed?.nsStore) {\n nsStore.seedFrom(_seed.nsStore);\n }\n\n // ─── Initial catalogs from config ─────────────────────────────────────────\n if (cfg.catalogs) {\n const staticEntries = new Map<Locale, CatalogEntry>();\n const loaderEntries = new Map<Locale, Loader<M>>();\n\n for (const [loc, source] of Object.entries(cfg.catalogs)) {\n const normalized = canonL(loc);\n\n if (typeof source === 'function') {\n loaderEntries.set(normalized, source as Loader<M>);\n } else {\n const entry = new CatalogEntry();\n\n entry.setAll(flattenStrings(source as M));\n staticEntries.set(normalized, entry);\n }\n }\n\n // Use seedFrom for zero-overhead init (no bump, no notifications during setup)\n catalogStore.seedFrom(staticEntries, loaderEntries);\n }\n\n // ─── Preload helper ───────────────────────────────────────────────────────\n\n const preload = (loc: Locale): Promise<void> => catalogStore.preload(canonL(loc));\n\n // ─── Monotonic generation counter — last writer wins for concurrent setLocale() ──\n let switchGen = 0;\n\n // ─── Subscribe helper ─────────────────────────────────────────────────────\n\n const subscribeInternal = (callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe => {\n const signal = options?.signal;\n\n const unsubscribe = (): void => {\n subscribers.delete(callback);\n signal?.removeEventListener('abort', unsubscribe);\n subscriptionUnsubscribers.delete(unsubscribe);\n };\n\n if (disposed) throw new LinguaDisposedError();\n\n if (signal?.aborted) return unsubscribe;\n\n if (options?.immediate === true) {\n try {\n callback(snapshot);\n } catch (error) {\n onSubscriberError(error);\n\n return unsubscribe;\n }\n }\n\n subscribers.add(callback);\n signal?.addEventListener('abort', unsubscribe, { once: true });\n subscriptionUnsubscribers.add(unsubscribe);\n\n return unsubscribe;\n };\n\n // ─── Public object ─────────────────────────────────────────────────────────\n\n return {\n get disposalSignal(): AbortSignal {\n return disposeController.signal;\n },\n\n dispose(): void {\n if (disposed) return;\n\n disposed = true;\n disposeController.abort();\n for (const unsubscribe of [...subscriptionUnsubscribers]) unsubscribe();\n subscriptionUnsubscribers.clear();\n subscribers.clear();\n catalogStore.dispose();\n nsStore.dispose();\n scopeCache.clear();\n },\n\n get disposed(): boolean {\n return disposed;\n },\n\n extend(ns: string, factory: NamespaceFactory, loc?: Locale): Promise<void> {\n checkDisposed(disposed);\n\n nsStore.registerNamespace(ns, factory);\n\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get fmt(): Formatter {\n return getFormatter();\n },\n\n fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M> {\n return _createI18nImpl(\n {\n fallback: overrides?.fallback ?? (fallback.length > 0 ? fallback : undefined),\n locale: overrides?.locale ?? state.locale,\n onMissingKey: overrides?.onMissingKey ?? cfg.onMissingKey,\n onMissingVar: overrides?.onMissingVar ?? cfg.onMissingVar,\n onSubscriberError: overrides?.onSubscriberError ?? cfg.onSubscriberError,\n },\n {\n catalogStore: catalogStore as CatalogStore<M>,\n nsStore: nsStore as NamespaceStore,\n },\n );\n },\n\n getSnapshot() {\n return snapshot;\n },\n\n getState(): I18nState {\n const catalogsOut: Record<Locale, Record<string, string>> = {};\n\n for (const [loc, entry] of catalogStore.catalogs) {\n catalogsOut[loc] = Object.fromEntries([...entry.entries.entries()].map(([k, { message }]) => [k, message]));\n }\n\n return { catalogs: catalogsOut, locale: state.locale };\n },\n\n getSupportedLocales(sorted?: boolean): Locale[] {\n const locales = [...catalogStore.knownLocales()];\n\n return sorted === true ? locales.sort() : locales;\n },\n\n has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean {\n return hasKey(String(key));\n },\n\n isLoaded(loc: Locale): boolean {\n try {\n return catalogStore.isLoaded(canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceLoaded(ns: string, loc?: Locale): boolean {\n if (!loc) return nsStore.isLoaded(ns, state.locale);\n\n try {\n return nsStore.isLoaded(ns, canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceRegistered(ns: string): boolean {\n return nsStore.isRegistered(ns);\n },\n\n isRegistered(loc: Locale): boolean {\n try {\n return catalogStore.isRegistered(canonL(loc));\n } catch {\n return false;\n }\n },\n\n loadNamespace(ns: string, loc?: Locale): Promise<void> {\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get locale(): Locale {\n return state.locale;\n },\n\n preload,\n\n register(loc: Locale, source: LocaleSource<M>): Promise<void> {\n const normalized = canonL(loc);\n\n return catalogStore.register(normalized, source, nsStore);\n },\n\n registerNamespace(ns: string, factory: NamespaceFactory): void {\n nsStore.registerNamespace(ns, factory);\n },\n\n restoreState(st: I18nState): void {\n checkDisposed(disposed);\n\n if (!Object.hasOwn(st.catalogs, st.locale)) {\n throw new LinguaRestoreError(`restoreState: locale \"${st.locale}\" has no catalog in the provided state.`);\n }\n\n const freshEntries = new Map<Locale, CatalogEntry>();\n const knownLocales = catalogStore.knownLocales();\n\n for (const knownLocale of knownLocales) {\n nsStore.clearLocale(knownLocale);\n }\n\n for (const [loc, flatCatalog] of Object.entries(st.catalogs)) {\n const normalized = canonL(loc);\n const entry = new CatalogEntry();\n\n entry.setAll(Object.entries(flatCatalog));\n freshEntries.set(normalized, entry);\n }\n\n // Dispose and re-seed the catalog store with the restored entries.\n // onChange is re-wired immediately after dispose.\n catalogStore.dispose();\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n catalogStore.seedFrom(freshEntries, new Map());\n\n const normalized = canonL(st.locale);\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n {\n const pre = String(prefix);\n const cached = scopeCache.get(pre);\n\n if (cached) return cached;\n\n const scoped: ScopedI18n = {\n get fmt() {\n return getFormatter();\n },\n has: (key) => hasKey(`${pre}.${key}`),\n t: (key, vars?) => translate(`${pre}.${key}`, vars),\n tp: (key, count, options?) => translatePlural(`${pre}.${key}`, count, options),\n };\n\n scopeCache.set(pre, scoped);\n\n return scoped;\n },\n\n async setLocale(next: Locale): Promise<void> {\n checkDisposed(disposed);\n\n const normalized = canonL(next);\n\n if (state.locale === normalized) return;\n\n // Monotonic generation counter — last writer wins.\n const gen = ++switchGen;\n\n await preload(normalized);\n\n if (disposed || switchGen !== gen) return;\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n subscribe: subscribeInternal,\n\n [Symbol.dispose](): void {\n this.dispose();\n },\n\n t: translate,\n\n tp: translatePlural,\n };\n}\n\n// ─── SSR standalone helpers ───────────────────────────────────────────────────\n\n/**\n * Serialises the currently loaded catalogs and active locale into a plain object.\n * Pass the result to `hydrateI18n()` on the client.\n *\n * Prefer calling `i18n.getState()` directly — these standalone functions are provided\n * for convenience when you receive a plain `I18n` reference without the full type.\n *\n * **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet\n * preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.\n *\n * **Warning:** The namespace registry is **not** serialized — factory functions cannot\n * be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace\n * before relying on namespace-patched keys.\n */\nexport function serializeI18n(i18n: I18n): I18nState {\n return i18n.getState();\n}\n\n/**\n * Hydrates an i18n instance with pre-loaded state (e.g. from a server-rendered payload).\n *\n * Prefer calling `i18n.restoreState(state)` directly — these standalone functions are\n * provided for convenience.\n *\n * @remarks The namespace registry is **not** included in `I18nState`. After hydrating,\n * call `extend()` for each namespace before relying on namespace-patched keys.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n * @throws `LinguaRestoreError` if the state's locale has no catalog.\n */\nexport function hydrateI18n(i18n: I18n, state: I18nState): void {\n i18n.restoreState(state);\n}\n"],"mappings":"0OAoEA,SAAS,EAAW,EAAgB,EAAoB,EAAmC,CACzF,GAAM,CAAE,QAAO,OAAQ,EAAA,iBAAiB,EAAQ,EAAU,CAAM,EAEhE,MAAO,CAAE,QAAO,SAAU,EAAK,QAAO,CACxC,CAKA,SAAS,EAAkB,EAAc,EAAc,EAAe,EAA4B,CAChG,IAAM,EAAiB,CAAC,EAQxB,MANI,CAAC,GAAW,IAAU,GAAG,EAAK,KAAK,GAAG,EAAK,MAAM,GAEjD,IAAS,QAAU,IAAS,EAAK,KAAK,GAAG,EAAK,GAAG,GAAM,EAEvD,IAAS,SAAS,EAAK,KAAK,GAAG,EAAK,OAAO,EAExC,CACT,CAQA,SAAgB,EAA0C,EAAkC,CAC1F,OAAO,EAAmB,CAAM,CAClC,CASA,SAAS,EAA+C,EAAyB,EAA8B,CAC7G,IAAM,EAAsB,GAAU,CAAC,EAGjC,EAAuB,EAAA,mBAAmB,EAE1C,EAAU,GAAgB,EAAA,MAAM,EAAK,CAAM,EAE3C,EAAW,MAAM,QAAQ,EAAI,QAAQ,EAAI,EAAI,SAAS,IAAI,CAAM,EAAI,EAAI,SAAW,CAAC,EAAO,EAAI,QAAQ,CAAC,EAAI,CAAC,EAG/G,EAAW,GACT,EAAoB,IAAI,gBAGxB,EAAgC,EAAA,uBAAyB,CAAQ,EACjE,EAA0B,EAAA,yBAA2B,CAAQ,EAG/D,EAAqB,EAAW,EAAO,EAAI,QAAU,IAAI,EAAG,EAAU,CAAM,EAG1E,EAAc,IAAI,IAClB,EAA4B,IAAI,IAEhC,EAAe,EAAI,eAAkB,GAAgB,GACrD,EAAe,EAAI,eAA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