@oxog/i18n 0.2.0 → 0.2.1

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/README.md CHANGED
@@ -39,15 +39,18 @@ i18n.t('greeting', { name: 'Mundo' }); // "¡Hola, Mundo!"
39
39
  | Option | Description |
40
40
  | --- | --- |
41
41
  | `locale` | Active locale (required). |
42
- | `fallbackLocale` | Catalog used when a key is missing in the active locale. |
42
+ | `fallbackLocale` | Catalog used when a key is missing in the active locale and its base languages. |
43
43
  | `messages` | `{ [locale]: catalog }`; catalogs may nest objects (`user.profile.title`). |
44
44
  | `plugins` | Plugins such as `icuPlugin` or `markdownPlugin`. |
45
45
  | `pluralizationRules` | Custom rules per locale or language, e.g. `{ ar: count => ... }`. |
46
- | `formats` | Named `Intl.NumberFormat` / `Intl.DateTimeFormat` options (`{{value:number}}`). |
46
+ | `formats` | Named `Intl.NumberFormat` / `Intl.DateTimeFormat` options: `{{value:number}}` uses `default`, `{{value:number:percent}}` / `{{value:date:short}}` a named one. |
47
47
  | `warnOnMissingTranslations` | Log missing keys outside production. |
48
48
  | `onError` | Called with errors from plugins, formatters and listeners. |
49
49
 
50
- A missing key returns the key itself. Lookups only use own string values: nested groups,
50
+ Keys are looked up BCP 47 style: the active locale, then its base languages
51
+ (`zh-Hant-TW` → `zh-Hant` → `zh`, `en-US` → `en`), then `fallbackLocale` and its base
52
+ languages. So `locale: 'en-US'` works with an `en` catalog, and `pt-BR` uses `pt` before
53
+ the fallback. A missing key returns the key itself. Lookups only use own string values: nested groups,
51
54
  `constructor`, `toString` and other `Object.prototype` members are never returned as
52
55
  translations, and `__proto__` keys in loaded JSON cannot modify `Object.prototype`.
53
56
 
@@ -100,10 +103,13 @@ nested `select`. `{{name}}` interpolation keeps working.
100
103
 
101
104
  - `t(key, params?)` – translate.
102
105
  - `setLocale(locale)`, `getLocale()`, `locale`, `fallbackLocale`.
103
- - `hasTranslation(key, locale?)` – whether a string exists for the key.
106
+ - `hasTranslation(key, locale?, { exact }?)` – whether `t()` finds a string for the key in
107
+ `locale` (default: the active locale), following the same lookup chain (base languages,
108
+ then the fallback locale). `{ exact: true }` checks only that locale's own catalog.
104
109
  - `addMessages(locale, messages)` – deep-merge messages (e.g. after a lazy `import()`).
105
- - `subscribe(listener)` – called after a locale switch and after `addMessages()` for the
106
- active or fallback locale; returns an unsubscribe function. `revision` increments on each
110
+ - `subscribe(listener)` – called after a locale switch, after `addMessages()` for a locale
111
+ in the lookup chain, and after `addPlugin()` / `removePlugin()`; returns an unsubscribe
112
+ function. `revision` increments on each
107
113
  such change.
108
114
  - `addPlugin(plugin)`, `removePlugin(name)`.
109
115
  - `formatNumber(value, format?)`, `formatDate(date, format?)`, `formatRelativeTime(date, base?)`.
package/dist/index.d.mts CHANGED
@@ -74,13 +74,22 @@ interface I18nInstance<TMessages extends object = Messages> {
74
74
  readonly messages: LocaleMessages<TMessages>;
75
75
  readonly t: TranslationFunction<TMessages>;
76
76
  /**
77
- * Incremented whenever the visible translations change (locale switch, or messages
78
- * added for the active or fallback locale). Useful as a snapshot for UI bindings.
77
+ * Incremented whenever the visible translations change (locale switch, messages added
78
+ * for a locale in the lookup chain, plugin added or removed). Useful as a snapshot for UI
79
+ * bindings.
79
80
  */
80
81
  readonly revision?: number;
81
82
  setLocale(locale: LocaleCode): void;
82
83
  getLocale(): LocaleCode;
83
- hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
84
+ /**
85
+ * Whether `t()` finds a string for `key` in `locale` (default: the active locale), following
86
+ * the same lookup chain: the locale, its base languages (`en-US` → `en`), then
87
+ * `fallbackLocale` and its base languages. Pass `{ exact: true }` to check only that
88
+ * locale's own catalog (e.g. to list keys still missing from a translation).
89
+ */
90
+ hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode, options?: {
91
+ exact?: boolean;
92
+ }): boolean;
84
93
  addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
85
94
  addPlugin(plugin: I18nPlugin<TMessages>): void;
86
95
  removePlugin(pluginName: string): void;
@@ -89,7 +98,9 @@ interface I18nInstance<TMessages extends object = Messages> {
89
98
  formatRelativeTime(value: Date, baseDate?: Date): string;
90
99
  /**
91
100
  * Subscribes to translation changes: called with the active locale after `setLocale`
92
- * switches locale and after `addMessages` adds messages for the active or fallback locale.
101
+ * switches locale, after `addMessages` adds messages for a locale in the lookup chain
102
+ * (the active locale, its base languages, the fallback locale and its base languages) and
103
+ * after `addPlugin` / `removePlugin`.
93
104
  */
94
105
  subscribe(listener: (locale: LocaleCode) => void): () => void;
95
106
  }
package/dist/index.d.ts CHANGED
@@ -74,13 +74,22 @@ interface I18nInstance<TMessages extends object = Messages> {
74
74
  readonly messages: LocaleMessages<TMessages>;
75
75
  readonly t: TranslationFunction<TMessages>;
76
76
  /**
77
- * Incremented whenever the visible translations change (locale switch, or messages
78
- * added for the active or fallback locale). Useful as a snapshot for UI bindings.
77
+ * Incremented whenever the visible translations change (locale switch, messages added
78
+ * for a locale in the lookup chain, plugin added or removed). Useful as a snapshot for UI
79
+ * bindings.
79
80
  */
80
81
  readonly revision?: number;
81
82
  setLocale(locale: LocaleCode): void;
82
83
  getLocale(): LocaleCode;
83
- hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
84
+ /**
85
+ * Whether `t()` finds a string for `key` in `locale` (default: the active locale), following
86
+ * the same lookup chain: the locale, its base languages (`en-US` → `en`), then
87
+ * `fallbackLocale` and its base languages. Pass `{ exact: true }` to check only that
88
+ * locale's own catalog (e.g. to list keys still missing from a translation).
89
+ */
90
+ hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode, options?: {
91
+ exact?: boolean;
92
+ }): boolean;
84
93
  addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
85
94
  addPlugin(plugin: I18nPlugin<TMessages>): void;
86
95
  removePlugin(pluginName: string): void;
