@vielzeug/lingua 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +86 -0
  2. package/dist/_catalog-store.cjs +2 -0
  3. package/dist/_catalog-store.cjs.map +1 -0
  4. package/dist/_catalog-store.d.ts +33 -0
  5. package/dist/_catalog-store.d.ts.map +1 -0
  6. package/dist/_catalog-store.js +74 -0
  7. package/dist/_catalog-store.js.map +1 -0
  8. package/dist/_catalog.cjs +2 -0
  9. package/dist/_catalog.cjs.map +1 -0
  10. package/dist/_catalog.d.ts +18 -0
  11. package/dist/_catalog.d.ts.map +1 -0
  12. package/dist/_catalog.js +42 -0
  13. package/dist/_catalog.js.map +1 -0
  14. package/dist/_chain.cjs +2 -0
  15. package/dist/_chain.cjs.map +1 -0
  16. package/dist/_chain.d.ts +21 -0
  17. package/dist/_chain.d.ts.map +1 -0
  18. package/dist/_chain.js +45 -0
  19. package/dist/_chain.js.map +1 -0
  20. package/dist/_constants.cjs +2 -0
  21. package/dist/_constants.cjs.map +1 -0
  22. package/dist/_constants.d.ts +3 -0
  23. package/dist/_constants.d.ts.map +1 -0
  24. package/dist/_constants.js +17 -0
  25. package/dist/_constants.js.map +1 -0
  26. package/dist/_dev.cjs +2 -0
  27. package/dist/_dev.cjs.map +1 -0
  28. package/dist/_dev.d.ts +2 -0
  29. package/dist/_dev.d.ts.map +1 -0
  30. package/dist/_dev.js +12 -0
  31. package/dist/_dev.js.map +1 -0
  32. package/dist/_namespace-store.cjs +2 -0
  33. package/dist/_namespace-store.cjs.map +1 -0
  34. package/dist/_namespace-store.d.ts +31 -0
  35. package/dist/_namespace-store.d.ts.map +1 -0
  36. package/dist/_namespace-store.js +54 -0
  37. package/dist/_namespace-store.js.map +1 -0
  38. package/dist/errors.cjs +2 -0
  39. package/dist/errors.cjs.map +1 -0
  40. package/dist/errors.d.ts +30 -0
  41. package/dist/errors.d.ts.map +1 -0
  42. package/dist/errors.js +23 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/format.cjs +2 -0
  45. package/dist/format.cjs.map +1 -0
  46. package/dist/format.d.ts +73 -0
  47. package/dist/format.d.ts.map +1 -0
  48. package/dist/format.js +91 -0
  49. package/dist/format.js.map +1 -0
  50. package/dist/i18n.cjs +2 -0
  51. package/dist/i18n.cjs.map +1 -0
  52. package/dist/i18n.d.ts +283 -0
  53. package/dist/i18n.d.ts.map +1 -0
  54. package/dist/i18n.js +234 -0
  55. package/dist/i18n.js.map +1 -0
  56. package/dist/index.cjs +1 -0
  57. package/dist/index.d.ts +13 -0
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +4 -0
  60. package/dist/lingua.cjs +2 -0
  61. package/dist/lingua.cjs.map +1 -0
  62. package/dist/lingua.iife.js +2 -0
  63. package/dist/lingua.iife.js.map +1 -0
  64. package/dist/lingua.js +2 -0
  65. package/dist/lingua.js.map +1 -0
  66. package/dist/template.cjs +2 -0
  67. package/dist/template.cjs.map +1 -0
  68. package/dist/template.d.ts +15 -0
  69. package/dist/template.d.ts.map +1 -0
  70. package/dist/template.js +49 -0
  71. package/dist/template.js.map +1 -0
  72. package/dist/validate.cjs +2 -0
  73. package/dist/validate.cjs.map +1 -0
  74. package/dist/validate.d.ts +40 -0
  75. package/dist/validate.d.ts.map +1 -0
  76. package/dist/validate.js +59 -0
  77. package/dist/validate.js.map +1 -0
  78. package/package.json +53 -0
