@oxog/i18n 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,242 +1,133 @@
1
1
  # @oxog/i18n
2
2
 
3
- A modern, lightweight, and framework-agnostic internationalization library with TypeScript support.
4
-
5
- ## Features
6
-
7
- - 🚀 **Lightweight**: Small bundle size with zero dependencies
8
- - 🔥 **Fast**: Optimized performance with memoization
9
- - 🌐 **Framework Agnostic**: Works with any JavaScript framework
10
- - 📦 **TypeScript First**: Full TypeScript support with type safety
11
- - 🔌 **Extensible**: Plugin system for custom functionality
12
- - 🎯 **Simple API**: Easy to learn and use
13
- - 💾 **Flexible Storage**: Support for multiple locale loading strategies
3
+ A small, dependency-free and framework-agnostic internationalization library with
4
+ TypeScript key checking, CLDR plural rules, fallback locales and an optional ICU
5
+ MessageFormat plugin.
14
6
 
15
7
  ## Installation
16
8
 
17
9
  ```bash
18
10
  npm install @oxog/i18n
19
- # or
20
- pnpm add @oxog/i18n
21
- # or
22
- yarn add @oxog/i18n
23
11
  ```
24
12
 
25
- ## Quick Start
13
+ Ships ESM and CommonJS builds with matching type declarations. Node.js 18+ and modern
14
+ browsers (it relies on `Intl.PluralRules`, `Intl.NumberFormat` and `structuredClone`).
26
15
 
27
- ```typescript
16
+ ## Quick start
17
+
18
+ ```ts
28
19
  import { createI18n } from '@oxog/i18n';
29
20
 
30
- // Create i18n instance
31
21
  const i18n = createI18n({
32
22
  locale: 'en',
33
23
  fallbackLocale: 'en',
34
24
  messages: {
35
- en: {
36
- greeting: 'Hello, {name}!',
37
- messages: {
38
- welcome: 'Welcome to our app'
39
- }
40
- },
41
- es: {
42
- greeting: '¡Hola, {name}!',
43
- messages: {
44
- welcome: 'Bienvenido a nuestra aplicación'
45
- }
46
- }
47
- }
25
+ en: { greeting: 'Hello, {{name}}!', messages: { welcome: 'Welcome to our app' } },
26
+ es: { greeting: '¡Hola, {{name}}!', messages: { welcome: 'Bienvenido a nuestra aplicación' } },
27
+ },
48
28
  });
49
29
 
50
- // Use translations
51
- console.log(i18n.t('greeting', { name: 'World' })); // Hello, World!
52
- console.log(i18n.t('messages.welcome')); // Welcome to our app
30
+ i18n.t('greeting', { name: 'World' }); // "Hello, World!"
31
+ i18n.t('messages.welcome'); // "Welcome to our app"
53
32
 
54
- // Change locale
55
33
  i18n.setLocale('es');
