@flare-engine/localization 0.4.17 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -82,8 +82,18 @@ export declare class LocalizationManager {
82
82
  * Minimal CLDR-inspired plural classifier. Supports a handful of locales
83
83
  * natively — fall back to English rules if unknown. This is not a full ICU
84
84
  * implementation; it covers the categories used by our string tables.
85
+ *
86
+ * The sign of the count is ignored, and a non-integer count follows CLDR's
87
+ * visible-fraction rules: a JS number shows fraction digits only when it is
88
+ * not an integer, so CLDR's `v = 0` is `Number.isInteger(n)`.
85
89
  */
86
90
  type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
91
+ /**
92
+ * Plural category of `n` in `locale`. The sign of `n` is ignored, a
93
+ * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity
94
+ * is `other`. A region with its own entry (`pt-PT`) is looked up before its
95
+ * language; an unknown locale uses the English rule.
96
+ */
87
97
  export declare function pluralCategory(locale: LocaleCode, n: number): PluralCategory;
88
98
  /**
89
99
  * Negotiate the best locale match from a prioritized list against a set of
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/format.ts","../src/format-timestamp.ts","../src/manager.ts","../src/plurals.ts","../src/resolve.ts"],"mappings":";;;;;;;;;KASY;KACA;KACA,gBAAgB,eAAe;KAC/B,cAAc;;;;;;;;;;;;;wBCIV,cACd,kBACA,QAAQ,2BACR,QAAQ;UCjBO;;EAEf;;;;;;;;;EASA;;EAEA;;;;;;;;;;;;wBAac,gBACd,YACA,QAAQ,YACR,UAAU;UC1BK;EACf,QAAQ,OAAO,YAAY;EAC3B,eAAe;EACf,gBAAgB;;;;;;;;qBASL;UACH;UACA;mBACS;WACR,UAAQ;EAEL,YAAA,SAAS;MAMjB,UAAU;MAIV,YAAY;EAIhB,oBAAoB;EAIpB,UAAU,QAAQ;;EAOlB,gBAAgB,oBAAoB,eAAe;;EAOnD,SAAS,QAAQ,YAAY,OAAO;EAKpC,IAAI;EASJ,EAAE,aAAa,SAAS;;;;;;;KC7Dd;wBAoDI,eAAe,QAAQ,YAAY,YAAY;;;;;;wBCrD/C,cACd,oBAAoB,cACpB,oBAAoB,cACpB,UAAU,aACT"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/format.ts","../src/format-timestamp.ts","../src/manager.ts","../src/plurals.ts","../src/resolve.ts"],"mappings":";;;;;;;;;KASY;KACA;KACA,gBAAgB,eAAe;KAC/B,cAAc;;;;;;;;;;;;;wBCIV,cACd,kBACA,QAAQ,2BACR,QAAQ;UCjBO;;EAEf;;;;;;;;;EASA;;EAEA;;;;;;;;;;;;wBAac,gBACd,YACA,QAAQ,YACR,UAAU;UC1BK;EACf,QAAQ,OAAO,YAAY;EAC3B,eAAe;EACf,gBAAgB;;;;;;;;qBASL;UACH;UACA;mBACS;WACR,UAAQ;EAEL,YAAA,SAAS;MAMjB,UAAU;MAIV,YAAY;EAIhB,oBAAoB;EAIpB,UAAU,QAAQ;;EAOlB,gBAAgB,oBAAoB,eAAe;;EAOnD,SAAS,QAAQ,YAAY,OAAO;EAKpC,IAAI;EASJ,EAAE,aAAa,SAAS;;;;;;;;;;;KCzDd;;;;;;;wBA6EI,eAAe,QAAQ,YAAY,YAAY;;;;;;wBClF/C,cACd,oBAAoB,cACpB,oBAAoB,cACpB,UAAU,aACT"}
package/dist/index.d.ts CHANGED
@@ -82,8 +82,18 @@ export declare class LocalizationManager {
82
82
  * Minimal CLDR-inspired plural classifier. Supports a handful of locales
83
83
  * natively — fall back to English rules if unknown. This is not a full ICU
84
84
  * implementation; it covers the categories used by our string tables.
85
+ *
86
+ * The sign of the count is ignored, and a non-integer count follows CLDR's
87
+ * visible-fraction rules: a JS number shows fraction digits only when it is
88
+ * not an integer, so CLDR's `v = 0` is `Number.isInteger(n)`.
85
89
  */
86
90
  type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
91
+ /**
92
+ * Plural category of `n` in `locale`. The sign of `n` is ignored, a
93
+ * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity
94
+ * is `other`. A region with its own entry (`pt-PT`) is looked up before its
95
+ * language; an unknown locale uses the English rule.
96
+ */
87
97
  export declare function pluralCategory(locale: LocaleCode, n: number): PluralCategory;
88
98
  /**
89
99
  * Negotiate the best locale match from a prioritized list against a set of
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/format.ts","../src/format-timestamp.ts","../src/manager.ts","../src/plurals.ts","../src/resolve.ts"],"mappings":";;;;;;;;;KASY;KACA;KACA,gBAAgB,eAAe;KAC/B,cAAc;;;;;;;;;;;;;wBCIV,cACd,kBACA,QAAQ,2BACR,QAAQ;UCjBO;;EAEf;;;;;;;;;EASA;;EAEA;;;;;;;;;;;;wBAac,gBACd,YACA,QAAQ,YACR,UAAU;UC1BK;EACf,QAAQ,OAAO,YAAY;EAC3B,eAAe;EACf,gBAAgB;;;;;;;;qBASL;UACH;UACA;mBACS;WACR,UAAQ;EAEL,YAAA,SAAS;MAMjB,UAAU;MAIV,YAAY;EAIhB,oBAAoB;EAIpB,UAAU,QAAQ;;EAOlB,gBAAgB,oBAAoB,eAAe;;EAOnD,SAAS,QAAQ,YAAY,OAAO;EAKpC,IAAI;EASJ,EAAE,aAAa,SAAS;;;;;;;KC7Dd;wBAoDI,eAAe,QAAQ,YAAY,YAAY;;;;;;wBCrD/C,cACd,oBAAoB,cACpB,oBAAoB,cACpB,UAAU,aACT"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/format.ts","../src/format-timestamp.ts","../src/manager.ts","../src/plurals.ts","../src/resolve.ts"],"mappings":";;;;;;;;;KASY;KACA;KACA,gBAAgB,eAAe;KAC/B,cAAc;;;;;;;;;;;;;wBCIV,cACd,kBACA,QAAQ,2BACR,QAAQ;UCjBO;;EAEf;;;;;;;;;EASA;;EAEA;;;;;;;;;;;;wBAac,gBACd,YACA,QAAQ,YACR,UAAU;UC1BK;EACf,QAAQ,OAAO,YAAY;EAC3B,eAAe;EACf,gBAAgB;;;;;;;;qBASL;UACH;UACA;mBACS;WACR,UAAQ;EAEL,YAAA,SAAS;MAMjB,UAAU;MAIV,YAAY;EAIhB,oBAAoB;EAIpB,UAAU,QAAQ;;EAOlB,gBAAgB,oBAAoB,eAAe;;EAOnD,SAAS,QAAQ,YAAY,OAAO;EAKpC,IAAI;EASJ,EAAE,aAAa,SAAS;;;;;;;;;;;KCzDd;;;;;;;wBA6EI,eAAe,QAAQ,YAAY,YAAY;;;;;;wBClF/C,cACd,oBAAoB,cACpB,oBAAoB,cACpB,UAAU,aACT"}
package/dist/index.js CHANGED
@@ -2,7 +2,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _flare_engine_events = require("@flare-engine/events");
3
3
  // src/plurals.ts
4
4
  const ENGLISH = (n) => n === 1 ? "one" : "other";
5
+ const FRENCH = (n) => n < 2 ? "one" : "other";
5
6
  const POLISH = (n) => {
7
+ if (!Number.isInteger(n)) return "other";
6
8
  if (n === 1) return "one";
7
9
  const mod10 = n % 10;
8
10
  const mod100 = n % 100;
@@ -10,6 +12,7 @@ const POLISH = (n) => {
10
12
  return "many";
11
13
  };
12
14
  const RUSSIAN = (n) => {
15
+ if (!Number.isInteger(n)) return "other";
13
16
  const mod10 = n % 10;
14
17
  const mod100 = n % 100;
15
18
  if (mod10 === 1 && mod100 !== 11) return "one";
@@ -18,6 +21,7 @@ const RUSSIAN = (n) => {
18
21
  return "other";
19
22
  };
20
23
  const ARABIC = (n) => {
24
+ if (!Number.isInteger(n)) return "other";
21
25
  if (n === 0) return "zero";
22
26
  if (n === 1) return "one";
23
27
  if (n === 2) return "two";
@@ -31,9 +35,10 @@ const RULES = {
31
35
  en: ENGLISH,
32
36
  de: ENGLISH,
33
37
  es: ENGLISH,
34
- fr: (n) => n === 0 || n === 1 ? "one" : "other",
38
+ fr: FRENCH,
35
39
  it: ENGLISH,
36
- pt: ENGLISH,
40
+ pt: FRENCH,
41
+ "pt-pt": ENGLISH,
37
42
  nl: ENGLISH,
38
43
  pl: POLISH,
39
44
  ru: RUSSIAN,
@@ -43,9 +48,23 @@ const RULES = {
43
48
  ko: JAPANESE,
44
49
  zh: JAPANESE
45
50
  };
51
+ const SUBTAG_SEPARATOR = /[-_]/;
52
+ const UNDERSCORES = /_/g;
53
+ function ruleFor(locale) {
54
+ const tag = locale.toLowerCase();
55
+ const sep = tag.search(SUBTAG_SEPARATOR);
56
+ if (sep < 0) return RULES[tag] ?? ENGLISH;
57
+ return RULES[tag.replace(UNDERSCORES, "-")] ?? RULES[tag.slice(0, sep)] ?? ENGLISH;
58
+ }
59
+ /**
60
+ * Plural category of `n` in `locale`. The sign of `n` is ignored, a
61
+ * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity
62
+ * is `other`. A region with its own entry (`pt-PT`) is looked up before its
63
+ * language; an unknown locale uses the English rule.
64
+ */
46
65
  function pluralCategory(locale, n) {
47
- const lang = locale.toLowerCase().split(/[-_]/)[0] ?? "en";
48
- return (RULES[lang] ?? ENGLISH)(n);
66
+ if (!Number.isFinite(n)) return "other";
67
+ return ruleFor(locale)(Math.abs(n));
49
68
  }
50
69
  // src/format.ts
51
70
  /**
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Signal"],"sources":["../src/plurals.ts","../src/format.ts","../src/format-timestamp.ts","../src/resolve.ts","../src/manager.ts"],"sourcesContent":["import type { LocaleCode } from './types.js';\n\n/**\n * Minimal CLDR-inspired plural classifier. Supports a handful of locales\n * natively — fall back to English rules if unknown. This is not a full ICU\n * implementation; it covers the categories used by our string tables.\n */\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';\n\ntype PluralRule = (n: number) => PluralCategory;\n\nconst ENGLISH: PluralRule = (n) => (n === 1 ? 'one' : 'other');\n\nconst POLISH: PluralRule = (n) => {\n if (n === 1) return 'one';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n return 'many';\n};\n\nconst RUSSIAN: PluralRule = (n) => {\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 === 1 && mod100 !== 11) return 'one';\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n if (mod10 === 0 || (mod10 >= 5 && mod10 <= 9) || (mod100 >= 11 && mod100 <= 14)) return 'many';\n return 'other';\n};\n\nconst ARABIC: PluralRule = (n) => {\n if (n === 0) return 'zero';\n if (n === 1) return 'one';\n if (n === 2) return 'two';\n const mod100 = n % 100;\n if (mod100 >= 3 && mod100 <= 10) return 'few';\n if (mod100 >= 11 && mod100 <= 99) return 'many';\n return 'other';\n};\n\nconst JAPANESE: PluralRule = () => 'other';\n\nconst RULES: Record<string, PluralRule> = {\n en: ENGLISH,\n de: ENGLISH,\n es: ENGLISH,\n fr: (n) => (n === 0 || n === 1 ? 'one' : 'other'),\n it: ENGLISH,\n pt: ENGLISH,\n nl: ENGLISH,\n pl: POLISH,\n ru: RUSSIAN,\n uk: RUSSIAN,\n ar: ARABIC,\n ja: JAPANESE,\n ko: JAPANESE,\n zh: JAPANESE,\n};\n\nexport function pluralCategory(locale: LocaleCode, n: number): PluralCategory {\n const lang = locale.toLowerCase().split(/[-_]/)[0] ?? 'en';\n const rule = RULES[lang] ?? ENGLISH;\n return rule(n);\n}\n","import { pluralCategory } from './plurals.js';\nimport type { LocaleCode, MessageValues } from './types.js';\n\n/**\n * Minimal ICU MessageFormat-ish parser.\n *\n * Grammar:\n * text := (chunk)*\n * chunk := literal | '{' var '}' | '{' var ',' 'plural' ',' branches '}'\n * branches := (selector '{' text '}')+\n * selector := '=' number | identifier // one | few | many | other | zero | two\n * number/ident literals inside a branch may reference '#' → the variable's number value.\n *\n * Nested plural blocks are not supported (not needed for our tables).\n */\n\nexport function formatMessage(\n template: string,\n values: MessageValues | undefined,\n locale: LocaleCode,\n): string {\n const vals = values ?? {};\n let out = '';\n let i = 0;\n const len = template.length;\n while (i < len) {\n const ch = template[i];\n if (ch !== '{') {\n out += ch;\n i++;\n continue;\n }\n // Find the matching closing brace, respecting nested braces.\n const endIdx = findMatchingClose(template, i);\n if (endIdx === -1) {\n // Malformed — emit remainder literally.\n out += template.slice(i);\n break;\n }\n const inner = template.slice(i + 1, endIdx);\n out += renderPlaceholder(inner, vals, locale);\n i = endIdx + 1;\n }\n return out;\n}\n\nfunction findMatchingClose(src: string, startBrace: number): number {\n let depth = 0;\n for (let i = startBrace; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\nfunction renderPlaceholder(inner: string, values: MessageValues, locale: LocaleCode): string {\n // Split only on the top-level commas into at most 3 parts: name, type, body.\n const commaIdx = topLevelComma(inner);\n if (commaIdx === -1) {\n const k = inner.trim();\n return stringifyValue(Object.hasOwn(values, k) ? values[k] : undefined);\n }\n const name = inner.slice(0, commaIdx).trim();\n const rest = inner.slice(commaIdx + 1).trim();\n const secondComma = topLevelComma(rest);\n if (secondComma === -1)\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n const type = rest.slice(0, secondComma).trim();\n const body = rest.slice(secondComma + 1).trim();\n if (type !== 'plural') {\n // Unknown formatter — fall back to raw substitution.\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n }\n const raw = Object.hasOwn(values, name) ? values[name] : undefined;\n const n = typeof raw === 'number' ? raw : Number(raw);\n const category = Number.isFinite(n) ? pluralCategory(locale, n) : 'other';\n const branches = parsePluralBranches(body);\n const branchText =\n branches[`=${Number.isFinite(n) ? n : ''}`] ?? branches[category] ?? branches.other ?? '';\n // '#' inside the branch refers to the numeric value.\n const replaced = branchText.replace(/#/g, Number.isFinite(n) ? String(n) : '');\n // Recurse so nested `{var}` inside the branch is resolved.\n return formatMessage(replaced, values, locale);\n}\n\nfunction topLevelComma(src: string): number {\n let depth = 0;\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') depth--;\n else if (c === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nfunction parsePluralBranches(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n let i = 0;\n while (i < body.length) {\n // Skip whitespace.\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (i >= body.length) break;\n // Read selector until whitespace or '{'.\n const selStart = i;\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '{') break;\n i++;\n }\n const selector = body.slice(selStart, i);\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (body[i] !== '{') break;\n const end = findMatchingClose(body, i);\n if (end === -1) break;\n out[selector] = body.slice(i + 1, end);\n i = end + 1;\n }\n return out;\n}\n\nfunction stringifyValue(v: unknown): string {\n if (v === undefined || v === null) return '';\n return String(v);\n}\n","import type { LocaleCode } from './types.js';\n\nexport interface FormatTimestampOptions {\n /** Intl.DateTimeFormat date style. Defaults to 'short'. */\n dateStyle?: 'full' | 'long' | 'medium' | 'short';\n /**\n * Intl.DateTimeFormat time style.\n *\n * Applied when explicitly provided here, or when the entire `options`\n * argument is omitted (defaults to 'short' in that case).\n * Passing an `options` object that does NOT include `timeStyle` yields a\n * date-only result — time is suppressed.\n */\n timeStyle?: 'full' | 'long' | 'medium' | 'short';\n /** Returned for ts <= 0 or on any Intl failure. Defaults to ''. */\n fallback?: string;\n}\n\n/**\n * Format a Unix timestamp (milliseconds) as a human-readable date/time string\n * using Intl.DateTimeFormat with the given locale.\n *\n * Returns `options.fallback` (default '') for ts <= 0 or on any Intl error\n * (e.g. unsupported locale on a constrained runtime). The locale is used\n * directly as the Intl BCP-47 tag.\n *\n * Safe on all target runtimes: Bun (V8), React Native Hermes (>= 0.70), web.\n */\nexport function formatTimestamp(\n ts: number,\n locale: LocaleCode,\n options?: FormatTimestampOptions,\n): string {\n const fallback = options?.fallback ?? '';\n if (ts <= 0) return fallback;\n try {\n const intlOpts: Intl.DateTimeFormatOptions = {\n dateStyle: options?.dateStyle ?? 'short',\n };\n if (options?.timeStyle !== undefined) {\n intlOpts.timeStyle = options.timeStyle;\n } else if (options === undefined) {\n intlOpts.timeStyle = 'short';\n }\n return new Intl.DateTimeFormat(locale, intlOpts).format(new Date(ts));\n } catch {\n return fallback;\n }\n}\n","import type { LocaleCode } from './types.js';\n\n/**\n * Negotiate the best locale match from a prioritized list against a set of\n * available locales. Matching is case-insensitive and considers language +\n * region. Returns the fallback when nothing matches.\n */\nexport function resolveLocale(\n requested: readonly LocaleCode[],\n available: readonly LocaleCode[],\n fallback: LocaleCode,\n): LocaleCode {\n if (available.length === 0) return fallback;\n const norm = (s: string): string => s.toLowerCase().replace(/_/g, '-');\n const avail = available.map(norm);\n\n for (const rawReq of requested) {\n const req = norm(rawReq);\n // Exact match.\n const exactIdx = avail.indexOf(req);\n if (exactIdx !== -1) return available[exactIdx] as LocaleCode;\n // Language-only match against any region variant.\n const lang = req.split('-')[0] ?? req;\n const langIdx = avail.findIndex((a) => (a.split('-')[0] ?? a) === lang);\n if (langIdx !== -1) return available[langIdx] as LocaleCode;\n }\n // Fallback — ensure it is actually present; otherwise first available.\n const fbIdx = avail.indexOf(norm(fallback));\n if (fbIdx !== -1) return available[fbIdx] as LocaleCode;\n return available[0] as LocaleCode;\n}\n","import { Signal } from '@flare-engine/events';\nimport { formatMessage } from './format.js';\nimport { resolveLocale } from './resolve.js';\nimport type { LocaleCode, MessageValues, StringTable } from './types.js';\n\nexport interface LocalizationManagerOptions {\n tables: Record<LocaleCode, StringTable>;\n initialLocale: LocaleCode;\n fallbackLocale: LocaleCode;\n}\n\n/**\n * Owns the active locale + string tables. `t(key, values?)` renders a message\n * using the active locale, falling back to the fallback locale, then the raw\n * key. `onChange` fires whenever the active locale is swapped. `setTable`\n * replaces a locale's table in place — enables hot-reload in dev.\n */\nexport class LocalizationManager {\n private _tables: Record<LocaleCode, StringTable>;\n private _locale: LocaleCode;\n private readonly _fallback: LocaleCode;\n readonly onChange = new Signal<LocaleCode>();\n\n constructor(options: LocalizationManagerOptions) {\n this._tables = { ...options.tables };\n this._fallback = options.fallbackLocale;\n this._locale = options.initialLocale;\n }\n\n get locale(): LocaleCode {\n return this._locale;\n }\n\n get fallback(): LocaleCode {\n return this._fallback;\n }\n\n availableLocales(): LocaleCode[] {\n return Object.keys(this._tables);\n }\n\n setLocale(locale: LocaleCode): void {\n if (this._locale === locale) return;\n this._locale = locale;\n this.onChange.emit(locale);\n }\n\n /** Pick the best-matching locale from the given requests and make it active. */\n negotiateLocale(requested: readonly LocaleCode[]): LocaleCode {\n const chosen = resolveLocale(requested, this.availableLocales(), this._fallback);\n this.setLocale(chosen);\n return chosen;\n }\n\n /** Replace (or install) a locale's table. Emits `onChange` if it targets the active locale. */\n setTable(locale: LocaleCode, table: StringTable): void {\n this._tables[locale] = table;\n if (locale === this._locale) this.onChange.emit(locale);\n }\n\n has(key: string): boolean {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n return (\n (active !== undefined && Object.hasOwn(active, key)) ||\n (fallback !== undefined && Object.hasOwn(fallback, key))\n );\n }\n\n t(key: string, values?: MessageValues): string {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n const template =\n (active !== undefined && Object.hasOwn(active, key) ? active[key] : undefined) ??\n (fallback !== undefined && Object.hasOwn(fallback, key) ? fallback[key] : undefined) ??\n key;\n return formatMessage(template, values, this._locale);\n }\n}\n"],"mappings":";;;AAYA,MAAM,WAAuB,MAAO,MAAM,IAAI,QAAQ;AAEtD,MAAM,UAAsB,MAAM;CAChC,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,Q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"}
1
+ {"version":3,"file":"index.js","names":["Signal"],"sources":["../src/plurals.ts","../src/format.ts","../src/format-timestamp.ts","../src/resolve.ts","../src/manager.ts"],"sourcesContent":["import type { LocaleCode } from './types.js';\n\n/**\n * Minimal CLDR-inspired plural classifier. Supports a handful of locales\n * natively — fall back to English rules if unknown. This is not a full ICU\n * implementation; it covers the categories used by our string tables.\n *\n * The sign of the count is ignored, and a non-integer count follows CLDR's\n * visible-fraction rules: a JS number shows fraction digits only when it is\n * not an integer, so CLDR's `v = 0` is `Number.isInteger(n)`.\n */\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';\n\n/** Receives a finite, non-negative count. */\ntype PluralRule = (n: number) => PluralCategory;\n\nconst ENGLISH: PluralRule = (n) => (n === 1 ? 'one' : 'other');\n\n// CLDR `i = 0,1`: the integer part decides, so 0.5 and 1.5 are `one`.\nconst FRENCH: PluralRule = (n) => (n < 2 ? 'one' : 'other');\n\nconst POLISH: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n if (n === 1) return 'one';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n return 'many';\n};\n\nconst RUSSIAN: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 === 1 && mod100 !== 11) return 'one';\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n if (mod10 === 0 || (mod10 >= 5 && mod10 <= 9) || (mod100 >= 11 && mod100 <= 14)) return 'many';\n return 'other';\n};\n\nconst ARABIC: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n if (n === 0) return 'zero';\n if (n === 1) return 'one';\n if (n === 2) return 'two';\n const mod100 = n % 100;\n if (mod100 >= 3 && mod100 <= 10) return 'few';\n if (mod100 >= 11 && mod100 <= 99) return 'many';\n return 'other';\n};\n\nconst JAPANESE: PluralRule = () => 'other';\n\n// Keyed by lower-case tag with `-` separators. A full tag wins over its language.\nconst RULES: Record<string, PluralRule> = {\n en: ENGLISH,\n de: ENGLISH,\n es: ENGLISH,\n fr: FRENCH,\n it: ENGLISH,\n pt: FRENCH,\n 'pt-pt': ENGLISH,\n nl: ENGLISH,\n pl: POLISH,\n ru: RUSSIAN,\n uk: RUSSIAN,\n ar: ARABIC,\n ja: JAPANESE,\n ko: JAPANESE,\n zh: JAPANESE,\n};\n\nconst SUBTAG_SEPARATOR = /[-_]/;\nconst UNDERSCORES = /_/g;\n\nfunction ruleFor(locale: LocaleCode): PluralRule {\n const tag = locale.toLowerCase();\n const sep = tag.search(SUBTAG_SEPARATOR);\n if (sep < 0) return RULES[tag] ?? ENGLISH;\n return RULES[tag.replace(UNDERSCORES, '-')] ?? RULES[tag.slice(0, sep)] ?? ENGLISH;\n}\n\n/**\n * Plural category of `n` in `locale`. The sign of `n` is ignored, a\n * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity\n * is `other`. A region with its own entry (`pt-PT`) is looked up before its\n * language; an unknown locale uses the English rule.\n */\nexport function pluralCategory(locale: LocaleCode, n: number): PluralCategory {\n if (!Number.isFinite(n)) return 'other';\n return ruleFor(locale)(Math.abs(n));\n}\n","import { pluralCategory } from './plurals.js';\nimport type { LocaleCode, MessageValues } from './types.js';\n\n/**\n * Minimal ICU MessageFormat-ish parser.\n *\n * Grammar:\n * text := (chunk)*\n * chunk := literal | '{' var '}' | '{' var ',' 'plural' ',' branches '}'\n * branches := (selector '{' text '}')+\n * selector := '=' number | identifier // one | few | many | other | zero | two\n * number/ident literals inside a branch may reference '#' → the variable's number value.\n *\n * Nested plural blocks are not supported (not needed for our tables).\n */\n\nexport function formatMessage(\n template: string,\n values: MessageValues | undefined,\n locale: LocaleCode,\n): string {\n const vals = values ?? {};\n let out = '';\n let i = 0;\n const len = template.length;\n while (i < len) {\n const ch = template[i];\n if (ch !== '{') {\n out += ch;\n i++;\n continue;\n }\n // Find the matching closing brace, respecting nested braces.\n const endIdx = findMatchingClose(template, i);\n if (endIdx === -1) {\n // Malformed — emit remainder literally.\n out += template.slice(i);\n break;\n }\n const inner = template.slice(i + 1, endIdx);\n out += renderPlaceholder(inner, vals, locale);\n i = endIdx + 1;\n }\n return out;\n}\n\nfunction findMatchingClose(src: string, startBrace: number): number {\n let depth = 0;\n for (let i = startBrace; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\nfunction renderPlaceholder(inner: string, values: MessageValues, locale: LocaleCode): string {\n // Split only on the top-level commas into at most 3 parts: name, type, body.\n const commaIdx = topLevelComma(inner);\n if (commaIdx === -1) {\n const k = inner.trim();\n return stringifyValue(Object.hasOwn(values, k) ? values[k] : undefined);\n }\n const name = inner.slice(0, commaIdx).trim();\n const rest = inner.slice(commaIdx + 1).trim();\n const secondComma = topLevelComma(rest);\n if (secondComma === -1)\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n const type = rest.slice(0, secondComma).trim();\n const body = rest.slice(secondComma + 1).trim();\n if (type !== 'plural') {\n // Unknown formatter — fall back to raw substitution.\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n }\n const raw = Object.hasOwn(values, name) ? values[name] : undefined;\n const n = typeof raw === 'number' ? raw : Number(raw);\n const category = Number.isFinite(n) ? pluralCategory(locale, n) : 'other';\n const branches = parsePluralBranches(body);\n const branchText =\n branches[`=${Number.isFinite(n) ? n : ''}`] ?? branches[category] ?? branches.other ?? '';\n // '#' inside the branch refers to the numeric value.\n const replaced = branchText.replace(/#/g, Number.isFinite(n) ? String(n) : '');\n // Recurse so nested `{var}` inside the branch is resolved.\n return formatMessage(replaced, values, locale);\n}\n\nfunction topLevelComma(src: string): number {\n let depth = 0;\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') depth--;\n else if (c === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nfunction parsePluralBranches(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n let i = 0;\n while (i < body.length) {\n // Skip whitespace.\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (i >= body.length) break;\n // Read selector until whitespace or '{'.\n const selStart = i;\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '{') break;\n i++;\n }\n const selector = body.slice(selStart, i);\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (body[i] !== '{') break;\n const end = findMatchingClose(body, i);\n if (end === -1) break;\n out[selector] = body.slice(i + 1, end);\n i = end + 1;\n }\n return out;\n}\n\nfunction stringifyValue(v: unknown): string {\n if (v === undefined || v === null) return '';\n return String(v);\n}\n","import type { LocaleCode } from './types.js';\n\nexport interface FormatTimestampOptions {\n /** Intl.DateTimeFormat date style. Defaults to 'short'. */\n dateStyle?: 'full' | 'long' | 'medium' | 'short';\n /**\n * Intl.DateTimeFormat time style.\n *\n * Applied when explicitly provided here, or when the entire `options`\n * argument is omitted (defaults to 'short' in that case).\n * Passing an `options` object that does NOT include `timeStyle` yields a\n * date-only result — time is suppressed.\n */\n timeStyle?: 'full' | 'long' | 'medium' | 'short';\n /** Returned for ts <= 0 or on any Intl failure. Defaults to ''. */\n fallback?: string;\n}\n\n/**\n * Format a Unix timestamp (milliseconds) as a human-readable date/time string\n * using Intl.DateTimeFormat with the given locale.\n *\n * Returns `options.fallback` (default '') for ts <= 0 or on any Intl error\n * (e.g. unsupported locale on a constrained runtime). The locale is used\n * directly as the Intl BCP-47 tag.\n *\n * Safe on all target runtimes: Bun (V8), React Native Hermes (>= 0.70), web.\n */\nexport function formatTimestamp(\n ts: number,\n locale: LocaleCode,\n options?: FormatTimestampOptions,\n): string {\n const fallback = options?.fallback ?? '';\n if (ts <= 0) return fallback;\n try {\n const intlOpts: Intl.DateTimeFormatOptions = {\n dateStyle: options?.dateStyle ?? 'short',\n };\n if (options?.timeStyle !== undefined) {\n intlOpts.timeStyle = options.timeStyle;\n } else if (options === undefined) {\n intlOpts.timeStyle = 'short';\n }\n return new Intl.DateTimeFormat(locale, intlOpts).format(new Date(ts));\n } catch {\n return fallback;\n }\n}\n","import type { LocaleCode } from './types.js';\n\n/**\n * Negotiate the best locale match from a prioritized list against a set of\n * available locales. Matching is case-insensitive and considers language +\n * region. Returns the fallback when nothing matches.\n */\nexport function resolveLocale(\n requested: readonly LocaleCode[],\n available: readonly LocaleCode[],\n fallback: LocaleCode,\n): LocaleCode {\n if (available.length === 0) return fallback;\n const norm = (s: string): string => s.toLowerCase().replace(/_/g, '-');\n const avail = available.map(norm);\n\n for (const rawReq of requested) {\n const req = norm(rawReq);\n // Exact match.\n const exactIdx = avail.indexOf(req);\n if (exactIdx !== -1) return available[exactIdx] as LocaleCode;\n // Language-only match against any region variant.\n const lang = req.split('-')[0] ?? req;\n const langIdx = avail.findIndex((a) => (a.split('-')[0] ?? a) === lang);\n if (langIdx !== -1) return available[langIdx] as LocaleCode;\n }\n // Fallback — ensure it is actually present; otherwise first available.\n const fbIdx = avail.indexOf(norm(fallback));\n if (fbIdx !== -1) return available[fbIdx] as LocaleCode;\n return available[0] as LocaleCode;\n}\n","import { Signal } from '@flare-engine/events';\nimport { formatMessage } from './format.js';\nimport { resolveLocale } from './resolve.js';\nimport type { LocaleCode, MessageValues, StringTable } from './types.js';\n\nexport interface LocalizationManagerOptions {\n tables: Record<LocaleCode, StringTable>;\n initialLocale: LocaleCode;\n fallbackLocale: LocaleCode;\n}\n\n/**\n * Owns the active locale + string tables. `t(key, values?)` renders a message\n * using the active locale, falling back to the fallback locale, then the raw\n * key. `onChange` fires whenever the active locale is swapped. `setTable`\n * replaces a locale's table in place — enables hot-reload in dev.\n */\nexport class LocalizationManager {\n private _tables: Record<LocaleCode, StringTable>;\n private _locale: LocaleCode;\n private readonly _fallback: LocaleCode;\n readonly onChange = new Signal<LocaleCode>();\n\n constructor(options: LocalizationManagerOptions) {\n this._tables = { ...options.tables };\n this._fallback = options.fallbackLocale;\n this._locale = options.initialLocale;\n }\n\n get locale(): LocaleCode {\n return this._locale;\n }\n\n get fallback(): LocaleCode {\n return this._fallback;\n }\n\n availableLocales(): LocaleCode[] {\n return Object.keys(this._tables);\n }\n\n setLocale(locale: LocaleCode): void {\n if (this._locale === locale) return;\n this._locale = locale;\n this.onChange.emit(locale);\n }\n\n /** Pick the best-matching locale from the given requests and make it active. */\n negotiateLocale(requested: readonly LocaleCode[]): LocaleCode {\n const chosen = resolveLocale(requested, this.availableLocales(), this._fallback);\n this.setLocale(chosen);\n return chosen;\n }\n\n /** Replace (or install) a locale's table. Emits `onChange` if it targets the active locale. */\n setTable(locale: LocaleCode, table: StringTable): void {\n this._tables[locale] = table;\n if (locale === this._locale) this.onChange.emit(locale);\n }\n\n has(key: string): boolean {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n return (\n (active !== undefined && Object.hasOwn(active, key)) ||\n (fallback !== undefined && Object.hasOwn(fallback, key))\n );\n }\n\n t(key: string, values?: MessageValues): string {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n const template =\n (active !== undefined && Object.hasOwn(active, key) ? active[key] : undefined) ??\n (fallback !== undefined && Object.hasOwn(fallback, key) ? fallback[key] : undefined) ??\n key;\n return formatMessage(template, values, this._locale);\n }\n}\n"],"mappings":";;;AAiBA,MAAM,WAAuB,MAAO,MAAM,IAAI,QAAQ;AAGtD,MAAM,UAAsB,MAAO,IAAI,IAAI,QAAQ;AAEnD,MAAM,UAAsB,MAAM;CAChC,IAAI,CAAC,OAAO,UAAU,CAAC,GAAG,OAAO;CACjC,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CACnB,IAAI,SAAS,KAAK,SAAS,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C;EAC7C,MAAM,SAAS,KAAK,QAAQ,KAAK;EACjC,MAAM,WAAW,KAAK,QAAQ,KAAK;EAKnC,OAAO,eAHJ,WAAW,KAAA,KAAa,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA,OACnE,aAAa,KAAA,KAAa,OAAO,OAAO,UAAU,GAAG,IAAI,SAAS,OAAO,KAAA,MAC1E,KAC6B,QAAQ,KAAK,OAAO;CACrD;AACF"}
package/dist/index.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  import { Signal } from "@flare-engine/events";
2
2
  // src/plurals.ts
3
3
  const ENGLISH = (n) => n === 1 ? "one" : "other";
4
+ const FRENCH = (n) => n < 2 ? "one" : "other";
4
5
  const POLISH = (n) => {
6
+ if (!Number.isInteger(n)) return "other";
5
7
  if (n === 1) return "one";
6
8
  const mod10 = n % 10;
7
9
  const mod100 = n % 100;
@@ -9,6 +11,7 @@ const POLISH = (n) => {
9
11
  return "many";
10
12
  };
11
13
  const RUSSIAN = (n) => {
14
+ if (!Number.isInteger(n)) return "other";
12
15
  const mod10 = n % 10;
13
16
  const mod100 = n % 100;
14
17
  if (mod10 === 1 && mod100 !== 11) return "one";
@@ -17,6 +20,7 @@ const RUSSIAN = (n) => {
17
20
  return "other";
18
21
  };
19
22
  const ARABIC = (n) => {
23
+ if (!Number.isInteger(n)) return "other";
20
24
  if (n === 0) return "zero";
21
25
  if (n === 1) return "one";
22
26
  if (n === 2) return "two";
@@ -30,9 +34,10 @@ const RULES = {
30
34
  en: ENGLISH,
31
35
  de: ENGLISH,
32
36
  es: ENGLISH,
33
- fr: (n) => n === 0 || n === 1 ? "one" : "other",
37
+ fr: FRENCH,
34
38
  it: ENGLISH,
35
- pt: ENGLISH,
39
+ pt: FRENCH,
40
+ "pt-pt": ENGLISH,
36
41
  nl: ENGLISH,
37
42
  pl: POLISH,
38
43
  ru: RUSSIAN,
@@ -42,9 +47,23 @@ const RULES = {
42
47
  ko: JAPANESE,
43
48
  zh: JAPANESE
44
49
  };
50
+ const SUBTAG_SEPARATOR = /[-_]/;
51
+ const UNDERSCORES = /_/g;
52
+ function ruleFor(locale) {
53
+ const tag = locale.toLowerCase();
54
+ const sep = tag.search(SUBTAG_SEPARATOR);
55
+ if (sep < 0) return RULES[tag] ?? ENGLISH;
56
+ return RULES[tag.replace(UNDERSCORES, "-")] ?? RULES[tag.slice(0, sep)] ?? ENGLISH;
57
+ }
58
+ /**
59
+ * Plural category of `n` in `locale`. The sign of `n` is ignored, a
60
+ * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity
61
+ * is `other`. A region with its own entry (`pt-PT`) is looked up before its
62
+ * language; an unknown locale uses the English rule.
63
+ */
45
64
  function pluralCategory(locale, n) {
46
- const lang = locale.toLowerCase().split(/[-_]/)[0] ?? "en";
47
- return (RULES[lang] ?? ENGLISH)(n);
65
+ if (!Number.isFinite(n)) return "other";
66
+ return ruleFor(locale)(Math.abs(n));
48
67
  }
49
68
  // src/format.ts
50
69
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/plurals.ts","../src/format.ts","../src/format-timestamp.ts","../src/resolve.ts","../src/manager.ts"],"sourcesContent":["import type { LocaleCode } from './types.js';\n\n/**\n * Minimal CLDR-inspired plural classifier. Supports a handful of locales\n * natively — fall back to English rules if unknown. This is not a full ICU\n * implementation; it covers the categories used by our string tables.\n */\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';\n\ntype PluralRule = (n: number) => PluralCategory;\n\nconst ENGLISH: PluralRule = (n) => (n === 1 ? 'one' : 'other');\n\nconst POLISH: PluralRule = (n) => {\n if (n === 1) return 'one';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n return 'many';\n};\n\nconst RUSSIAN: PluralRule = (n) => {\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 === 1 && mod100 !== 11) return 'one';\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n if (mod10 === 0 || (mod10 >= 5 && mod10 <= 9) || (mod100 >= 11 && mod100 <= 14)) return 'many';\n return 'other';\n};\n\nconst ARABIC: PluralRule = (n) => {\n if (n === 0) return 'zero';\n if (n === 1) return 'one';\n if (n === 2) return 'two';\n const mod100 = n % 100;\n if (mod100 >= 3 && mod100 <= 10) return 'few';\n if (mod100 >= 11 && mod100 <= 99) return 'many';\n return 'other';\n};\n\nconst JAPANESE: PluralRule = () => 'other';\n\nconst RULES: Record<string, PluralRule> = {\n en: ENGLISH,\n de: ENGLISH,\n es: ENGLISH,\n fr: (n) => (n === 0 || n === 1 ? 'one' : 'other'),\n it: ENGLISH,\n pt: ENGLISH,\n nl: ENGLISH,\n pl: POLISH,\n ru: RUSSIAN,\n uk: RUSSIAN,\n ar: ARABIC,\n ja: JAPANESE,\n ko: JAPANESE,\n zh: JAPANESE,\n};\n\nexport function pluralCategory(locale: LocaleCode, n: number): PluralCategory {\n const lang = locale.toLowerCase().split(/[-_]/)[0] ?? 'en';\n const rule = RULES[lang] ?? ENGLISH;\n return rule(n);\n}\n","import { pluralCategory } from './plurals.js';\nimport type { LocaleCode, MessageValues } from './types.js';\n\n/**\n * Minimal ICU MessageFormat-ish parser.\n *\n * Grammar:\n * text := (chunk)*\n * chunk := literal | '{' var '}' | '{' var ',' 'plural' ',' branches '}'\n * branches := (selector '{' text '}')+\n * selector := '=' number | identifier // one | few | many | other | zero | two\n * number/ident literals inside a branch may reference '#' → the variable's number value.\n *\n * Nested plural blocks are not supported (not needed for our tables).\n */\n\nexport function formatMessage(\n template: string,\n values: MessageValues | undefined,\n locale: LocaleCode,\n): string {\n const vals = values ?? {};\n let out = '';\n let i = 0;\n const len = template.length;\n while (i < len) {\n const ch = template[i];\n if (ch !== '{') {\n out += ch;\n i++;\n continue;\n }\n // Find the matching closing brace, respecting nested braces.\n const endIdx = findMatchingClose(template, i);\n if (endIdx === -1) {\n // Malformed — emit remainder literally.\n out += template.slice(i);\n break;\n }\n const inner = template.slice(i + 1, endIdx);\n out += renderPlaceholder(inner, vals, locale);\n i = endIdx + 1;\n }\n return out;\n}\n\nfunction findMatchingClose(src: string, startBrace: number): number {\n let depth = 0;\n for (let i = startBrace; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\nfunction renderPlaceholder(inner: string, values: MessageValues, locale: LocaleCode): string {\n // Split only on the top-level commas into at most 3 parts: name, type, body.\n const commaIdx = topLevelComma(inner);\n if (commaIdx === -1) {\n const k = inner.trim();\n return stringifyValue(Object.hasOwn(values, k) ? values[k] : undefined);\n }\n const name = inner.slice(0, commaIdx).trim();\n const rest = inner.slice(commaIdx + 1).trim();\n const secondComma = topLevelComma(rest);\n if (secondComma === -1)\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n const type = rest.slice(0, secondComma).trim();\n const body = rest.slice(secondComma + 1).trim();\n if (type !== 'plural') {\n // Unknown formatter — fall back to raw substitution.\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n }\n const raw = Object.hasOwn(values, name) ? values[name] : undefined;\n const n = typeof raw === 'number' ? raw : Number(raw);\n const category = Number.isFinite(n) ? pluralCategory(locale, n) : 'other';\n const branches = parsePluralBranches(body);\n const branchText =\n branches[`=${Number.isFinite(n) ? n : ''}`] ?? branches[category] ?? branches.other ?? '';\n // '#' inside the branch refers to the numeric value.\n const replaced = branchText.replace(/#/g, Number.isFinite(n) ? String(n) : '');\n // Recurse so nested `{var}` inside the branch is resolved.\n return formatMessage(replaced, values, locale);\n}\n\nfunction topLevelComma(src: string): number {\n let depth = 0;\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') depth--;\n else if (c === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nfunction parsePluralBranches(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n let i = 0;\n while (i < body.length) {\n // Skip whitespace.\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (i >= body.length) break;\n // Read selector until whitespace or '{'.\n const selStart = i;\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '{') break;\n i++;\n }\n const selector = body.slice(selStart, i);\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (body[i] !== '{') break;\n const end = findMatchingClose(body, i);\n if (end === -1) break;\n out[selector] = body.slice(i + 1, end);\n i = end + 1;\n }\n return out;\n}\n\nfunction stringifyValue(v: unknown): string {\n if (v === undefined || v === null) return '';\n return String(v);\n}\n","import type { LocaleCode } from './types.js';\n\nexport interface FormatTimestampOptions {\n /** Intl.DateTimeFormat date style. Defaults to 'short'. */\n dateStyle?: 'full' | 'long' | 'medium' | 'short';\n /**\n * Intl.DateTimeFormat time style.\n *\n * Applied when explicitly provided here, or when the entire `options`\n * argument is omitted (defaults to 'short' in that case).\n * Passing an `options` object that does NOT include `timeStyle` yields a\n * date-only result — time is suppressed.\n */\n timeStyle?: 'full' | 'long' | 'medium' | 'short';\n /** Returned for ts <= 0 or on any Intl failure. Defaults to ''. */\n fallback?: string;\n}\n\n/**\n * Format a Unix timestamp (milliseconds) as a human-readable date/time string\n * using Intl.DateTimeFormat with the given locale.\n *\n * Returns `options.fallback` (default '') for ts <= 0 or on any Intl error\n * (e.g. unsupported locale on a constrained runtime). The locale is used\n * directly as the Intl BCP-47 tag.\n *\n * Safe on all target runtimes: Bun (V8), React Native Hermes (>= 0.70), web.\n */\nexport function formatTimestamp(\n ts: number,\n locale: LocaleCode,\n options?: FormatTimestampOptions,\n): string {\n const fallback = options?.fallback ?? '';\n if (ts <= 0) return fallback;\n try {\n const intlOpts: Intl.DateTimeFormatOptions = {\n dateStyle: options?.dateStyle ?? 'short',\n };\n if (options?.timeStyle !== undefined) {\n intlOpts.timeStyle = options.timeStyle;\n } else if (options === undefined) {\n intlOpts.timeStyle = 'short';\n }\n return new Intl.DateTimeFormat(locale, intlOpts).format(new Date(ts));\n } catch {\n return fallback;\n }\n}\n","import type { LocaleCode } from './types.js';\n\n/**\n * Negotiate the best locale match from a prioritized list against a set of\n * available locales. Matching is case-insensitive and considers language +\n * region. Returns the fallback when nothing matches.\n */\nexport function resolveLocale(\n requested: readonly LocaleCode[],\n available: readonly LocaleCode[],\n fallback: LocaleCode,\n): LocaleCode {\n if (available.length === 0) return fallback;\n const norm = (s: string): string => s.toLowerCase().replace(/_/g, '-');\n const avail = available.map(norm);\n\n for (const rawReq of requested) {\n const req = norm(rawReq);\n // Exact match.\n const exactIdx = avail.indexOf(req);\n if (exactIdx !== -1) return available[exactIdx] as LocaleCode;\n // Language-only match against any region variant.\n const lang = req.split('-')[0] ?? req;\n const langIdx = avail.findIndex((a) => (a.split('-')[0] ?? a) === lang);\n if (langIdx !== -1) return available[langIdx] as LocaleCode;\n }\n // Fallback — ensure it is actually present; otherwise first available.\n const fbIdx = avail.indexOf(norm(fallback));\n if (fbIdx !== -1) return available[fbIdx] as LocaleCode;\n return available[0] as LocaleCode;\n}\n","import { Signal } from '@flare-engine/events';\nimport { formatMessage } from './format.js';\nimport { resolveLocale } from './resolve.js';\nimport type { LocaleCode, MessageValues, StringTable } from './types.js';\n\nexport interface LocalizationManagerOptions {\n tables: Record<LocaleCode, StringTable>;\n initialLocale: LocaleCode;\n fallbackLocale: LocaleCode;\n}\n\n/**\n * Owns the active locale + string tables. `t(key, values?)` renders a message\n * using the active locale, falling back to the fallback locale, then the raw\n * key. `onChange` fires whenever the active locale is swapped. `setTable`\n * replaces a locale's table in place — enables hot-reload in dev.\n */\nexport class LocalizationManager {\n private _tables: Record<LocaleCode, StringTable>;\n private _locale: LocaleCode;\n private readonly _fallback: LocaleCode;\n readonly onChange = new Signal<LocaleCode>();\n\n constructor(options: LocalizationManagerOptions) {\n this._tables = { ...options.tables };\n this._fallback = options.fallbackLocale;\n this._locale = options.initialLocale;\n }\n\n get locale(): LocaleCode {\n return this._locale;\n }\n\n get fallback(): LocaleCode {\n return this._fallback;\n }\n\n availableLocales(): LocaleCode[] {\n return Object.keys(this._tables);\n }\n\n setLocale(locale: LocaleCode): void {\n if (this._locale === locale) return;\n this._locale = locale;\n this.onChange.emit(locale);\n }\n\n /** Pick the best-matching locale from the given requests and make it active. */\n negotiateLocale(requested: readonly LocaleCode[]): LocaleCode {\n const chosen = resolveLocale(requested, this.availableLocales(), this._fallback);\n this.setLocale(chosen);\n return chosen;\n }\n\n /** Replace (or install) a locale's table. Emits `onChange` if it targets the active locale. */\n setTable(locale: LocaleCode, table: StringTable): void {\n this._tables[locale] = table;\n if (locale === this._locale) this.onChange.emit(locale);\n }\n\n has(key: string): boolean {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n return (\n (active !== undefined && Object.hasOwn(active, key)) ||\n (fallback !== undefined && Object.hasOwn(fallback, key))\n );\n }\n\n t(key: string, values?: MessageValues): string {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n const template =\n (active !== undefined && Object.hasOwn(active, key) ? active[key] : undefined) ??\n (fallback !== undefined && Object.hasOwn(fallback, key) ? fallback[key] : undefined) ??\n key;\n return formatMessage(template, values, this._locale);\n }\n}\n"],"mappings":";;AAYA,MAAM,WAAuB,MAAO,MAAM,IAAI,QAAQ;AAEtD,MAAM,UAAsB,MAAM;CAChC,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CACnB,IAAI,SAAS,KAAK,SAAS,MAAM,SAAS,MAAM,SAAS,KAAK,OAAO;CACrE,OAAO;AACT;AAEA,MAAM,WAAuB,MAAM;CACjC,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CACnB,IAAI,UAAU,KAAK,WAAW,IAAI,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,IAAI,SAAqB;EACvB,OAAO,KAAK;CACd;CAEA,IAAI,WAAuB;EACzB,OAAO,KAAK;CACd;CAEA,mBAAiC;EAC/B,OAAO,OAAO,KAAK,KAAK,OAAO;CACjC;CAEA,UAAU,QAA0B;EAClC,IAAI,KAAK,YAAY,QAAQ;EAC7B,KAAK,UAAU;EACf,KAAK,SAAS,KAAK,MAAM;CAC3B;;CAGA,gBAAgB,WAA8C;EAC5D,MAAM,SAAS,cAAc,WAAW,KAAK,iBAAiB,GAAG,KAAK,SAAS;EAC/E,KAAK,UAAU,MAAM;EACrB,OAAO;CACT;;CAGA,SAAS,QAAoB,OAA0B;EACrD,KAAK,QAAQ,UAAU;EACvB,IAAI,WAAW,KAAK,SAAS,KAAK,SAAS,KAAK,MAAM;CACxD;CAEA,IAAI,KAAsB;EACxB,MAAM,SAAS,KAAK,QAAQ,KAAK;EACjC,MAAM,WAAW,KAAK,QAAQ,KAAK;EACnC,OACG,WAAW,KAAA,KAAa,OAAO,OAAO,QAAQ,GAAG,KACjD,aAAa,KAAA,KAAa,OAAO,OAAO,UAAU,GAAG;CAE1D;CAEA,EAAE,KAAa,QAAgC;EAC7C,MAAM,SAAS,KAAK,QAAQ,KAAK;EACjC,MAAM,WAAW,KAAK,QAAQ,KAAK;EAKnC,OAAO,eAHJ,WAAW,KAAA,KAAa,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA,OACnE,aAAa,KAAA,KAAa,OAAO,OAAO,UAAU,GAAG,IAAI,SAAS,OAAO,KAAA,MAC1E,KAC6B,QAAQ,KAAK,OAAO;CACrD;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/plurals.ts","../src/format.ts","../src/format-timestamp.ts","../src/resolve.ts","../src/manager.ts"],"sourcesContent":["import type { LocaleCode } from './types.js';\n\n/**\n * Minimal CLDR-inspired plural classifier. Supports a handful of locales\n * natively — fall back to English rules if unknown. This is not a full ICU\n * implementation; it covers the categories used by our string tables.\n *\n * The sign of the count is ignored, and a non-integer count follows CLDR's\n * visible-fraction rules: a JS number shows fraction digits only when it is\n * not an integer, so CLDR's `v = 0` is `Number.isInteger(n)`.\n */\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';\n\n/** Receives a finite, non-negative count. */\ntype PluralRule = (n: number) => PluralCategory;\n\nconst ENGLISH: PluralRule = (n) => (n === 1 ? 'one' : 'other');\n\n// CLDR `i = 0,1`: the integer part decides, so 0.5 and 1.5 are `one`.\nconst FRENCH: PluralRule = (n) => (n < 2 ? 'one' : 'other');\n\nconst POLISH: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n if (n === 1) return 'one';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n return 'many';\n};\n\nconst RUSSIAN: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n const mod10 = n % 10;\n const mod100 = n % 100;\n if (mod10 === 1 && mod100 !== 11) return 'one';\n if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';\n if (mod10 === 0 || (mod10 >= 5 && mod10 <= 9) || (mod100 >= 11 && mod100 <= 14)) return 'many';\n return 'other';\n};\n\nconst ARABIC: PluralRule = (n) => {\n if (!Number.isInteger(n)) return 'other';\n if (n === 0) return 'zero';\n if (n === 1) return 'one';\n if (n === 2) return 'two';\n const mod100 = n % 100;\n if (mod100 >= 3 && mod100 <= 10) return 'few';\n if (mod100 >= 11 && mod100 <= 99) return 'many';\n return 'other';\n};\n\nconst JAPANESE: PluralRule = () => 'other';\n\n// Keyed by lower-case tag with `-` separators. A full tag wins over its language.\nconst RULES: Record<string, PluralRule> = {\n en: ENGLISH,\n de: ENGLISH,\n es: ENGLISH,\n fr: FRENCH,\n it: ENGLISH,\n pt: FRENCH,\n 'pt-pt': ENGLISH,\n nl: ENGLISH,\n pl: POLISH,\n ru: RUSSIAN,\n uk: RUSSIAN,\n ar: ARABIC,\n ja: JAPANESE,\n ko: JAPANESE,\n zh: JAPANESE,\n};\n\nconst SUBTAG_SEPARATOR = /[-_]/;\nconst UNDERSCORES = /_/g;\n\nfunction ruleFor(locale: LocaleCode): PluralRule {\n const tag = locale.toLowerCase();\n const sep = tag.search(SUBTAG_SEPARATOR);\n if (sep < 0) return RULES[tag] ?? ENGLISH;\n return RULES[tag.replace(UNDERSCORES, '-')] ?? RULES[tag.slice(0, sep)] ?? ENGLISH;\n}\n\n/**\n * Plural category of `n` in `locale`. The sign of `n` is ignored, a\n * non-integer follows CLDR's visible-fraction rules, and `NaN` or an infinity\n * is `other`. A region with its own entry (`pt-PT`) is looked up before its\n * language; an unknown locale uses the English rule.\n */\nexport function pluralCategory(locale: LocaleCode, n: number): PluralCategory {\n if (!Number.isFinite(n)) return 'other';\n return ruleFor(locale)(Math.abs(n));\n}\n","import { pluralCategory } from './plurals.js';\nimport type { LocaleCode, MessageValues } from './types.js';\n\n/**\n * Minimal ICU MessageFormat-ish parser.\n *\n * Grammar:\n * text := (chunk)*\n * chunk := literal | '{' var '}' | '{' var ',' 'plural' ',' branches '}'\n * branches := (selector '{' text '}')+\n * selector := '=' number | identifier // one | few | many | other | zero | two\n * number/ident literals inside a branch may reference '#' → the variable's number value.\n *\n * Nested plural blocks are not supported (not needed for our tables).\n */\n\nexport function formatMessage(\n template: string,\n values: MessageValues | undefined,\n locale: LocaleCode,\n): string {\n const vals = values ?? {};\n let out = '';\n let i = 0;\n const len = template.length;\n while (i < len) {\n const ch = template[i];\n if (ch !== '{') {\n out += ch;\n i++;\n continue;\n }\n // Find the matching closing brace, respecting nested braces.\n const endIdx = findMatchingClose(template, i);\n if (endIdx === -1) {\n // Malformed — emit remainder literally.\n out += template.slice(i);\n break;\n }\n const inner = template.slice(i + 1, endIdx);\n out += renderPlaceholder(inner, vals, locale);\n i = endIdx + 1;\n }\n return out;\n}\n\nfunction findMatchingClose(src: string, startBrace: number): number {\n let depth = 0;\n for (let i = startBrace; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\nfunction renderPlaceholder(inner: string, values: MessageValues, locale: LocaleCode): string {\n // Split only on the top-level commas into at most 3 parts: name, type, body.\n const commaIdx = topLevelComma(inner);\n if (commaIdx === -1) {\n const k = inner.trim();\n return stringifyValue(Object.hasOwn(values, k) ? values[k] : undefined);\n }\n const name = inner.slice(0, commaIdx).trim();\n const rest = inner.slice(commaIdx + 1).trim();\n const secondComma = topLevelComma(rest);\n if (secondComma === -1)\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n const type = rest.slice(0, secondComma).trim();\n const body = rest.slice(secondComma + 1).trim();\n if (type !== 'plural') {\n // Unknown formatter — fall back to raw substitution.\n return stringifyValue(Object.hasOwn(values, name) ? values[name] : undefined);\n }\n const raw = Object.hasOwn(values, name) ? values[name] : undefined;\n const n = typeof raw === 'number' ? raw : Number(raw);\n const category = Number.isFinite(n) ? pluralCategory(locale, n) : 'other';\n const branches = parsePluralBranches(body);\n const branchText =\n branches[`=${Number.isFinite(n) ? n : ''}`] ?? branches[category] ?? branches.other ?? '';\n // '#' inside the branch refers to the numeric value.\n const replaced = branchText.replace(/#/g, Number.isFinite(n) ? String(n) : '');\n // Recurse so nested `{var}` inside the branch is resolved.\n return formatMessage(replaced, values, locale);\n}\n\nfunction topLevelComma(src: string): number {\n let depth = 0;\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '{') depth++;\n else if (c === '}') depth--;\n else if (c === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nfunction parsePluralBranches(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n let i = 0;\n while (i < body.length) {\n // Skip whitespace.\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (i >= body.length) break;\n // Read selector until whitespace or '{'.\n const selStart = i;\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '{') break;\n i++;\n }\n const selector = body.slice(selStart, i);\n while (i < body.length) {\n const ch = body[i];\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') i++;\n else break;\n }\n if (body[i] !== '{') break;\n const end = findMatchingClose(body, i);\n if (end === -1) break;\n out[selector] = body.slice(i + 1, end);\n i = end + 1;\n }\n return out;\n}\n\nfunction stringifyValue(v: unknown): string {\n if (v === undefined || v === null) return '';\n return String(v);\n}\n","import type { LocaleCode } from './types.js';\n\nexport interface FormatTimestampOptions {\n /** Intl.DateTimeFormat date style. Defaults to 'short'. */\n dateStyle?: 'full' | 'long' | 'medium' | 'short';\n /**\n * Intl.DateTimeFormat time style.\n *\n * Applied when explicitly provided here, or when the entire `options`\n * argument is omitted (defaults to 'short' in that case).\n * Passing an `options` object that does NOT include `timeStyle` yields a\n * date-only result — time is suppressed.\n */\n timeStyle?: 'full' | 'long' | 'medium' | 'short';\n /** Returned for ts <= 0 or on any Intl failure. Defaults to ''. */\n fallback?: string;\n}\n\n/**\n * Format a Unix timestamp (milliseconds) as a human-readable date/time string\n * using Intl.DateTimeFormat with the given locale.\n *\n * Returns `options.fallback` (default '') for ts <= 0 or on any Intl error\n * (e.g. unsupported locale on a constrained runtime). The locale is used\n * directly as the Intl BCP-47 tag.\n *\n * Safe on all target runtimes: Bun (V8), React Native Hermes (>= 0.70), web.\n */\nexport function formatTimestamp(\n ts: number,\n locale: LocaleCode,\n options?: FormatTimestampOptions,\n): string {\n const fallback = options?.fallback ?? '';\n if (ts <= 0) return fallback;\n try {\n const intlOpts: Intl.DateTimeFormatOptions = {\n dateStyle: options?.dateStyle ?? 'short',\n };\n if (options?.timeStyle !== undefined) {\n intlOpts.timeStyle = options.timeStyle;\n } else if (options === undefined) {\n intlOpts.timeStyle = 'short';\n }\n return new Intl.DateTimeFormat(locale, intlOpts).format(new Date(ts));\n } catch {\n return fallback;\n }\n}\n","import type { LocaleCode } from './types.js';\n\n/**\n * Negotiate the best locale match from a prioritized list against a set of\n * available locales. Matching is case-insensitive and considers language +\n * region. Returns the fallback when nothing matches.\n */\nexport function resolveLocale(\n requested: readonly LocaleCode[],\n available: readonly LocaleCode[],\n fallback: LocaleCode,\n): LocaleCode {\n if (available.length === 0) return fallback;\n const norm = (s: string): string => s.toLowerCase().replace(/_/g, '-');\n const avail = available.map(norm);\n\n for (const rawReq of requested) {\n const req = norm(rawReq);\n // Exact match.\n const exactIdx = avail.indexOf(req);\n if (exactIdx !== -1) return available[exactIdx] as LocaleCode;\n // Language-only match against any region variant.\n const lang = req.split('-')[0] ?? req;\n const langIdx = avail.findIndex((a) => (a.split('-')[0] ?? a) === lang);\n if (langIdx !== -1) return available[langIdx] as LocaleCode;\n }\n // Fallback — ensure it is actually present; otherwise first available.\n const fbIdx = avail.indexOf(norm(fallback));\n if (fbIdx !== -1) return available[fbIdx] as LocaleCode;\n return available[0] as LocaleCode;\n}\n","import { Signal } from '@flare-engine/events';\nimport { formatMessage } from './format.js';\nimport { resolveLocale } from './resolve.js';\nimport type { LocaleCode, MessageValues, StringTable } from './types.js';\n\nexport interface LocalizationManagerOptions {\n tables: Record<LocaleCode, StringTable>;\n initialLocale: LocaleCode;\n fallbackLocale: LocaleCode;\n}\n\n/**\n * Owns the active locale + string tables. `t(key, values?)` renders a message\n * using the active locale, falling back to the fallback locale, then the raw\n * key. `onChange` fires whenever the active locale is swapped. `setTable`\n * replaces a locale's table in place — enables hot-reload in dev.\n */\nexport class LocalizationManager {\n private _tables: Record<LocaleCode, StringTable>;\n private _locale: LocaleCode;\n private readonly _fallback: LocaleCode;\n readonly onChange = new Signal<LocaleCode>();\n\n constructor(options: LocalizationManagerOptions) {\n this._tables = { ...options.tables };\n this._fallback = options.fallbackLocale;\n this._locale = options.initialLocale;\n }\n\n get locale(): LocaleCode {\n return this._locale;\n }\n\n get fallback(): LocaleCode {\n return this._fallback;\n }\n\n availableLocales(): LocaleCode[] {\n return Object.keys(this._tables);\n }\n\n setLocale(locale: LocaleCode): void {\n if (this._locale === locale) return;\n this._locale = locale;\n this.onChange.emit(locale);\n }\n\n /** Pick the best-matching locale from the given requests and make it active. */\n negotiateLocale(requested: readonly LocaleCode[]): LocaleCode {\n const chosen = resolveLocale(requested, this.availableLocales(), this._fallback);\n this.setLocale(chosen);\n return chosen;\n }\n\n /** Replace (or install) a locale's table. Emits `onChange` if it targets the active locale. */\n setTable(locale: LocaleCode, table: StringTable): void {\n this._tables[locale] = table;\n if (locale === this._locale) this.onChange.emit(locale);\n }\n\n has(key: string): boolean {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n return (\n (active !== undefined && Object.hasOwn(active, key)) ||\n (fallback !== undefined && Object.hasOwn(fallback, key))\n );\n }\n\n t(key: string, values?: MessageValues): string {\n const active = this._tables[this._locale];\n const fallback = this._tables[this._fallback];\n const template =\n (active !== undefined && Object.hasOwn(active, key) ? active[key] : undefined) ??\n (fallback !== undefined && Object.hasOwn(fallback, key) ? fallback[key] : undefined) ??\n key;\n return formatMessage(template, values, this._locale);\n }\n}\n"],"mappings":";;AAiBA,MAAM,WAAuB,MAAO,MAAM,IAAI,QAAQ;AAGtD,MAAM,UAAsB,MAAO,IAAI,IAAI,QAAQ;AAEnD,MAAM,UAAsB,MAAM;CAChC,IAAI,CAAC,OAAO,UAAU,CAAC,GAAG,OAAO;CACjC,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CACnB,IAAI,SAAS,KAAK,SAAS,MAAM,SAAS,MAAM,SAAS,KAAK,OAAO;CACrE,OAAO;AACT;AAEA,MAAM,WAAuB,MAAM;CACjC,IAAI,CAAC,OAAO,UAAU,CAAC,GAAG,OAAO;CACjC,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CACnB,IAAI,UAAU,KAAK,WAAW,IAAI,OAAO;CACzC,IAAI,SAAS,KAAK,S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QAAQ,KAAK,OAAO;CACrD;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/localization",
3
- "version": "0.4.17",
3
+ "version": "0.4.19",
4
4
  "description": "String tables, locale resolution, ICU-style plurals + interpolation",
5
5
  "keywords": [
6
6
  "flare-engine",
@@ -45,7 +45,7 @@
45
45
  "typecheck": "tsc --noEmit"
46
46
  },
47
47
  "dependencies": {
48
- "@flare-engine/events": "^0.4.17"
48
+ "@flare-engine/events": "^0.4.19"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=20"