@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.
Files changed (76) hide show
  1. package/dist/cjs/deepTransformPlugins/getLocalizedContent.cjs +3 -1
  2. package/dist/cjs/deepTransformPlugins/getLocalizedContent.cjs.map +1 -1
  3. package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs +2 -1
  4. package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs.map +1 -1
  5. package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs +262 -0
  6. package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs.map +1 -0
  7. package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs +25 -0
  8. package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs.map +1 -0
  9. package/dist/cjs/dictionaryManipulator/index.cjs +27 -3
  10. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +3 -0
  11. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
  12. package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +6 -2
  13. package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
  14. package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs +2 -1
  15. package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs.map +1 -1
  16. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +80 -12
  17. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
  18. package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs +9 -3
  19. package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs.map +1 -1
  20. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +38 -68
  21. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
  22. package/dist/cjs/index.cjs +27 -3
  23. package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
  24. package/dist/cjs/interpreter/getDictionary.cjs +3 -0
  25. package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
  26. package/dist/cjs/interpreter/getDictionaryAsync.cjs +5 -19
  27. package/dist/cjs/interpreter/getDictionaryAsync.cjs.map +1 -1
  28. package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs +3 -1
  29. package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs.map +1 -1
  30. package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs +2 -1
  31. package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs.map +1 -1
  32. package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs +252 -0
  33. package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs.map +1 -0
  34. package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs +22 -0
  35. package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs.map +1 -0
  36. package/dist/esm/dictionaryManipulator/index.mjs +6 -4
  37. package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs +3 -0
  38. package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs.map +1 -1
  39. package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs +6 -2
  40. package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs.map +1 -1
  41. package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs +2 -1
  42. package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs.map +1 -1
  43. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs +75 -13
  44. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
  45. package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs +10 -5
  46. package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs.map +1 -1
  47. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +33 -68
  48. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
  49. package/dist/esm/index.mjs +6 -4
  50. package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
  51. package/dist/esm/interpreter/getDictionary.mjs +3 -0
  52. package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
  53. package/dist/esm/interpreter/getDictionaryAsync.mjs +5 -19
  54. package/dist/esm/interpreter/getDictionaryAsync.mjs.map +1 -1
  55. package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +2 -1
  56. package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +2 -1
  57. package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +2 -1
  58. package/dist/types/deepTransformPlugins/getLocalizedContent.d.ts.map +1 -1
  59. package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts +159 -0
  60. package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts.map +1 -0
  61. package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts +14 -0
  62. package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts.map +1 -0
  63. package/dist/types/dictionaryManipulator/index.d.ts +6 -4
  64. package/dist/types/dictionaryManipulator/normalizeDictionary.d.ts.map +1 -1
  65. package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts +51 -5
  66. package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts.map +1 -1
  67. package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts +7 -2
  68. package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts.map +1 -1
  69. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +34 -54
  70. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
  71. package/dist/types/index.d.ts +6 -4
  72. package/dist/types/interpreter/getContent/plugins.d.ts +2 -1
  73. package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
  74. package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
  75. package/dist/types/interpreter/getDictionaryAsync.d.ts.map +1 -1
  76. package/package.json +6 -6
@@ -0,0 +1,252 @@
1
+ import { resolveInterpreterLocale } from "../interpreter/resolveInterpreterLocale.mjs";
2
+ import { findPlainDynamicLoader } from "./plainDynamicLoader.mjs";
3
+ import { getPreloadedDictionary } from "./preloadedDynamicLoader.mjs";
4
+ import { getDictionarySelectorCacheKey, parseDictionarySelector, resolveDictionaryArgument } from "./qualifiedDictionary.mjs";
5
+ import { QUALIFIER_DYNAMIC_TYPES_KEY, collectQualifiedChunks, isQualifiedDynamicLoaderMap, readMetadataIndex } from "./qualifiedDynamicLoader.mjs";
6
+
7
+ // src/dictionaryManipulator/dynamicDictionary.ts
8
+ /**
9
+ * Resolves the locale and selector of a dynamic dictionary read: the call-site
10
+ * argument wins, then the provider context (locale and ambient variant), then
11
+ * the interpreter locale. Every binding's dynamic hook goes through it, so
12
+ * static and dynamic reads resolve identically.
13
+ *
14
+ * Subscription-based bindings call it again on each locale change with the new
15
+ * `contextLocale`, so a locale pinned at the call site stays pinned and an
16
+ * unpinned one follows the switch.
17
+ */
18
+ const resolveDictionaryRead = (params) => {
19
+ const localeOrSelector = params.localeOrSelector ?? void 0;
20
+ const { locale, selector } = process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? parseDictionarySelector(resolveDictionaryArgument({
21
+ ...params,
22
+ localeOrSelector
23
+ })) : {
24
+ locale: localeOrSelector ?? params.contextLocale,
25
+ selector: void 0
26
+ };
27
+ return {
28
+ locale: resolveInterpreterLocale(locale),
29
+ selector
30
+ };
31
+ };
32
+ /**
33
+ * The argument a loaded chunk is transformed with: its locale, plus
34
+ * `metadataOnly` when the read requests metadata. The other selector dimensions
35
+ * were already applied by picking the chunk.
36
+ *
37
+ * @param locale - The read's locale; `undefined` lets the binding's
38
+ * `useDictionary` follow its context locale.
39
+ * @param selector - The read's selector, if any.
40
+ */
41
+ const getDynamicChunkArgument = (locale, selector) => process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && selector?.metadataOnly ? {
42
+ locale,
43
+ metadataOnly: true
44
+ } : locale;
45
+ /**
46
+ * Collects the chunks a read targets. A plain map serves the locale through
47
+ * the same fallback chain as static mode, from its preload when it holds one.
48
+ */
49
+ const collectDynamicChunks = (loaderMap, key, locale, selector) => {
50
+ if (process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && isQualifiedDynamicLoaderMap(loaderMap)) return collectQualifiedChunks(loaderMap, key, locale, selector);
51
+ const resolvedLoader = findPlainDynamicLoader(loaderMap, locale);
52
+ if (!resolvedLoader) return {
53
+ itemAxisOpen: false,
54
+ missed: true,
55
+ chunks: []
56
+ };
57
+ return {
58
+ itemAxisOpen: false,
59
+ missed: false,
60
+ chunks: [{
61
+ cacheKey: `${key}.${resolvedLoader.locale}`,
62
+ loader: resolvedLoader.loader,
63
+ preloaded: getPreloadedDictionary(loaderMap, resolvedLoader.locale)
64
+ }]
65
+ };
66
+ };
67
+ /** Turns the loaded chunks of a read into its content. */
68
+ const readLoadedChunks = (params, collected, dictionaries) => {
69
+ const { loaderMap, locale, selector, transform } = params;
70
+ if (process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" && collected.readsMetadataIndex) return readMetadataIndex(dictionaries[0], loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY], selector);
71
+ const argument = getDynamicChunkArgument(locale, selector);
72
+ const read = (dictionary) => transform(dictionary, argument);
73
+ if (collected.itemAxisOpen) return dictionaries.map(read);
74
+ const [dictionary] = dictionaries;
75
+ return dictionary ? read(dictionary) : null;
76
+ };
77
+ /** Content of a read whose coordinate is absent: no item, or no entry. */
78
+ const getMissedContent = (collected) => collected.itemAxisOpen ? [] : null;
79
+ /**
80
+ * Lists the chunks a read targets without loading them — lets a binding warm
81
+ * its chunk cache ahead of render.
82
+ *
83
+ * @returns The targeted chunks, empty when a required coordinate is absent.
84
+ */
85
+ const getDynamicChunks = (loaderMap, key, locale, selector) => {
86
+ const { missed, chunks } = collectDynamicChunks(loaderMap, key, locale, selector);
87
+ return missed ? [] : chunks;
88
+ };
89
+ /**
90
+ * Loads the raw chunk a plain loader map serves for a locale — same fallback
91
+ * chain and preload as every other dynamic read — for the `useDictionaryAsync`
92
+ * bindings, which interpret it with their own `useDictionary`.
93
+ *
94
+ * @returns The chunk, or `undefined` when the map holds none for the locale
95
+ * nor for any of its fallbacks.
96
+ */
97
+ const loadDynamicDictionary = async (loaderMap, locale) => {
98
+ const [chunk] = getDynamicChunks(loaderMap, "", locale, void 0);
99
+ if (!chunk) return void 0;
100
+ return chunk.preloaded ?? await chunk.loader();
101
+ };
102
+ /**
103
+ * Resolves a dynamic read synchronously, loading only the chunk(s) it targets
104
+ * through `loadChunk` — a suspender cache that throws while a chunk is pending.
105
+ *
106
+ * Every pending loader is started before the first chunk is read, so sibling
107
+ * chunks load in parallel rather than waterfalling. Preloaded chunks are read
108
+ * directly, never through `loadChunk`, which would suspend for one microtask.
109
+ *
110
+ * @param params.loadChunk - Reads a started chunk, suspending until it resolves.
111
+ */
112
+ const resolveDynamicContent = (params) => {
113
+ const { loaderMap, key, locale, selector, loadChunk } = params;
114
+ const collected = collectDynamicChunks(loaderMap, key, locale, selector);
115
+ if (collected.missed) return getMissedContent(collected);
116
+ const dictionaries = collected.chunks.map((chunk) => ({
117
+ chunk,
118
+ promise: chunk.preloaded ? void 0 : chunk.loader()
119
+ })).map(({ chunk, promise }) => chunk.preloaded ?? loadChunk(chunk.cacheKey, promise));
120
+ return readLoadedChunks(params, collected, dictionaries);
121
+ };
122
+ /**
123
+ * Resolves a dynamic read, awaiting only the chunk(s) it targets.
124
+ */
125
+ const resolveDynamicContentAsync = async (params) => {
126
+ const { loaderMap, key, locale, selector } = params;
127
+ const collected = collectDynamicChunks(loaderMap, key, locale, selector);
128
+ if (collected.missed) return getMissedContent(collected);
129
+ const dictionaries = await Promise.all(collected.chunks.map((chunk) => chunk.preloaded ?? chunk.loader()));
130
+ return readLoadedChunks(params, collected, dictionaries);
131
+ };
132
+ /**
133
+ * Creates the content cache of a binding. Entries are kept per loader map, so
134
+ * a hot-reloaded entry point (a new map object) never serves stale content.
135
+ *
136
+ * @param transform - The binding's `getDictionary`, applied to every chunk.
137
+ */
138
+ const createDynamicContentStore = (transform) => {
139
+ const entriesByLoaderMap = /* @__PURE__ */ new WeakMap();
140
+ const getReadId = ({ locale, selector }) => process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? `${locale}|${getDictionarySelectorCacheKey(selector)}` : locale;
141
+ const peek = (read) => {
142
+ const settled = entriesByLoaderMap.get(read.loaderMap)?.get(getReadId(read))?.settled;
143
+ if (settled) return settled;
144
+ const collected = collectDynamicChunks(read.loaderMap, read.key, read.locale, read.selector);
145
+ if (collected.missed) return { content: getMissedContent(collected) };
146
+ if (!collected.chunks.every((chunk) => chunk.preloaded)) return void 0;
147
+ return { content: readLoadedChunks({
148
+ ...read,
149
+ transform
150
+ }, collected, collected.chunks.map((chunk) => chunk.preloaded)) };
151
+ };
152
+ const load = (read) => {
153
+ const entries = entriesByLoaderMap.get(read.loaderMap) ?? /* @__PURE__ */ new Map();
154
+ entriesByLoaderMap.set(read.loaderMap, entries);
155
+ const readId = getReadId(read);
156
+ const existingEntry = entries.get(readId);
157
+ if (existingEntry) return existingEntry.promise;
158
+ const entry = { promise: resolveDynamicContentAsync({
159
+ ...read,
160
+ transform
161
+ }) };
162
+ entries.set(readId, entry);
163
+ entry.promise.then((content) => {
164
+ entry.settled = { content };
165
+ }, () => entries.delete(readId));
166
+ return entry.promise;
167
+ };
168
+ const createReader = (loaderMap, dictionaryKey) => {
169
+ let latestRead;
170
+ return (context, onLoad, onError) => {
171
+ const read = {
172
+ loaderMap,
173
+ key: dictionaryKey,
174
+ ...resolveDictionaryRead({
175
+ ...context,
176
+ dictionaryKey
177
+ })
178
+ };
179
+ latestRead = read;
180
+ const settled = peek(read);
181
+ if (settled) return settled;
182
+ load(read).then((content) => {
183
+ if (latestRead === read) onLoad(content);
184
+ }, (error) => {
185
+ if (latestRead !== read) return;
186
+ if (!onError) throw error;
187
+ onError(error);
188
+ });
189
+ };
190
+ };
191
+ return {
192
+ peek,
193
+ load,
194
+ createReader
195
+ };
196
+ };
197
+ /**
198
+ * Inert stand-in for content still loading: any property access, call or
199
+ * construction returns it again, and string coercion yields `''`. It never
200
+ * passes for a thenable, an iterable, a DOM node or a Lit template part, so
201
+ * renderers print nothing instead of crashing.
202
+ */
203
+ const loadingContentPlaceholder = /* @__PURE__ */ new Proxy(function loadingContent() {}, {
204
+ get: (_target, property) => {
205
+ if (property === Symbol.toPrimitive || property === "toString" || property === "valueOf") return () => "";
206
+ if (property === "then" || property === "nodeType" || property === Symbol.iterator || typeof property === "string" && property.startsWith("_$")) return;
207
+ return loadingContentPlaceholder;
208
+ },
209
+ apply: () => loadingContentPlaceholder,
210
+ construct: () => ({})
211
+ });
212
+ const createSuspenseEntry = (promise) => {
213
+ let status = "pending";
214
+ let result;
215
+ const settled = promise.then((value) => {
216
+ status = "success";
217
+ result = value;
218
+ }, (error) => {
219
+ status = "error";
220
+ result = error;
221
+ });
222
+ return {
223
+ settled,
224
+ read: () => {
225
+ if (status === "pending") throw settled;
226
+ if (status === "error") throw result;
227
+ return result;
228
+ }
229
+ };
230
+ };
231
+ /**
232
+ * Creates the chunk cache of a Suspense binding (React, Preact): the
233
+ * `loadChunk` of {@link resolveDynamicContent}.
234
+ */
235
+ const createChunkSuspenseCache = () => {
236
+ const entries = /* @__PURE__ */ new Map();
237
+ const getEntry = (cacheKey, start) => {
238
+ const existingEntry = entries.get(cacheKey);
239
+ if (existingEntry) return existingEntry;
240
+ const entry = createSuspenseEntry(start());
241
+ entries.set(cacheKey, entry);
242
+ return entry;
243
+ };
244
+ return {
245
+ has: (cacheKey) => entries.has(cacheKey),
246
+ read: (cacheKey, promise) => getEntry(cacheKey, () => promise).read(),
247
+ preload: (cacheKey, loader) => getEntry(cacheKey, loader).settled
248
+ };
249
+ };
250
+
251
+ export { createChunkSuspenseCache, createDynamicContentStore, getDynamicChunkArgument, getDynamicChunks, loadDynamicDictionary, loadingContentPlaceholder, resolveDictionaryRead, resolveDynamicContent, resolveDynamicContentAsync };
252
+ //# sourceMappingURL=dynamicDictionary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dynamicDictionary.mjs","names":[],"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,UACzC,wBACE,0BAA0B;EAAE,GAAG;EAAQ;CAAiB,CAAC,CAC3D,IACA;EACE,QACG,oBACD,OAAO;EACT,UAAU;CACZ;CAEN,OAAO;EAAE,QAAQ,yBAAyB,MAAM;EAAG;CAAS;AAC9D;;;;;;;;;;AAWA,MAAa,2BAGX,QACA,aAEA,QAAQ,IAAI,iCAAiC,WAAW,UAAU,eAC9D;CAAU;CAAwC,cAAc;AAAK,IACrE;;;;;AAMN,MAAM,wBACJ,WACA,KACA,QACA,aACoB;CACpB,IACE,QAAQ,IAAI,iCAAiC,WAC7C,4BAA4B,SAAS,GAErC,OAAO,uBAAuB,WAAW,KAAK,QAAQ,QAAQ;CAGhE,MAAM,iBAAiB,uBACrB,WACA,MACF;CAEA,IAAI,CAAC,gBAAgB,OAAO;EAAE,cAAc;EAAO,QAAQ;EAAM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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,22 @@
1
+ import * as NodeTypes from "@intlayer/types/nodeType";
2
+
3
+ // src/dictionaryManipulator/getLocalizedMetadata.ts
4
+ /**
5
+ * Returns the metadata of a dictionary for a locale. The build merges
6
+ * per-locale declarations under a translation node (`t({ en: {…}, fr: {…} })`),
7
+ * read for `locale`, else `fallbackLocale`; any other metadata applies to
8
+ * every locale.
9
+ *
10
+ * @param metadata - The `metadata` of a dictionary or of a collection entry.
11
+ * @param locale - The locale to read.
12
+ * @param fallbackLocale - The locale read when `locale` declares none.
13
+ */
14
+ const getLocalizedMetadata = (metadata, locale, fallbackLocale) => {
15
+ const perLocaleMetadata = metadata;
16
+ if (perLocaleMetadata?.nodeType !== NodeTypes.TRANSLATION) return metadata ?? {};
17
+ const translations = perLocaleMetadata[NodeTypes.TRANSLATION] ?? {};
18
+ return translations[locale] ?? (fallbackLocale === void 0 ? void 0 : translations[fallbackLocale]) ?? {};
19
+ };
20
+
21
+ export { getLocalizedMetadata };
22
+ //# sourceMappingURL=getLocalizedMetadata.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getLocalizedMetadata.mjs","names":[],"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,aAAa,UAAU,aAC5C,OAAQ,YAAY,CAAC;CAGvB,MAAM,eAAe,kBAAkB,UAAU,gBAAgB,CAAC;CAElE,OACE,aAAa,YACZ,mBAAmB,SAAY,SAAY,aAAa,oBACzD,CAAC;AAEL"}
@@ -1,7 +1,9 @@
1
+ import { createChunkSuspenseCache, createDynamicContentStore, getDynamicChunkArgument, getDynamicChunks, loadDynamicDictionary, loadingContentPlaceholder, resolveDictionaryRead, resolveDynamicContent, resolveDynamicContentAsync } from "./dynamicDictionary.mjs";
1
2
  import { editDictionaryByKeyPath } from "./editDictionaryByKeyPath.mjs";
2
3
  import { getContentNodeByKeyPath } from "./getContentNodeByKeyPath.mjs";
3
4
  import { getDefaultNode } from "./getDefaultNode.mjs";
4
5
  import { getEmptyNode } from "./getEmptyNode.mjs";
6
+ import { getLocalizedMetadata } from "./getLocalizedMetadata.mjs";
5
7
  import { getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences } from "./getNestedDictionaryReferences.mjs";
6
8
  import { getNodeChildren } from "./getNodeChildren.mjs";
7
9
  import { getNodeType } from "./getNodeType.mjs";
@@ -11,11 +13,11 @@ import { normalizeDictionaries, normalizeDictionary } from "./normalizeDictionar
11
13
  import { orderDictionaries } from "./orderDictionaries.mjs";
12
14
  import { findPlainDynamicLoader, resolvePlainDynamicLoader } from "./plainDynamicLoader.mjs";
13
15
  import { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary } from "./preloadedDynamicLoader.mjs";
14
- import { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, getDictionarySelectorCacheKey, isQualifiedDictionaryGroup, parseDictionarySelector, reconstructQualifiedEntry, resolveDictionaryArgument, resolveEffectiveVariantId, resolveProviderVariant, resolveQualifiedDictionary, serializeVariant, serializeVariantChain } from "./qualifiedDictionary.mjs";
15
- import { QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getVariantIds } from "./qualifiedDictionaryDeclaration.mjs";
16
- import { QUALIFIER_DYNAMIC_TYPES_KEY, getQualifiedDynamicChunks, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./qualifiedDynamicLoader.mjs";
16
+ import { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, compareItemIds, compareItemSegments, getDictionarySelectorCacheKey, isQualifiedDictionaryGroup, matchQualifiedEntryIds, parseDictionarySelector, parseItemId, parseItemSegment, reconstructQualifiedEntry, resolveDictionaryArgument, resolveEffectiveVariantId, resolveProviderVariant, resolveQualifiedDictionary, serializeItem, serializeVariant, serializeVariantChain } from "./qualifiedDictionary.mjs";
17
+ import { QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getVariantIds, isDeclaredItem } from "./qualifiedDictionaryDeclaration.mjs";
18
+ import { QUALIFIER_DYNAMIC_METADATA_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, collectQualifiedChunks, isQualifiedDynamicLoaderMap, readMetadataIndex } from "./qualifiedDynamicLoader.mjs";
17
19
  import { removeContentNodeByKeyPath } from "./removeContentNodeByKeyPath.mjs";
18
20
  import { renameContentNodeByKeyPath } from "./renameContentNodeByKeyPath.mjs";
19
21
  import { updateNodeChildren } from "./updateNodeChildren.mjs";
20
22
 
21
- export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, findPlainDynamicLoader, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getPreloadedDictionary, getQualifiedDynamicChunks, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveEffectiveVariantId, resolvePlainDynamicLoader, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
23
+ export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_METADATA_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, collectQualifiedChunks, compareItemIds, compareItemSegments, createChunkSuspenseCache, createDynamicContentStore, editDictionaryByKeyPath, findPlainDynamicLoader, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDynamicChunkArgument, getDynamicChunks, getEmptyNode, getLocalizedMetadata, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getPreloadedDictionary, getVariantIds, isDeclaredItem, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, loadDynamicDictionary, loadingContentPlaceholder, matchQualifiedEntryIds, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, parseItemId, parseItemSegment, readMetadataIndex, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveDictionaryRead, resolveDynamicContent, resolveDynamicContentAsync, resolveEffectiveVariantId, resolvePlainDynamicLoader, resolveProviderVariant, resolveQualifiedDictionary, serializeItem, serializeVariant, serializeVariantChain, updateNodeChildren };
@@ -52,16 +52,19 @@ const mergeDictionaries = (dictionaries) => {
52
52
  const dictionariesKeys = dictionaries.map((dict) => dict.key);
53
53
  if (new Set(dictionariesKeys).size !== 1) throw new Error("All dictionaries must have the same key");
54
54
  let mergedContent = dictionaries[0].content;
55
+ let mergedMetadata = dictionaries[0].metadata;
55
56
  for (let i = 1; i < dictionaries.length; i++) {
56
57
  const dict = dictionaries[i];
57
58
  if (!dict) continue;
58
59
  const currentDictionary = getMultilingualDictionary(dict);
59
60
  checkTypesMatch(mergedContent, currentDictionary.content, currentDictionary.localId, currentDictionary.key, []);
60
61
  mergedContent = customMerge(mergedContent, currentDictionary.content);
62
+ if (currentDictionary.metadata !== void 0) mergedMetadata = mergedMetadata === void 0 ? currentDictionary.metadata : customMerge(mergedMetadata, currentDictionary.metadata);
61
63
  }
62
64
  return {
63
65
  key: dictionaries[0].key,
64
66
  content: mergedContent,
67
+ ...mergedMetadata !== void 0 && { metadata: mergedMetadata },
65
68
  localIds
66
69
  };
67
70
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mergeDictionaries.mjs","names":[],"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 };\n\n return mergedDictionary;\n};\n"],"mappings":";;;;;;AAaA,MAAM,mBACJ,SACA,SACA,gBACA,eACA,OAAiB,CAAC,MACT;CACT,MAAM,YAAY,aAAa,EAAE,IAAI,CAAC;CAGtC,IACE,YAAY,UACZ,YAAY,QACZ,YAAY,UACZ,YAAY,MAEZ;CAEF,MAAM,QAAQ,YAAY,OAAO;CACjC,MAAM,QAAQ,YAAY,OAAO;CAGjC,IAAI,UAAU,aAAa,UAAU,WAAW;CAEhD,IAAI,UAAU,OAAO;EACnB,UACE,CACE,q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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;CAE3D,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;EAC5C,MAAM,OAAO,aAAa;EAE1B,IAAI,CAAC,MAAM;EAGX,MAAM,oBAAoB,0BAA0B,IAAI;EAGxD,gBACE,eACA,kBAAkB,SAClB,kBAAkB,SAClB,kBAAkB,KAClB,CAAC,CACH;EAEA,gBAAgB,YACd,eACA,kBAAkB,OACpB;CACF;CAQA,OAAO;EALL,KAAK,aAAa,EAAE,CAAC;EACrB,SAAS;EACT;CAGoB;AACxB"}
1
+ {"version":3,"file":"mergeDictionaries.mjs","names":[],"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,YAAY,aAAa,EAAE,IAAI,CAAC;CAGtC,IACE,YAAY,UACZ,YAAY,QACZ,YAAY,UACZ,YAAY,MAEZ;CAEF,MAAM,QAAQ,YAAY,OAAO;CACjC,MAAM,QAAQ,YAAY,OAAO;CAGjC,IAAI,UAAU,aAAa,UAAU,WAAW;CAEhD,IAAI,UAAU,OAAO;EACnB,UACE,CACE,qBAAqB,YAAY,aAAa,EAAE,4DAA4D,KAAK,KAAK,GAAG,EAAE,kBAAkB,MAAM,QAAQ,MAAM,iBAAiB,gBACpL,GACA,EACE,OAAO,QACT,CACF;EAEA;CACF;AACF;AAGA,MAAM,eACJ,aACA,WACqB;CAErB,IAAI,gBAAgB,UAAa,gBAAgB,MAC/C,OAAO;CAIT,IAAI,W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AAO;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,oBAAoB,0BAA0B,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"}
@@ -50,6 +50,7 @@ const mergeQualifiedDictionaries = (dictionaries) => {
50
50
  });