56
- console.log(i18n.t('greeting', { name: 'Mundo' })); // ¡Hola, Mundo!
34
+ i18n.t('greeting', { name: 'Mundo' }); // "¡Hola, Mundo!"
57
35
  ```
58
36
 
59
- ## API Reference
60
-
61
- ### `createI18n(options)`
62
-
63
- Creates a new i18n instance.
64
-
65
- #### Options
66
-
67
- - `locale`: Current locale (default: 'en')
68
- - `fallbackLocale`: Fallback locale when translation is missing
69
- - `messages`: Translation messages object
70
- - `plugins`: Array of plugins to use
71
- - `interpolation`: Custom interpolation options
72
- - `missing`: Custom missing translation handler
37
+ ## Options
73
38
 
74
- ### Instance Methods
39
+ | Option | Description |
40
+ | --- | --- |
41
+ | `locale` | Active locale (required). |
42
+ | `fallbackLocale` | Catalog used when a key is missing in the active locale. |
43
+ | `messages` | `{ [locale]: catalog }`; catalogs may nest objects (`user.profile.title`). |
44
+ | `plugins` | Plugins such as `icuPlugin` or `markdownPlugin`. |
45
+ | `pluralizationRules` | Custom rules per locale or language, e.g. `{ ar: count => ... }`. |
46
+ | `formats` | Named `Intl.NumberFormat` / `Intl.DateTimeFormat` options (`{{value:number}}`). |
47
+ | `warnOnMissingTranslations` | Log missing keys outside production. |
48
+ | `onError` | Called with errors from plugins, formatters and listeners. |
75
49
 
76
- #### `t(key, params?, options?)`
50
+ A missing key returns the key itself. Lookups only use own string values: nested groups,
51
+ `constructor`, `toString` and other `Object.prototype` members are never returned as
52
+ translations, and `__proto__` keys in loaded JSON cannot modify `Object.prototype`.
77
53
 
78
- Get a translation for the given key.
79
-
80
- ```typescript
81
- i18n.t('greeting', { name: 'Alice' });
82
- i18n.t('user.profile.title');
83
- ```
84
-
85
- #### `setLocale(locale)`
86
-
87
- Change the current locale.
88
-
89
- ```typescript
90
- i18n.setLocale('fr');
91
- ```
54
+ ## Interpolation
92
55
 
93
- #### `getLocale()`
56
+ `{{name}}` placeholders are replaced with the matching parameter; unknown placeholders are
57
+ left as they are. `t()` returns plain text and does not escape HTML: render it as text (React
58
+ does) or escape it before inserting it as HTML.
94
59
 
95
- Get the current locale.
96
-
97
- ```typescript
98
- const currentLocale = i18n.getLocale(); // 'en'
99
- ```
100
-
101
- #### `hasTranslation(key, locale?)`
102
-
103
- Check if a translation exists.
104
-
105
- ```typescript
106
- if (i18n.hasTranslation('feature.title')) {
107
- // Translation exists
108
- }
109
- ```
110
-
111
- #### `addMessages(locale, messages)`
112
-
113
- Add translations for a locale.
114
-
115
- ```typescript
116
- i18n.addMessages('de', {
117
- greeting: 'Hallo, {name}!'
118
- });
119
- ```
60
+ ## Pluralization
120
61
 
121
- ## Advanced Features
122
-
123
- ### Interpolation
124
-
125
- ```typescript
126
- // Basic interpolation
127
- i18n.t('greeting', { name: 'World' }); // Hello, World!
128
-
129
- // Custom interpolation pattern
130
- const i18n = createI18n({
131
- interpolation: {
132
- prefix: '{{',
133
- suffix: '}}'
134
- }
135
- });
136
- ```
137
-
138
- ### Pluralization
139
-
140
- ```typescript
141
- const messages = {
142
- items: {
143
- zero: 'No items',
144
- one: 'One item',
145
- other: '{count} items'
146
- }
147
- };
148
-
149
- i18n.t('items', { count: 0 }); // No items
150
- i18n.t('items', { count: 1 }); // One item
151
- i18n.t('items', { count: 5 }); // 5 items
152
- ```
153
-
154
- ### Plugins
155
-
156
- ```typescript
157
- import { createI18n, ICUPlugin } from '@oxog/i18n';
62
+ Pass `count` and group the forms under the key. Categories follow the CLDR rules of the
63
+ catalog's language via `Intl.PluralRules` (`zero`, `one`, `two`, `few`, `many`, `other`), so
64
+ Russian, Polish, Arabic, Welsh and every other language select the right form. An explicit
65
+ `zero` form is used for `count: 0` when present, and `other` is the last resort.
158
66
 
67
+ ```ts
159
68
  const i18n = createI18n({
160
- plugins: [ICUPlugin()],
69
+ locale: 'ru',
161
70
  messages: {
162
- en: {
163
- greeting: 'Hello, {name}! You have {count, plural, =0 {no messages} =1 {one message} other {# messages}}.'
164
- }
165
- }
71
+ ru: { apples: { one: '{{count}} яблоко', few: '{{count}} яблока', many: '{{count}} яблок', other: '{{count}} яблока' } },
72
+ },
166
73
  });
74
+ i18n.t('apples', { count: 21 }); // "21 яблоко"
75
+ i18n.t('apples', { count: 5 }); // "5 яблок"
167
76
  ```
168
77
 
169
- ### Missing Translations
78
+ When the text comes from the fallback catalog, the fallback language's rules are used.
170
79
 
171
- ```typescript
172
- const i18n = createI18n({
173
- missing: (key, locale) => {
174
- console.warn(`Missing translation: ${key} for locale: ${locale}`);
175
- return key; // Return the key as fallback
176
- }
177
- });
178
- ```
80
+ ## ICU MessageFormat plugin
179
81
 
