@intlayer/core 9.8.5 → 9.9.1
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/deepTransformPlugins/getLocalizedContent.cjs +3 -1
- package/dist/cjs/deepTransformPlugins/getLocalizedContent.cjs.map +1 -1
- package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs +2 -1
- package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs +262 -0
- package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs.map +1 -0
- package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs +25 -0
- package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs.map +1 -0
- package/dist/cjs/dictionaryManipulator/index.cjs +27 -3
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +3 -0
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +6 -2
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs +2 -1
- package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +80 -12
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs +9 -3
- package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +38 -68
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
- package/dist/cjs/index.cjs +27 -3
- package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
- package/dist/cjs/interpreter/getDictionary.cjs +3 -0
- package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
- package/dist/cjs/interpreter/getDictionaryAsync.cjs +5 -19
- package/dist/cjs/interpreter/getDictionaryAsync.cjs.map +1 -1
- package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs +3 -1
- package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs.map +1 -1
- package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs +2 -1
- package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs +252 -0
- package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs.map +1 -0
- package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs +22 -0
- package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs.map +1 -0
- package/dist/esm/dictionaryManipulator/index.mjs +6 -4
- package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs +3 -0
- package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs +6 -2
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs +2 -1
- package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs +75 -13
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs +10 -5
- package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +33 -68
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
- package/dist/esm/index.mjs +6 -4
- package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
- package/dist/esm/interpreter/getDictionary.mjs +3 -0
- package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
- package/dist/esm/interpreter/getDictionaryAsync.mjs +5 -19
- package/dist/esm/interpreter/getDictionaryAsync.mjs.map +1 -1
- package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +2 -1
- package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +2 -1
- package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +2 -1
- package/dist/types/deepTransformPlugins/getLocalizedContent.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts +159 -0
- package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts.map +1 -0
- package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts +14 -0
- package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts.map +1 -0
- package/dist/types/dictionaryManipulator/index.d.ts +6 -4
- package/dist/types/dictionaryManipulator/normalizeDictionary.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts +51 -5
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts +7 -2
- package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +34 -54
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
- package/dist/types/index.d.ts +6 -4
- package/dist/types/interpreter/getContent/plugins.d.ts +2 -1
- package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
- package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
- package/dist/types/interpreter/getDictionaryAsync.d.ts.map +1 -1
- package/package.json +6 -6
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_dictionaryManipulator_getLocalizedMetadata = require("../dictionaryManipulator/getLocalizedMetadata.cjs");
|
|
2
3
|
const require_interpreter_getContent_plugins = require("../interpreter/getContent/plugins.cjs");
|
|
3
4
|
const require_interpreter_getContent_deepTransform = require("../interpreter/getContent/deepTransform.cjs");
|
|
4
5
|
|
|
@@ -25,7 +26,8 @@ const getPerLocaleDictionary = (dictionary, locale, fallback) => ({
|
|
|
25
26
|
dictionaryKey: dictionary.key,
|
|
26
27
|
keyPath: [],
|
|
27
28
|
plugins: []
|
|
28
|
-
}, fallback)
|
|
29
|
+
}, fallback),
|
|
30
|
+
...dictionary.metadata !== void 0 && { metadata: require_dictionaryManipulator_getLocalizedMetadata.getLocalizedMetadata(dictionary.metadata, locale, fallback) }
|
|
29
31
|
});
|
|
30
32
|
|
|
31
33
|
exports.getLocalizedContent = getLocalizedContent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocalizedContent.cjs","names":["translationPlugin","deepTransformNode"],"sources":["../../../src/deepTransformPlugins/getLocalizedContent.ts"],"sourcesContent":["import type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n type DeepTransformContent,\n type NodeProps,\n type Plugins,\n translationPlugin,\n} from '../interpreter';\nimport { deepTransformNode } from '../interpreter/getContent/deepTransform';\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n * In comparison to `getContent`, this function will only apply the translation plugin.\n * It will not transform enumerations, insertions, or other content types.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getLocalizedContent = <\n T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n locale: L,\n nodeProps: NodeProps,\n fallback?: LocalesValues // fallback mean that if field is not translated, it will use the default locale\n) => {\n const plugins: Plugins[] = [\n translationPlugin(locale, fallback),\n ...(nodeProps.plugins ?? []),\n ];\n\n return deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T>;\n};\n\nexport const getPerLocaleDictionary = <\n T extends Dictionary,\n L extends LocalesValues,\n>(\n dictionary: T,\n locale: L,\n fallback?: LocalesValues\n): Dictionary => ({\n ...dictionary,\n locale,\n content: getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [],\n },\n fallback\n ),\n});\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getLocalizedContent.cjs","names":["translationPlugin","deepTransformNode","getLocalizedMetadata"],"sources":["../../../src/deepTransformPlugins/getLocalizedContent.ts"],"sourcesContent":["import type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getLocalizedMetadata } from '../dictionaryManipulator/getLocalizedMetadata';\nimport {\n type DeepTransformContent,\n type NodeProps,\n type Plugins,\n translationPlugin,\n} from '../interpreter';\nimport { deepTransformNode } from '../interpreter/getContent/deepTransform';\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n * In comparison to `getContent`, this function will only apply the translation plugin.\n * It will not transform enumerations, insertions, or other content types.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getLocalizedContent = <\n T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n locale: L,\n nodeProps: NodeProps,\n fallback?: LocalesValues // fallback mean that if field is not translated, it will use the default locale\n) => {\n const plugins: Plugins[] = [\n translationPlugin(locale, fallback),\n ...(nodeProps.plugins ?? []),\n ];\n\n return deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T>;\n};\n\nexport const getPerLocaleDictionary = <\n T extends Dictionary,\n L extends LocalesValues,\n>(\n dictionary: T,\n locale: L,\n fallback?: LocalesValues\n): Dictionary => ({\n ...dictionary,\n locale,\n content: getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [],\n },\n fallback\n ),\n ...(dictionary.metadata !== undefined && {\n metadata: getLocalizedMetadata(dictionary.metadata, locale, fallback),\n }),\n});\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,uBAIX,MACA,QACA,WACA,aACG;CACH,MAAM,UAAqB,CACzBA,yDAAkB,QAAQ,QAAQ,GAClC,GAAI,UAAU,WAAW,CAAC,CAC5B;CAEA,OAAOC,+DAAkB,MAAM;EAC7B,GAAG;EACH;CACF,CAAC;AACH;AAEA,MAAa,0BAIX,YACA,QACA,cACgB;CAChB,GAAG;CACH;CACA,SAAS,oBACP,WAAW,SACX,QACA;EACE,eAAe,WAAW;EAC1B,SAAS,CAAC;EACV,SAAS,CAAC;CACZ,GACA,QACF;CACA,GAAI,WAAW,aAAa,UAAa,EACvC,UAAUC,wEAAqB,WAAW,UAAU,QAAQ,QAAQ,EACtE;AACF"}
|
|
@@ -79,7 +79,8 @@ const getMultilingualDictionary = (dictionary) => {
|
|
|
79
79
|
const { locale: _omitLocale, ...rest } = dictionary;
|
|
80
80
|
return {
|
|
81
81
|
...rest,
|
|
82
|
-
content: transformedContent
|
|
82
|
+
content: transformedContent,
|
|
83
|
+
...dictionary.metadata !== void 0 && { metadata: require_transpiler_translation_translation.t({ [locale]: dictionary.metadata }) }
|
|
83
84
|
};
|
|
84
85
|
};
|
|
85
86
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getMultilingualDictionary.cjs","names":["deepTransformNode","t"],"sources":["../../../src/deepTransformPlugins/getMultilingualDictionary.ts"],"sourcesContent":["import type { Dictionary, TypedNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport {\n deepTransformNode,\n type NodeProps,\n type Plugins,\n} from '../interpreter';\nimport { t } from '../transpiler';\n\n/**\n * Transform a per-locale dictionary into a multilingual dictionary.\n *\n * Example:\n * ```json\n * {\n * \"key\": \"about-page\",\n * \"locale\": \"en\",\n * \"content\": {\n * \"myContent\": \"English content\"\n * }\n * }\n * ```\n *\n * ```json\n * {\n * \"key\": \"about-page\",\n * \"content\": {\n * \"myContent\": t({\n * \"en\": \"English content\",\n * })\n * }\n * }\n * ```\n */\nexport const getMultilingualDictionary = (\n dictionary: Dictionary\n): Dictionary => {\n if (!dictionary.locale) {\n return dictionary;\n }\n\n const locale = dictionary.locale;\n\n const wrapPrimitiveInTranslationPlugin: Plugins = {\n id: 'wrap-primitive-in-translation',\n canHandle: (node) =>\n typeof node === 'string' ||\n typeof node === 'number' ||\n typeof node === 'boolean',\n transform: (node) => t({ [locale]: node } as Record<string, unknown>),\n };\n\n const traverseTypedNodePlugin: Plugins = {\n id: 'traverse-typed-node-plugin',\n canHandle: (node) =>\n typeof node === 'object' && typeof (node as any)?.nodeType === 'string',\n transform: (node: TypedNode, props, transformFn) => {\n const nodeType = (node as any).nodeType as NodeType;\n const inner = structuredClone(\n (node as any)[nodeType as unknown as keyof TypedNode] as any\n );\n\n if (typeof inner !== 'object' || inner === null) {\n const transformed = transformFn(inner, {\n ...props,\n children: inner,\n keyPath: [\n ...props.keyPath,\n { type: nodeType, key: nodeType } as KeyPath,\n ],\n });\n return {\n ...node,\n [nodeType as unknown as keyof TypedNode]: transformed,\n };\n }\n\n for (const key in inner) {\n const childProps: NodeProps = {\n ...props,\n children: inner[key as unknown as keyof typeof inner],\n keyPath: [...props.keyPath, { type: nodeType, key } as KeyPath],\n };\n inner[key as unknown as keyof typeof inner] = transformFn(\n inner[key as unknown as keyof typeof inner],\n childProps\n );\n }\n\n return { ...node, [nodeType as unknown as keyof TypedNode]: inner };\n },\n };\n\n const transformedContent = deepTransformNode(\n JSON.parse(JSON.stringify(dictionary.content)),\n {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [traverseTypedNodePlugin, wrapPrimitiveInTranslationPlugin],\n }\n );\n\n const { locale: _omitLocale, ...rest } = dictionary as any;\n return {\n ...rest,\n content: transformedContent,\n } as Dictionary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,6BACX,eACe;CACf,IAAI,CAAC,WAAW,QACd,OAAO;CAGT,MAAM,SAAS,WAAW;CAoD1B,MAAM,qBAAqBA,+DACzB,KAAK,MAAM,KAAK,UAAU,WAAW,OAAO,CAAC,GAC7C;EACE,eAAe,WAAW;EAC1B,SAAS,CAAC;EACV,SAAS,CAAC;GA7CZ,IAAI;GACJ,YAAY,SACV,OAAO,SAAS,YAAY,OAAQ,MAAc,aAAa;GACjE,YAAY,MAAiB,OAAO,gBAAgB;IAClD,MAAM,WAAY,KAAa;IAC/B,MAAM,QAAQ,gBACX,KAAa,SAChB;IAEA,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;KAC/C,MAAM,cAAc,YAAY,OAAO;MACrC,GAAG;MACH,UAAU;MACV,SAAS,CACP,GAAG,MAAM,SACT;OAAE,MAAM;OAAU,KAAK;MAAS,CAClC;KACF,CAAC;KACD,OAAO;MACL,GAAG;OACF,WAAyC;KAC5C;IACF;IAEA,KAAK,MAAM,OAAO,OAAO;KACvB,MAAM,aAAwB;MAC5B,GAAG;MACH,UAAU,MAAM;MAChB,SAAS,CAAC,GAAG,MAAM,SAAS;OAAE,MAAM;OAAU;MAAI,CAAY;KAChE;KACA,MAAM,OAAwC,YAC5C,MAAM,MACN,UACF;IACF;IAEA,OAAO;KAAE,GAAG;MAAO,WAAyC;IAAM;GACpE;EAQkC,GAAG;GAtDrC,IAAI;GACJ,YAAY,SACV,OAAO,SAAS,YAChB,OAAO,SAAS,YAChB,OAAO,SAAS;GAClB,YAAY,SAASC,6CAAE,GAAG,SAAS,KAAK,CAA4B;EAiDA,CAAC;CACrE,CACF;CAEA,MAAM,EAAE,QAAQ,aAAa,GAAG,SAAS;CACzC,OAAO;EACL,GAAG;EACH,SAAS;
|
|
1
|
+
{"version":3,"file":"getMultilingualDictionary.cjs","names":["deepTransformNode","t"],"sources":["../../../src/deepTransformPlugins/getMultilingualDictionary.ts"],"sourcesContent":["import type { Dictionary, TypedNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport {\n deepTransformNode,\n type NodeProps,\n type Plugins,\n} from '../interpreter';\nimport { t } from '../transpiler';\n\n/**\n * Transform a per-locale dictionary into a multilingual dictionary.\n *\n * Example:\n * ```json\n * {\n * \"key\": \"about-page\",\n * \"locale\": \"en\",\n * \"content\": {\n * \"myContent\": \"English content\"\n * }\n * }\n * ```\n *\n * ```json\n * {\n * \"key\": \"about-page\",\n * \"content\": {\n * \"myContent\": t({\n * \"en\": \"English content\",\n * })\n * }\n * }\n * ```\n */\nexport const getMultilingualDictionary = (\n dictionary: Dictionary\n): Dictionary => {\n if (!dictionary.locale) {\n return dictionary;\n }\n\n const locale = dictionary.locale;\n\n const wrapPrimitiveInTranslationPlugin: Plugins = {\n id: 'wrap-primitive-in-translation',\n canHandle: (node) =>\n typeof node === 'string' ||\n typeof node === 'number' ||\n typeof node === 'boolean',\n transform: (node) => t({ [locale]: node } as Record<string, unknown>),\n };\n\n const traverseTypedNodePlugin: Plugins = {\n id: 'traverse-typed-node-plugin',\n canHandle: (node) =>\n typeof node === 'object' && typeof (node as any)?.nodeType === 'string',\n transform: (node: TypedNode, props, transformFn) => {\n const nodeType = (node as any).nodeType as NodeType;\n const inner = structuredClone(\n (node as any)[nodeType as unknown as keyof TypedNode] as any\n );\n\n if (typeof inner !== 'object' || inner === null) {\n const transformed = transformFn(inner, {\n ...props,\n children: inner,\n keyPath: [\n ...props.keyPath,\n { type: nodeType, key: nodeType } as KeyPath,\n ],\n });\n return {\n ...node,\n [nodeType as unknown as keyof TypedNode]: transformed,\n };\n }\n\n for (const key in inner) {\n const childProps: NodeProps = {\n ...props,\n children: inner[key as unknown as keyof typeof inner],\n keyPath: [...props.keyPath, { type: nodeType, key } as KeyPath],\n };\n inner[key as unknown as keyof typeof inner] = transformFn(\n inner[key as unknown as keyof typeof inner],\n childProps\n );\n }\n\n return { ...node, [nodeType as unknown as keyof TypedNode]: inner };\n },\n };\n\n const transformedContent = deepTransformNode(\n JSON.parse(JSON.stringify(dictionary.content)),\n {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [traverseTypedNodePlugin, wrapPrimitiveInTranslationPlugin],\n }\n );\n\n const { locale: _omitLocale, ...rest } = dictionary as any;\n return {\n ...rest,\n content: transformedContent,\n ...(dictionary.metadata !== undefined && {\n metadata: t({ [locale]: dictionary.metadata } as Record<string, unknown>),\n }),\n } as Dictionary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,6BACX,eACe;CACf,IAAI,CAAC,WAAW,QACd,OAAO;CAGT,MAAM,SAAS,WAAW;CAoD1B,MAAM,qBAAqBA,+DACzB,KAAK,MAAM,KAAK,UAAU,WAAW,OAAO,CAAC,GAC7C;EACE,eAAe,WAAW;EAC1B,SAAS,CAAC;EACV,SAAS,CAAC;GA7CZ,IAAI;GACJ,YAAY,SACV,OAAO,SAAS,YAAY,OAAQ,MAAc,aAAa;GACjE,YAAY,MAAiB,OAAO,gBAAgB;IAClD,MAAM,WAAY,KAAa;IAC/B,MAAM,QAAQ,gBACX,KAAa,SAChB;IAEA,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;KAC/C,MAAM,cAAc,YAAY,OAAO;MACrC,GAAG;MACH,UAAU;MACV,SAAS,CACP,GAAG,MAAM,SACT;OAAE,MAAM;OAAU,KAAK;MAAS,CAClC;KACF,CAAC;KACD,OAAO;MACL,GAAG;OACF,WAAyC;KAC5C;IACF;IAEA,KAAK,MAAM,OAAO,OAAO;KACvB,MAAM,aAAwB;MAC5B,GAAG;MACH,UAAU,MAAM;MAChB,SAAS,CAAC,GAAG,MAAM,SAAS;OAAE,MAAM;OAAU;MAAI,CAAY;KAChE;KACA,MAAM,OAAwC,YAC5C,MAAM,MACN,UACF;IACF;IAEA,OAAO;KAAE,GAAG;MAAO,WAAyC;IAAM;GACpE;EAQkC,GAAG;GAtDrC,IAAI;GACJ,YAAY,SACV,OAAO,SAAS,YAChB,OAAO,SAAS,YAChB,OAAO,SAAS;GAClB,YAAY,SAASC,6CAAE,GAAG,SAAS,KAAK,CAA4B;EAiDA,CAAC;CACrE,CACF;CAEA,MAAM,EAAE,QAAQ,aAAa,GAAG,SAAS;CACzC,OAAO;EACL,GAAG;EACH,SAAS;EACT,GAAI,WAAW,aAAa,UAAa,EACvC,UAAUA,6CAAE,GAAG,SAAS,WAAW,SAAS,CAA4B,EAC1E;CACF;AACF"}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_interpreter_resolveInterpreterLocale = require("../interpreter/resolveInterpreterLocale.cjs");
|
|
3
|
+
const require_dictionaryManipulator_plainDynamicLoader = require("./plainDynamicLoader.cjs");
|
|
4
|
+
const require_dictionaryManipulator_preloadedDynamicLoader = require("./preloadedDynamicLoader.cjs");
|
|
5
|
+
const require_dictionaryManipulator_qualifiedDictionary = require("./qualifiedDictionary.cjs");
|
|
6
|
+
const require_dictionaryManipulator_qualifiedDynamicLoader = require("./qualifiedDynamicLoader.cjs");
|
|
7
|
+
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
8
|
+
|
|
9
|
+
// src/dictionaryManipulator/dynamicDictionary.ts
|
|
10
|
+
/**
|
|
11
|
+
* Resolves the locale and selector of a dynamic dictionary read: the call-site
|
|
12
|
+
* argument wins, then the provider context (locale and ambient variant), then
|
|
13
|
+
* the interpreter locale. Every binding's dynamic hook goes through it, so
|
|
14
|
+
* static and dynamic reads resolve identically.
|
|
15
|
+
*
|
|
16
|
+
* Subscription-based bindings call it again on each locale change with the new
|
|
17
|
+
* `contextLocale`, so a locale pinned at the call site stays pinned and an
|
|
18
|
+
* unpinned one follows the switch.
|
|
19
|
+
*/
|
|
20
|
+
const resolveDictionaryRead = (params) => {
|
|
21
|
+
const localeOrSelector = params.localeOrSelector ?? void 0;
|
|
22
|
+
const { locale, selector } = process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? require_dictionaryManipulator_qualifiedDictionary.parseDictionarySelector(require_dictionaryManipulator_qualifiedDictionary.resolveDictionaryArgument({
|
|
23
|
+
...params,
|
|
24
|
+
localeOrSelector
|
|
25
|
+
})) : {
|
|
26
|
+
locale: localeOrSelector ?? params.contextLocale,
|
|
27
|
+
selector: void 0
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
locale: require_interpreter_resolveInterpreterLocale.resolveInterpreterLocale(locale),
|
|
31
|
+
selector
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The argument a loaded chunk is transformed with: its locale, plus
|
|
36
|
+
* `metadataOnly` when the read requests metadata. The other selector dimensions
|
|
37
|
+
* were already applied by picking the chunk.
|
|
38
|
+
*
|
|
39
|
+
* @param locale - The read's locale; `undefined` lets the binding's
|
|
40
|
+
* `useDictionary` follow its context locale.
|
|
41
|
+
* @param selector - The read's selector, if any.
|
|
42
|
+
*/
|
|
43
|
+
const getDynamicChunkArgument = (locale, selector) => process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && selector?.metadataOnly ? {
|
|
44
|
+
locale,
|
|
45
|
+
metadataOnly: true
|
|
46
|
+
} : locale;
|
|
47
|
+
/**
|
|
48
|
+
* Collects the chunks a read targets. A plain map serves the locale through
|
|
49
|
+
* the same fallback chain as static mode, from its preload when it holds one.
|
|
50
|
+
*/
|
|
51
|
+
const collectDynamicChunks = (loaderMap, key, locale, selector) => {
|
|
52
|
+
if (process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && require_dictionaryManipulator_qualifiedDynamicLoader.isQualifiedDynamicLoaderMap(loaderMap)) return require_dictionaryManipulator_qualifiedDynamicLoader.collectQualifiedChunks(loaderMap, key, locale, selector);
|
|
53
|
+
const resolvedLoader = require_dictionaryManipulator_plainDynamicLoader.findPlainDynamicLoader(loaderMap, locale);
|
|
54
|
+
if (!resolvedLoader) return {
|
|
55
|
+
itemAxisOpen: false,
|
|
56
|
+
missed: true,
|
|
57
|
+
chunks: []
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
itemAxisOpen: false,
|
|
61
|
+
missed: false,
|
|
62
|
+
chunks: [{
|
|
63
|
+
cacheKey: `${key}.${resolvedLoader.locale}`,
|
|
64
|
+
loader: resolvedLoader.loader,
|
|
65
|
+
preloaded: require_dictionaryManipulator_preloadedDynamicLoader.getPreloadedDictionary(loaderMap, resolvedLoader.locale)
|
|
66
|
+
}]
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
/** Turns the loaded chunks of a read into its content. */
|
|
70
|
+
const readLoadedChunks = (params, collected, dictionaries) => {
|
|
71
|
+
const { loaderMap, locale, selector, transform } = params;
|
|
72
|
+
if (process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && collected.readsMetadataIndex) return require_dictionaryManipulator_qualifiedDynamicLoader.readMetadataIndex(dictionaries[0], loaderMap[_intlayer_config_defaultValues.QUALIFIER_DYNAMIC_TYPES_KEY], selector);
|
|
73
|
+
const argument = getDynamicChunkArgument(locale, selector);
|
|
74
|
+
const read = (dictionary) => transform(dictionary, argument);
|
|
75
|
+
if (collected.itemAxisOpen) return dictionaries.map(read);
|
|
76
|
+
const [dictionary] = dictionaries;
|
|
77
|
+
return dictionary ? read(dictionary) : null;
|
|
78
|
+
};
|
|
79
|
+
/** Content of a read whose coordinate is absent: no item, or no entry. */
|
|
80
|
+
const getMissedContent = (collected) => collected.itemAxisOpen ? [] : null;
|
|
81
|
+
/**
|
|
82
|
+
* Lists the chunks a read targets without loading them — lets a binding warm
|
|
83
|
+
* its chunk cache ahead of render.
|
|
84
|
+
*
|
|
85
|
+
* @returns The targeted chunks, empty when a required coordinate is absent.
|
|
86
|
+
*/
|
|
87
|
+
const getDynamicChunks = (loaderMap, key, locale, selector) => {
|
|
88
|
+
const { missed, chunks } = collectDynamicChunks(loaderMap, key, locale, selector);
|
|
89
|
+
return missed ? [] : chunks;
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Loads the raw chunk a plain loader map serves for a locale — same fallback
|
|
93
|
+
* chain and preload as every other dynamic read — for the `useDictionaryAsync`
|
|
94
|
+
* bindings, which interpret it with their own `useDictionary`.
|
|
95
|
+
*
|
|
96
|
+
* @returns The chunk, or `undefined` when the map holds none for the locale
|
|
97
|
+
* nor for any of its fallbacks.
|
|
98
|
+
*/
|
|
99
|
+
const loadDynamicDictionary = async (loaderMap, locale) => {
|
|
100
|
+
const [chunk] = getDynamicChunks(loaderMap, "", locale, void 0);
|
|
101
|
+
if (!chunk) return void 0;
|
|
102
|
+
return chunk.preloaded ?? await chunk.loader();
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Resolves a dynamic read synchronously, loading only the chunk(s) it targets
|
|
106
|
+
* through `loadChunk` — a suspender cache that throws while a chunk is pending.
|
|
107
|
+
*
|
|
108
|
+
* Every pending loader is started before the first chunk is read, so sibling
|
|
109
|
+
* chunks load in parallel rather than waterfalling. Preloaded chunks are read
|
|
110
|
+
* directly, never through `loadChunk`, which would suspend for one microtask.
|
|
111
|
+
*
|
|
112
|
+
* @param params.loadChunk - Reads a started chunk, suspending until it resolves.
|
|
113
|
+
*/
|
|
114
|
+
const resolveDynamicContent = (params) => {
|
|
115
|
+
const { loaderMap, key, locale, selector, loadChunk } = params;
|
|
116
|
+
const collected = collectDynamicChunks(loaderMap, key, locale, selector);
|
|
117
|
+
if (collected.missed) return getMissedContent(collected);
|
|
118
|
+
const dictionaries = collected.chunks.map((chunk) => ({
|
|
119
|
+
chunk,
|
|
120
|
+
promise: chunk.preloaded ? void 0 : chunk.loader()
|
|
121
|
+
})).map(({ chunk, promise }) => chunk.preloaded ?? loadChunk(chunk.cacheKey, promise));
|
|
122
|
+
return readLoadedChunks(params, collected, dictionaries);
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Resolves a dynamic read, awaiting only the chunk(s) it targets.
|
|
126
|
+
*/
|
|
127
|
+
const resolveDynamicContentAsync = async (params) => {
|
|
128
|
+
const { loaderMap, key, locale, selector } = params;
|
|
129
|
+
const collected = collectDynamicChunks(loaderMap, key, locale, selector);
|
|
130
|
+
if (collected.missed) return getMissedContent(collected);
|
|
131
|
+
const dictionaries = await Promise.all(collected.chunks.map((chunk) => chunk.preloaded ?? chunk.loader()));
|
|
132
|
+
return readLoadedChunks(params, collected, dictionaries);
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Creates the content cache of a binding. Entries are kept per loader map, so
|
|
136
|
+
* a hot-reloaded entry point (a new map object) never serves stale content.
|
|
137
|
+
*
|
|
138
|
+
* @param transform - The binding's `getDictionary`, applied to every chunk.
|
|
139
|
+
*/
|
|
140
|
+
const createDynamicContentStore = (transform) => {
|
|
141
|
+
const entriesByLoaderMap = /* @__PURE__ */ new WeakMap();
|
|
142
|
+
const getReadId = ({ locale, selector }) => process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? `${locale}|${require_dictionaryManipulator_qualifiedDictionary.getDictionarySelectorCacheKey(selector)}` : locale;
|
|
143
|
+
const peek = (read) => {
|
|
144
|
+
const settled = entriesByLoaderMap.get(read.loaderMap)?.get(getReadId(read))?.settled;
|
|
145
|
+
if (settled) return settled;
|
|
146
|
+
const collected = collectDynamicChunks(read.loaderMap, read.key, read.locale, read.selector);
|
|
147
|
+
if (collected.missed) return { content: getMissedContent(collected) };
|
|
148
|
+
if (!collected.chunks.every((chunk) => chunk.preloaded)) return void 0;
|
|
149
|
+
return { content: readLoadedChunks({
|
|
150
|
+
...read,
|
|
151
|
+
transform
|
|
152
|
+
}, collected, collected.chunks.map((chunk) => chunk.preloaded)) };
|
|
153
|
+
};
|
|
154
|
+
const load = (read) => {
|
|
155
|
+
const entries = entriesByLoaderMap.get(read.loaderMap) ?? /* @__PURE__ */ new Map();
|
|
156
|
+
entriesByLoaderMap.set(read.loaderMap, entries);
|
|
157
|
+
const readId = getReadId(read);
|
|
158
|
+
const existingEntry = entries.get(readId);
|
|
159
|
+
if (existingEntry) return existingEntry.promise;
|
|
160
|
+
const entry = { promise: resolveDynamicContentAsync({
|
|
161
|
+
...read,
|
|
162
|
+
transform
|
|
163
|
+
}) };
|
|
164
|
+
entries.set(readId, entry);
|
|
165
|
+
entry.promise.then((content) => {
|
|
166
|
+
entry.settled = { content };
|
|
167
|
+
}, () => entries.delete(readId));
|
|
168
|
+
return entry.promise;
|
|
169
|
+
};
|
|
170
|
+
const createReader = (loaderMap, dictionaryKey) => {
|
|
171
|
+
let latestRead;
|
|
172
|
+
return (context, onLoad, onError) => {
|
|
173
|
+
const read = {
|
|
174
|
+
loaderMap,
|
|
175
|
+
key: dictionaryKey,
|
|
176
|
+
...resolveDictionaryRead({
|
|
177
|
+
...context,
|
|
178
|
+
dictionaryKey
|
|
179
|
+
})
|
|
180
|
+
};
|
|
181
|
+
latestRead = read;
|
|
182
|
+
const settled = peek(read);
|
|
183
|
+
if (settled) return settled;
|
|
184
|
+
load(read).then((content) => {
|
|
185
|
+
if (latestRead === read) onLoad(content);
|
|
186
|
+
}, (error) => {
|
|
187
|
+
if (latestRead !== read) return;
|
|
188
|
+
if (!onError) throw error;
|
|
189
|
+
onError(error);
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
return {
|
|
194
|
+
peek,
|
|
195
|
+
load,
|
|
196
|
+
createReader
|
|
197
|
+
};
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* Inert stand-in for content still loading: any property access, call or
|
|
201
|
+
* construction returns it again, and string coercion yields `''`. It never
|
|
202
|
+
* passes for a thenable, an iterable, a DOM node or a Lit template part, so
|
|
203
|
+
* renderers print nothing instead of crashing.
|
|
204
|
+
*/
|
|
205
|
+
const loadingContentPlaceholder = /* @__PURE__ */ new Proxy(function loadingContent() {}, {
|
|
206
|
+
get: (_target, property) => {
|
|
207
|
+
if (property === Symbol.toPrimitive || property === "toString" || property === "valueOf") return () => "";
|
|
208
|
+
if (property === "then" || property === "nodeType" || property === Symbol.iterator || typeof property === "string" && property.startsWith("_$")) return;
|
|
209
|
+
return loadingContentPlaceholder;
|
|
210
|
+
},
|
|
211
|
+
apply: () => loadingContentPlaceholder,
|
|
212
|
+
construct: () => ({})
|
|
213
|
+
});
|
|
214
|
+
const createSuspenseEntry = (promise) => {
|
|
215
|
+
let status = "pending";
|
|
216
|
+
let result;
|
|
217
|
+
const settled = promise.then((value) => {
|
|
218
|
+
status = "success";
|
|
219
|
+
result = value;
|
|
220
|
+
}, (error) => {
|
|
221
|
+
status = "error";
|
|
222
|
+
result = error;
|
|
223
|
+
});
|
|
224
|
+
return {
|
|
225
|
+
settled,
|
|
226
|
+
read: () => {
|
|
227
|
+
if (status === "pending") throw settled;
|
|
228
|
+
if (status === "error") throw result;
|
|
229
|
+
return result;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
};
|
|
233
|
+
/**
|
|
234
|
+
* Creates the chunk cache of a Suspense binding (React, Preact): the
|
|
235
|
+
* `loadChunk` of {@link resolveDynamicContent}.
|
|
236
|
+
*/
|
|
237
|
+
const createChunkSuspenseCache = () => {
|
|
238
|
+
const entries = /* @__PURE__ */ new Map();
|
|
239
|
+
const getEntry = (cacheKey, start) => {
|
|
240
|
+
const existingEntry = entries.get(cacheKey);
|
|
241
|
+
if (existingEntry) return existingEntry;
|
|
242
|
+
const entry = createSuspenseEntry(start());
|
|
243
|
+
entries.set(cacheKey, entry);
|
|
244
|
+
return entry;
|
|
245
|
+
};
|
|
246
|
+
return {
|
|
247
|
+
has: (cacheKey) => entries.has(cacheKey),
|
|
248
|
+
read: (cacheKey, promise) => getEntry(cacheKey, () => promise).read(),
|
|
249
|
+
preload: (cacheKey, loader) => getEntry(cacheKey, loader).settled
|
|
250
|
+
};
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
exports.createChunkSuspenseCache = createChunkSuspenseCache;
|
|
254
|
+
exports.createDynamicContentStore = createDynamicContentStore;
|
|
255
|
+
exports.getDynamicChunkArgument = getDynamicChunkArgument;
|
|
256
|
+
exports.getDynamicChunks = getDynamicChunks;
|
|
257
|
+
exports.loadDynamicDictionary = loadDynamicDictionary;
|
|
258
|
+
exports.loadingContentPlaceholder = loadingContentPlaceholder;
|
|
259
|
+
exports.resolveDictionaryRead = resolveDictionaryRead;
|
|
260
|
+
exports.resolveDynamicContent = resolveDynamicContent;
|
|
261
|
+
exports.resolveDynamicContentAsync = resolveDynamicContentAsync;
|
|
262
|
+
//# sourceMappingURL=dynamicDictionary.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dynamicDictionary.cjs","names":["parseDictionarySelector","resolveDictionaryArgument","resolveInterpreterLocale","isQualifiedDynamicLoaderMap","collectQualifiedChunks","findPlainDynamicLoader","getPreloadedDictionary","readMetadataIndex","QUALIFIER_DYNAMIC_TYPES_KEY","getDictionarySelectorCacheKey"],"sources":["../../../src/dictionaryManipulator/dynamicDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n ProviderVariantBase,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { resolveInterpreterLocale } from '../interpreter/resolveInterpreterLocale';\nimport {\n findPlainDynamicLoader,\n type PlainDynamicLoaderMap,\n} from './plainDynamicLoader';\nimport { getPreloadedDictionary } from './preloadedDynamicLoader';\nimport {\n getDictionarySelectorCacheKey,\n parseDictionarySelector,\n resolveDictionaryArgument,\n} from './qualifiedDictionary';\nimport {\n type CollectedChunk,\n type CollectedChunks,\n collectQualifiedChunks,\n isQualifiedDynamicLoaderMap,\n QUALIFIER_DYNAMIC_TYPES_KEY,\n type QualifiedDynamicLoaderMap,\n readMetadataIndex,\n} from './qualifiedDynamicLoader';\n\n/**\n * Default export of a generated dynamic entry point: a plain `locale → loader`\n * map, or a qualified one (collections / variants).\n */\nexport type DynamicLoaderMap<T extends Dictionary = Dictionary> =\n | PlainDynamicLoaderMap<T>\n | QualifiedDynamicLoaderMap;\n\n/** The effective locale and selector of a dictionary read. */\nexport type DictionaryRead = {\n locale: LocalesValues;\n selector?: DictionarySelector;\n};\n\n/**\n * Turns a loaded chunk into content — a binding's `getDictionary`, so its\n * plugins apply. Receives the bare locale, or `{ locale, metadataOnly }`.\n */\nexport type DynamicChunkTransform<Content> = (\n dictionary: Dictionary,\n argument: LocalesValues | DictionarySelector\n) => Content;\n\n/** Result of a dynamic read: an entry, a collection, or a missed coordinate. */\nexport type DynamicContent<Content> = Content | Content[] | null;\n\n/** Everything a dynamic read needs, besides how chunks are loaded. */\nexport type DynamicReadParams<Content> = DictionaryRead & {\n loaderMap: DynamicLoaderMap;\n /** Dictionary key, namespacing the chunk cache keys. */\n key: string;\n transform: DynamicChunkTransform<Content>;\n};\n\n/**\n * Resolves the locale and selector of a dynamic dictionary read: the call-site\n * argument wins, then the provider context (locale and ambient variant), then\n * the interpreter locale. Every binding's dynamic hook goes through it, so\n * static and dynamic reads resolve identically.\n *\n * Subscription-based bindings call it again on each locale change with the new\n * `contextLocale`, so a locale pinned at the call site stays pinned and an\n * unpinned one follows the switch.\n */\nexport const resolveDictionaryRead = (params: {\n localeOrSelector?: LocalesValues | DictionarySelector | null;\n contextLocale?: LocalesValues;\n contextVariant?: ProviderVariantBase;\n dictionaryKey: string;\n}): DictionaryRead => {\n const localeOrSelector = params.localeOrSelector ?? undefined;\n\n // Inline flag check: with selectors disabled project-wide (build-time flag),\n // the argument can only be a locale and the bundler drops the selector code.\n const { locale, selector } =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false'\n ? parseDictionarySelector<LocalesValues>(\n resolveDictionaryArgument({ ...params, localeOrSelector })\n )\n : {\n locale:\n (localeOrSelector as LocalesValues | undefined) ??\n params.contextLocale,\n selector: undefined,\n };\n\n return { locale: resolveInterpreterLocale(locale), selector };\n};\n\n/**\n * The argument a loaded chunk is transformed with: its locale, plus\n * `metadataOnly` when the read requests metadata. The other selector dimensions\n * were already applied by picking the chunk.\n *\n * @param locale - The read's locale; `undefined` lets the binding's\n * `useDictionary` follow its context locale.\n * @param selector - The read's selector, if any.\n */\nexport const getDynamicChunkArgument = <\n L extends LocalesValues | undefined = LocalesValues,\n>(\n locale: L,\n selector: DictionarySelector | undefined\n): L | DictionarySelector =>\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' && selector?.metadataOnly\n ? { locale: locale as DictionarySelector['locale'], metadataOnly: true }\n : locale;\n\n/**\n * Collects the chunks a read targets. A plain map serves the locale through\n * the same fallback chain as static mode, from its preload when it holds one.\n */\nconst collectDynamicChunks = (\n loaderMap: DynamicLoaderMap,\n key: string,\n locale: LocalesValues,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n if (\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n isQualifiedDynamicLoaderMap(loaderMap)\n ) {\n return collectQualifiedChunks(loaderMap, key, locale, selector);\n }\n\n const resolvedLoader = findPlainDynamicLoader(\n loaderMap as PlainDynamicLoaderMap,\n locale\n );\n\n if (!resolvedLoader) return { itemAxisOpen: false, missed: true, chunks: [] };\n\n return {\n itemAxisOpen: false,\n missed: false,\n chunks: [\n {\n cacheKey: `${key}.${resolvedLoader.locale}`,\n loader: resolvedLoader.loader,\n preloaded: getPreloadedDictionary(loaderMap, resolvedLoader.locale),\n },\n ],\n };\n};\n\n/** Turns the loaded chunks of a read into its content. */\nconst readLoadedChunks = <Content>(\n params: DynamicReadParams<Content>,\n collected: CollectedChunks,\n dictionaries: Dictionary[]\n): DynamicContent<Content> => {\n const { loaderMap, locale, selector, transform } = params;\n\n // The index holds plain records, returned as declared (never interpreted)\n if (\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n collected.readsMetadataIndex\n ) {\n return readMetadataIndex(\n dictionaries[0],\n (loaderMap as QualifiedDynamicLoaderMap)[QUALIFIER_DYNAMIC_TYPES_KEY],\n selector\n ) as Content[];\n }\n\n const argument = getDynamicChunkArgument(locale, selector);\n const read = (dictionary: Dictionary) => transform(dictionary, argument);\n\n if (collected.itemAxisOpen) return dictionaries.map(read);\n\n const [dictionary] = dictionaries;\n\n return dictionary ? read(dictionary) : null;\n};\n\n/** Content of a read whose coordinate is absent: no item, or no entry. */\nconst getMissedContent = <Content>(\n collected: CollectedChunks\n): DynamicContent<Content> => (collected.itemAxisOpen ? [] : null);\n\n/**\n * Lists the chunks a read targets without loading them — lets a binding warm\n * its chunk cache ahead of render.\n *\n * @returns The targeted chunks, empty when a required coordinate is absent.\n */\nexport const getDynamicChunks = (\n loaderMap: DynamicLoaderMap,\n key: string,\n locale: LocalesValues,\n selector: DictionarySelector | undefined\n): CollectedChunk[] => {\n const { missed, chunks } = collectDynamicChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n return missed ? [] : chunks;\n};\n\n/**\n * Loads the raw chunk a plain loader map serves for a locale — same fallback\n * chain and preload as every other dynamic read — for the `useDictionaryAsync`\n * bindings, which interpret it with their own `useDictionary`.\n *\n * @returns The chunk, or `undefined` when the map holds none for the locale\n * nor for any of its fallbacks.\n */\nexport const loadDynamicDictionary = async <T extends Dictionary>(\n loaderMap: PlainDynamicLoaderMap<T>,\n locale: LocalesValues\n): Promise<T | undefined> => {\n const [chunk] = getDynamicChunks(loaderMap, '', locale, undefined);\n\n if (!chunk) return undefined;\n\n return (chunk.preloaded ?? (await chunk.loader())) as T;\n};\n\n/**\n * Resolves a dynamic read synchronously, loading only the chunk(s) it targets\n * through `loadChunk` — a suspender cache that throws while a chunk is pending.\n *\n * Every pending loader is started before the first chunk is read, so sibling\n * chunks load in parallel rather than waterfalling. Preloaded chunks are read\n * directly, never through `loadChunk`, which would suspend for one microtask.\n *\n * @param params.loadChunk - Reads a started chunk, suspending until it resolves.\n */\nexport const resolveDynamicContent = <Content>(\n params: DynamicReadParams<Content> & {\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n }\n): DynamicContent<Content> => {\n const { loaderMap, key, locale, selector, loadChunk } = params;\n\n const collected = collectDynamicChunks(loaderMap, key, locale, selector);\n\n if (collected.missed) return getMissedContent<Content>(collected);\n\n const startedChunks = collected.chunks.map((chunk) => ({\n chunk,\n promise: chunk.preloaded ? undefined : chunk.loader(),\n }));\n\n const dictionaries = startedChunks.map(\n ({ chunk, promise }) =>\n chunk.preloaded ?? loadChunk(chunk.cacheKey, promise!)\n );\n\n return readLoadedChunks(params, collected, dictionaries);\n};\n\n/**\n * Resolves a dynamic read, awaiting only the chunk(s) it targets.\n */\nexport const resolveDynamicContentAsync = async <Content>(\n params: DynamicReadParams<Content>\n): Promise<DynamicContent<Content>> => {\n const { loaderMap, key, locale, selector } = params;\n\n const collected = collectDynamicChunks(loaderMap, key, locale, selector);\n\n if (collected.missed) return getMissedContent<Content>(collected);\n\n const dictionaries = await Promise.all(\n collected.chunks.map((chunk) => chunk.preloaded ?? chunk.loader())\n );\n\n return readLoadedChunks(params, collected, dictionaries);\n};\n\n/** A dynamic read handed to a {@link DynamicContentStore}. */\nexport type DynamicStoreRead = DictionaryRead & {\n loaderMap: DynamicLoaderMap;\n key: string;\n};\n\n/** Settled content of a read; wrapped, since `null` is a valid content. */\nexport type SettledDynamicContent<Content> = {\n content: DynamicContent<Content>;\n};\n\n/** What a {@link DynamicReader} resolves a read from, besides the map. */\nexport type DynamicReadContext = {\n localeOrSelector?: LocalesValues | DictionarySelector | null;\n contextLocale?: LocalesValues;\n contextVariant?: ProviderVariantBase;\n};\n\n/**\n * Reads one dictionary across context changes: returns the content when it is\n * available synchronously, else loads it and calls `onLoad` (or `onError`) —\n * unless a newer read of the same reader superseded it meanwhile. Without\n * `onError`, a failed load surfaces as an unhandled rejection.\n */\nexport type DynamicReader<Content> = (\n context: DynamicReadContext,\n onLoad: (content: DynamicContent<Content>) => void,\n onError?: (error: unknown) => void\n) => SettledDynamicContent<Content> | undefined;\n\n/**\n * Content cache of the bindings that re-render on a notification instead of\n * suspending (vanilla, Lit, Svelte, Vue, Angular).\n */\nexport type DynamicContentStore<Content> = {\n /**\n * The content of a read when it is available without loading — loaded\n * before, or preloaded by the entry point — else `undefined`.\n */\n peek: (read: DynamicStoreRead) => SettledDynamicContent<Content> | undefined;\n /** Loads the content of a read, sharing one load between concurrent reads. */\n load: (read: DynamicStoreRead) => Promise<DynamicContent<Content>>;\n /** Creates the reader of one hook call (see {@link DynamicReader}). */\n createReader: (\n loaderMap: DynamicLoaderMap,\n dictionaryKey: string\n ) => DynamicReader<Content>;\n};\n\ntype DynamicStoreEntry<Content> = {\n promise: Promise<DynamicContent<Content>>;\n settled?: SettledDynamicContent<Content>;\n};\n\n/**\n * Creates the content cache of a binding. Entries are kept per loader map, so\n * a hot-reloaded entry point (a new map object) never serves stale content.\n *\n * @param transform - The binding's `getDictionary`, applied to every chunk.\n */\nexport const createDynamicContentStore = <Content>(\n transform: DynamicChunkTransform<Content>\n): DynamicContentStore<Content> => {\n const entriesByLoaderMap = new WeakMap<\n object,\n Map<string, DynamicStoreEntry<Content>>\n >();\n\n const getReadId = ({ locale, selector }: DynamicStoreRead): string =>\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false'\n ? `${locale}|${getDictionarySelectorCacheKey(selector)}`\n : locale;\n\n const peek = (\n read: DynamicStoreRead\n ): SettledDynamicContent<Content> | undefined => {\n const settled = entriesByLoaderMap\n .get(read.loaderMap)\n ?.get(getReadId(read))?.settled;\n\n if (settled) return settled;\n\n const collected = collectDynamicChunks(\n read.loaderMap,\n read.key,\n read.locale,\n read.selector\n );\n\n if (collected.missed) {\n return { content: getMissedContent<Content>(collected) };\n }\n\n if (!collected.chunks.every((chunk) => chunk.preloaded)) return undefined;\n\n return {\n content: readLoadedChunks(\n { ...read, transform },\n collected,\n collected.chunks.map((chunk) => chunk.preloaded!)\n ),\n };\n };\n\n const load = (read: DynamicStoreRead): Promise<DynamicContent<Content>> => {\n const entries =\n entriesByLoaderMap.get(read.loaderMap) ??\n new Map<string, DynamicStoreEntry<Content>>();\n\n entriesByLoaderMap.set(read.loaderMap, entries);\n\n const readId = getReadId(read);\n const existingEntry = entries.get(readId);\n\n if (existingEntry) return existingEntry.promise;\n\n const entry: DynamicStoreEntry<Content> = {\n promise: resolveDynamicContentAsync({ ...read, transform }),\n };\n\n entries.set(readId, entry);\n\n // Registered before any caller's continuation, so `peek` hits once a\n // caller awaiting `load` resumes. A failed load is dropped to be retried.\n entry.promise.then(\n (content) => {\n entry.settled = { content };\n },\n () => entries.delete(readId)\n );\n\n return entry.promise;\n };\n\n const createReader = (\n loaderMap: DynamicLoaderMap,\n dictionaryKey: string\n ): DynamicReader<Content> => {\n let latestRead: DynamicStoreRead | undefined;\n\n return (context, onLoad, onError) => {\n const read: DynamicStoreRead = {\n loaderMap,\n key: dictionaryKey,\n ...resolveDictionaryRead({ ...context, dictionaryKey }),\n };\n latestRead = read;\n\n const settled = peek(read);\n\n if (settled) return settled;\n\n load(read).then(\n (content) => {\n if (latestRead === read) onLoad(content);\n },\n (error: unknown) => {\n if (latestRead !== read) return;\n if (!onError) throw error;\n\n onError(error);\n }\n );\n\n return undefined;\n };\n };\n\n return { peek, load, createReader };\n};\n\n/**\n * Inert stand-in for content still loading: any property access, call or\n * construction returns it again, and string coercion yields `''`. It never\n * passes for a thenable, an iterable, a DOM node or a Lit template part, so\n * renderers print nothing instead of crashing.\n */\nexport const loadingContentPlaceholder: any = /* @__PURE__ */ new Proxy(\n function loadingContent() {},\n {\n get: (_target, property) => {\n if (\n property === Symbol.toPrimitive ||\n property === 'toString' ||\n property === 'valueOf'\n ) {\n return () => '';\n }\n\n if (\n property === 'then' ||\n property === 'nodeType' ||\n property === Symbol.iterator ||\n (typeof property === 'string' && property.startsWith('_$'))\n ) {\n return undefined;\n }\n\n return loadingContentPlaceholder;\n },\n apply: () => loadingContentPlaceholder,\n construct: () => ({}),\n }\n);\n\ntype SuspenseEntry = {\n /** Settles — never rejects — once the entry has left `pending`. */\n settled: Promise<void>;\n read: () => unknown;\n};\n\nconst createSuspenseEntry = (promise: Promise<unknown>): SuspenseEntry => {\n let status: 'pending' | 'success' | 'error' = 'pending';\n let result: unknown;\n\n const settled = promise.then(\n (value) => {\n status = 'success';\n result = value;\n },\n (error: unknown) => {\n status = 'error';\n result = error;\n }\n );\n\n return {\n settled,\n read: () => {\n if (status === 'pending') throw settled;\n if (status === 'error') throw result;\n\n return result;\n },\n };\n};\n\n/** Chunk cache read the Suspense way (see {@link createChunkSuspenseCache}). */\nexport type ChunkSuspenseCache = {\n /** Whether `cacheKey` holds an entry, pending or settled. */\n has: (cacheKey: string) => boolean;\n /**\n * Reads `cacheKey`, started from `promise` on the first read: throws the\n * pending promise (Suspense) or the rejection until it resolves.\n */\n read: <T>(cacheKey: string, promise: Promise<T>) => T;\n /**\n * Starts `cacheKey` ahead of render. The returned promise settles — never\n * rejects — once a `read` no longer suspends.\n */\n preload: (cacheKey: string, loader: () => Promise<unknown>) => Promise<void>;\n};\n\n/**\n * Creates the chunk cache of a Suspense binding (React, Preact): the\n * `loadChunk` of {@link resolveDynamicContent}.\n */\nexport const createChunkSuspenseCache = (): ChunkSuspenseCache => {\n const entries = new Map<string, SuspenseEntry>();\n\n const getEntry = (\n cacheKey: string,\n start: () => Promise<unknown>\n ): SuspenseEntry => {\n const existingEntry = entries.get(cacheKey);\n\n if (existingEntry) return existingEntry;\n\n const entry = createSuspenseEntry(start());\n entries.set(cacheKey, entry);\n\n return entry;\n };\n\n return {\n has: (cacheKey) => entries.has(cacheKey),\n read: <T>(cacheKey: string, promise: Promise<T>) =>\n getEntry(cacheKey, () => promise).read() as T,\n preload: (cacheKey, loader) => getEntry(cacheKey, loader).settled,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuEA,MAAa,yBAAyB,WAKhB;CACpB,MAAM,mBAAmB,OAAO,oBAAoB;CAIpD,MAAM,EAAE,QAAQ,aACd,QAAQ,IAAI,iCAAiC,UACzCA,0EACEC,4EAA0B;EAAE,GAAG;EAAQ;CAAiB,CAAC,CAC3D,IACA;EACE,QACG,oBACD,OAAO;EACT,UAAU;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;;AAQA,MAAa,4CAAiD,IAAI,MAChE,SAAS,iBAAiB,CAAC,GAC3B;CACE,MAAM,SAAS,aAAa;EAC1B,IACE,aAAa,OAAO,eACpB,aAAa,cACb,aAAa,WAEb,aAAa;EAGf,IACE,aAAa,UACb,aAAa,cACb,aAAa,OAAO,YACnB,OAAO,aAAa,YAAY,SAAS,WAAW,IAAI,GAEzD;EAGF,OAAO;CACT;CACA,aAAa;CACb,kBAAkB,CAAC;AACrB,CACF;AAQA,MAAM,uBAAuB,YAA6C;CACxE,IAAI,SAA0C;CAC9C,IAAI;CAEJ,MAAM,UAAU,QAAQ,MACrB,UAAU;EACT,SAAS;EACT,SAAS;CACX,IACC,UAAmB;EAClB,SAAS;EACT,SAAS;CACX,CACF;CAEA,OAAO;EACL;EACA,YAAY;GACV,IAAI,WAAW,WAAW,MAAM;GAChC,IAAI,WAAW,SAAS,MAAM;GAE9B,OAAO;EACT;CACF;AACF;;;;;AAsBA,MAAa,iCAAqD;CAChE,MAAM,0BAAU,IAAI,IAA2B;CAE/C,MAAM,YACJ,UACA,UACkB;EAClB,MAAM,gBAAgB,QAAQ,IAAI,QAAQ;EAE1C,IAAI,eAAe,OAAO;EAE1B,MAAM,QAAQ,oBAAoB,MAAM,CAAC;EACzC,QAAQ,IAAI,UAAU,KAAK;EAE3B,OAAO;CACT;CAEA,OAAO;EACL,MAAM,aAAa,QAAQ,IAAI,QAAQ;EACvC,OAAU,UAAkB,YAC1B,SAAS,gBAAgB,OAAO,CAAC,CAAC,KAAK;EACzC,UAAU,UAAU,WAAW,SAAS,UAAU,MAAM,CAAC,CAAC;CAC5D;AACF"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
3
|
+
let _intlayer_types_nodeType = require("@intlayer/types/nodeType");
|
|
4
|
+
_intlayer_types_nodeType = require_runtime.__toESM(_intlayer_types_nodeType);
|
|
5
|
+
|
|
6
|
+
// src/dictionaryManipulator/getLocalizedMetadata.ts
|
|
7
|
+
/**
|
|
8
|
+
* Returns the metadata of a dictionary for a locale. The build merges
|
|
9
|
+
* per-locale declarations under a translation node (`t({ en: {…}, fr: {…} })`),
|
|
10
|
+
* read for `locale`, else `fallbackLocale`; any other metadata applies to
|
|
11
|
+
* every locale.
|
|
12
|
+
*
|
|
13
|
+
* @param metadata - The `metadata` of a dictionary or of a collection entry.
|
|
14
|
+
* @param locale - The locale to read.
|
|
15
|
+
* @param fallbackLocale - The locale read when `locale` declares none.
|
|
16
|
+
*/
|
|
17
|
+
const getLocalizedMetadata = (metadata, locale, fallbackLocale) => {
|
|
18
|
+
const perLocaleMetadata = metadata;
|
|
19
|
+
if (perLocaleMetadata?.nodeType !== _intlayer_types_nodeType.TRANSLATION) return metadata ?? {};
|
|
20
|
+
const translations = perLocaleMetadata[_intlayer_types_nodeType.TRANSLATION] ?? {};
|
|
21
|
+
return translations[locale] ?? (fallbackLocale === void 0 ? void 0 : translations[fallbackLocale]) ?? {};
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
exports.getLocalizedMetadata = getLocalizedMetadata;
|
|
25
|
+
//# sourceMappingURL=getLocalizedMetadata.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getLocalizedMetadata.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/getLocalizedMetadata.ts"],"sourcesContent":["import type { DictionaryMetadata } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\ntype PerLocaleMetadata = {\n nodeType?: unknown;\n [NodeTypes.TRANSLATION]?: Record<string, DictionaryMetadata | undefined>;\n};\n\n/**\n * Returns the metadata of a dictionary for a locale. The build merges\n * per-locale declarations under a translation node (`t({ en: {…}, fr: {…} })`),\n * read for `locale`, else `fallbackLocale`; any other metadata applies to\n * every locale.\n *\n * @param metadata - The `metadata` of a dictionary or of a collection entry.\n * @param locale - The locale to read.\n * @param fallbackLocale - The locale read when `locale` declares none.\n */\nexport const getLocalizedMetadata = (\n metadata: unknown,\n locale: LocalesValues,\n fallbackLocale?: LocalesValues\n): DictionaryMetadata => {\n const perLocaleMetadata = metadata as PerLocaleMetadata | undefined;\n\n if (perLocaleMetadata?.nodeType !== NodeTypes.TRANSLATION) {\n return (metadata ?? {}) as DictionaryMetadata;\n }\n\n const translations = perLocaleMetadata[NodeTypes.TRANSLATION] ?? {};\n\n return (\n translations[locale] ??\n (fallbackLocale === undefined ? undefined : translations[fallbackLocale]) ??\n {}\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,wBACX,UACA,QACA,mBACuB;CACvB,MAAM,oBAAoB;CAE1B,IAAI,mBAAmB,aAAaA,yBAAU,aAC5C,OAAQ,YAAY,CAAC;CAGvB,MAAM,eAAe,kBAAkBA,yBAAU,gBAAgB,CAAC;CAElE,OACE,aAAa,YACZ,mBAAmB,SAAY,SAAY,aAAa,oBACzD,CAAC;AAEL"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_dictionaryManipulator_dynamicDictionary = require("./dynamicDictionary.cjs");
|
|
2
3
|
const require_dictionaryManipulator_editDictionaryByKeyPath = require("./editDictionaryByKeyPath.cjs");
|
|
3
4
|
const require_dictionaryManipulator_getContentNodeByKeyPath = require("./getContentNodeByKeyPath.cjs");
|
|
4
5
|
const require_dictionaryManipulator_getDefaultNode = require("./getDefaultNode.cjs");
|
|
5
6
|
const require_dictionaryManipulator_getEmptyNode = require("./getEmptyNode.cjs");
|
|
7
|
+
const require_dictionaryManipulator_getLocalizedMetadata = require("./getLocalizedMetadata.cjs");
|
|
6
8
|
const require_dictionaryManipulator_getNestedDictionaryReferences = require("./getNestedDictionaryReferences.cjs");
|
|
7
9
|
const require_dictionaryManipulator_getNodeChildren = require("./getNodeChildren.cjs");
|
|
8
10
|
const require_dictionaryManipulator_getNodeType = require("./getNodeType.cjs");
|
|
@@ -28,6 +30,12 @@ Object.defineProperty(exports, "PRELOADED_DYNAMIC_KEY", {
|
|
|
28
30
|
return _intlayer_config_defaultValues.PRELOADED_DYNAMIC_KEY;
|
|
29
31
|
}
|
|
30
32
|
});
|
|
33
|
+
Object.defineProperty(exports, "QUALIFIER_DYNAMIC_METADATA_KEY", {
|
|
34
|
+
enumerable: true,
|
|
35
|
+
get: function () {
|
|
36
|
+
return _intlayer_config_defaultValues.QUALIFIER_DYNAMIC_METADATA_KEY;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
31
39
|
Object.defineProperty(exports, "QUALIFIER_DYNAMIC_TYPES_KEY", {
|
|
32
40
|
enumerable: true,
|
|
33
41
|
get: function () {
|
|
@@ -35,6 +43,11 @@ Object.defineProperty(exports, "QUALIFIER_DYNAMIC_TYPES_KEY", {
|
|
|
35
43
|
}
|
|
36
44
|
});
|
|
37
45
|
exports.QUALIFIER_ORDER = require_dictionaryManipulator_qualifiedDictionaryDeclaration.QUALIFIER_ORDER;
|
|
46
|
+
exports.collectQualifiedChunks = require_dictionaryManipulator_qualifiedDynamicLoader.collectQualifiedChunks;
|
|
47
|
+
exports.compareItemIds = require_dictionaryManipulator_qualifiedDictionary.compareItemIds;
|
|
48
|
+
exports.compareItemSegments = require_dictionaryManipulator_qualifiedDictionary.compareItemSegments;
|
|
49
|
+
exports.createChunkSuspenseCache = require_dictionaryManipulator_dynamicDictionary.createChunkSuspenseCache;
|
|
50
|
+
exports.createDynamicContentStore = require_dictionaryManipulator_dynamicDictionary.createDynamicContentStore;
|
|
38
51
|
exports.editDictionaryByKeyPath = require_dictionaryManipulator_editDictionaryByKeyPath.editDictionaryByKeyPath;
|
|
39
52
|
exports.findPlainDynamicLoader = require_dictionaryManipulator_plainDynamicLoader.findPlainDynamicLoader;
|
|
40
53
|
exports.getContentNodeByKeyPath = require_dictionaryManipulator_getContentNodeByKeyPath.getContentNodeByKeyPath;
|
|
@@ -43,33 +56,44 @@ exports.getDictionaryCompositeIds = require_dictionaryManipulator_qualifiedDicti
|
|
|
43
56
|
exports.getDictionaryQualifierIds = require_dictionaryManipulator_qualifiedDictionaryDeclaration.getDictionaryQualifierIds;
|
|
44
57
|
exports.getDictionaryQualifierTypes = require_dictionaryManipulator_qualifiedDictionaryDeclaration.getDictionaryQualifierTypes;
|
|
45
58
|
exports.getDictionarySelectorCacheKey = require_dictionaryManipulator_qualifiedDictionary.getDictionarySelectorCacheKey;
|
|
59
|
+
exports.getDynamicChunkArgument = require_dictionaryManipulator_dynamicDictionary.getDynamicChunkArgument;
|
|
60
|
+
exports.getDynamicChunks = require_dictionaryManipulator_dynamicDictionary.getDynamicChunks;
|
|
46
61
|
exports.getEmptyNode = require_dictionaryManipulator_getEmptyNode.getEmptyNode;
|
|
62
|
+
exports.getLocalizedMetadata = require_dictionaryManipulator_getLocalizedMetadata.getLocalizedMetadata;
|
|
47
63
|
exports.getNestedDictionaryGraph = require_dictionaryManipulator_getNestedDictionaryReferences.getNestedDictionaryGraph;
|
|
48
64
|
exports.getNestedDictionaryKeys = require_dictionaryManipulator_getNestedDictionaryReferences.getNestedDictionaryKeys;
|
|
49
65
|
exports.getNestedDictionaryReferences = require_dictionaryManipulator_getNestedDictionaryReferences.getNestedDictionaryReferences;
|
|
50
66
|
exports.getNodeChildren = require_dictionaryManipulator_getNodeChildren.getNodeChildren;
|
|
51
67
|
exports.getNodeType = require_dictionaryManipulator_getNodeType.getNodeType;
|
|
52
68
|
exports.getPreloadedDictionary = require_dictionaryManipulator_preloadedDynamicLoader.getPreloadedDictionary;
|
|
53
|
-
exports.getQualifiedDynamicChunks = require_dictionaryManipulator_qualifiedDynamicLoader.getQualifiedDynamicChunks;
|
|
54
69
|
exports.getVariantIds = require_dictionaryManipulator_qualifiedDictionaryDeclaration.getVariantIds;
|
|
70
|
+
exports.isDeclaredItem = require_dictionaryManipulator_qualifiedDictionaryDeclaration.isDeclaredItem;
|
|
55
71
|
exports.isQualifiedDictionaryGroup = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDictionaryGroup;
|
|
56
72
|
exports.isQualifiedDynamicLoaderMap = require_dictionaryManipulator_qualifiedDynamicLoader.isQualifiedDynamicLoaderMap;
|
|
73
|
+
exports.loadDynamicDictionary = require_dictionaryManipulator_dynamicDictionary.loadDynamicDictionary;
|
|
74
|
+
exports.loadingContentPlaceholder = require_dictionaryManipulator_dynamicDictionary.loadingContentPlaceholder;
|
|
75
|
+
exports.matchQualifiedEntryIds = require_dictionaryManipulator_qualifiedDictionary.matchQualifiedEntryIds;
|
|
57
76
|
exports.mergeDictionaries = require_dictionaryManipulator_mergeDictionaries.mergeDictionaries;
|
|
58
77
|
exports.mergeQualifiedDictionaries = require_dictionaryManipulator_mergeQualifiedDictionaries.mergeQualifiedDictionaries;
|
|
59
78
|
exports.normalizeDictionaries = require_dictionaryManipulator_normalizeDictionary.normalizeDictionaries;
|
|
60
79
|
exports.normalizeDictionary = require_dictionaryManipulator_normalizeDictionary.normalizeDictionary;
|
|
61
80
|
exports.orderDictionaries = require_dictionaryManipulator_orderDictionaries.orderDictionaries;
|
|
62
81
|
exports.parseDictionarySelector = require_dictionaryManipulator_qualifiedDictionary.parseDictionarySelector;
|
|
82
|
+
exports.parseItemId = require_dictionaryManipulator_qualifiedDictionary.parseItemId;
|
|
83
|
+
exports.parseItemSegment = require_dictionaryManipulator_qualifiedDictionary.parseItemSegment;
|
|
84
|
+
exports.readMetadataIndex = require_dictionaryManipulator_qualifiedDynamicLoader.readMetadataIndex;
|
|
63
85
|
exports.reconstructQualifiedEntry = require_dictionaryManipulator_qualifiedDictionary.reconstructQualifiedEntry;
|
|
64
86
|
exports.removeContentNodeByKeyPath = require_dictionaryManipulator_removeContentNodeByKeyPath.removeContentNodeByKeyPath;
|
|
65
87
|
exports.renameContentNodeByKeyPath = require_dictionaryManipulator_renameContentNodeByKeyPath.renameContentNodeByKeyPath;
|
|
66
88
|
exports.resolveDictionaryArgument = require_dictionaryManipulator_qualifiedDictionary.resolveDictionaryArgument;
|
|
89
|
+
exports.resolveDictionaryRead = require_dictionaryManipulator_dynamicDictionary.resolveDictionaryRead;
|
|
90
|
+
exports.resolveDynamicContent = require_dictionaryManipulator_dynamicDictionary.resolveDynamicContent;
|
|
91
|
+
exports.resolveDynamicContentAsync = require_dictionaryManipulator_dynamicDictionary.resolveDynamicContentAsync;
|
|
67
92
|
exports.resolveEffectiveVariantId = require_dictionaryManipulator_qualifiedDictionary.resolveEffectiveVariantId;
|
|
68
93
|
exports.resolvePlainDynamicLoader = require_dictionaryManipulator_plainDynamicLoader.resolvePlainDynamicLoader;
|
|
69
94
|
exports.resolveProviderVariant = require_dictionaryManipulator_qualifiedDictionary.resolveProviderVariant;
|
|
70
95
|
exports.resolveQualifiedDictionary = require_dictionaryManipulator_qualifiedDictionary.resolveQualifiedDictionary;
|
|
71
|
-
exports.
|
|
72
|
-
exports.resolveQualifiedDynamicContentAsync = require_dictionaryManipulator_qualifiedDynamicLoader.resolveQualifiedDynamicContentAsync;
|
|
96
|
+
exports.serializeItem = require_dictionaryManipulator_qualifiedDictionary.serializeItem;
|
|
73
97
|
exports.serializeVariant = require_dictionaryManipulator_qualifiedDictionary.serializeVariant;
|
|
74
98
|
exports.serializeVariantChain = require_dictionaryManipulator_qualifiedDictionary.serializeVariantChain;
|
|
75
99
|
exports.updateNodeChildren = require_dictionaryManipulator_updateNodeChildren.updateNodeChildren;
|
|
@@ -53,16 +53,19 @@ const mergeDictionaries = (dictionaries) => {
|
|
|
53
53
|
const dictionariesKeys = dictionaries.map((dict) => dict.key);
|
|
54
54
|
if (new Set(dictionariesKeys).size !== 1) throw new Error("All dictionaries must have the same key");
|
|
55
55
|
let mergedContent = dictionaries[0].content;
|
|
56
|
+
let mergedMetadata = dictionaries[0].metadata;
|
|
56
57
|
for (let i = 1; i < dictionaries.length; i++) {
|
|
57
58
|
const dict = dictionaries[i];
|
|
58
59
|
if (!dict) continue;
|
|
59
60
|
const currentDictionary = require_deepTransformPlugins_getMultilingualDictionary.getMultilingualDictionary(dict);
|
|
60
61
|
checkTypesMatch(mergedContent, currentDictionary.content, currentDictionary.localId, currentDictionary.key, []);
|
|
61
62
|
mergedContent = customMerge(mergedContent, currentDictionary.content);
|
|
63
|
+
if (currentDictionary.metadata !== void 0) mergedMetadata = mergedMetadata === void 0 ? currentDictionary.metadata : customMerge(mergedMetadata, currentDictionary.metadata);
|
|
62
64
|
}
|
|
63
65
|
return {
|
|
64
66
|
key: dictionaries[0].key,
|
|
65
67
|
content: mergedContent,
|
|
68
|
+
...mergedMetadata !== void 0 && { metadata: mergedMetadata },
|
|
66
69
|
localIds
|
|
67
70
|
};
|
|
68
71
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeDictionaries.cjs","names":["getAppLogger","getNodeType","colorizeKey","getMultilingualDictionary"],"sources":["../../../src/dictionaryManipulator/mergeDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport { getMultilingualDictionary } from '../deepTransformPlugins';\nimport { getNodeType } from './getNodeType';\n\n// Extended type that includes arrays for internal merge operations\ntype MergeableContent = ContentNode | ContentNode[];\n\nconst checkTypesMatch = (\n object1: ContentNode,\n object2: ContentNode,\n object2LocalId: LocalDictionaryId | undefined,\n dictionaryKey: string,\n path: string[] = []\n): void => {\n const appLogger = getAppLogger({ log });\n\n // If either side is missing/undefined, allow merge without error\n if (\n object1 === undefined ||\n object1 === null ||\n object2 === undefined ||\n object2 === null\n )\n return;\n\n const type1 = getNodeType(object1);\n const type2 = getNodeType(object2);\n\n // Unknown types are treated as flexible; skip strict mismatch reporting\n if (type1 === 'unknown' || type2 === 'unknown') return;\n\n if (type1 !== type2) {\n appLogger(\n [\n `Error: Dictionary ${colorizeKey(dictionaryKey)} has a multiple content files with type mismatch at path \"${path.join('.')}\": Cannot merge ${type1} with ${type2} while merging ${object2LocalId}`,\n ],\n {\n level: 'error',\n }\n );\n\n return;\n }\n};\n\n// Custom merge function that prefers destination (first dictionary) values\nconst customMerge = (\n destination: ContentNode,\n source: ContentNode\n): MergeableContent => {\n // If destination is undefined/null, use source\n if (destination === undefined || destination === null) {\n return source;\n }\n\n // If source is undefined/null, use destination\n if (source === undefined || source === null) {\n return destination;\n }\n\n // For primitive values, prefer destination (first dictionary)\n if (typeof destination !== 'object' || typeof source !== 'object') {\n return destination;\n }\n\n // For arrays, use our custom array merge\n if (Array.isArray(destination) && Array.isArray(source)) {\n return arrayMerge(\n destination as ContentNode[],\n source as ContentNode[]\n ) as MergeableContent;\n }\n\n // For objects, recursively merge with our custom logic\n if (typeof destination === 'object' && typeof source === 'object') {\n const result: Record<string, MergeableContent> = {};\n const allKeys = new Set([\n ...Object.keys(destination as unknown as Record<string, ContentNode>),\n ...Object.keys(source as unknown as Record<string, ContentNode>),\n ]);\n\n for (const key of allKeys) {\n result[key] = customMerge(\n (destination as unknown as Record<string, ContentNode>)[key],\n (source as unknown as Record<string, ContentNode>)[key]\n );\n }\n\n return result as unknown as MergeableContent;\n }\n\n // Fallback to destination\n return destination;\n};\n\n// Custom array merge strategy that merges arrays by key when present, otherwise by index\nconst arrayMerge = (\n destinationArray: ContentNode[],\n sourceArray: ContentNode[]\n): MergeableContent[] => {\n // Check if both arrays contain only primitives\n const destHasOnlyPrimitives = destinationArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n const sourceHasOnlyPrimitives = sourceArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n\n // If both arrays contain only primitives, use the source array (second dictionary)\n if (destHasOnlyPrimitives && sourceHasOnlyPrimitives) {\n return sourceArray;\n }\n\n // Otherwise, merge by index with object merging logic\n const result: MergeableContent[] = [];\n const maxLength = Math.max(destinationArray.length, sourceArray.length);\n\n for (let i = 0; i < maxLength; i++) {\n const destItem = destinationArray[i];\n const sourceItem = sourceArray[i];\n\n if (destItem === undefined && sourceItem === undefined) {\n } else if (destItem === undefined) {\n // Only source exists, add it\n result.push(sourceItem);\n } else if (sourceItem === undefined) {\n // Only destination exists, add it\n result.push(destItem);\n } else {\n // Both exist, merge them\n if (\n typeof destItem === 'object' &&\n typeof sourceItem === 'object' &&\n destItem !== null &&\n sourceItem !== null\n ) {\n // Check if both objects have a 'key' property for keyed merging\n if (\n 'key' in destItem &&\n 'key' in sourceItem &&\n (destItem as Record<string, string>).key ===\n (sourceItem as Record<string, string>).key\n ) {\n // Merge objects with same key, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n } else {\n // Merge objects by index, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n }\n } else {\n // For primitives or non-objects, use destination value (first dictionary)\n result.push(destItem);\n }\n }\n }\n\n return result;\n};\n\nexport const mergeDictionaries = (dictionaries: Dictionary[]): Dictionary => {\n const localIds = Array.from(\n new Set<LocalDictionaryId>(\n dictionaries.filter((dict) => dict.localId).map((dict) => dict.localId!)\n )\n );\n\n if (!dictionaries[0] || dictionaries.length <= 1) {\n return dictionaries[0]!;\n }\n\n const dictionariesKeys = dictionaries.map((dict) => dict.key);\n\n // Check if all dictionaries have the same key\n if (new Set(dictionariesKeys).size !== 1) {\n throw new Error('All dictionaries must have the same key');\n }\n\n let mergedContent: Dictionary['content'] = dictionaries[0].content;\n\n for (let i = 1; i < dictionaries.length; i++) {\n const dict = dictionaries[i];\n\n if (!dict) continue;\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n const currentDictionary = getMultilingualDictionary(dict);\n\n // Check types before merging\n checkTypesMatch(\n mergedContent,\n currentDictionary.content,\n currentDictionary.localId,\n currentDictionary.key,\n []\n );\n\n mergedContent = customMerge(\n mergedContent,\n currentDictionary.content\n ) as ContentNode;\n }\n\n const mergedDictionary: Dictionary = {\n key: dictionaries[0].key,\n content: mergedContent,\n localIds,\n };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BAC3B,OAAO;CAIT,MAAM,SAA6B,CAAC;CACpC,MAAM,YAAY,KAAK,IAAI,iBAAiB,QAAQ,YAAY,MAAM;CAEtE,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,KAAK;EAClC,MAAM,WAAW,iBAAiB;EAClC,MAAM,aAAa,YAAY;EAE/B,IAAI,aAAa,UAAa,eAAe,QAAW,CACxD,OAAO,IAAI,aAAa,QAEtB,OAAO,KAAK,UAAU;OACjB,IAAI,eAAe,QAExB,OAAO,KAAK,QAAQ;OAGpB,IACE,OAAO,aAAa,YACpB,OAAO,eAAe,YACtB,aAAa,QACb,eAAe,MACf;GAEA,IACE,SAAS,YACT,SAAS,cACR,SAAoC,QAClC,WAAsC,KAGzC,OAAO,KAAK,YAAY,UAAU,UAAU,CAAC;QAG7C,OAAO,KAAK,YAAY,UAAU,UAAU,CAAC;EAEjD,OAEE,OAAO,KAAK,QAAQ;CAG1B;CAEA,OAAO;AACT;AAEA,MAAa,qBAAqB,iBAA2C;CAC3E,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aAAa,QAAQ,SAAS,KAAK,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,OAAQ,CACzE,CACF;CAEA,IAAI,CAAC,aAAa,MAAM,aAAa,UAAU,GAC7C,OAAO,aAAa;CAGtB,MAAM,mBAAmB,aAAa,KAAK,SAAS,KAAK,GAAG;CAG5D,IAAI,IAAI,IAAI,gBAAgB,CAAC,CAAC,SAAS,GACrC,MAAM,IAAI,MAAM,yCAAyC;CAG3D,IAAI,gBAAuC,aAAa,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"mergeDictionaries.cjs","names":["getAppLogger","getNodeType","colorizeKey","getMultilingualDictionary"],"sources":["../../../src/dictionaryManipulator/mergeDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport { getMultilingualDictionary } from '../deepTransformPlugins';\nimport { getNodeType } from './getNodeType';\n\n// Extended type that includes arrays for internal merge operations\ntype MergeableContent = ContentNode | ContentNode[];\n\nconst checkTypesMatch = (\n object1: ContentNode,\n object2: ContentNode,\n object2LocalId: LocalDictionaryId | undefined,\n dictionaryKey: string,\n path: string[] = []\n): void => {\n const appLogger = getAppLogger({ log });\n\n // If either side is missing/undefined, allow merge without error\n if (\n object1 === undefined ||\n object1 === null ||\n object2 === undefined ||\n object2 === null\n )\n return;\n\n const type1 = getNodeType(object1);\n const type2 = getNodeType(object2);\n\n // Unknown types are treated as flexible; skip strict mismatch reporting\n if (type1 === 'unknown' || type2 === 'unknown') return;\n\n if (type1 !== type2) {\n appLogger(\n [\n `Error: Dictionary ${colorizeKey(dictionaryKey)} has a multiple content files with type mismatch at path \"${path.join('.')}\": Cannot merge ${type1} with ${type2} while merging ${object2LocalId}`,\n ],\n {\n level: 'error',\n }\n );\n\n return;\n }\n};\n\n// Custom merge function that prefers destination (first dictionary) values\nconst customMerge = (\n destination: ContentNode,\n source: ContentNode\n): MergeableContent => {\n // If destination is undefined/null, use source\n if (destination === undefined || destination === null) {\n return source;\n }\n\n // If source is undefined/null, use destination\n if (source === undefined || source === null) {\n return destination;\n }\n\n // For primitive values, prefer destination (first dictionary)\n if (typeof destination !== 'object' || typeof source !== 'object') {\n return destination;\n }\n\n // For arrays, use our custom array merge\n if (Array.isArray(destination) && Array.isArray(source)) {\n return arrayMerge(\n destination as ContentNode[],\n source as ContentNode[]\n ) as MergeableContent;\n }\n\n // For objects, recursively merge with our custom logic\n if (typeof destination === 'object' && typeof source === 'object') {\n const result: Record<string, MergeableContent> = {};\n const allKeys = new Set([\n ...Object.keys(destination as unknown as Record<string, ContentNode>),\n ...Object.keys(source as unknown as Record<string, ContentNode>),\n ]);\n\n for (const key of allKeys) {\n result[key] = customMerge(\n (destination as unknown as Record<string, ContentNode>)[key],\n (source as unknown as Record<string, ContentNode>)[key]\n );\n }\n\n return result as unknown as MergeableContent;\n }\n\n // Fallback to destination\n return destination;\n};\n\n// Custom array merge strategy that merges arrays by key when present, otherwise by index\nconst arrayMerge = (\n destinationArray: ContentNode[],\n sourceArray: ContentNode[]\n): MergeableContent[] => {\n // Check if both arrays contain only primitives\n const destHasOnlyPrimitives = destinationArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n const sourceHasOnlyPrimitives = sourceArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n\n // If both arrays contain only primitives, use the source array (second dictionary)\n if (destHasOnlyPrimitives && sourceHasOnlyPrimitives) {\n return sourceArray;\n }\n\n // Otherwise, merge by index with object merging logic\n const result: MergeableContent[] = [];\n const maxLength = Math.max(destinationArray.length, sourceArray.length);\n\n for (let i = 0; i < maxLength; i++) {\n const destItem = destinationArray[i];\n const sourceItem = sourceArray[i];\n\n if (destItem === undefined && sourceItem === undefined) {\n } else if (destItem === undefined) {\n // Only source exists, add it\n result.push(sourceItem);\n } else if (sourceItem === undefined) {\n // Only destination exists, add it\n result.push(destItem);\n } else {\n // Both exist, merge them\n if (\n typeof destItem === 'object' &&\n typeof sourceItem === 'object' &&\n destItem !== null &&\n sourceItem !== null\n ) {\n // Check if both objects have a 'key' property for keyed merging\n if (\n 'key' in destItem &&\n 'key' in sourceItem &&\n (destItem as Record<string, string>).key ===\n (sourceItem as Record<string, string>).key\n ) {\n // Merge objects with same key, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n } else {\n // Merge objects by index, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n }\n } else {\n // For primitives or non-objects, use destination value (first dictionary)\n result.push(destItem);\n }\n }\n }\n\n return result;\n};\n\nexport const mergeDictionaries = (dictionaries: Dictionary[]): Dictionary => {\n const localIds = Array.from(\n new Set<LocalDictionaryId>(\n dictionaries.filter((dict) => dict.localId).map((dict) => dict.localId!)\n )\n );\n\n if (!dictionaries[0] || dictionaries.length <= 1) {\n return dictionaries[0]!;\n }\n\n const dictionariesKeys = dictionaries.map((dict) => dict.key);\n\n // Check if all dictionaries have the same key\n if (new Set(dictionariesKeys).size !== 1) {\n throw new Error('All dictionaries must have the same key');\n }\n\n let mergedContent: Dictionary['content'] = dictionaries[0].content;\n let mergedMetadata: Dictionary['metadata'] = dictionaries[0].metadata;\n\n for (let i = 1; i < dictionaries.length; i++) {\n const dict = dictionaries[i];\n\n if (!dict) continue;\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n const currentDictionary = getMultilingualDictionary(dict);\n\n // Check types before merging\n checkTypesMatch(\n mergedContent,\n currentDictionary.content,\n currentDictionary.localId,\n currentDictionary.key,\n []\n );\n\n mergedContent = customMerge(\n mergedContent,\n currentDictionary.content\n ) as ContentNode;\n\n if (currentDictionary.metadata !== undefined) {\n mergedMetadata = (\n mergedMetadata === undefined\n ? currentDictionary.metadata\n : customMerge(\n mergedMetadata as unknown as ContentNode,\n currentDictionary.metadata as unknown as ContentNode\n )\n ) as Dictionary['metadata'];\n }\n }\n\n const mergedDictionary: Dictionary = {\n key: dictionaries[0].key,\n content: mergedContent,\n ...(mergedMetadata !== undefined && { metadata: mergedMetadata }),\n localIds,\n };\n\n return mergedDictionary;\n};\n"],"mappings":";;;;;;;AAaA,MAAM,mBACJ,SACA,SACA,gBACA,eACA,OAAiB,CAAC,MACT;CACT,MAAM,gBAAYA,sCAAa,EAAE,gCAAI,CAAC;CAGtC,IACE,YAAY,UACZ,YAAY,QACZ,YAAY,UACZ,YAAY,MAEZ;CAEF,MAAM,QAAQC,sDAAY,OAAO;CACjC,MAAM,QAAQA,sDAAY,OAAO;CAGjC,IAAI,UAAU,aAAa,UAAU,WAAW;CAEhD,IAAI,UAAU,OAAO;EACnB,UACE,CACE,yBAAqBC,qCAAY,aAAa,EAAE,4DAA4D,KAAK,KAAK,GAAG,EAAE,kBAAkB,MAAM,QAAQ,MAAM,iBAAiB,gBACpL,GACA,EACE,OAAO,QACT,CACF;EAEA;CACF;AACF;AAGA,MAAM,eAC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AAK,YAAY,UAAU,UAAU,CAAC;EAEjD,OAEE,OAAO,KAAK,QAAQ;CAG1B;CAEA,OAAO;AACT;AAEA,MAAa,qBAAqB,iBAA2C;CAC3E,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aAAa,QAAQ,SAAS,KAAK,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,OAAQ,CACzE,CACF;CAEA,IAAI,CAAC,aAAa,MAAM,aAAa,UAAU,GAC7C,OAAO,aAAa;CAGtB,MAAM,mBAAmB,aAAa,KAAK,SAAS,KAAK,GAAG;CAG5D,IAAI,IAAI,IAAI,gBAAgB,CAAC,CAAC,SAAS,GACrC,MAAM,IAAI,MAAM,yCAAyC;CAG3D,IAAI,gBAAuC,aAAa,EAAE,CAAC;CAC3D,IAAI,iBAAyC,aAAa,EAAE,CAAC;CAE7D,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;EAC5C,MAAM,OAAO,aAAa;EAE1B,IAAI,CAAC,MAAM;EAGX,MAAM,oBAAoBC,iFAA0B,IAAI;EAGxD,gBACE,eACA,kBAAkB,SAClB,kBAAkB,SAClB,kBAAkB,KAClB,CAAC,CACH;EAEA,gBAAgB,YACd,eACA,kBAAkB,OACpB;EAEA,IAAI,kBAAkB,aAAa,QACjC,iBACE,mBAAmB,SACf,kBAAkB,WAClB,YACE,gBACA,kBAAkB,QACpB;CAGV;CASA,OAAO;EANL,KAAK,aAAa,EAAE,CAAC;EACrB,SAAS;EACT,GAAI,mBAAmB,UAAa,EAAE,UAAU,eAAe;EAC/D;CAGoB;AACxB"}
|
|
@@ -51,6 +51,7 @@ const mergeQualifiedDictionaries = (dictionaries) => {
|
|
|
51
51
|
});
|
|
52
52
|
if (groupQualifierTypes.length === 1 && groupQualifierTypes[0] === "variant" && baseDictionaries.length > 0 && !entriesDictionaries.has("default")) entriesDictionaries.set(require_dictionaryManipulator_qualifiedDictionary.DEFAULT_VARIANT_ID, []);
|
|
53
53
|
const content = {};
|
|
54
|
+
const metadata = {};
|
|
54
55
|
let importMode;
|
|
55
56
|
const variantIndex = groupQualifierTypes.indexOf("variant");
|
|
56
57
|
/**
|
|
@@ -68,11 +69,13 @@ const mergeQualifiedDictionaries = (dictionaries) => {
|
|
|
68
69
|
for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {
|
|
69
70
|
const inheritedEntryId = getInheritedEntryId(compositeId);
|
|
70
71
|
const inheritedDictionaries = inheritedEntryId ? entriesDictionaries.get(inheritedEntryId) ?? [] : [];
|
|
71
|
-
|
|
72
|
+
const mergedEntry = require_dictionaryManipulator_mergeDictionaries.mergeDictionaries([
|
|
72
73
|
...qualifiedDictionaries,
|
|
73
74
|
...inheritedDictionaries,
|
|
74
75
|
...baseDictionaries
|
|
75
|
-
])
|
|
76
|
+
]);
|
|
77
|
+
content[compositeId] = mergedEntry.content;
|
|
78
|
+
if (mergedEntry.metadata !== void 0) metadata[compositeId] = mergedEntry.metadata;
|
|
76
79
|
const [firstQualified] = qualifiedDictionaries;
|
|
77
80
|
importMode ??= firstQualified?.importMode;
|
|
78
81
|
}
|
|
@@ -81,6 +84,7 @@ const mergeQualifiedDictionaries = (dictionaries) => {
|
|
|
81
84
|
key: dictionaries[0].key,
|
|
82
85
|
qualifierTypes: groupQualifierTypes,
|
|
83
86
|
content,
|
|
87
|
+
...Object.keys(metadata).length > 0 && { metadata },
|
|
84
88
|
...importMode !== void 0 && { importMode },
|
|
85
89
|
localIds
|
|
86
90
|
};
|