@vielzeug/lingua 1.1.3 → 2.0.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 (110) hide show
  1. package/README.md +15 -54
  2. package/dist/_bounded-cache.cjs +2 -0
  3. package/dist/_bounded-cache.cjs.map +1 -0
  4. package/dist/_bounded-cache.d.ts +2 -0
  5. package/dist/_bounded-cache.d.ts.map +1 -0
  6. package/dist/_bounded-cache.js +10 -0
  7. package/dist/_bounded-cache.js.map +1 -0
  8. package/dist/_catalog.cjs +1 -1
  9. package/dist/_catalog.cjs.map +1 -1
  10. package/dist/_catalog.d.ts +13 -16
  11. package/dist/_catalog.d.ts.map +1 -1
  12. package/dist/_catalog.js +43 -36
  13. package/dist/_catalog.js.map +1 -1
  14. package/dist/_dev.cjs +1 -1
  15. package/dist/_dev.cjs.map +1 -1
  16. package/dist/_dev.js +3 -8
  17. package/dist/_dev.js.map +1 -1
  18. package/dist/_locale.cjs +2 -0
  19. package/dist/_locale.cjs.map +1 -0
  20. package/dist/_locale.d.ts +5 -0
  21. package/dist/_locale.d.ts.map +1 -0
  22. package/dist/_locale.js +26 -0
  23. package/dist/_locale.js.map +1 -0
  24. package/dist/_resources.cjs +2 -0
  25. package/dist/_resources.cjs.map +1 -0
  26. package/dist/_resources.d.ts +10 -0
  27. package/dist/_resources.d.ts.map +1 -0
  28. package/dist/_resources.js +51 -0
  29. package/dist/_resources.js.map +1 -0
  30. package/dist/_template.cjs +2 -0
  31. package/dist/_template.cjs.map +1 -0
  32. package/dist/_template.d.ts +8 -0
  33. package/dist/_template.d.ts.map +1 -0
  34. package/dist/_template.js +32 -0
  35. package/dist/_template.js.map +1 -0
  36. package/dist/errors.cjs +1 -1
  37. package/dist/errors.cjs.map +1 -1
  38. package/dist/errors.d.ts +6 -18
  39. package/dist/errors.d.ts.map +1 -1
  40. package/dist/errors.js +3 -9
  41. package/dist/errors.js.map +1 -1
  42. package/dist/format.cjs +1 -1
  43. package/dist/format.cjs.map +1 -1
  44. package/dist/format.d.ts +0 -9
  45. package/dist/format.d.ts.map +1 -1
  46. package/dist/format.js +40 -46
  47. package/dist/format.js.map +1 -1
  48. package/dist/i18n.cjs +1 -1
  49. package/dist/i18n.cjs.map +1 -1
  50. package/dist/i18n.d.ts +25 -39
  51. package/dist/i18n.d.ts.map +1 -1
  52. package/dist/i18n.js +65 -218
  53. package/dist/i18n.js.map +1 -1
  54. package/dist/index.cjs +1 -1
  55. package/dist/index.d.ts +4 -12
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +4 -4
  58. package/dist/lingua.cjs +1 -1
  59. package/dist/lingua.cjs.map +1 -1
  60. package/dist/lingua.iife.js +1 -1
  61. package/dist/lingua.iife.js.map +1 -1
  62. package/dist/lingua.js +1 -1
  63. package/dist/lingua.js.map +1 -1
  64. package/dist/translator.cjs +2 -0
  65. package/dist/translator.cjs.map +1 -0
  66. package/dist/translator.d.ts +20 -0
  67. package/dist/translator.d.ts.map +1 -0
  68. package/dist/translator.js +61 -0
  69. package/dist/translator.js.map +1 -0
  70. package/dist/types.d.ts +53 -0
  71. package/dist/types.d.ts.map +1 -0
  72. package/dist/validate.cjs +1 -1
  73. package/dist/validate.cjs.map +1 -1
  74. package/dist/validate.d.ts +5 -36
  75. package/dist/validate.d.ts.map +1 -1
  76. package/dist/validate.js +21 -52
  77. package/dist/validate.js.map +1 -1
  78. package/package.json +4 -4
  79. package/dist/_catalog-store.cjs +0 -2
  80. package/dist/_catalog-store.cjs.map +0 -1
  81. package/dist/_catalog-store.d.ts +0 -33
  82. package/dist/_catalog-store.d.ts.map +0 -1
  83. package/dist/_catalog-store.js +0 -74
  84. package/dist/_catalog-store.js.map +0 -1
  85. package/dist/_chain.cjs +0 -2
  86. package/dist/_chain.cjs.map +0 -1
  87. package/dist/_chain.d.ts +0 -21
  88. package/dist/_chain.d.ts.map +0 -1
  89. package/dist/_chain.js +0 -45
  90. package/dist/_chain.js.map +0 -1
  91. package/dist/_constants.cjs +0 -2
  92. package/dist/_constants.cjs.map +0 -1
  93. package/dist/_constants.d.ts +0 -3
  94. package/dist/_constants.d.ts.map +0 -1
  95. package/dist/_constants.js +0 -17
  96. package/dist/_constants.js.map +0 -1
  97. package/dist/_namespace-store.cjs +0 -2
  98. package/dist/_namespace-store.cjs.map +0 -1
  99. package/dist/_namespace-store.d.ts +0 -31
  100. package/dist/_namespace-store.d.ts.map +0 -1
  101. package/dist/_namespace-store.js +0 -54
  102. package/dist/_namespace-store.js.map +0 -1
  103. package/dist/i18n-types.d.ts +0 -250
  104. package/dist/i18n-types.d.ts.map +0 -1
  105. package/dist/template.cjs +0 -2
  106. package/dist/template.cjs.map +0 -1
  107. package/dist/template.d.ts +0 -15
  108. package/dist/template.d.ts.map +0 -1
  109. package/dist/template.js +0 -49
  110. package/dist/template.js.map +0 -1