180
- ## TypeScript Support
82
+ ```ts
83
+ import { createI18n, icuPlugin } from '@oxog/i18n';
181
84
 
182
- ```typescript
183
- // Define your message schema
184
- type MessageSchema = {
185
- greeting: string;
186
- user: {
187
- profile: {
188
- title: string;
189
- description: string;
190
- };
191
- };
192
- };
193
-
194
- // Create typed i18n instance
195
- const i18n = createI18n<MessageSchema>({
85
+ const i18n = createI18n({
196
86
  locale: 'en',
87
+ plugins: [icuPlugin],
197
88
  messages: {
198
- en: {
199
- greeting: 'Hello!',
200
- user: {
201
- profile: {
202
- title: 'Profile',
203
- description: 'User profile page'
204
- }
205
- }
206
- }
207
- }
89
+ en: { inbox: 'Hello, {name}! You have {count, plural, =0 {no messages} one {# message} other {# messages}}.' },
90
+ },
208
91
  });
209
92
 
210
- // Now you get full type safety
211
- i18n.t('greeting'); // ✅ Valid
212
- i18n.t('user.profile.title'); // ✅ Valid
213
- i18n.t('invalid.key'); // ❌ TypeScript error
93
+ i18n.t('inbox', { name: 'Ada', count: 2 }); // "Hello, Ada! You have 2 messages."
214
94
  ```
215
95
 
216
- ## Performance
96
+ Supports named arguments, `plural`/`selectordinal` with exact selectors and `offset`, and
97
+ nested `select`. `{{name}}` interpolation keeps working.
217
98
 
218
- The library is optimized for performance with:
99
+ ## Instance API
219
100
 
220
- - Memoization of translation lookups
221
- - Efficient message traversal
222
- - Minimal bundle size
223
- - No runtime dependencies
101
+ - `t(key, params?)` – translate.
102
+ - `setLocale(locale)`, `getLocale()`, `locale`, `fallbackLocale`.
103
+ - `hasTranslation(key, locale?)` – whether a string exists for the key.
104
+ - `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
107
+ such change.
108
+ - `addPlugin(plugin)`, `removePlugin(name)`.
109
+ - `formatNumber(value, format?)`, `formatDate(date, format?)`, `formatRelativeTime(date, base?)`.
224
110
 
225
- ## Browser Support
111
+ ## TypeScript
226
112
 
227
- - Modern browsers (Chrome, Firefox, Safari, Edge)
228
- - Node.js 18+
113
+ Catalog types may be inferred, declared as `type`s or plain `interface`s, and nested:
229
114
 
230
- ## License
115
+ ```ts
116
+ interface MessageSchema {
117
+ greeting: string;
118
+ user: { profile: { title: string; description: string } };
119
+ }
231
120
 
232
- MIT © Ersin Koç
121
+ const i18n = createI18n<MessageSchema>({ locale: 'en', messages: { en: { /* ... */ } as MessageSchema } });
233
122
 
234
- ## Contributing
123
+ i18n.t('greeting'); // ✅
124
+ i18n.t('user.profile.title'); // ✅
125
+ i18n.t('invalid.key'); // ❌ type error
126
+ ```
235
127
 
236
- Contributions are welcome! Please read our [Contributing Guide](https://github.com/ersinkoc/i18n/blob/main/CONTRIBUTING.md) for details.
128
+ With `as const` catalogs, placeholders become required parameters
129
+ (`'Hi {{name}}'` requires `{ name }`, `{{n:number}}` requires a number).
237
130
 
238
- ## Links
131
+ ## License
239
132
 
240
- - [GitHub Repository](https://github.com/ersinkoc/i18n)
241
- - [NPM Package](https://www.npmjs.com/package/@oxog/i18n)
242
- - [Documentation](https://github.com/ersinkoc/i18n#readme)
133
+ MIT © Ersin Koç
package/dist/index.d.mts CHANGED
@@ -5,65 +5,137 @@ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ?
5
5
  [K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
6
6
  } & ParseKeys<Rest> : {
7
7
  [K in Param]: TranslationValue;
8
- } & ParseKeys<Rest> : {};
9
- type TranslationFunction<TMessages extends Messages> = <TKey extends keyof TMessages, TParams extends ParseKeys<TMessages[TKey]>>(key: TKey, ...args: keyof TParams extends never ? [] : [params: TParams]) => string;
10
- type Messages = Record<string, string>;
11
- type LocaleMessages<TMessages extends Messages = Messages> = Record<LocaleCode, TMessages>;
12
- interface I18nPlugin<TMessages extends Messages = Messages> {
8
+ } & ParseKeys<Rest> : object;
9
+ /**
10
+ * Shape of a translation catalog: string messages, optionally grouped in nested objects
11
+ * (`{ user: { profile: { title: '...' } } }`) or plural groups (`{ items: { one, other } }`).
12
+ */
13
+ interface MessageTree {
14
+ [key: string]: string | MessageTree;
15
+ }
16
+ /**
17
+ * Default (untyped) message catalog type. Typed catalogs may be any object type,
18
+ * including plain `interface`s without an index signature.
19
+ */
20
+ type Messages = MessageTree;
21
+ type PrevDepth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
22
+ type JoinKey<K extends string, P> = P extends string ? `${K}.${P}` : never;
23
+ /**
24
+ * Dotted translation keys of a catalog: leaf keys (`'user.profile.title'`) and the keys
25
+ * of nested groups (`'items'`, used for plural groups such as `{ items: { one, other } }`).
26
+ * Catalogs with a string index signature accept any string key.
27
+ */
28
+ type TranslationKey<T, Depth extends number = 8> = [Depth] extends [never] ? never : T extends string ? never : string extends keyof T ? string : {
29
+ [K in keyof T & string]: NonNullable<T[K]> extends string ? K : NonNullable<T[K]> extends object ? K | JoinKey<K, TranslationKey<NonNullable<T[K]>, PrevDepth[Depth]>> : never;
30
+ }[keyof T & string];
31
+ /** Type of the catalog entry at a dotted key. */
32
+ type TranslationValueAt<T, P extends string> = P extends keyof T ? T[P] : P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? TranslationValueAt<NonNullable<T[Head]>, Rest> : unknown : unknown;
33
+ type TranslationArgs<V> = V extends string ? keyof ParseKeys<V> extends never ? [params?: TranslationParams] : [params: ParseKeys<V> & TranslationParams] : [params?: TranslationParams];
34
+ type TranslationFunction<TMessages extends object = Messages> = <TKey extends TranslationKey<TMessages>>(key: TKey, ...args: TranslationArgs<TranslationValueAt<TMessages, TKey>>) => string;
35
+ type LocaleMessages<TMessages extends object = Messages> = Record<LocaleCode, TMessages>;
36
+ /** Recursive `Partial`, used for incremental catalogs passed to `addMessages`. */
37
+ type DeepPartial<T> = T extends string ? T : {
38
+ [K in keyof T]?: DeepPartial<T[K]>;
39
+ };
40
+ interface I18nPlugin<TMessages extends object = Messages> {
13
41
  name: string;
14
- transform?: (key: keyof TMessages, value: string, params: TranslationParams, locale: LocaleCode) => string;
42
+ /** The optional message locale identifies the catalog that supplied the text after fallback. */
43
+ transform?: (key: string, value: string, params: TranslationParams, locale: LocaleCode, messageLocale?: LocaleCode) => string;
15
44
  beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
16
45
  afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
17
46
  format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
47
+ /**
48
+ * Escapes every value inserted by `{{placeholder}}` interpolation. Plugins whose
49
+ * `transform` produces HTML (such as `markdownPlugin`) set it so parameters cannot inject
50
+ * markup into that HTML.
51
+ */
52
+ escapeValue?: (value: string) => string;
18
53
  }
19
- interface I18nConfig<TMessages extends Messages = Messages> {
54
+ interface I18nConfig<TMessages extends object = Messages> {
20
55
  locale: LocaleCode;
21
56
  fallbackLocale?: LocaleCode;
22
57
  messages: LocaleMessages<TMessages>;
23
58
  plugins?: I18nPlugin<TMessages>[];
24
59
  warnOnMissingTranslations?: boolean;
60
+ /**
61
+ * Custom plural rules keyed by locale or language (`'pt-BR'` or `'pt'`). They take
62
+ * precedence over the built-in CLDR rules (`Intl.PluralRules`) for those locales only.
63
+ */
25
64
  pluralizationRules?: Record<LocaleCode, (count: number) => string>;
26
65
  formats?: {
27
66
  number?: Record<string, Intl.NumberFormatOptions>;
28
67
  date?: Record<string, Intl.DateTimeFormatOptions>;
29
68
  };
69
+ onError?: (error: Error, context: string) => void;
30
70
  }
31
- interface I18nInstance<TMessages extends Messages = Messages> {
71
+ interface I18nInstance<TMessages extends object = Messages> {
32
72
  readonly locale: LocaleCode;
33
73
  readonly fallbackLocale?: LocaleCode;
34
74
  readonly messages: LocaleMessages<TMessages>;
35
75
  readonly t: TranslationFunction<TMessages>;
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.
79
+ */
80
+ readonly revision?: number;
36
81
  setLocale(locale: LocaleCode): void;
37
82
  getLocale(): LocaleCode;
38
- hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean;
39
- addMessages(locale: LocaleCode, messages: Partial<TMessages>): void;
83
+ hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
84
+ addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
40
85
  addPlugin(plugin: I18nPlugin<TMessages>): void;
41
86
  removePlugin(pluginName: string): void;
42
87
  formatNumber(value: number, format?: string): string;
43
88
  formatDate(value: Date, format?: string): string;
44
89
  formatRelativeTime(value: Date, baseDate?: Date): string;
90
+ /**
91
+ * 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.
93
+ */
45
94
  subscribe(listener: (locale: LocaleCode) => void): () => void;
46
95
  }
47
- type ExtractTranslationKeys<T> = T extends Messages ? keyof T : never;
48
- type ExtractTranslationParams<TMessages extends Messages, TKey extends keyof TMessages> = TMessages[TKey] extends string ? ParseKeys<TMessages[TKey]> : never;
96
+ type ExtractTranslationKeys<T> = TranslationKey<T>;
97
+ type ExtractTranslationParams<TMessages extends object, TKey extends string> = TranslationValueAt<TMessages, TKey> extends infer V ? V extends string ? ParseKeys<V> & TranslationParams : TranslationParams : TranslationParams;
49
98
 
50
- declare function createI18n<TMessages extends Messages = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
99
+ declare function createI18n<TMessages extends object = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
51
100
 
52
- declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string): string;
53
- declare function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
54
- declare function getNestedValue<T>(obj: Record<string, any>, path: string): T | undefined;
55
- declare function createCache<T>(): {
101
+ /**
102
+ * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given
103
+ * (e.g. by a plugin that produces HTML), every inserted value is passed through it.
104
+ */
105
+ declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string, escape?: (value: string) => string): string;
106
+ declare function deepMerge<T extends object>(target: T, source: Partial<T>): T;
107
+ declare function getNestedValue<T>(obj: Record<string, unknown>, path: string): T | undefined;
108
+ interface CacheOptions {
109
+ maxSize?: number;
110
+ }
111
+ declare function createCache<T>(options?: CacheOptions): {
56
112
  get: (key: string) => T | undefined;
57
113
  set: (key: string, value: T) => void;
58
114
  clear: () => void;
115
+ size: () => number;
59
116
  };
117
+ /**
118
+ * @deprecated Kept for backwards compatibility. Plural categories are now resolved with
119
+ * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no
120
+ * longer used by `getPluralForm` or `createI18n`.
121
+ */
60
122
  declare const defaultPluralRules: Record<string, (count: number) => string>;
123
+ /**
124
+ * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)
125
+ * for `count` in `locale`.
126
+ *
127
+ * Custom rules are looked up by the exact locale first and then by its language
128
+ * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
129
+ */
61
130
  declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
62
131
 
63
132
  /**
64
- * Markdown plugin for basic markdown syntax transformation
133
+ * Markdown plugin for basic markdown syntax transformation.
65
134
  */
66
135
  declare const markdownPlugin: I18nPlugin;
136
+ /**
137
+ * ICU MessageFormat plugin for named arguments, plural forms and select branches.
138
+ */
67
139
  declare const icuPlugin: I18nPlugin;
68
140
 
69
- export { type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type Messages, type ParseKeys, type TranslationFunction, type TranslationParams, type TranslationValue, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
141
+ export { type CacheOptions, type DeepPartial, type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type MessageTree, type Messages, type ParseKeys, type TranslationFunction, type TranslationKey, type TranslationParams, type TranslationValue, type TranslationValueAt, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
package/dist/index.d.ts CHANGED
@@ -5,65 +5,137 @@ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ?
5
5
  [K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
6
6
  } & ParseKeys<Rest> : {
7
7
  [K in Param]: TranslationValue;
8
- } & ParseKeys<Rest> : {};
9
- type TranslationFunction<TMessages extends Messages> = <TKey extends keyof TMessages, TParams extends ParseKeys<TMessages[TKey]>>(key: TKey, ...args: keyof TParams extends never ? [] : [params: TParams]) => string;
10
- type Messages = Record<string, string>;
11
- type LocaleMessages<TMessages extends Messages = Messages> = Record<LocaleCode, TMessages>;
12
- interface I18nPlugin<TMessages extends Messages = Messages> {
8
+ } & ParseKeys<Rest> : object;
9
+ /**
10
+ * Shape of a translation catalog: string messages, optionally grouped in nested objects
11
+ * (`{ user: { profile: { title: '...' } } }`) or plural groups (`{ items: { one, other } }`).
12
+ */
13
+ interface MessageTree {
14
+ [key: string]: string | MessageTree;
15
+ }
16
+ /**
17
+ * Default (untyped) message catalog type. Typed catalogs may be any object type,
18
+ * including plain `interface`s without an index signature.
19
+ */
20
+ type Messages = MessageTree;
21
+ type PrevDepth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
22
+ type JoinKey<K extends string, P> = P extends string ? `${K}.${P}` : never;
23
+ /**
24
+ * Dotted translation keys of a catalog: leaf keys (`'user.profile.title'`) and the keys
25
+ * of nested groups (`'items'`, used for plural groups such as `{ items: { one, other } }`).
26
+ * Catalogs with a string index signature accept any string key.
27
+ */
28
+ type TranslationKey<T, Depth extends number = 8> = [Depth] extends [never] ? never : T extends string ? never : string extends keyof T ? string : {
29
+ [K in keyof T & string]: NonNullable<T[K]> extends string ? K : NonNullable<T[K]> extends object ? K | JoinKey<K, TranslationKey<NonNullable<T[K]>, PrevDepth[Depth]>> : never;
30
+ }[keyof T & string];
31
+ /** Type of the catalog entry at a dotted key. */
32
+ type TranslationValueAt<T, P extends string> = P extends keyof T ? T[P] : P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? TranslationValueAt<NonNullable<T[Head]>, Rest> : unknown : unknown;
33
+ type TranslationArgs<V> = V extends string ? keyof ParseKeys<V> extends never ? [params?: TranslationParams] : [params: ParseKeys<V> & TranslationParams] : [params?: TranslationParams];
34
+ type TranslationFunction<TMessages extends object = Messages> = <TKey extends TranslationKey<TMessages>>(key: TKey, ...args: TranslationArgs<TranslationValueAt<TMessages, TKey>>) => string;
35
+ type LocaleMessages<TMessages extends object = Messages> = Record<LocaleCode, TMessages>;
36
+ /** Recursive `Partial`, used for incremental catalogs passed to `addMessages`. */
37
+ type DeepPartial<T> = T extends string ? T : {
38
+ [K in keyof T]?: DeepPartial<T[K]>;
39
+ };
40
+ interface I18nPlugin<TMessages extends object = Messages> {
13
41
  name: string;
14
- transform?: (key: keyof TMessages, value: string, params: TranslationParams, locale: LocaleCode) => string;
42
+ /** The optional message locale identifies the catalog that supplied the text after fallback. */
43
+ transform?: (key: string, value: string, params: TranslationParams, locale: LocaleCode, messageLocale?: LocaleCode) => string;
15
44
  beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
16
45
  afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
17
46
  format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
47
+ /**
48
+ * Escapes every value inserted by `{{placeholder}}` interpolation. Plugins whose
49
+ * `transform` produces HTML (such as `markdownPlugin`) set it so parameters cannot inject
50
+ * markup into that HTML.
51
+ */
52
+ escapeValue?: (value: string) => string;
18
53
  }
19
- interface I18nConfig<TMessages extends Messages = Messages> {
54
+ interface I18nConfig<TMessages extends object = Messages> {
20
55
  locale: LocaleCode;
21
56
  fallbackLocale?: LocaleCode;
22
57
  messages: LocaleMessages<TMessages>;
23
58
  plugins?: I18nPlugin<TMessages>[];
24
59
  warnOnMissingTranslations?: boolean;
60
+ /**
61
+ * Custom plural rules keyed by locale or language (`'pt-BR'` or `'pt'`). They take
62
+ * precedence over the built-in CLDR rules (`Intl.PluralRules`) for those locales only.
63
+ */
25
64
  pluralizationRules?: Record<LocaleCode, (count: number) => string>;
26
65
  formats?: {
27
66
  number?: Record<string, Intl.NumberFormatOptions>;
28
67
  date?: Record<string, Intl.DateTimeFormatOptions>;
29
68
  };
69
+ onError?: (error: Error, context: string) => void;
30
70
  }
31
- interface I18nInstance<TMessages extends Messages = Messages> {
71
+ interface I18nInstance<TMessages extends object = Messages> {
32
72
  readonly locale: LocaleCode;
33
73
  readonly fallbackLocale?: LocaleCode;
34
74
  readonly messages: LocaleMessages<TMessages>;
35
75
  readonly t: TranslationFunction<TMessages>;
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.
79
+ */
80
+ readonly revision?: number;
36
81
  setLocale(locale: LocaleCode): void;
37
82
  getLocale(): LocaleCode;
38
- hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean;
39
- addMessages(locale: LocaleCode, messages: Partial<TMessages>): void;
83
+ hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
84
+ addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
40
85
  addPlugin(plugin: I18nPlugin<TMessages>): void;
41
86
  removePlugin(pluginName: string): void;
42
87
  formatNumber(value: number, format?: string): string;
43
88
  formatDate(value: Date, format?: string): string;
44
89
  formatRelativeTime(value: Date, baseDate?: Date): string;
90
+ /**
91
+ * 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.
93
+ */
45
94
  subscribe(listener: (locale: LocaleCode) => void): () => void;
46
95
  }
47
- type ExtractTranslationKeys<T> = T extends Messages ? keyof T : never;
48
- type ExtractTranslationParams<TMessages extends Messages, TKey extends keyof TMessages> = TMessages[TKey] extends string ? ParseKeys<TMessages[TKey]> : never;
96
+ type ExtractTranslationKeys<T> = TranslationKey<T>;
97
+ type ExtractTranslationParams<TMessages extends object, TKey extends string> = TranslationValueAt<TMessages, TKey> extends infer V ? V extends string ? ParseKeys<V> & TranslationParams : TranslationParams : TranslationParams;
49
98
 
50
- declare function createI18n<TMessages extends Messages = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
99
+ declare function createI18n<TMessages extends object = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
51
100
 
52
- declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string): string;
53
- declare function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
54
- declare function getNestedValue<T>(obj: Record<string, any>, path: string): T | undefined;
55
- declare function createCache<T>(): {
101
+ /**
102
+ * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given
103
+ * (e.g. by a plugin that produces HTML), every inserted value is passed through it.
104
+ */
105
+ declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string, escape?: (value: string) => string): string;
106
+ declare function deepMerge<T extends object>(target: T, source: Partial<T>): T;
107
+ declare function getNestedValue<T>(obj: Record<string, unknown>, path: string): T | undefined;
108
+ interface CacheOptions {
109
+ maxSize?: number;
110
+ }
111
+ declare function createCache<T>(options?: CacheOptions): {
56
112
  get: (key: string) => T | undefined;
57
113
  set: (key: string, value: T) => void;
58
114
  clear: () => void;
115
+ size: () => number;
59
116
  };
117
+ /**
118
+ * @deprecated Kept for backwards compatibility. Plural categories are now resolved with
119
+ * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no
120
+ * longer used by `getPluralForm` or `createI18n`.
121
+ */
60
122
  declare const defaultPluralRules: Record<string, (count: number) => string>;
123
+ /**
124
+ * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)
125
+ * for `count` in `locale`.
126
+ *
127
+ * Custom rules are looked up by the exact locale first and then by its language
128
+ * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
129
+ */
61
130
  declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
62
131
 
63
132
  /**
64
- * Markdown plugin for basic markdown syntax transformation
133
+ * Markdown plugin for basic markdown syntax transformation.
65
134
  */
66
135
  declare const markdownPlugin: I18nPlugin;
136
+ /**
137
+ * ICU MessageFormat plugin for named arguments, plural forms and select branches.
138
+ */
67
139
  declare const icuPlugin: I18nPlugin;
68
140
 
69
- export { type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type Messages, type ParseKeys, type TranslationFunction, type TranslationParams, type TranslationValue, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
141
+ export { type CacheOptions, type DeepPartial, type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type MessageTree, type Messages, type ParseKeys, type TranslationFunction, type TranslationKey, type TranslationParams, type TranslationValue, type TranslationValueAt, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };