@intlayer/core 9.8.0 → 9.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cjs/dictionaryManipulator/index.cjs +1 -0
  2. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +15 -1
  3. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
  4. package/dist/cjs/index.cjs +3 -0
  5. package/dist/cjs/interpreter/dictionaryTransformCache.cjs +40 -0
  6. package/dist/cjs/interpreter/dictionaryTransformCache.cjs.map +1 -1
  7. package/dist/cjs/interpreter/index.cjs +2 -0
  8. package/dist/cjs/messageFormat/ICU.cjs +50 -25
  9. package/dist/cjs/messageFormat/ICU.cjs.map +1 -1
  10. package/dist/cjs/messageFormat/resolveMessage.cjs +43 -21
  11. package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
  12. package/dist/esm/dictionaryManipulator/index.mjs +2 -2
  13. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +15 -2
  14. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
  15. package/dist/esm/index.mjs +3 -3
  16. package/dist/esm/interpreter/dictionaryTransformCache.mjs +39 -1
  17. package/dist/esm/interpreter/dictionaryTransformCache.mjs.map +1 -1
  18. package/dist/esm/interpreter/index.mjs +2 -2
  19. package/dist/esm/messageFormat/ICU.mjs +51 -26
  20. package/dist/esm/messageFormat/ICU.mjs.map +1 -1
  21. package/dist/esm/messageFormat/resolveMessage.mjs +44 -22
  22. package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
  23. package/dist/types/dictionaryManipulator/index.d.ts +2 -2
  24. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +12 -0
  25. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
  26. package/dist/types/index.d.ts +4 -4
  27. package/dist/types/interpreter/dictionaryTransformCache.d.ts +23 -0
  28. package/dist/types/interpreter/dictionaryTransformCache.d.ts.map +1 -1
  29. package/dist/types/interpreter/index.d.ts +2 -2
  30. package/dist/types/messageFormat/ICU.d.ts.map +1 -1
  31. package/dist/types/messageFormat/index.d.ts +2 -2
  32. package/dist/types/messageFormat/resolveMessage.d.ts +18 -4
  33. package/dist/types/messageFormat/resolveMessage.d.ts.map +1 -1
  34. package/package.json +6 -6
@@ -4,6 +4,7 @@ const require_utils_intl = require("../utils/intl.cjs");
4
4
  const require_interpreter_getEnumeration = require("../interpreter/getEnumeration.cjs");
5
5
  const require_interpreter_getPlural = require("../interpreter/getPlural.cjs");
6
6
  const require_interpreter_getSelect = require("../interpreter/getSelect.cjs");
7
+ const require_transpiler_plural_plural = require("../transpiler/plural/plural.cjs");
7
8
  const require_messageFormat_i18next = require("./i18next.cjs");
8
9
  const require_messageFormat_ICU = require("./ICU.cjs");
9
10
  const require_messageFormat_vue_i18n = require("./vue-i18n.cjs");
@@ -29,8 +30,25 @@ const resolveValuePath = (values, path) => {
29
30
  }
30
31
  return current;
31
32
  };