package/dist/errors.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e=class e extends Error{constructor(e,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;
1
+ var e=class e extends Error{constructor(e,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 translation store.`)}},n=class extends e{},r=class extends e{},i=class extends e{},a=class extends e{},o=class extends e{};exports.LinguaDisposedError=t,exports.LinguaError=e,exports.LinguaInvalidCatalogError=n,exports.LinguaInvalidLocaleError=r,exports.LinguaInvalidPluralCountError=i,exports.LinguaInvalidStateError=a,exports.LinguaMissingCatalogError=o;
2
2
  //# sourceMappingURL=errors.cjs.map
@@ -1 +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"}
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(error: unknown): error is LinguaError {\n return error instanceof LinguaError;\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed translation store.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaInvalidStateError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\n"],"mappings":"AAAA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CAEA,OAAO,GAAG,EAAsC,CAC9C,OAAO,aAAiB,CAC1B,CACF,EAEa,EAAb,cAAyC,CAAY,CACnD,aAAc,CACZ,MAAM,mDAAmD,CAC3D,CACF,EAEa,EAAb,cAA+C,CAAY,CAAC,EAC/C,EAAb,cAA8C,CAAY,CAAC,EAC9C,EAAb,cAAmD,CAAY,CAAC,EACnD,EAAb,cAA6C,CAAY,CAAC,EAC7C,EAAb,cAA+C,CAAY,CAAC"}
package/dist/errors.d.ts CHANGED
@@ -1,30 +1,18 @@
1
- /** Base class for all lingua errors. Use `instanceof LinguaError` or `LinguaError.is()` to catch any lingua-originated error. */
2
1
  export declare class LinguaError extends Error {
3
2
  constructor(message: string, opts?: ErrorOptions);
4
- static is(err: unknown): err is LinguaError;
3
+ static is(error: unknown): error is LinguaError;
5
4
  }
6
- /** Thrown when a method is called on a disposed i18n instance. */
7
5
  export declare class LinguaDisposedError extends LinguaError {
8
6
  constructor();
9
7
  }
10
- /** Thrown when `tp()` receives a non-finite `count` value. */
11
- export declare class LinguaInvalidCountError extends LinguaError {
8
+ export declare class LinguaInvalidCatalogError extends LinguaError {
12
9
  }
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
10
  export declare class LinguaInvalidLocaleError extends LinguaError {
21
11
  }
22
- /** Thrown when `loadNamespace()` / `extend()` is called for a namespace that has not been registered with `registerNamespace()`. */
23
- export declare class LinguaNamespaceMissingError extends LinguaError {
12
+ export declare class LinguaInvalidPluralCountError extends LinguaError {
13
+ }
14
+ export declare class LinguaInvalidStateError extends LinguaError {
24
15
  }
25
- /** Thrown when restoring i18n state whose locale has no catalog. */
26
- export declare class LinguaRestoreError extends LinguaError {
16
+ export declare class LinguaMissingCatalogError extends LinguaError {
27
17
  }
28
- export declare function checkDisposed(disposed: boolean): void;
29
- export declare function checkDisposedAsync(disposed: boolean): Promise<never> | null;
30
18
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3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;CAAG;AAC3D,qBAAa,yBAA0B,SAAQ,WAAW;CAAG"}
package/dist/errors.js CHANGED
@@ -8,16 +8,10 @@ var e = class e extends Error {
8
8
  }
9
9
  }, t = class extends e {
10
10
  constructor() {
11
- super("Operation called on a disposed i18n instance.");
11
+ super("Operation called on a disposed translation store.");
12
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
- }
13
+ }, n = class extends e {}, r = class extends e {}, i = class extends e {}, a = class extends e {}, o = class extends e {};
20
14
  //#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 };
15
+ export { t as LinguaDisposedError, e as LinguaError, n as LinguaInvalidCatalogError, r as LinguaInvalidLocaleError, i as LinguaInvalidPluralCountError, a as LinguaInvalidStateError, o as LinguaMissingCatalogError };
22
16
 
23
17
  //# sourceMappingURL=errors.js.map
@@ -1 +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"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(error: unknown): error is LinguaError {\n return error instanceof LinguaError;\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed translation store.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaInvalidStateError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\n"],"mappings":";AAAA,IAAa,IAAb,MAAa,UAAoB,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAM,GAAS,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;CAEA,OAAO,GAAG,GAAsC;EAC9C,OAAO,aAAiB;CAC1B;AACF,GAEa,IAAb,cAAyC,EAAY;CACnD,cAAc;EACZ,MAAM,mDAAmD;CAC3D;AACF,GAEa,IAAb,cAA+C,EAAY,CAAC,GAC/C,IAAb,cAA8C,EAAY,CAAC,GAC9C,IAAb,cAAmD,EAAY,CAAC,GACnD,IAAb,cAA6C,EAAY,CAAC,GAC7C,IAAb,cAA+C,EAAY,CAAC"}
package/dist/format.cjs CHANGED
@@ -1,2 +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;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./_bounded-cache.cjs");require("./_dev.cjs");var t=128,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(r){let a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=typeof r==`string`?()=>r:r,f=!1;function p(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 f||=!0,e}}return{currency(n,r,i){let a=d(),s={...i,currency:r,style:`currency`};return e.getOrCreate(o,p(a,s),t,()=>new Intl.NumberFormat(a,s)).format(n)},date(n,r){let i=d();return e.getOrCreate(s,p(i,r),t,()=>new Intl.DateTimeFormat(i,r)).format(n)},duration(r,a){let o=d(),s=Intl;return s.DurationFormat?n.every(e=>r[e]===void 0)?``:e.getOrCreate(u,p(o,a),t,()=>new s.DurationFormat(o,a)).format(r):i(r)},list(n,r){let i=d(),a=n.map(e=>String(e)),o=r?.style??`long`,s=r?.type===`or`?`disjunction`:`conjunction`;return e.getOrCreate(l,p(i,{style:o,type:s}),t,()=>new Intl.ListFormat(i,{style:o,type:s})).format(a)},number(n,r){let i=d();return e.getOrCreate(a,p(i,r),t,()=>new Intl.NumberFormat(i,r)).format(n)},relative(n,r,i){let a=d();return e.getOrCreate(c,p(a,i),t,()=>new Intl.RelativeTimeFormat(a,i)).format(n,r)}}}exports.createFormatter=a;
2
2
  //# sourceMappingURL=format.cjs.map
@@ -1 +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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AAO,CAAI,CACtB,CACF,CACF"}
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\nimport { getOrCreate } from './_bounded-cache';\nimport { warn } from './_dev';\n\nconst FORMAT_CACHE_MAX = 128;\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 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 // Warn at most once per formatter instance on the unserializable-options fallback —\n // a hot render loop with such options must not spam the console on every call.\n let warnedUnserializable = false;\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\n // formatter instance; never silently.\n if (!warnedUnserializable) {\n warnedUnserializable = true;\n warn('formatter options could not be serialized — falling back to a shared per-locale formatter instance.');\n }\n\n return locale;\n }\n }\n\n return {\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(\n currencyCache,\n cachedKey(locale, opts),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, opts),\n ).format(value);\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n dateCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.DateTimeFormat(locale, options),\n ).format(value);\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 FORMAT_CACHE_MAX,\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 FORMAT_CACHE_MAX,\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n numberCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, options),\n ).format(value);\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":"iIA8BA,IAAM,EAAmB,IAsDnB,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,EAI1D,EAAuB,GAE3B,SAAS,EAAU,EAAgB,EAA0B,CAC3D,GAAI,CAAC,EAAS,OAAO,EAErB,IAAM,EAAkC,CAAC,EAEzC,IAAK,IAAM,KAAO,OAAO,KAAK,CAAkC,CAAC,CAAC,KAAK,EACrE,EAAO,GAAQ,EAAoC,GAGrD,GAAI,CACF,MAAO,GAAG,EAAO,GAAG,KAAK,UAAU,CAAM,GAC3C,MAAQ,C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EAEA,SAAS,EAAO,EAAM,EAAS,CAC7B,IAAM,EAAS,EAAU,EAEzB,OAAO,EAAA,YACL,EACA,EAAU,EAAQ,CAAO,EACzB,MACM,IAAI,KAAK,mBAAmB,EAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,EAAO,CAAI,CACtB,CACF,CACF"}
package/dist/format.d.ts CHANGED
@@ -39,15 +39,6 @@ export type ListFormatOptions = {
39
39
  type?: 'and' | 'or';
40
40
  };
41
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
42
  currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;
52
43
  date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
53
44
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAkBH,MAAM,MAAM,aAAa,GAAG,OAAO,CACjC,MAAM,CACF,MAAM,GACN,OAAO,GACP,cAAc,GACd,cAAc,GACd,SAAS,GACT,QAAQ,GACR,aAAa,GACb,SAAS,GACT,OAAO,GACP,OAAO,EACT,MAAM,CACP,CACF,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,KAAK,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAC9B,YAAY,CAAC,EAAE,SAAS,CAAC;IACzB,YAAY,CAAC,EAAE,SAAS,CAAC;IACzB,OAAO,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAChC,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,OAAO,CAAC,EAAE,SAAS,GAAG,SAAS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E,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,OAAO,CAAC,EAAE,iBAAiB,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,CAsH1E"}
package/dist/format.js CHANGED
@@ -1,10 +1,7 @@
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 = [
1
+ import { getOrCreate as e } from "./_bounded-cache.js";
2
+ import "./_dev.js";
3
+ //#region src/format.ts
4
+ var t = 128, n = [
8
5
  "years",
9
6
  "months",
10
7
  "weeks",
@@ -15,7 +12,7 @@ var t = [
15
12
  "milliseconds",
16
13
  "microseconds",
17
14
  "nanoseconds"
18
- ], n = {
15
+ ], r = {
19
16
  days: "d",
20
17
  hours: "h",
21
18
  microseconds: "us",
@@ -27,65 +24,62 @@ var t = [
27
24
  weeks: "w",
28
25
  years: "y"
29
26
  };
30
- function r(e) {
31
- return t.map((t) => {
32
- let r = e[t];
33
- return typeof r == "number" ? `${r}${n[t]}` : void 0;
27
+ function i(e) {
28
+ return n.map((t) => {
29
+ let n = e[t];
30
+ return typeof n == "number" ? `${n}${r[t]}` : void 0;
34
31
  }).filter((e) => e !== void 0).join(" ");
35
32
  }
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) {
33
+ function a(r) {
34
+ let a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = typeof r == "string" ? () => r : r, f = !1;
35
+ function p(e, t) {
39
36
  if (!t) return e;
40
37
  let n = {};
41
38
  for (let e of Object.keys(t).sort()) n[e] = t[e];
42
39
  try {
43
40
  return `${e}:${JSON.stringify(n)}`;
44
41
  } catch {
45
- return e;
42
+ return f ||= !0, e;
46
43
  }
47
44
  }
48
45
  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,
46
+ currency(n, r, i) {
47
+ let a = d(), s = {
48
+ ...i,
49
+ currency: r,
56
50
  style: "currency"
57
51
  };
58
- return e(a, d(i, o), () => new Intl.NumberFormat(i, o)).format(t);
52
+ return e(o, p(a, s), t, () => new Intl.NumberFormat(a, s)).format(n);
59
53
  },
60
- date(t, n) {
61
- let r = u();
62
- return e(o, d(r, n), () => new Intl.DateTimeFormat(r, n)).format(t);
54
+ date(n, r) {
55
+ let i = d();
56
+ return e(s, p(i, r), t, () => new Intl.DateTimeFormat(i, r)).format(n);
63
57
  },
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);
58
+ duration(r, a) {
59
+ let o = d(), s = Intl;
60
+ return s.DurationFormat ? n.every((e) => r[e] === void 0) ? "" : e(u, p(o, a), t, () => new s.DurationFormat(o, a)).format(r) : i(r);
67
61
  },
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);
62
+ list(n, r) {
63
+ let i = d(), a = n.map((e) => String(e)), o = r?.style ?? "long", s = r?.type === "or" ? "disjunction" : "conjunction";
64
+ return e(l, p(i, {
65
+ style: o,
66
+ type: s
67
+ }), t, () => new Intl.ListFormat(i, {
68
+ style: o,
69
+ type: s
70
+ })).format(a);
77
71
  },
78
- number(t, n) {
79
- let r = u();
80
- return e(i, d(r, n), () => new Intl.NumberFormat(r, n)).format(t);
72
+ number(n, r) {
73
+ let i = d();
74
+ return e(a, p(i, r), t, () => new Intl.NumberFormat(i, r)).format(n);
81
75
  },
82
- relative(t, n, r) {
83
- let i = u();
84
- return e(s, d(i, r), () => new Intl.RelativeTimeFormat(i, r)).format(t, n);
76
+ relative(n, r, i) {
77
+ let a = d();
78
+ return e(c, p(a, i), t, () => new Intl.RelativeTimeFormat(a, i)).format(n, r);
85
79
  }
86
80
  };
87
81
  }
88
82
  //#endregion
89
- export { i as createFormatter };
83
+ export { a as createFormatter };
90
84
 
91
85
  //# sourceMappingURL=format.js.map
@@ -1 +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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AO,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"}
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\nimport { getOrCreate } from './_bounded-cache';\nimport { warn } from './_dev';\n\nconst FORMAT_CACHE_MAX = 128;\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 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 // Warn at most once per formatter instance on the unserializable-options fallback —\n // a hot render loop with such options must not spam the console on every call.\n let warnedUnserializable = false;\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\n // formatter instance; never silently.\n if (!warnedUnserializable) {\n warnedUnserializable = true;\n warn('formatter options could not be serialized — falling back to a shared per-locale formatter instance.');\n }\n\n return locale;\n }\n }\n\n return {\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(\n currencyCache,\n cachedKey(locale, opts),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, opts),\n ).format(value);\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n dateCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.DateTimeFormat(locale, options),\n ).format(value);\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 FORMAT_CACHE_MAX,\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 FORMAT_CACHE_MAX,\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n numberCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, options),\n ).format(value);\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":";;;AA8BA,IAAM,IAAmB,KAsDnB,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,GAI1D,IAAuB;CAE3B,SAAS,EAAU,GAAgB,GAA0B;EAC3D,IAAI,CAAC,GA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B;EAEA,OAAO,GAAO,GAAS;GACrB,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,GACzB,SACM,IAAI,KAAK,aAAa,GAAQ,CAAO,CAC7C,CAAC,CAAC,OAAO,CAAK;EAChB;EAEA,SAAS,GAAO,GAAM,GAAS;GAC7B,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,GACzB,SACM,IAAI,KAAK,mBAAmB,GAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,GAAO,CAAI;EACtB;CACF;AACF"}
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=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;
1
+ require("./_dev.cjs");const e=require("./errors.cjs"),t=require("./_locale.cjs"),n=require("./_resources.cjs"),r=require("./translator.cjs");function i(i){let a=n.createCatalogStore(i.catalogs),o=i.fallback,s=(Array.isArray(o)?o:o?[o]:[]).map(t.canonicalLocale),c=new AbortController,l=new Set,u=!1,d=t.canonicalLocale(i.locale??`en`),f=0,p=()=>({locale:d,revision:f,translator:r.createTranslatorFromCompiled(a.catalogMap(),{...i,fallback:o,locale:d})}),m=p(),h=()=>{if(u)throw new e.LinguaDisposedError},g=()=>{u||(u=!0,l.clear(),c.abort())},_=e=>{try{e(m)}catch{}},v=()=>{f++,m=p();for(let e of[...l])_(e)},y=e=>t.localeChain(d,s).includes(e);return{get disposalSignal(){return c.signal},dispose:g,get disposed(){return u},getSnapshot(){return m},isLoaded(e){return!u&&a.isLoaded(e?.locale??d)},async load(e){h();let n=t.canonicalLocale(e?.locale??d),r=await a.load(n);!u&&r&&y(n)&&v()},get locale(){return d},segments(e,t){return m.translator.segmentsDynamic(e,t)},segmentsDynamic(e,t){return m.translator.segmentsDynamic(e,t)},serialize(){return h(),a.state(d)},async setLocale(e){h();let n=t.canonicalLocale(e);n!==d&&(d=n,v())},subscribe(e,t){if(h(),t?.signal?.aborted)return()=>{};let n=()=>{l.delete(e),t?.signal?.removeEventListener(`abort`,n)};return t?.signal?.addEventListener(`abort`,n,{once:!0}),l.add(e),t?.immediate&&_(e),n},[Symbol.dispose]:g,translate(e,t={}){return m.translator.translateDynamic(e,t)},translateDynamic(e,t){return m.translator.translateDynamic(e,t)}}}function a(t,n){if(t.version!==3)throw new e.LinguaInvalidStateError(`Unsupported lingua state version: ${String(t.version)}.`);return i({...n,catalogs:t.catalogs,locale:t.locale})}exports.createTranslationStore=i,exports.hydrateTranslationStore=a;
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 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,GA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 {"version":3,"file":"i18n.cjs","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import type { Catalog, TranslationStoreOptions, TranslationState, Locale, SubscribeOptions } from './types';\n\nimport { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaInvalidStateError } from './errors';\nimport { type Translator, createTranslatorFromCompiled } from './translator';\n\nexport type TranslationSnapshot<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n readonly revision: number;\n readonly translator: Translator<C>;\n};\n\nexport type TranslationStore<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): TranslationSnapshot<C>;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): TranslationState<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (snapshot: TranslationSnapshot<C>) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createTranslationStore<C extends Catalog>(options: TranslationStoreOptions<C>): TranslationStore<C> {\n const catalogs = createCatalogStore(options.catalogs);\n const fallback = options.fallback;\n const fallbackLocales = (Array.isArray(fallback) ? fallback : fallback ? [fallback] : []).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(snapshot: TranslationSnapshot<C>) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let revision = 0;\n\n const buildSnapshot = (): TranslationSnapshot<C> => ({\n locale,\n revision,\n translator: createTranslatorFromCompiled<C>(catalogs.catalogMap(), { ...options, fallback, locale }),\n });\n let snapshot = buildSnapshot();\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const dispatch = (listener: (next: TranslationSnapshot<C>) => void): void => {\n try {\n listener(snapshot);\n } catch (error) {\n logError('subscriber error', error);\n }\n };\n\n const notify = (): void => {\n revision++;\n snapshot = buildSnapshot();\n\n for (const listener of [...subscribers]) dispatch(listener);\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n return {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return snapshot;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await catalogs.load(targetLocale);\n\n if (!disposed && changed && relevant(targetLocale)) notify();\n },\n get locale() {\n return locale;\n },\n segments(key: string, translateOptions) {\n return snapshot.translator.segmentsDynamic(key, translateOptions);\n },\n segmentsDynamic(key, translateOptions) {\n return snapshot.translator.segmentsDynamic(key, translateOptions);\n },\n serialize() {\n assertLive();\n\n return catalogs.state(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n\n if (next === locale) return;\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) dispatch(listener);\n\n return unsubscribe;\n },\n [Symbol.dispose]: dispose,\n translate(key: string, translateOptions = {}) {\n return snapshot.translator.translateDynamic(key, translateOptions);\n },\n translateDynamic(key, translateOptions) {\n return snapshot.translator.translateDynamic(key, translateOptions);\n },\n } as TranslationStore<C>;\n}\n\nexport function hydrateTranslationStore<C extends Catalog>(\n state: TranslationState<C>,\n options?: Omit<TranslationStoreOptions<C>, 'locale' | 'catalogs'>,\n): TranslationStore<C> {\n if (state.version !== 3) {\n throw new LinguaInvalidStateError(`Unsupported lingua state version: ${String(state.version)}.`);\n }\n\n return createTranslationStore({ ...options, catalogs: state.catalogs, locale: state.locale });\n}\n"],"mappings":"6IA2BA,SAAgB,EAA0C,EAA0D,CAClH,IAAM,EAAW,EAAA,mBAAmB,EAAQ,QAAQ,EAC9C,EAAW,EAAQ,SACnB,GAAmB,MAAM,QAAQ,CAAQ,EAAI,EAAW,EAAW,CAAC,CAAQ,EAAI,CAAC,EAAA,CAAG,IAAI,EAAA,eAAe,EACvG,EAAa,IAAI,gBACjB,EAAc,IAAI,IACpB,EAAW,GACX,EAAS,EAAA,gBAAgB,EAAQ,QAAU,IAAI,EAC/C,EAAW,EAET,OAA+C,CACnD,SACA,WACA,WAAY,EAAA,6BAAgC,EAAS,WAAW,EAAG,CAAE,GAAG,EAAS,WAAU,QAAO,CAAC,CACrG,GACI,EAAW,EAAc,EAEvB,MAAyB,CAC7B,GAAI,EAAU,MAAM,IAAI,EAAA,mBAC1B,EAEM,MAAsB,CACtB,IAEJ,EAAW,GACX,EAAY,MAAM,EAClB,EAAW,MAAM,EACnB,EAEM,EAAY,GAA2D,CAC3E,GAAI,CACF,EAAS,CAAQ,CACnB,MAAgB,CAEhB,CACF,EAEM,MAAqB,CACzB,IACA,EAAW,EAAc,EAEzB,IAAK,IAAM,IAAY,CAAC,GAAG,CAAW,EAAG,EAAS,CAAQ,CAC5D,EAEM,EAAY,GAA+B,EAAA,YAAY,EAAQ,CAAe,CAAC,CAAC,SAAS,CAAS,EAExG,MAAO,CACL,IAAI,gBAAiB,CACnB,OAAO,EAAW,MACpB,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,aAAc,CACZ,OAAO,CACT,EACA,SAAS,EAAa,CACpB,MAAO,CAAC,GAAY,EAAS,SAAS,GAAa,QAAU,CAAM,CACrE,EACA,MAAM,KAAK,EAAa,CACtB,EAAW,EAEX,IAAM,EAAe,EAAA,gBAAgB,GAAa,QAAU,CAAM,EAC5D,EAAU,MAAM,EAA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'./i18n-types';
2
- import { type Messages } from './_catalog';
3
- export { LinguaCountInVarsError, LinguaDisposedError, LinguaError, LinguaInvalidCountError, LinguaInvalidLocaleError, LinguaMissingLocaleError, LinguaNamespaceMissingError, LinguaRestoreError, } from './errors';
4
- export type { I18n, I18nOptions, I18nSnapshot, I18nState, Locale, MessageBranchKeys, MessageLeafKeys, ScopedI18n, SubscribeOptions, TpOptions, TranslateVars, Unsubscribe, } from './i18n-types';
5
- export type { Loader, LocaleSource } from './_catalog-store';
6
- export type { Messages } from './_catalog';
7
- export type { NamespaceFactory } from './_namespace-store';
8
- /** Overload: explicit type parameter (strict typing) */
9
- export declare function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;
10
- /** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */
11
- export declare function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;
12
- /**
13
- * Serialises the currently loaded catalogs and active locale into a plain object.
14
- * Pass the result to `hydrateI18n()` on the client.
15
- *
16
- * Prefer calling `i18n.getState()` directly — these standalone functions are provided
17
- * for convenience when you receive a plain `I18n` reference without the full type.
18
- *
19
- * **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet
20
- * preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.
21
- *
22
- * **Warning:** The namespace registry is **not** serialized — factory functions cannot
23
- * be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace
24
- * before relying on namespace-patched keys.
25
- */
26
- export declare function serializeI18n(i18n: I18n): I18nState;
27
- /**
28
- * Hydrates an i18n instance with pre-loaded state (e.g. from a server-rendered payload).
29
- *
30
- * Prefer calling `i18n.restoreState(state)` directly — these standalone functions are
31
- * provided for convenience.
32
- *
33
- * @remarks The namespace registry is **not** included in `I18nState`. After hydrating,
34
- * call `extend()` for each namespace before relying on namespace-patched keys.
35
- *
36
- * @throws `LinguaDisposedError` if called on a disposed instance.
37
- * @throws `LinguaRestoreError` if the state's locale has no catalog.
38
- */
39
- export declare function hydrateI18n(i18n: I18n, state: I18nState): void;
1
+ import type { Catalog, TranslationStoreOptions, TranslationState, Locale, SubscribeOptions } from './types';
2
+ import { type Translator } from './translator';
3
+ export type TranslationSnapshot<C extends Catalog = Catalog> = {
4
+ readonly locale: Locale;
5
+ readonly revision: number;
6
+ readonly translator: Translator<C>;
7
+ };
8
+ export type TranslationStore<C extends Catalog = Catalog> = Translator<C> & {
9
+ [Symbol.dispose](): void;
10
+ readonly disposalSignal: AbortSignal;
11
+ dispose(): void;
12
+ readonly disposed: boolean;
13
+ getSnapshot(): TranslationSnapshot<C>;
14
+ isLoaded(options?: {
15
+ locale?: Locale;
16
+ }): boolean;
17
+ load(options?: {
18
+ locale?: Locale;
19
+ }): Promise<void>;
20
+ serialize(): TranslationState<C>;
21
+ setLocale(locale: Locale): Promise<void>;
22
+ subscribe(listener: (snapshot: TranslationSnapshot<C>) => void, options?: SubscribeOptions): () => void;
23
+ };
24
+ export declare function createTranslationStore<C extends Catalog>(options: TranslationStoreOptions<C>): TranslationStore<C>;
25
+ export declare function hydrateTranslationStore<C extends Catalog>(state: TranslationState<C>, options?: Omit<TranslationStoreOptions<C>, 'locale' | 'catalogs'>): TranslationStore<C>;
40
26
  //# sourceMappingURL=i18n.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,IAAI,EACJ,WAAW,EAEX,SAAS,EASV,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAgB,KAAK,QAAQ,EAAkB,MAAM,YAAY,CAAC;AAezE,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,WAAW,EACX,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAElB,YAAY,EACV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,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