@@ -0,0 +1,54 @@
1
+ import { LinguaNamespaceMissingError as e, checkDisposed as t, checkDisposedAsync as n } from "./errors.js";
2
+ //#region src/_namespace-store.ts
3
+ function r(r) {
4
+ let i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map();
5
+ return {
6
+ clearLocale(e) {
7
+ let t = [];
8
+ for (let [n, r] of a.entries()) r.delete(e) && t.push(n);
9
+ return t;
10
+ },
11
+ dispose() {
12
+ i.clear(), a.clear(), o.clear();
13
+ },
14
+ isLoaded(e, t) {
15
+ return a.get(e)?.has(t) ?? !1;
16
+ },
17
+ isRegistered(e) {
18
+ return i.has(e);
19
+ },
20
+ loadNamespace(t, s, c) {
21
+ let l = n(r());
22
+ if (l) return l;
23
+ let u = i.get(t);
24
+ if (!u) return Promise.reject(new e(`Namespace '${t}' is not registered. Call registerNamespace() first.`));
25
+ if (a.get(t)?.has(s)) return Promise.resolve();
26
+ let d = o.get(t)?.get(s);
27
+ if (d) return d;
28
+ let f = u(s).then((e) => c(s, e)).then(() => {
29
+ let e = a.get(t);
30
+ e || (e = /* @__PURE__ */ new Set(), a.set(t, e)), e.add(s), o.get(t)?.delete(s);
31
+ }, (e) => {
32
+ throw o.get(t)?.delete(s), e;
33
+ });
34
+ return o.has(t) || o.set(t, /* @__PURE__ */ new Map()), o.get(t).set(s, f), f;
35
+ },
36
+ registerNamespace(e, n) {
37
+ t(r()), i.set(e, n);
38
+ },
39
+ seedFrom(e) {
40
+ for (let [t, n] of e.snapshotRegistry()) i.set(t, n);
41
+ for (let [t, n] of e.snapshotLoaded()) a.set(t, new Set(n));
42
+ },
43
+ snapshotLoaded() {
44
+ return a;
45
+ },
46
+ snapshotRegistry() {
47
+ return i;
48
+ }
49
+ };
50
+ }
51
+ //#endregion
52
+ export { r as createNamespaceStore };
53
+
54
+ //# sourceMappingURL=_namespace-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_namespace-store.js","names":[],"sources":["../src/_namespace-store.ts"],"sourcesContent":["// Internal — not part of the public API.\n// Owns namespace factory registry, per-locale loaded markers, and in-flight namespace tasks.\n\nimport type { Messages } from './_catalog';\n\nimport { LinguaNamespaceMissingError, checkDisposed, checkDisposedAsync } from './errors';\n\nexport type Locale = string;\nexport type NamespaceFactory<M extends Messages = Messages> = (locale: Locale) => Promise<M>;\n\nexport type NamespaceStore<M extends Messages = Messages> = {\n /**\n * Remove loaded-markers for a locale across all namespaces.\n * Called by CatalogStore.register() when a catalog is replaced.\n * Returns the list of namespace names whose markers were cleared.\n */\n clearLocale(loc: Locale): string[];\n dispose(): void;\n /** Returns true if the namespace has been loaded for the given locale. */\n isLoaded(ns: string, loc: Locale): boolean;\n /** Returns true if the namespace factory is registered. */\n isRegistered(ns: string): boolean;\n /**\n * Load a namespace for the given locale. Deduplicates concurrent and repeated calls.\n * The `patch` callback is responsible for merging the loaded messages into the catalog.\n */\n loadNamespace(ns: string, loc: Locale, patch: (loc: Locale, messages: Messages) => Promise<void>): Promise<void>;\n /** Register a namespace factory. Idempotent — re-registration updates the factory for future loads. */\n registerNamespace(ns: string, factory: NamespaceFactory<M>): void;\n /** Seed from a parent instance (fork). Copies loaded markers; registry is shared by reference. */\n seedFrom(parent: NamespaceStore<M>): void;\n /** Snapshot of loaded markers for fork() */\n snapshotLoaded(): ReadonlyMap<string, ReadonlySet<string>>;\n /** Snapshot of the registry for fork() */\n snapshotRegistry(): ReadonlyMap<string, NamespaceFactory<M>>;\n};\n\nexport function createNamespaceStore<M extends Messages = Messages>(disposed: () => boolean): NamespaceStore<M> {\n const registry = new Map<string, NamespaceFactory<M>>();\n // Two-level: Map<namespace, Set<locale>>\n const loaded = new Map<string, Set<string>>();\n const tasks = new Map<string, Map<string, Promise<void>>>();\n\n return {\n clearLocale(loc) {\n const cleared: string[] = [];\n\n for (const [ns, localeSet] of loaded.entries()) {\n if (localeSet.delete(loc)) cleared.push(ns);\n }\n\n return cleared;\n },\n\n dispose() {\n registry.clear();\n loaded.clear();\n tasks.clear();\n },\n\n isLoaded(ns, loc) {\n return loaded.get(ns)?.has(loc) ?? false;\n },\n\n isRegistered(ns) {\n return registry.has(ns);\n },\n\n loadNamespace(ns, loc, patch) {\n const early = checkDisposedAsync(disposed());\n\n if (early) return early;\n\n const factory = registry.get(ns);\n\n if (!factory) {\n return Promise.reject(\n new LinguaNamespaceMissingError(`Namespace '${ns}' is not registered. Call registerNamespace() first.`),\n );\n }\n\n if (loaded.get(ns)?.has(loc)) return Promise.resolve();\n\n const nsTasks = tasks.get(ns);\n const existing = nsTasks?.get(loc);\n\n if (existing) return existing;\n\n const task = factory(loc)\n .then((messages) => patch(loc, messages as Messages))\n .then(\n () => {\n let localeSet = loaded.get(ns);\n\n if (!localeSet) {\n localeSet = new Set();\n loaded.set(ns, localeSet);\n }\n\n localeSet.add(loc);\n tasks.get(ns)?.delete(loc);\n },\n (err: unknown) => {\n tasks.get(ns)?.delete(loc);\n throw err;\n },\n );\n\n if (!tasks.has(ns)) tasks.set(ns, new Map());\n\n tasks.get(ns)!.set(loc, task);\n\n return task;\n },\n\n registerNamespace(ns, factory) {\n checkDisposed(disposed());\n registry.set(ns, factory);\n },\n\n seedFrom(parent) {\n for (const [ns, factory] of parent.snapshotRegistry()) {\n registry.set(ns, factory);\n }\n\n for (const [ns, localeSet] of parent.snapshotLoaded()) {\n loaded.set(ns, new Set(localeSet));\n }\n },\n\n snapshotLoaded() {\n return loaded as ReadonlyMap<string, ReadonlySet<string>>;\n },\n\n snapshotRegistry() {\n return registry as ReadonlyMap<string, NamespaceFactory<M>>;\n },\n };\n}\n"],"mappings":";;AAqCA,SAAgB,EAAoD,GAA4C;CAC9G,IAAM,oBAAW,IAAI,IAAiC,GAEhD,oBAAS,IAAI,IAAyB,GACtC,oBAAQ,IAAI,IAAwC;CAE1D,OAAO;EACL,YAAY,GAAK;GACf,IAAM,IAAoB,CAAC;GAE3B,KAAK,IAAM,CAAC,GAAI,MAAc,EAAO,QAAQ,GAC3C,AAAI,EAAU,OAAO,CAAG,KAAG,EAAQ,KAAK,CAAE;GAG5C,OAAO;EACT;EAEA,UAAU;GAGR,AAFA,EAAS,MAAM,GACf,EAAO,MAAM,GACb,EAAM,MAAM;EACd;EAEA,SAAS,GAAI,GAAK;GAChB,OAAO,EAAO,IAAI,CAAE,CAAC,EAAE,IAAI,CAAG,KAAK;EACrC;EAEA,aAAa,GAAI;GACf,OAAO,EAAS,IAAI,CAAE;EACxB;EAEA,cAAc,GAAI,GAAK,GAAO;GAC5B,IAAM,IAAQ,EAAmB,EA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,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{constructor(){super(`Operation called on a disposed i18n instance.`)}},n=class extends e{},r=class extends e{},i=class extends e{},a=class extends e{},o=class extends e{},s=class extends e{};function c(e){if(e)throw new t}function l(e){return e?Promise.reject(new t):null}exports.LinguaCountInVarsError=r,exports.LinguaDisposedError=t,exports.LinguaError=e,exports.LinguaInvalidCountError=n,exports.LinguaInvalidLocaleError=a,exports.LinguaMissingLocaleError=i,exports.LinguaNamespaceMissingError=o,exports.LinguaRestoreError=s,exports.checkDisposed=c,exports.checkDisposedAsync=l;
2
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all lingua errors. Use `instanceof LinguaError` or `LinguaError.is()` to catch any lingua-originated error. */\nexport 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 static is(err: unknown): err is LinguaError {\n return err instanceof LinguaError;\n }\n}\n\n/** Thrown when a method is called on a disposed i18n instance. */\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\n/** Thrown when `tp()` receives a non-finite `count` value. */\nexport class LinguaInvalidCountError extends LinguaError {}\n\n/** Thrown when `vars.count` is set alongside the `count` parameter in `tp()`. */\nexport class LinguaCountInVarsError extends LinguaError {}\n\n/** Thrown when a requested locale has not been registered. */\nexport class LinguaMissingLocaleError extends LinguaError {}\n\n/** Thrown when a locale string is not a valid BCP 47 tag. */\nexport class LinguaInvalidLocaleError extends LinguaError {}\n\n/** Thrown when `loadNamespace()` / `extend()` is called for a namespace that has not been registered with `registerNamespace()`. */\nexport class LinguaNamespaceMissingError extends LinguaError {}\n\n/** Thrown when restoring i18n state whose locale has no catalog. */\nexport class LinguaRestoreError extends LinguaError {}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\nexport function checkDisposed(disposed: boolean): void {\n if (disposed) throw new LinguaDisposedError();\n}\n\nexport function checkDisposedAsync(disposed: boolean): Promise<never> | null {\n return disposed ? Promise.reject(new LinguaDisposedError()) : null;\n}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAAkC,CAC1C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAyC,CAAY,CACnD,aAAc,CACZ,MAAM,+CAA+C,CACvD,CACF,EAGa,EAAb,cAA6C,CAAY,CAAC,EAG7C,EAAb,cAA4C,CAAY,CAAC,EAG5C,EAAb,cAA8C,CAAY,CAAC,EAG9C,EAAb,cAA8C,CAAY,CAAC,EAG9C,EAAb,cAAiD,CAAY,CAAC,EAGjD,EAAb,cAAwC,CAAY,CAAC,EAIrD,SAAgB,EAAc,EAAyB,CACrD,GAAI,EAAU,MAAM,IAAI,CAC1B,CAEA,SAAgB,EAAmB,EAA0C,CAC3E,OAAO,EAAW,QAAQ,OAAO,IAAI,CAAqB,EAAI,IAChE"}
@@ -0,0 +1,30 @@
1
+ /** Base class for all lingua errors. Use `instanceof LinguaError` or `LinguaError.is()` to catch any lingua-originated error. */
2
+ export declare class LinguaError extends Error {
3
+ constructor(message: string, opts?: ErrorOptions);
4
+ static is(err: unknown): err is LinguaError;
5
+ }
6
+ /** Thrown when a method is called on a disposed i18n instance. */
7
+ export declare class LinguaDisposedError extends LinguaError {
8
+ constructor();
9
+ }
10
+ /** Thrown when `tp()` receives a non-finite `count` value. */
11
+ export declare class LinguaInvalidCountError extends LinguaError {
12
+ }
13
+ /** Thrown when `vars.count` is set alongside the `count` parameter in `tp()`. */
14
+ export declare class LinguaCountInVarsError extends LinguaError {
15
+ }
16
+ /** Thrown when a requested locale has not been registered. */
17
+ export declare class LinguaMissingLocaleError extends LinguaError {
18
+ }
19
+ /** Thrown when a locale string is not a valid BCP 47 tag. */
20
+ export declare class LinguaInvalidLocaleError extends LinguaError {
21
+ }
22
+ /** Thrown when `loadNamespace()` / `extend()` is called for a namespace that has not been registered with `registerNamespace()`. */
23
+ export declare class LinguaNamespaceMissingError extends LinguaError {
24
+ }
25
+ /** Thrown when restoring i18n state whose locale has no catalog. */
26
+ export declare class LinguaRestoreError extends LinguaError {
27
+ }
28
+ export declare function checkDisposed(disposed: boolean): void;
29
+ export declare function checkDisposedAsync(disposed: boolean): Promise<never> | null;
30
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,iIAAiI;AACjI,qBAAa,WAAY,SAAQ,KAAK;gBACxB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;IAMhD,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,WAAW;CAG5C;AAED,kEAAkE;AAClE,qBAAa,mBAAoB,SAAQ,WAAW;;CAInD;AAED,8DAA8D;AAC9D,qBAAa,uBAAwB,SAAQ,WAAW;CAAG;AAE3D,iFAAiF;AACjF,qBAAa,sBAAuB,SAAQ,WAAW;CAAG;AAE1D,8DAA8D;AAC9D,qBAAa,wBAAyB,SAAQ,WAAW;CAAG;AAE5D,6DAA6D;AAC7D,qBAAa,wBAAyB,SAAQ,WAAW;CAAG;AAE5D,oIAAoI;AACpI,qBAAa,2BAA4B,SAAQ,WAAW;CAAG;AAE/D,oEAAoE;AACpE,qBAAa,kBAAmB,SAAQ,WAAW;CAAG;AAItD,wBAAgB,aAAa,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAErD;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAE3E"}
package/dist/errors.js ADDED
@@ -0,0 +1,23 @@
1
+ //#region src/errors.ts
2
+ var e = class e extends Error {
3
+ constructor(e, t) {
4
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
5
+ }
6
+ static is(t) {
7
+ return t instanceof e;
8
+ }
9
+ }, t = class extends e {
10
+ constructor() {
11
+ super("Operation called on a disposed i18n instance.");
12
+ }
13
+ }, n = class extends e {}, r = class extends e {}, i = class extends e {}, a = class extends e {}, o = class extends e {}, s = class extends e {};
14
+ function c(e) {
15
+ if (e) throw new t();
16
+ }
17
+ function l(e) {
18
+ return e ? Promise.reject(new t()) : null;
19
+ }
20
+ //#endregion
21
+ export { r as LinguaCountInVarsError, t as LinguaDisposedError, e as LinguaError, n as LinguaInvalidCountError, a as LinguaInvalidLocaleError, i as LinguaMissingLocaleError, o as LinguaNamespaceMissingError, s as LinguaRestoreError, c as checkDisposed, l as checkDisposedAsync };
22
+
23
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all lingua errors. Use `instanceof LinguaError` or `LinguaError.is()` to catch any lingua-originated error. */\nexport 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 static is(err: unknown): err is LinguaError {\n return err instanceof LinguaError;\n }\n}\n\n/** Thrown when a method is called on a disposed i18n instance. */\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\n/** Thrown when `tp()` receives a non-finite `count` value. */\nexport class LinguaInvalidCountError extends LinguaError {}\n\n/** Thrown when `vars.count` is set alongside the `count` parameter in `tp()`. */\nexport class LinguaCountInVarsError extends LinguaError {}\n\n/** Thrown when a requested locale has not been registered. */\nexport class LinguaMissingLocaleError extends LinguaError {}\n\n/** Thrown when a locale string is not a valid BCP 47 tag. */\nexport class LinguaInvalidLocaleError extends LinguaError {}\n\n/** Thrown when `loadNamespace()` / `extend()` is called for a namespace that has not been registered with `registerNamespace()`. */\nexport class LinguaNamespaceMissingError extends LinguaError {}\n\n/** Thrown when restoring i18n state whose locale has no catalog. */\nexport class LinguaRestoreError extends LinguaError {}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\nexport function checkDisposed(disposed: boolean): void {\n if (disposed) throw new LinguaDisposedError();\n}\n\nexport function checkDisposedAsync(disposed: boolean): Promise<never> | null {\n return disposed ? Promise.reject(new LinguaDisposedError()) : null;\n}\n"],"mappings":";AACA,IAAa,IAAb,MAAa,UAAoB,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAM,GAAS,CAAI,GACnB,KAAK,OAAO,IAAI,OAAO,MACvB,OAAO,eAAe,MAAM,IAAI,OAAO,SAAS;CAClD;CAEA,OAAO,GAAG,GAAkC;EAC1C,OAAO,aAAe;CACxB;AACF,GAGa,IAAb,cAAyC,EAAY;CACnD,cAAc;EACZ,MAAM,+CAA+C;CACvD;AACF,GAGa,IAAb,cAA6C,EAAY,CAAC,GAG7C,IAAb,cAA4C,EAAY,CAAC,GAG5C,IAAb,cAA8C,EAAY,CAAC,GAG9C,IAAb,cAA8C,EAAY,CAAC,GAG9C,IAAb,cAAiD,EAAY,CAAC,GAGjD,IAAb,cAAwC,EAAY,CAAC;AAIrD,SAAgB,EAAc,GAAyB;CACrD,IAAI,GAAU,MAAM,IAAI,EAAoB;AAC9C;AAEA,SAAgB,EAAmB,GAA0C;CAC3E,OAAO,IAAW,QAAQ,OAAO,IAAI,EAAoB,CAAC,IAAI;AAChE"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=128;function t(t,n,r){let i=t.get(n);if(i!==void 0)return i;let a=r();return t.size>=e&&t.delete(t.keys().next().value),t.set(n,a),a}var n=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`],r={days:`d`,hours:`h`,microseconds:`us`,milliseconds:`ms`,minutes:`min`,months:`mo`,nanoseconds:`ns`,seconds:`s`,weeks:`w`,years:`y`};function i(e){return n.map(t=>{let n=e[t];return typeof n==`number`?`${n}${r[t]}`:void 0}).filter(e=>e!==void 0).join(` `)}function a(e){let r=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=typeof e==`string`?()=>e:e;function d(e,t){if(!t)return e;let n={};for(let e of Object.keys(t).sort())n[e]=t[e];try{return`${e}:${JSON.stringify(n)}`}catch{return e}}return{clear(){r.clear(),a.clear(),o.clear(),s.clear(),c.clear(),l.clear()},currency(e,n,r){let i=u(),o={...r,currency:n,style:`currency`};return t(a,d(i,o),()=>new Intl.NumberFormat(i,o)).format(e)},date(e,n){let r=u();return t(o,d(r,n),()=>new Intl.DateTimeFormat(r,n)).format(e)},duration(e,r){let a=u(),o=Intl;return o.DurationFormat?n.every(t=>e[t]===void 0)?``:t(l,d(a,r),()=>new o.DurationFormat(a,r)).format(e):i(e)},list(e,n){let r=u(),i=e.map(e=>String(e)),a=n?.style??`long`,o=n?.type===`or`?`disjunction`:`conjunction`;return t(c,d(r,{style:a,type:o}),()=>new Intl.ListFormat(r,{style:a,type:o})).format(i)},number(e,n){let i=u();return t(r,d(i,n),()=>new Intl.NumberFormat(i,n)).format(e)},relative(e,n,r){let i=u();return t(s,d(i,r),()=>new Intl.RelativeTimeFormat(i,r)).format(e,n)}}}exports.createFormatter=a;
2
+ //# sourceMappingURL=format.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["/**\n * /lingua/format\n *\n * Standalone Intl formatter factory. Import from `/lingua/format`.\n * Creates formatters for numbers, dates, currencies, lists, durations, and relative time.\n *\n * Pass a static locale string or a reactive locale getter.\n *\n * @example\n * ```ts\n * import { createFormatter } from '@vielzeug/lingua/format';\n *\n * // Static locale\n * const fmt = createFormatter('en-US');\n *\n * // Reactive — always reads the current locale from the i18n instance\n * const fmt = createFormatter(() => i18n.locale);\n *\n * fmt.number(1_234.56);\n * fmt.currency(9.99, 'USD');\n * fmt.date(new Date());\n * fmt.relative(-1, 'day');\n * fmt.list(['A', 'B', 'C']);\n * fmt.duration({ hours: 1, minutes: 30 });\n * ```\n */\n\nconst FORMAT_CACHE_MAX = 128;\n\nfunction getOrCreate<F>(cache: Map<string, F>, key: string, build: () => F): F {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n const value = build();\n\n if (cache.size >= FORMAT_CACHE_MAX) cache.delete(cache.keys().next().value as string);\n\n cache.set(key, value);\n\n return value;\n}\n\nexport type DurationValue = Partial<\n Record<\n | 'days'\n | 'hours'\n | 'microseconds'\n | 'milliseconds'\n | 'minutes'\n | 'months'\n | 'nanoseconds'\n | 'seconds'\n | 'weeks'\n | 'years',\n number\n >\n>;\n\nexport type DurationFormatOptions = {\n hours?: '2-digit' | 'numeric';\n microseconds?: 'numeric';\n milliseconds?: 'numeric';\n minutes?: '2-digit' | 'numeric';\n nanoseconds?: 'numeric';\n seconds?: '2-digit' | 'numeric';\n style?: 'digital' | 'long' | 'narrow' | 'short';\n};\n\nexport type ListFormatOptions = {\n style?: 'long' | 'narrow' | 'short';\n type?: 'and' | 'or';\n};\n\nexport type Formatter = {\n /**\n * Clears all cached `Intl` formatter instances. Useful after a locale change on a long-running\n * SSR server, or to reclaim memory.\n *\n * @note This clears the cache for **all callers sharing this formatter instance**. When called on\n * `i18n.fmt`, the cache is cleared for every part of the application that reads `i18n.fmt`.\n * `setLocale()` already calls `clear()` automatically — manual calls are rarely needed.\n */\n clear(): void;\n currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;\n /**\n * Formats a duration using `Intl.DurationFormat` when available, or a compact labeled fallback\n * (e.g. `'1h 30min'`). Returns `''` when every field of `value` is `undefined`.\n *\n * @note The fallback labels (`h`, `min`, `s`, `ms`, etc.) are English-only and are not\n * locale-aware. If `Intl.DurationFormat` is unavailable in your target environment and\n * you need localised duration output, provide your own formatter using the individual\n * duration fields from `DurationValue`.\n */\n duration(value: DurationValue, options?: DurationFormatOptions): string;\n list(value: Array<string | number>, options?: ListFormatOptions): string;\n /** Formats a number with the current locale. */\n number(value: number, options?: Intl.NumberFormatOptions): string;\n relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;\n};\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nconst DURATION_UNITS: Array<keyof DurationValue> = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n];\n\nconst DURATION_LABELS: Record<keyof DurationValue, string> = {\n days: 'd',\n hours: 'h',\n microseconds: 'us',\n milliseconds: 'ms',\n minutes: 'min',\n months: 'mo',\n nanoseconds: 'ns',\n seconds: 's',\n weeks: 'w',\n years: 'y',\n};\n\ntype DurationFormatterCtor = new (\n locale: string,\n options?: DurationFormatOptions,\n) => { format(value: DurationValue): string };\n\nfunction durationLabeled(value: DurationValue): string {\n return DURATION_UNITS.map((unit) => {\n const amount = value[unit];\n\n return typeof amount === 'number' ? `${amount}${DURATION_LABELS[unit]}` : undefined;\n })\n .filter((part): part is string => part !== undefined)\n .join(' ');\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a formatter bound to a locale. Pass a static locale string or a\n * reactive getter function `() => string` (e.g. `() => i18n.locale`).\n */\nexport function createFormatter(source: string | (() => string)): Formatter {\n const numberCache = new Map<string, Intl.NumberFormat>();\n const currencyCache = new Map<string, Intl.NumberFormat>();\n const dateCache = new Map<string, Intl.DateTimeFormat>();\n const relativeCache = new Map<string, Intl.RelativeTimeFormat>();\n const listCache = new Map<string, Intl.ListFormat>();\n const durationCache = new Map<string, { format(value: DurationValue): string }>();\n\n const getLocale = typeof source === 'string' ? () => source : source;\n\n function cachedKey(locale: string, options?: object): string {\n if (!options) return locale;\n\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(options as Record<string, unknown>).sort()) {\n sorted[key] = (options as Record<string, unknown>)[key];\n }\n\n try {\n return `${locale}:${JSON.stringify(sorted)}`;\n } catch {\n // Circular references or BigInt values — fall back to locale-only key.\n // Multiple callers with different unserializable options will share the same formatter instance.\n return locale;\n }\n }\n\n return {\n clear() {\n numberCache.clear();\n currencyCache.clear();\n dateCache.clear();\n relativeCache.clear();\n listCache.clear();\n durationCache.clear();\n },\n\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(currencyCache, cachedKey(locale, opts), () => new Intl.NumberFormat(locale, opts)).format(\n value,\n );\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(dateCache, cachedKey(locale, options), () => new Intl.DateTimeFormat(locale, options)).format(\n value,\n );\n },\n\n duration(value, options) {\n const locale = getLocale();\n const IntlExt = Intl as typeof Intl & { DurationFormat?: DurationFormatterCtor };\n\n if (!IntlExt.DurationFormat) return durationLabeled(value);\n\n if (DURATION_UNITS.every((u) => value[u] === undefined)) return '';\n\n return getOrCreate(\n durationCache,\n cachedKey(locale, options),\n () => new IntlExt.DurationFormat!(locale, options),\n ).format(value);\n },\n\n list(value, options) {\n const locale = getLocale();\n const items = value.map((v) => String(v));\n // list() has exactly two string options with small finite value domains.\n // We normalize both to their resolved defaults and build the key directly\n // rather than using cachedKey(). This also prevents cache misses when\n // callers pass { style: 'long', type: 'and' } vs {} (same ListFormat).\n const style = options?.style ?? 'long';\n const type = options?.type === 'or' ? 'disjunction' : 'conjunction';\n\n return getOrCreate(\n listCache,\n cachedKey(locale, { style, type }),\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(numberCache, cachedKey(locale, options), () => new Intl.NumberFormat(locale, options)).format(\n value,\n );\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":"mEA2BA,IAAM,EAAmB,IAEzB,SAAS,EAAe,EAAuB,EAAa,EAAmB,CAC7E,IAAM,EAAS,EAAM,IAAI,CAAG,EAE5B,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,IAAM,EAAQ,EAAM,EAMpB,OAJI,EAAM,MAAQ,GAAkB,EAAM,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAe,EAEpF,EAAM,IAAI,EAAK,CAAK,EAEb,CACT,CA+DA,IAAM,EAA6C,CACjD,QACA,SACA,QACA,OACA,QACA,UACA,UACA,eACA,eACA,aACF,EAEM,EAAuD,CAC3D,KAAM,IACN,MAAO,IACP,aAAc,KACd,aAAc,KACd,QAAS,MACT,OAAQ,KACR,YAAa,KACb,QAAS,IACT,MAAO,IACP,MAAO,GACT,EAOA,SAAS,EAAgB,EAA8B,CACrD,OAAO,EAAe,IAAK,GAAS,CAClC,IAAM,EAAS,EAAM,GAErB,OAAO,OAAO,GAAW,SAAW,GAAG,IAAS,EAAgB,KAAU,IAAA,EAC5E,CAAC,CAAC,CACC,OAAQ,GAAyB,IAAS,IAAA,EAAS,CAAC,CACpD,KAAK,GAAG,CACb,CAQA,SAAgB,EAAgB,EAA4C,CAC1E,IAAM,EAAc,IAAI,IAClB,EAAgB,IAAI,IACpB,EAAY,IAAI,IAChB,EAAgB,IAAI,IACpB,EAAY,IAAI,IAChB,EAAgB,IAAI,IAEpB,EAAY,OAAO,GAAW,aAAiB,EAAS,EAE9D,SAAS,EAAU,EAAgB,EAA0B,CAC3D,GAAI,CAAC,EAAS,OAAO,EAErB,IAAM,EAAkC,CAAC,EAEzC,IAAK,IAA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,CACnD,CAAC,CAAC,OAAO,CAAK,CAChB,EAEA,OAAO,EAAO,EAAS,CACrB,IAAM,EAAS,EAAU,EAEzB,OAAO,EAAY,EAAa,EAAU,EAAQ,CAAO,MAAS,IAAI,KAAK,aAAa,EAAQ,CAAO,CAAC,CAAC,CAAC,OACxG,CACF,CACF,EAEA,SAAS,EAAO,EAAM,EAAS,CAC7B,IAAM,EAAS,EAAU,EAEzB,OAAO,EACL,EACA,EAAU,EAAQ,CAAO,MACnB,IAAI,KAAK,mBAAmB,EAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,EAAO,CAAI,CACtB,CACF,CACF"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * /lingua/format
3
+ *
4
+ * Standalone Intl formatter factory. Import from `/lingua/format`.
5
+ * Creates formatters for numbers, dates, currencies, lists, durations, and relative time.
6
+ *
7
+ * Pass a static locale string or a reactive locale getter.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { createFormatter } from '@vielzeug/lingua/format';
12
+ *
13
+ * // Static locale
14
+ * const fmt = createFormatter('en-US');
15
+ *
16
+ * // Reactive — always reads the current locale from the i18n instance
17
+ * const fmt = createFormatter(() => i18n.locale);
18
+ *
19
+ * fmt.number(1_234.56);
20
+ * fmt.currency(9.99, 'USD');
21
+ * fmt.date(new Date());
22
+ * fmt.relative(-1, 'day');
23
+ * fmt.list(['A', 'B', 'C']);
24
+ * fmt.duration({ hours: 1, minutes: 30 });
25
+ * ```
26
+ */
27
+ export type DurationValue = Partial<Record<'days' | 'hours' | 'microseconds' | 'milliseconds' | 'minutes' | 'months' | 'nanoseconds' | 'seconds' | 'weeks' | 'years', number>>;
28
+ export type DurationFormatOptions = {
29
+ hours?: '2-digit' | 'numeric';
30
+ microseconds?: 'numeric';
31
+ milliseconds?: 'numeric';
32
+ minutes?: '2-digit' | 'numeric';
33
+ nanoseconds?: 'numeric';
34
+ seconds?: '2-digit' | 'numeric';
35
+ style?: 'digital' | 'long' | 'narrow' | 'short';
36
+ };
37
+ export type ListFormatOptions = {
38
+ style?: 'long' | 'narrow' | 'short';
39
+ type?: 'and' | 'or';
40
+ };
41
+ export type Formatter = {
42
+ /**
43
+ * Clears all cached `Intl` formatter instances. Useful after a locale change on a long-running
44
+ * SSR server, or to reclaim memory.
45
+ *
46
+ * @note This clears the cache for **all callers sharing this formatter instance**. When called on
47
+ * `i18n.fmt`, the cache is cleared for every part of the application that reads `i18n.fmt`.
48
+ * `setLocale()` already calls `clear()` automatically — manual calls are rarely needed.
49
+ */
50
+ clear(): void;
51
+ currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;
52
+ date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
53
+ /**
54
+ * Formats a duration using `Intl.DurationFormat` when available, or a compact labeled fallback
55
+ * (e.g. `'1h 30min'`). Returns `''` when every field of `value` is `undefined`.
56
+ *
57
+ * @note The fallback labels (`h`, `min`, `s`, `ms`, etc.) are English-only and are not
58
+ * locale-aware. If `Intl.DurationFormat` is unavailable in your target environment and
59
+ * you need localised duration output, provide your own formatter using the individual
60
+ * duration fields from `DurationValue`.
61
+ */
62
+ duration(value: DurationValue, options?: DurationFormatOptions): string;
63
+ list(value: Array<string | number>, options?: ListFormatOptions): string;
64
+ /** Formats a number with the current locale. */
65
+ number(value: number, options?: Intl.NumberFormatOptions): string;
66
+ relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
67
+ };
68
+ /**
69
+ * Creates a formatter bound to a locale. Pass a static locale string or a
70
+ * reactive getter function `() => string` (e.g. `() => i18n.locale`).
71
+ */
72
+ export declare function createFormatter(source: string | (() => string)): Formatter;
73
+ //# sourceMappingURL=format.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAkBH,MAAM,MAAM,aAAa,GAAG,OAAO,CAC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,GAAG,MAAM,CAAC;IACzE,gDAAgD;IAChD,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,GAAG,MAAM,CAAC;IAClE,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,yBAAyB,GAAG,MAAM,CAAC;CAC9G,CAAC;AA+CF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,SAAS,CAyG1E"}
package/dist/format.js ADDED
@@ -0,0 +1,91 @@
1
+ function e(e, t, n) {
2
+ let r = e.get(t);
3
+ if (r !== void 0) return r;
4
+ let i = n();
5
+ return e.size >= 128 && e.delete(e.keys().next().value), e.set(t, i), i;
6
+ }
7
+ var t = [
8
+ "years",
9
+ "months",
10
+ "weeks",
11
+ "days",
12
+ "hours",
13
+ "minutes",
14
+ "seconds",
15
+ "milliseconds",
16
+ "microseconds",
17
+ "nanoseconds"
18
+ ], n = {
19
+ days: "d",
20
+ hours: "h",
21
+ microseconds: "us",
22
+ milliseconds: "ms",
23
+ minutes: "min",
24
+ months: "mo",
25
+ nanoseconds: "ns",
26
+ seconds: "s",
27
+ weeks: "w",
28
+ years: "y"
29
+ };
30
+ function r(e) {
31
+ return t.map((t) => {
32
+ let r = e[t];
33
+ return typeof r == "number" ? `${r}${n[t]}` : void 0;
34
+ }).filter((e) => e !== void 0).join(" ");
35
+ }
36
+ function i(n) {
37
+ let i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = typeof n == "string" ? () => n : n;
38
+ function d(e, t) {
39
+ if (!t) return e;
40
+ let n = {};
41
+ for (let e of Object.keys(t).sort()) n[e] = t[e];
42
+ try {
43
+ return `${e}:${JSON.stringify(n)}`;
44
+ } catch {
45
+ return e;
46
+ }
47
+ }
48
+ return {
49
+ clear() {
50
+ i.clear(), a.clear(), o.clear(), s.clear(), c.clear(), l.clear();
51
+ },
52
+ currency(t, n, r) {
53
+ let i = u(), o = {
54
+ ...r,
55
+ currency: n,
56
+ style: "currency"
57
+ };
58
+ return e(a, d(i, o), () => new Intl.NumberFormat(i, o)).format(t);
59
+ },
60
+ date(t, n) {
61
+ let r = u();
62
+ return e(o, d(r, n), () => new Intl.DateTimeFormat(r, n)).format(t);
63
+ },
64
+ duration(n, i) {
65
+ let a = u(), o = Intl;
66
+ return o.DurationFormat ? t.every((e) => n[e] === void 0) ? "" : e(l, d(a, i), () => new o.DurationFormat(a, i)).format(n) : r(n);
67
+ },
68
+ list(t, n) {
69
+ let r = u(), i = t.map((e) => String(e)), a = n?.style ?? "long", o = n?.type === "or" ? "disjunction" : "conjunction";
70
+ return e(c, d(r, {
71
+ style: a,
72
+ type: o
73
+ }), () => new Intl.ListFormat(r, {
74
+ style: a,
75
+ type: o
76
+ })).format(i);
77
+ },
78
+ number(t, n) {
79
+ let r = u();
80
+ return e(i, d(r, n), () => new Intl.NumberFormat(r, n)).format(t);
81
+ },
82
+ relative(t, n, r) {
83
+ let i = u();
84
+ return e(s, d(i, r), () => new Intl.RelativeTimeFormat(i, r)).format(t, n);
85
+ }
86
+ };
87
+ }
88
+ //#endregion
89
+ export { i as createFormatter };
90
+
91
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["/**\n * /lingua/format\n *\n * Standalone Intl formatter factory. Import from `/lingua/format`.\n * Creates formatters for numbers, dates, currencies, lists, durations, and relative time.\n *\n * Pass a static locale string or a reactive locale getter.\n *\n * @example\n * ```ts\n * import { createFormatter } from '@vielzeug/lingua/format';\n *\n * // Static locale\n * const fmt = createFormatter('en-US');\n *\n * // Reactive — always reads the current locale from the i18n instance\n * const fmt = createFormatter(() => i18n.locale);\n *\n * fmt.number(1_234.56);\n * fmt.currency(9.99, 'USD');\n * fmt.date(new Date());\n * fmt.relative(-1, 'day');\n * fmt.list(['A', 'B', 'C']);\n * fmt.duration({ hours: 1, minutes: 30 });\n * ```\n */\n\nconst FORMAT_CACHE_MAX = 128;\n\nfunction getOrCreate<F>(cache: Map<string, F>, key: string, build: () => F): F {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n const value = build();\n\n if (cache.size >= FORMAT_CACHE_MAX) cache.delete(cache.keys().next().value as string);\n\n cache.set(key, value);\n\n return value;\n}\n\nexport type DurationValue = Partial<\n Record<\n | 'days'\n | 'hours'\n | 'microseconds'\n | 'milliseconds'\n | 'minutes'\n | 'months'\n | 'nanoseconds'\n | 'seconds'\n | 'weeks'\n | 'years',\n number\n >\n>;\n\nexport type DurationFormatOptions = {\n hours?: '2-digit' | 'numeric';\n microseconds?: 'numeric';\n milliseconds?: 'numeric';\n minutes?: '2-digit' | 'numeric';\n nanoseconds?: 'numeric';\n seconds?: '2-digit' | 'numeric';\n style?: 'digital' | 'long' | 'narrow' | 'short';\n};\n\nexport type ListFormatOptions = {\n style?: 'long' | 'narrow' | 'short';\n type?: 'and' | 'or';\n};\n\nexport type Formatter = {\n /**\n * Clears all cached `Intl` formatter instances. Useful after a locale change on a long-running\n * SSR server, or to reclaim memory.\n *\n * @note This clears the cache for **all callers sharing this formatter instance**. When called on\n * `i18n.fmt`, the cache is cleared for every part of the application that reads `i18n.fmt`.\n * `setLocale()` already calls `clear()` automatically — manual calls are rarely needed.\n */\n clear(): void;\n currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;\n /**\n * Formats a duration using `Intl.DurationFormat` when available, or a compact labeled fallback\n * (e.g. `'1h 30min'`). Returns `''` when every field of `value` is `undefined`.\n *\n * @note The fallback labels (`h`, `min`, `s`, `ms`, etc.) are English-only and are not\n * locale-aware. If `Intl.DurationFormat` is unavailable in your target environment and\n * you need localised duration output, provide your own formatter using the individual\n * duration fields from `DurationValue`.\n */\n duration(value: DurationValue, options?: DurationFormatOptions): string;\n list(value: Array<string | number>, options?: ListFormatOptions): string;\n /** Formats a number with the current locale. */\n number(value: number, options?: Intl.NumberFormatOptions): string;\n relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;\n};\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nconst DURATION_UNITS: Array<keyof DurationValue> = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n];\n\nconst DURATION_LABELS: Record<keyof DurationValue, string> = {\n days: 'd',\n hours: 'h',\n microseconds: 'us',\n milliseconds: 'ms',\n minutes: 'min',\n months: 'mo',\n nanoseconds: 'ns',\n seconds: 's',\n weeks: 'w',\n years: 'y',\n};\n\ntype DurationFormatterCtor = new (\n locale: string,\n options?: DurationFormatOptions,\n) => { format(value: DurationValue): string };\n\nfunction durationLabeled(value: DurationValue): string {\n return DURATION_UNITS.map((unit) => {\n const amount = value[unit];\n\n return typeof amount === 'number' ? `${amount}${DURATION_LABELS[unit]}` : undefined;\n })\n .filter((part): part is string => part !== undefined)\n .join(' ');\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a formatter bound to a locale. Pass a static locale string or a\n * reactive getter function `() => string` (e.g. `() => i18n.locale`).\n */\nexport function createFormatter(source: string | (() => string)): Formatter {\n const numberCache = new Map<string, Intl.NumberFormat>();\n const currencyCache = new Map<string, Intl.NumberFormat>();\n const dateCache = new Map<string, Intl.DateTimeFormat>();\n const relativeCache = new Map<string, Intl.RelativeTimeFormat>();\n const listCache = new Map<string, Intl.ListFormat>();\n const durationCache = new Map<string, { format(value: DurationValue): string }>();\n\n const getLocale = typeof source === 'string' ? () => source : source;\n\n function cachedKey(locale: string, options?: object): string {\n if (!options) return locale;\n\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(options as Record<string, unknown>).sort()) {\n sorted[key] = (options as Record<string, unknown>)[key];\n }\n\n try {\n return `${locale}:${JSON.stringify(sorted)}`;\n } catch {\n // Circular references or BigInt values — fall back to locale-only key.\n // Multiple callers with different unserializable options will share the same formatter instance.\n return locale;\n }\n }\n\n return {\n clear() {\n numberCache.clear();\n currencyCache.clear();\n dateCache.clear();\n relativeCache.clear();\n listCache.clear();\n durationCache.clear();\n },\n\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(currencyCache, cachedKey(locale, opts), () => new Intl.NumberFormat(locale, opts)).format(\n value,\n );\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(dateCache, cachedKey(locale, options), () => new Intl.DateTimeFormat(locale, options)).format(\n value,\n );\n },\n\n duration(value, options) {\n const locale = getLocale();\n const IntlExt = Intl as typeof Intl & { DurationFormat?: DurationFormatterCtor };\n\n if (!IntlExt.DurationFormat) return durationLabeled(value);\n\n if (DURATION_UNITS.every((u) => value[u] === undefined)) return '';\n\n return getOrCreate(\n durationCache,\n cachedKey(locale, options),\n () => new IntlExt.DurationFormat!(locale, options),\n ).format(value);\n },\n\n list(value, options) {\n const locale = getLocale();\n const items = value.map((v) => String(v));\n // list() has exactly two string options with small finite value domains.\n // We normalize both to their resolved defaults and build the key directly\n // rather than using cachedKey(). This also prevents cache misses when\n // callers pass { style: 'long', type: 'and' } vs {} (same ListFormat).\n const style = options?.style ?? 'long';\n const type = options?.type === 'or' ? 'disjunction' : 'conjunction';\n\n return getOrCreate(\n listCache,\n cachedKey(locale, { style, type }),\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(numberCache, cachedKey(locale, options), () => new Intl.NumberFormat(locale, options)).format(\n value,\n );\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":"AA6BA,SAAS,EAAe,GAAuB,GAAa,GAAmB;CAC7E,IAAM,IAAS,EAAM,IAAI,CAAG;CAE5B,IAAI,MAAW,KAAA,GAAW,OAAO;CAEjC,IAAM,IAAQ,EAAM;CAMpB,OAJI,EAAM,QAAQ,OAAkB,EAAM,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAe,GAEpF,EAAM,IAAI,GAAK,CAAK,GAEb;AACT;AA+DA,IAAM,IAA6C;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,GAEM,IAAuD;CAC3D,MAAM;CACN,OAAO;CACP,cAAc;CACd,cAAc;CACd,SAAS;CACT,QAAQ;CACR,aAAa;CACb,SAAS;CACT,OAAO;CACP,OAAO;AACT;AAOA,SAAS,EAAgB,GAA8B;CACrD,OAAO,EAAe,KAAK,MAAS;EAClC,IAAM,IAAS,EAAM;EAErB,OAAO,OAAO,KAAW,WAAW,GAAG,IAAS,EAAgB,OAAU,KAAA;CAC5E,CAAC,CAAC,CACC,QAAQ,MAAyB,MAAS,KAAA,CAAS,CAAC,CACpD,KAAK,GAAG;AACb;AAQA,SAAgB,EAAgB,GAA4C;CAC1E,IAAM,oBAAc,IAAI,IAA+B,GACjD,oBAAgB,IAAI,IAA+B,GACnD,oBAAY,IAAI,IAAiC,GACjD,oBAAgB,IAAI,IAAqC,GACzD,oBAAY,IAAI,IAA6B,GAC7C,oBAAgB,IAAI,IAAsD,GAE1E,IAAY,OAAO,KAAW,iBAAiB,IAAS;CAE9D,SAAS,EAAU,GAAgB,GAA0B;EAC3D,IAAI,CAAC,GAAS,OAAO;EAErB,IAAM,IAAkC,CAAC;EAEzC,KAAK,IAAM,KAAO,OAAO,KAAK,CAAkC,CAAC,CAAC,KAAK,GACrE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,OAAO,GAAO,GAAS;GACrB,IAAM,IAAS,EAAU;GAEzB,OAAO,EAAY,GAAa,EAAU,GAAQ,CAAO,SAAS,IAAI,KAAK,aAAa,GAAQ,CAAO,CAAC,CAAC,CAAC,OACxG,CACF;EACF;EAEA,SAAS,GAAO,GAAM,GAAS;GAC7B,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,SACnB,IAAI,KAAK,mBAAmB,GAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,GAAO,CAAI;EACtB;CACF;AACF"}
package/dist/i18n.cjs ADDED
@@ -0,0 +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),w=p.onMissingVar??(e=>`{${e}}`),T=p.onSubscriberError??(e=>t.error(`subscriber error`,e)),E,D=new Map,O=()=>(E||=e.createFormatter(()=>x.locale),E),k=e=>{for(let t of x.chain){let n=y.resolve(t)?.get(e);if(n!==void 0)return n}},A=e=>{if(k(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},j=(e,t,r)=>n.renderTemplate(t.compiled,r,e,x.locale,w),M=(e,t)=>{let n=String(e),r=k(n);return r?j(n,r,t):C(n,x.locale)},N=(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 j(e,t,c)}}return C(s,x.locale)},P={locale:x.locale,t:M,tp:N},F=()=>{P={locale:x.locale,t:M,tp:N};let e=[...S];for(let t of e)try{t(P)}catch(e){T(e)}};if(y.onChange=e=>{x.chainSet.has(e)&&F()},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 I=e=>y.preload(h(e)),L=0;return{get disposalSignal(){return v.signal},dispose(){_||(_=!0,v.abort(),S.clear(),y.dispose(),b.dispose(),D.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 O()},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 P},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 A(String(e))},isLoaded(e){try{return y.isLoaded(h(e))}catch{return!1}},isNamespaceLoaded(e,t){return b.isLoaded(e,t?h(t):x.locale)},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:I,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;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),b.clearLocale(e)}y.dispose(),y.onChange=e=>{x.chainSet.has(e)&&F()},y.seedFrom(t,new Map),x=c(h(e.locale),g,m),E?.clear(),F()},scope(e){let t=String(e),n=D.get(t);if(n)return n;let r={get fmt(){return O()},has:e=>A(`${t}.${e}`),t:(e,n)=>M(`${t}.${e}`,n),tp:(e,n,r)=>N(`${t}.${e}`,n,r)};return D.set(t,r),r},async setLocale(e){i.checkDisposed(_);let t=h(e);if(x.locale===t)return;let n=++L;await I(t),!(_||L!==n)&&(x=c(t,g,m),E?.clear(),F())},subscribe:(e,t)=>{let n=()=>{S.delete(e)};if(_)throw new i.LinguaDisposedError;if(t?.signal?.aborted)return n;if(t?.immediate===!0)try{e(P)}catch(e){return T(e),n}return S.add(e),t?.signal?.addEventListener(`abort`,n,{once:!0}),n},[Symbol.dispose](){this.dispose()},t:M,tp:N}}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
+ //# sourceMappingURL=i18n.cjs.map
@@ -0,0 +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,EA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