51
51
  if (groupQualifierTypes.length === 1 && groupQualifierTypes[0] === "variant" && baseDictionaries.length > 0 && !entriesDictionaries.has("default")) entriesDictionaries.set(DEFAULT_VARIANT_ID, []);
52
52
  const content = {};
53
+ const metadata = {};
53
54
  let importMode;
54
55
  const variantIndex = groupQualifierTypes.indexOf("variant");
55
56
  /**
@@ -67,11 +68,13 @@ const mergeQualifiedDictionaries = (dictionaries) => {
67
68
  for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {
68
69
  const inheritedEntryId = getInheritedEntryId(compositeId);
69
70
  const inheritedDictionaries = inheritedEntryId ? entriesDictionaries.get(inheritedEntryId) ?? [] : [];
70
- content[compositeId] = mergeDictionaries([
71
+ const mergedEntry = mergeDictionaries([
71
72
  ...qualifiedDictionaries,
72
73
  ...inheritedDictionaries,
73
74
  ...baseDictionaries
74
- ]).content;
75
+ ]);
76
+ content[compositeId] = mergedEntry.content;
77
+ if (mergedEntry.metadata !== void 0) metadata[compositeId] = mergedEntry.metadata;
75
78
  const [firstQualified] = qualifiedDictionaries;
76
79
  importMode ??= firstQualified?.importMode;
77
80
  }
@@ -80,6 +83,7 @@ const mergeQualifiedDictionaries = (dictionaries) => {
80
83
  key: dictionaries[0].key,
81
84
  qualifierTypes: groupQualifierTypes,
82
85
  content,
86
+ ...Object.keys(metadata).length > 0 && { metadata },
83
87
  ...importMode !== void 0 && { importMode },
84
88
  localIds
85
89
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mergeQualifiedDictionaries.mjs","names":[],"sources":["../../../src/dictionaryManipulator/mergeQualifiedDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport { mergeDictionaries } from './mergeDictionaries';\nimport {\n COMPOSITE_ID_SEPARATOR,\n DEFAULT_VARIANT_ID,\n} from './qualifiedDictionary';\nimport {\n getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionaryDeclaration';\n\n/**\n * Merges sibling dictionaries sharing the same key, honouring qualifiers.\n *\n * - No dictionary declares a qualifier → behaves exactly like\n * `mergeDictionaries` (single merged dictionary).\n * - At least one dictionary declares a qualifier → the group's dimension set is\n * the union of every declared dimension (in canonical order\n * `variant → item`). Dictionaries are grouped by their composite id\n * (one segment per dimension), merged within each group (locale completion /\n * priority overrides preserved), and a `QualifiedDictionaryGroup` is returned.\n * Unqualified siblings act as shared base content merged into every entry —\n * and, on a variant-only key, also materialize the `default` entry when no\n * declaration claims it. Every other variant entry then inherits from that\n * `default` entry, so a variant only declares the fields it overrides.\n *\n * Every qualified entry must declare ALL dimensions of the group; an entry that\n * declares only a subset is ambiguous and is rejected with an error log.\n */\nexport const mergeQualifiedDictionaries = (\n dictionaries: Dictionary[]\n): Dictionary | QualifiedDictionaryGroup => {\n const perDictionaryTypes = dictionaries.map(getDictionaryQualifierTypes);\n\n const declaredDimensions = new Set<DictionaryQualifierType>();\n for (const types of perDictionaryTypes) {\n for (const type of types) declaredDimensions.add(type);\n }\n\n // Canonical order, restricted to the dimensions actually declared.\n const groupQualifierTypes = QUALIFIER_ORDER.filter((qualifierType) =>\n declaredDimensions.has(qualifierType)\n );\n\n if (groupQualifierTypes.length === 0) {\n return mergeDictionaries(dictionaries);\n }\n\n const appLogger = getAppLogger({ log });\n\n const baseDictionaries: Dictionary[] = [];\n const entriesDictionaries = new Map<string, Dictionary[]>();\n\n dictionaries.forEach((dictionary, index) => {\n if (perDictionaryTypes[index]?.length === 0) {\n baseDictionaries.push(dictionary);\n return;\n }\n\n // A dictionary may map to several composite ids (array variant fan-out):\n // its content is registered under every id it lists.\n const compositeIds = getDictionaryCompositeIds(\n dictionary,\n groupQualifierTypes\n );\n\n if (compositeIds === undefined) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} declares (${perDictionaryTypes[index].join(', ')}) but the key's dimensions are (${groupQualifierTypes.join(', ')}); every entry must declare all of them. Entry ignored${dictionary.filePath ? ` - ${dictionary.filePath}` : ''}.`,\n { level: 'error' }\n );\n return;\n }\n\n for (const compositeId of compositeIds) {\n const existingEntries = entriesDictionaries.get(compositeId) ?? [];\n existingEntries.push(dictionary);\n entriesDictionaries.set(compositeId, existingEntries);\n }\n });\n\n // Unqualified siblings are the key's base content. On a variant key they also\n // materialize the `default` entry when no declaration claims it, so the key\n // still resolves when no variant is selected — and so variants that declare\n // no entry of their own can fall back to it. Registering an empty entry list\n // is enough: the merge loop below appends the base dictionaries to it.\n //\n // Composite (variant × item) keys are excluded: base content carries no item\n // index, so it cannot be placed on the collection axis.\n const isVariantOnlyGroup =\n groupQualifierTypes.length === 1 && groupQualifierTypes[0] === 'variant';\n\n if (\n isVariantOnlyGroup &&\n baseDictionaries.length > 0 &&\n !entriesDictionaries.has(DEFAULT_VARIANT_ID)\n ) {\n entriesDictionaries.set(DEFAULT_VARIANT_ID, []);\n }\n\n // `content` maps each composite id to its resolved content node directly; the\n // qualifier coordinates live in the key, not in a per-entry wrapper. For an\n // object variant the variant segment is the canonical serialization of the\n // object, so it fully identifies the entry — no side-map is needed.\n const content: Record<string, unknown> = {};\n\n let importMode: Dictionary['importMode'];\n\n const variantIndex = groupQualifierTypes.indexOf('variant');\n\n /**\n * The id of the entry a composite id inherits from — itself with its variant\n * segment swapped for `default` (`'promo/2'` → `'default/2'`). `undefined`\n * for the default entries themselves and for keys with no variant dimension.\n */\n const getInheritedEntryId = (compositeId: string): string | undefined => {\n if (variantIndex === -1) return undefined;\n\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n if (segments[variantIndex] === DEFAULT_VARIANT_ID) return undefined;\n\n segments[variantIndex] = DEFAULT_VARIANT_ID;\n return segments.join(COMPOSITE_ID_SEPARATOR);\n };\n\n for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n // Precedence, highest first: the entry's own declarations, then the\n // `default` variant it inherits from, then the unqualified siblings shared\n // by the whole key (mergeDictionaries prefers the first occurrence).\n //\n // Inheriting from `default` is what makes a variant declaration partial: it\n // only has to declare the fields whose wording actually differs, and every\n // other field is completed from the default entry.\n const inheritedEntryId = getInheritedEntryId(compositeId);\n const inheritedDictionaries = inheritedEntryId\n ? (entriesDictionaries.get(inheritedEntryId) ?? [])\n : [];\n\n const mergedEntry = mergeDictionaries([\n ...qualifiedDictionaries,\n ...inheritedDictionaries,\n ...baseDictionaries,\n ]);\n\n content[compositeId] = mergedEntry.content;\n\n const [firstQualified] = qualifiedDictionaries;\n\n importMode ??= firstQualified?.importMode;\n }\n\n const localIds = Array.from(\n new Set(\n dictionaries\n .filter((dictionary) => dictionary.localId)\n .map((dictionary) => dictionary.localId!)\n )\n );\n\n return {\n key: dictionaries[0]!.key,\n qualifierTypes: groupQualifierTypes,\n content,\n ...(importMode !== undefined && { importMode }),\n localIds,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAI,2BAA2B;CAEvE,MAAM,qCAAqB,IAAI,IAA6B;CAC5D,KAAK,MAAM,SAAS,oBAClB,KAAK,MAAM,QAAQ,OAAO,mBAAmB,IAAI,IAAI;CAIvD,MAAM,sBAAsB,gBAAgB,QAAQ,kBAClD,mBAAmB,IAAI,aAAa,CACtC;CAEA,IAAI,oBAAoB,WAAW,GACjC,OAAO,kBAAkB,YAAY;CAGvC,MAAM,YAAY,aAAa,EAAE,IAAI,CAAC;CAEtC,MAAM,mBAAiC,CAAC;CACxC,MAAM,sCAAsB,IAAI,IAA0B;CAE1D,aAAa,SAAS,YAAY,UAAU;EAC1C,IAAI,mBAAmB,MAAM,EAAE,WAAW,GAAG;GAC3C,iBAAiB,KAAK,UAAU;GAChC;EACF;EAIA,MAAM,eAAe,0BACnB,YACA,mBACF;EAEA,IAAI,iBAAiB,QAAW;GAC9B,UACE,cAAc,YAAY,WAAW,GAAG,EAAE,aAAa,mBAAmB,MAAM,CAAC,KAAK,IAAI,EAAE,kCAAkC,oBAAoB,KAAK,IAAI,EAAE,wDAAwD,WAAW,WAAW,MAAM,WAAW,aAAa,GAAG,IAC5Q,EAAE,OAAO,QAAQ,CACnB;GACA;EACF;EAEA,KAAK,MAAM,eAAe,cAAc;GACtC,MAAM,kBAAkB,oBAAoB,IAAI,WAAW,KAAK,CAAC;GACjE,gBAAgB,KAAK,UAAU;GAC/B,oBAAoB,IAAI,aAAa,eAAe;EACtD;CACF,CAAC;CAaD,IAFE,oBAAoB,WAAW,KAAK,oBAAoB,OAAO,aAI/D,iBAAiB,SAAS,KAC1B,CAAC,oBAAoB,aAAsB,GAE3C,oBAAoB,IAAI,oBAAoB,CAAC,CAAC;CAOhD,MAAM,UAAmC,CAAC;CAE1C,IAAI;CAEJ,MAAM,eAAe,oBAAoB,QAAQ,SAAS;;;;;;CAO1D,MAAM,uBAAuB,gBAA4C;EACvE,IAAI,iBAAiB,IAAI,OAAO;EAEhC,MAAM,WAAW,YAAY,SAA4B;EACzD,IAAI,SAAS,6BAAsC,OAAO;EAE1D,SAAS,gBAAgB;EACzB,OAAO,SAAS,QAA2B;CAC7C;CAEA,KAAK,MAAM,CAAC,aAAa,0BAA0B,qBAAqB;EAQtE,MAAM,mBAAmB,oBAAoB,WAAW;EACxD,MAAM,wBAAwB,mBACzB,oBAAoB,IAAI,gBAAgB,KAAK,CAAC,IAC/C,CAAC;EAQL,QAAQ,eANY,kBAAkB;GACpC,GAAG;GACH,GAAG;GACH,GAAG;EACL,CAEiC,CAAC,CAAC;EAEnC,MAAM,CAAC,kBAAkB;EAEzB,eAAe,gBAAgB;CACjC;CAEA,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aACG,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,eAAe,WAAW,OAAQ,CAC5C,CACF;CAEA,OAAO;EACL,KAAK,aAAa,EAAE,CAAE;EACtB,gBAAgB;EAChB;EACA,GAAI,eAAe,UAAa,EAAE,WAAW;EAC7C;CACF;AACF"}
1
+ {"version":3,"file":"mergeQualifiedDictionaries.mjs","names":[],"sources":["../../../src/dictionaryManipulator/mergeQualifiedDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport { mergeDictionaries } from './mergeDictionaries';\nimport {\n COMPOSITE_ID_SEPARATOR,\n DEFAULT_VARIANT_ID,\n} from './qualifiedDictionary';\nimport {\n getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionaryDeclaration';\n\n/**\n * Merges sibling dictionaries sharing the same key, honouring qualifiers.\n *\n * - No dictionary declares a qualifier → behaves exactly like\n * `mergeDictionaries` (single merged dictionary).\n * - At least one dictionary declares a qualifier → the group's dimension set is\n * the union of every declared dimension (in canonical order\n * `variant → item`). Dictionaries are grouped by their composite id\n * (one segment per dimension), merged within each group (locale completion /\n * priority overrides preserved), and a `QualifiedDictionaryGroup` is returned.\n * Unqualified siblings act as shared base content merged into every entry —\n * and, on a variant-only key, also materialize the `default` entry when no\n * declaration claims it. Every other variant entry then inherits from that\n * `default` entry, so a variant only declares the fields it overrides.\n *\n * Every qualified entry must declare ALL dimensions of the group; an entry that\n * declares only a subset is ambiguous and is rejected with an error log.\n */\nexport const mergeQualifiedDictionaries = (\n dictionaries: Dictionary[]\n): Dictionary | QualifiedDictionaryGroup => {\n const perDictionaryTypes = dictionaries.map(getDictionaryQualifierTypes);\n\n const declaredDimensions = new Set<DictionaryQualifierType>();\n for (const types of perDictionaryTypes) {\n for (const type of types) declaredDimensions.add(type);\n }\n\n // Canonical order, restricted to the dimensions actually declared.\n const groupQualifierTypes = QUALIFIER_ORDER.filter((qualifierType) =>\n declaredDimensions.has(qualifierType)\n );\n\n if (groupQualifierTypes.length === 0) {\n return mergeDictionaries(dictionaries);\n }\n\n const appLogger = getAppLogger({ log });\n\n const baseDictionaries: Dictionary[] = [];\n const entriesDictionaries = new Map<string, Dictionary[]>();\n\n dictionaries.forEach((dictionary, index) => {\n if (perDictionaryTypes[index]?.length === 0) {\n baseDictionaries.push(dictionary);\n return;\n }\n\n // A dictionary may map to several composite ids (array variant fan-out):\n // its content is registered under every id it lists.\n const compositeIds = getDictionaryCompositeIds(\n dictionary,\n groupQualifierTypes\n );\n\n if (compositeIds === undefined) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} declares (${perDictionaryTypes[index].join(', ')}) but the key's dimensions are (${groupQualifierTypes.join(', ')}); every entry must declare all of them. Entry ignored${dictionary.filePath ? ` - ${dictionary.filePath}` : ''}.`,\n { level: 'error' }\n );\n return;\n }\n\n for (const compositeId of compositeIds) {\n const existingEntries = entriesDictionaries.get(compositeId) ?? [];\n existingEntries.push(dictionary);\n entriesDictionaries.set(compositeId, existingEntries);\n }\n });\n\n // Unqualified siblings are the key's base content. On a variant key they also\n // materialize the `default` entry when no declaration claims it, so the key\n // still resolves when no variant is selected — and so variants that declare\n // no entry of their own can fall back to it. Registering an empty entry list\n // is enough: the merge loop below appends the base dictionaries to it.\n //\n // Composite (variant × item) keys are excluded: base content carries no item\n // index, so it cannot be placed on the collection axis.\n const isVariantOnlyGroup =\n groupQualifierTypes.length === 1 && groupQualifierTypes[0] === 'variant';\n\n if (\n isVariantOnlyGroup &&\n baseDictionaries.length > 0 &&\n !entriesDictionaries.has(DEFAULT_VARIANT_ID)\n ) {\n entriesDictionaries.set(DEFAULT_VARIANT_ID, []);\n }\n\n // `content` maps each composite id to its resolved content node directly; the\n // qualifier coordinates live in the key, not in a per-entry wrapper. For an\n // object variant the variant segment is the canonical serialization of the\n // object, so it fully identifies the entry — no side-map is needed.\n const content: Record<string, unknown> = {};\n const metadata: Record<string, unknown> = {};\n\n let importMode: Dictionary['importMode'];\n\n const variantIndex = groupQualifierTypes.indexOf('variant');\n\n /**\n * The id of the entry a composite id inherits from — itself with its variant\n * segment swapped for `default` (`'promo/2'` → `'default/2'`). `undefined`\n * for the default entries themselves and for keys with no variant dimension.\n */\n const getInheritedEntryId = (compositeId: string): string | undefined => {\n if (variantIndex === -1) return undefined;\n\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n if (segments[variantIndex] === DEFAULT_VARIANT_ID) return undefined;\n\n segments[variantIndex] = DEFAULT_VARIANT_ID;\n return segments.join(COMPOSITE_ID_SEPARATOR);\n };\n\n for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n // Precedence, highest first: the entry's own declarations, then the\n // `default` variant it inherits from, then the unqualified siblings shared\n // by the whole key (mergeDictionaries prefers the first occurrence).\n //\n // Inheriting from `default` is what makes a variant declaration partial: it\n // only has to declare the fields whose wording actually differs, and every\n // other field is completed from the default entry.\n const inheritedEntryId = getInheritedEntryId(compositeId);\n const inheritedDictionaries = inheritedEntryId\n ? (entriesDictionaries.get(inheritedEntryId) ?? [])\n : [];\n\n const mergedEntry = mergeDictionaries([\n ...qualifiedDictionaries,\n ...inheritedDictionaries,\n ...baseDictionaries,\n ]);\n\n content[compositeId] = mergedEntry.content;\n\n if (mergedEntry.metadata !== undefined) {\n metadata[compositeId] = mergedEntry.metadata;\n }\n\n const [firstQualified] = qualifiedDictionaries;\n\n importMode ??= firstQualified?.importMode;\n }\n\n const localIds = Array.from(\n new Set(\n dictionaries\n .filter((dictionary) => dictionary.localId)\n .map((dictionary) => dictionary.localId!)\n )\n );\n\n return {\n key: dictionaries[0]!.key,\n qualifierTypes: groupQualifierTypes,\n content,\n ...(Object.keys(metadata).length > 0 && { metadata }),\n ...(importMode !== undefined && { importMode }),\n localIds,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAI,2BAA2B;CAEvE,MAAM,qCAAqB,IAAI,IAA6B;CAC5D,KAAK,MAAM,SAAS,oBAClB,KAAK,MAAM,QAAQ,OAAO,mBAAmB,IAAI,IAAI;CAIvD,MAAM,sBAAsB,gBAAgB,QAAQ,kBAClD,mBAAmB,IAAI,aAAa,CACtC;CAEA,IAAI,oBAAoB,WAAW,GACjC,OAAO,kBAAkB,YAAY;CAGvC,MAAM,YAAY,aAAa,EAAE,IAAI,CAAC;CAEtC,MAAM,mBAAiC,CAAC;CACxC,MAAM,sCAAsB,I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Q,eAAe,YAAY;EAEnC,IAAI,YAAY,aAAa,QAC3B,SAAS,eAAe,YAAY;EAGtC,MAAM,CAAC,kBAAkB;EAEzB,eAAe,gBAAgB;CACjC;CAEA,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aACG,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,eAAe,WAAW,OAAQ,CAC5C,CACF;CAEA,OAAO;EACL,KAAK,aAAa,EAAE,CAAE;EACtB,gBAAgB;EAChB;EACA,GAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,KAAK,EAAE,SAAS;EACnD,GAAI,eAAe,UAAa,EAAE,WAAW;EAC7C;CACF;AACF"}
@@ -9,7 +9,8 @@ const normalizeDictionary = (dictionary, configuration) => {
9
9
  if (dictionary.locale) return {
10
10
  ...dictionary,
11
11
  locale: void 0,
12
- content: translation({ [dictionary.locale]: dictionary.content })
12
+ content: translation({ [dictionary.locale]: dictionary.content }),
13
+ ...dictionary.metadata !== void 0 && { metadata: translation({ [dictionary.locale]: dictionary.metadata }) }
13
14
  };
14
15
  const perLocaleContent = locales.reduce((acc, locale) => {
15
16
  acc[locale] = getPerLocaleDictionary(parsedDictionary, locale).content;
@@ -1 +1 @@
1
- {"version":3,"file":"normalizeDictionary.mjs","names":["t"],"sources":["../../../src/dictionaryManipulator/normalizeDictionary.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getPerLocaleDictionary } from '../deepTransformPlugins';\nimport { t } from '../transpiler/translation';\nimport { orderDictionaries } from './orderDictionaries';\n\nexport const normalizeDictionary = (\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Dictionary => {\n const { locales } = configuration.internationalization;\n\n const parsedDictionary = JSON.parse(JSON.stringify(dictionary));\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n if (dictionary.locale) {\n return {\n ...dictionary,\n locale: undefined,\n content: t({\n [dictionary.locale]: dictionary.content,\n }),\n };\n }\n\n const perLocaleContent = locales.reduce(\n (acc, locale) => {\n const perLocaleDictionary = getPerLocaleDictionary(\n parsedDictionary,\n locale\n );\n\n acc[locale] = perLocaleDictionary.content;\n return acc;\n },\n {} as Record<Locale, Dictionary['content']>\n );\n\n return {\n ...dictionary,\n content: t(perLocaleContent),\n };\n};\n\nexport const normalizeDictionaries = (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Dictionary[] => {\n const orderedDictionaries = orderDictionaries(dictionaries, configuration);\n\n const structuredDictionaries = orderedDictionaries.map((dictionary) =>\n normalizeDictionary(dictionary, configuration)\n );\n\n return structuredDictionaries;\n};\n"],"mappings":";;;;;AAOA,MAAa,uBACX,YACA,kBACe;CACf,MAAM,EAAE,YAAY,cAAc;CAElC,MAAM,mBAAmB,KAAK,MAAM,KAAK,UAAU,UAAU,CAAC;CAG9D,IAAI,WAAW,QACb,OAAO;EACL,GAAG;EACH,QAAQ;EACR,SAASA,YAAE,GACR,WAAW,SAAS,WAAW,QAClC,CAAC;CACH;CAGF,MAAM,mBAAmB,QAAQ,QAC9B,KAAK,WAAW;EAMf,IAAI,UALwB,uBAC1B,kBACA,MAG8B,CAAC,CAAC;EAClC,OAAO;CACT,GACA,CAAC,CACH;CAEA,OAAO;EACL,GAAG;EACH,SAASA,YAAE,gBAAgB;CAC7B;AACF;AAEA,MAAa,yBACX,cACA,kBACiB;CAOjB,OAN4B,kBAAkB,cAAc,aAEX,CAAC,CAAC,KAAK,eACtD,oBAAoB,YAAY,aAAa,CAGnB;AAC9B"}
1
+ {"version":3,"file":"normalizeDictionary.mjs","names":["t"],"sources":["../../../src/dictionaryManipulator/normalizeDictionary.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getPerLocaleDictionary } from '../deepTransformPlugins';\nimport { t } from '../transpiler/translation';\nimport { orderDictionaries } from './orderDictionaries';\n\nexport const normalizeDictionary = (\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Dictionary => {\n const { locales } = configuration.internationalization;\n\n const parsedDictionary = JSON.parse(JSON.stringify(dictionary));\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n if (dictionary.locale) {\n return {\n ...dictionary,\n locale: undefined,\n content: t({\n [dictionary.locale]: dictionary.content,\n }),\n // Merged with the other locales' metadata, like the content\n ...(dictionary.metadata !== undefined && {\n metadata: t({ [dictionary.locale]: dictionary.metadata }),\n }),\n };\n }\n\n const perLocaleContent = locales.reduce(\n (acc, locale) => {\n const perLocaleDictionary = getPerLocaleDictionary(\n parsedDictionary,\n locale\n );\n\n acc[locale] = perLocaleDictionary.content;\n return acc;\n },\n {} as Record<Locale, Dictionary['content']>\n );\n\n return {\n ...dictionary,\n content: t(perLocaleContent),\n };\n};\n\nexport const normalizeDictionaries = (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Dictionary[] => {\n const orderedDictionaries = orderDictionaries(dictionaries, configuration);\n\n const structuredDictionaries = orderedDictionaries.map((dictionary) =>\n normalizeDictionary(dictionary, configuration)\n );\n\n return structuredDictionaries;\n};\n"],"mappings":";;;;;AAOA,MAAa,uBACX,YACA,kBACe;CACf,MAAM,EAAE,YAAY,cAAc;CAElC,MAAM,mBAAmB,KAAK,MAAM,KAAK,UAAU,UAAU,CAAC;CAG9D,IAAI,WAAW,QACb,OAAO;EACL,GAAG;EACH,QAAQ;EACR,SAASA,YAAE,GACR,WAAW,SAAS,WAAW,QAClC,CAAC;EAED,GAAI,WAAW,aAAa,UAAa,EACvC,UAAUA,YAAE,GAAG,WAAW,SAAS,WAAW,SAAS,CAAC,EAC1D;CACF;CAGF,MAAM,mBAAmB,QAAQ,QAC9B,KAAK,WAAW;EAMf,IAAI,UALwB,uBAC1B,kBACA,MAG8B,CAAC,CAAC;EAClC,OAAO;CACT,GACA,CAAC,CACH;CAEA,OAAO;EACL,GAAG;EACH,SAASA,YAAE,gBAAgB;CAC7B;AACF;AAEA,MAAa,yBACX,cACA,kBACiB;CAOjB,OAN4B,kBAAkB,cAAc,aAEX,CAAC,CAAC,KAAK,eACtD,oBAAoB,YAAY,aAAa,CAGnB;AAC9B"}