@intlayer/i18next 9.9.1 → 9.9.3-canary.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.
@@ -1,4 +1,4 @@
1
- import { getInterpolationValues, resolveTranslation } from "./resolveTranslation.mjs";
1
+ import { getInterpolationValues, resolveTranslation, toNamespaceList } from "./resolveTranslation.mjs";
2
2
  import { internationalization, log } from "@intlayer/config/built";
3
3
  import { getIntlayer } from "@intlayer/core/interpreter";
4
4
  import { navigatePath, resolveMessageNodeToString } from "@intlayer/core/messageFormat";
@@ -7,14 +7,29 @@ import { colorize, getAppLogger } from "@intlayer/config/logger";
7
7
  import { getHTMLTextDir } from "@intlayer/core/localization";
8
8
 
9
9
  // src/createInstance.ts
10
+ /** i18next's namespace when neither `defaultNS` nor `ns` is configured. */
11
+ const DEFAULT_NAMESPACE = "translation";
12
+ /**
13
+ * Fills `defaultNS` from `ns` the way i18next's `init()` does: a string `ns`
14
+ * becomes the default, an array gives its first entry unless it lists
15
+ * `translation`.
16
+ */
17
+ const withDerivedDefaultNamespace = (options) => {
18
+ if (options.defaultNS !== void 0 && options.defaultNS !== null || !options.ns || Array.isArray(options.ns) && options.ns.includes(DEFAULT_NAMESPACE)) return options;
19
+ return {
20
+ ...options,
21
+ defaultNS: toNamespaceList(options.ns)[0]
22
+ };
23
+ };
10
24
  const warnIgnoredResources = (location) => {
11
25
  getAppLogger({ log })(`${colorize(location, ANSIColors.CYAN)}: the ${colorize("`resources`", ANSIColors.CYAN)} option is ignored when using ${colorize("@intlayer/i18next", ANSIColors.MAGENTA)} — translations are served from the compiled intlayer dictionaries instead. Remove the resource imports and the ${colorize("`resources`", ANSIColors.CYAN)} option to reduce your bundle size.`);
12
26
  };
13
27
  const createInstance = (instanceOptions = {}) => {
14
28
  if (instanceOptions.resources !== void 0) warnIgnoredResources("createInstance");
15
29
  const config = internationalization;
16
- let currentLanguage = instanceOptions.lng ?? config?.defaultLocale ?? "en";
17
- let defaultNS = instanceOptions.defaultNS ?? (Array.isArray(instanceOptions.ns) ? instanceOptions.ns[0] : instanceOptions.ns) ?? "translation";
30
+ /** `createInstance` options, with every later `init()` merged in. */
31
+ const currentOptions = withDerivedDefaultNamespace({ ...instanceOptions });
32
+ let currentLanguage = currentOptions.lng ?? config?.defaultLocale ?? "en";
18
33
  const listeners = /* @__PURE__ */ new Map();
19
34
  let initialized = false;
20
35
  const emit = (event, ...args) => {
@@ -22,9 +37,28 @@ const createInstance = (instanceOptions = {}) => {
22
37
  h(...args);
23
38
  });
24
39
  };
