@intlayer/core 9.8.1 → 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.
- package/dist/cjs/dictionaryManipulator/index.cjs +1 -0
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +15 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/interpreter/dictionaryTransformCache.cjs +40 -0
- package/dist/cjs/interpreter/dictionaryTransformCache.cjs.map +1 -1
- package/dist/cjs/interpreter/index.cjs +2 -0
- package/dist/cjs/messageFormat/resolveMessage.cjs +35 -18
- package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
- package/dist/esm/dictionaryManipulator/index.mjs +2 -2
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +15 -2
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
- package/dist/esm/index.mjs +3 -3
- package/dist/esm/interpreter/dictionaryTransformCache.mjs +39 -1
- package/dist/esm/interpreter/dictionaryTransformCache.mjs.map +1 -1
- package/dist/esm/interpreter/index.mjs +2 -2
- package/dist/esm/messageFormat/resolveMessage.mjs +35 -18
- package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
- package/dist/types/dictionaryManipulator/index.d.ts +2 -2
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +12 -0
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/interpreter/dictionaryTransformCache.d.ts +23 -0
- package/dist/types/interpreter/dictionaryTransformCache.d.ts.map +1 -1
- package/dist/types/interpreter/index.d.ts +2 -2
- package/dist/types/messageFormat/index.d.ts +2 -2
- package/dist/types/messageFormat/resolveMessage.d.ts +18 -4
- package/dist/types/messageFormat/resolveMessage.d.ts.map +1 -1
- package/package.json +6 -6
|
@@ -50,6 +50,7 @@ exports.getNestedDictionaryReferences = require_dictionaryManipulator_getNestedD
|
|
|
50
50
|
exports.getNodeChildren = require_dictionaryManipulator_getNodeChildren.getNodeChildren;
|
|
51
51
|
exports.getNodeType = require_dictionaryManipulator_getNodeType.getNodeType;
|
|
52
52
|
exports.getPreloadedDictionary = require_dictionaryManipulator_preloadedDynamicLoader.getPreloadedDictionary;
|
|
53
|
+
exports.getQualifiedDynamicChunks = require_dictionaryManipulator_qualifiedDynamicLoader.getQualifiedDynamicChunks;
|
|
53
54
|
exports.getVariantIds = require_dictionaryManipulator_qualifiedDictionaryDeclaration.getVariantIds;
|
|
54
55
|
exports.isQualifiedDictionaryGroup = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDictionaryGroup;
|
|
55
56
|
exports.isQualifiedDynamicLoaderMap = require_dictionaryManipulator_qualifiedDynamicLoader.isQualifiedDynamicLoaderMap;
|
|
@@ -49,6 +49,16 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
|
|
|
49
49
|
};
|
|
50
50
|
};
|
|
51
51
|
/**
|
|
52
|
+
* Lists the chunks a selector targets in a qualified dynamic loader map,
|
|
53
|
+
* without loading them — lets a caller warm a suspender cache ahead of render.
|
|
54
|
+
*
|
|
55
|
+
* @returns The targeted chunks, empty when a required coordinate is absent.
|
|
56
|
+
*/
|
|
57
|
+
const getQualifiedDynamicChunks = (loaderMap, key, locale, selector) => {
|
|
58
|
+
const { missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
|
|
59
|
+
return missed ? [] : chunks;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
52
62
|
* Resolves the content of a qualified dynamic loader map against a selector,
|
|
53
63
|
* loading only the chunk(s) the selector actually targets.
|
|
54
64
|
*
|
|
@@ -75,7 +85,10 @@ const resolveQualifiedDynamicContent = (params) => {
|
|
|
75
85
|
const { loaderMap, key, locale, selector, loadChunk, transform } = params;
|
|
76
86
|
const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
|
|
77
87
|
if (missed) return itemAxisOpen ? [] : null;
|
|
78
|
-
const dictionaries = chunks.map(({ cacheKey, loader }) =>
|
|
88
|
+
const dictionaries = chunks.map(({ cacheKey, loader }) => ({
|
|
89
|
+
cacheKey,
|
|
90
|
+
promise: loader()
|
|
91
|
+
})).map(({ cacheKey, promise }) => loadChunk(cacheKey, promise));
|
|
79
92
|
if (itemAxisOpen) return dictionaries.map(transform);
|
|
80
93
|
const [dictionary] = dictionaries;
|
|
81
94
|
return dictionary ? transform(dictionary) : null;
|
|
@@ -107,6 +120,7 @@ Object.defineProperty(exports, "QUALIFIER_DYNAMIC_TYPES_KEY", {
|
|
|
107
120
|
return _intlayer_config_defaultValues.QUALIFIER_DYNAMIC_TYPES_KEY;
|
|
108
121
|
}
|
|
109
122
|
});
|
|
123
|
+
exports.getQualifiedDynamicChunks = getQualifiedDynamicChunks;
|
|
110
124
|
exports.isQualifiedDynamicLoaderMap = isQualifiedDynamicLoaderMap;
|
|
111
125
|
exports.resolveQualifiedDynamicContent = resolveQualifiedDynamicContent;
|
|
112
126
|
exports.resolveQualifiedDynamicContentAsync = resolveQualifiedDynamicContentAsync;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qualifiedDynamicLoader.cjs","names":["QUALIFIER_DYNAMIC_TYPES_KEY","resolveEffectiveVariantId","serializeVariantChain"],"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 return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;;AAsDA,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,QACVA,8DAA+B;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAUA;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,GACE,KAAK,KAAK,UAAW,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;GAEnD,OAAO;EACT;EAIA,MAAM,UACJ,cAAc,YACVC,4EACEC,wEAAsB,UAAU,OAAO,IACtC,cAAc,KAAK,eAAe,MACrC,IACA,OAAO,UAAU,IAAI;EAE3B,MAAM,QAAQ,KAAK;EACnB,IAAI,CAAC,OAAO,OAAO;EAEnB,OAAO,KAAK,OAAO,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;CACjD;CAIA,OAAO;EAAE;EAAc,QAAQ,CAFjB,KAAK,YAAY,gBAAgB,CAAC,CAEZ;EAAG;CAAO;AAChD;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kCAA2C,WAOtB;CAChC,MAAM,EAAE,WAAW,KAAK,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.cjs","names":["QUALIFIER_DYNAMIC_TYPES_KEY","resolveEffectiveVariantId","serializeVariantChain"],"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,QACVA,8DAA+B;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAUA;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,QAA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B,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"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -224,6 +224,7 @@ exports.buildMaskPlugin = require_deepTransformPlugins_getMaskContent.buildMaskP
|
|
|
224
224
|
exports.captureNothing = require_markdown_utils.captureNothing;
|
|
225
225
|
exports.checkIsURLAbsolute = require_utils_checkIsURLAbsolute.checkIsURLAbsolute;
|
|
226
226
|
exports.checkMissingLocalesPlugin = require_deepTransformPlugins_getMissingLocalesContent.checkMissingLocalesPlugin;
|
|
227
|
+
exports.collectTransformCacheWrites = require_interpreter_dictionaryTransformCache.collectTransformCacheWrites;
|
|
227
228
|
exports.compact = require_formatters_compact.compact;
|
|
228
229
|
exports.comparePaths = require_localization_comparePaths.comparePaths;
|
|
229
230
|
exports.compile = require_markdown_compiler.compile;
|
|
@@ -237,6 +238,7 @@ exports.currency = require_formatters_currency.currency;
|
|
|
237
238
|
exports.cx = require_markdown_utils.cx;
|
|
238
239
|
exports.date = require_formatters_date.date;
|
|
239
240
|
exports.deepTransformNode = require_interpreter_getContent_deepTransform.deepTransformNode;
|
|
241
|
+
exports.deleteTransformCacheWrites = require_interpreter_dictionaryTransformCache.deleteTransformCacheWrites;
|
|
240
242
|
exports.editDictionaryByKeyPath = require_dictionaryManipulator_editDictionaryByKeyPath.editDictionaryByKeyPath;
|
|
241
243
|
exports.enu = require_transpiler_enumeration_enumeration.enu;
|
|
242
244
|
exports.enumerationPlugin = require_interpreter_getContent_plugins.enumerationPlugin;
|
|
@@ -326,6 +328,7 @@ exports.getPlural = require_interpreter_getPlural.getPlural;
|
|
|
326
328
|
exports.getPrefix = require_localization_getPrefix.getPrefix;
|
|
327
329
|
exports.getPreloadLocale = require_localization_resolveBrowserLocale.getPreloadLocale;
|
|
328
330
|
exports.getPreloadedDictionary = require_dictionaryManipulator_preloadedDynamicLoader.getPreloadedDictionary;
|
|
331
|
+
exports.getQualifiedDynamicChunks = require_dictionaryManipulator_qualifiedDynamicLoader.getQualifiedDynamicChunks;
|
|
329
332
|
exports.getReplacedValuesContent = require_deepTransformPlugins_getReplacedValuesContent.getReplacedValuesContent;
|
|
330
333
|
exports.getRewritePath = require_localization_rewriteUtils.getRewritePath;
|
|
331
334
|
exports.getRewriteRules = require_localization_rewriteMatch.getRewriteRules;
|
|
@@ -100,9 +100,49 @@ const writeTransformCache = (dictionary, cacheKey, content) => {
|
|
|
100
100
|
}
|
|
101
101
|
if (entries.size >= MAX_ENTRIES_PER_DICTIONARY) entries.clear();
|
|
102
102
|
entries.set(cacheKey, content);
|
|
103
|
+
activeWriteCollector?.push({
|
|
104
|
+
dictionary,
|
|
105
|
+
cacheKey,
|
|
106
|
+
content
|
|
107
|
+
});
|
|
103
108
|
return content;
|
|
104
109
|
};
|
|
110
|
+
/** Receives the writes made while {@link collectTransformCacheWrites} runs. */
|
|
111
|
+
let activeWriteCollector = null;
|
|
112
|
+
/**
|
|
113
|
+
* Runs `run` and reports every transform-cache entry it wrote, nested
|
|
114
|
+
* dictionaries included.
|
|
115
|
+
*
|
|
116
|
+
* Frameworks whose transformed content holds owned, disposable elements
|
|
117
|
+
* (Solid) use it to forget those entries once the scope that built the
|
|
118
|
+
* elements is disposed — see {@link deleteTransformCacheWrites}.
|
|
119
|
+
*/
|
|
120
|
+
const collectTransformCacheWrites = (run) => {
|
|
121
|
+
const previousCollector = activeWriteCollector;
|
|
122
|
+
const writes = [];
|
|
123
|
+
activeWriteCollector = writes;
|
|
124
|
+
try {
|
|
125
|
+
return {
|
|
126
|
+
result: run(),
|
|
127
|
+
writes
|
|
128
|
+
};
|
|
129
|
+
} finally {
|
|
130
|
+
activeWriteCollector = previousCollector;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Removes entries reported by {@link collectTransformCacheWrites}. An entry
|
|
135
|
+
* rewritten since then holds other content and is kept.
|
|
136
|
+
*/
|
|
137
|
+
const deleteTransformCacheWrites = (writes) => {
|
|
138
|
+
for (const { dictionary, cacheKey, content } of writes) {
|
|
139
|
+
const entries = transformCache.get(dictionary);
|
|
140
|
+
if (entries?.get(cacheKey) === content) entries.delete(cacheKey);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
105
143
|
|
|
144
|
+
exports.collectTransformCacheWrites = collectTransformCacheWrites;
|
|
145
|
+
exports.deleteTransformCacheWrites = deleteTransformCacheWrites;
|
|
106
146
|
exports.getDictionaryTransformCacheKey = getDictionaryTransformCacheKey;
|
|
107
147
|
exports.getPluginsCacheKey = getPluginsCacheKey;
|
|
108
148
|
exports.readTransformCache = readTransformCache;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dictionaryTransformCache.cjs","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;
|
|
1
|
+
{"version":3,"file":"dictionaryTransformCache.cjs","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"}
|
|
@@ -21,8 +21,10 @@ const require_interpreter_resolveInterpreterLocale = require("./resolveInterpret
|
|
|
21
21
|
const require_interpreter_splitAndJoinInsertion = require("./splitAndJoinInsertion.cjs");
|
|
22
22
|
|
|
23
23
|
exports.bindInsertedValues = require_interpreter_getContent_plugins.bindInsertedValues;
|
|
24
|
+
exports.collectTransformCacheWrites = require_interpreter_dictionaryTransformCache.collectTransformCacheWrites;
|
|
24
25
|
exports.conditionPlugin = require_interpreter_getContent_plugins.conditionPlugin;
|
|
25
26
|
exports.deepTransformNode = require_interpreter_getContent_deepTransform.deepTransformNode;
|
|
27
|
+
exports.deleteTransformCacheWrites = require_interpreter_dictionaryTransformCache.deleteTransformCacheWrites;
|
|
26
28
|
exports.enumerationPlugin = require_interpreter_getContent_plugins.enumerationPlugin;
|
|
27
29
|
exports.fallbackPlugin = require_interpreter_getContent_plugins.fallbackPlugin;
|
|
28
30
|
exports.filePlugin = require_interpreter_getContent_plugins.filePlugin;
|
|
@@ -30,8 +30,25 @@ const resolveValuePath = (values, path) => {
|
|
|
30
30
|
}
|
|
31
31
|
return current;
|
|
32
32
|
};
|
|
33
|
-
/**
|
|
34
|
-
const
|
|
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
|
+
}
|
|
35
52
|
try {
|
|
36
53
|
if (type === "number") {
|
|
37
54
|
const numberValue = Number(value);
|
|
@@ -61,14 +78,14 @@ const formatArgument = (value, type, style, locale) => {
|
|
|
61
78
|
* 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`
|
|
62
79
|
* 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)
|
|
63
80
|
*/
|
|
64
|
-
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) => {
|
|
65
82
|
const value = resolveValuePath(values, path);
|
|
66
83
|
if (value === void 0) return match;
|
|
67
|
-
return type ? formatArgument(value, type, style, locale) : String(value);
|
|
84
|
+
return type ? formatArgument(value, type, style, locale, formatters) : String(value);
|
|
68
85
|
}).replace(/\{\s*([\w.]+)\s*,\s*(\w+)\s*(?:,\s*([^}]+?)\s*)?\}/g, (match, path, type, style) => {
|
|
69
86
|
const value = resolveValuePath(values, path);
|
|
70
87
|
if (value === void 0) return match;
|
|
71
|
-
return formatArgument(value, type, style, locale);
|
|
88
|
+
return formatArgument(value, type, style, locale, formatters);
|
|
72
89
|
}).replace(/\{\s*([\w.]+)\s*\}/g, (match, path) => {
|
|
73
90
|
const value = resolveValuePath(values, path);
|
|
74
91
|
return value === void 0 ? match : String(value);
|
|
@@ -83,25 +100,25 @@ const getSelectorValue = (values, variableName) => values[variableName] ?? value
|
|
|
83
100
|
* Function nodes (produced by the interpreter plugins for `insertion`,
|
|
84
101
|
* `enumeration` and `plural` content) are invoked with the values.
|
|
85
102
|
*/
|
|
86
|
-
const resolveMessageNode = (node, values = {}, locale = "en") => {
|
|
103
|
+
const resolveMessageNode = (node, values = {}, locale = "en", formatters) => {
|
|
87
104
|
if (node === null || node === void 0) return node;
|
|
88
|
-
if (typeof node === "string") return interpolateMessage(node, values, locale);
|
|
105
|
+
if (typeof node === "string") return interpolateMessage(node, values, locale, formatters);
|
|
89
106
|
if (typeof node === "number" || typeof node === "boolean") return String(node);
|
|
90
107
|
if (typeof node === "function") try {
|
|
91
|
-
return resolveMessageNode(node(values), values, locale);
|
|
108
|
+
return resolveMessageNode(node(values), values, locale, formatters);
|
|
92
109
|
} catch {
|
|
93
110
|
return;
|
|
94
111
|
}
|
|
95
|
-
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("");
|
|
96
113
|
const typedNode = node;
|
|
97
|
-
if (typedNode.nodeType === _intlayer_types_nodeType.INSERTION) return resolveMessageNode(typedNode[_intlayer_types_nodeType.INSERTION], values, locale);
|
|
98
|
-
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);
|
|
99
116
|
if (typedNode.nodeType === _intlayer_types_nodeType.PLURAL) {
|
|
100
117
|
const pluralState = typedNode[_intlayer_types_nodeType.PLURAL];
|
|
101
118
|
const variableName = typeof typedNode.variable === "string" ? typedNode.variable : require_transpiler_plural_plural.DEFAULT_PLURAL_VARIABLE;
|
|
102
119
|
const count = Number(getSelectorValue(values, variableName) ?? 1);
|
|
103
120
|
const selected = require_interpreter_getPlural.getPlural(pluralState, count, locale);
|
|
104
|
-
return resolveMessageNode(selected, values, locale);
|
|
121
|
+
return resolveMessageNode(selected, values, locale, formatters);
|
|
105
122
|
}
|
|
106
123
|
if (typedNode.nodeType === _intlayer_types_nodeType.ENUMERATION) {
|
|
107
124
|
const enumerationState = typedNode[_intlayer_types_nodeType.ENUMERATION];
|
|
@@ -120,19 +137,19 @@ const resolveMessageNode = (node, values = {}, locale = "en") => {
|
|
|
120
137
|
const matchedKey = require_interpreter_getEnumeration.findMatchingCondition(options, count);
|
|
121
138
|
selected = matchedKey ? options[matchedKey] : options[require_utils_intl.getCachedIntl("PluralRules", locale).select(count)] ?? require_interpreter_getEnumeration.getEnumeration(options, count);
|
|
122
139
|
} else selected = options[String(selector)] ?? options.fallback ?? options.other;
|
|
123
|
-
return resolveMessageNode(selected, values, locale);
|
|
140
|
+
return resolveMessageNode(selected, values, locale, formatters);
|
|
124
141
|
}
|
|
125
142
|
if (typedNode.nodeType === _intlayer_types_nodeType.SELECT) {
|
|
126
143
|
const selectState = typedNode[_intlayer_types_nodeType.SELECT];
|
|
127
144
|
const variableName = typeof typedNode.variable === "string" ? typedNode.variable : "value";
|
|
128
145
|
const selector = getSelectorValue(values, variableName);
|
|
129
146
|
const selected = require_interpreter_getSelect.getSelect(selectState, String(selector ?? ""));
|
|
130
|
-
return resolveMessageNode(selected, values, locale);
|
|
147
|
+
return resolveMessageNode(selected, values, locale, formatters);
|
|
131
148
|
}
|
|
132
149
|
if (typedNode.nodeType === _intlayer_types_nodeType.GENDER) {
|
|
133
150
|
const genderState = typedNode[_intlayer_types_nodeType.GENDER];
|
|
134
151
|
const selected = genderState[String(values.gender ?? "")] ?? genderState.fallback ?? genderState.other;
|
|
135
|
-
return resolveMessageNode(selected, values, locale);
|
|
152
|
+
return resolveMessageNode(selected, values, locale, formatters);
|
|
136
153
|
}
|
|
137
154
|
return node;
|
|
138
155
|
};
|
|
@@ -145,8 +162,8 @@ const resolveMessageNode = (node, values = {}, locale = "en") => {
|
|
|
145
162
|
* callables, so no message parser is involved. Plain strings still get
|
|
146
163
|
* `{{name}}` / `{name}` / `{value, number}` interpolation.
|
|
147
164
|
*/
|
|
148
|
-
const resolveMessageNodeToString = (node, values = {}, locale = "en") => {
|
|
149
|
-
const resolved = resolveMessageNode(node, values, locale);
|
|
165
|
+
const resolveMessageNodeToString = (node, values = {}, locale = "en", formatters) => {
|
|
166
|
+
const resolved = resolveMessageNode(node, values, locale, formatters);
|
|
150
167
|
return typeof resolved === "string" ? resolved : String(resolved ?? "");
|
|
151
168
|
};
|
|
152
169
|
/**
|
|
@@ -162,7 +179,7 @@ const resolveMessageNodeToString = (node, values = {}, locale = "en") => {
|
|
|
162
179
|
* resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'
|
|
163
180
|
* ```
|
|
164
181
|
*/
|
|
165
|
-
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);
|
|
166
183
|
const DIALECT_FORMATTERS = {
|
|
167
184
|
icu: require_messageFormat_ICU.icuToIntlayerFormatter,
|
|
168
185
|
i18next: require_messageFormat_i18next.i18nextToIntlayerFormatter,
|
|
@@ -1 +1 @@
|
|
|
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/** 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 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);\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);\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":";;;;;;;;;;;;;;;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;;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,KAA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,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"}
|
|
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,S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nC,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 }) =>
|
|
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 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;G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,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"],"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