32
- /** Formats an ICU-style formatted argument (`{value, number, percent}`). */
33
- const formatArgument = (value, type, style, locale) => {
33
+ /** Argument types handled natively; custom formatters cannot override them. */
34
+ const BUILT_IN_ARGUMENT_TYPES = [
35
+ "number",
36
+ "date",
37
+ "time"
38
+ ];
39
+ /**
40
+ * Formats an ICU-style formatted argument (`{value, number, percent}`).
41
+ * Types that are not built in go to the matching custom formatter, if any.
42
+ */
43
+ const formatArgument = (value, type, style, locale, formatters) => {
44
+ const customFormatter = !BUILT_IN_ARGUMENT_TYPES.includes(type) && formatters && Object.hasOwn(formatters, type) ? formatters[type] : void 0;
45
+ if (customFormatter) {
46
+ const formatted = customFormatter(value, {
47
+ locale,
48
+ style
49
+ });
50
+ return formatted === null || formatted === void 0 ? "" : String(formatted);
51
+ }
34
52
  try {
35
53
  if (type === "number") {
36
54
  const numberValue = Number(value);
@@ -60,14 +78,14 @@ const formatArgument = (value, type, style, locale) => {
60
78
  * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`
61
79
  * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)
62
80
  */
63
- const interpolateMessage = (template, values = {}, locale = "en") => template.replace(/\{\{\s*([^{},]+?)\s*(?:,\s*(\w+)\s*(?:,\s*([^{}]+?)\s*)?)?\}\}/g, (match, path, type, style) => {
81
+ const interpolateMessage = (template, values = {}, locale = "en", formatters) => template.replace(/\{\{\s*([^{},]+?)\s*(?:,\s*(\w+)\s*(?:,\s*([^{}]+?)\s*)?)?\}\}/g, (match, path, type, style) => {
64
82
  const value = resolveValuePath(values, path);
65
83
  if (value === void 0) return match;
66
- return type ? formatArgument(value, type, style, locale) : String(value);
84
+ return type ? formatArgument(value, type, style, locale, formatters) : String(value);
67
85
  }).replace(/\{\s*([\w.]+)\s*,\s*(\w+)\s*(?:,\s*([^}]+?)\s*)?\}/g, (match, path, type, style) => {
68
86
  const value = resolveValuePath(values, path);
69
87
  if (value === void 0) return match;
70
- return formatArgument(value, type, style, locale);
88
+ return formatArgument(value, type, style, locale, formatters);
71
89
  }).replace(/\{\s*([\w.]+)\s*\}/g, (match, path) => {
72
90
  const value = resolveValuePath(values, path);
73
91
  return value === void 0 ? match : String(value);
@@ -82,24 +100,25 @@ const getSelectorValue = (values, variableName) => values[variableName] ?? value
82
100
  * Function nodes (produced by the interpreter plugins for `insertion`,
83
101
  * `enumeration` and `plural` content) are invoked with the values.
84
102
  */
85
- const resolveMessageNode = (node, values = {}, locale = "en") => {
103
+ const resolveMessageNode = (node, values = {}, locale = "en", formatters) => {
86
104
  if (node === null || node === void 0) return node;
87
- if (typeof node === "string") return interpolateMessage(node, values, locale);
105
+ if (typeof node === "string") return interpolateMessage(node, values, locale, formatters);
88
106
  if (typeof node === "number" || typeof node === "boolean") return String(node);
89
107
  if (typeof node === "function") try {
90
- return resolveMessageNode(node(values), values, locale);
108
+ return resolveMessageNode(node(values), values, locale, formatters);
91
109
  } catch {
92
110
  return;
93
111
  }
94
- if (Array.isArray(node)) return node.map((item) => String(resolveMessageNode(item, values, locale) ?? "")).join("");
112
+ if (Array.isArray(node)) return node.map((item) => String(resolveMessageNode(item, values, locale, formatters) ?? "")).join("");
95
113
  const typedNode = node;
96
- if (typedNode.nodeType === _intlayer_types_nodeType.INSERTION) return resolveMessageNode(typedNode[_intlayer_types_nodeType.INSERTION], values, locale);
97
- if (typedNode.nodeType === _intlayer_types_nodeType.HTML) return resolveMessageNode(typedNode[_intlayer_types_nodeType.HTML], values, locale);
114
+ if (typedNode.nodeType === _intlayer_types_nodeType.INSERTION) return resolveMessageNode(typedNode[_intlayer_types_nodeType.INSERTION], values, locale, formatters);
115
+ if (typedNode.nodeType === _intlayer_types_nodeType.HTML) return resolveMessageNode(typedNode[_intlayer_types_nodeType.HTML], values, locale, formatters);
98
116
  if (typedNode.nodeType === _intlayer_types_nodeType.PLURAL) {
99
117
  const pluralState = typedNode[_intlayer_types_nodeType.PLURAL];
100
- const count = Number(getSelectorValue(values, "count") ?? 1);
118
+ const variableName = typeof typedNode.variable === "string" ? typedNode.variable : require_transpiler_plural_plural.DEFAULT_PLURAL_VARIABLE;
119
+ const count = Number(getSelectorValue(values, variableName) ?? 1);
101
120
  const selected = require_interpreter_getPlural.getPlural(pluralState, count, locale);
102
- return resolveMessageNode(selected, values, locale);
121
+ return resolveMessageNode(selected, values, locale, formatters);
103
122
  }
104
123
  if (typedNode.nodeType === _intlayer_types_nodeType.ENUMERATION) {
105
124
  const enumerationState = typedNode[_intlayer_types_nodeType.ENUMERATION];
@@ -113,21 +132,24 @@ const resolveMessageNode = (node, values = {}, locale = "en") => {
113
132
  const ordinalCount = Number(selector);
114
133
  const ordinalCategory = require_utils_intl.getCachedIntl("PluralRules", locale, { type: "ordinal" }).select(ordinalCount);
115
134
  selected = options[String(ordinalCount)] ?? options[ordinalCategory] ?? options.fallback ?? options.other;
116
- } else if (typeof selector === "number" || !Number.isNaN(Number(selector))) selected = require_interpreter_getEnumeration.getEnumeration(options, Number(selector));
117
- else selected = options[String(selector)] ?? options.fallback ?? options.other;
118
- return resolveMessageNode(selected, values, locale);
135
+ } else if (typeof selector === "number" || !Number.isNaN(Number(selector))) {
136
+ const count = Number(selector);
137
+ const matchedKey = require_interpreter_getEnumeration.findMatchingCondition(options, count);
138
+ selected = matchedKey ? options[matchedKey] : options[require_utils_intl.getCachedIntl("PluralRules", locale).select(count)] ?? require_interpreter_getEnumeration.getEnumeration(options, count);
139
+ } else selected = options[String(selector)] ?? options.fallback ?? options.other;
140
+ return resolveMessageNode(selected, values, locale, formatters);
119
141
  }
120
142
  if (typedNode.nodeType === _intlayer_types_nodeType.SELECT) {
121
143
  const selectState = typedNode[_intlayer_types_nodeType.SELECT];
122
144
  const variableName = typeof typedNode.variable === "string" ? typedNode.variable : "value";
123
145
  const selector = getSelectorValue(values, variableName);
124
146
  const selected = require_interpreter_getSelect.getSelect(selectState, String(selector ?? ""));
125
- return resolveMessageNode(selected, values, locale);
147
+ return resolveMessageNode(selected, values, locale, formatters);
126
148
  }
127
149
  if (typedNode.nodeType === _intlayer_types_nodeType.GENDER) {
128
150
  const genderState = typedNode[_intlayer_types_nodeType.GENDER];
129
151
  const selected = genderState[String(values.gender ?? "")] ?? genderState.fallback ?? genderState.other;
130
- return resolveMessageNode(selected, values, locale);
152
+ return resolveMessageNode(selected, values, locale, formatters);
131
153
  }
132
154
  return node;
133
155
  };
@@ -140,8 +162,8 @@ const resolveMessageNode = (node, values = {}, locale = "en") => {
140
162
  * callables, so no message parser is involved. Plain strings still get
141
163
  * `{{name}}` / `{name}` / `{value, number}` interpolation.
142
164
  */
143
- const resolveMessageNodeToString = (node, values = {}, locale = "en") => {
144
- const resolved = resolveMessageNode(node, values, locale);
165
+ const resolveMessageNodeToString = (node, values = {}, locale = "en", formatters) => {
166
+ const resolved = resolveMessageNode(node, values, locale, formatters);
145
167
  return typeof resolved === "string" ? resolved : String(resolved ?? "");
146
168
  };
147
169
  /**
@@ -157,7 +179,7 @@ const resolveMessageNodeToString = (node, values = {}, locale = "en") => {
157
179
  * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'
158
180
  * ```
159
181
  */
160
- const createMessageResolver = (formatter) => (message, values = {}, locale = "en") => resolveMessageNodeToString(typeof message === "string" ? formatter(message) : message, values, locale);
182
+ const createMessageResolver = (formatter) => (message, values = {}, locale = "en", formatters) => resolveMessageNodeToString(typeof message === "string" ? formatter(message) : message, values, locale, formatters);
161
183
  const DIALECT_FORMATTERS = {
162
184
  icu: require_messageFormat_ICU.icuToIntlayerFormatter,
163
185
  i18next: require_messageFormat_i18next.i18nextToIntlayerFormatter,
@@ -1 +1 @@
1
- {"version":3,"file":"resolveMessage.cjs","names":["getCachedIntl","NodeTypes","getPlural","getEnumeration","getSelect","icuToIntlayerFormatter","i18nextToIntlayerFormatter","vueI18nToIntlayerFormatter"],"sources":["../../../src/messageFormat/resolveMessage.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { getCachedIntl } from '../formatters';\nimport { getEnumeration } from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport type { PluralContentState } from '../transpiler/plural/plural';\nimport { i18nextToIntlayerFormatter } from './i18next';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { vueI18nToIntlayerFormatter } from './vue-i18n';\n\n/**\n * Runtime counterpart of the `messageFormat` converters.\n *\n * The converters (`icuToIntlayerFormatter`, `i18nextToIntlayerFormatter`,\n * `vueI18nToIntlayerFormatter`) turn library-specific message syntax into\n * intlayer nodes (`insert`, `plural`, `enu`, `gender`, `html`). This module\n * resolves those nodes — or raw message strings — into a final string using\n * the provided interpolation values and locale.\n *\n * It is the mutualized resolution engine used by the compat adapter packages\n * (`@intlayer/i18next`, `@intlayer/next-intl`, `@intlayer/vue-i18n`, …).\n */\n\n/** Message syntax dialect of the source i18n library. */\nexport type MessageFormatDialect = 'icu' | 'i18next' | 'vue-i18n';\n\n/** Interpolation values passed alongside a translation lookup. */\nexport type MessageValues = Record<string, unknown>;\n\n/** Internal enumeration metadata keys injected by the converters. */\nconst ENUMERATION_METADATA_KEYS = [\n '__intlayer_icu_var',\n '__intlayer_icu_ordinal',\n '__intlayer_vue_i18n_var',\n] as const;\n\n/**\n * Resolves a possibly-dotted path (`user.name`) inside the values object.\n */\nconst resolveValuePath = (values: MessageValues, path: string): unknown => {\n if (path in values) return values[path];\n\n let current: unknown = values;\n for (const part of path.split('.')) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n};\n\n/** Formats an ICU-style formatted argument (`{value, number, percent}`). */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues\n): string => {\n try {\n if (type === 'number') {\n const numberValue = Number(value);\n if (style === 'percent') {\n return getCachedIntl('NumberFormat', locale, {\n style: 'percent',\n }).format(numberValue);\n }\n if (style === 'integer') {\n return getCachedIntl('NumberFormat', locale, {\n maximumFractionDigits: 0,\n }).format(numberValue);\n }\n return getCachedIntl('NumberFormat', locale).format(numberValue);\n }\n\n if (type === 'date' || type === 'time') {\n const dateValue =\n value instanceof Date ? value : new Date(value as string | number);\n const dateTimeStyle = (\n ['short', 'medium', 'long', 'full'].includes(style ?? '')\n ? style\n : type === 'date'\n ? 'medium'\n : 'short'\n ) as 'short' | 'medium' | 'long' | 'full';\n\n return getCachedIntl(\n 'DateTimeFormat',\n locale,\n type === 'date'\n ? { dateStyle: dateTimeStyle }\n : { timeStyle: dateTimeStyle }\n ).format(dateValue);\n }\n } catch {\n // Fall through to the raw string representation below\n }\n\n return String(value);\n};\n\n/**\n * Interpolates a message template with values.\n *\n * Handles, in order:\n * 1. Intlayer insertions `{{name}}` (whitespace-tolerant, dotted paths),\n * optionally formatted the i18next way (`{{price, number}}`)\n * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`\n * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)\n */\nexport const interpolateMessage = (\n template: string,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues\n): string =>\n template\n .replace(\n /\\{\\{\\s*([^{},]+?)\\s*(?:,\\s*(\\w+)\\s*(?:,\\s*([^{}]+?)\\s*)?)?\\}\\}/g,\n (match, path: string, type: string | undefined, style?: string) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return type\n ? formatArgument(value, type, style, locale)\n : String(value);\n }\n )\n .replace(\n /\\{\\s*([\\w.]+)\\s*,\\s*(\\w+)\\s*(?:,\\s*([^}]+?)\\s*)?\\}/g,\n (match, path: string, type: string, style: string | undefined) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return formatArgument(value, type, style, locale);\n }\n )\n .replace(/\\{\\s*([\\w.]+)\\s*\\}/g, (match, path: string) => {\n const value = resolveValuePath(values, path);\n return value === undefined ? match : String(value);\n });\n\n/** Reads the selector value of an enumeration/plural node from the values. */\nconst getSelectorValue = (\n values: MessageValues,\n variableName: string\n): unknown => values[variableName] ?? values.count ?? values.n;\n\n/**\n * Resolves an intlayer message node tree (as produced by the\n * `*ToIntlayerFormatter` converters, or already present in a built\n * dictionary) into its final value using interpolation values and locale.\n *\n * Function nodes (produced by the interpreter plugins for `insertion`,\n * `enumeration` and `plural` content) are invoked with the values.\n */\nexport const resolveMessageNode = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues\n): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale);\n }\n\n if (typeof node === 'number' || typeof node === 'boolean') {\n return String(node);\n }\n\n // Interpreter-transformed nodes (insertion/enumeration/plural plugins)\n // are exposed as callables taking the interpolation values.\n if (typeof node === 'function') {\n try {\n return resolveMessageNode(\n (node as (arg: MessageValues) => unknown)(values),\n values,\n locale\n );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) => String(resolveMessageNode(item, values, locale) ?? ''))\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(typedNode[NodeTypes.INSERTION], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(typedNode[NodeTypes.HTML], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const count = Number(getSelectorValue(values, 'count') ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(selected, values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.ENUMERATION) {\n const enumerationState = typedNode[NodeTypes.ENUMERATION] as Record<\n string,\n unknown\n >;\n\n const variableName = (ENUMERATION_METADATA_KEYS.map(\n (metadataKey) => enumerationState[metadataKey]\n ).find((name) => typeof name === 'string') ?? 'count') as string;\n\n const isOrdinal = enumerationState.__intlayer_icu_ordinal === true;\n\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(enumerationState)) {\n if (!(ENUMERATION_METADATA_KEYS as readonly string[]).includes(key)) {\n options[key] = value;\n }\n }\n\n const selector = getSelectorValue(values, variableName);\n\n let selected: unknown;\n if (isOrdinal && !Number.isNaN(Number(selector))) {\n // ICU `selectordinal` — exact numeric match first, then the CLDR\n // ordinal category, then the fallback\n const ordinalCount = Number(selector);\n const ordinalCategory = getCachedIntl('PluralRules', locale, {\n type: 'ordinal',\n }).select(ordinalCount);\n selected =\n options[String(ordinalCount)] ??\n options[ordinalCategory] ??\n options.fallback ??\n options.other;\n } else if (\n typeof selector === 'number' ||\n !Number.isNaN(Number(selector))\n ) {\n selected = getEnumeration(options, Number(selector));\n } else {\n // String selector — ICU `select` converted to an enumeration\n selected = options[String(selector)] ?? options.fallback ?? options.other;\n }\n\n return resolveMessageNode(selected, values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.SELECT) {\n const selectState = typedNode[NodeTypes.SELECT] as Record<string, unknown>;\n\n // The node records the ICU variable it was imported from; fall back to\n // `value` for nodes authored directly with `select()`.\n const variableName =\n typeof typedNode.variable === 'string' ? typedNode.variable : 'value';\n\n const selector = getSelectorValue(values, variableName);\n const selected = getSelect(selectState, String(selector ?? ''));\n\n return resolveMessageNode(selected, values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.GENDER) {\n const genderState = typedNode[NodeTypes.GENDER] as Record<string, unknown>;\n const genderValue = String(values.gender ?? '');\n const selected =\n genderState[genderValue] ?? genderState.fallback ?? genderState.other;\n return resolveMessageNode(selected, values, locale);\n }\n\n return node;\n};\n\n/**\n * {@link resolveMessageNode} coerced to a string.\n *\n * This is the whole runtime a compat adapter needs for content that reached\n * the bundle through a built dictionary: the build already converted every\n * dialect construct into intlayer nodes, and the interpreter turned those into\n * callables, so no message parser is involved. Plain strings still get\n * `{{name}}` / `{name}` / `{value, number}` interpolation.\n */\nexport const resolveMessageNodeToString = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues\n): string => {\n const resolved = resolveMessageNode(node, values, locale);\n\n return typeof resolved === 'string' ? resolved : String(resolved ?? '');\n};\n\n/** Converts a raw message string of one dialect into an intlayer node tree. */\nexport type MessageFormatter = (message: string) => unknown;\n\n/**\n * Resolves a raw message — string, or an intlayer node tree — into a final\n * string using interpolation values and locale.\n */\nexport type MessageResolver = (\n message: unknown,\n values?: MessageValues,\n locale?: LocalesValues\n) => string;\n\n/**\n * Binds {@link resolveMessageNode} to one dialect converter.\n *\n * The compat adapters each speak a single dialect, and referencing the\n * converter directly — rather than picking it from a record keyed by dialect —\n * is what lets a bundler drop the two parsers the adapter never uses.\n *\n * @example\n * ```ts\n * const resolveIcuMessage = createMessageResolver(icuToIntlayerFormatter);\n * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'\n * ```\n */\nexport const createMessageResolver =\n (formatter: MessageFormatter): MessageResolver =>\n (message, values = {}, locale = 'en' as LocalesValues) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale\n );\n\nconst DIALECT_FORMATTERS: Record<MessageFormatDialect, MessageFormatter> = {\n icu: icuToIntlayerFormatter,\n i18next: i18nextToIntlayerFormatter,\n 'vue-i18n': vueI18nToIntlayerFormatter,\n};\n\n/**\n * Resolves a raw message — string in a library dialect, or an intlayer node\n * tree — into a final string using interpolation values and locale.\n *\n * Selecting the dialect at runtime keeps every converter reachable; a package\n * that only ever needs one should bind it with {@link createMessageResolver}.\n *\n * @example\n * ```ts\n * resolveMessage('Hello {name}', { name: 'John' }, 'en', 'icu');\n * // 'Hello John'\n *\n * resolveMessage(\n * '{count, plural, one {# item} other {# items}}',\n * { count: 3 },\n * 'en',\n * 'icu'\n * );\n * // '3 items'\n * ```\n */\nexport const resolveMessage = (\n message: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n dialect: MessageFormatDialect = 'icu'\n): string =>\n createMessageResolver(DIALECT_FORMATTERS[dialect])(message, values, locale);\n\n/** A parsed token of a tagged message: plain text or a tag with children. */\nexport type TaggedMessageToken =\n | string\n | { tag: string; children: TaggedMessageToken[] };\n\n/**\n * Tokenizes a message containing XML-like tags (`'Visit <link>the docs</link>'`,\n * `'hello <1>{{name}}</1>'`, `'line<br/>break'`) into a token tree.\n *\n * Used by rich-text renderers (`t.rich`, `<Trans components>`,\n * `<i18n-t>` slots) to map tags to framework elements.\n */\nexport const parseTaggedMessage = (message: string): TaggedMessageToken[] => {\n const tokens: TaggedMessageToken[] = [];\n const tagRegex = /<([\\w-]+)\\s*\\/>|<([\\w-]+)[^>]*>([\\s\\S]*?)<\\/\\2>/g;\n let lastIndex = 0;\n let match = tagRegex.exec(message);\n\n while (match !== null) {\n if (match.index > lastIndex) {\n tokens.push(message.slice(lastIndex, match.index));\n }\n\n const [, selfClosingTag, tag, inner] = match;\n\n if (selfClosingTag) {\n tokens.push({ tag: selfClosingTag, children: [] });\n } else if (tag) {\n tokens.push({ tag, children: parseTaggedMessage(inner ?? '') });\n }\n\n lastIndex = match.index + match[0].length;\n match = tagRegex.exec(message);\n }\n\n if (lastIndex < message.length) {\n tokens.push(message.slice(lastIndex));\n }\n\n return tokens;\n};\n"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,4BAA4B;CAChC;CACA;CACA;AACF;;;;AAKA,MAAM,oBAAoB,QAAuB,SAA0B;CACzE,IAAI,QAAQ,QAAQ,OAAO,OAAO;CAElC,IAAI,UAAmB;CACvB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,IACE,YAAY,QACZ,YAAY,UACZ,OAAO,YAAY,UAEnB;EAEF,UAAW,QAAoC;CACjD;CACA,OAAO;AACT;;AAGA,MAAM,kBACJ,OACA,MACA,OACA,WACW;CACX,IAAI;EACF,IAAI,SAAS,UAAU;GACrB,MAAM,cAAc,OAAO,KAAK;GAChC,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,uBAAuB,EACzB,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,OAAOA,iCAAc,gBAAgB,MAAM,CAAC,CAAC,OAAO,WAAW;EACjE;EAEA,IAAI,SAAS,UAAU,SAAS,QAAQ;GACtC,MAAM,YACJ,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAwB;GACnE,MAAM,gBACJ;IAAC;IAAS;IAAU;IAAQ;GAAM,CAAC,CAAC,SAAS,SAAS,EAAE,IACpD,QACA,SAAS,SACP,WACA;GAGR,OAAOA,iCACL,kBACA,QACA,SAAS,SACL,EAAE,WAAW,cAAc,IAC3B,EA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AI,MAAM,QAAQ,WAChB,OAAO,KAAK,QAAQ,MAAM,WAAW,MAAM,KAAK,CAAC;EAGnD,MAAM,GAAG,gBAAgB,KAAK,SAAS;EAEvC,IAAI,gBACF,OAAO,KAAK;GAAE,KAAK;GAAgB,UAAU,CAAC;EAAE,CAAC;OAC5C,IAAI,KACT,OAAO,KAAK;GAAE;GAAK,UAAU,mBAAmB,SAAS,EAAE;EAAE,CAAC;EAGhE,YAAY,MAAM,QAAQ,MAAM,EAAE,CAAC;EACnC,QAAQ,SAAS,KAAK,OAAO;CAC/B;CAEA,IAAI,YAAY,QAAQ,QACtB,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAC;CAGtC,OAAO;AACT"}
1
+ {"version":3,"file":"resolveMessage.cjs","names":["getCachedIntl","NodeTypes","DEFAULT_PLURAL_VARIABLE","getPlural","findMatchingCondition","getEnumeration","getSelect","icuToIntlayerFormatter","i18nextToIntlayerFormatter","vueI18nToIntlayerFormatter"],"sources":["../../../src/messageFormat/resolveMessage.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { getCachedIntl } from '../formatters';\nimport {\n findMatchingCondition,\n getEnumeration,\n} from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport {\n DEFAULT_PLURAL_VARIABLE,\n type PluralContentState,\n} from '../transpiler/plural/plural';\nimport { i18nextToIntlayerFormatter } from './i18next';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { vueI18nToIntlayerFormatter } from './vue-i18n';\n\n/**\n * Runtime counterpart of the `messageFormat` converters.\n *\n * The converters (`icuToIntlayerFormatter`, `i18nextToIntlayerFormatter`,\n * `vueI18nToIntlayerFormatter`) turn library-specific message syntax into\n * intlayer nodes (`insert`, `plural`, `enu`, `gender`, `html`). This module\n * resolves those nodes — or raw message strings — into a final string using\n * the provided interpolation values and locale.\n *\n * It is the mutualized resolution engine used by the compat adapter packages\n * (`@intlayer/i18next`, `@intlayer/next-intl`, `@intlayer/vue-i18n`, …).\n */\n\n/** Message syntax dialect of the source i18n library. */\nexport type MessageFormatDialect = 'icu' | 'i18next' | 'vue-i18n';\n\n/** Interpolation values passed alongside a translation lookup. */\nexport type MessageValues = Record<string, unknown>;\n\n/** Internal enumeration metadata keys injected by the converters. */\nconst ENUMERATION_METADATA_KEYS = [\n '__intlayer_icu_var',\n '__intlayer_icu_ordinal',\n '__intlayer_vue_i18n_var',\n] as const;\n\n/**\n * Resolves a possibly-dotted path (`user.name`) inside the values object.\n */\nconst resolveValuePath = (values: MessageValues, path: string): unknown => {\n if (path in values) return values[path];\n\n let current: unknown = values;\n for (const part of path.split('.')) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n};\n\n/** Context handed to a {@link MessageArgumentFormatter}. */\nexport type MessageArgumentFormatterContext = {\n /** Active locale. */\n locale: LocalesValues;\n /** Third segment of the argument (`EUR` in `{price, currency, EUR}`). */\n style?: string;\n};\n\n/**\n * Formats an argument whose type is not built in, e.g. `currency` in\n * `{price, currency, EUR}`.\n */\nexport type MessageArgumentFormatter = (\n value: unknown,\n context: MessageArgumentFormatterContext\n) => unknown;\n\n/** Custom argument formatters, keyed by argument type. */\nexport type MessageArgumentFormatters = Record<\n string,\n MessageArgumentFormatter\n>;\n\n/** Argument types handled natively; custom formatters cannot override them. */\nconst BUILT_IN_ARGUMENT_TYPES = ['number', 'date', 'time'];\n\n/**\n * Formats an ICU-style formatted argument (`{value, number, percent}`).\n * Types that are not built in go to the matching custom formatter, if any.\n */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues,\n formatters?: MessageArgumentFormatters\n): string => {\n const customFormatter =\n !BUILT_IN_ARGUMENT_TYPES.includes(type) &&\n formatters &&\n Object.hasOwn(formatters, type)\n ? formatters[type]\n : undefined;\n\n if (customFormatter) {\n const formatted = customFormatter(value, { locale, style });\n return formatted === null || formatted === undefined\n ? ''\n : String(formatted);\n }\n\n try {\n if (type === 'number') {\n const numberValue = Number(value);\n if (style === 'percent') {\n return getCachedIntl('NumberFormat', locale, {\n style: 'percent',\n }).format(numberValue);\n }\n if (style === 'integer') {\n return getCachedIntl('NumberFormat', locale, {\n maximumFractionDigits: 0,\n }).format(numberValue);\n }\n return getCachedIntl('NumberFormat', locale).format(numberValue);\n }\n\n if (type === 'date' || type === 'time') {\n const dateValue =\n value instanceof Date ? value : new Date(value as string | number);\n const dateTimeStyle = (\n ['short', 'medium', 'long', 'full'].includes(style ?? '')\n ? style\n : type === 'date'\n ? 'medium'\n : 'short'\n ) as 'short' | 'medium' | 'long' | 'full';\n\n return getCachedIntl(\n 'DateTimeFormat',\n locale,\n type === 'date'\n ? { dateStyle: dateTimeStyle }\n : { timeStyle: dateTimeStyle }\n ).format(dateValue);\n }\n } catch {\n // Fall through to the raw string representation below\n }\n\n return String(value);\n};\n\n/**\n * Interpolates a message template with values.\n *\n * Handles, in order:\n * 1. Intlayer insertions `{{name}}` (whitespace-tolerant, dotted paths),\n * optionally formatted the i18next way (`{{price, number}}`)\n * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`\n * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)\n */\nexport const interpolateMessage = (\n template: string,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): string =>\n template\n .replace(\n /\\{\\{\\s*([^{},]+?)\\s*(?:,\\s*(\\w+)\\s*(?:,\\s*([^{}]+?)\\s*)?)?\\}\\}/g,\n (match, path: string, type: string | undefined, style?: string) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return type\n ? formatArgument(value, type, style, locale, formatters)\n : String(value);\n }\n )\n .replace(\n /\\{\\s*([\\w.]+)\\s*,\\s*(\\w+)\\s*(?:,\\s*([^}]+?)\\s*)?\\}/g,\n (match, path: string, type: string, style: string | undefined) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return formatArgument(value, type, style, locale, formatters);\n }\n )\n .replace(/\\{\\s*([\\w.]+)\\s*\\}/g, (match, path: string) => {\n const value = resolveValuePath(values, path);\n return value === undefined ? match : String(value);\n });\n\n/** Reads the selector value of an enumeration/plural node from the values. */\nconst getSelectorValue = (\n values: MessageValues,\n variableName: string\n): unknown => values[variableName] ?? values.count ?? values.n;\n\n/**\n * Resolves an intlayer message node tree (as produced by the\n * `*ToIntlayerFormatter` converters, or already present in a built\n * dictionary) into its final value using interpolation values and locale.\n *\n * Function nodes (produced by the interpreter plugins for `insertion`,\n * `enumeration` and `plural` content) are invoked with the values.\n */\nexport const resolveMessageNode = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale, formatters);\n }\n\n if (typeof node === 'number' || typeof node === 'boolean') {\n return String(node);\n }\n\n // Interpreter-transformed nodes (insertion/enumeration/plural plugins)\n // are exposed as callables taking the interpolation values.\n if (typeof node === 'function') {\n try {\n return resolveMessageNode(\n (node as (arg: MessageValues) => unknown)(values),\n values,\n locale,\n formatters\n );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) =>\n String(resolveMessageNode(item, values, locale, formatters) ?? '')\n )\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(\n typedNode[NodeTypes.INSERTION],\n values,\n locale,\n formatters\n );\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(\n typedNode[NodeTypes.HTML],\n values,\n locale,\n formatters\n );\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const variableName =\n typeof typedNode.variable === 'string'\n ? typedNode.variable\n : DEFAULT_PLURAL_VARIABLE;\n const count = Number(getSelectorValue(values, variableName) ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.ENUMERATION) {\n const enumerationState = typedNode[NodeTypes.ENUMERATION] as Record<\n string,\n unknown\n >;\n\n const variableName = (ENUMERATION_METADATA_KEYS.map(\n (metadataKey) => enumerationState[metadataKey]\n ).find((name) => typeof name === 'string') ?? 'count') as string;\n\n const isOrdinal = enumerationState.__intlayer_icu_ordinal === true;\n\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(enumerationState)) {\n if (!(ENUMERATION_METADATA_KEYS as readonly string[]).includes(key)) {\n options[key] = value;\n }\n }\n\n const selector = getSelectorValue(values, variableName);\n\n let selected: unknown;\n if (isOrdinal && !Number.isNaN(Number(selector))) {\n // ICU `selectordinal` — exact numeric match first, then the CLDR\n // ordinal category, then the fallback\n const ordinalCount = Number(selector);\n const ordinalCategory = getCachedIntl('PluralRules', locale, {\n type: 'ordinal',\n }).select(ordinalCount);\n selected =\n options[String(ordinalCount)] ??\n options[ordinalCategory] ??\n options.fallback ??\n options.other;\n } else if (\n typeof selector === 'number' ||\n !Number.isNaN(Number(selector))\n ) {\n // Exact / range keys first, then a CLDR category kept by the ICU\n // converter (`=1 {…} one {…}`), then the fallback\n const count = Number(selector);\n const matchedKey = findMatchingCondition(options, count);\n selected = matchedKey\n ? options[matchedKey]\n : (options[getCachedIntl('PluralRules', locale).select(count)] ??\n getEnumeration(options, count));\n } else {\n // String selector — ICU `select` converted to an enumeration\n selected = options[String(selector)] ?? options.fallback ?? options.other;\n }\n\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.SELECT) {\n const selectState = typedNode[NodeTypes.SELECT] as Record<string, unknown>;\n\n // The node records the ICU variable it was imported from; fall back to\n // `value` for nodes authored directly with `select()`.\n const variableName =\n typeof typedNode.variable === 'string' ? typedNode.variable : 'value';\n\n const selector = getSelectorValue(values, variableName);\n const selected = getSelect(selectState, String(selector ?? ''));\n\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.GENDER) {\n const genderState = typedNode[NodeTypes.GENDER] as Record<string, unknown>;\n const genderValue = String(values.gender ?? '');\n const selected =\n genderState[genderValue] ?? genderState.fallback ?? genderState.other;\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n return node;\n};\n\n/**\n * {@link resolveMessageNode} coerced to a string.\n *\n * This is the whole runtime a compat adapter needs for content that reached\n * the bundle through a built dictionary: the build already converted every\n * dialect construct into intlayer nodes, and the interpreter turned those into\n * callables, so no message parser is involved. Plain strings still get\n * `{{name}}` / `{name}` / `{value, number}` interpolation.\n */\nexport const resolveMessageNodeToString = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): string => {\n const resolved = resolveMessageNode(node, values, locale, formatters);\n\n return typeof resolved === 'string' ? resolved : String(resolved ?? '');\n};\n\n/** Converts a raw message string of one dialect into an intlayer node tree. */\nexport type MessageFormatter = (message: string) => unknown;\n\n/**\n * Resolves a raw message — string, or an intlayer node tree — into a final\n * string using interpolation values and locale.\n */\nexport type MessageResolver = (\n message: unknown,\n values?: MessageValues,\n locale?: LocalesValues,\n formatters?: MessageArgumentFormatters\n) => string;\n\n/**\n * Binds {@link resolveMessageNode} to one dialect converter.\n *\n * The compat adapters each speak a single dialect, and referencing the\n * converter directly — rather than picking it from a record keyed by dialect —\n * is what lets a bundler drop the two parsers the adapter never uses.\n *\n * @example\n * ```ts\n * const resolveIcuMessage = createMessageResolver(icuToIntlayerFormatter);\n * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'\n * ```\n */\nexport const createMessageResolver =\n (formatter: MessageFormatter): MessageResolver =>\n (message, values = {}, locale = 'en' as LocalesValues, formatters) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale,\n formatters\n );\n\nconst DIALECT_FORMATTERS: Record<MessageFormatDialect, MessageFormatter> = {\n icu: icuToIntlayerFormatter,\n i18next: i18nextToIntlayerFormatter,\n 'vue-i18n': vueI18nToIntlayerFormatter,\n};\n\n/**\n * Resolves a raw message — string in a library dialect, or an intlayer node\n * tree — into a final string using interpolation values and locale.\n *\n * Selecting the dialect at runtime keeps every converter reachable; a package\n * that only ever needs one should bind it with {@link createMessageResolver}.\n *\n * @example\n * ```ts\n * resolveMessage('Hello {name}', { name: 'John' }, 'en', 'icu');\n * // 'Hello John'\n *\n * resolveMessage(\n * '{count, plural, one {# item} other {# items}}',\n * { count: 3 },\n * 'en',\n * 'icu'\n * );\n * // '3 items'\n * ```\n */\nexport const resolveMessage = (\n message: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n dialect: MessageFormatDialect = 'icu'\n): string =>\n createMessageResolver(DIALECT_FORMATTERS[dialect])(message, values, locale);\n\n/** A parsed token of a tagged message: plain text or a tag with children. */\nexport type TaggedMessageToken =\n | string\n | { tag: string; children: TaggedMessageToken[] };\n\n/**\n * Tokenizes a message containing XML-like tags (`'Visit <link>the docs</link>'`,\n * `'hello <1>{{name}}</1>'`, `'line<br/>break'`) into a token tree.\n *\n * Used by rich-text renderers (`t.rich`, `<Trans components>`,\n * `<i18n-t>` slots) to map tags to framework elements.\n */\nexport const parseTaggedMessage = (message: string): TaggedMessageToken[] => {\n const tokens: TaggedMessageToken[] = [];\n const tagRegex = /<([\\w-]+)\\s*\\/>|<([\\w-]+)[^>]*>([\\s\\S]*?)<\\/\\2>/g;\n let lastIndex = 0;\n let match = tagRegex.exec(message);\n\n while (match !== null) {\n if (match.index > lastIndex) {\n tokens.push(message.slice(lastIndex, match.index));\n }\n\n const [, selfClosingTag, tag, inner] = match;\n\n if (selfClosingTag) {\n tokens.push({ tag: selfClosingTag, children: [] });\n } else if (tag) {\n tokens.push({ tag, children: parseTaggedMessage(inner ?? '') });\n }\n\n lastIndex = match.index + match[0].length;\n match = tagRegex.exec(message);\n }\n\n if (lastIndex < message.length) {\n tokens.push(message.slice(lastIndex));\n }\n\n return tokens;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,MAAM,4BAA4B;CAChC;CACA;CACA;AACF;;;;AAKA,MAAM,oBAAoB,QAAuB,SAA0B;CACzE,IAAI,QAAQ,QAAQ,OAAO,OAAO;CAElC,IAAI,UAAmB;CACvB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,IACE,YAAY,QACZ,YAAY,UACZ,OAAO,YAAY,UAEnB;EAEF,UAAW,QAAoC;CACjD;CACA,OAAO;AACT;;AA0BA,MAAM,0BAA0B;CAAC;CAAU;CAAQ;AAAM;;;;;AAMzD,MAAM,kBACJ,OACA,MACA,OACA,QACA,eACW;CACX,MAAM,kBACJ,CAAC,wBAAwB,SAAS,IAAI,KACtC,cACA,OAAO,OAAO,YAAY,IAAI,IAC1B,WAAW,QACX;CAEN,IAAI,iBAAiB;EACnB,MAAM,YAAY,gBAAgB,OAAO;GAAE;GAAQ;EAAM,CAAC;EAC1D,OAAO,cAAc,QAAQ,cAAc,SACvC,KACA,OAAO,SAAS;CACtB;CAEA,IAAI;EACF,IAAI,SAAS,UAAU;GACrB,MAAM,cAAc,OAAO,KAAK;GAChC,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,uBAAuB,EACzB,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,OAAOA,iCAAc,gBAAgB,MAAM,CAAC,CAAC,OAAO,WAAW;EACjE;EAEA,IAAI,SAAS,UAAU,SAAS,QAAQ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;;;;;;;;;;;;;AA6BA,MAAa,yBACV,eACA,SAAS,SAAS,CAAC,GAAG,SAAS,MAAuB,eACrD,2BACE,OAAO,YAAY,WAAW,UAAU,OAAO,IAAI,SACnD,QACA,QACA,UACF;AAEJ,MAAM,qBAAqE;CACzE,KAAKM;CACL,SAASC;CACT,YAAYC;AACd;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,kBACX,SACA,SAAwB,CAAC,GACzB,SAAwB,MACxB,UAAgC,UAEhC,sBAAsB,mBAAmB,QAAQ,CAAC,CAAC,SAAS,QAAQ,MAAM;;;;;;;;AAc5E,MAAa,sBAAsB,YAA0C;CAC3E,MAAM,SAA+B,CAAC;CACtC,MAAM,WAAW;CACjB,IAAI,YAAY;CAChB,IAAI,QAAQ,SAAS,KAAK,OAAO;CAEjC,OAAO,UAAU,MAAM;EACrB,IAAI,MAAM,QAAQ,WAChB,OAAO,KAAK,QAAQ,MAAM,WAAW,MAAM,KAAK,CAAC;EAGnD,MAAM,GAAG,gBAAgB,KAAK,SAAS;EAEvC,IAAI,gBACF,OAAO,KAAK;GAAE,KAAK;GAAgB,UAAU,CAAC;EAAE,CAAC;OAC5C,IAAI,KACT,OAAO,KAAK;GAAE;GAAK,UAAU,mBAAmB,SAAS,EAAE;EAAE,CAAC;EAGhE,YAAY,MAAM,QAAQ,MAAM,EAAE,CAAC;EACnC,QAAQ,SAAS,KAAK,OAAO;CAC/B;CAEA,IAAI,YAAY,QAAQ,QACtB,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAC;CAGtC,OAAO;AACT"}
@@ -13,9 +13,9 @@ import { findPlainDynamicLoader, resolvePlainDynamicLoader } from "./plainDynami
13
13
  import { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary } from "./preloadedDynamicLoader.mjs";
14
14
  import { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, getDictionarySelectorCacheKey, isQualifiedDictionaryGroup, parseDictionarySelector, reconstructQualifiedEntry, resolveDictionaryArgument, resolveEffectiveVariantId, resolveProviderVariant, resolveQualifiedDictionary, serializeVariant, serializeVariantChain } from "./qualifiedDictionary.mjs";
15
15
  import { QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getVariantIds } from "./qualifiedDictionaryDeclaration.mjs";
16
- import { QUALIFIER_DYNAMIC_TYPES_KEY, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./qualifiedDynamicLoader.mjs";
16
+ import { QUALIFIER_DYNAMIC_TYPES_KEY, getQualifiedDynamicChunks, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./qualifiedDynamicLoader.mjs";
17
17
  import { removeContentNodeByKeyPath } from "./removeContentNodeByKeyPath.mjs";
18
18
  import { renameContentNodeByKeyPath } from "./renameContentNodeByKeyPath.mjs";
19
19
  import { updateNodeChildren } from "./updateNodeChildren.mjs";
20
20
 
21
- export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, findPlainDynamicLoader, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getPreloadedDictionary, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveEffectiveVariantId, resolvePlainDynamicLoader, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
21
+ export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, findPlainDynamicLoader, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getPreloadedDictionary, getQualifiedDynamicChunks, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveEffectiveVariantId, resolvePlainDynamicLoader, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
@@ -48,6 +48,16 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
48
48
  };
49
49
  };
50
50
  /**
51
+ * Lists the chunks a selector targets in a qualified dynamic loader map,
52
+ * without loading them — lets a caller warm a suspender cache ahead of render.
53
+ *
54
+ * @returns The targeted chunks, empty when a required coordinate is absent.
55
+ */
56
+ const getQualifiedDynamicChunks = (loaderMap, key, locale, selector) => {
57
+ const { missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
58
+ return missed ? [] : chunks;
59
+ };
60
+ /**
51
61
  * Resolves the content of a qualified dynamic loader map against a selector,
52
62
  * loading only the chunk(s) the selector actually targets.
53
63
  *
@@ -74,7 +84,10 @@ const resolveQualifiedDynamicContent = (params) => {
74
84
  const { loaderMap, key, locale, selector, loadChunk, transform } = params;
75
85
  const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
76
86
  if (missed) return itemAxisOpen ? [] : null;
77
- const dictionaries = chunks.map(({ cacheKey, loader }) => loadChunk(cacheKey, loader()));
87
+ const dictionaries = chunks.map(({ cacheKey, loader }) => ({
88
+ cacheKey,
89
+ promise: loader()
90
+ })).map(({ cacheKey, promise }) => loadChunk(cacheKey, promise));
78
91
  if (itemAxisOpen) return dictionaries.map(transform);
79
92
  const [dictionary] = dictionaries;
80
93
  return dictionary ? transform(dictionary) : null;
@@ -100,5 +113,5 @@ const resolveQualifiedDynamicContentAsync = async (params) => {
100
113
  return dictionary ? transform(dictionary) : null;
101
114
  };
102
115
 
103
- export { QUALIFIER_DYNAMIC_TYPES_KEY, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync };
116
+ export { QUALIFIER_DYNAMIC_TYPES_KEY, getQualifiedDynamicChunks, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync };
104
117
  //# sourceMappingURL=qualifiedDynamicLoader.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"qualifiedDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import { QUALIFIER_DYNAMIC_TYPES_KEY } from '@intlayer/config/defaultValues';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n resolveEffectiveVariantId,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Defined in `@intlayer/config` so the code generator and the build\n * plugins can read it without pulling the runtime in, and re-exported here\n * where its consumers live.\n */\nexport { QUALIFIER_DYNAMIC_TYPES_KEY };\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A variant with no chunk of its own falls back to the `default` chunk, so\n // only the entries that actually differ need to be emitted.\n const segment =\n dimension === 'variant'\n ? resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n )\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` descends by the serialized id, falling back to\n * `default` when the selected variant has no chunk of its own, and `item`\n * either narrows to the selected index or — when no item is given — expands\n * into every sibling chunk (the collection axis). Semantics mirror\n * `resolveQualifiedDictionary` so dynamic and static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n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,QAAQ,UAAU,WAAW,cAAc;CAEnE,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAGvC,MAAM,eAAe,OAAO,KAAK,EAAE,UAAU,aAC3C,UAAU,UAAU,OAAO,CAAC,CAC9B;CAEA,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C;;;;;;;;;;;;AAaA,MAAa,sCAAsC,OAAgB,WAMxB;CACzC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,cAAc;CAExD,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAEvC,MAAM,eAAe,MAAM,QAAQ,IAAI,OAAO,KAAK,EAAE,aAAa,OAAO,CAAC,CAAC;CAE3E,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C"}
1
+ {"version":3,"file":"qualifiedDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import { QUALIFIER_DYNAMIC_TYPES_KEY } from '@intlayer/config/defaultValues';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n resolveEffectiveVariantId,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Defined in `@intlayer/config` so the code generator and the build\n * plugins can read it without pulling the runtime in, and re-exported here\n * where its consumers live.\n */\nexport { QUALIFIER_DYNAMIC_TYPES_KEY };\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\nexport type CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A variant with no chunk of its own falls back to the `default` chunk, so\n // only the entries that actually differ need to be emitted.\n const segment =\n dimension === 'variant'\n ? resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n )\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Lists the chunks a selector targets in a qualified dynamic loader map,\n * without loading them — lets a caller warm a suspender cache ahead of render.\n *\n * @returns The targeted chunks, empty when a required coordinate is absent.\n */\nexport const getQualifiedDynamicChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunk[] => {\n const { missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n return missed ? [] : chunks;\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` descends by the serialized id, falling back to\n * `default` when the selected variant has no chunk of its own, and `item`\n * either narrows to the selected index or — when no item is given — expands\n * into every sibling chunk (the collection axis). Semantics mirror\n * `resolveQualifiedDictionary` so dynamic and static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel: the first\n // `loadChunk` that suspends throws, and would leave later loaders unstarted.\n const startedChunks = chunks.map(({ cacheKey, loader }) => ({\n cacheKey,\n promise: loader(),\n }));\n const dictionaries = startedChunks.map(({ cacheKey, promise }) =>\n loadChunk(cacheKey, promise)\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;AAsDA,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,QACV,+BAA+B;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAU;CACjC,MAAM,aAAa,UAAU;CAI7B,MAAM,eACJ,eAAe,SAAS,MAAM,KAAK,UAAU,SAAS;CAExD,IAAI,CAAC,YAAY,OAAO;EAAE;EAAc,QAAQ;EAAM,QAAQ,CAAC;CAAE;CAEjE,MAAM,SAA2B,CAAC;CAElC,MAAM,QACJ,MACA,YACA,aACY;EACZ,IAAI,WAAW,WAAW,GAAG;GAC3B,OAAO,KAAK;IACV,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,QAA2B;IAClE,QAAQ;GACV,CAAC;GACD,OAAO;EACT;EAEA,MAAM,CAAC,WAAW,GAAG,QAAQ;EAC7B,MAAM,OAAO;EAEb,IAAI,cAAc,UAAU,UAAU,SAAS,QAAW;GAExD,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,MACrC,MAAM,UAAU,OAAO,IAAI,IAAI,OAAO,KAAK,CAC9C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AAM,eAAe,MAAM,QAAQ,IAAI,OAAO,KAAK,EAAE,aAAa,OAAO,CAAC,CAAC;CAE3E,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C"}
@@ -1,5 +1,5 @@
1
1
  import { getEditedContent, getEditedDictionary } from "./deepTransformPlugins/getEditedContent.mjs";
2
- import { getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache } from "./interpreter/dictionaryTransformCache.mjs";
2
+ import { collectTransformCacheWrites, deleteTransformCacheWrites, getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache } from "./interpreter/dictionaryTransformCache.mjs";
3
3
  import { getCondition } from "./interpreter/getCondition.mjs";
4
4
  import { deepTransformNode } from "./interpreter/getContent/deepTransform.mjs";
5
5
  import { DEFAULT_PLURAL_VARIABLE, plural } from "./transpiler/plural/plural.mjs";
@@ -29,7 +29,7 @@ import { getInterpolableContent, isInterpolableWrapperNode, rebuildInterpolableC
29
29
  import { bindInsertedValues, conditionPlugin, enumerationPlugin, fallbackPlugin, filePlugin, genderPlugin, insertionPlugin, nestedPlugin, pluralPlugin, resolveInsertedSelector, selectPlugin, translationPlugin } from "./interpreter/getContent/plugins.mjs";
30
30
  import { getBasePlugins, getContent } from "./interpreter/getContent/getContent.mjs";
31
31
  import { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary } from "./dictionaryManipulator/preloadedDynamicLoader.mjs";
32
- import { QUALIFIER_DYNAMIC_TYPES_KEY, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./dictionaryManipulator/qualifiedDynamicLoader.mjs";
32
+ import { QUALIFIER_DYNAMIC_TYPES_KEY, getQualifiedDynamicChunks, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./dictionaryManipulator/qualifiedDynamicLoader.mjs";
33
33
  import { findPlainDynamicLoader, resolvePlainDynamicLoader } from "./dictionaryManipulator/plainDynamicLoader.mjs";
34
34
  import { getDictionaryAsync } from "./interpreter/getDictionaryAsync.mjs";
35
35
  import { getHTML } from "./interpreter/getHTML.mjs";
@@ -116,4 +116,4 @@ import { getIntlayerNodePrototype } from "./utils/intlayerNodePrototype.mjs";
116
116
  import { isSameKeyPath } from "./utils/isSameKeyPath.mjs";
117
117
  import { stringifyYaml } from "./utils/stringifyYaml.mjs";
118
118
 
119
- export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_NAME_START_R, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CachedIntl, CachedIntl as Intl, DEFAULT_PLURAL_VARIABLE, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, PRELOADED_DYNAMIC_KEY, Priority, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleScope, RuleType, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindInsertedValues, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, compact, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createMessageResolver, createRenderer, currency, cx, date, deepTransformNode, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, findPlainDynamicLoader, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCachedLocaleFromStorageClient, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryAsync, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDictionaryTransformCacheKey, getDomainHostname, getDomainOrigin, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getIntlayerAsync, getIntlayerNodePrototype, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromRequest, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPluginsCacheKey, getPlural, getPrefix, getPreloadLocale, getPreloadedDictionary, getReplacedValuesContent, getRewritePath, getRewriteRules, getRuleSet, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isDeclaredLocale, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, readTransformCache, rebuildInterpolableContent, reconstructQualifiedEntry, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveBrowserLocale, resolveDictionaryArgument, resolveEffectiveVariantId, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, resolveLocalizedPath, resolveMessage, resolveMessageNode, resolveMessageNodeToString, resolvePlainDynamicLoader, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, sanitizer, select, selectPlugin, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter, writeTransformCache };
119
+ export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_NAME_START_R, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CachedIntl, CachedIntl as Intl, DEFAULT_PLURAL_VARIABLE, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, PRELOADED_DYNAMIC_KEY, Priority, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleScope, RuleType, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindInsertedValues, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, collectTransformCacheWrites, compact, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createMessageResolver, createRenderer, currency, cx, date, deepTransformNode, deleteTransformCacheWrites, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, findPlainDynamicLoader, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCachedLocaleFromStorageClient, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryAsync, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDictionaryTransformCacheKey, getDomainHostname, getDomainOrigin, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getIntlayerAsync, getIntlayerNodePrototype, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromRequest, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPluginsCacheKey, getPlural, getPrefix, getPreloadLocale, getPreloadedDictionary, getQualifiedDynamicChunks, getReplacedValuesContent, getRewritePath, getRewriteRules, getRuleSet, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isDeclaredLocale, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, readTransformCache, rebuildInterpolableContent, reconstructQualifiedEntry, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveBrowserLocale, resolveDictionaryArgument, resolveEffectiveVariantId, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, resolveLocalizedPath, resolveMessage, resolveMessageNode, resolveMessageNodeToString, resolvePlainDynamicLoader, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, sanitizer, select, selectPlugin, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter, writeTransformCache };
@@ -99,8 +99,46 @@ const writeTransformCache = (dictionary, cacheKey, content) => {
99
99
  }
100
100
  if (entries.size >= MAX_ENTRIES_PER_DICTIONARY) entries.clear();
101
101
  entries.set(cacheKey, content);
102
+ activeWriteCollector?.push({
103
+ dictionary,
104
+ cacheKey,
105
+ content
106
+ });
102
107
  return content;
103
108
  };
109
+ /** Receives the writes made while {@link collectTransformCacheWrites} runs. */
110
+ let activeWriteCollector = null;
111
+ /**
112
+ * Runs `run` and reports every transform-cache entry it wrote, nested
113
+ * dictionaries included.
114
+ *
115
+ * Frameworks whose transformed content holds owned, disposable elements
116
+ * (Solid) use it to forget those entries once the scope that built the
117
+ * elements is disposed — see {@link deleteTransformCacheWrites}.
118
+ */
119
+ const collectTransformCacheWrites = (run) => {
120
+ const previousCollector = activeWriteCollector;
121
+ const writes = [];
122
+ activeWriteCollector = writes;
123
+ try {
124
+ return {
125
+ result: run(),
126
+ writes
127
+ };
128
+ } finally {
129
+ activeWriteCollector = previousCollector;
130
+ }
131
+ };
132
+ /**
133
+ * Removes entries reported by {@link collectTransformCacheWrites}. An entry
134
+ * rewritten since then holds other content and is kept.
135
+ */
136
+ const deleteTransformCacheWrites = (writes) => {
137
+ for (const { dictionary, cacheKey, content } of writes) {
138
+ const entries = transformCache.get(dictionary);
139
+ if (entries?.get(cacheKey) === content) entries.delete(cacheKey);
140
+ }
141
+ };
104
142
 
105
- export { getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache };
143
+ export { collectTransformCacheWrites, deleteTransformCacheWrites, getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache };
106
144
  //# sourceMappingURL=dictionaryTransformCache.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dictionaryTransformCache.mjs","names":[],"sources":["../../../src/interpreter/dictionaryTransformCache.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { Plugins } from './getContent';\n\n/**\n * Stable identity per plugin array, so a cache key can tell two custom plugin\n * sets apart.\n *\n * A boolean `custom / default` discriminator is not enough: two callers passing\n * *different* plugin arrays for the same dictionary and locale would collide,\n * and the second one would be served the first one's transformed content.\n *\n * Every framework package memoizes `getPlugins(locale)` per locale, so the same\n * locale always hands over the same array reference and reuses its identity —\n * an array built fresh on every call only ever costs a cache miss, never a\n * wrong hit.\n */\nconst pluginsIdentities = new WeakMap<Plugins[], string>();\n\nlet nextPluginsIdentity = 0;\n\n/**\n * Returns the cache-key fragment identifying a plugin array.\n *\n * @param plugins - The plugin array a transform runs with, or `undefined` when\n * the interpreter's base plugins are used.\n */\nexport const getPluginsCacheKey = (plugins?: Plugins[]): string => {\n if (!plugins) return 'base';\n\n const existingIdentity = pluginsIdentities.get(plugins);\n if (existingIdentity) return existingIdentity;\n\n nextPluginsIdentity += 1;\n const identity = `p${nextPluginsIdentity}`;\n pluginsIdentities.set(plugins, identity);\n\n return identity;\n};\n\n/**\n * Upper bound of transformed entries kept per dictionary. A dictionary is\n * transformed once per `locale × selector × plugin set`, so the realistic count\n * stays in the tens; the cap only guards pathological selector fan-out (a\n * collection read by hundreds of item ids). Reaching it drops the dictionary's\n * entries rather than evicting one by one — the next reads simply re-transform.\n */\nconst MAX_ENTRIES_PER_DICTIONARY = 256;\n\n/**\n * Transformed content, keyed first by the dictionary object it came from, then\n * by `locale × selector × plugin set`.\n *\n * Keying on the object rather than on the dictionary key is what makes this\n * safe for the paths the build optimization produces: `useDictionary` and\n * `useDictionaryDynamic` receive the dictionary itself, never its key, and a\n * dictionary replaced at runtime — a hot reload, a freshly loaded locale chunk\n * — is a new object, so it can never be served stale content. Being weak also\n * means a dictionary that goes out of scope takes its entries with it.\n */\nconst transformCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Whether a value is a settled dictionary worth memoizing.\n *\n * Two kinds of argument are deliberately excluded, and both are callable:\n * - a callable stand-in proxy — `solid-intlayer`'s `useLoadDynamic` hands\n * `getDictionary` a placeholder that reads a Solid resource on every property\n * access, so its content changes the moment the chunk lands. Memoizing it\n * would freeze the pending, empty state for the rest of the session.\n * - anything a non-typed caller passes that a `WeakMap` cannot hold as a key,\n * which would otherwise throw instead of simply running uncached.\n */\nconst isMemoizableDictionary = (value: unknown): value is object =>\n value !== null && typeof value === 'object';\n\n/**\n * Builds the cache key for one transformed entry.\n *\n * @param locale - The resolved locale, already defaulted by the caller.\n * @param selectorCacheKey - Serialized selector, empty for a plain dictionary.\n * @param plugins - The plugin array the transform runs with.\n */\nexport const getDictionaryTransformCacheKey = (\n locale: LocalesValues,\n selectorCacheKey: string,\n plugins?: Plugins[]\n): string => `${locale}_${selectorCacheKey}_${getPluginsCacheKey(plugins)}`;\n\n/**\n * Looks up the transformed content cached for `dictionary` under `cacheKey`.\n *\n * The hit is reported through a discriminated result rather than through the\n * value: `null` is a legitimate cached content — an unresolvable qualified\n * coordinate — so a miss can never be inferred from the value alone.\n */\nexport const readTransformCache = <Content>(\n dictionary: Dictionary | object,\n cacheKey: string\n): { hit: true; content: Content } | { hit: false } => {\n if (!isMemoizableDictionary(dictionary)) return { hit: false };\n\n const entries = transformCache.get(dictionary);\n\n if (!entries?.has(cacheKey)) return { hit: false };\n\n return { hit: true, content: entries.get(cacheKey) as Content };\n};\n\n/**\n * Stores transformed content for `dictionary` under `cacheKey`.\n *\n * @returns The stored content, so callers can `return writeTransformCache(...)`.\n */\nexport const writeTransformCache = <Content>(\n dictionary: Dictionary | object,\n cacheKey: string,\n content: Content\n): Content => {\n if (!isMemoizableDictionary(dictionary)) return content;\n\n let entries = transformCache.get(dictionary);\n\n if (!entries) {\n entries = new Map<string, unknown>();\n transformCache.set(dictionary, entries);\n }\n\n if (entries.size >= MAX_ENTRIES_PER_DICTIONARY) entries.clear();\n\n entries.set(cacheKey, content);\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,oCAAoB,IAAI,QAA2B;AAEzD,IAAI,sBAAsB;;;;;;;AAQ1B,MAAa,sBAAsB,YAAgC;CACjE,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,mBAAmB,kBAAkB,IAAI,OAAO;CACtD,IAAI,kBAAkB,OAAO;CAE7B,uBAAuB;CACvB,MAAM,WAAW,IAAI;CACrB,kBAAkB,IAAI,SAAS,QAAQ;CAEvC,OAAO;AACT;;;;;;;;AASA,MAAM,6BAA6B;;;;;;;;;;;;AAanC,MAAM,iCAAiB,IAAI,QAAsC;;;;;;;;;;;;AAajE,MAAM,0BAA0B,UAC9B,UAAU,QAAQ,OAAO,UAAU;;;;;;;;AASrC,MAAa,kCACX,QACA,kBACA,YACW,GAAG,OAAO,GAAG,iBAAiB,GAAG,mBAAmB,OAAO;;;;;;;;AASxE,MAAa,sBACX,YACA,aACqD;CACrD,IAAI,CAAC,uBAAuB,UAAU,GAAG,OAAO,EAAE,KAAK,MAAM;CAE7D,MAAM,UAAU,eAAe,IAAI,UAAU;CAE7C,IAAI,CAAC,SAAS,IAAI,QAAQ,GAAG,OAAO,EAAE,KAAK,MAAM;CAEjD,OAAO;EAAE,KAAK;EAAM,SAAS,QAAQ,IAAI,QAAQ;CAAa;AAChE;;;;;;AAOA,MAAa,uBACX,YACA,UACA,YACY;CACZ,IAAI,CAAC,uBAAuB,UAAU,GAAG,OAAO;CAEhD,IAAI,UAAU,eAAe,IAAI,UAAU;CAE3C,IAAI,CAAC,SAAS;EACZ,0BAAU,IAAI,IAAqB;EACnC,eAAe,IAAI,YAAY,OAAO;CACxC;CAEA,IAAI,QAAQ,QAAQ,4BAA4B,QAAQ,MAAM;CAE9D,QAAQ,IAAI,UAAU,OAAO;CAE7B,OAAO;AACT"}
1
+ {"version":3,"file":"dictionaryTransformCache.mjs","names":[],"sources":["../../../src/interpreter/dictionaryTransformCache.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { Plugins } from './getContent';\n\n/**\n * Stable identity per plugin array, so a cache key can tell two custom plugin\n * sets apart.\n *\n * A boolean `custom / default` discriminator is not enough: two callers passing\n * *different* plugin arrays for the same dictionary and locale would collide,\n * and the second one would be served the first one's transformed content.\n *\n * Every framework package memoizes `getPlugins(locale)` per locale, so the same\n * locale always hands over the same array reference and reuses its identity —\n * an array built fresh on every call only ever costs a cache miss, never a\n * wrong hit.\n */\nconst pluginsIdentities = new WeakMap<Plugins[], string>();\n\nlet nextPluginsIdentity = 0;\n\n/**\n * Returns the cache-key fragment identifying a plugin array.\n *\n * @param plugins - The plugin array a transform runs with, or `undefined` when\n * the interpreter's base plugins are used.\n */\nexport const getPluginsCacheKey = (plugins?: Plugins[]): string => {\n if (!plugins) return 'base';\n\n const existingIdentity = pluginsIdentities.get(plugins);\n if (existingIdentity) return existingIdentity;\n\n nextPluginsIdentity += 1;\n const identity = `p${nextPluginsIdentity}`;\n pluginsIdentities.set(plugins, identity);\n\n return identity;\n};\n\n/**\n * Upper bound of transformed entries kept per dictionary. A dictionary is\n * transformed once per `locale × selector × plugin set`, so the realistic count\n * stays in the tens; the cap only guards pathological selector fan-out (a\n * collection read by hundreds of item ids). Reaching it drops the dictionary's\n * entries rather than evicting one by one — the next reads simply re-transform.\n */\nconst MAX_ENTRIES_PER_DICTIONARY = 256;\n\n/**\n * Transformed content, keyed first by the dictionary object it came from, then\n * by `locale × selector × plugin set`.\n *\n * Keying on the object rather than on the dictionary key is what makes this\n * safe for the paths the build optimization produces: `useDictionary` and\n * `useDictionaryDynamic` receive the dictionary itself, never its key, and a\n * dictionary replaced at runtime — a hot reload, a freshly loaded locale chunk\n * — is a new object, so it can never be served stale content. Being weak also\n * means a dictionary that goes out of scope takes its entries with it.\n */\nconst transformCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Whether a value is a settled dictionary worth memoizing.\n *\n * Two kinds of argument are deliberately excluded, and both are callable:\n * - a callable stand-in proxy — `solid-intlayer`'s `useLoadDynamic` hands\n * `getDictionary` a placeholder that reads a Solid resource on every property\n * access, so its content changes the moment the chunk lands. Memoizing it\n * would freeze the pending, empty state for the rest of the session.\n * - anything a non-typed caller passes that a `WeakMap` cannot hold as a key,\n * which would otherwise throw instead of simply running uncached.\n */\nconst isMemoizableDictionary = (value: unknown): value is object =>\n value !== null && typeof value === 'object';\n\n/**\n * Builds the cache key for one transformed entry.\n *\n * @param locale - The resolved locale, already defaulted by the caller.\n * @param selectorCacheKey - Serialized selector, empty for a plain dictionary.\n * @param plugins - The plugin array the transform runs with.\n */\nexport const getDictionaryTransformCacheKey = (\n locale: LocalesValues,\n selectorCacheKey: string,\n plugins?: Plugins[]\n): string => `${locale}_${selectorCacheKey}_${getPluginsCacheKey(plugins)}`;\n\n/**\n * Looks up the transformed content cached for `dictionary` under `cacheKey`.\n *\n * The hit is reported through a discriminated result rather than through the\n * value: `null` is a legitimate cached content — an unresolvable qualified\n * coordinate — so a miss can never be inferred from the value alone.\n */\nexport const readTransformCache = <Content>(\n dictionary: Dictionary | object,\n cacheKey: string\n): { hit: true; content: Content } | { hit: false } => {\n if (!isMemoizableDictionary(dictionary)) return { hit: false };\n\n const entries = transformCache.get(dictionary);\n\n if (!entries?.has(cacheKey)) return { hit: false };\n\n return { hit: true, content: entries.get(cacheKey) as Content };\n};\n\n/**\n * Stores transformed content for `dictionary` under `cacheKey`.\n *\n * @returns The stored content, so callers can `return writeTransformCache(...)`.\n */\nexport const writeTransformCache = <Content>(\n dictionary: Dictionary | object,\n cacheKey: string,\n content: Content\n): Content => {\n if (!isMemoizableDictionary(dictionary)) return content;\n\n let entries = transformCache.get(dictionary);\n\n if (!entries) {\n entries = new Map<string, unknown>();\n transformCache.set(dictionary, entries);\n }\n\n if (entries.size >= MAX_ENTRIES_PER_DICTIONARY) entries.clear();\n\n entries.set(cacheKey, content);\n activeWriteCollector?.push({ dictionary, cacheKey, content });\n\n return content;\n};\n\n/** One entry stored by {@link writeTransformCache}. */\nexport type TransformCacheWrite = {\n dictionary: object;\n cacheKey: string;\n content: unknown;\n};\n\n/** Receives the writes made while {@link collectTransformCacheWrites} runs. */\nlet activeWriteCollector: TransformCacheWrite[] | null = null;\n\n/**\n * Runs `run` and reports every transform-cache entry it wrote, nested\n * dictionaries included.\n *\n * Frameworks whose transformed content holds owned, disposable elements\n * (Solid) use it to forget those entries once the scope that built the\n * elements is disposed — see {@link deleteTransformCacheWrites}.\n */\nexport const collectTransformCacheWrites = <Result>(\n run: () => Result\n): { result: Result; writes: TransformCacheWrite[] } => {\n const previousCollector = activeWriteCollector;\n const writes: TransformCacheWrite[] = [];\n\n activeWriteCollector = writes;\n\n try {\n return { result: run(), writes };\n } finally {\n activeWriteCollector = previousCollector;\n }\n};\n\n/**\n * Removes entries reported by {@link collectTransformCacheWrites}. An entry\n * rewritten since then holds other content and is kept.\n */\nexport const deleteTransformCacheWrites = (\n writes: readonly TransformCacheWrite[]\n): void => {\n for (const { dictionary, cacheKey, content } of writes) {\n const entries = transformCache.get(dictionary);\n\n if (entries?.get(cacheKey) === content) entries.delete(cacheKey);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,oCAAoB,IAAI,QAA2B;AAEzD,IAAI,sBAAsB;;;;;;;AAQ1B,MAAa,sBAAsB,YAAgC;CACjE,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,mBAAmB,kBAAkB,IAAI,OAAO;CACtD,IAAI,kBAAkB,OAAO;CAE7B,uBAAuB;CACvB,MAAM,WAAW,IAAI;CACrB,kBAAkB,IAAI,SAAS,QAAQ;CAEvC,OAAO;AACT;;;;;;;;AASA,MAAM,6BAA6B;;;;;;;;;;;;AAanC,MAAM,iCAAiB,IAAI,QAAsC;;;;;;;;;;;;AAajE,MAAM,0BAA0B,UAC9B,UAAU,QAAQ,OAAO,UAAU;;;;;;;;AASrC,MAAa,kCACX,QACA,kBACA,YACW,GAAG,OAAO,GAAG,iBAAiB,GAAG,mBAAmB,OAAO;;;;;;;;AASxE,MAAa,sBACX,YACA,aACqD;CACrD,IAAI,CAAC,uBAAuB,UAAU,GAAG,OAAO,EAAE,KAAK,MAAM;CAE7D,MAAM,UAAU,eAAe,IAAI,UAAU;CAE7C,IAAI,CAAC,SAAS,IAAI,QAAQ,GAAG,OAAO,EAAE,KAAK,MAAM;CAEjD,OAAO;EAAE,KAAK;EAAM,SAAS,QAAQ,IAAI,QAAQ;CAAa;AAChE;;;;;;AAOA,MAAa,uBACX,YACA,UACA,YACY;CACZ,IAAI,CAAC,uBAAuB,UAAU,GAAG,OAAO;CAEhD,IAAI,UAAU,eAAe,IAAI,UAAU;CAE3C,IAAI,CAAC,SAAS;EACZ,0BAAU,IAAI,IAAqB;EACnC,eAAe,IAAI,YAAY,OAAO;CACxC;CAEA,IAAI,QAAQ,QAAQ,4BAA4B,QAAQ,MAAM;CAE9D,QAAQ,IAAI,UAAU,OAAO;CAC7B,sBAAsB,KAAK;EAAE;EAAY;EAAU;CAAQ,CAAC;CAE5D,OAAO;AACT;;AAUA,IAAI,uBAAqD;;;;;;;;;AAUzD,MAAa,+BACX,QACsD;CACtD,MAAM,oBAAoB;CAC1B,MAAM,SAAgC,CAAC;CAEvC,uBAAuB;CAEvB,IAAI;EACF,OAAO;GAAE,QAAQ,IAAI;GAAG;EAAO;CACjC,UAAU;EACR,uBAAuB;CACzB;AACF;;;;;AAMA,MAAa,8BACX,WACS;CACT,KAAK,MAAM,EAAE,YAAY,UAAU,aAAa,QAAQ;EACtD,MAAM,UAAU,eAAe,IAAI,UAAU;EAE7C,IAAI,SAAS,IAAI,QAAQ,MAAM,SAAS,QAAQ,OAAO,QAAQ;CACjE;AACF"}
@@ -1,4 +1,4 @@
1
- import { getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache } from "./dictionaryTransformCache.mjs";
1
+ import { collectTransformCacheWrites, deleteTransformCacheWrites, getDictionaryTransformCacheKey, getPluginsCacheKey, readTransformCache, writeTransformCache } from "./dictionaryTransformCache.mjs";
2
2
  import { getCondition } from "./getCondition.mjs";
3
3
  import { deepTransformNode } from "./getContent/deepTransform.mjs";
4
4
  import { getDictionary } from "./getDictionary.mjs";
@@ -19,4 +19,4 @@ import { getInterpolableContent, isInterpolableWrapperNode, rebuildInterpolableC
19
19
  import { registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, resolveInterpreterLocale, resolveInterpreterLocaleAsync } from "./resolveInterpreterLocale.mjs";
20
20
  import { splitInsertionTemplate } from "./splitAndJoinInsertion.mjs";
21
21
 
22
- export { bindInsertedValues, conditionPlugin, deepTransformNode, enumerationPlugin, fallbackPlugin, filePlugin, findMatchingCondition, genderPlugin, getBasePlugins, getCondition, getContent, getDictionary, getDictionaryAsync, getDictionaryTransformCacheKey, getEnumeration, getGender, getHTML, getInsertion, getInterpolableContent, getIntlayer, getIntlayerAsync, getNesting, getPluginsCacheKey, getPlural, getSelect, getTranslation, insertionPlugin, isInterpolableWrapperNode, nestedPlugin, pluralPlugin, readTransformCache, rebuildInterpolableContent, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, selectPlugin, splitInsertionTemplate, transformInterpolableNode, translationPlugin, writeTransformCache };
22
+ export { bindInsertedValues, collectTransformCacheWrites, conditionPlugin, deepTransformNode, deleteTransformCacheWrites, enumerationPlugin, fallbackPlugin, filePlugin, findMatchingCondition, genderPlugin, getBasePlugins, getCondition, getContent, getDictionary, getDictionaryAsync, getDictionaryTransformCacheKey, getEnumeration, getGender, getHTML, getInsertion, getInterpolableContent, getIntlayer, getIntlayerAsync, getNesting, getPluginsCacheKey, getPlural, getSelect, getTranslation, insertionPlugin, isInterpolableWrapperNode, nestedPlugin, pluralPlugin, readTransformCache, rebuildInterpolableContent, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, selectPlugin, splitInsertionTemplate, transformInterpolableNode, translationPlugin, writeTransformCache };