@@ -89,7 +98,9 @@ interface I18nInstance<TMessages extends object = Messages> {
89
98
  formatRelativeTime(value: Date, baseDate?: Date): string;
90
99
  /**
91
100
  * Subscribes to translation changes: called with the active locale after `setLocale`
92
- * switches locale and after `addMessages` adds messages for the active or fallback locale.
101
+ * switches locale, after `addMessages` adds messages for a locale in the lookup chain
102
+ * (the active locale, its base languages, the fallback locale and its base languages) and
103
+ * after `addPlugin` / `removePlugin`.
93
104
  */
94
105
  subscribe(listener: (locale: LocaleCode) => void): () => void;
95
106
  }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';function V(r,t,s,o,n){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(u,d)=>{let p=c(d);return p===void 0?u:n?n(p):p})}catch(u){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",u),r}function c(u){try{let[d,p]=u.trim().split(":").map(h=>h.trim());if(!Object.prototype.hasOwnProperty.call(t,d)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${d}`);return}let m=t[d];if(p&&s?.has(p))try{let h=s.get(p);if(!h)return String(m);let f=h(m,u.includes(":")?u.split(":").slice(1).join(":"):void 0,o);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${p}' must return a string, got ${typeof f}`),String(m)):f}catch(h){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,h),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(o||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(d){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",d);return}}}function M(r,t){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!t||typeof t!="object")return r;try{let s={...r};for(let o in t){if(o==="__proto__"||o==="constructor"||o==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${o}`);continue}if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];if(n!==void 0)if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof Date)){let c=s[o];s[o]=M(c&&typeof c=="object"?c:{},n);}else s[o]=n;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),r}}function A(r,t){if(!(!r||typeof r!="object"||!t||typeof t!="string"))try{let s=t.split("."),o=r;for(let n of s)if(o&&typeof o=="object"&&Object.prototype.hasOwnProperty.call(o,n))o=o[n];else return;return o}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function F(r){let t=new Map,s=r?.maxSize??1e3;return {get:o=>{let n=t.get(o);return n!==void 0&&(t.delete(o),t.set(o,n)),n},set:(o,n)=>{if(t.has(o))t.delete(o);else if(t.size>=s){let c=t.keys().next().value;c!==void 0&&t.delete(c);}t.set(o,n);},clear:()=>t.clear(),size:()=>t.size}}var te={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},S=new Map;function X(r){let t=S.get(r);if(!t){try{let s=r.replace(/_/g,"-");t=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{t=new Intl.PluralRules("en");}S.set(r,t);}return t}function K(r,t,s){if(s){let o=r.split(/[-_]/)[0],n=Object.prototype.hasOwnProperty.call(s,r)?s[r]:Object.prototype.hasOwnProperty.call(s,o)?s[o]:void 0;if(typeof n=="function")return n(t)}return X(r).select(t)}function Y(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let t=Object.keys(r.messages).length>0;if(t||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys"),t&&!(r.locale in r.messages)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!(r.locale in r.messages)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!(r.fallbackLocale in r.messages)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let s=r.locale,o=r.fallbackLocale,n=structuredClone(r.messages),c=[...r.plugins||[]],u=new Set,d=F(),p=0,m=()=>{p++,u.forEach(e=>{try{e(s);}catch(i){h(i,"Locale change listener");}});},h=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},f=new Map;f.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let l=r.formats?.number?.[i||"default"]||{};return new Intl.NumberFormat(a||s,l).format(e)}),f.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let l=r.formats?.date?.[i||"default"]||{};return new Intl.DateTimeFormat(a||s,l).format(e)}),f.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let l=(i||"currency:USD").split(":"),g=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||s,{style:"currency",currency:g}).format(e)}catch(w){return h(w,`Currency formatter error for currency '${g}'`),`${g} ${e}`}}),c.forEach(e=>{e.format&&f.set(e.name,(i,a,l)=>e.format(i,a??"",l??s));});function P(e,i){if(!Object.prototype.hasOwnProperty.call(n,i))return;let a=n[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof l=="string"?l:void 0}function L(e,i,a){let l=o&&o!==a?[a,o]:[a],g=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let w of l){if(typeof g=="number"){let O=new Set;g===0&&O.add("zero"),O.add(K(w,g,r.pluralizationRules)),O.add("other");for(let $ of O){let v=P(`${e}.${$}`,w);if(v)return {message:v,messageLocale:w}}}let _=P(e,w);if(_)return {message:_,messageLocale:w}}}function N(e,i,a=s){try{let l="";if(i){let y=Object.keys(i);if(y.length>0)try{if(y.length===1){let b=y[0];l=`${b}:${JSON.stringify(i[b])}`;}else {let b=y.sort(),D={};for(let C of b)D[C]=i[C];l=JSON.stringify(D);}}catch{typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Failed to serialize params for caching, using fallback key"),l=y.sort().join(",");}}let g=`${a}:${e}:${l}`,w=d.get(g);if(w!==void 0)return w;let _=L(e,i,a);if(!_)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:O,messageLocale:$}=_,v=O;for(let y of c)if(y.transform)try{let b=y.transform(e,v,i||{},a,$);if(typeof b!="string"){h(new Error(`Plugin transform must return a string, got ${typeof b}`),`Plugin ${y.name} transform validation`);continue}v=b;}catch(b){h(b,`Plugin ${y.name} transform`);}let R=c.filter(y=>typeof y.escapeValue=="function");return v=V(v,i||{},f,s,R.length>0?y=>R.reduce((b,D)=>D.escapeValue(b),y):void 0),d.set(g,v),v}catch(l){return h(l,`Translation error for key ${e}`),e}}let x=(e,i)=>N(String(e),i);function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");n[e]||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(n).join(", ")}`),e!==s&&(s=e,d.clear(),m());}function I(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{n[e]||(n[e]={});let a=i;for(let l of c)if(l.beforeLoad)try{let g=l.beforeLoad(e,a);if(!g||typeof g!="object"||Array.isArray(g)){h(new Error(`Plugin beforeLoad must return an object, got ${typeof g}`),`Plugin ${l.name} beforeLoad validation`);continue}a=g;}catch(g){h(g,`Plugin ${l.name} beforeLoad`);}n[e]=M(n[e],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(e,n[e]);}catch(g){h(g,`Plugin ${l.name} afterLoad`);}d.clear(),(e===s||e===o)&&m();}catch(a){throw h(a,"Error adding messages"),a}}function U(e,i){let a=i||s;return P(String(e),a)!==void 0}function H(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&f.set(e.name,(a,l,g)=>e.format(a,l??"",g??s)),d.clear();}function q(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),f.delete(e),d.clear());}function J(e){return u.add(e),()=>u.delete(e)}function B(e,i){let a=f.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,s)}function G(e,i){let a=f.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,s)}function Q(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),g=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[w,_]of g)if(Math.abs(a)>=_)return l.format(Math.round(a/_),w);return l.format(0,"second")}return {get locale(){return s},get fallbackLocale(){return o},get messages(){return n},get revision(){return p},t:x,setLocale:T,getLocale:()=>s,hasTranslation:U,addMessages:I,addPlugin:H,removePlugin:q,subscribe:J,formatNumber:B,formatDate:G,formatRelativeTime:Q}}var E=class extends Error{},j=class{constructor(t){this.source=t;}cursor=0;parse(){return this.message(0,false).parts}take(t){t.lastIndex=this.cursor;let s=t.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(t){let s=this.take(t);if(s===void 0)throw new E;return s}space(){this.take(/\s+/y);}number(){let t=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(t))throw new E;return t}quote(){let t="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;t+=s;}return t}message(t,s){if(t>64)throw new E;let o=[],n="";function c(){n&&o.push(n),n="";}for(;this.cursor<this.source.length;){let u=this.source.charAt(this.cursor);if(u==="}"){if(t===0)throw new E;return this.cursor++,c(),{parts:o,closed:true}}if(u==="{"){let d=this.take(/\{\{[^{}]*\}\}/y);d!==void 0?n+=d:(c(),o.push(this.argument(t)));}else u==="'"&&this.take(/''/y)?n+="'":u==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?n+=this.quote():(this.cursor++,u==="#"&&s?(c(),o.push({kind:"number"})):n+=u);}return c(),{parts:o,closed:false}}argument(t){let s=this.cursor++;this.space();let o=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:o,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let n=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let c=n!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let u=new Map;for(;!this.take(/\}/y);){let d=n!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(t+1,n!=="select");if(!p.closed)throw new E;u.has(d)||u.set(d,p.parts),this.space();}if(!u.has("other"))throw new E;return {kind:n,name:o,choices:u,offset:c,source:this.source.slice(s,this.cursor)}}};function Z(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ee(r,t,s){let o=Z(s),n={maximumSignificantDigits:21},c,u,d;function p(m,h){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return h===void 0?"#":(d??=new Intl.NumberFormat(o,n)).format(h);if(!Object.hasOwn(t,f.name))return f.source;let P=t[f.name];if(f.kind==="value")return String(P);if(f.kind==="select"){let I=f.choices.get(String(P))??f.choices.get("other");return I?p(I):f.source}if(typeof P!="number"||!Number.isFinite(P))return f.source;let L=P-f.offset;if(!Number.isFinite(L))return f.source;let N=f.choices.get("="+P);if(N)return p(N,L);let x=f.kind==="plural"?c??=new Intl.PluralRules(o,n):u??=new Intl.PluralRules(o,{...n,type:"ordinal"}),T=f.choices.get(x.select(L))??f.choices.get("other");return T?p(T,L):f.source}).join("")}return p(r)}function z(){return {name:"icu",transform:(r,t,s,o,n)=>{if(!/[{']/.test(t))return t;try{return ee(new j(t).parse(),s,n??o)}catch(c){if(c instanceof E)return t;throw c}}}}function k(r){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,s=>t[s])}function re(r){let t=r.trim().toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:")||t.startsWith("vbscript:")||t.startsWith("file:")?"#":k(r)}function W(){return {name:"markdown",escapeValue:k,transform:(r,t,s,o)=>{let n=t,c=[],u=0;n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(d,p,m)=>{let h=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<a href="${re(m)}">${k(p)}</a>`,u++,h}),n=n.replace(/\*\*(.*?)\*\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<strong>${k(p)}</strong>`,u++,m}),n=n.replace(/\*(.*?)\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<em>${k(p)}</em>`,u++,m}),n=n.replace(/`(.*?)`/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<code>${k(p)}</code>`,u++,m}),n=k(n);for(let d=0;d<c.length;d++)n=n.replace(`__MARKDOWN_PLACEHOLDER_${d}__`,c[d]);return n}}}var le=W(),fe=z();exports.createCache=F;exports.createI18n=Y;exports.deepMerge=M;exports.defaultPluralRules=te;exports.getNestedValue=A;exports.getPluralForm=K;exports.icuPlugin=fe;exports.interpolate=V;exports.markdownPlugin=le;//# sourceMappingURL=index.js.map
1
+ 'use strict';function S(r,n,o,t,s){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let d=l(g);return d===void 0?c:s?s(d):d})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),r}function l(c){try{let[g,d]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(d&&o?.has(d))try{let b=o.get(d);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${d}' must return a string, got ${typeof f}`),String(m)):f}catch(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${d}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function D(r,n){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return r;try{let o={...r};for(let t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let s=n[t];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Date)){let l=o[t];o[t]=D(l&&typeof l=="object"?l:{},s);}else o[t]=s;}return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function A(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),t=r;for(let s of o)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,s))t=t[s];else return;return t}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function V(r){let n=new Map,o=r?.maxSize??1e3;return {get:t=>{let s=n.get(t);return s!==void 0&&(n.delete(t),n.set(t,s)),s},set:(t,s)=>{if(n.has(t))n.delete(t);else if(n.size>=o){let l=n.keys().next().value;l!==void 0&&n.delete(l);}n.set(t,s);},clear:()=>n.clear(),size:()=>n.size}}var ae={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},R=new Map;function ee(r){let n=R.get(r);if(!n){try{let o=r.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(o).length>0?o:"en");}catch{n=new Intl.PluralRules("en");}R.set(r,n);}return n}function F(r,n,o){if(o){let t=r.split(/[-_]/)[0],s=Object.prototype.hasOwnProperty.call(o,r)?o[r]:Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0;if(typeof s=="function")return s(n)}return ee(r).select(n)}function re(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let n=Object.keys(r.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let o=e=>N(e).some(i=>Object.prototype.hasOwnProperty.call(r.messages,i));if(n&&!o(r.locale)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!o(r.locale)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!o(r.fallbackLocale)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let t=r.locale,s=r.fallbackLocale,l=structuredClone(r.messages),c=[...r.plugins||[]],g=new Set,d=V(),m=0,b=()=>{m++,g.forEach(e=>{try{e(t);}catch(i){f(i,"Locale change listener");}});},f=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},y=new Map;function E(e,i,a){if(!e)return;let u=h=>Object.prototype.hasOwnProperty.call(e,h)?e[h]:void 0;if(i&&u(i))return u(i);let p=(i||"").split(":").map(h=>h.trim());return p[0]===a&&p.shift(),u(p.join(":")||"default")}y.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let u=E(r.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,u).format(e)}),y.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let u=E(r.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,u).format(e)}),y.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let u=(i||"currency:USD").split(":"),p=u.length>1&&u[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:p}).format(e)}catch(h){return f(h,`Currency formatter error for currency '${p}'`),`${p} ${e}`}}),c.forEach(e=>{e.format&&y.set(e.name,(i,a,u)=>e.format(i,a??"",u??t));});function T(e,i){if(!Object.prototype.hasOwnProperty.call(l,i))return;let a=l[i];if(!a||typeof a!="object")return;let u=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof u=="string"?u:void 0}function j(e,i,a){let u=k(a),p=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of u){if(typeof p=="number"){let x=new Set;p===0&&x.add("zero"),x.add(F(h,p,r.pluralizationRules)),x.add("other");for(let $ of x){let w=T(`${e}.${$}`,h);if(w)return {message:w,messageLocale:h}}}let v=T(e,h);if(v)return {message:v,messageLocale:h}}}function k(e){return [...new Set([...N(e),...s?N(s):[]])]}function I(e,i,a=t){try{let u=i?te(i):"",p=u===void 0?void 0:`${a}:${e}:${u}`,h=p===void 0?void 0:d.get(p);if(h!==void 0)return h;let v=j(e,i,a);if(!v)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:x,messageLocale:$}=v,w=x;for(let O of c)if(O.transform)try{let L=O.transform(e,w,i||{},a,$);if(typeof L!="string"){f(new Error(`Plugin transform must return a string, got ${typeof L}`),`Plugin ${O.name} transform validation`);continue}w=L;}catch(L){f(L,`Plugin ${O.name} transform`);}let M=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,M.length>0?O=>M.reduce((L,Z)=>Z.escapeValue(L),O):void 0),p!==void 0&&d.set(p,w),w}catch(u){return f(u,`Translation error for key ${e}`),e}}let W=(e,i)=>I(String(e),i);function H(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");N(e).some(i=>Object.prototype.hasOwnProperty.call(l,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(l).join(", ")}`),e!==t&&(t=e,d.clear(),b());}function U(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{l[e]||(l[e]={});let a=i;for(let u of c)if(u.beforeLoad)try{let p=u.beforeLoad(e,a);if(!p||typeof p!="object"||Array.isArray(p)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof p}`),`Plugin ${u.name} beforeLoad validation`);continue}a=p;}catch(p){f(p,`Plugin ${u.name} beforeLoad`);}l[e]=D(l[e],a);for(let u of c)if(u.afterLoad)try{u.afterLoad(e,l[e]);}catch(p){f(p,`Plugin ${u.name} afterLoad`);}d.clear(),k(t).includes(e)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function q(e,i,a){let u=i||t;return (a?.exact?[u]:k(u)).some(h=>T(String(e),h)!==void 0)}function J(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&y.set(e.name,(a,u,p)=>e.format(a,u??"",p??t)),d.clear(),b();}function B(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),y.delete(e),d.clear(),b());}function G(e){return g.add(e),()=>g.delete(e)}function Q(e,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,t)}function X(e,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,t)}function Y(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),u=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),p=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[h,v]of p)if(Math.abs(a)>=v)return u.format(Math.round(a/v),h);return u.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return s},get messages(){return l},get revision(){return m},t:W,setLocale:H,getLocale:()=>t,hasTranslation:q,addMessages:U,addPlugin:J,removePlugin:B,subscribe:G,formatNumber:Q,formatDate:X,formatRelativeTime:Y}}function N(r){let n=[r],o=r;for(;;){let t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_"));if(t<=0)break;o=o.slice(0,t),t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_")),t>0&&o.length-t-1===1&&(o=o.slice(0,t)),n.push(o);}return n}function te(r){let n=[];for(let o of Object.keys(r).sort()){let t=r[o],s;if(typeof t=="string")s=JSON.stringify(t);else if(typeof t=="number")s=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)s=String(t);else if(t instanceof Date)s=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(o)}=${s}`);}return n.join(",")}var P=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let o=n.exec(this.source)?.[0];return o!==void 0&&(this.cursor+=o.length),o}expect(n){let o=this.take(n);if(o===void 0)throw new P;return o}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new P;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let o=this.source.charAt(this.cursor++);if(o==="'"&&!this.take(/'/y))break;n+=o;}return n}message(n,o){if(n>64)throw new P;let t=[],s="";function l(){s&&t.push(s),s="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new P;return this.cursor++,l(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?s+=g:(l(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?s+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||o&&this.source.charAt(this.cursor+1)==="#")?s+=this.quote():(this.cursor++,c==="#"&&o?(l(),t.push({kind:"number"})):s+=c);}return l(),{parts:t,closed:false}}argument(n){let o=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(o,this.cursor)};this.expect(/,/y),this.space();let s=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let l=s!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=s!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let d=this.message(n+1,s!=="select");if(!d.closed)throw new P;c.has(g)||c.set(g,d.parts),this.space();}if(!c.has("other"))throw new P;return {kind:s,name:t,choices:c,offset:l,source:this.source.slice(o,this.cursor)}}};function ne(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function oe(r,n,o){let t=ne(o),s={maximumSignificantDigits:21},l,c,g;function d(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,s)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return String(y);if(f.kind==="select"){let I=f.choices.get(String(y))??f.choices.get("other");return I?d(I):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let E=y-f.offset;if(!Number.isFinite(E))return f.source;let T=f.choices.get("="+y);if(T)return d(T,E);let j=f.kind==="plural"?l??=new Intl.PluralRules(t,s):c??=new Intl.PluralRules(t,{...s,type:"ordinal"}),k=f.choices.get(j.select(E))??f.choices.get("other");return k?d(k,E):f.source}).join("")}return d(r)}function K(){return {name:"icu",transform:(r,n,o,t,s)=>{if(!/[{']/.test(n))return n;try{return oe(new C(n).parse(),o,s??t)}catch(l){if(l instanceof P)return n;throw l}}}}function _(r){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,o=>n[o])}function se(r){let n=Array.from(r).filter(o=>o.charCodeAt(0)>32&&o.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":_(r)}function ie(r,n){return r.replace(/\{\{([^}]+)\}\}/g,(o,t)=>{let s=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,s))return o;let l=n[s];return l==null?"":String(l)})}function z(){return {name:"markdown",escapeValue:_,transform:(r,n,o,t)=>{let s=n,l=[],c=0;s=s.replace(/`(.*?)`/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<code>${_(d)}</code>`,c++,m}),s=s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,d,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=se(ie(m,o||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return l[c]=`<a href="${f}">${_(d)}</a>`,c++,b}),s=s.replace(/\*\*(.*?)\*\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<strong>${_(d)}</strong>`,c++,m}),s=s.replace(/\*(.*?)\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<em>${_(d)}</em>`,c++,m}),s=_(s);for(let g=l.length-1;g>=0;g--)s=s.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>l[g]);return s}}}var me=z(),he=K();exports.createCache=V;exports.createI18n=re;exports.deepMerge=D;exports.defaultPluralRules=ae;exports.getNestedValue=A;exports.getPluralForm=F;exports.icuPlugin=he;exports.interpolate=S;exports.markdownPlugin=me;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","parts","currency","plugin","getMessage","localeMessages","resolveMessage","locales","candidate","forms","form","pluralMessage","message","translate","paramKeys","sortedKeys","sortedParams","k","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","name","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","part","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","createMarkdownPlugin","_params","_locale","placeholders","placeholderIndex","_","placeholder","i","markdownPlugin","ic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CAAgB,CAAA,CAAI,WAAWX,CAAAA,CAAWC,CAAI,CAAC,CAAA,SAAA,CAAA,CAC5DU,CAAAA,EAAAA,CACOE,CACT,CAAC,CAAA,CAGD/H,EAASA,CAAAA,CAAO,OAAA,CAAQ,aAAc,CAAC8H,CAAAA,CAAGX,IAAS,CACjD,IAAMY,EAAc,CAAA,uBAAA,EAA0BF,CAAgB,KAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOX,EAAWC,CAAI,CAAC,QACxDU,CAAAA,EAAAA,CACOE,CACT,CAAC,CAAA,CAGD/H,CAAAA,CAASA,EAAO,OAAA,CAAQ,UAAA,CAAY,CAAC8H,CAAAA,CAAGX,CAAAA,GAAS,CAC/C,IAAMY,CAAAA,CAAc,0BAA0BF,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,EAAI,CAAA,MAAA,EAASX,CAAAA,CAAWC,CAAI,CAAC,CAAA,OAAA,CAAA,CAC1DU,IACOE,CACT,CAAC,EAGD/H,CAAAA,CAASkH,CAAAA,CAAWlH,CAAM,CAAA,CAG1B,IAAA,IAASgI,EAAI,CAAA,CAAGA,CAAAA,CAAIJ,EAAa,MAAA,CAAQI,CAAAA,EAAAA,CACvChI,EAASA,CAAAA,CAAO,OAAA,CAAQ,0BAA0BgI,CAAC,CAAA,EAAA,CAAA,CAAMJ,EAAaI,CAAC,CAAC,EAG1E,OAAOhI,CACT,CACF,CACF,KCxFaiI,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBlB,CAAAA","file":"index.js","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n // Validate that the current locale exists in messages, unless a fallback is provided or messages is empty\n if (hasMessages && !(config.locale in config.messages) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!(config.locale in config.messages) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !(config.fallbackLocale in config.messages)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n const locales = fallbackLocale && fallbackLocale !== locale ? [locale, fallbackLocale] : [locale];\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Generate cache key with deterministic param serialization\n // Sort keys to ensure consistent caching regardless of property order\n let paramKey = '';\n if (params) {\n const paramKeys = Object.keys(params);\n if (paramKeys.length > 0) {\n try {\n // Fast path for single parameter\n if (paramKeys.length === 1) {\n const key = paramKeys[0];\n paramKey = `${key}:${JSON.stringify(params[key])}`;\n } else {\n // Sort only when multiple parameters exist\n const sortedKeys = paramKeys.sort();\n const sortedParams: Record<string, unknown> = {};\n for (const k of sortedKeys) {\n sortedParams[k] = params[k];\n }\n paramKey = JSON.stringify(sortedParams);\n }\n } catch (stringifyError) {\n // Handle circular references or other JSON.stringify errors\n // Use a simpler key based on param keys only\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Failed to serialize params for caching, using fallback key');\n }\n paramKey = paramKeys.sort().join(',');\n }\n }\n }\n\n const cacheKey = `${locale}:${key}:${paramKey}`;\n const cached = translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if locale doesn't exist in messages\n if (!messages[locale]) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (locale === currentLocale || locale === fallbackLocale) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n const trimmed = href.trim().toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, _params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<a href=\"${sanitizeHref(href)}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // `code` -> <code>text</code>\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders\n for (let i = 0; i < placeholders.length; i++) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
1
+ {"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","i","markdownPlugin","icuPlugin"],"mappings":"aAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACK,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,EAAmBF,CAAG,CAAA,CAC1C,OAAIC,CAAAA,GAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,CAAAA,CAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,WAAa,YAAA,EAC9D,OAAA,CAAQ,MAAM,sCAAA,CAAwCA,CAAK,EAEtDT,CACT,CAEA,SAASQ,CAAAA,CAAmBF,CAAAA,CAAiC,CAC3D,GAAI,CACF,GAAM,CAACI,CAAAA,CAAUC,CAAM,EAAIL,CAAAA,CAAI,IAAA,E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,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,EAASA,CAAAA,CAAO,OAAA,CAAQ,gBAAA,CAAkB,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACrD,IAAMO,CAAAA,CAAc,0BAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,QAAA,EAAWZ,CAAAA,CAAWC,CAAI,CAAC,CAAA,SAAA,CAAA,CAC5DW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASA,EAAO,OAAA,CAAQ,YAAA,CAAc,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACjD,IAAMO,CAAAA,CAAc,CAAA,uBAAA,EAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,EAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOZ,CAAAA,CAAWC,CAAI,CAAC,QACxDW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASyH,EAAWzH,CAAM,CAAA,CAK1B,IAAA,IAASyI,CAAAA,CAAIL,CAAAA,CAAa,MAAA,CAAS,EAAGK,CAAAA,EAAK,CAAA,CAAGA,IAC5CzI,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0ByI,CAAC,CAAA,EAAA,CAAA,CAAM,IAAML,CAAAA,CAAaK,CAAC,CAAC,CAAA,CAGhF,OAAOzI,CACT,CACF,CACF,KChHa0I,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBpB,CAAAA","file":"index.js","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate => Object.prototype.hasOwnProperty.call(config.messages, candidate));\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(table: Record<string, T> | undefined, format: string | undefined, type: string): T | undefined {\n if (!table) return undefined;\n const own = (name: string) => (Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined);\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n\n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = namedFormat(config.formats?.date, format, 'date') || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function lookupChain(locale: LocaleCode): LocaleCode[] {\n return [...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])])];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n if (cacheKey !== undefined) translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if neither the locale nor its base language exists in messages\n if (!localeChain(locale).some(candidate => Object.prototype.hasOwnProperty.call(messages, candidate))) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== undefined);\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n notify();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined) encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace => (brace === '{' ? '&#123;' : '&#125;'));\n placeholders[placeholderIndex] = `<a href=\"${url}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- function V(r,t,s,o,n){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(u,d)=>{let p=c(d);return p===void 0?u:n?n(p):p})}catch(u){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",u),r}function c(u){try{let[d,p]=u.trim().split(":").map(h=>h.trim());if(!Object.prototype.hasOwnProperty.call(t,d)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${d}`);return}let m=t[d];if(p&&s?.has(p))try{let h=s.get(p);if(!h)return String(m);let f=h(m,u.includes(":")?u.split(":").slice(1).join(":"):void 0,o);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${p}' must return a string, got ${typeof f}`),String(m)):f}catch(h){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,h),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(o||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(d){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",d);return}}}function M(r,t){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!t||typeof t!="object")return r;try{let s={...r};for(let o in t){if(o==="__proto__"||o==="constructor"||o==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${o}`);continue}if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];if(n!==void 0)if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof Date)){let c=s[o];s[o]=M(c&&typeof c=="object"?c:{},n);}else s[o]=n;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),r}}function A(r,t){if(!(!r||typeof r!="object"||!t||typeof t!="string"))try{let s=t.split("."),o=r;for(let n of s)if(o&&typeof o=="object"&&Object.prototype.hasOwnProperty.call(o,n))o=o[n];else return;return o}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function F(r){let t=new Map,s=r?.maxSize??1e3;return {get:o=>{let n=t.get(o);return n!==void 0&&(t.delete(o),t.set(o,n)),n},set:(o,n)=>{if(t.has(o))t.delete(o);else if(t.size>=s){let c=t.keys().next().value;c!==void 0&&t.delete(c);}t.set(o,n);},clear:()=>t.clear(),size:()=>t.size}}var te={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},S=new Map;function X(r){let t=S.get(r);if(!t){try{let s=r.replace(/_/g,"-");t=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{t=new Intl.PluralRules("en");}S.set(r,t);}return t}function K(r,t,s){if(s){let o=r.split(/[-_]/)[0],n=Object.prototype.hasOwnProperty.call(s,r)?s[r]:Object.prototype.hasOwnProperty.call(s,o)?s[o]:void 0;if(typeof n=="function")return n(t)}return X(r).select(t)}function Y(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let t=Object.keys(r.messages).length>0;if(t||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys"),t&&!(r.locale in r.messages)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!(r.locale in r.messages)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!(r.fallbackLocale in r.messages)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let s=r.locale,o=r.fallbackLocale,n=structuredClone(r.messages),c=[...r.plugins||[]],u=new Set,d=F(),p=0,m=()=>{p++,u.forEach(e=>{try{e(s);}catch(i){h(i,"Locale change listener");}});},h=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},f=new Map;f.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let l=r.formats?.number?.[i||"default"]||{};return new Intl.NumberFormat(a||s,l).format(e)}),f.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let l=r.formats?.date?.[i||"default"]||{};return new Intl.DateTimeFormat(a||s,l).format(e)}),f.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let l=(i||"currency:USD").split(":"),g=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||s,{style:"currency",currency:g}).format(e)}catch(w){return h(w,`Currency formatter error for currency '${g}'`),`${g} ${e}`}}),c.forEach(e=>{e.format&&f.set(e.name,(i,a,l)=>e.format(i,a??"",l??s));});function P(e,i){if(!Object.prototype.hasOwnProperty.call(n,i))return;let a=n[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof l=="string"?l:void 0}function L(e,i,a){let l=o&&o!==a?[a,o]:[a],g=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let w of l){if(typeof g=="number"){let O=new Set;g===0&&O.add("zero"),O.add(K(w,g,r.pluralizationRules)),O.add("other");for(let $ of O){let v=P(`${e}.${$}`,w);if(v)return {message:v,messageLocale:w}}}let _=P(e,w);if(_)return {message:_,messageLocale:w}}}function N(e,i,a=s){try{let l="";if(i){let y=Object.keys(i);if(y.length>0)try{if(y.length===1){let b=y[0];l=`${b}:${JSON.stringify(i[b])}`;}else {let b=y.sort(),D={};for(let C of b)D[C]=i[C];l=JSON.stringify(D);}}catch{typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Failed to serialize params for caching, using fallback key"),l=y.sort().join(",");}}let g=`${a}:${e}:${l}`,w=d.get(g);if(w!==void 0)return w;let _=L(e,i,a);if(!_)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:O,messageLocale:$}=_,v=O;for(let y of c)if(y.transform)try{let b=y.transform(e,v,i||{},a,$);if(typeof b!="string"){h(new Error(`Plugin transform must return a string, got ${typeof b}`),`Plugin ${y.name} transform validation`);continue}v=b;}catch(b){h(b,`Plugin ${y.name} transform`);}let R=c.filter(y=>typeof y.escapeValue=="function");return v=V(v,i||{},f,s,R.length>0?y=>R.reduce((b,D)=>D.escapeValue(b),y):void 0),d.set(g,v),v}catch(l){return h(l,`Translation error for key ${e}`),e}}let x=(e,i)=>N(String(e),i);function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");n[e]||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(n).join(", ")}`),e!==s&&(s=e,d.clear(),m());}function I(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{n[e]||(n[e]={});let a=i;for(let l of c)if(l.beforeLoad)try{let g=l.beforeLoad(e,a);if(!g||typeof g!="object"||Array.isArray(g)){h(new Error(`Plugin beforeLoad must return an object, got ${typeof g}`),`Plugin ${l.name} beforeLoad validation`);continue}a=g;}catch(g){h(g,`Plugin ${l.name} beforeLoad`);}n[e]=M(n[e],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(e,n[e]);}catch(g){h(g,`Plugin ${l.name} afterLoad`);}d.clear(),(e===s||e===o)&&m();}catch(a){throw h(a,"Error adding messages"),a}}function U(e,i){let a=i||s;return P(String(e),a)!==void 0}function H(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&f.set(e.name,(a,l,g)=>e.format(a,l??"",g??s)),d.clear();}function q(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),f.delete(e),d.clear());}function J(e){return u.add(e),()=>u.delete(e)}function B(e,i){let a=f.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,s)}function G(e,i){let a=f.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,s)}function Q(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),g=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[w,_]of g)if(Math.abs(a)>=_)return l.format(Math.round(a/_),w);return l.format(0,"second")}return {get locale(){return s},get fallbackLocale(){return o},get messages(){return n},get revision(){return p},t:x,setLocale:T,getLocale:()=>s,hasTranslation:U,addMessages:I,addPlugin:H,removePlugin:q,subscribe:J,formatNumber:B,formatDate:G,formatRelativeTime:Q}}var E=class extends Error{},j=class{constructor(t){this.source=t;}cursor=0;parse(){return this.message(0,false).parts}take(t){t.lastIndex=this.cursor;let s=t.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(t){let s=this.take(t);if(s===void 0)throw new E;return s}space(){this.take(/\s+/y);}number(){let t=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(t))throw new E;return t}quote(){let t="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;t+=s;}return t}message(t,s){if(t>64)throw new E;let o=[],n="";function c(){n&&o.push(n),n="";}for(;this.cursor<this.source.length;){let u=this.source.charAt(this.cursor);if(u==="}"){if(t===0)throw new E;return this.cursor++,c(),{parts:o,closed:true}}if(u==="{"){let d=this.take(/\{\{[^{}]*\}\}/y);d!==void 0?n+=d:(c(),o.push(this.argument(t)));}else u==="'"&&this.take(/''/y)?n+="'":u==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?n+=this.quote():(this.cursor++,u==="#"&&s?(c(),o.push({kind:"number"})):n+=u);}return c(),{parts:o,closed:false}}argument(t){let s=this.cursor++;this.space();let o=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:o,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let n=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let c=n!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let u=new Map;for(;!this.take(/\}/y);){let d=n!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(t+1,n!=="select");if(!p.closed)throw new E;u.has(d)||u.set(d,p.parts),this.space();}if(!u.has("other"))throw new E;return {kind:n,name:o,choices:u,offset:c,source:this.source.slice(s,this.cursor)}}};function Z(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ee(r,t,s){let o=Z(s),n={maximumSignificantDigits:21},c,u,d;function p(m,h){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return h===void 0?"#":(d??=new Intl.NumberFormat(o,n)).format(h);if(!Object.hasOwn(t,f.name))return f.source;let P=t[f.name];if(f.kind==="value")return String(P);if(f.kind==="select"){let I=f.choices.get(String(P))??f.choices.get("other");return I?p(I):f.source}if(typeof P!="number"||!Number.isFinite(P))return f.source;let L=P-f.offset;if(!Number.isFinite(L))return f.source;let N=f.choices.get("="+P);if(N)return p(N,L);let x=f.kind==="plural"?c??=new Intl.PluralRules(o,n):u??=new Intl.PluralRules(o,{...n,type:"ordinal"}),T=f.choices.get(x.select(L))??f.choices.get("other");return T?p(T,L):f.source}).join("")}return p(r)}function z(){return {name:"icu",transform:(r,t,s,o,n)=>{if(!/[{']/.test(t))return t;try{return ee(new j(t).parse(),s,n??o)}catch(c){if(c instanceof E)return t;throw c}}}}function k(r){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,s=>t[s])}function re(r){let t=r.trim().toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:")||t.startsWith("vbscript:")||t.startsWith("file:")?"#":k(r)}function W(){return {name:"markdown",escapeValue:k,transform:(r,t,s,o)=>{let n=t,c=[],u=0;n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(d,p,m)=>{let h=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<a href="${re(m)}">${k(p)}</a>`,u++,h}),n=n.replace(/\*\*(.*?)\*\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<strong>${k(p)}</strong>`,u++,m}),n=n.replace(/\*(.*?)\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<em>${k(p)}</em>`,u++,m}),n=n.replace(/`(.*?)`/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<code>${k(p)}</code>`,u++,m}),n=k(n);for(let d=0;d<c.length;d++)n=n.replace(`__MARKDOWN_PLACEHOLDER_${d}__`,c[d]);return n}}}var le=W(),fe=z();export{F as createCache,Y as createI18n,M as deepMerge,te as defaultPluralRules,A as getNestedValue,K as getPluralForm,fe as icuPlugin,V as interpolate,le as markdownPlugin};//# sourceMappingURL=index.mjs.map
1
+ function S(r,n,o,t,s){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let d=l(g);return d===void 0?c:s?s(d):d})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),r}function l(c){try{let[g,d]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(d&&o?.has(d))try{let b=o.get(d);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${d}' must return a string, got ${typeof f}`),String(m)):f}catch(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${d}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function D(r,n){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return r;try{let o={...r};for(let t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let s=n[t];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Date)){let l=o[t];o[t]=D(l&&typeof l=="object"?l:{},s);}else o[t]=s;}return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function A(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),t=r;for(let s of o)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,s))t=t[s];else return;return t}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function V(r){let n=new Map,o=r?.maxSize??1e3;return {get:t=>{let s=n.get(t);return s!==void 0&&(n.delete(t),n.set(t,s)),s},set:(t,s)=>{if(n.has(t))n.delete(t);else if(n.size>=o){let l=n.keys().next().value;l!==void 0&&n.delete(l);}n.set(t,s);},clear:()=>n.clear(),size:()=>n.size}}var ae={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},R=new Map;function ee(r){let n=R.get(r);if(!n){try{let o=r.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(o).length>0?o:"en");}catch{n=new Intl.PluralRules("en");}R.set(r,n);}return n}function F(r,n,o){if(o){let t=r.split(/[-_]/)[0],s=Object.prototype.hasOwnProperty.call(o,r)?o[r]:Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0;if(typeof s=="function")return s(n)}return ee(r).select(n)}function re(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let n=Object.keys(r.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let o=e=>N(e).some(i=>Object.prototype.hasOwnProperty.call(r.messages,i));if(n&&!o(r.locale)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!o(r.locale)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!o(r.fallbackLocale)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let t=r.locale,s=r.fallbackLocale,l=structuredClone(r.messages),c=[...r.plugins||[]],g=new Set,d=V(),m=0,b=()=>{m++,g.forEach(e=>{try{e(t);}catch(i){f(i,"Locale change listener");}});},f=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},y=new Map;function E(e,i,a){if(!e)return;let u=h=>Object.prototype.hasOwnProperty.call(e,h)?e[h]:void 0;if(i&&u(i))return u(i);let p=(i||"").split(":").map(h=>h.trim());return p[0]===a&&p.shift(),u(p.join(":")||"default")}y.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let u=E(r.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,u).format(e)}),y.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let u=E(r.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,u).format(e)}),y.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let u=(i||"currency:USD").split(":"),p=u.length>1&&u[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:p}).format(e)}catch(h){return f(h,`Currency formatter error for currency '${p}'`),`${p} ${e}`}}),c.forEach(e=>{e.format&&y.set(e.name,(i,a,u)=>e.format(i,a??"",u??t));});function T(e,i){if(!Object.prototype.hasOwnProperty.call(l,i))return;let a=l[i];if(!a||typeof a!="object")return;let u=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof u=="string"?u:void 0}function j(e,i,a){let u=k(a),p=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of u){if(typeof p=="number"){let x=new Set;p===0&&x.add("zero"),x.add(F(h,p,r.pluralizationRules)),x.add("other");for(let $ of x){let w=T(`${e}.${$}`,h);if(w)return {message:w,messageLocale:h}}}let v=T(e,h);if(v)return {message:v,messageLocale:h}}}function k(e){return [...new Set([...N(e),...s?N(s):[]])]}function I(e,i,a=t){try{let u=i?te(i):"",p=u===void 0?void 0:`${a}:${e}:${u}`,h=p===void 0?void 0:d.get(p);if(h!==void 0)return h;let v=j(e,i,a);if(!v)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:x,messageLocale:$}=v,w=x;for(let O of c)if(O.transform)try{let L=O.transform(e,w,i||{},a,$);if(typeof L!="string"){f(new Error(`Plugin transform must return a string, got ${typeof L}`),`Plugin ${O.name} transform validation`);continue}w=L;}catch(L){f(L,`Plugin ${O.name} transform`);}let M=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,M.length>0?O=>M.reduce((L,Z)=>Z.escapeValue(L),O):void 0),p!==void 0&&d.set(p,w),w}catch(u){return f(u,`Translation error for key ${e}`),e}}let W=(e,i)=>I(String(e),i);function H(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");N(e).some(i=>Object.prototype.hasOwnProperty.call(l,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(l).join(", ")}`),e!==t&&(t=e,d.clear(),b());}function U(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{l[e]||(l[e]={});let a=i;for(let u of c)if(u.beforeLoad)try{let p=u.beforeLoad(e,a);if(!p||typeof p!="object"||Array.isArray(p)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof p}`),`Plugin ${u.name} beforeLoad validation`);continue}a=p;}catch(p){f(p,`Plugin ${u.name} beforeLoad`);}l[e]=D(l[e],a);for(let u of c)if(u.afterLoad)try{u.afterLoad(e,l[e]);}catch(p){f(p,`Plugin ${u.name} afterLoad`);}d.clear(),k(t).includes(e)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function q(e,i,a){let u=i||t;return (a?.exact?[u]:k(u)).some(h=>T(String(e),h)!==void 0)}function J(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&y.set(e.name,(a,u,p)=>e.format(a,u??"",p??t)),d.clear(),b();}function B(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),y.delete(e),d.clear(),b());}function G(e){return g.add(e),()=>g.delete(e)}function Q(e,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,t)}function X(e,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,t)}function Y(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),u=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),p=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[h,v]of p)if(Math.abs(a)>=v)return u.format(Math.round(a/v),h);return u.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return s},get messages(){return l},get revision(){return m},t:W,setLocale:H,getLocale:()=>t,hasTranslation:q,addMessages:U,addPlugin:J,removePlugin:B,subscribe:G,formatNumber:Q,formatDate:X,formatRelativeTime:Y}}function N(r){let n=[r],o=r;for(;;){let t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_"));if(t<=0)break;o=o.slice(0,t),t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_")),t>0&&o.length-t-1===1&&(o=o.slice(0,t)),n.push(o);}return n}function te(r){let n=[];for(let o of Object.keys(r).sort()){let t=r[o],s;if(typeof t=="string")s=JSON.stringify(t);else if(typeof t=="number")s=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)s=String(t);else if(t instanceof Date)s=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(o)}=${s}`);}return n.join(",")}var P=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let o=n.exec(this.source)?.[0];return o!==void 0&&(this.cursor+=o.length),o}expect(n){let o=this.take(n);if(o===void 0)throw new P;return o}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new P;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let o=this.source.charAt(this.cursor++);if(o==="'"&&!this.take(/'/y))break;n+=o;}return n}message(n,o){if(n>64)throw new P;let t=[],s="";function l(){s&&t.push(s),s="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new P;return this.cursor++,l(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?s+=g:(l(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?s+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||o&&this.source.charAt(this.cursor+1)==="#")?s+=this.quote():(this.cursor++,c==="#"&&o?(l(),t.push({kind:"number"})):s+=c);}return l(),{parts:t,closed:false}}argument(n){let o=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(o,this.cursor)};this.expect(/,/y),this.space();let s=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let l=s!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=s!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let d=this.message(n+1,s!=="select");if(!d.closed)throw new P;c.has(g)||c.set(g,d.parts),this.space();}if(!c.has("other"))throw new P;return {kind:s,name:t,choices:c,offset:l,source:this.source.slice(o,this.cursor)}}};function ne(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function oe(r,n,o){let t=ne(o),s={maximumSignificantDigits:21},l,c,g;function d(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,s)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return String(y);if(f.kind==="select"){let I=f.choices.get(String(y))??f.choices.get("other");return I?d(I):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let E=y-f.offset;if(!Number.isFinite(E))return f.source;let T=f.choices.get("="+y);if(T)return d(T,E);let j=f.kind==="plural"?l??=new Intl.PluralRules(t,s):c??=new Intl.PluralRules(t,{...s,type:"ordinal"}),k=f.choices.get(j.select(E))??f.choices.get("other");return k?d(k,E):f.source}).join("")}return d(r)}function K(){return {name:"icu",transform:(r,n,o,t,s)=>{if(!/[{']/.test(n))return n;try{return oe(new C(n).parse(),o,s??t)}catch(l){if(l instanceof P)return n;throw l}}}}function _(r){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,o=>n[o])}function se(r){let n=Array.from(r).filter(o=>o.charCodeAt(0)>32&&o.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":_(r)}function ie(r,n){return r.replace(/\{\{([^}]+)\}\}/g,(o,t)=>{let s=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,s))return o;let l=n[s];return l==null?"":String(l)})}function z(){return {name:"markdown",escapeValue:_,transform:(r,n,o,t)=>{let s=n,l=[],c=0;s=s.replace(/`(.*?)`/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<code>${_(d)}</code>`,c++,m}),s=s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,d,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=se(ie(m,o||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return l[c]=`<a href="${f}">${_(d)}</a>`,c++,b}),s=s.replace(/\*\*(.*?)\*\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<strong>${_(d)}</strong>`,c++,m}),s=s.replace(/\*(.*?)\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<em>${_(d)}</em>`,c++,m}),s=_(s);for(let g=l.length-1;g>=0;g--)s=s.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>l[g]);return s}}}var me=z(),he=K();export{V as createCache,re as createI18n,D as deepMerge,ae as defaultPluralRules,A as getNestedValue,F as getPluralForm,he as icuPlugin,S as interpolate,me as markdownPlugin};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","parts","currency","plugin","getMessage","localeMessages","resolveMessage","locales","candidate","forms","form","pluralMessage","message","translate","paramKeys","sortedKeys","sortedParams","k","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","name","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","part","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","createMarkdownPlugin","_params","_locale","placeholders","placeholderIndex","_","placeholder","i","markdownPlugin","icuPlugin"],"m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A,CAAI,WAAWX,CAAAA,CAAWC,CAAI,CAAC,CAAA,SAAA,CAAA,CAC5DU,CAAAA,EAAAA,CACOE,CACT,CAAC,CAAA,CAGD/H,EAASA,CAAAA,CAAO,OAAA,CAAQ,aAAc,CAAC8H,CAAAA,CAAGX,IAAS,CACjD,IAAMY,EAAc,CAAA,uBAAA,EAA0BF,CAAgB,KAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOX,EAAWC,CAAI,CAAC,QACxDU,CAAAA,EAAAA,CACOE,CACT,CAAC,CAAA,CAGD/H,CAAAA,CAASA,EAAO,OAAA,CAAQ,UAAA,CAAY,CAAC8H,CAAAA,CAAGX,CAAAA,GAAS,CAC/C,IAAMY,CAAAA,CAAc,0BAA0BF,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,EAAI,CAAA,MAAA,EAASX,CAAAA,CAAWC,CAAI,CAAC,CAAA,OAAA,CAAA,CAC1DU,IACOE,CACT,CAAC,EAGD/H,CAAAA,CAASkH,CAAAA,CAAWlH,CAAM,CAAA,CAG1B,IAAA,IAASgI,EAAI,CAAA,CAAGA,CAAAA,CAAIJ,EAAa,MAAA,CAAQI,CAAAA,EAAAA,CACvChI,EAASA,CAAAA,CAAO,OAAA,CAAQ,0BAA0BgI,CAAC,CAAA,EAAA,CAAA,CAAMJ,EAAaI,CAAC,CAAC,EAG1E,OAAOhI,CACT,CACF,CACF,KCxFaiI,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBlB,CAAAA","file":"index.mjs","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n // Validate that the current locale exists in messages, unless a fallback is provided or messages is empty\n if (hasMessages && !(config.locale in config.messages) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!(config.locale in config.messages) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !(config.fallbackLocale in config.messages)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n const locales = fallbackLocale && fallbackLocale !== locale ? [locale, fallbackLocale] : [locale];\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Generate cache key with deterministic param serialization\n // Sort keys to ensure consistent caching regardless of property order\n let paramKey = '';\n if (params) {\n const paramKeys = Object.keys(params);\n if (paramKeys.length > 0) {\n try {\n // Fast path for single parameter\n if (paramKeys.length === 1) {\n const key = paramKeys[0];\n paramKey = `${key}:${JSON.stringify(params[key])}`;\n } else {\n // Sort only when multiple parameters exist\n const sortedKeys = paramKeys.sort();\n const sortedParams: Record<string, unknown> = {};\n for (const k of sortedKeys) {\n sortedParams[k] = params[k];\n }\n paramKey = JSON.stringify(sortedParams);\n }\n } catch (stringifyError) {\n // Handle circular references or other JSON.stringify errors\n // Use a simpler key based on param keys only\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Failed to serialize params for caching, using fallback key');\n }\n paramKey = paramKeys.sort().join(',');\n }\n }\n }\n\n const cacheKey = `${locale}:${key}:${paramKey}`;\n const cached = translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if locale doesn't exist in messages\n if (!messages[locale]) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (locale === currentLocale || locale === fallbackLocale) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n const trimmed = href.trim().toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, _params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<a href=\"${sanitizeHref(href)}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // `code` -> <code>text</code>\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders\n for (let i = 0; i < placeholders.length; i++) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
1
+ {"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","i","markdownPlugin","icuPlugin"],"mappings":"AAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACK,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,EAAmBF,CAAG,CAAA,CAC1C,OAAIC,CAAAA,GAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,CAAAA,CAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,WAAa,YAAA,EAC9D,OAAA,CAAQ,MAAM,sCAAA,CAAwCA,CAAK,EAEtDT,CACT,CAEA,SAASQ,CAAAA,CAAmBF,CAAAA,CAAiC,CAC3D,GAAI,CACF,GAAM,CAACI,CAAAA,CAAUC,CAAM,EAAIL,CAAAA,CAAI,IAAA,EAAK,CAA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CACOJ,CACT,CAAC,CAAA,CAGDjI,EAASA,CAAAA,CAAO,OAAA,CAAQ,gBAAA,CAAkB,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACrD,IAAMO,CAAAA,CAAc,0BAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,QAAA,EAAWZ,CAAAA,CAAWC,CAAI,CAAC,CAAA,SAAA,CAAA,CAC5DW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASA,EAAO,OAAA,CAAQ,YAAA,CAAc,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACjD,IAAMO,CAAAA,CAAc,CAAA,uBAAA,EAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,EAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOZ,CAAAA,CAAWC,CAAI,CAAC,QACxDW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASyH,EAAWzH,CAAM,CAAA,CAK1B,IAAA,IAASyI,CAAAA,CAAIL,CAAAA,CAAa,MAAA,CAAS,EAAGK,CAAAA,EAAK,CAAA,CAAGA,IAC5CzI,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0ByI,CAAC,CAAA,EAAA,CAAA,CAAM,IAAML,CAAAA,CAAaK,CAAC,CAAC,CAAA,CAGhF,OAAOzI,CACT,CACF,CACF,KChHa0I,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBpB,CAAAA","file":"index.mjs","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate => Object.prototype.hasOwnProperty.call(config.messages, candidate));\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(table: Record<string, T> | undefined, format: string | undefined, type: string): T | undefined {\n if (!table) return undefined;\n const own = (name: string) => (Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined);\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n\n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = namedFormat(config.formats?.date, format, 'date') || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function lookupChain(locale: LocaleCode): LocaleCode[] {\n return [...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])])];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n if (cacheKey !== undefined) translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if neither the locale nor its base language exists in messages\n if (!localeChain(locale).some(candidate => Object.prototype.hasOwnProperty.call(messages, candidate))) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== undefined);\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n notify();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined) encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace => (brace === '{' ? '&#123;' : '&#125;'));\n placeholders[placeholderIndex] = `<a href=\"${url}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxog/i18n",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Modern, lightweight, and framework-agnostic internationalization library",
5
5
  "author": "Ersin Koç",
6
6
  "license": "MIT",