25
- const getSeparators = () => ({
26
- keySeparator: instanceOptions.keySeparator ?? ".",
27
- nsSeparator: instanceOptions.nsSeparator ?? ":"
40
+ /** Configured default namespaces as written, else i18next's `translation`. */
41
+ const getDefaultNamespaces = () => {
42
+ const { defaultNS } = currentOptions;
43
+ if (typeof defaultNS === "string" && defaultNS !== "") return defaultNS;
44
+ if (Array.isArray(defaultNS) && defaultNS.length > 0) return defaultNS;
45
+ return DEFAULT_NAMESPACE;
46
+ };
47
+ /** Whether interpolated values are HTML-escaped (i18next default: on). */
48
+ const getEscapeValue = () => currentOptions.interpolation?.escapeValue ?? true;
49
+ /**
50
+ * `resolveTranslation` params for one lookup, with the instance settings
51
+ * read as written so no option list is copied on the `t()` hot path.
52
+ */
53
+ const getResolveParams = (language, namespace, key, options) => ({
54
+ locale: language,
55
+ namespace,
56
+ key,
57
+ options,
58
+ keySeparator: currentOptions.keySeparator ?? ".",
59
+ nsSeparator: currentOptions.nsSeparator ?? ":",
60
+ fallbackNamespaces: currentOptions.fallbackNS,
61
+ escapeValue: getEscapeValue()
28
62
  });
29
63
  /**
30
64
  * Resolves a key through the full i18next pipeline (namespace prefix,
@@ -33,16 +67,10 @@ const createInstance = (instanceOptions = {}) => {
33
67
  */
34
68
  const resolveKey = (lang, ns, key, opts) => {
35
69
  const options = typeof opts === "string" ? { defaultValue: opts } : opts;
36
- const resolved = resolveTranslation({
37
- locale: lang,
38
- namespace: ns,
39
- key,
40
- options,
41
- ...getSeparators()
42
- });
70
+ const resolved = resolveTranslation(getResolveParams(lang, ns, key, options));
43
71
  if (resolved !== void 0) return resolved;
44
72
  const defaultValue = options?.defaultValue;
45
- if (typeof defaultValue === "string") return resolveMessageNodeToString(defaultValue, getInterpolationValues(options), lang);
73
+ if (typeof defaultValue === "string") return resolveMessageNodeToString(defaultValue, getInterpolationValues(options, getEscapeValue()), lang);
46
74
  return key;
47
75
  };
48
76
  const instance = {
@@ -61,7 +89,9 @@ const createInstance = (instanceOptions = {}) => {
61
89
  isInitializing: false,
62
90
  initializedStoreOnce: false,
63
91
  initializedLanguageOnce: false,
64
- options: instanceOptions,
92
+ get options() {
93
+ return currentOptions;
94
+ },
65
95
  modules: {},
66
96
  services: {},
67
97
  store: {},
@@ -69,9 +99,8 @@ const createInstance = (instanceOptions = {}) => {
69
99
  async init(optionsOrCb, cb) {
70
100
  const opts = typeof optionsOrCb === "function" ? {} : optionsOrCb ?? {};
71
101
  if (opts.resources !== void 0) warnIgnoredResources("i18next.init");
102
+ Object.assign(currentOptions, withDerivedDefaultNamespace(opts));
72
103
  if (opts.lng) currentLanguage = opts.lng;
73
- if (opts.defaultNS) defaultNS = opts.defaultNS;
74
- else if (opts.ns) defaultNS = Array.isArray(opts.ns) ? opts.ns[0] : opts.ns;
75
104
  initialized = true;
76
105
  emit("initialized", opts);
77
106
  const t = instance.t.bind(instance);
@@ -85,17 +114,11 @@ const createInstance = (instanceOptions = {}) => {
85
114
  } : optionsOrDefaultValue;
86
115
  const keys = Array.isArray(key) ? key : [String(key)];
87
116
  for (const candidateKey of keys) {
88
- const result = resolveTranslation({
89
- locale: currentLanguage,
90
- namespace: defaultNS,
91
- key: candidateKey,
92
- options,
93
- ...getSeparators()
94
- });
117
+ const result = resolveTranslation(getResolveParams(currentLanguage, getDefaultNamespaces(), candidateKey, options));
95
118
  if (result !== void 0) return result;
96
119
  }
97
120
  const defaultValue = options?.defaultValue;
98
- if (typeof defaultValue === "string") return resolveMessageNodeToString(defaultValue, getInterpolationValues(options), currentLanguage);
121
+ if (typeof defaultValue === "string") return resolveMessageNodeToString(defaultValue, getInterpolationValues(options, getEscapeValue()), currentLanguage);
99
122
  return defaultValue ?? (Array.isArray(key) ? key[key.length - 1] : key);
100
123
  },
101
124
  async changeLanguage(language, cb) {
@@ -107,13 +130,7 @@ const createInstance = (instanceOptions = {}) => {
107
130
  return t;
108
131
  },
109
132
  exists(key, options) {
110
- return resolveTranslation({
111
- locale: currentLanguage,
112
- namespace: defaultNS,
113
- key,
114
- options,
115
- ...getSeparators()
116
- }) !== void 0;
133
+ return resolveTranslation(getResolveParams(currentLanguage, getDefaultNamespaces(), key, options)) !== void 0;
117
134
  },
118
135
  /**
119
136
  * Returns a `t()` function bound to a fixed locale and namespace.
@@ -131,10 +148,9 @@ const createInstance = (instanceOptions = {}) => {
131
148
  */
132
149
  getFixedT: ((language, ns, keyPrefix) => {
133
150
  const fixedLng = Array.isArray(language) ? language[0] ?? currentLanguage : language ?? currentLanguage;
134
- const fixedNS = ns ?? defaultNS;
135
151
  return (key, opts) => {
136
152
  const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;
137
- return resolveKey(fixedLng, fixedNS, fullKey, opts);
153
+ return resolveKey(fixedLng, ns ?? getDefaultNamespaces(), fullKey, opts);
138
154
  };
139
155
  }),
140
156
  use(module) {
@@ -169,7 +185,7 @@ const createInstance = (instanceOptions = {}) => {
169
185
  },
170
186
  cloneInstance(opts, _cb) {
171
187
  return createInstance({
172
- ...instanceOptions,
188
+ ...currentOptions,
173
189
  ...opts
174
190
  });
175
191
  },
@@ -177,7 +193,7 @@ const createInstance = (instanceOptions = {}) => {
177
193
  return getHTMLTextDir(language ?? currentLanguage) === "rtl" ? "rtl" : "ltr";
178
194
  },
179
195
  setDefaultNamespace(ns) {
180
- defaultNS = ns;
196
+ currentOptions.defaultNS = ns;
181
197
  },
182
198
  hasLoadedNamespace(ns) {
183
199
  try {
@@ -207,7 +223,7 @@ const createInstance = (instanceOptions = {}) => {
207
223
  removeResourceBundle: () => instance,
208
224
  toJSON() {
209
225
  return {
210
- options: instanceOptions,
226
+ options: currentOptions,
211
227
  store: {},
212
228
  language: currentLanguage,
213
229
  languages: config?.locales?.map(String) ?? [currentLanguage],
@@ -1 +1 @@
1
- {"version":3,"file":"createInstance.mjs","names":[],"sources":["../../src/createInstance.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { getHTMLTextDir } from '@intlayer/core/localization';\nimport {\n navigatePath,\n resolveMessageNodeToString,\n} from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n createInstance as _createInstance,\n i18n as I18nInterface,\n InitOptions,\n TOptions,\n} from 'i18next';\nimport {\n getInterpolationValues,\n resolveTranslation,\n} from './resolveTranslation';\nimport type { TypedGetFixedT } from './typedTranslation';\n\ntype EventHandler = (...args: unknown[]) => void;\n\nconst warnIgnoredResources = (location: string) => {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize(location, ANSIColors.CYAN)}: the ${colorize('`resources`', ANSIColors.CYAN)} option is ignored when using ${colorize('@intlayer/i18next', ANSIColors.MAGENTA)} — translations are served from the compiled intlayer dictionaries instead. Remove the resource imports and the ${colorize('`resources`', ANSIColors.CYAN)} option to reduce your bundle size.`\n );\n};\n\nexport const createInstance: typeof _createInstance = (\n instanceOptions: InitOptions = {}\n): I18nInterface => {\n if ((instanceOptions as Record<string, unknown>).resources !== undefined) {\n warnIgnoredResources('createInstance');\n }\n\n const config = internationalization;\n\n let currentLanguage: string =\n (instanceOptions.lng as string) ?? config?.defaultLocale ?? 'en';\n\n let defaultNS: string =\n (instanceOptions.defaultNS as string) ??\n (Array.isArray(instanceOptions.ns)\n ? (instanceOptions.ns[0] as string)\n : (instanceOptions.ns as string)) ??\n 'translation';\n\n const listeners = new Map<string, Set<EventHandler>>();\n let initialized = false;\n\n const emit = (event: string, ...args: unknown[]) => {\n listeners.get(event)?.forEach((h) => {\n h(...args);\n });\n };\n\n const getSeparators = () => ({\n keySeparator:\n (instanceOptions.keySeparator as string | false | undefined) ?? '.',\n nsSeparator:\n (instanceOptions.nsSeparator as string | false | undefined) ?? ':',\n });\n\n /**\n * Resolves a key through the full i18next pipeline (namespace prefix,\n * `ns` option, plural/context suffixes, `$t()` nesting, interpolation).\n * Falls back to the interpolated `defaultValue`, then to the key itself.\n */\n const resolveKey = (\n lang: string,\n ns: string,\n key: string,\n opts?: TOptions | string\n ): string => {\n const options =\n typeof opts === 'string' ? { defaultValue: opts } : (opts as TOptions);\n\n const resolved = resolveTranslation({\n locale: lang as LocalesValues,\n namespace: ns,\n key,\n options,\n ...getSeparators(),\n });\n\n if (resolved !== undefined) return resolved as string;\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n // A runtime default gets `{{name}}` / `{{price, number}}` interpolation only;\n // dialect constructs (`$t()`, plural blocks) belong in dictionaries, where\n // the build converts them — parsing them here would ship the parser.\n return resolveMessageNodeToString(\n defaultValue,\n getInterpolationValues(options),\n lang as LocalesValues\n );\n }\n\n return key;\n };\n\n const instance = {\n get language() {\n return currentLanguage;\n },\n get languages() {\n return (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[];\n },\n get resolvedLanguage() {\n return currentLanguage;\n },\n get isInitialized() {\n return initialized;\n },\n isInitializing: false,\n initializedStoreOnce: false,\n initializedLanguageOnce: false,\n options: instanceOptions,\n modules: {} as I18nInterface['modules'],\n services: {} as I18nInterface['services'],\n store: {} as I18nInterface['store'],\n format: ((value: unknown) => String(value)) as I18nInterface['format'],\n\n async init(optionsOrCb?: unknown, cb?: unknown) {\n const opts =\n typeof optionsOrCb === 'function'\n ? {}\n : ((optionsOrCb ?? {}) as Record<string, unknown>);\n if (opts.resources !== undefined) {\n warnIgnoredResources('i18next.init');\n }\n if (opts.lng) currentLanguage = opts.lng as string;\n if (opts.defaultNS) defaultNS = opts.defaultNS as string;\n else if (opts.ns)\n defaultNS = Array.isArray(opts.ns)\n ? (opts.ns[0] as string)\n : (opts.ns as string);\n initialized = true;\n emit('initialized', opts);\n const t = instance.t.bind(instance);\n const callback = typeof optionsOrCb === 'function' ? optionsOrCb : cb;\n (callback as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n t(\n key: unknown,\n optionsOrDefaultValue?: unknown,\n extraOpts?: unknown\n ): unknown {\n const options =\n typeof optionsOrDefaultValue === 'string'\n ? {\n defaultValue: optionsOrDefaultValue,\n ...((extraOpts ?? {}) as Record<string, unknown>),\n }\n : (optionsOrDefaultValue as TOptions | undefined);\n const keys: string[] = Array.isArray(key)\n ? (key as string[])\n : [String(key)];\n for (const candidateKey of keys) {\n const result = resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key: candidateKey,\n options,\n ...getSeparators(),\n });\n if (result !== undefined) return result;\n }\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n // A runtime default gets `{{name}}` / `{{price, number}}` interpolation only;\n // dialect constructs (`$t()`, plural blocks) belong in dictionaries, where\n // the build converts them — parsing them here would ship the parser.\n return resolveMessageNodeToString(\n defaultValue,\n getInterpolationValues(options),\n currentLanguage as LocalesValues\n );\n }\n\n return defaultValue ?? (Array.isArray(key) ? key[key.length - 1] : key);\n },\n\n async changeLanguage(language?: string, cb?: unknown) {\n const prev = currentLanguage;\n\n if (language) currentLanguage = language;\n\n emit('languageChanged', currentLanguage, prev);\n const t = instance.t.bind(instance);\n\n (cb as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n exists(key: string, options?: unknown): boolean {\n return (\n resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key,\n options: options as TOptions,\n ...getSeparators(),\n }) !== undefined\n );\n },\n\n /**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary, and its return type is resolved from the\n * content at that path. With a `keyPrefix`, keys are relative dot-paths\n * under the prefix.\n *\n * @example\n * ```ts\n * const tAbout = i18n.getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed key and return value\n * ```\n */\n getFixedT: ((\n language: string | readonly string[] | null,\n ns?: string | null,\n keyPrefix?: string\n ) => {\n const fixedLng = Array.isArray(language)\n ? ((language[0] as string) ?? currentLanguage)\n : ((language as string) ?? currentLanguage);\n\n const fixedNS = ns ?? defaultNS;\n\n return (key: string, opts?: TOptions): string => {\n const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;\n return resolveKey(fixedLng, fixedNS, fullKey, opts);\n };\n }) as TypedGetFixedT,\n\n use(module: unknown) {\n (module as { init?: (i18n: I18nInterface) => void })?.init?.(\n instance as unknown as I18nInterface\n );\n return instance as unknown as I18nInterface;\n },\n\n on(event: string, handler: EventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return instance as unknown as I18nInterface;\n },\n\n once(event: string, handler: EventHandler) {\n const wrapper: EventHandler = (...args) => {\n handler(...args);\n instance.off(event, wrapper);\n };\n instance.on(event, wrapper);\n return instance as unknown as I18nInterface;\n },\n\n off(event: string, handler?: EventHandler) {\n if (!handler) listeners.delete(event);\n else listeners.get(event)?.delete(handler);\n },\n\n emit(eventName: string, ...args: unknown[]) {\n emit(eventName, ...args);\n },\n\n createInstance(opts?: InitOptions, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n cloneInstance(opts?: Record<string, unknown>, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n dir(language?: string): 'ltr' | 'rtl' {\n const direction = getHTMLTextDir(\n (language ?? currentLanguage) as LocalesValues\n );\n return direction === 'rtl' ? 'rtl' : 'ltr';\n },\n\n setDefaultNamespace(ns: string) {\n defaultNS = ns;\n },\n\n hasLoadedNamespace(ns: string | readonly string[]): boolean {\n try {\n getIntlayer(\n (Array.isArray(ns) ? ns[0] : ns) as DictionaryKeys,\n currentLanguage as LocalesValues\n );\n return true;\n } catch {\n return false;\n }\n },\n\n async loadNamespaces(_ns: unknown) {},\n async loadLanguages(_lngs: unknown) {},\n loadResources(_cb?: unknown) {},\n async reloadResources() {},\n\n getDataByLanguage(_lng: string) {\n return undefined;\n },\n\n getResource(lng: string, ns: string, key: string): unknown {\n try {\n return navigatePath(\n getIntlayer(ns as DictionaryKeys, lng as LocalesValues),\n key\n );\n } catch {\n return undefined;\n }\n },\n\n addResource: () => instance as unknown as I18nInterface,\n addResources: () => instance as unknown as I18nInterface,\n addResourceBundle: () => instance as unknown as I18nInterface,\n hasResourceBundle: () => false,\n getResourceBundle: () => undefined,\n removeResourceBundle: () => instance as unknown as I18nInterface,\n\n toJSON() {\n return {\n options: instanceOptions,\n store: {} as I18nInterface['store'],\n language: currentLanguage,\n languages: (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[],\n resolvedLanguage: currentLanguage,\n };\n },\n };\n\n return instance as unknown as I18nInterface;\n};\n"],"mappings":";;;;;;;;;AA2BA,MAAM,wBAAwB,aAAqB;CAEjD,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,UAAU,WAAW,IAAI,EAAE,QAAQ,SAAS,eAAe,WAAW,IAAI,EAAE,gCAAgC,SAAS,qBAAqB,WAAW,OAAO,EAAE,kHAAkH,SAAS,eAAe,WAAW,IAAI,EAAE,oCACvU;AACF;AAEA,MAAa,kBACX,kBAA+B,CAAC,MACd;CAClB,IAAK,gBAA4C,cAAc,QAC7D,qBAAqB,gBAAgB;CAGvC,MAAM,SAAS;CAEf,IAAI,kBACD,gBAA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C,MAAM,cAAc,OAAgB,CAAC;EACrC,cAAc,KAAe,CAAC;EAC9B,MAAM,kBAAkB,CAAC;EAEzB,kBAAkB,MAAc,CAEhC;EAEA,YAAY,KAAa,IAAY,KAAsB;GACzD,IAAI;IACF,OAAO,aACL,YAAY,IAAsB,GAAoB,GACtD,GACF;GACF,QAAQ;IACN;GACF;EACF;EAEA,mBAAmB;EACnB,oBAAoB;EACpB,yBAAyB;EACzB,yBAAyB;EACzB,yBAAyB;EACzB,4BAA4B;EAE5B,SAAS;GACP,OAAO;IACL,SAAS;IACT,OAAO,CAAC;IACR,UAAU;IACV,WAAY,QAAQ,SAAS,IAAI,MAAM,KAAK,CAC1C,eACF;IACA,kBAAkB;GACpB;EACF;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"createInstance.mjs","names":[],"sources":["../../src/createInstance.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { getHTMLTextDir } from '@intlayer/core/localization';\nimport {\n navigatePath,\n resolveMessageNodeToString,\n} from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n createInstance as _createInstance,\n i18n as I18nInterface,\n InitOptions,\n TOptions,\n} from 'i18next';\nimport {\n getInterpolationValues,\n type ResolveTranslationParams,\n resolveTranslation,\n toNamespaceList,\n} from './resolveTranslation';\nimport type { TypedGetFixedT } from './typedTranslation';\n\ntype EventHandler = (...args: unknown[]) => void;\n\n/** i18next's namespace when neither `defaultNS` nor `ns` is configured. */\nconst DEFAULT_NAMESPACE = 'translation';\n\n/**\n * Fills `defaultNS` from `ns` the way i18next's `init()` does: a string `ns`\n * becomes the default, an array gives its first entry unless it lists\n * `translation`.\n */\nconst withDerivedDefaultNamespace = <T extends InitOptions>(options: T): T => {\n if (\n (options.defaultNS !== undefined && options.defaultNS !== null) ||\n !options.ns ||\n (Array.isArray(options.ns) && options.ns.includes(DEFAULT_NAMESPACE))\n ) {\n return options;\n }\n\n return { ...options, defaultNS: toNamespaceList(options.ns)[0] };\n};\n\nconst warnIgnoredResources = (location: string) => {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize(location, ANSIColors.CYAN)}: the ${colorize('`resources`', ANSIColors.CYAN)} option is ignored when using ${colorize('@intlayer/i18next', ANSIColors.MAGENTA)} — translations are served from the compiled intlayer dictionaries instead. Remove the resource imports and the ${colorize('`resources`', ANSIColors.CYAN)} option to reduce your bundle size.`\n );\n};\n\nexport const createInstance: typeof _createInstance = (\n instanceOptions: InitOptions = {}\n): I18nInterface => {\n if ((instanceOptions as Record<string, unknown>).resources !== undefined) {\n warnIgnoredResources('createInstance');\n }\n\n const config = internationalization;\n\n /** `createInstance` options, with every later `init()` merged in. */\n const currentOptions: InitOptions = withDerivedDefaultNamespace({\n ...instanceOptions,\n });\n\n let currentLanguage: string =\n (currentOptions.lng as string) ?? config?.defaultLocale ?? 'en';\n\n const listeners = new Map<string, Set<EventHandler>>();\n let initialized = false;\n\n const emit = (event: string, ...args: unknown[]) => {\n listeners.get(event)?.forEach((h) => {\n h(...args);\n });\n };\n\n /** Configured default namespaces as written, else i18next's `translation`. */\n const getDefaultNamespaces = (): string | readonly string[] => {\n const { defaultNS } = currentOptions;\n if (typeof defaultNS === 'string' && defaultNS !== '') return defaultNS;\n if (Array.isArray(defaultNS) && defaultNS.length > 0) return defaultNS;\n return DEFAULT_NAMESPACE;\n };\n\n /** Whether interpolated values are HTML-escaped (i18next default: on). */\n const getEscapeValue = (): boolean =>\n currentOptions.interpolation?.escapeValue ?? true;\n\n /**\n * `resolveTranslation` params for one lookup, with the instance settings\n * read as written so no option list is copied on the `t()` hot path.\n */\n const getResolveParams = (\n language: string,\n namespace: string | readonly string[],\n key: string,\n options?: TOptions\n ): ResolveTranslationParams => ({\n locale: language as LocalesValues,\n namespace,\n key,\n options,\n keySeparator: (currentOptions.keySeparator as string | false) ?? '.',\n nsSeparator: (currentOptions.nsSeparator as string | false) ?? ':',\n fallbackNamespaces: currentOptions.fallbackNS,\n escapeValue: getEscapeValue(),\n });\n\n /**\n * Resolves a key through the full i18next pipeline (namespace prefix,\n * `ns` option, plural/context suffixes, `$t()` nesting, interpolation).\n * Falls back to the interpolated `defaultValue`, then to the key itself.\n */\n const resolveKey = (\n lang: string,\n ns: string | readonly string[],\n key: string,\n opts?: TOptions | string\n ): string => {\n const options =\n typeof opts === 'string' ? { defaultValue: opts } : (opts as TOptions);\n\n const resolved = resolveTranslation(\n getResolveParams(lang, ns, key, options)\n );\n\n if (resolved !== undefined) return resolved as string;\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n // A runtime default gets `{{name}}` / `{{price, number}}` interpolation only;\n // dialect constructs (`$t()`, plural blocks) belong in dictionaries, where\n // the build converts them — parsing them here would ship the parser.\n return resolveMessageNodeToString(\n defaultValue,\n getInterpolationValues(options, getEscapeValue()),\n lang as LocalesValues\n );\n }\n\n return key;\n };\n\n const instance = {\n get language() {\n return currentLanguage;\n },\n get languages() {\n return (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[];\n },\n get resolvedLanguage() {\n return currentLanguage;\n },\n get isInitialized() {\n return initialized;\n },\n isInitializing: false,\n initializedStoreOnce: false,\n initializedLanguageOnce: false,\n get options() {\n return currentOptions;\n },\n modules: {} as I18nInterface['modules'],\n services: {} as I18nInterface['services'],\n store: {} as I18nInterface['store'],\n format: ((value: unknown) => String(value)) as I18nInterface['format'],\n\n async init(optionsOrCb?: unknown, cb?: unknown) {\n const opts =\n typeof optionsOrCb === 'function'\n ? {}\n : ((optionsOrCb ?? {}) as Record<string, unknown>);\n if (opts.resources !== undefined) {\n warnIgnoredResources('i18next.init');\n }\n // i18next merges `init()` options over the `createInstance()` ones\n Object.assign(currentOptions, withDerivedDefaultNamespace(opts));\n if (opts.lng) currentLanguage = opts.lng as string;\n initialized = true;\n emit('initialized', opts);\n const t = instance.t.bind(instance);\n const callback = typeof optionsOrCb === 'function' ? optionsOrCb : cb;\n (callback as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n t(\n key: unknown,\n optionsOrDefaultValue?: unknown,\n extraOpts?: unknown\n ): unknown {\n const options =\n typeof optionsOrDefaultValue === 'string'\n ? {\n defaultValue: optionsOrDefaultValue,\n ...((extraOpts ?? {}) as Record<string, unknown>),\n }\n : (optionsOrDefaultValue as TOptions | undefined);\n const keys: string[] = Array.isArray(key)\n ? (key as string[])\n : [String(key)];\n for (const candidateKey of keys) {\n const result = resolveTranslation(\n getResolveParams(\n currentLanguage,\n getDefaultNamespaces(),\n candidateKey,\n options\n )\n );\n if (result !== undefined) return result;\n }\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n // A runtime default gets `{{name}}` / `{{price, number}}` interpolation only;\n // dialect constructs (`$t()`, plural blocks) belong in dictionaries, where\n // the build converts them — parsing them here would ship the parser.\n return resolveMessageNodeToString(\n defaultValue,\n getInterpolationValues(options, getEscapeValue()),\n currentLanguage as LocalesValues\n );\n }\n\n return defaultValue ?? (Array.isArray(key) ? key[key.length - 1] : key);\n },\n\n async changeLanguage(language?: string, cb?: unknown) {\n const prev = currentLanguage;\n\n if (language) currentLanguage = language;\n\n emit('languageChanged', currentLanguage, prev);\n const t = instance.t.bind(instance);\n\n (cb as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n exists(key: string, options?: unknown): boolean {\n return (\n resolveTranslation(\n getResolveParams(\n currentLanguage,\n getDefaultNamespaces(),\n key,\n options as TOptions\n )\n ) !== undefined\n );\n },\n\n /**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary, and its return type is resolved from the\n * content at that path. With a `keyPrefix`, keys are relative dot-paths\n * under the prefix.\n *\n * @example\n * ```ts\n * const tAbout = i18n.getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed key and return value\n * ```\n */\n getFixedT: ((\n language: string | readonly string[] | null,\n ns?: string | readonly string[] | null,\n keyPrefix?: string\n ) => {\n const fixedLng = Array.isArray(language)\n ? ((language[0] as string) ?? currentLanguage)\n : ((language as string) ?? currentLanguage);\n\n return (key: string, opts?: TOptions): string => {\n const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;\n return resolveKey(\n fixedLng,\n ns ?? getDefaultNamespaces(),\n fullKey,\n opts\n );\n };\n }) as TypedGetFixedT,\n\n use(module: unknown) {\n (module as { init?: (i18n: I18nInterface) => void })?.init?.(\n instance as unknown as I18nInterface\n );\n return instance as unknown as I18nInterface;\n },\n\n on(event: string, handler: EventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return instance as unknown as I18nInterface;\n },\n\n once(event: string, handler: EventHandler) {\n const wrapper: EventHandler = (...args) => {\n handler(...args);\n instance.off(event, wrapper);\n };\n instance.on(event, wrapper);\n return instance as unknown as I18nInterface;\n },\n\n off(event: string, handler?: EventHandler) {\n if (!handler) listeners.delete(event);\n else listeners.get(event)?.delete(handler);\n },\n\n emit(eventName: string, ...args: unknown[]) {\n emit(eventName, ...args);\n },\n\n createInstance(opts?: InitOptions, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n cloneInstance(opts?: Record<string, unknown>, _cb?: unknown) {\n return createInstance({ ...currentOptions, ...opts });\n },\n\n dir(language?: string): 'ltr' | 'rtl' {\n const direction = getHTMLTextDir(\n (language ?? currentLanguage) as LocalesValues\n );\n return direction === 'rtl' ? 'rtl' : 'ltr';\n },\n\n setDefaultNamespace(ns: string | readonly string[]) {\n currentOptions.defaultNS = ns;\n },\n\n hasLoadedNamespace(ns: string | readonly string[]): boolean {\n try {\n getIntlayer(\n (Array.isArray(ns) ? ns[0] : ns) as DictionaryKeys,\n currentLanguage as LocalesValues\n );\n return true;\n } catch {\n return false;\n }\n },\n\n async loadNamespaces(_ns: unknown) {},\n async loadLanguages(_lngs: unknown) {},\n loadResources(_cb?: unknown) {},\n async reloadResources() {},\n\n getDataByLanguage(_lng: string) {\n return undefined;\n },\n\n getResource(lng: string, ns: string, key: string): unknown {\n try {\n return navigatePath(\n getIntlayer(ns as DictionaryKeys, lng as LocalesValues),\n key\n );\n } catch {\n return undefined;\n }\n },\n\n addResource: () => instance as unknown as I18nInterface,\n addResources: () => instance as unknown as I18nInterface,\n addResourceBundle: () => instance as unknown as I18nInterface,\n hasResourceBundle: () => false,\n getResourceBundle: () => undefined,\n removeResourceBundle: () => instance as unknown as I18nInterface,\n\n toJSON() {\n return {\n options: currentOptions,\n store: {} as I18nInterface['store'],\n language: currentLanguage,\n languages: (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[],\n resolvedLanguage: currentLanguage,\n };\n },\n };\n\n return instance as unknown as I18nInterface;\n};\n"],"mappings":";;;;;;;;;;AA8BA,MAAM,oBAAoB;;;;;;AAO1B,MAAM,+BAAsD,YAAkB;CAC5E,IACG,QAAQ,cAAc,UAAa,QAAQ,cAAc,QAC1D,CAAC,QAAQ,MACR,MAAM,QAAQ,QAAQ,EAAE,KAAK,QAAQ,GAAG,SAAS,iBAAiB,GAEnE,OAAO;CAGT,OAAO;EAAE,GAAG;EAAS,WAAW,gBAAgB,QAAQ,EAAE,CAAC,CAAC;CAAG;AACjE;AAEA,MAAM,wBAAwB,aAAqB;CAEjD,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,UAAU,WAAW,IAAI,EAAE,QAAQ,SAAS,eAAe,WAAW,IAAI,EAAE,gCAAgC,SAAS,qBAAqB,WAAW,OAAO,EAAE,kHAAkH,SAAS,eAAe,WAAW,IAAI,EAAE,oCACv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kC;GAIpC,OAHkB,eACf,YAAY,eAEA,MAAM,QAAQ,QAAQ;EACvC;EAEA,oBAAoB,IAAgC;GAClD,eAAe,YAAY;EAC7B;EAEA,mBAAmB,IAAyC;GAC1D,IAAI;IACF,YACG,MAAM,QAAQ,EAAE,IAAI,GAAG,KAAK,IAC7B,eACF;IACA,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,eAAe,KAAc,CAAC;EACpC,MAAM,cAAc,OAAgB,CAAC;EACrC,cAAc,KAAe,CAAC;EAC9B,MAAM,kBAAkB,CAAC;EAEzB,kBAAkB,MAAc,CAEhC;EAEA,YAAY,KAAa,IAAY,KAAsB;GACzD,IAAI;IACF,OAAO,aACL,YAAY,IAAsB,GAAoB,GACtD,GACF;GACF,QAAQ;IACN;GACF;EACF;EAEA,mBAAmB;EACnB,oBAAoB;EACpB,yBAAyB;EACzB,yBAAyB;EACzB,yBAAyB;EACzB,4BAA4B;EAE5B,SAAS;GACP,OAAO;IACL,SAAS;IACT,OAAO,CAAC;IACR,UAAU;IACV,WAAY,QAAQ,SAAS,IAAI,MAAM,KAAK,CAC1C,eACF;IACA,kBAAkB;GACpB;EACF;CACF;CAEA,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
  import { createInstance } from "./createInstance.mjs";
2
2
  import { getDictionary } from "./getDictionary.mjs";
3
3
  import { getDictionaryDynamic } from "./getDictionaryDynamic.mjs";
4
- import { getInterpolationValues, resolveTranslation } from "./resolveTranslation.mjs";
4
+ import { getInterpolationValues, resolveTranslation, toNamespaceList } from "./resolveTranslation.mjs";
5
5
 
6
6
  // src/index.ts
7
7
  const i18next = createInstance();
@@ -37,5 +37,5 @@ const loadLanguages = i18next.loadLanguages.bind(i18next);
37
37
  */
38
38
  const keyFromSelector = (selector) => selector;
39
39
 
40
- export { changeLanguage, createInstance, i18next as default, i18next, dir, exists, getDictionary, getDictionaryDynamic, getFixedT, getInterpolationValues, hasLoadedNamespace, init, keyFromSelector, loadLanguages, loadNamespaces, loadResources, reloadResources, resolveTranslation, setDefaultNamespace, t, use };
40
+ export { changeLanguage, createInstance, i18next as default, i18next, dir, exists, getDictionary, getDictionaryDynamic, getFixedT, getInterpolationValues, hasLoadedNamespace, init, keyFromSelector, loadLanguages, loadNamespaces, loadResources, reloadResources, resolveTranslation, setDefaultNamespace, t, toNamespaceList, use };
41
41
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import type {\n changeLanguage as _changeLanguage,\n dir as _dir,\n exists as _exists,\n hasLoadedNamespace as _hasLoadedNamespace,\n init as _init,\n loadLanguages as _loadLanguages,\n loadNamespaces as _loadNamespaces,\n loadResources as _loadResources,\n reloadResources as _reloadResources,\n setDefaultNamespace as _setDefaultNamespace,\n t as _t,\n use as _use,\n i18n,\n} from 'i18next';\nimport { createInstance } from './createInstance';\nimport type { TypedGetFixedT } from './typedTranslation';\n\nexport { getDictionary } from './getDictionary';\nexport { getDictionaryDynamic } from './getDictionaryDynamic';\nexport {\n getInterpolationValues,\n type ResolveTranslationParams,\n resolveTranslation,\n} from './resolveTranslation';\nexport type {\n ContentAtPath,\n ScopedDotPaths,\n ScopedTFunction,\n TranslatedValue,\n TypedGetFixedT,\n TypedTFunction,\n} from './typedTranslation';\n\nconst i18next: i18n = createInstance();\n\nexport { createInstance };\nexport default i18next;\nexport { i18next };\n\nexport const dir: typeof _dir = i18next.dir.bind(i18next);\nexport const init: typeof _init = i18next.init.bind(i18next);\nexport const loadResources: typeof _loadResources =\n i18next.loadResources.bind(i18next);\nexport const reloadResources: typeof _reloadResources =\n i18next.reloadResources.bind(i18next);\nexport const use: typeof _use = i18next.use.bind(i18next);\nexport const changeLanguage: typeof _changeLanguage =\n i18next.changeLanguage.bind(i18next);\n\n/**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary.\n *\n * @example\n * ```ts\n * const tAbout = getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed\n * ```\n */\nexport const getFixedT: TypedGetFixedT = i18next.getFixedT.bind(\n i18next\n) as unknown as TypedGetFixedT;\n\nexport const t: typeof _t = i18next.t.bind(i18next);\nexport const exists: typeof _exists = i18next.exists.bind(i18next);\nexport const setDefaultNamespace: typeof _setDefaultNamespace =\n i18next.setDefaultNamespace.bind(i18next);\nexport const hasLoadedNamespace: typeof _hasLoadedNamespace =\n i18next.hasLoadedNamespace.bind(i18next);\nexport const loadNamespaces: typeof _loadNamespaces =\n i18next.loadNamespaces.bind(i18next);\nexport const loadLanguages: typeof _loadLanguages =\n i18next.loadLanguages.bind(i18next);\n\n/**\n * No-op shim for i18next's `keyFromSelector`. This helper is not exposed by\n * every supported i18next version, so a permissive identity function is\n * provided to keep `.keyFromSelector(...)` call-sites working.\n */\nexport const keyFromSelector = (selector: unknown): unknown => selector;\n\nexport type { InitOptions, i18n, TFunction, TOptions } from 'i18next';\n"],"mappings":";;;;;;AAkCA,MAAM,UAAgB,eAAe;AAMrC,MAAa,MAAmB,QAAQ,IAAI,KAAK,OAAO;AACxD,MAAa,OAAqB,QAAQ,KAAK,KAAK,OAAO;AAC3D,MAAa,gBACX,QAAQ,cAAc,KAAK,OAAO;AACpC,MAAa,kBACX,QAAQ,gBAAgB,KAAK,OAAO;AACtC,MAAa,MAAmB,QAAQ,IAAI,KAAK,OAAO;AACxD,MAAa,iBACX,QAAQ,eAAe,KAAK,OAAO;;;;;;;;;;;;;AAcrC,MAAa,YAA4B,QAAQ,UAAU,KACzD,OACF;AAEA,MAAa,IAAe,QAAQ,EAAE,KAAK,OAAO;AAClD,MAAa,SAAyB,QAAQ,OAAO,KAAK,OAAO;AACjE,MAAa,sBACX,QAAQ,oBAAoB,KAAK,OAAO;AAC1C,MAAa,qBACX,QAAQ,mBAAmB,KAAK,OAAO;AACzC,MAAa,iBACX,QAAQ,eAAe,KAAK,OAAO;AACrC,MAAa,gBACX,QAAQ,cAAc,KAAK,OAAO;;;;;;AAOpC,MAAa,mBAAmB,aAA+B"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import type {\n changeLanguage as _changeLanguage,\n dir as _dir,\n exists as _exists,\n hasLoadedNamespace as _hasLoadedNamespace,\n init as _init,\n loadLanguages as _loadLanguages,\n loadNamespaces as _loadNamespaces,\n loadResources as _loadResources,\n reloadResources as _reloadResources,\n setDefaultNamespace as _setDefaultNamespace,\n t as _t,\n use as _use,\n i18n,\n} from 'i18next';\nimport { createInstance } from './createInstance';\nimport type { TypedGetFixedT } from './typedTranslation';\n\nexport { getDictionary } from './getDictionary';\nexport { getDictionaryDynamic } from './getDictionaryDynamic';\nexport {\n getInterpolationValues,\n type ResolveTranslationParams,\n resolveTranslation,\n toNamespaceList,\n} from './resolveTranslation';\nexport type {\n ContentAtPath,\n FallbackNamespaceKeys,\n ResolvedNamespace,\n ScopedDotPaths,\n ScopedTFunction,\n TranslatedValue,\n TranslationKey,\n TypedGetFixedT,\n TypedTFunction,\n} from './typedTranslation';\n\nconst i18next: i18n = createInstance();\n\nexport { createInstance };\nexport default i18next;\nexport { i18next };\n\nexport const dir: typeof _dir = i18next.dir.bind(i18next);\nexport const init: typeof _init = i18next.init.bind(i18next);\nexport const loadResources: typeof _loadResources =\n i18next.loadResources.bind(i18next);\nexport const reloadResources: typeof _reloadResources =\n i18next.reloadResources.bind(i18next);\nexport const use: typeof _use = i18next.use.bind(i18next);\nexport const changeLanguage: typeof _changeLanguage =\n i18next.changeLanguage.bind(i18next);\n\n/**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary.\n *\n * @example\n * ```ts\n * const tAbout = getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed\n * ```\n */\nexport const getFixedT: TypedGetFixedT = i18next.getFixedT.bind(\n i18next\n) as unknown as TypedGetFixedT;\n\nexport const t: typeof _t = i18next.t.bind(i18next);\nexport const exists: typeof _exists = i18next.exists.bind(i18next);\nexport const setDefaultNamespace: typeof _setDefaultNamespace =\n i18next.setDefaultNamespace.bind(i18next);\nexport const hasLoadedNamespace: typeof _hasLoadedNamespace =\n i18next.hasLoadedNamespace.bind(i18next);\nexport const loadNamespaces: typeof _loadNamespaces =\n i18next.loadNamespaces.bind(i18next);\nexport const loadLanguages: typeof _loadLanguages =\n i18next.loadLanguages.bind(i18next);\n\n/**\n * No-op shim for i18next's `keyFromSelector`. This helper is not exposed by\n * every supported i18next version, so a permissive identity function is\n * provided to keep `.keyFromSelector(...)` call-sites working.\n */\nexport const keyFromSelector = (selector: unknown): unknown => selector;\n\nexport type { InitOptions, i18n, TFunction, TOptions } from 'i18next';\n"],"mappings":";;;;;;AAsCA,MAAM,UAAgB,eAAe;AAMrC,MAAa,MAAmB,QAAQ,IAAI,KAAK,OAAO;AACxD,MAAa,OAAqB,QAAQ,KAAK,KAAK,OAAO;AAC3D,MAAa,gBACX,QAAQ,cAAc,KAAK,OAAO;AACpC,MAAa,kBACX,QAAQ,gBAAgB,KAAK,OAAO;AACtC,MAAa,MAAmB,QAAQ,IAAI,KAAK,OAAO;AACxD,MAAa,iBACX,QAAQ,eAAe,KAAK,OAAO;;;;;;;;;;;;;AAcrC,MAAa,YAA4B,QAAQ,UAAU,KACzD,OACF;AAEA,MAAa,IAAe,QAAQ,EAAE,KAAK,OAAO;AAClD,MAAa,SAAyB,QAAQ,OAAO,KAAK,OAAO;AACjE,MAAa,sBACX,QAAQ,oBAAoB,KAAK,OAAO;AAC1C,MAAa,qBACX,QAAQ,mBAAmB,KAAK,OAAO;AACzC,MAAa,iBACX,QAAQ,eAAe,KAAK,OAAO;AACrC,MAAa,gBACX,QAAQ,cAAc,KAAK,OAAO;;;;;;AAOpC,MAAa,mBAAmB,aAA+B"}
@@ -7,9 +7,10 @@ import { getDictionaries } from "@intlayer/dictionaries-entry";
7
7
  * Shared i18next-dialect translation resolution.
8
8
  *
9
9
  * Implements the i18next lookup pipeline on top of intlayer dictionaries:
10
- * namespace prefix (`ns:key`), `ns` option override, plural suffixes
11
- * (`key_one`, `key_other`, …) via `Intl.PluralRules`, context suffixes
12
- * (`key_male`), `$t()` nesting, `defaultValue` and `{{var}}` interpolation.
10
+ * namespace prefix (`ns:key`), `ns` option override, fallback namespaces
11
+ * (`fallbackNS`), plural suffixes (`key_one`, `key_other`, …) via
12
+ * `Intl.PluralRules`, context suffixes (`key_male`), `$t()` nesting,
13
+ * `defaultValue` and `{{var}}` interpolation with optional value escaping.
13
14
  *
14
15
  * Used by `@intlayer/i18next` (instance `t`) and `@intlayer/react-i18next`
15
16
  * (`useTranslation`, `<Trans>`).
@@ -36,6 +37,50 @@ const CONTROL_OPTION_KEYS = /* @__PURE__ */ new Set([
36
37
  ]);
37
38
  /** Maximum `$t()` nesting recursion depth. */
38
39
  const MAX_NESTING_DEPTH = 5;
40
+ /** Characters i18next replaces in interpolated values when `escapeValue` is on. */
41
+ const HTML_ESCAPE_ENTITIES = {
42
+ "&": "&amp;",
43
+ "<": "&lt;",
44
+ ">": "&gt;",
45
+ "\"": "&quot;",
46
+ "'": "&#39;"
47
+ };
48
+ /**
49
+ * Prefix of i18next's unescaped placeholder. The build normalizes
50
+ * `{{- name}}` to `{{-name}}`, so every value is also exposed, never escaped,
51
+ * under `-name`.
52
+ */
53
+ const UNESCAPED_VALUE_PREFIX = "-";
54
+ /**
55
+ * Escapes a value the way i18next's `escapeValue` does — strings, including
56
+ * those nested in arrays and plain objects (`{{user.name}}`).
57
+ */
58
+ const escapeInterpolationValue = (value) => {
59
+ if (typeof value === "string") return value.replace(/[&<>"']/g, (character) => HTML_ESCAPE_ENTITIES[character] ?? character);
60
+ if (Array.isArray(value)) return value.map(escapeInterpolationValue);
61
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [entryKey, escapeInterpolationValue(entryValue)]));
62
+ return value;
63
+ };
64
+ /**
65
+ * Normalizes an i18next namespace option (`ns`, `defaultNS`, `fallbackNS`),
66
+ * which can be a string, an array or `false`, into a list.
67
+ */
68
+ const toNamespaceList = (namespaces) => {
69
+ if (!namespaces) return [];
70
+ return Array.isArray(namespaces) ? namespaces : [namespaces];
71
+ };
72
+ /** Number of namespaces in a namespace option, without copying it. */
73
+ const getNamespaceCount = (namespaces) => {
74
+ if (!namespaces) return 0;
75
+ return typeof namespaces === "string" ? 1 : namespaces.length;
76
+ };
77
+ /** Namespace at `index` of a non-empty namespace option. */
78
+ const getNamespaceAt = (namespaces, index) => typeof namespaces === "string" ? namespaces : namespaces[index];
79
+ /** Whether a namespace option lists `namespace`. */
80
+ const hasNamespace = (namespaces, namespace) => {
81
+ if (!namespaces) return false;
82
+ return typeof namespaces === "string" ? namespaces === namespace : namespaces.includes(namespace);
83
+ };
39
84
  /**
40
85
  * Canonical key of the single dictionary produced when a JSON source pattern
41
86
  * has no `{{key}}` segment (one file holds the whole namespace, e.g.
@@ -57,6 +102,25 @@ const getDictionaryOrUndefined = (namespace, locale) => {
57
102
  return getIntlayer(namespace, locale);
58
103
  };
59
104
  /**
105
+ * Dictionary searched for one namespace, `undefined` when unregistered.
106
+ *
107
+ * `primaryDictionaryContent` is the pre-resolved content of the first default
108
+ * namespace, when the call may use it.
109
+ */
110
+ const getNamespaceDictionary = (candidateNamespace, defaultNamespaces, locale, primaryDictionaryContent) => {
111
+ if (primaryDictionaryContent !== void 0 && candidateNamespace === getNamespaceAt(defaultNamespaces, 0)) return primaryDictionaryContent;
112
+ const dictionary = getDictionaryOrUndefined(candidateNamespace, locale);
113
+ if (dictionary === void 0 && candidateNamespace !== ROOT_DICTIONARY_KEY && hasNamespace(defaultNamespaces, candidateNamespace)) return getDictionaryOrUndefined(ROOT_DICTIONARY_KEY, locale);
114
+ return dictionary;
115
+ };
116
+ /** Value of the first key candidate found in `dictionary`. */
117
+ const findKeyCandidate = (dictionary, keyCandidates, keySeparator) => {
118
+ for (const candidateKey of keyCandidates) {
119
+ const value = navigatePath(dictionary, candidateKey, keySeparator);
120
+ if (value !== null && value !== void 0) return value;
121
+ }
122
+ };
123
+ /**
60
124
  * Builds the ordered list of key candidates following i18next's resolution
61
125
  * order: context + plural → context → plural → exact key.
62
126
  */
@@ -79,18 +143,35 @@ const buildKeyCandidates = (path, locale, count, context, ordinal) => {
79
143
  candidates.push(path);
80
144
  return candidates;
81
145
  };
82
- /** Extracts interpolation values from i18next `t()` options. */
83
- const getInterpolationValues = (options) => {
146
+ /** Whether an interpolation value is absent (`null` or `undefined`). */
147
+ const isMissingValue = (value) => value === void 0 || value === null;
148
+ /**
149
+ * Sets one interpolation value, escaped when asked, and its raw `-name` alias
150
+ * read by `{{- name}}` placeholders.
151
+ */
152
+ const setInterpolationValue = (values, valueName, value, shouldEscape) => {
153
+ values[valueName] = shouldEscape ? escapeInterpolationValue(value) : value;
154
+ values[`${UNESCAPED_VALUE_PREFIX}${valueName}`] = value;
155
+ };
156
+ /**
157
+ * Extracts interpolation values from i18next `t()` options.
158
+ *
159
+ * With `escapeValue` (overridden per call by `interpolation.escapeValue`),
160
+ * values are HTML-escaped like i18next does; each value stays reachable
161
+ * unescaped as `-name` for `{{- name}}` placeholders.
162
+ */
163
+ const getInterpolationValues = (options, escapeValue = false) => {
84
164
  if (!options || typeof options !== "object") return {};
165
+ const shouldEscape = options.interpolation?.escapeValue ?? escapeValue;
166
+ const values = {};
85
167
  const replace = options.replace;
86
168
  if (replace) {
87
- const values = { ...replace };
88
- if (options.count !== void 0) values.count ??= options.count;
89
- if (options.context !== void 0) values.context ??= options.context;
169
+ for (const valueName of Object.keys(replace)) setInterpolationValue(values, valueName, replace[valueName], shouldEscape);
170
+ if (options.count !== void 0 && isMissingValue(values.count)) setInterpolationValue(values, "count", options.count, shouldEscape);
171
+ if (options.context !== void 0 && isMissingValue(values.context)) setInterpolationValue(values, "context", options.context, shouldEscape);
90
172
  return values;
91
173
  }
92
- const values = {};
93
- for (const [optionKey, optionValue] of Object.entries(options)) if (!CONTROL_OPTION_KEYS.has(optionKey)) values[optionKey] = optionValue;
174
+ for (const optionKey of Object.keys(options)) if (!CONTROL_OPTION_KEYS.has(optionKey)) setInterpolationValue(values, optionKey, options[optionKey], shouldEscape);
94
175
  return values;
95
176
  };
96
177
  /**
@@ -102,52 +183,58 @@ const getInterpolationValues = (options) => {
102
183
  * cannot be resolved (caller decides between `defaultValue`, fallback keys
103
184
  * and key echo).
104
185
  */
105
- const resolveTranslation = ({ locale, namespace, key, options, keySeparator = ".", nsSeparator = ":", depth = 0, dictionaryContent }) => {
106
- let targetNamespace = namespace;
186
+ const resolveTranslation = ({ locale, namespace, key, options, keySeparator = ".", nsSeparator = ":", fallbackNamespaces, escapeValue = false, depth = 0, dictionaryContent }) => {
187
+ let requestedNamespaces = namespace;
107
188
  let path = key;
108
189
  if (nsSeparator !== false && key.includes(nsSeparator)) {
109
190
  const separatorIndex = key.indexOf(nsSeparator);
110
- targetNamespace = key.slice(0, separatorIndex);
191
+ requestedNamespaces = key.slice(0, separatorIndex);
111
192
  path = key.slice(separatorIndex + nsSeparator.length);
112
- } else if (options?.ns) targetNamespace = Array.isArray(options.ns) ? options.ns[0] : options.ns;
193
+ } else if (options?.ns) requestedNamespaces = options.ns;
113
194
  const count = typeof options?.count === "number" ? options.count : void 0;
114
195
  const context = options?.context !== void 0 ? String(options.context) : void 0;
115
196
  const ordinal = options?.ordinal === true;
116
197
  const resolvedLocale = options?.lng ?? locale;
117
- let dictionary;
118
- if (dictionaryContent !== void 0 && targetNamespace === namespace && options?.lng === void 0) dictionary = dictionaryContent;
119
- else {
120
- dictionary = getDictionaryOrUndefined(targetNamespace, resolvedLocale);
121
- if (dictionary === void 0 && targetNamespace === namespace && targetNamespace !== ROOT_DICTIONARY_KEY) dictionary = getDictionaryOrUndefined(ROOT_DICTIONARY_KEY, resolvedLocale);
122
- if (dictionary === void 0) return void 0;
123
- }
198
+ const primaryDictionaryContent = options?.lng === void 0 ? dictionaryContent : void 0;
199
+ const requestedNamespaceCount = getNamespaceCount(requestedNamespaces);
200
+ const namespaceCount = requestedNamespaceCount + getNamespaceCount(fallbackNamespaces);
201
+ let keyCandidates;
124
202
  let resolvedValue;
125
- for (const candidate of buildKeyCandidates(path, options?.lng ?? locale, count, context, ordinal)) {
126
- const value = navigatePath(dictionary, candidate, keySeparator);
127
- if (value !== null && value !== void 0) {
203
+ let resolvedNamespace;
204
+ for (let namespaceIndex = 0; namespaceIndex < namespaceCount && resolvedNamespace === void 0; namespaceIndex++) {
205
+ const isFallbackNamespace = namespaceIndex >= requestedNamespaceCount;
206
+ const candidateNamespace = isFallbackNamespace ? getNamespaceAt(fallbackNamespaces, namespaceIndex - requestedNamespaceCount) : getNamespaceAt(requestedNamespaces, namespaceIndex);
207
+ if (isFallbackNamespace && hasNamespace(requestedNamespaces, candidateNamespace)) continue;
208
+ const dictionary = getNamespaceDictionary(candidateNamespace, namespace, resolvedLocale, primaryDictionaryContent);
209
+ if (dictionary === void 0) continue;
210
+ keyCandidates ??= buildKeyCandidates(path, resolvedLocale, count, context, ordinal);
211
+ const value = findKeyCandidate(dictionary, keyCandidates, keySeparator);
212
+ if (value !== void 0) {
128
213
  resolvedValue = value;
129
- break;
214
+ resolvedNamespace = candidateNamespace;
130
215
  }
131
216
  }
132
- if (resolvedValue === null || resolvedValue === void 0) return void 0;
217
+ if (resolvedNamespace === void 0) return void 0;
133
218
  if (options?.returnObjects && typeof resolvedValue === "object" && resolvedValue !== null) return resolvedValue;
134
- const values = getInterpolationValues(options);
135
- let resolved = resolveMessageNodeToString(resolvedValue, values, options?.lng ?? locale);
219
+ const values = getInterpolationValues(options, escapeValue);
220
+ let resolved = resolveMessageNodeToString(resolvedValue, values, resolvedLocale);
136
221
  if (depth < MAX_NESTING_DEPTH && resolved.includes("$t(")) resolved = resolved.replace(/\$t\(\s*([^),]+?)\s*(?:,[^)]*)?\)/g, (match, nestedKey) => {
137
222
  const nestedValue = resolveTranslation({
138
223
  locale,
139
- namespace: targetNamespace,
224
+ namespace: resolvedNamespace,
140
225
  key: nestedKey.trim(),
141
226
  options,
142
227
  keySeparator,
143
228
  nsSeparator,
229
+ fallbackNamespaces,
230
+ escapeValue,
144
231
  depth: depth + 1,
145
- dictionaryContent: targetNamespace === namespace ? dictionaryContent : void 0
232
+ dictionaryContent: resolvedNamespace === getNamespaceAt(namespace, 0) ? dictionaryContent : void 0
146
233
  });
147
234
  return typeof nestedValue === "string" ? nestedValue : match;
148
235
  });
149
236
  return resolved;
150
237
  };
151
238
 
152
- export { getInterpolationValues, resolveTranslation };
239
+ export { getInterpolationValues, resolveTranslation, toNamespaceList };
153
240
  //# sourceMappingURL=resolveTranslation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolveTranslation.mjs","names":[],"sources":["../../src/resolveTranslation.ts"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n navigatePath,\n resolveMessageNodeToString,\n} from '@intlayer/core/messageFormat';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { TOptions } from 'i18next';\n\n/**\n * Shared i18next-dialect translation resolution.\n *\n * Implements the i18next lookup pipeline on top of intlayer dictionaries:\n * namespace prefix (`ns:key`), `ns` option override, plural suffixes\n * (`key_one`, `key_other`, …) via `Intl.PluralRules`, context suffixes\n * (`key_male`), `$t()` nesting, `defaultValue` and `{{var}}` interpolation.\n *\n * Used by `@intlayer/i18next` (instance `t`) and `@intlayer/react-i18next`\n * (`useTranslation`, `<Trans>`).\n */\n\n/** Option keys that are control flags, never interpolation values. */\nconst CONTROL_OPTION_KEYS = new Set([\n 'defaultValue',\n 'ns',\n 'lng',\n 'lngs',\n 'fallbackLng',\n 'returnObjects',\n 'returnDetails',\n 'keySeparator',\n 'nsSeparator',\n 'ordinal',\n 'postProcess',\n 'postProcessPassResolved',\n 'interpolation',\n 'replace',\n 'joinArrays',\n 'nsMode',\n 'keyPrefix',\n]);\n\n/** Maximum `$t()` nesting recursion depth. */\nconst MAX_NESTING_DEPTH = 5;\n\n/**\n * Canonical key of the single dictionary produced when a JSON source pattern\n * has no `{{key}}` segment (one file holds the whole namespace, e.g.\n * `./src/i18n/{{locale}}.json`). Used as the fallback namespace so i18next's\n * default `translation` namespace resolves against the whole-file dictionary.\n */\nconst ROOT_DICTIONARY_KEY = 'index';\n\n/**\n * Reads a dictionary from the runtime registry, returning `undefined` when the\n * namespace is not a registered dictionary.\n *\n * `getIntlayer` never throws for a missing key — in development it returns a\n * path-stringifying fallback proxy — so a plain `getIntlayer` call cannot tell\n * \"missing namespace\" apart from \"resolved content\". The registry membership\n * check makes the distinction explicit before resolving.\n */\nconst getDictionaryOrUndefined = (\n namespace: DictionaryKeys,\n locale: LocalesValues\n): unknown => {\n if (!(namespace in getDictionaries())) return undefined;\n\n return getIntlayer(namespace, locale);\n};\n\n/**\n * Builds the ordered list of key candidates following i18next's resolution\n * order: context + plural → context → plural → exact key.\n */\nconst buildKeyCandidates = (\n path: string,\n locale: string,\n count: number | undefined,\n context: string | undefined,\n ordinal: boolean\n): string[] => {\n const candidates: string[] = [];\n\n const pluralCategory =\n count === undefined\n ? undefined\n : new Intl.PluralRules(locale, {\n type: ordinal ? 'ordinal' : 'cardinal',\n }).select(count);\n\n if (context) {\n if (pluralCategory) {\n if (ordinal) {\n candidates.push(`${path}_${context}_ordinal_${pluralCategory}`);\n }\n candidates.push(`${path}_${context}_${pluralCategory}`);\n if (count !== 1) candidates.push(`${path}_${context}_plural`);\n }\n candidates.push(`${path}_${context}`);\n }\n\n if (pluralCategory) {\n if (ordinal) candidates.push(`${path}_ordinal_${pluralCategory}`);\n candidates.push(`${path}_${pluralCategory}`);\n // Legacy i18next v3 JSON suffix\n if (count !== 1) candidates.push(`${path}_plural`);\n }\n\n candidates.push(path);\n\n return candidates;\n};\n\n/** Extracts interpolation values from i18next `t()` options. */\nexport const getInterpolationValues = (options?: TOptions): MessageValues => {\n if (!options || typeof options !== 'object') return {};\n\n const replace = (options as { replace?: MessageValues }).replace;\n if (replace) {\n // `count` and `context` are always interpolatable, even with `replace`\n const values: MessageValues = { ...replace };\n if (options.count !== undefined) values.count ??= options.count;\n if (options.context !== undefined) values.context ??= options.context;\n return values;\n }\n\n const values: MessageValues = {};\n for (const [optionKey, optionValue] of Object.entries(options)) {\n if (!CONTROL_OPTION_KEYS.has(optionKey)) values[optionKey] = optionValue;\n }\n return values;\n};\n\nexport type ResolveTranslationParams = {\n /** Locale to resolve against. */\n locale: LocalesValues;\n /** Default namespace (dictionary key) when the key has no `ns:` prefix. */\n namespace: string;\n /** The translation key, possibly `ns:path.to.key`. */\n key: string;\n /** i18next `t()` options (interpolation values, count, context, …). */\n options?: TOptions;\n /** Custom key separator (`init({ keySeparator })`). */\n keySeparator?: string | false;\n /** Custom namespace separator (`init({ nsSeparator })`). */\n nsSeparator?: string | false;\n /** Internal `$t()` nesting recursion depth. */\n depth?: number;\n /**\n * Pre-resolved content of the `namespace` dictionary for `locale`.\n *\n * Supplied by the build-optimized `useDictionary` / `getDictionary`\n * variants, where the dictionary is imported at build time instead of read\n * from the runtime registry. Only used when the call resolves to the\n * default `namespace` without a locale override — cross-namespace\n * (`other:key`, `{ ns }`) and `{ lng }` lookups still go through\n * `getIntlayer`.\n */\n dictionaryContent?: unknown;\n};\n\n/**\n * Resolves a single translation key the i18next way against intlayer\n * dictionaries.\n *\n * Returns the resolved value: a string in the common case, or an\n * object/array when `returnObjects: true`. Returns `undefined` when the key\n * cannot be resolved (caller decides between `defaultValue`, fallback keys\n * and key echo).\n */\nexport const resolveTranslation = ({\n locale,\n namespace,\n key,\n options,\n keySeparator = '.',\n nsSeparator = ':',\n depth = 0,\n dictionaryContent,\n}: ResolveTranslationParams): unknown => {\n // Namespace resolution: `ns:` prefix > `ns` option > default namespace\n let targetNamespace = namespace;\n let path = key;\n\n if (nsSeparator !== false && key.includes(nsSeparator)) {\n const separatorIndex = key.indexOf(nsSeparator);\n targetNamespace = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + nsSeparator.length);\n } else if (options?.ns) {\n targetNamespace = Array.isArray(options.ns)\n ? (options.ns[0] as string)\n : (options.ns as string);\n }\n\n const count = typeof options?.count === 'number' ? options.count : undefined;\n const context =\n options?.context !== undefined ? String(options.context) : undefined;\n const ordinal = options?.ordinal === true;\n\n const resolvedLocale = ((options?.lng as string) ?? locale) as LocalesValues;\n\n let dictionary: unknown;\n if (\n dictionaryContent !== undefined &&\n targetNamespace === namespace &&\n options?.lng === undefined\n ) {\n dictionary = dictionaryContent;\n } else {\n dictionary = getDictionaryOrUndefined(\n targetNamespace as DictionaryKeys,\n resolvedLocale\n );\n\n // i18next's default namespace is `translation`, but a single-file JSON\n // source (no `{{key}}` segment) is loaded as the root `index` dictionary.\n // When the *default* namespace is not itself a registered dictionary, fall\n // back to `index` so `t('login.heroSubtitle')` resolves against the\n // whole-file dictionary. Explicit `ns:` prefixes / `ns` options never fall\n // back, so a genuinely missing namespace still returns `undefined`.\n if (\n dictionary === undefined &&\n targetNamespace === namespace &&\n targetNamespace !== ROOT_DICTIONARY_KEY\n ) {\n dictionary = getDictionaryOrUndefined(\n ROOT_DICTIONARY_KEY as DictionaryKeys,\n resolvedLocale\n );\n }\n\n if (dictionary === undefined) return undefined;\n }\n\n let resolvedValue: unknown;\n for (const candidate of buildKeyCandidates(\n path,\n (options?.lng as string) ?? (locale as string),\n count,\n context,\n ordinal\n )) {\n const value = navigatePath(dictionary, candidate, keySeparator);\n if (value !== null && value !== undefined) {\n resolvedValue = value;\n break;\n }\n }\n\n if (resolvedValue === null || resolvedValue === undefined) return undefined;\n\n // `returnObjects: true` — return the raw subtree\n if (\n options?.returnObjects &&\n typeof resolvedValue === 'object' &&\n resolvedValue !== null\n ) {\n return resolvedValue;\n }\n\n const values = getInterpolationValues(options);\n\n // Dictionary content was converted to intlayer nodes at build time, so no\n // i18next parser is needed here — which keeps it out of the app bundle.\n let resolved = resolveMessageNodeToString(\n resolvedValue,\n values,\n ((options?.lng as string) ?? locale) as LocalesValues\n );\n\n // `$t(key)` nesting\n if (depth < MAX_NESTING_DEPTH && resolved.includes('$t(')) {\n resolved = resolved.replace(\n /\\$t\\(\\s*([^),]+?)\\s*(?:,[^)]*)?\\)/g,\n (match, nestedKey: string) => {\n const nestedValue = resolveTranslation({\n locale,\n namespace: targetNamespace,\n key: nestedKey.trim(),\n options,\n keySeparator,\n nsSeparator,\n depth: depth + 1,\n dictionaryContent:\n targetNamespace === namespace ? dictionaryContent : undefined,\n });\n return typeof nestedValue === 'string' ? nestedValue : match;\n }\n );\n }\n\n return resolved;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,oBAAoB;;;;;;;AAQ1B,MAAM,sBAAsB;;;;;;;;;;AAW5B,MAAM,4BACJ,WACA,WACY;CACZ,IAAI,EAAE,aAAa,gBAAgB,IAAI,OAAO;CAE9C,OAAO,YAAY,WAAW,MAAM;AACtC;;;;;AAMA,MAAM,sBACJ,MACA,QACA,OACA,SACA,YACa;CACb,MAAM,aAAuB,CAAC;CAE9B,MAAM,iBACJ,UAAU,SACN,SACA,IAAI,KAAK,YAAY,QAAQ,EAC3B,MAAM,UAAU,YAAY,WAC9B,CAAC,CAAC,CAAC,OAAO,KAAK;CAErB,IAAI,SAAS;EACX,IAAI,gBAAgB;GAClB,IAAI,SACF,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,WAAW,gBAAgB;GAEhE,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,gBAAgB;GACtD,IAAI,UAAU,GAAG,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,QAAQ;EAC9D;EACA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,OAAO,IAAI;CAC7D,MAAM,UAAU,SAAS,YAAY;CAErC,MAAM,iBAAmB,SAAS,OAAkB;CAEpD,IAAI;CACJ,IACE,sBAAsB,UACtB,oBAAoB,aACpB,SAAS,QAAQ,QAEjB,aAAa;MACR;EACL,aAAa,yBACX,iBACA,cACF;EAQA,IACE,eAAe,UACf,oBAAoB,aACpB,oBAAoB,qBAEpB,aAAa,yBACX,qBACA,cACF;EAGF,IAAI,eAAe,QAAW,OAAO;CACvC;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,mBACtB,MACC,SAAS,OAAmB,QAC7B,OACA,SACA,OACF,GAAG;EACD,MAAM,QAAQ,aAAa,YAAY,WAAW,YAAY;EAC9D,IAAI,UAAU,QAAQ,UAAU,QAAW;GACzC,gBAAgB;GAChB;EACF;CACF;CAEA,IAAI,kBAAkB,QAAQ,kBAAkB,QAAW,OAAO;CAGlE,IACE,SAAS,iBACT,OAAO,kBAAkB,YACzB,kBAAkB,MAElB,OAAO;CAGT,MAAM,SAAS,uBAAuB,OAAO;CAI7C,IAAI,WAAW,2BACb,eACA,QACE,SAAS,OAAkB,MAC/B;CAGA,IAAI,QAAQ,qBAAqB,SAAS,SAAS,KAAK,GACtD,WAAW,SAAS,QAClB,uCACC,OAAO,cAAsB;EAC5B,MAAM,cAAc,mBAAmB;GACrC;GACA,WAAW;GACX,KAAK,UAAU,KAAK;GACpB;GACA;GACA;GACA,OAAO,QAAQ;GACf,mBACE,oBAAoB,YAAY,oBAAoB;EACxD,CAAC;EACD,OAAO,OAAO,gBAAgB,WAAW,cAAc;CACzD,CACF;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"resolveTranslation.mjs","names":[],"sources":["../../src/resolveTranslation.ts"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n navigatePath,\n resolveMessageNodeToString,\n} from '@intlayer/core/messageFormat';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { TOptions } from 'i18next';\n\n/**\n * Shared i18next-dialect translation resolution.\n *\n * Implements the i18next lookup pipeline on top of intlayer dictionaries:\n * namespace prefix (`ns:key`), `ns` option override, fallback namespaces\n * (`fallbackNS`), plural suffixes (`key_one`, `key_other`, …) via\n * `Intl.PluralRules`, context suffixes (`key_male`), `$t()` nesting,\n * `defaultValue` and `{{var}}` interpolation with optional value escaping.\n *\n * Used by `@intlayer/i18next` (instance `t`) and `@intlayer/react-i18next`\n * (`useTranslation`, `<Trans>`).\n */\n\n/** Option keys that are control flags, never interpolation values. */\nconst CONTROL_OPTION_KEYS = new Set([\n 'defaultValue',\n 'ns',\n 'lng',\n 'lngs',\n 'fallbackLng',\n 'returnObjects',\n 'returnDetails',\n 'keySeparator',\n 'nsSeparator',\n 'ordinal',\n 'postProcess',\n 'postProcessPassResolved',\n 'interpolation',\n 'replace',\n 'joinArrays',\n 'nsMode',\n 'keyPrefix',\n]);\n\n/** Maximum `$t()` nesting recursion depth. */\nconst MAX_NESTING_DEPTH = 5;\n\n/** Characters i18next replaces in interpolated values when `escapeValue` is on. */\nconst HTML_ESCAPE_ENTITIES: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n};\n\n/**\n * Prefix of i18next's unescaped placeholder. The build normalizes\n * `{{- name}}` to `{{-name}}`, so every value is also exposed, never escaped,\n * under `-name`.\n */\nconst UNESCAPED_VALUE_PREFIX = '-';\n\n/**\n * Escapes a value the way i18next's `escapeValue` does — strings, including\n * those nested in arrays and plain objects (`{{user.name}}`).\n */\nconst escapeInterpolationValue = (value: unknown): unknown => {\n if (typeof value === 'string') {\n return value.replace(\n /[&<>\"']/g,\n (character) => HTML_ESCAPE_ENTITIES[character] ?? character\n );\n }\n\n if (Array.isArray(value)) return value.map(escapeInterpolationValue);\n\n if (\n value !== null &&\n typeof value === 'object' &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n return Object.fromEntries(\n Object.entries(value).map(([entryKey, entryValue]) => [\n entryKey,\n escapeInterpolationValue(entryValue),\n ])\n );\n }\n\n return value;\n};\n\n/**\n * Normalizes an i18next namespace option (`ns`, `defaultNS`, `fallbackNS`),\n * which can be a string, an array or `false`, into a list.\n */\nexport const toNamespaceList = (namespaces: unknown): string[] => {\n if (!namespaces) return [];\n\n return (Array.isArray(namespaces) ? namespaces : [namespaces]) as string[];\n};\n\n/** An i18next namespace option as written: a string, a list or `false`. */\nexport type NamespaceOption = string | readonly string[] | false | undefined;\n\n/** Number of namespaces in a namespace option, without copying it. */\nconst getNamespaceCount = (namespaces: NamespaceOption): number => {\n if (!namespaces) return 0;\n\n return typeof namespaces === 'string' ? 1 : namespaces.length;\n};\n\n/** Namespace at `index` of a non-empty namespace option. */\nconst getNamespaceAt = (\n namespaces: string | readonly string[],\n index: number\n): string =>\n typeof namespaces === 'string' ? namespaces : (namespaces[index] as string);\n\n/** Whether a namespace option lists `namespace`. */\nconst hasNamespace = (\n namespaces: NamespaceOption,\n namespace: string\n): boolean => {\n if (!namespaces) return false;\n\n return typeof namespaces === 'string'\n ? namespaces === namespace\n : namespaces.includes(namespace);\n};\n\n/**\n * Canonical key of the single dictionary produced when a JSON source pattern\n * has no `{{key}}` segment (one file holds the whole namespace, e.g.\n * `./src/i18n/{{locale}}.json`). Used as the fallback namespace so i18next's\n * default `translation` namespace resolves against the whole-file dictionary.\n */\nconst ROOT_DICTIONARY_KEY = 'index';\n\n/**\n * Reads a dictionary from the runtime registry, returning `undefined` when the\n * namespace is not a registered dictionary.\n *\n * `getIntlayer` never throws for a missing key — in development it returns a\n * path-stringifying fallback proxy — so a plain `getIntlayer` call cannot tell\n * \"missing namespace\" apart from \"resolved content\". The registry membership\n * check makes the distinction explicit before resolving.\n */\nconst getDictionaryOrUndefined = (\n namespace: DictionaryKeys,\n locale: LocalesValues\n): unknown => {\n if (!(namespace in getDictionaries())) return undefined;\n\n return getIntlayer(namespace, locale);\n};\n\n/**\n * Dictionary searched for one namespace, `undefined` when unregistered.\n *\n * `primaryDictionaryContent` is the pre-resolved content of the first default\n * namespace, when the call may use it.\n */\nconst getNamespaceDictionary = (\n candidateNamespace: string,\n defaultNamespaces: string | readonly string[],\n locale: LocalesValues,\n primaryDictionaryContent: unknown\n): unknown => {\n if (\n primaryDictionaryContent !== undefined &&\n candidateNamespace === getNamespaceAt(defaultNamespaces, 0)\n ) {\n return primaryDictionaryContent;\n }\n\n const dictionary = getDictionaryOrUndefined(\n candidateNamespace as DictionaryKeys,\n locale\n );\n\n // i18next's default namespace is `translation`, but a single-file JSON\n // source (no `{{key}}` segment) is loaded as the root `index` dictionary.\n // When a *default* namespace is not itself a registered dictionary, fall\n // back to `index` so `t('login.heroSubtitle')` resolves against the\n // whole-file dictionary. Other namespaces (`ns:` prefix, `ns` option,\n // fallback namespaces) never do, so a genuinely missing one is skipped.\n if (\n dictionary === undefined &&\n candidateNamespace !== ROOT_DICTIONARY_KEY &&\n hasNamespace(defaultNamespaces, candidateNamespace)\n ) {\n return getDictionaryOrUndefined(\n ROOT_DICTIONARY_KEY as DictionaryKeys,\n locale\n );\n }\n\n return dictionary;\n};\n\n/** Value of the first key candidate found in `dictionary`. */\nconst findKeyCandidate = (\n dictionary: unknown,\n keyCandidates: readonly string[],\n keySeparator: string | false\n): unknown => {\n for (const candidateKey of keyCandidates) {\n const value = navigatePath(dictionary, candidateKey, keySeparator);\n if (value !== null && value !== undefined) return value;\n }\n\n return undefined;\n};\n\n/**\n * Builds the ordered list of key candidates following i18next's resolution\n * order: context + plural → context → plural → exact key.\n */\nconst buildKeyCandidates = (\n path: string,\n locale: string,\n count: number | undefined,\n context: string | undefined,\n ordinal: boolean\n): string[] => {\n const candidates: string[] = [];\n\n const pluralCategory =\n count === undefined\n ? undefined\n : new Intl.PluralRules(locale, {\n type: ordinal ? 'ordinal' : 'cardinal',\n }).select(count);\n\n if (context) {\n if (pluralCategory) {\n if (ordinal) {\n candidates.push(`${path}_${context}_ordinal_${pluralCategory}`);\n }\n candidates.push(`${path}_${context}_${pluralCategory}`);\n if (count !== 1) candidates.push(`${path}_${context}_plural`);\n }\n candidates.push(`${path}_${context}`);\n }\n\n if (pluralCategory) {\n if (ordinal) candidates.push(`${path}_ordinal_${pluralCategory}`);\n candidates.push(`${path}_${pluralCategory}`);\n // Legacy i18next v3 JSON suffix\n if (count !== 1) candidates.push(`${path}_plural`);\n }\n\n candidates.push(path);\n\n return candidates;\n};\n\n/** Whether an interpolation value is absent (`null` or `undefined`). */\nconst isMissingValue = (value: unknown): boolean =>\n value === undefined || value === null;\n\n/**\n * Sets one interpolation value, escaped when asked, and its raw `-name` alias\n * read by `{{- name}}` placeholders.\n */\nconst setInterpolationValue = (\n values: MessageValues,\n valueName: string,\n value: unknown,\n shouldEscape: boolean\n): void => {\n values[valueName] = shouldEscape ? escapeInterpolationValue(value) : value;\n values[`${UNESCAPED_VALUE_PREFIX}${valueName}`] = value;\n};\n\n/**\n * Extracts interpolation values from i18next `t()` options.\n *\n * With `escapeValue` (overridden per call by `interpolation.escapeValue`),\n * values are HTML-escaped like i18next does; each value stays reachable\n * unescaped as `-name` for `{{- name}}` placeholders.\n */\nexport const getInterpolationValues = (\n options?: TOptions,\n escapeValue = false\n): MessageValues => {\n if (!options || typeof options !== 'object') return {};\n\n const shouldEscape = options.interpolation?.escapeValue ?? escapeValue;\n const values: MessageValues = {};\n const replace = (options as { replace?: MessageValues }).replace;\n\n if (replace) {\n for (const valueName of Object.keys(replace)) {\n setInterpolationValue(\n values,\n valueName,\n replace[valueName],\n shouldEscape\n );\n }\n\n // `count` and `context` are always interpolatable, even with `replace`\n if (options.count !== undefined && isMissingValue(values.count)) {\n setInterpolationValue(values, 'count', options.count, shouldEscape);\n }\n if (options.context !== undefined && isMissingValue(values.context)) {\n setInterpolationValue(values, 'context', options.context, shouldEscape);\n }\n return values;\n }\n\n for (const optionKey of Object.keys(options)) {\n if (!CONTROL_OPTION_KEYS.has(optionKey)) {\n setInterpolationValue(\n values,\n optionKey,\n (options as Record<string, unknown>)[optionKey],\n shouldEscape\n );\n }\n }\n return values;\n};\n\nexport type ResolveTranslationParams = {\n /** Locale to resolve against. */\n locale: LocalesValues;\n /**\n * Default namespace (dictionary key) when the key has no `ns:` prefix. A\n * list (i18next `defaultNS` array) is tried in order.\n */\n namespace: string | readonly string[];\n /**\n * Namespaces tried, in order, after the requested ones: i18next's\n * `fallbackNS` as written (a string, a list or `false`). Like i18next, they\n * also apply to `ns:` prefixes and the `ns` option.\n */\n fallbackNamespaces?: NamespaceOption;\n /**\n * HTML-escapes interpolated values (i18next `interpolation.escapeValue`).\n * Defaults to `false`; a per-call `interpolation.escapeValue` wins.\n */\n escapeValue?: boolean;\n /** The translation key, possibly `ns:path.to.key`. */\n key: string;\n /** i18next `t()` options (interpolation values, count, context, …). */\n options?: TOptions;\n /** Custom key separator (`init({ keySeparator })`). */\n keySeparator?: string | false;\n /** Custom namespace separator (`init({ nsSeparator })`). */\n nsSeparator?: string | false;\n /** Internal `$t()` nesting recursion depth. */\n depth?: number;\n /**\n * Pre-resolved content of the (first) `namespace` dictionary for `locale`.\n *\n * Supplied by the build-optimized `useDictionary` / `getDictionary`\n * variants, where the dictionary is imported at build time instead of read\n * from the runtime registry. Only used when the call resolves to the\n * default `namespace` without a locale override — cross-namespace\n * (`other:key`, `{ ns }`, fallback namespaces) and `{ lng }` lookups still\n * go through `getIntlayer`.\n */\n dictionaryContent?: unknown;\n};\n\n/**\n * Resolves a single translation key the i18next way against intlayer\n * dictionaries.\n *\n * Returns the resolved value: a string in the common case, or an\n * object/array when `returnObjects: true`. Returns `undefined` when the key\n * cannot be resolved (caller decides between `defaultValue`, fallback keys\n * and key echo).\n */\nexport const resolveTranslation = ({\n locale,\n namespace,\n key,\n options,\n keySeparator = '.',\n nsSeparator = ':',\n fallbackNamespaces,\n escapeValue = false,\n depth = 0,\n dictionaryContent,\n}: ResolveTranslationParams): unknown => {\n // Namespace resolution: `ns:` prefix > `ns` option > default namespaces.\n // The fallback namespaces are searched after them in every case, as\n // i18next does. Options are read as written, so no list is copied.\n let requestedNamespaces: string | readonly string[] = namespace;\n let path = key;\n\n if (nsSeparator !== false && key.includes(nsSeparator)) {\n const separatorIndex = key.indexOf(nsSeparator);\n requestedNamespaces = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + nsSeparator.length);\n } else if (options?.ns) {\n requestedNamespaces = options.ns as string | readonly string[];\n }\n\n const count = typeof options?.count === 'number' ? options.count : undefined;\n const context =\n options?.context !== undefined ? String(options.context) : undefined;\n const ordinal = options?.ordinal === true;\n\n const resolvedLocale = ((options?.lng as string) ?? locale) as LocalesValues;\n const primaryDictionaryContent =\n options?.lng === undefined ? dictionaryContent : undefined;\n\n const requestedNamespaceCount = getNamespaceCount(requestedNamespaces);\n const namespaceCount =\n requestedNamespaceCount + getNamespaceCount(fallbackNamespaces);\n\n let keyCandidates: string[] | undefined;\n let resolvedValue: unknown;\n let resolvedNamespace: string | undefined;\n\n for (\n let namespaceIndex = 0;\n namespaceIndex < namespaceCount && resolvedNamespace === undefined;\n namespaceIndex++\n ) {\n const isFallbackNamespace = namespaceIndex >= requestedNamespaceCount;\n const candidateNamespace = isFallbackNamespace\n ? getNamespaceAt(\n fallbackNamespaces as string | readonly string[],\n namespaceIndex - requestedNamespaceCount\n )\n : getNamespaceAt(requestedNamespaces, namespaceIndex);\n\n // A fallback namespace that was already requested has been searched\n if (\n isFallbackNamespace &&\n hasNamespace(requestedNamespaces, candidateNamespace)\n ) {\n continue;\n }\n\n const dictionary = getNamespaceDictionary(\n candidateNamespace,\n namespace,\n resolvedLocale,\n primaryDictionaryContent\n );\n if (dictionary === undefined) continue;\n\n keyCandidates ??= buildKeyCandidates(\n path,\n resolvedLocale as string,\n count,\n context,\n ordinal\n );\n\n const value = findKeyCandidate(dictionary, keyCandidates, keySeparator);\n if (value !== undefined) {\n resolvedValue = value;\n resolvedNamespace = candidateNamespace;\n }\n }\n\n if (resolvedNamespace === undefined) return undefined;\n\n // `returnObjects: true` — return the raw subtree\n if (\n options?.returnObjects &&\n typeof resolvedValue === 'object' &&\n resolvedValue !== null\n ) {\n return resolvedValue;\n }\n\n const values = getInterpolationValues(options, escapeValue);\n\n // Dictionary content was converted to intlayer nodes at build time, so no\n // i18next parser is needed here — which keeps it out of the app bundle.\n let resolved = resolveMessageNodeToString(\n resolvedValue,\n values,\n resolvedLocale\n );\n\n // `$t(key)` nesting\n if (depth < MAX_NESTING_DEPTH && resolved.includes('$t(')) {\n resolved = resolved.replace(\n /\\$t\\(\\s*([^),]+?)\\s*(?:,[^)]*)?\\)/g,\n (match, nestedKey: string) => {\n const nestedValue = resolveTranslation({\n locale,\n namespace: resolvedNamespace,\n key: nestedKey.trim(),\n options,\n keySeparator,\n nsSeparator,\n fallbackNamespaces,\n escapeValue,\n depth: depth + 1,\n dictionaryContent:\n resolvedNamespace === getNamespaceAt(namespace, 0)\n ? dictionaryContent\n : undefined,\n });\n return typeof nestedValue === 'string' ? nestedValue : match;\n }\n );\n }\n\n return resolved;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,oBAAoB;;AAG1B,MAAM,uBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;AACP;;;;;;AAOA,MAAM,yBAAyB;;;;;AAM/B,MAAM,4BAA4B,UAA4B;CAC5D,IAAI,OAAO,UAAU,UACnB,OAAO,MAAM,QACX,aACC,cAAc,qBAAqB,cAAc,SACpD;CAGF,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,wBAAwB;CAEnE,IACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAO,eAAe,KAAK,MAAM,OAAO,WAExC,OAAO,OAAO,YACZ,OAAO,Q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SACA,OACF;EAEA,MAAM,QAAQ,iBAAiB,YAAY,eAAe,YAAY;EACtE,IAAI,UAAU,QAAW;GACvB,gBAAgB;GAChB,oBAAoB;EACtB;CACF;CAEA,IAAI,sBAAsB,QAAW,OAAO;CAG5C,IACE,SAAS,iBACT,OAAO,kBAAkB,YACzB,kBAAkB,MAElB,OAAO;CAGT,MAAM,SAAS,uBAAuB,SAAS,WAAW;CAI1D,IAAI,WAAW,2BACb,eACA,QACA,cACF;CAGA,IAAI,QAAQ,qBAAqB,SAAS,SAAS,KAAK,GACtD,WAAW,SAAS,QAClB,uCACC,OAAO,cAAsB;EAC5B,MAAM,cAAc,mBAAmB;GACrC;GACA,WAAW;GACX,KAAK,UAAU,KAAK;GACpB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,mBACE,sBAAsB,eAAe,WAAW,CAAC,IAC7C,oBACA;EACR,CAAC;EACD,OAAO,OAAO,gBAAgB,WAAW,cAAc;CACzD,CACF;CAGF,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"createInstance.d.ts","names":["_createInstance"],"sources":["../../src/createInstance.ts"],"mappings":";qBAkCa,uBAAuBA"}
1
+ {"version":3,"file":"createInstance.d.ts","names":["_createInstance"],"sources":["../../src/createInstance.ts"],"mappings":";qBAwDa,uBAAuBA"}
@@ -1,8 +1,8 @@
1
1
  import { createInstance } from "./createInstance.js";
2
- import { ContentAtPath, ScopedDotPaths, ScopedTFunction, TranslatedValue, TypedGetFixedT, TypedTFunction } from "./typedTranslation.js";
2
+ import { ContentAtPath, FallbackNamespaceKeys, ResolvedNamespace, ScopedDotPaths, ScopedTFunction, TranslatedValue, TranslationKey, TypedGetFixedT, TypedTFunction } from "./typedTranslation.js";
3
3
  import { getDictionary } from "./getDictionary.js";
4
4
  import { getDictionaryDynamic } from "./getDictionaryDynamic.js";
5
- import { ResolveTranslationParams, getInterpolationValues, resolveTranslation } from "./resolveTranslation.js";
5
+ import { ResolveTranslationParams, getInterpolationValues, resolveTranslation, toNamespaceList } from "./resolveTranslation.js";
6
6
  import { InitOptions, TFunction, TOptions, changeLanguage as changeLanguage$1, dir as dir$1, exists as exists$1, hasLoadedNamespace as hasLoadedNamespace$1, i18n, i18n as i18n$1, init as init$1, loadLanguages as loadLanguages$1, loadNamespaces as loadNamespaces$1, loadResources as loadResources$1, reloadResources as reloadResources$1, setDefaultNamespace as setDefaultNamespace$1, t as t$1, use as use$1 } from "i18next";
7
7
  declare const i18next: i18n$1;
8
8
  export declare const dir: typeof dir$1;
@@ -36,5 +36,5 @@ export declare const loadLanguages: typeof loadLanguages$1;
36
36
  * provided to keep `.keyFromSelector(...)` call-sites working.
37
37
  */
38
38
  export declare const keyFromSelector: (selector: unknown) => unknown;
39
- export { type ContentAtPath, type InitOptions, type ResolveTranslationParams, type ScopedDotPaths, type ScopedTFunction, type TFunction, type TOptions, type TranslatedValue, type TypedGetFixedT, type TypedTFunction, createInstance, i18next as default, i18next, getDictionary, getDictionaryDynamic, getInterpolationValues, type i18n, resolveTranslation };
39
+ export { type ContentAtPath, type FallbackNamespaceKeys, type InitOptions, type ResolveTranslationParams, type ResolvedNamespace, type ScopedDotPaths, type ScopedTFunction, type TFunction, type TOptions, type TranslatedValue, type TranslationKey, type TypedGetFixedT, type TypedTFunction, createInstance, i18next as default, i18next, getDictionary, getDictionaryDynamic, getInterpolationValues, type i18n, resolveTranslation, toNamespaceList };
40
40
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["i18n","_dir","_init","_loadResources","_reloadResources","_use","_changeLanguage","_t","_exists","_setDefaultNamespace","_hasLoadedNamespace","_loadNamespaces","_loadLanguages"],"sources":["../../src/index.ts"],"mappings":";;;;;;cAkCM,SAASA;qBAMF,YAAYC;qBACZ,aAAaC;qBACb,sBAAsBC;qBAEtB,wBAAwBC;qBAExB,YAAYC;qBACZ,uBAAuBC;;;;;;;;;;;;;qBAevB,WAAW;qBAIX,UAAUC;qBACV,eAAeC;qBACf,4BAA4BC;qBAE5B,2BAA2BC;qBAE3B,uBAAuBC;qBAEvB,sBAAsBC;;;;;;qBAQtB,kBAAe"}
1
+ {"version":3,"file":"index.d.ts","names":["i18n","_dir","_init","_loadResources","_reloadResources","_use","_changeLanguage","_t","_exists","_setDefaultNamespace","_hasLoadedNamespace","_loadNamespaces","_loadLanguages"],"sources":["../../src/index.ts"],"mappings":";;;;;;cAsCM,SAASA;qBAMF,YAAYC;qBACZ,aAAaC;qBACb,sBAAsBC;qBAEtB,wBAAwBC;qBAExB,YAAYC;qBACZ,uBAAuBC;;;;;;;;;;;;;qBAevB,WAAW;qBAIX,UAAUC;qBACV,eAAeC;qBACf,4BAA4BC;qBAE5B,2BAA2BC;qBAE3B,uBAAuBC;qBAEvB,sBAAsBC;;;;;;qBAQtB,kBAAe"}
@@ -1,13 +1,40 @@
1
1
  import { LocalesValues } from "@intlayer/types/module_augmentation";
2
2
  import { TOptions } from "i18next";
3
3
  import { MessageValues } from "@intlayer/core/messageFormat";
4
- /** Extracts interpolation values from i18next `t()` options. */
5
- export declare const getInterpolationValues: (options?: TOptions) => MessageValues;
4
+ /**
5
+ * Normalizes an i18next namespace option (`ns`, `defaultNS`, `fallbackNS`),
6
+ * which can be a string, an array or `false`, into a list.
7
+ */
8
+ export declare const toNamespaceList: (namespaces: unknown) => string[];
9
+ /** An i18next namespace option as written: a string, a list or `false`. */
10
+ export type NamespaceOption = string | readonly string[] | false | undefined;
11
+ /**
12
+ * Extracts interpolation values from i18next `t()` options.
13
+ *
14
+ * With `escapeValue` (overridden per call by `interpolation.escapeValue`),
15
+ * values are HTML-escaped like i18next does; each value stays reachable
16
+ * unescaped as `-name` for `{{- name}}` placeholders.
17
+ */
18
+ export declare const getInterpolationValues: (options?: TOptions, escapeValue?: boolean) => MessageValues;
6
19
  export type ResolveTranslationParams = {
7
20
  /** Locale to resolve against. */
8
21
  locale: LocalesValues;
9
- /** Default namespace (dictionary key) when the key has no `ns:` prefix. */
10
- namespace: string;
22
+ /**
23
+ * Default namespace (dictionary key) when the key has no `ns:` prefix. A
24
+ * list (i18next `defaultNS` array) is tried in order.
25
+ */
26
+ namespace: string | readonly string[];
27
+ /**
28
+ * Namespaces tried, in order, after the requested ones: i18next's
29
+ * `fallbackNS` as written (a string, a list or `false`). Like i18next, they
30
+ * also apply to `ns:` prefixes and the `ns` option.
31
+ */
32
+ fallbackNamespaces?: NamespaceOption;
33
+ /**
34
+ * HTML-escapes interpolated values (i18next `interpolation.escapeValue`).
35
+ * Defaults to `false`; a per-call `interpolation.escapeValue` wins.
36
+ */
37
+ escapeValue?: boolean;
11
38
  /** The translation key, possibly `ns:path.to.key`. */
12
39
  key: string;
13
40
  /** i18next `t()` options (interpolation values, count, context, …). */
@@ -19,14 +46,14 @@ export type ResolveTranslationParams = {
19
46
  /** Internal `$t()` nesting recursion depth. */
20
47
  depth?: number;
21
48
  /**
22
- * Pre-resolved content of the `namespace` dictionary for `locale`.
49
+ * Pre-resolved content of the (first) `namespace` dictionary for `locale`.
23
50
  *
24
51
  * Supplied by the build-optimized `useDictionary` / `getDictionary`
25
52
  * variants, where the dictionary is imported at build time instead of read
26
53
  * from the runtime registry. Only used when the call resolves to the
27
54
  * default `namespace` without a locale override — cross-namespace
28
- * (`other:key`, `{ ns }`) and `{ lng }` lookups still go through
29
- * `getIntlayer`.
55
+ * (`other:key`, `{ ns }`, fallback namespaces) and `{ lng }` lookups still
56
+ * go through `getIntlayer`.
30
57
  */
31
58
  dictionaryContent?: unknown;
32
59
  };
@@ -39,5 +66,5 @@ export type ResolveTranslationParams = {
39
66
  * cannot be resolved (caller decides between `defaultValue`, fallback keys
40
67
  * and key echo).
41
68
  */
42
- export declare const resolveTranslation: ({ locale, namespace, key, options, keySeparator, nsSeparator, depth, dictionaryContent }: ResolveTranslationParams) => unknown;
69
+ export declare const resolveTranslation: ({ locale, namespace, key, options, keySeparator, nsSeparator, fallbackNamespaces, escapeValue, depth, dictionaryContent }: ResolveTranslationParams) => unknown;
43
70
  //# sourceMappingURL=resolveTranslation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolveTranslation.d.ts","names":[],"sources":["../../src/resolveTranslation.ts"],"mappings":";;;;qBAuHa,yBAAsB,UAAc,aAAW;YAmBhD;;EAEV,QAAQ;;EAER;;EAEA;;EAEA,UAAU;;EAEV;;EAEA;;EAEA;;;;;;;;;;;EAWA;;;;;;;;;;;qBAYW,uBAAkB,QAAA,WAAA,KAAA,SAAA,cAAA,aAAA,OAAA,qBAS5B"}
1
+ {"version":3,"file":"resolveTranslation.d.ts","names":[],"sources":["../../src/resolveTranslation.ts"],"mappings":";;;;;;;qBAoGa,kBAAe;;YAOhB;;;;;;;;qBAoLC,yBAAsB,UACvB,UAAQ,0BAEjB;YAwCS;;EAEV,QAAQ;;;;;EAKR;;;;;;EAMA,qBAAqB;;;;;EAKrB;;EAEA;;EAEA,UAAU;;EAEV;;EAEA;;EAEA;;;;;;;;;;;EAWA;;;;;;;;;;;qBAYW,uBAAkB,QAAA,WAAA,KAAA,SAAA,cAAA,aAAA,oBAAA,aAAA,OAAA,qBAW5B"}
@@ -1,7 +1,40 @@
1
1
  import { DictionaryKeys } from "@intlayer/types/module_augmentation";
2
2
  import { GetNestingResult } from "@intlayer/core/interpreter";
3
3
  import { ValidDotPathsFor } from "@intlayer/core/transpiler";
4
- import { TOptions } from "i18next";
4
+ import { TOptions, TypeOptions } from "i18next";
5
+ /**
6
+ * Dictionaries declared as fallback namespaces through i18next's own type
7
+ * declaration, so a key found only there type-checks as it resolves at
8
+ * runtime. `never` when nothing is declared.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * declare module 'i18next' {
13
+ * interface CustomTypeOptions {
14
+ * fallbackNS: 'common';
15
+ * }
16
+ * }
17
+ * ```
18
+ */
19
+ export type FallbackNamespaceKeys = TypeOptions extends {
20
+ fallbackNS: infer FallbackNamespace;
21
+ } ? (FallbackNamespace extends readonly (infer FallbackNamespaceEntry)[] ? FallbackNamespaceEntry : FallbackNamespace) & DictionaryKeys : never;
22
+ /** Dot-paths of every fallback dictionary. */
23
+ type FallbackDotPaths<Namespace = FallbackNamespaceKeys> = Namespace extends DictionaryKeys ? ValidDotPathsFor<Namespace> : never;
24
+ /** Dot-paths of every fallback dictionary, relative to `Prefix`. */
25
+ type FallbackScopedDotPaths<Prefix extends string, Namespace = FallbackNamespaceKeys> = Namespace extends DictionaryKeys ? ScopedDotPaths<Namespace, Prefix> : never;
26
+ /** The fallback dictionaries holding the dot-path `P`. */
27
+ type FallbackNamespaceHolding<P, Namespace = FallbackNamespaceKeys> = Namespace extends DictionaryKeys ? P extends ValidDotPathsFor<Namespace> ? Namespace : never : never;
28
+ /**
29
+ * The dictionary serving dot-path `P` for a `t()` bound to `N`: `N` when it
30
+ * declares the path, otherwise the fallback dictionary that does.
31
+ */
32
+ export type ResolvedNamespace<N extends DictionaryKeys, P> = P extends ValidDotPathsFor<N> ? N : FallbackNamespaceHolding<P>;
33
+ /**
34
+ * The dot-paths a `t()` bound to `N` accepts: its own, then the fallback
35
+ * dictionaries' ones.
36
+ */
37
+ export type TranslationKey<N extends DictionaryKeys> = ValidDotPathsFor<N> | FallbackDotPaths;
5
38
  /**
6
39
  * The interpreter-resolved content type at dot-path `P` of dictionary `N` —
7
40
  * the same type strength as the base `useIntlayer` hook.
@@ -21,30 +54,32 @@ export type ScopedDotPaths<N extends DictionaryKeys, Prefix extends string> = Va
21
54
  /**
22
55
  * Fully-typed i18next `t()` bound to the dictionary namespace `N`.
23
56
  *
24
- * Keys are validated against the dictionary's dot-paths; the return type is
25
- * resolved from the content at that path. With `returnObjects: true` the raw
26
- * content subtree is returned instead of a string.
57
+ * Keys are validated against the dictionary's dot-paths, plus the declared
58
+ * fallback dictionaries' ones ({@link FallbackNamespaceKeys}); the return type
59
+ * is resolved from the content at that path. With `returnObjects: true` the
60
+ * raw content subtree is returned instead of a string.
27
61
  */
28
62
  export type TypedTFunction<N extends DictionaryKeys> = {
29
63
  /** Returns the raw content subtree at `key` (i18next `returnObjects`). */
30
- <P extends ValidDotPathsFor<N>>(key: P | P[], options: TOptions & {
64
+ <P extends TranslationKey<N>>(key: P | P[], options: TOptions & {
31
65
  returnObjects: true;
32
- }): ContentAtPath<N, P>;
66
+ }): ContentAtPath<ResolvedNamespace<N, P> & DictionaryKeys, P>;
33
67
  /** Translate a key, with optional default value and interpolation options. */
34
- <P extends ValidDotPathsFor<N>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<N, P>;
68
+ <P extends TranslationKey<N>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<ResolvedNamespace<N, P> & DictionaryKeys, P>;
35
69
  };
36
70
  /**
37
71
  * Fully-typed i18next `t()` bound to the dictionary namespace `N` and the key
38
- * prefix `Prefix`: keys are relative dot-paths under the prefix, and return
39
- * types are resolved against the absolute path in the dictionary.
72
+ * prefix `Prefix`: keys are relative dot-paths under the prefix (in `N` or a
73
+ * declared fallback dictionary), and return types are resolved against the
74
+ * absolute path in the dictionary serving it.
40
75
  */
41
76
  export type ScopedTFunction<N extends DictionaryKeys, Prefix extends string> = {
42
77
  /** Returns the raw content subtree at `key` (i18next `returnObjects`). */
43
- <P extends ScopedDotPaths<N, Prefix>>(key: P | P[], options: TOptions & {
78
+ <P extends ScopedDotPaths<N, Prefix> | FallbackScopedDotPaths<Prefix>>(key: P | P[], options: TOptions & {
44
79
  returnObjects: true;
45
- }): ContentAtPath<N, `${Prefix}.${P}`>;
80
+ }): ContentAtPath<ResolvedNamespace<N, `${Prefix}.${P}`> & DictionaryKeys, `${Prefix}.${P}`>;
46
81
  /** Translate a scoped key, with optional default value and options. */
47
- <P extends ScopedDotPaths<N, Prefix>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<N, `${Prefix}.${P}`>;
82
+ <P extends ScopedDotPaths<N, Prefix> | FallbackScopedDotPaths<Prefix>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<ResolvedNamespace<N, `${Prefix}.${P}`> & DictionaryKeys, `${Prefix}.${P}`>;
48
83
  };
49
84
  /**
50
85
  * Typed variant of i18next's `getFixedT`, scoped to an intlayer dictionary
@@ -54,4 +89,5 @@ export type TypedGetFixedT = {
54
89
  <N extends DictionaryKeys, Prefix extends string>(lng: string | readonly string[] | null, ns: N | null | undefined, keyPrefix: Prefix): ScopedTFunction<N, Prefix>;
55
90
  <N extends DictionaryKeys>(lng: string | readonly string[] | null, ns?: N | null): TypedTFunction<N>;
56
91
  };
92
+ export {};
57
93
  //# sourceMappingURL=typedTranslation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"typedTranslation.d.ts","names":[],"sources":["../../src/typedTranslation.ts"],"mappings":";;;;;;;;YASY,cAAc,UAAU,gBAAgB,KAAK,iBAAiB,GAAG;;;;;;YAOjE,gBAAgB,UAAU,gBAAgB,KACpD,cAAc,GAAG,oBAAoB,cAAc,GAAG;;;;;YAM5C,eAAe,UAAU,gBAAgB,yBACnD,iBAAiB,kBAAiB,YAC9B,oBAAoB,gBAAgB,iBAClC;;;;;;;;YAWI,eAAe,UAAU;;GAElC,UAAU,iBAAiB,IAC1B,KAAK,IAAI,KACT,SAAS;IAAa;MACrB,cAAc,GAAG;;GAEnB,UAAU,iBAAiB,IAC1B,KAAK,IAAI,KACT,wBAAwB,mBACxB,eAAe,WACd,gBAAgB,GAAG;;;;;;;YAQZ,gBAAgB,UAAU,gBAAgB;;GAEnD,UAAU,eAAe,GAAG,SAC3B,KAAK,IAAI,KACT,SAAS;IAAa;MACrB,cAAc,MAAM,UAAU;;GAEhC,UAAU,eAAe,GAAG,SAC3B,KAAK,IAAI,KACT,wBAAwB,mBACxB,eAAe,WACd,gBAAgB,MAAM,UAAU;;;;;;YAOzB;GACT,UAAU,gBAAgB,uBACzB,wCACA,IAAI,sBACJ,WAAW,SACV,gBAAgB,GAAG;GACrB,UAAU,gBACT,wCACA,KAAK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AAU,gBAAgB,uBACzB,wCACA,IAAI,sBACJ,WAAW,SACV,gBAAgB,GAAG;GACrB,UAAU,gBACT,wCACA,KAAK,WACJ,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/i18next",
3
- "version": "9.9.1",
3
+ "version": "9.9.3-canary.0",
4
4
  "private": false,
5
5
  "description": "i18next API adapter for intlayer — drop-in compatibility layer that exposes the i18next interface while using @intlayer/core under the hood",
6
6
  "keywords": [
@@ -68,19 +68,19 @@
68
68
  "prepublish": "cp -f ../../README.md ./README.md",
69
69
  "publish": "bun publish || true",
70
70
  "publish:canary": "bun publish --access public --tag canary || true",
71
- "publish:ci": "bun ../../scripts/publish-package.mjs",
71
+ "publish:ci": "bun ../../scripts/publish-package.ts",
72
72
  "publish:latest": "bun publish --access public --tag latest || true",
73
73
  "test": "bun --bun vitest run",
74
74
  "test:watch": "bun --bun vitest",
75
75
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
76
76
  },
77
77
  "dependencies": {
78
- "@intlayer/config": "9.9.1",
79
- "@intlayer/core": "9.9.1",
80
- "@intlayer/dictionaries-entry": "9.9.1",
81
- "@intlayer/engine": "9.9.1",
82
- "@intlayer/types": "9.9.1",
83
- "vite-intlayer": "9.9.1"
78
+ "@intlayer/config": "9.9.3-canary.0",
79
+ "@intlayer/core": "9.9.3-canary.0",
80
+ "@intlayer/dictionaries-entry": "9.9.3-canary.0",
81
+ "@intlayer/engine": "9.9.3-canary.0",
82
+ "@intlayer/types": "9.9.3-canary.0",
83
+ "vite-intlayer": "9.9.3-canary.0"
84
84
  },
85
85
  "devDependencies": {
86
86
  "@types/node": "^26",
@@ -92,7 +92,7 @@
92
92
  "rimraf": "6.1.4",
93
93
  "tsdown": "0.23.7",
94
94
  "typescript": "7.0.2",
95
- "vite": "8.3.8",
95
+ "vite": "8.4.0",
96
96
  "vitest": "5.1.2"
97
97
  },
98
98
  "peerDependencies": {