@intlayer/core 9.8.0 → 9.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/ICU.cjs +50 -25
- package/dist/cjs/messageFormat/ICU.cjs.map +1 -1
- package/dist/cjs/messageFormat/resolveMessage.cjs +43 -21
- 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/ICU.mjs +51 -26
- package/dist/esm/messageFormat/ICU.mjs.map +1 -1
- package/dist/esm/messageFormat/resolveMessage.mjs +44 -22
- 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/ICU.d.ts.map +1 -1
- 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,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AU,cAAc;EAC1D;EACA,SAAS,OAAO;CAClB,EACiC,CAAC,CAAC,KAAK,EAAE,UAAU,cAClD,UAAU,UAAU,OAAO,CAC7B;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"}
|
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;
|
|
@@ -11,6 +11,30 @@ let _intlayer_types_nodeType = require("@intlayer/types/nodeType");
|
|
|
11
11
|
_intlayer_types_nodeType = require_runtime.__toESM(_intlayer_types_nodeType);
|
|
12
12
|
|
|
13
13
|
// src/messageFormat/ICU.ts
|
|
14
|
+
/** Characters an ICU apostrophe can quote to make them literal. */
|
|
15
|
+
const QUOTABLE_SYNTAX_CHARACTERS = ["{", "}"];
|
|
16
|
+
/** ICU plural categories (CLDR) and the enumeration key each maps to. */
|
|
17
|
+
const PLURAL_CATEGORY_TO_ENUMERATION_KEY = {
|
|
18
|
+
one: "1",
|
|
19
|
+
two: "2",
|
|
20
|
+
few: "<=3",
|
|
21
|
+
many: ">=4",
|
|
22
|
+
other: "fallback"
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Converts Intlayer text to ICU text:
|
|
26
|
+
* - `{{name}}` → `{name}`
|
|
27
|
+
* - formatted arguments `{value, number, percent}` are kept as is
|
|
28
|
+
* - any other `{` / `}` is a literal and gets quoted (`'{'`)
|
|
29
|
+
*/
|
|
30
|
+
const intlayerTextToIcu = (text) => {
|
|
31
|
+
return text.replace(/\{\{\s*([^{}\s]+?)\s*\}\}|\{\s*[\w.]+\s*,\s*\w+\s*(?:,[^{}]*)?\}|'(?=[{}])|[{}]/g, (match, variableName) => {
|
|
32
|
+
if (variableName) return `{${variableName}}`;
|
|
33
|
+
if (match === "'") return "''";
|
|
34
|
+
if (match === "{" || match === "}") return `'${match}'`;
|
|
35
|
+
return match;
|
|
36
|
+
});
|
|
37
|
+
};
|
|
14
38
|
const parseICU = (text) => {
|
|
15
39
|
let index = 0;
|
|
16
40
|
const parseNodes = () => {
|
|
@@ -31,10 +55,13 @@ const parseICU = (text) => {
|
|
|
31
55
|
currentText += "'";
|
|
32
56
|
index += 2;
|
|
33
57
|
} else {
|
|
34
|
-
const nextQuote = text.indexOf("'", index + 1);
|
|
58
|
+
const nextQuote = QUOTABLE_SYNTAX_CHARACTERS.includes(text[index + 1] ?? "") ? text.indexOf("'", index + 1) : -1;
|
|
35
59
|
if (nextQuote !== -1) {
|
|
36
|
-
currentText += text.substring(index + 1, nextQuote);
|
|
60
|
+
currentText += text.substring(index + 1, nextQuote).replace(/''/g, "'");
|
|
37
61
|
index = nextQuote + 1;
|
|
62
|
+
} else if (QUOTABLE_SYNTAX_CHARACTERS.includes(text[index + 1] ?? "")) {
|
|
63
|
+
currentText += text.substring(index + 1);
|
|
64
|
+
index = text.length;
|
|
38
65
|
} else {
|
|
39
66
|
currentText += "'";
|
|
40
67
|
index++;
|
|
@@ -140,11 +167,17 @@ const parseICU = (text) => {
|
|
|
140
167
|
};
|
|
141
168
|
return parseNodes();
|
|
142
169
|
};
|
|
170
|
+
/**
|
|
171
|
+
* Whether a text holds a `{` / `}` that is not part of a `{{var}}` insertion,
|
|
172
|
+
* i.e. a brace that was quoted in the source ICU message.
|
|
173
|
+
*/
|
|
174
|
+
const hasLiteralBrace = (text) => /[{}]/.test(text.replace(/\{\{[^{}]+\}\}/g, ""));
|
|
143
175
|
const icuNodesToIntlayer = (nodes) => {
|
|
144
176
|
if (nodes.length === 0) return "";
|
|
145
177
|
if (nodes.length === 1 && typeof nodes[0] === "string") {
|
|
146
178
|
const node = nodes[0];
|
|
147
179
|
if (/<[a-zA-Z0-9-]+[^>]*>/.test(node)) return require_transpiler_html_html.html(node);
|
|
180
|
+
if (hasLiteralBrace(node)) return require_transpiler_insertion_insertion.insert(node);
|
|
148
181
|
return node;
|
|
149
182
|
}
|
|
150
183
|
if (nodes.every((node) => typeof node === "string" || node?.type === "argument")) {
|
|
@@ -175,14 +208,10 @@ const icuNodesToIntlayer = (nodes) => {
|
|
|
175
208
|
break;
|
|
176
209
|
}
|
|
177
210
|
if (hasExactMatch) {
|
|
211
|
+
const explicitKeys = Object.keys(node.options).filter((key) => key.startsWith("=")).map((key) => key.substring(1));
|
|
178
212
|
for (const [key, val] of Object.entries(node.options)) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
else if (key === "one") newKey = "1";
|
|
182
|
-
else if (key === "two") newKey = "2";
|
|
183
|
-
else if (key === "few") newKey = "<=3";
|
|
184
|
-
else if (key === "many") newKey = ">=4";
|
|
185
|
-
else if (key === "other") newKey = "fallback";
|
|
213
|
+
const categoryKey = PLURAL_CATEGORY_TO_ENUMERATION_KEY[key];
|
|
214
|
+
const newKey = key.startsWith("=") ? key.substring(1) : categoryKey && !explicitKeys.includes(categoryKey) ? categoryKey : key;
|
|
186
215
|
const replacedVal = val.map((v) => {
|
|
187
216
|
if (typeof v === "string") return v.replace(/#/g, `{{${node.name}}}`);
|
|
188
217
|
return v;
|
|
@@ -199,23 +228,18 @@ const icuNodesToIntlayer = (nodes) => {
|
|
|
199
228
|
});
|
|
200
229
|
options[key] = icuNodesToIntlayer(replacedVal);
|
|
201
230
|
}
|
|
202
|
-
return require_transpiler_plural_plural.plural(options);
|
|
231
|
+
return require_transpiler_plural_plural.plural(options, node.name === "count" ? void 0 : { variable: node.name });
|
|
203
232
|
}
|
|
204
233
|
}
|
|
205
234
|
if (node?.type === "select") {
|
|
206
235
|
const options = {};
|
|
207
236
|
for (const [key, val] of Object.entries(node.options)) options[key === "other" ? "fallback" : key] = icuNodesToIntlayer(val);
|
|
208
237
|
const optionKeys = Object.keys(options);
|
|
209
|
-
if ((
|
|
238
|
+
if (node.name === "gender" && optionKeys.some((key) => key === "male" || key === "female") && optionKeys.every((key) => [
|
|
210
239
|
"male",
|
|
211
240
|
"female",
|
|
212
|
-
"other",
|
|
213
241
|
"fallback"
|
|
214
|
-
].includes(
|
|
215
|
-
fallback: options.fallback,
|
|
216
|
-
male: options.male,
|
|
217
|
-
female: options.female
|
|
218
|
-
});
|
|
242
|
+
].includes(key))) return require_transpiler_gender_gender.gender(options);
|
|
219
243
|
return require_transpiler_select_select.select(options, node.name);
|
|
220
244
|
}
|
|
221
245
|
if (node?.type === "selectordinal") {
|
|
@@ -264,8 +288,11 @@ const intlayerToIcuPlugin = {
|
|
|
264
288
|
},
|
|
265
289
|
transform: (node, props, next) => {
|
|
266
290
|
if (typeof node === "string") return node.replace(/\{\{([^}]+)\}\}/g, "{$1}");
|
|
267
|
-
if (node.nodeType === _intlayer_types_nodeType.INSERTION) return node[_intlayer_types_nodeType.INSERTION]
|
|
268
|
-
if (node.nodeType === _intlayer_types_nodeType.HTML)
|
|
291
|
+
if (node.nodeType === _intlayer_types_nodeType.INSERTION) return intlayerTextToIcu(node[_intlayer_types_nodeType.INSERTION]);
|
|
292
|
+
if (node.nodeType === _intlayer_types_nodeType.HTML) {
|
|
293
|
+
const htmlContent = node[_intlayer_types_nodeType.HTML];
|
|
294
|
+
return typeof htmlContent === "string" ? intlayerTextToIcu(htmlContent) : next(htmlContent, props);
|
|
295
|
+
}
|
|
269
296
|
if (node.nodeType === _intlayer_types_nodeType.PLURAL) {
|
|
270
297
|
const options = node[_intlayer_types_nodeType.PLURAL];
|
|
271
298
|
const transformedOptions = {};
|
|
@@ -273,12 +300,7 @@ const intlayerToIcuPlugin = {
|
|
|
273
300
|
const childVal = next(val, props);
|
|
274
301
|
transformedOptions[key] = typeof childVal === "string" ? childVal : JSON.stringify(childVal);
|
|
275
302
|
}
|
|
276
|
-
|
|
277
|
-
const fallbackVal = transformedOptions.other || Object.values(transformedOptions)[0];
|
|
278
|
-
if (fallbackVal) {
|
|
279
|
-
const match = fallbackVal.match(/\{([a-zA-Z0-9_]+)\}(?!,)/);
|
|
280
|
-
if (match) varName = match[1];
|
|
281
|
-
}
|
|
303
|
+
const varName = node.variable ?? "count";
|
|
282
304
|
const parts = [];
|
|
283
305
|
for (const [key, val] of Object.entries(transformedOptions)) {
|
|
284
306
|
let strVal = val;
|
|
@@ -337,6 +359,8 @@ const intlayerToIcuPlugin = {
|
|
|
337
359
|
else if (/^\d+$/.test(key)) icuKey = `=${key}`;
|
|
338
360
|
else if ([
|
|
339
361
|
"zero",
|
|
362
|
+
"one",
|
|
363
|
+
"two",
|
|
340
364
|
"few",
|
|
341
365
|
"many"
|
|
342
366
|
].includes(key)) icuKey = key;
|
|
@@ -370,6 +394,7 @@ const intlayerToIcuPlugin = {
|
|
|
370
394
|
return 0;
|
|
371
395
|
});
|
|
372
396
|
for (const [key, val] of entries) {
|
|
397
|
+
if (val === void 0) continue;
|
|
373
398
|
let icuKey = key;
|
|
374
399
|
if (key === "fallback") icuKey = "other";
|
|
375
400
|
const childVal = next(val, props);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ICU.cjs","names":["html","insert","enu","plural","gender","select","NodeTypes","deepTransformNode"],"sources":["../../../src/messageFormat/ICU.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, gender, html, insert, plural, select } from '../transpiler';\n\n/**\n * ICU MessageFormat Converter\n *\n * This module converts between ICU MessageFormat and Intlayer's internal format.\n *\n * IMPORTANT: Two different formats are used:\n *\n * 1. ICU MessageFormat (external format):\n * - Simple variables: {name}\n * - Formatted variables: {amount, number, currency}\n * - Plural: {count, plural, =0 {none} other {# items}}\n * - Select: {gender, select, male {He} female {She} other {They}}\n *\n * 2. Intlayer Internal Format:\n * - Simple variables: {{name}} (double braces for clarity and to distinguish from literal text)\n * - Formatted variables: {amount, number, currency} (keeps ICU format)\n * - Plural: enu({ 0: 'none', fallback: '{{count}} items' })\n * - Select/Gender: gender({ male: 'He', female: 'She', fallback: 'They' })\n *\n * Conversion flow:\n * - ICU → Intlayer: {name} → {{name}}\n * - Intlayer → ICU: {{name}} → {name}\n *\n * The double braces in Intlayer format serve to:\n * - Distinguish variables from literal text containing braces\n * - Work with getInsertion() runtime function which expects {{var}} patterns\n * - Provide clear visual distinction in content dictionaries\n */\n\n// Types for our AST\ntype ICUNode =\n | string\n | {\n type: 'argument';\n name: string;\n format?: { type: string; style?: string };\n }\n | { type: 'plural'; name: string; options: Record<string, ICUNode[]> }\n | { type: 'select'; name: string; options: Record<string, ICUNode[]> }\n | {\n type: 'selectordinal';\n name: string;\n options: Record<string, ICUNode[]>;\n };\n\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nconst parseICU = (text: string): ICUNode[] => {\n let index = 0;\n\n const parseNodes = (): ICUNode[] => {\n const nodes: ICUNode[] = [];\n let currentText = '';\n\n while (index < text.length) {\n const char = text[index];\n\n if (char === '{') {\n if (currentText) {\n nodes.push(currentText);\n currentText = '';\n }\n index++; // skip {\n nodes.push(parseArgument());\n } else if (char === '}') {\n // End of current block\n break;\n } else if (char === \"'\") {\n // Escaping\n if (index + 1 < text.length && text[index + 1] === \"'\") {\n currentText += \"'\";\n index += 2;\n } else {\n // Find next quote\n const nextQuote = text.indexOf(\"'\", index + 1);\n if (nextQuote !== -1) {\n // Determine if this is escaping syntax characters\n // For simplicity, we'll treat content between single quotes as literal\n // provided it contains syntax chars.\n // Standard ICU: ' quoted string '\n // If it is just an apostrophe, it should be doubled.\n // But simplified: take content between quotes literally.\n currentText += text.substring(index + 1, nextQuote);\n index = nextQuote + 1;\n } else {\n currentText += \"'\";\n index++;\n }\n }\n } else {\n currentText += char;\n index++;\n }\n }\n\n if (currentText) {\n nodes.push(currentText);\n }\n return nodes;\n };\n\n const parseArgument = (): ICUNode => {\n // We are past '{'\n // Parse name\n let name = '';\n while (index < text.length && /[^,}]/.test(text[index]!)) {\n name += text[index];\n index++;\n }\n name = name.trim();\n\n if (index >= text.length) throw new Error('Unclosed argument');\n\n if (text[index] === '}') {\n index++;\n return { type: 'argument', name };\n }\n\n // Must be comma\n if (text[index] === ',') {\n index++;\n // Parse type\n let type = '';\n while (index < text.length && /[^,}]/.test(text[index]!)) {\n type += text[index];\n index++;\n }\n type = type.trim();\n\n if (index >= text.length) throw new Error('Unclosed argument');\n\n if (text[index] === '}') {\n index++;\n return { type: 'argument', name, format: { type } };\n }\n\n if (text[index] === ',') {\n index++;\n\n // If plural, select or selectordinal, parse options\n if (\n type === 'plural' ||\n type === 'select' ||\n type === 'selectordinal'\n ) {\n // Parse options\n const options: Record<string, ICUNode[]> = {};\n\n while (index < text.length && text[index] !== '}') {\n // skip whitespace\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n\n // parse key\n let key = '';\n while (index < text.length && /[^{\\s]/.test(text[index]!)) {\n key += text[index];\n index++;\n }\n\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n\n if (text[index] !== '{')\n throw new Error('Expected { after option key');\n index++; // skip {\n\n const value = parseNodes();\n\n if (text[index] !== '}')\n throw new Error('Expected } after option value');\n index++; // skip }\n\n options[key] = value;\n\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n }\n\n index++; // skip closing argument }\n\n if (type === 'plural') {\n return { type: 'plural', name, options };\n } else if (type === 'select') {\n return { type: 'select', name, options };\n } else if (type === 'selectordinal') {\n return { type: 'selectordinal', name, options };\n }\n } else {\n // Parse style for number/date/time\n let style = '';\n while (index < text.length && text[index] !== '}') {\n style += text[index];\n index++;\n }\n if (index >= text.length) throw new Error('Unclosed argument');\n\n style = style.trim();\n index++; // skip }\n\n return { type: 'argument', name, format: { type, style } };\n }\n }\n }\n\n throw new Error('Malformed argument');\n };\n\n return parseNodes();\n};\n\nconst icuNodesToIntlayer = (nodes: ICUNode[]): any => {\n if (nodes.length === 0) return '';\n if (nodes.length === 1 && typeof nodes[0] === 'string') {\n const node = nodes[0];\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(node)) {\n return html(node);\n }\n return node;\n }\n\n // Check if we can flatten to a single string (insert)\n const canFlatten = nodes.every(\n (node) => typeof node === 'string' || node?.type === 'argument'\n );\n if (canFlatten) {\n let str = '';\n for (const node of nodes) {\n if (typeof node === 'string') {\n str += node;\n } else if (typeof node !== 'string' && node?.type === 'argument') {\n if (node.format) {\n // Formatted variables keep ICU format: {var, type, style}\n str += `{${node.name}, ${node.format.type}${\n node.format.style ? `, ${node.format.style}` : ''\n }}`;\n } else {\n // Simple variables use Intlayer format: {{var}}\n str += `{{${node.name}}}`;\n }\n }\n }\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(str)) {\n return html(str);\n }\n return insert(str);\n }\n\n // Mix of string and complex types.\n // If we have just one complex type and it covers everything?\n if (nodes.length === 1) {\n const node = nodes[0];\n\n if (typeof node === 'string') {\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(node)) {\n return html(node);\n }\n return node;\n }\n if (node?.type === 'argument') {\n if (node.format) {\n return insert(\n `{${node.name}, ${node.format.type}${\n node.format.style ? `, ${node.format.style}` : ''\n }}`\n );\n }\n return insert(`{{${node.name}}}`);\n }\n if (node?.type === 'plural') {\n const options: Record<string, any> = {};\n let hasExactMatch = false;\n\n for (const key of Object.keys(node.options)) {\n if (key.startsWith('=')) {\n hasExactMatch = true;\n break;\n }\n }\n\n if (hasExactMatch) {\n for (const [key, val] of Object.entries(node.options)) {\n // Map ICU keys to Intlayer keys\n let newKey = key;\n if (key.startsWith('=')) {\n newKey = key.substring(1); // =0 -> 0\n } else if (key === 'one') {\n newKey = '1';\n } else if (key === 'two') {\n newKey = '2';\n } else if (key === 'few') {\n newKey = '<=3';\n } else if (key === 'many') {\n newKey = '>=4';\n } else if (key === 'other') {\n newKey = 'fallback';\n }\n // Handle # in plural value\n // For plural, we need to pass the variable name down or replace #\n // Intlayer uses {{n}} (or whatever var name) for simple variables\n // We should replace # with {{n}} in the string parts of val\n const replacedVal = val.map((v) => {\n if (typeof v === 'string') {\n return v.replace(/#/g, `{{${node.name}}}`);\n }\n return v;\n });\n\n options[newKey] = icuNodesToIntlayer(replacedVal);\n }\n\n // Preserve variable name\n options.__intlayer_icu_var = node.name;\n\n return enu(options);\n } else {\n for (const [key, val] of Object.entries(node.options)) {\n // Handle # in plural value\n const replacedVal = val?.map((v) => {\n if (typeof v === 'string') {\n return v.replace(/#/g, `{{${node.name}}}`);\n }\n return v;\n });\n\n options[key] = icuNodesToIntlayer(replacedVal);\n }\n\n return plural(options as any);\n }\n }\n if (node?.type === 'select') {\n const options: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(node.options)) {\n // ICU names its catch-all case `other`; intlayer names it `fallback`.\n options[key === 'other' ? 'fallback' : key] = icuNodesToIntlayer(val);\n }\n\n // Check if it looks like gender\n const optionKeys = Object.keys(options);\n // It is gender if it has 'male' OR 'female' AND only contains gender keys (male, female, other)\n const isGender =\n (options.male || options.female) &&\n optionKeys.every((k) =>\n ['male', 'female', 'other', 'fallback'].includes(k)\n );\n\n if (isGender) {\n return gender({\n fallback: options.fallback,\n male: options.male,\n female: options.female,\n });\n }\n\n // Any other discriminant (status, plan, platform…) maps to a `select`\n // node, which resolves on arbitrary string values at runtime.\n return select(options, node.name);\n }\n\n if (node?.type === 'selectordinal') {\n // Ordinal plural ({n, selectordinal, one {#st} two {#nd} other {#th}}).\n // Stored as an enumeration with the ordinal marker: exact matches keep\n // numeric keys, CLDR ordinal categories keep their names, and the\n // runtime selects via `Intl.PluralRules(locale, { type: 'ordinal' })`.\n const options: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(node.options)) {\n const newKey = key.startsWith('=')\n ? key.substring(1)\n : key === 'other'\n ? 'fallback'\n : key;\n\n const replacedVal = val.map((value) => {\n if (typeof value === 'string') {\n return value.replace(/#/g, `{{${node.name}}}`);\n }\n return value;\n });\n\n options[newKey] = icuNodesToIntlayer(replacedVal);\n }\n\n options.__intlayer_icu_var = node.name;\n options.__intlayer_icu_ordinal = true;\n\n return enu(options);\n }\n }\n\n // If multiple nodes, return array\n return nodes.map((node) => icuNodesToIntlayer([node]));\n};\n\nconst icuToIntlayerPlugin = {\n canHandle: (node: any) =>\n typeof node === 'string' &&\n (node.includes('{') ||\n node.includes('}') ||\n /<[a-zA-Z0-9-]+[^>]*>/.test(node)),\n transform: (node: any) => {\n try {\n const ast = parseICU(node);\n return icuNodesToIntlayer(ast);\n } catch {\n // If parsing fails, return original string\n return node;\n }\n },\n};\n\nconst intlayerToIcuPlugin = {\n canHandle: (node: any) => {\n if (\n typeof node === 'string' &&\n (node.includes('{') || node.includes('}'))\n ) {\n return true;\n }\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.HTML ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === NodeTypes.SELECT ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.HTML ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.PLURAL ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === NodeTypes.SELECT ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n // If it contains plain objects or nested arrays, it's a structural array\n if (hasPlainObjectOrArray) return false;\n // If it contains ONLY strings, it's a structural array, not a composite string\n if (!hasNode) return false;\n\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any) => {\n // Convert Intlayer's double-brace format {{var}} to ICU's single-brace format {var}\n if (typeof node === 'string') {\n return node.replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.INSERTION) {\n return node[NodeTypes.INSERTION].replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.HTML) {\n return node[NodeTypes.HTML];\n }\n\n if (node.nodeType === NodeTypes.PLURAL) {\n const options = node[NodeTypes.PLURAL];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n let varName = 'count';\n\n const fallbackVal =\n transformedOptions.other || Object.values(transformedOptions)[0];\n\n if (fallbackVal) {\n const match = fallbackVal.match(/\\{([a-zA-Z0-9_]+)\\}(?!,)/);\n if (match) {\n varName = match[1]!;\n }\n }\n\n const parts = [];\n\n for (const [key, val] of Object.entries(transformedOptions)) {\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n parts.push(`${key} {${strVal}}`);\n }\n return `{${varName}, plural, ${parts.join(' ')}}`;\n }\n\n if (node.nodeType === NodeTypes.ENUMERATION) {\n const options = node[NodeTypes.ENUMERATION];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n if (key === '__intlayer_icu_var' || key === '__intlayer_icu_ordinal')\n continue;\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n let varName = options.__intlayer_icu_var || 'n';\n\n if (!options.__intlayer_icu_var) {\n const fallbackVal =\n transformedOptions.fallback ||\n transformedOptions.other ||\n Object.values(transformedOptions)[0];\n const match = fallbackVal?.match(/\\{([a-zA-Z0-9_]+)\\}(?!,)/);\n if (match?.[1]) {\n varName = match[1];\n }\n }\n\n // Ordinal enumerations round-trip back to `selectordinal`\n if (options.__intlayer_icu_ordinal === true) {\n const ordinalParts = [];\n\n for (const [key, val] of Object.entries(transformedOptions)) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n else if (/^\\d+$/.test(key)) icuKey = `=${key}`;\n\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n ordinalParts.push(`${icuKey} {${strVal}}`);\n }\n\n return `{${varName}, selectordinal, ${ordinalParts.join(' ')}}`;\n }\n\n const keys = Object.keys(transformedOptions);\n const pluralKeys = [\n '1',\n '2',\n '<=3',\n '>=4',\n 'fallback',\n 'other',\n 'zero',\n 'one',\n 'two',\n 'few',\n 'many',\n ];\n\n const isPlural = keys.every(\n (k) => pluralKeys.includes(k) || /^[<>=]?\\d+(\\.\\d+)?$/.test(k)\n );\n\n const parts = [];\n\n if (isPlural) {\n for (const [key, val] of Object.entries(transformedOptions)) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n else if (key === '<=3') icuKey = 'few';\n else if (key === '>=4') icuKey = 'many';\n else if (/^\\d+$/.test(key)) icuKey = `=${key}`;\n else if (['zero', 'few', 'many'].includes(key)) icuKey = key;\n else icuKey = 'other';\n\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, plural, ${parts.join(' ')}}`;\n } else {\n const entries = Object.entries(transformedOptions).sort(\n ([keyA], [keyB]) => {\n if (keyA === 'fallback' || keyA === 'other') return 1;\n if (keyB === 'fallback' || keyB === 'other') return -1;\n return 0;\n }\n );\n\n for (const [key, val] of entries) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n parts.push(`${icuKey} {${val}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n }\n\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const varName = 'gender';\n const parts = [];\n\n const entries = Object.entries(options).sort(([keyA], [keyB]) => {\n if (keyA === 'fallback') return 1;\n if (keyB === 'fallback') return -1;\n return 0;\n });\n\n for (const [key, val] of entries) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n\n const childVal = next(val, props);\n const strVal =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n\n if (node.nodeType === NodeTypes.SELECT) {\n const options = node[NodeTypes.SELECT];\n const varName = node.variable || 'value';\n const parts = [];\n\n // ICU requires the `other` case to come last.\n const entries = Object.entries(options).sort(([keyA], [keyB]) => {\n if (keyA === 'fallback') return 1;\n if (keyB === 'fallback') return -1;\n return 0;\n });\n\n for (const [key, val] of entries) {\n const icuKey = key === 'fallback' ? 'other' : key;\n\n const childVal = next(val, props);\n const strVal =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n // handle array/composite strings that passed canHandle\n const arr = Array.isArray(node) ? node : node.composite;\n const items = arr.map((item: any) => next(item, props));\n return items.join('');\n }\n\n return next(node, props);\n },\n};\n\nexport const intlayerToICUFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'icu',\n keyPath: [],\n plugins: [{ id: 'icu', ...intlayerToIcuPlugin }],\n });\n};\n\nexport const icuToIntlayerFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'icu',\n keyPath: [],\n plugins: [{ id: 'icu', ...icuToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;;;;;AA0DA,MAAM,YAAY,SAA4B;CAC5C,IAAI,QAAQ;CAEZ,MAAM,mBAA8B;EAClC,MAAM,QAAmB,CAAC;EAC1B,IAAI,cAAc;EAElB,OAAO,QAAQ,KAAK,QAAQ;GAC1B,MAAM,OAAO,KAAK;GAElB,IAAI,SAAS,KAAK;IAChB,IAAI,aAAa;KACf,MAAM,KAAK,WAAW;KACtB,cAAc;IAChB;IACA;IACA,MAAM,KAAK,cAAc,CAAC;GAC5B,OAAO,IAAI,SAAS,KAElB;QACK,IAAI,SAAS,KAAK;IAEvB,IAAI,Q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SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAO,GAAG;EAAoB,CAAC;CACjD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"ICU.cjs","names":["html","insert","enu","plural","gender","select","NodeTypes","deepTransformNode"],"sources":["../../../src/messageFormat/ICU.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, gender, html, insert, plural, select } from '../transpiler';\nimport type { GenderContentStates } from '../transpiler/gender/gender';\nimport { DEFAULT_PLURAL_VARIABLE } from '../transpiler/plural/plural';\n\n/**\n * ICU MessageFormat Converter\n *\n * This module converts between ICU MessageFormat and Intlayer's internal format.\n *\n * IMPORTANT: Two different formats are used:\n *\n * 1. ICU MessageFormat (external format):\n * - Simple variables: {name}\n * - Formatted variables: {amount, number, currency}\n * - Plural: {count, plural, =0 {none} other {# items}}\n * - Select: {gender, select, male {He} female {She} other {They}}\n *\n * 2. Intlayer Internal Format:\n * - Simple variables: {{name}} (double braces for clarity and to distinguish from literal text)\n * - Formatted variables: {amount, number, currency} (keeps ICU format)\n * - Plural: enu({ 0: 'none', fallback: '{{count}} items' })\n * - Select/Gender: gender({ male: 'He', female: 'She', fallback: 'They' })\n *\n * Conversion flow:\n * - ICU → Intlayer: {name} → {{name}}\n * - Intlayer → ICU: {{name}} → {name}\n *\n * The double braces in Intlayer format serve to:\n * - Distinguish variables from literal text containing braces\n * - Work with getInsertion() runtime function which expects {{var}} patterns\n * - Provide clear visual distinction in content dictionaries\n */\n\n// Types for our AST\ntype ICUNode =\n | string\n | {\n type: 'argument';\n name: string;\n format?: { type: string; style?: string };\n }\n | { type: 'plural'; name: string; options: Record<string, ICUNode[]> }\n | { type: 'select'; name: string; options: Record<string, ICUNode[]> }\n | {\n type: 'selectordinal';\n name: string;\n options: Record<string, ICUNode[]>;\n };\n\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** Characters an ICU apostrophe can quote to make them literal. */\nconst QUOTABLE_SYNTAX_CHARACTERS = ['{', '}'];\n\n/** ICU plural categories (CLDR) and the enumeration key each maps to. */\nconst PLURAL_CATEGORY_TO_ENUMERATION_KEY: Record<string, string> = {\n one: '1',\n two: '2',\n few: '<=3',\n many: '>=4',\n other: 'fallback',\n};\n\n/**\n * Converts Intlayer text to ICU text:\n * - `{{name}}` → `{name}`\n * - formatted arguments `{value, number, percent}` are kept as is\n * - any other `{` / `}` is a literal and gets quoted (`'{'`)\n */\nconst intlayerTextToIcu = (text: string): string => {\n const tokenPattern =\n /\\{\\{\\s*([^{}\\s]+?)\\s*\\}\\}|\\{\\s*[\\w.]+\\s*,\\s*\\w+\\s*(?:,[^{}]*)?\\}|'(?=[{}])|[{}]/g;\n\n return text.replace(tokenPattern, (match, variableName?: string) => {\n if (variableName) return `{${variableName}}`;\n if (match === \"'\") return \"''\"; // keep a literal apostrophe before a quoted brace\n if (match === '{' || match === '}') return `'${match}'`;\n return match;\n });\n};\n\nconst parseICU = (text: string): ICUNode[] => {\n let index = 0;\n\n const parseNodes = (): ICUNode[] => {\n const nodes: ICUNode[] = [];\n let currentText = '';\n\n while (index < text.length) {\n const char = text[index];\n\n if (char === '{') {\n if (currentText) {\n nodes.push(currentText);\n currentText = '';\n }\n index++; // skip {\n nodes.push(parseArgument());\n } else if (char === '}') {\n // End of current block\n break;\n } else if (char === \"'\") {\n // Escaping\n if (index + 1 < text.length && text[index + 1] === \"'\") {\n currentText += \"'\";\n index += 2;\n } else {\n // ICU only opens a quoted literal when the apostrophe precedes a\n // syntax character; any other apostrophe (\"It's\") is plain text.\n const nextQuote = QUOTABLE_SYNTAX_CHARACTERS.includes(\n text[index + 1] ?? ''\n )\n ? text.indexOf(\"'\", index + 1)\n : -1;\n\n if (nextQuote !== -1) {\n // `''` inside a quoted literal is an escaped apostrophe\n currentText += text\n .substring(index + 1, nextQuote)\n .replace(/''/g, \"'\");\n index = nextQuote + 1;\n } else if (\n QUOTABLE_SYNTAX_CHARACTERS.includes(text[index + 1] ?? '')\n ) {\n // Unterminated quote: ICU quotes up to the end of the message\n currentText += text.substring(index + 1);\n index = text.length;\n } else {\n currentText += \"'\";\n index++;\n }\n }\n } else {\n currentText += char;\n index++;\n }\n }\n\n if (currentText) {\n nodes.push(currentText);\n }\n return nodes;\n };\n\n const parseArgument = (): ICUNode => {\n // We are past '{'\n // Parse name\n let name = '';\n while (index < text.length && /[^,}]/.test(text[index]!)) {\n name += text[index];\n index++;\n }\n name = name.trim();\n\n if (index >= text.length) throw new Error('Unclosed argument');\n\n if (text[index] === '}') {\n index++;\n return { type: 'argument', name };\n }\n\n // Must be comma\n if (text[index] === ',') {\n index++;\n // Parse type\n let type = '';\n while (index < text.length && /[^,}]/.test(text[index]!)) {\n type += text[index];\n index++;\n }\n type = type.trim();\n\n if (index >= text.length) throw new Error('Unclosed argument');\n\n if (text[index] === '}') {\n index++;\n return { type: 'argument', name, format: { type } };\n }\n\n if (text[index] === ',') {\n index++;\n\n // If plural, select or selectordinal, parse options\n if (\n type === 'plural' ||\n type === 'select' ||\n type === 'selectordinal'\n ) {\n // Parse options\n const options: Record<string, ICUNode[]> = {};\n\n while (index < text.length && text[index] !== '}') {\n // skip whitespace\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n\n // parse key\n let key = '';\n while (index < text.length && /[^{\\s]/.test(text[index]!)) {\n key += text[index];\n index++;\n }\n\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n\n if (text[index] !== '{')\n throw new Error('Expected { after option key');\n index++; // skip {\n\n const value = parseNodes();\n\n if (text[index] !== '}')\n throw new Error('Expected } after option value');\n index++; // skip }\n\n options[key] = value;\n\n while (index < text.length && /\\s/.test(text[index]!)) index++;\n }\n\n index++; // skip closing argument }\n\n if (type === 'plural') {\n return { type: 'plural', name, options };\n } else if (type === 'select') {\n return { type: 'select', name, options };\n } else if (type === 'selectordinal') {\n return { type: 'selectordinal', name, options };\n }\n } else {\n // Parse style for number/date/time\n let style = '';\n while (index < text.length && text[index] !== '}') {\n style += text[index];\n index++;\n }\n if (index >= text.length) throw new Error('Unclosed argument');\n\n style = style.trim();\n index++; // skip }\n\n return { type: 'argument', name, format: { type, style } };\n }\n }\n }\n\n throw new Error('Malformed argument');\n };\n\n return parseNodes();\n};\n\n/**\n * Whether a text holds a `{` / `}` that is not part of a `{{var}}` insertion,\n * i.e. a brace that was quoted in the source ICU message.\n */\nconst hasLiteralBrace = (text: string): boolean =>\n /[{}]/.test(text.replace(/\\{\\{[^{}]+\\}\\}/g, ''));\n\nconst icuNodesToIntlayer = (nodes: ICUNode[]): any => {\n if (nodes.length === 0) return '';\n if (nodes.length === 1 && typeof nodes[0] === 'string') {\n const node = nodes[0];\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(node)) {\n return html(node);\n }\n // A plain string is emitted back verbatim, so literal braces need an\n // `insert()` node to be re-quoted on the way back to ICU\n if (hasLiteralBrace(node)) {\n return insert(node);\n }\n return node;\n }\n\n // Check if we can flatten to a single string (insert)\n const canFlatten = nodes.every(\n (node) => typeof node === 'string' || node?.type === 'argument'\n );\n if (canFlatten) {\n let str = '';\n for (const node of nodes) {\n if (typeof node === 'string') {\n str += node;\n } else if (typeof node !== 'string' && node?.type === 'argument') {\n if (node.format) {\n // Formatted variables keep ICU format: {var, type, style}\n str += `{${node.name}, ${node.format.type}${\n node.format.style ? `, ${node.format.style}` : ''\n }}`;\n } else {\n // Simple variables use Intlayer format: {{var}}\n str += `{{${node.name}}}`;\n }\n }\n }\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(str)) {\n return html(str);\n }\n return insert(str);\n }\n\n // Mix of string and complex types.\n // If we have just one complex type and it covers everything?\n if (nodes.length === 1) {\n const node = nodes[0];\n\n if (typeof node === 'string') {\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(node)) {\n return html(node);\n }\n return node;\n }\n if (node?.type === 'argument') {\n if (node.format) {\n return insert(\n `{${node.name}, ${node.format.type}${\n node.format.style ? `, ${node.format.style}` : ''\n }}`\n );\n }\n return insert(`{{${node.name}}}`);\n }\n if (node?.type === 'plural') {\n const options: Record<string, any> = {};\n let hasExactMatch = false;\n\n for (const key of Object.keys(node.options)) {\n if (key.startsWith('=')) {\n hasExactMatch = true;\n break;\n }\n }\n\n if (hasExactMatch) {\n const explicitKeys = Object.keys(node.options)\n .filter((key) => key.startsWith('='))\n .map((key) => key.substring(1));\n\n for (const [key, val] of Object.entries(node.options)) {\n // Map ICU keys to Intlayer keys (=0 -> 0, one -> 1, other -> fallback).\n // A category whose key is already taken by an explicit `=N` keeps\n // its CLDR name: ICU checks `=N` first, so both must survive.\n const categoryKey = PLURAL_CATEGORY_TO_ENUMERATION_KEY[key];\n const newKey = key.startsWith('=')\n ? key.substring(1)\n : categoryKey && !explicitKeys.includes(categoryKey)\n ? categoryKey\n : key;\n // Handle # in plural value\n // For plural, we need to pass the variable name down or replace #\n // Intlayer uses {{n}} (or whatever var name) for simple variables\n // We should replace # with {{n}} in the string parts of val\n const replacedVal = val.map((v) => {\n if (typeof v === 'string') {\n return v.replace(/#/g, `{{${node.name}}}`);\n }\n return v;\n });\n\n options[newKey] = icuNodesToIntlayer(replacedVal);\n }\n\n // Preserve variable name\n options.__intlayer_icu_var = node.name;\n\n return enu(options);\n } else {\n for (const [key, val] of Object.entries(node.options)) {\n // Handle # in plural value\n const replacedVal = val?.map((v) => {\n if (typeof v === 'string') {\n return v.replace(/#/g, `{{${node.name}}}`);\n }\n return v;\n });\n\n options[key] = icuNodesToIntlayer(replacedVal);\n }\n\n // Keep the selector name: it cannot be inferred back from the\n // branches when they don't use `#`\n return plural(\n options as any,\n node.name === DEFAULT_PLURAL_VARIABLE\n ? undefined\n : { variable: node.name }\n );\n }\n }\n if (node?.type === 'select') {\n const options: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(node.options)) {\n // ICU names its catch-all case `other`; intlayer names it `fallback`.\n options[key === 'other' ? 'fallback' : key] = icuNodesToIntlayer(val);\n }\n\n // A `gender` node always selects on `gender`, so only a select on that\n // variable, with gender keys only, can become one without loss.\n const optionKeys = Object.keys(options);\n const isGender =\n node.name === 'gender' &&\n optionKeys.some((key) => key === 'male' || key === 'female') &&\n optionKeys.every((key) => ['male', 'female', 'fallback'].includes(key));\n\n if (isGender) {\n return gender(options as GenderContentStates<unknown>);\n }\n\n // Any other discriminant (status, plan, platform…) maps to a `select`\n // node, which resolves on arbitrary string values at runtime.\n return select(options, node.name);\n }\n\n if (node?.type === 'selectordinal') {\n // Ordinal plural ({n, selectordinal, one {#st} two {#nd} other {#th}}).\n // Stored as an enumeration with the ordinal marker: exact matches keep\n // numeric keys, CLDR ordinal categories keep their names, and the\n // runtime selects via `Intl.PluralRules(locale, { type: 'ordinal' })`.\n const options: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(node.options)) {\n const newKey = key.startsWith('=')\n ? key.substring(1)\n : key === 'other'\n ? 'fallback'\n : key;\n\n const replacedVal = val.map((value) => {\n if (typeof value === 'string') {\n return value.replace(/#/g, `{{${node.name}}}`);\n }\n return value;\n });\n\n options[newKey] = icuNodesToIntlayer(replacedVal);\n }\n\n options.__intlayer_icu_var = node.name;\n options.__intlayer_icu_ordinal = true;\n\n return enu(options);\n }\n }\n\n // If multiple nodes, return array\n return nodes.map((node) => icuNodesToIntlayer([node]));\n};\n\nconst icuToIntlayerPlugin = {\n canHandle: (node: any) =>\n typeof node === 'string' &&\n (node.includes('{') ||\n node.includes('}') ||\n /<[a-zA-Z0-9-]+[^>]*>/.test(node)),\n transform: (node: any) => {\n try {\n const ast = parseICU(node);\n return icuNodesToIntlayer(ast);\n } catch {\n // If parsing fails, return original string\n return node;\n }\n },\n};\n\nconst intlayerToIcuPlugin = {\n canHandle: (node: any) => {\n if (\n typeof node === 'string' &&\n (node.includes('{') || node.includes('}'))\n ) {\n return true;\n }\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.HTML ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === NodeTypes.SELECT ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.HTML ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.PLURAL ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === NodeTypes.SELECT ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n // If it contains plain objects or nested arrays, it's a structural array\n if (hasPlainObjectOrArray) return false;\n // If it contains ONLY strings, it's a structural array, not a composite string\n if (!hasNode) return false;\n\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any) => {\n // Convert Intlayer's double-brace format {{var}} to ICU's single-brace format {var}\n // Plain strings may already be ICU messages: only unwrap `{{var}}`.\n // Literal braces are carried by `insert()` nodes, escaped below.\n if (typeof node === 'string') {\n return node.replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.INSERTION) {\n return intlayerTextToIcu(node[NodeTypes.INSERTION]);\n }\n\n if (node.nodeType === NodeTypes.HTML) {\n const htmlContent = node[NodeTypes.HTML];\n return typeof htmlContent === 'string'\n ? intlayerTextToIcu(htmlContent)\n : next(htmlContent, props);\n }\n\n if (node.nodeType === NodeTypes.PLURAL) {\n const options = node[NodeTypes.PLURAL];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n // The plural selects on its declared variable, `count` by default.\n const varName: string = node.variable ?? DEFAULT_PLURAL_VARIABLE;\n\n const parts = [];\n\n for (const [key, val] of Object.entries(transformedOptions)) {\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n parts.push(`${key} {${strVal}}`);\n }\n return `{${varName}, plural, ${parts.join(' ')}}`;\n }\n\n if (node.nodeType === NodeTypes.ENUMERATION) {\n const options = node[NodeTypes.ENUMERATION];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n if (key === '__intlayer_icu_var' || key === '__intlayer_icu_ordinal')\n continue;\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n let varName = options.__intlayer_icu_var || 'n';\n\n if (!options.__intlayer_icu_var) {\n const fallbackVal =\n transformedOptions.fallback ||\n transformedOptions.other ||\n Object.values(transformedOptions)[0];\n const match = fallbackVal?.match(/\\{([a-zA-Z0-9_]+)\\}(?!,)/);\n if (match?.[1]) {\n varName = match[1];\n }\n }\n\n // Ordinal enumerations round-trip back to `selectordinal`\n if (options.__intlayer_icu_ordinal === true) {\n const ordinalParts = [];\n\n for (const [key, val] of Object.entries(transformedOptions)) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n else if (/^\\d+$/.test(key)) icuKey = `=${key}`;\n\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n ordinalParts.push(`${icuKey} {${strVal}}`);\n }\n\n return `{${varName}, selectordinal, ${ordinalParts.join(' ')}}`;\n }\n\n const keys = Object.keys(transformedOptions);\n const pluralKeys = [\n '1',\n '2',\n '<=3',\n '>=4',\n 'fallback',\n 'other',\n 'zero',\n 'one',\n 'two',\n 'few',\n 'many',\n ];\n\n const isPlural = keys.every(\n (k) => pluralKeys.includes(k) || /^[<>=]?\\d+(\\.\\d+)?$/.test(k)\n );\n\n const parts = [];\n\n if (isPlural) {\n for (const [key, val] of Object.entries(transformedOptions)) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n else if (key === '<=3') icuKey = 'few';\n else if (key === '>=4') icuKey = 'many';\n else if (/^\\d+$/.test(key)) icuKey = `=${key}`;\n else if (['zero', 'one', 'two', 'few', 'many'].includes(key))\n icuKey = key;\n else icuKey = 'other';\n\n let strVal = val;\n strVal = strVal.replace(new RegExp(`\\\\{${varName}\\\\}`, 'g'), '#');\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, plural, ${parts.join(' ')}}`;\n } else {\n const entries = Object.entries(transformedOptions).sort(\n ([keyA], [keyB]) => {\n if (keyA === 'fallback' || keyA === 'other') return 1;\n if (keyB === 'fallback' || keyB === 'other') return -1;\n return 0;\n }\n );\n\n for (const [key, val] of entries) {\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n parts.push(`${icuKey} {${val}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n }\n\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const varName = 'gender';\n const parts = [];\n\n const entries = Object.entries(options).sort(([keyA], [keyB]) => {\n if (keyA === 'fallback') return 1;\n if (keyB === 'fallback') return -1;\n return 0;\n });\n\n for (const [key, val] of entries) {\n // Branches absent from the source message are not emitted\n if (val === undefined) continue;\n\n let icuKey = key;\n if (key === 'fallback') icuKey = 'other';\n\n const childVal = next(val, props);\n const strVal =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n\n if (node.nodeType === NodeTypes.SELECT) {\n const options = node[NodeTypes.SELECT];\n const varName = node.variable || 'value';\n const parts = [];\n\n // ICU requires the `other` case to come last.\n const entries = Object.entries(options).sort(([keyA], [keyB]) => {\n if (keyA === 'fallback') return 1;\n if (keyB === 'fallback') return -1;\n return 0;\n });\n\n for (const [key, val] of entries) {\n const icuKey = key === 'fallback' ? 'other' : key;\n\n const childVal = next(val, props);\n const strVal =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n\n parts.push(`${icuKey} {${strVal}}`);\n }\n return `{${varName}, select, ${parts.join(' ')}}`;\n }\n\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n // handle array/composite strings that passed canHandle\n const arr = Array.isArray(node) ? node : node.composite;\n const items = arr.map((item: any) => next(item, props));\n return items.join('');\n }\n\n return next(node, props);\n },\n};\n\nexport const intlayerToICUFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'icu',\n keyPath: [],\n plugins: [{ id: 'icu', ...intlayerToIcuPlugin }],\n });\n};\n\nexport const icuToIntlayerFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'icu',\n keyPath: [],\n plugins: [{ id: 'icu', ...icuToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;;;;;;AA6DA,MAAM,6BAA6B,CAAC,KAAK,GAAG;;AAG5C,MAAM,qCAA6D;CACjE,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;CACN,OAAO;AACT;;;;;;;AAQA,MAAM,qBAAqB,SAAyB;CAIlD,OAAO,KAAK,QAAQ,qFAAe,OAAO,iBAA0B;EAClE,IAAI,cAAc,OAAO,IAAI,aAAa;EAC1C,IAAI,UAAU,KAAK,OAAO;EAC1B,IAAI,UAAU,OAAO,UAAU,KAAK,OAAO,IAAI,MAAM;EACrD,OAAO;CACT,CAAC;AACH;AAEA,MAAM,YAAY,SAA4B;CAC5C,IAAI,QAAQ;CAEZ,MAAM,mBAA8B;EAClC,MAAM,QAAmB,CAAC;EAC1B,IAAI,cAAc;EAElB,OAAO,QAAQ,KAAK,QAAQ;GAC1B,MAAM,OAAO,KAAK;GAElB,IAAI,SAAS,KAAK;IAChB,IAAI,aAAa;KACf,MAAM,KAAK,WAAW;KACtB,cAAc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