@intlayer/core 9.0.0-canary.11 → 9.0.0-canary.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/dictionaryManipulator/index.cjs +3 -3
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +8 -6
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +81 -40
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +10 -3
- package/dist/cjs/localization/domainUtils.cjs +82 -0
- package/dist/cjs/localization/domainUtils.cjs.map +1 -0
- package/dist/cjs/localization/getLocalizedUrl.cjs +4 -11
- package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
- package/dist/cjs/localization/getPrefix.cjs +5 -9
- package/dist/cjs/localization/getPrefix.cjs.map +1 -1
- package/dist/cjs/localization/index.cjs +5 -0
- package/dist/cjs/messageFormat/index.cjs +2 -0
- package/dist/cjs/messageFormat/navigatePath.cjs +38 -0
- package/dist/cjs/messageFormat/navigatePath.cjs.map +1 -0
- package/dist/esm/dictionaryManipulator/index.mjs +2 -2
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs +9 -7
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs +79 -38
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +4 -2
- package/dist/esm/localization/domainUtils.mjs +77 -0
- package/dist/esm/localization/domainUtils.mjs.map +1 -0
- package/dist/esm/localization/getLocalizedUrl.mjs +4 -11
- package/dist/esm/localization/getLocalizedUrl.mjs.map +1 -1
- package/dist/esm/localization/getPrefix.mjs +5 -9
- package/dist/esm/localization/getPrefix.mjs.map +1 -1
- package/dist/esm/localization/index.mjs +2 -1
- package/dist/esm/messageFormat/index.mjs +2 -1
- package/dist/esm/messageFormat/navigatePath.mjs +36 -0
- package/dist/esm/messageFormat/navigatePath.mjs.map +1 -0
- package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +1 -1
- package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +1 -1
- package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +1 -1
- package/dist/types/dictionaryManipulator/index.d.ts +2 -2
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts +33 -22
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -2
- package/dist/types/localization/domainUtils.d.ts +70 -0
- package/dist/types/localization/domainUtils.d.ts.map +1 -0
- package/dist/types/localization/getLocalizedUrl.d.ts.map +1 -1
- package/dist/types/localization/getPrefix.d.ts.map +1 -1
- package/dist/types/localization/index.d.ts +2 -1
- package/dist/types/messageFormat/index.d.ts +2 -1
- package/dist/types/messageFormat/navigatePath.d.ts +22 -0
- package/dist/types/messageFormat/navigatePath.d.ts.map +1 -0
- package/package.json +6 -6
|
@@ -20,14 +20,14 @@ exports.QUALIFIER_ORDER = require_dictionaryManipulator_qualifiedDictionary.QUAL
|
|
|
20
20
|
exports.editDictionaryByKeyPath = require_dictionaryManipulator_editDictionaryByKeyPath.editDictionaryByKeyPath;
|
|
21
21
|
exports.getContentNodeByKeyPath = require_dictionaryManipulator_getContentNodeByKeyPath.getContentNodeByKeyPath;
|
|
22
22
|
exports.getDefaultNode = require_dictionaryManipulator_getDefaultNode.getDefaultNode;
|
|
23
|
-
exports.
|
|
24
|
-
exports.
|
|
25
|
-
exports.getDictionaryQualifierSegments = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierSegments;
|
|
23
|
+
exports.getDictionaryCompositeIds = require_dictionaryManipulator_qualifiedDictionary.getDictionaryCompositeIds;
|
|
24
|
+
exports.getDictionaryQualifierIds = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierIds;
|
|
26
25
|
exports.getDictionaryQualifierTypes = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierTypes;
|
|
27
26
|
exports.getDictionarySelectorCacheKey = require_dictionaryManipulator_qualifiedDictionary.getDictionarySelectorCacheKey;
|
|
28
27
|
exports.getEmptyNode = require_dictionaryManipulator_getEmptyNode.getEmptyNode;
|
|
29
28
|
exports.getNodeChildren = require_dictionaryManipulator_getNodeChildren.getNodeChildren;
|
|
30
29
|
exports.getNodeType = require_dictionaryManipulator_getNodeType.getNodeType;
|
|
30
|
+
exports.getVariantIds = require_dictionaryManipulator_qualifiedDictionary.getVariantIds;
|
|
31
31
|
exports.isQualifiedDictionaryGroup = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDictionaryGroup;
|
|
32
32
|
exports.isQualifiedDynamicLoaderMap = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDynamicLoaderMap;
|
|
33
33
|
exports.mergeDictionaries = require_dictionaryManipulator_mergeDictionaries.mergeDictionaries;
|
|
@@ -31,18 +31,20 @@ const mergeQualifiedDictionaries = (dictionaries) => {
|
|
|
31
31
|
const baseDictionaries = [];
|
|
32
32
|
const entriesDictionaries = /* @__PURE__ */ new Map();
|
|
33
33
|
dictionaries.forEach((dictionary, index) => {
|
|
34
|
-
if (perDictionaryTypes[index]
|
|
34
|
+
if (perDictionaryTypes[index]?.length === 0) {
|
|
35
35
|
baseDictionaries.push(dictionary);
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
38
|
+
const compositeIds = require_dictionaryManipulator_qualifiedDictionary.getDictionaryCompositeIds(dictionary, groupQualifierTypes);
|
|
39
|
+
if (compositeIds === void 0) {
|
|
40
40
|
appLogger(`Dictionary ${(0, _intlayer_config_logger.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}` : ""}.`, { level: "error" });
|
|
41
41
|
return;
|
|
42
42
|
}
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
for (const compositeId of compositeIds) {
|
|
44
|
+
const existingEntries = entriesDictionaries.get(compositeId) ?? [];
|
|
45
|
+
existingEntries.push(dictionary);
|
|
46
|
+
entriesDictionaries.set(compositeId, existingEntries);
|
|
47
|
+
}
|
|
46
48
|
});
|
|
47
49
|
const content = {};
|
|
48
50
|
let importMode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeQualifiedDictionaries.cjs","names":["getDictionaryQualifierTypes","QUALIFIER_ORDER","mergeDictionaries","
|
|
1
|
+
{"version":3,"file":"mergeQualifiedDictionaries.cjs","names":["getDictionaryQualifierTypes","QUALIFIER_ORDER","mergeDictionaries","getDictionaryCompositeIds"],"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 getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionary';\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 *\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 // `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 for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n // Unqualified siblings act as shared base content: appended last so the\n // qualified entries take precedence (mergeDictionaries prefers first).\n const mergedEntry = mergeDictionaries([\n ...qualifiedDictionaries,\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":";;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAIA,8EAA4B;CAExE,MAAM,qCAAqB,IAAI,KAA8B;AAC7D,MAAK,MAAM,SAAS,mBAClB,MAAK,MAAM,QAAQ,MAAO,oBAAmB,IAAI,KAAK;CAIxD,MAAM,sBAAsBC,kEAAgB,QAAQ,kBAClD,mBAAmB,IAAI,cAAc,CACtC;AAED,KAAI,oBAAoB,WAAW,EACjC,QAAOC,kEAAkB,aAAa;CAGxC,MAAM,sDAAyB,EAAE,iCAAK,CAAC;CAEvC,MAAM,mBAAiC,EAAE;CACzC,MAAM,sCAAsB,IAAI,KAA2B;AAE3D,cAAa,SAAS,YAAY,UAAU;AAC1C,MAAI,mBAAmB,QAAQ,WAAW,GAAG;AAC3C,oBAAiB,KAAK,WAAW;AACjC;;EAKF,MAAM,eAAeC,4EACnB,YACA,oBACD;AAED,MAAI,iBAAiB,QAAW;AAC9B,aACE,uDAA0B,WAAW,IAAI,CAAC,aAAa,mBAAmB,OAAO,KAAK,KAAK,CAAC,kCAAkC,oBAAoB,KAAK,KAAK,CAAC,wDAAwD,WAAW,WAAW,MAAM,WAAW,aAAa,GAAG,IAC5Q,EAAE,OAAO,SAAS,CACnB;AACD;;AAGF,OAAK,MAAM,eAAe,cAAc;GACtC,MAAM,kBAAkB,oBAAoB,IAAI,YAAY,IAAI,EAAE;AAClE,mBAAgB,KAAK,WAAW;AAChC,uBAAoB,IAAI,aAAa,gBAAgB;;GAEvD;CAMF,MAAM,UAAmC,EAAE;CAE3C,IAAI;AAEJ,MAAK,MAAM,CAAC,aAAa,0BAA0B,qBAAqB;AAQtE,UAAQ,eALYD,kEAAkB,CACpC,GAAG,uBACH,GAAG,iBACJ,CAEiC,CAAC;EAEnC,MAAM,CAAC,kBAAkB;AAEzB,iBAAe,gBAAgB;;CAGjC,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aACG,QAAQ,eAAe,WAAW,QAAQ,CAC1C,KAAK,eAAe,WAAW,QAAS,CAC5C,CACF;AAED,QAAO;EACL,KAAK,aAAa,GAAI;EACtB,gBAAgB;EAChB;EACA,GAAI,eAAe,UAAa,EAAE,YAAY;EAC9C;EACD"}
|
|
@@ -13,21 +13,60 @@ const QUALIFIER_ORDER = ["variant", "item"];
|
|
|
13
13
|
*/
|
|
14
14
|
const COMPOSITE_ID_SEPARATOR = "/";
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
16
|
+
* Characters kept verbatim in an encoded qualifier segment. Everything else is
|
|
17
|
+
* percent-encoded so a segment can never contain the composite-id separator
|
|
18
|
+
* (`/`), path-hostile characters (`\` `:` `*` `?` `"` `<` `>` `|`, control
|
|
19
|
+
* chars), or characters that would break the generated loader modules (`'`).
|
|
20
|
+
*/
|
|
21
|
+
const SEGMENT_UNSAFE_CHARS = /[^A-Za-z0-9._&=-]/g;
|
|
22
|
+
/**
|
|
23
|
+
* Stricter set for the components of an object variant: also encodes `&` and
|
|
24
|
+
* `=` so the `field=value&field=value` serialization stays unambiguous.
|
|
25
|
+
*/
|
|
26
|
+
const COMPONENT_UNSAFE_CHARS = /[^A-Za-z0-9._-]/g;
|
|
27
|
+
/** Percent-encodes one UTF-16 code unit as a fixed-width `%XXXX` run. */
|
|
28
|
+
const percentEncodeChar = (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
29
|
+
const encodeSegmentText = (raw, unsafeChars) => {
|
|
30
|
+
if (raw === "") return "%";
|
|
31
|
+
const encoded = raw.replace(unsafeChars, percentEncodeChar);
|
|
32
|
+
if (encoded === "." || encoded === "..") return encoded.replace(/\./g, "%002E");
|
|
33
|
+
return encoded;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Canonical serialization of a single variant value into its identity string —
|
|
37
|
+
* the variant segment of a composite id, the chunk directory name in dynamic
|
|
38
|
+
* mode, and the runtime matching key.
|
|
18
39
|
*
|
|
19
40
|
* - `undefined` → `'default'` (the implicit fallback variant)
|
|
20
41
|
* - a string → the string itself (a named variant)
|
|
21
42
|
* - an object → its sorted `key=value` pairs joined by `&`
|
|
22
43
|
* (e.g. `{ userId: '123', id: 'abc' }` → `'id=abc&userId=123'`)
|
|
23
44
|
*
|
|
45
|
+
* Characters that are unsafe in file paths or generated code are
|
|
46
|
+
* percent-encoded (fixed-width `%XXXX` runs, injective). Common names —
|
|
47
|
+
* letters, digits, `-` `_` `.` — are left untouched. Both the declaration and
|
|
48
|
+
* the selector go through this function, so encoding never affects matching.
|
|
49
|
+
*
|
|
24
50
|
* Two variants resolve to the same entry iff their serializations are equal, so
|
|
25
51
|
* an object variant in a selector must equal the one declared on the dictionary.
|
|
26
52
|
*/
|
|
27
53
|
const serializeVariant = (variant) => {
|
|
28
54
|
if (variant === void 0) return "default";
|
|
29
|
-
if (typeof variant === "string") return variant;
|
|
30
|
-
return Object.keys(variant).sort().map((field) => `${field}=${variant[field]}`).join("&");
|
|
55
|
+
if (typeof variant === "string") return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);
|
|
56
|
+
return Object.keys(variant).sort().map((field) => `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`).join("&");
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Normalizes the `variant` field of a dictionary into the list of variant ids
|
|
60
|
+
* the declaration registers under. A single value yields one id; an **array**
|
|
61
|
+
* fans out into one id per element (duplicates collapsed). Returns `undefined`
|
|
62
|
+
* when the dictionary does not declare the variant dimension (no `variant`
|
|
63
|
+
* field, or an empty array).
|
|
64
|
+
*/
|
|
65
|
+
const getVariantIds = (variant) => {
|
|
66
|
+
if (variant === void 0) return void 0;
|
|
67
|
+
const values = Array.isArray(variant) ? variant : [variant];
|
|
68
|
+
if (values.length === 0) return void 0;
|
|
69
|
+
return [...new Set(values.map(serializeVariant))];
|
|
31
70
|
};
|
|
32
71
|
/**
|
|
33
72
|
* Returns the qualifier dimensions declared on a dictionary, in canonical
|
|
@@ -36,49 +75,51 @@ const serializeVariant = (variant) => {
|
|
|
36
75
|
*/
|
|
37
76
|
const getDictionaryQualifierTypes = (dictionary) => {
|
|
38
77
|
const declaredQualifiers = [];
|
|
39
|
-
if (dictionary.variant !== void 0) declaredQualifiers.push("variant");
|
|
78
|
+
if (getVariantIds(dictionary.variant) !== void 0) declaredQualifiers.push("variant");
|
|
40
79
|
if (typeof dictionary.item === "number") declaredQualifiers.push("item");
|
|
41
80
|
return declaredQualifiers;
|
|
42
81
|
};
|
|
43
82
|
/**
|
|
44
|
-
* Returns the qualifier
|
|
45
|
-
* dimension —
|
|
83
|
+
* Returns the qualifier identifiers of a dictionary for the given qualifier
|
|
84
|
+
* dimension — the candidate segments of the composite entry ids.
|
|
46
85
|
*
|
|
47
|
-
* - 'variant' → the serialized variant (
|
|
48
|
-
* -
|
|
86
|
+
* - 'variant' → the serialized variant id(s); an array variant yields one id
|
|
87
|
+
* per element (declaration-side fan-out)
|
|
88
|
+
* - 'item' → the item index as a single-element list
|
|
49
89
|
*/
|
|
50
|
-
const
|
|
51
|
-
if (qualifierType === "variant") return
|
|
52
|
-
return dictionary.item === void 0 ? void 0 : String(dictionary.item);
|
|
90
|
+
const getDictionaryQualifierIds = (dictionary, qualifierType) => {
|
|
91
|
+
if (qualifierType === "variant") return getVariantIds(dictionary.variant);
|
|
92
|
+
return dictionary.item === void 0 ? void 0 : [String(dictionary.item)];
|
|
53
93
|
};
|
|
54
94
|
/**
|
|
55
|
-
*
|
|
56
|
-
* dimension
|
|
57
|
-
*
|
|
95
|
+
* Builds every composite entry id of a dictionary — the cartesian product of
|
|
96
|
+
* its per-dimension id lists, joined in canonical order. A dictionary with a
|
|
97
|
+
* plain (non-array) variant yields exactly one id; an array variant fans out
|
|
98
|
+
* into one id per element. `undefined` when a dimension of the set is missing.
|
|
58
99
|
*/
|
|
59
|
-
const
|
|
60
|
-
|
|
100
|
+
const getDictionaryCompositeIds = (dictionary, qualifierTypes) => {
|
|
101
|
+
let compositeIds = [""];
|
|
61
102
|
for (const qualifierType of qualifierTypes) {
|
|
62
|
-
const
|
|
63
|
-
if (
|
|
64
|
-
|
|
103
|
+
const ids = getDictionaryQualifierIds(dictionary, qualifierType);
|
|
104
|
+
if (ids === void 0) return void 0;
|
|
105
|
+
compositeIds = compositeIds.flatMap((prefix) => ids.map((id) => prefix === "" ? id : `${prefix}${"/"}${id}`));
|
|
65
106
|
}
|
|
66
|
-
return
|
|
107
|
+
return compositeIds;
|
|
67
108
|
};
|
|
68
109
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
* Tests whether a group entry matches a selector across every declared
|
|
75
|
-
* dimension. The `item` dimension matches any value when the selector does not
|
|
76
|
-
* provide one (open collection axis).
|
|
110
|
+
* Tests whether a composite entry id matches a selector across every declared
|
|
111
|
+
* dimension. Segments are compared in their encoded form (both the stored id
|
|
112
|
+
* and the selector go through {@link serializeVariant}). The `item` dimension
|
|
113
|
+
* matches any value when the selector does not provide one (open collection
|
|
114
|
+
* axis).
|
|
77
115
|
*/
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
return
|
|
81
|
-
|
|
116
|
+
const compositeIdMatchesSelector = (compositeId, qualifierTypes, selector) => {
|
|
117
|
+
const segments = compositeId.split("/");
|
|
118
|
+
return qualifierTypes.every((qualifierType, index) => {
|
|
119
|
+
if (qualifierType === "variant") return segments[index] === serializeVariant(selector?.variant);
|
|
120
|
+
return selector?.item === void 0 || segments[index] === String(selector.item);
|
|
121
|
+
});
|
|
122
|
+
};
|
|
82
123
|
/**
|
|
83
124
|
* Type guard discriminating a `QualifiedDictionaryGroup` (merge output of a
|
|
84
125
|
* qualified key) from a plain `Dictionary`. Both carry a `content` field; only
|
|
@@ -90,11 +131,11 @@ const isQualifiedDictionaryGroup = (value) => typeof value === "object" && value
|
|
|
90
131
|
* qualified group: the content node stored under its composite id, plus the
|
|
91
132
|
* qualifier coordinates decoded from that id (`variant`, `item`).
|
|
92
133
|
*
|
|
93
|
-
* This keeps the resolver's
|
|
134
|
+
* This keeps the resolver's transform code unchanged: it still sees a
|
|
94
135
|
* `{ key, content, variant?, item? }` shape, even though the stored format no
|
|
95
136
|
* longer duplicates those fields per entry. The `variant` coordinate stays in
|
|
96
|
-
* its serialized form
|
|
97
|
-
*
|
|
137
|
+
* its serialized (encoded) form, e.g. `'id=abc&userId=123'` — matching happens
|
|
138
|
+
* on the composite id segments, never on this reconstructed field.
|
|
98
139
|
*/
|
|
99
140
|
const reconstructQualifiedEntry = (group, compositeId) => {
|
|
100
141
|
const segments = compositeId.split("/");
|
|
@@ -125,7 +166,7 @@ const resolveQualifiedDictionary = (dictionaryOrGroup, selector) => {
|
|
|
125
166
|
if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) return dictionaryOrGroup;
|
|
126
167
|
const { qualifierTypes, content } = dictionaryOrGroup;
|
|
127
168
|
const itemAxisOpen = qualifierTypes.includes("item") && selector?.item === void 0;
|
|
128
|
-
const matchedEntries = Object.keys(content).
|
|
169
|
+
const matchedEntries = Object.keys(content).filter((compositeId) => compositeIdMatchesSelector(compositeId, qualifierTypes, selector)).map((compositeId) => reconstructQualifiedEntry(dictionaryOrGroup, compositeId));
|
|
129
170
|
if (itemAxisOpen) return matchedEntries.sort((left, right) => (left.item ?? 0) - (right.item ?? 0));
|
|
130
171
|
return matchedEntries[0] ?? null;
|
|
131
172
|
};
|
|
@@ -260,11 +301,11 @@ const resolveQualifiedDynamicContentAsync = async (params) => {
|
|
|
260
301
|
exports.COMPOSITE_ID_SEPARATOR = COMPOSITE_ID_SEPARATOR;
|
|
261
302
|
exports.QUALIFIER_DYNAMIC_TYPES_KEY = QUALIFIER_DYNAMIC_TYPES_KEY;
|
|
262
303
|
exports.QUALIFIER_ORDER = QUALIFIER_ORDER;
|
|
263
|
-
exports.
|
|
264
|
-
exports.
|
|
265
|
-
exports.getDictionaryQualifierSegments = getDictionaryQualifierSegments;
|
|
304
|
+
exports.getDictionaryCompositeIds = getDictionaryCompositeIds;
|
|
305
|
+
exports.getDictionaryQualifierIds = getDictionaryQualifierIds;
|
|
266
306
|
exports.getDictionaryQualifierTypes = getDictionaryQualifierTypes;
|
|
267
307
|
exports.getDictionarySelectorCacheKey = getDictionarySelectorCacheKey;
|
|
308
|
+
exports.getVariantIds = getVariantIds;
|
|
268
309
|
exports.isQualifiedDictionaryGroup = isQualifiedDictionaryGroup;
|
|
269
310
|
exports.isQualifiedDynamicLoaderMap = isQualifiedDynamicLoaderMap;
|
|
270
311
|
exports.parseDictionarySelector = parseDictionarySelector;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qualifiedDictionary.cjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Canonical order of qualifier dimensions. A key that declares both dimensions\n * always nests them in this order, with `item` innermost so it can act as the\n * collection (array) axis.\n */\nexport const QUALIFIER_ORDER = [\n 'variant',\n 'item',\n] as const satisfies readonly DictionaryQualifierType[];\n\n/**\n * Separator joining per-dimension ids into a composite entry id. Also used as\n * the chunk path separator in dynamic mode.\n */\nexport const COMPOSITE_ID_SEPARATOR = '/';\n\n/**\n * Canonical serialization of a variant value into its identity string — the\n * variant segment of a composite id and the runtime matching key.\n *\n * - `undefined` → `'default'` (the implicit fallback variant)\n * - a string → the string itself (a named variant)\n * - an object → its sorted `key=value` pairs joined by `&`\n * (e.g. `{ userId: '123', id: 'abc' }` → `'id=abc&userId=123'`)\n *\n * Two variants resolve to the same entry iff their serializations are equal, so\n * an object variant in a selector must equal the one declared on the dictionary.\n */\nexport const serializeVariant = (\n variant: string | Record<string, string | number> | undefined\n): string => {\n if (variant === undefined) return 'default';\n if (typeof variant === 'string') return variant;\n\n return Object.keys(variant)\n .sort()\n .map((field) => `${field}=${variant[field]}`)\n .join('&');\n};\n\n/**\n * Returns the qualifier dimensions declared on a dictionary, in canonical\n * order (`variant → item`). Empty when the dictionary is unqualified\n * (plain dictionary or shared base content of a qualified group).\n */\nexport const getDictionaryQualifierTypes = (\n dictionary: Dictionary\n): DictionaryQualifierType[] => {\n const declaredQualifiers: DictionaryQualifierType[] = [];\n\n if (dictionary.variant !== undefined) declaredQualifiers.push('variant');\n if (typeof dictionary.item === 'number') declaredQualifiers.push('item');\n\n return declaredQualifiers;\n};\n\n/**\n * Returns the qualifier identifier of a dictionary for the given qualifier\n * dimension — one segment of the composite entry id.\n *\n * - 'variant' → the serialized variant (named string or object identity)\n * - 'item' → the item index as string\n */\nexport const getDictionaryQualifierId = (\n dictionary: Dictionary,\n qualifierType: DictionaryQualifierType\n): string | undefined => {\n if (qualifierType === 'variant') {\n return dictionary.variant === undefined\n ? undefined\n : serializeVariant(dictionary.variant);\n }\n return dictionary.item === undefined ? undefined : String(dictionary.item);\n};\n\n/**\n * Returns the per-dimension id segments of a dictionary for the given ordered\n * dimension set, or `undefined` when the dictionary does not declare every\n * dimension of the set.\n */\nexport const getDictionaryQualifierSegments = (\n dictionary: Dictionary,\n qualifierTypes: DictionaryQualifierType[]\n): string[] | undefined => {\n const segments: string[] = [];\n\n for (const qualifierType of qualifierTypes) {\n const id = getDictionaryQualifierId(dictionary, qualifierType);\n if (id === undefined) return undefined;\n segments.push(id);\n }\n\n return segments;\n};\n\n/**\n * Builds the composite entry id of a dictionary — its per-dimension id segments\n * joined in canonical order. `undefined` when a dimension is missing.\n */\nexport const getDictionaryCompositeId = (\n dictionary: Dictionary,\n qualifierTypes: DictionaryQualifierType[]\n): string | undefined =>\n getDictionaryQualifierSegments(dictionary, qualifierTypes)?.join(\n COMPOSITE_ID_SEPARATOR\n );\n\n/**\n * Tests whether a group entry matches a selector across every declared\n * dimension. The `item` dimension matches any value when the selector does not\n * provide one (open collection axis).\n */\nconst entryMatchesSelector = (\n entry: Dictionary,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined\n): boolean =>\n qualifierTypes.every((qualifierType) => {\n if (qualifierType === 'variant') {\n return (\n serializeVariant(entry.variant) === serializeVariant(selector?.variant)\n );\n }\n\n // qualifierType === 'item'\n return (\n selector?.item === undefined ||\n String(entry.item) === String(selector.item)\n );\n });\n\n/**\n * Type guard discriminating a `QualifiedDictionaryGroup` (merge output of a\n * qualified key) from a plain `Dictionary`. Both carry a `content` field; only\n * the group declares `qualifierTypes`, which is therefore the discriminator.\n */\nexport const isQualifiedDictionaryGroup = (\n value: unknown\n): value is QualifiedDictionaryGroup =>\n typeof value === 'object' &&\n value !== null &&\n 'qualifierTypes' in value &&\n Array.isArray((value as { qualifierTypes: unknown }).qualifierTypes) &&\n 'content' in value;\n\n/**\n * Reconstructs a resolvable {@link Dictionary} from a single entry of a\n * qualified group: the content node stored under its composite id, plus the\n * qualifier coordinates decoded from that id (`variant`, `item`).\n *\n * This keeps the resolver's matching/transform code unchanged: it still sees a\n * `{ key, content, variant?, item? }` shape, even though the stored format no\n * longer duplicates those fields per entry. The `variant` coordinate stays in\n * its serialized form (e.g. `'id=abc&userId=123'`), which round-trips through\n * {@link serializeVariant} during matching.\n */\nexport const reconstructQualifiedEntry = (\n group: QualifiedDictionaryGroup,\n compositeId: string\n): Dictionary => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n const entry = {\n key: group.key,\n content: group.content[compositeId],\n } as Dictionary;\n\n group.qualifierTypes.forEach((qualifierType, index) => {\n if (qualifierType === 'variant') {\n entry.variant = segments[index];\n } else if (qualifierType === 'item') {\n entry.item = Number(segments[index]);\n }\n });\n\n return entry;\n};\n\n/**\n * Resolves a dictionary (or qualified dictionary group) against a selector,\n * across every declared dimension.\n *\n * - Plain dictionary → returned as-is (selector ignored)\n * - `item` declared but not selected → every matching entry ordered by index\n * - `item` selected → the matching entry or null\n * - `variant` defaults to the `default` entry when not selected; an object\n * variant resolves only when the selector provides an equal object\n *\n * Dimensions compose: e.g. a variant × item key with `{ variant: 'promo' }`\n * returns every promo item as an array; adding `{ item: 2 }` narrows to one.\n */\nexport const resolveQualifiedDictionary = (\n dictionaryOrGroup: Dictionary | QualifiedDictionaryGroup,\n selector?: DictionarySelector\n): Dictionary | Dictionary[] | null => {\n if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) {\n return dictionaryOrGroup;\n }\n\n const { qualifierTypes, content } = dictionaryOrGroup;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n const matchedEntries = Object.keys(content)\n .map((compositeId) =>\n reconstructQualifiedEntry(dictionaryOrGroup, compositeId)\n )\n .filter((entry) => entryMatchesSelector(entry, qualifierTypes, selector));\n\n if (itemAxisOpen) {\n return matchedEntries.sort(\n (left, right) => (left.item ?? 0) - (right.item ?? 0)\n );\n }\n\n return matchedEntries[0] ?? null;\n};\n\n/**\n * Splits the second argument of `getIntlayer` / `getDictionary` into the\n * effective locale and the selector object (if any).\n */\nexport const parseDictionarySelector = <L extends LocalesValues>(\n localeOrSelector?: L | DictionarySelector\n): { locale?: L; selector?: DictionarySelector } => {\n if (typeof localeOrSelector === 'object' && localeOrSelector !== null) {\n return {\n locale: localeOrSelector.locale as L | undefined,\n selector: localeOrSelector,\n };\n }\n\n return { locale: localeOrSelector };\n};\n\n/**\n * Builds a stable string identity of a selector (excluding `locale`), suitable\n * for cache keys and memoization dependencies.\n */\nexport const getDictionarySelectorCacheKey = (\n selector?: DictionarySelector\n): string => {\n if (!selector) return '';\n\n return Object.keys(selector)\n .filter((selectorKey) => selectorKey !== 'locale')\n .sort()\n .map((selectorKey) => {\n const value = selector[selectorKey as keyof DictionarySelector];\n const serialized =\n selectorKey === 'variant'\n ? serializeVariant(value as Parameters<typeof serializeVariant>[0])\n : String(value);\n return `${selectorKey}:${serialized}`;\n })\n .join('|');\n};\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Its presence distinguishes a qualified group loader map (a nested tree\n * of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed\n * and unlikely to collide with a real locale code.\n */\nexport const QUALIFIER_DYNAMIC_TYPES_KEY = '__intlayerQualifierTypes';\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/**\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n const segment =\n dimension === 'variant'\n ? serializeVariant(selector?.variant)\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` defaults to `default` (or descends by the\n * serialized object identity), and `item` either narrows to the selected index\n * or — when no item is given — expands into every sibling chunk (the collection\n * axis). Semantics mirror {@link resolveQualifiedDictionary} so dynamic and\n * static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,kBAAkB,CAC7B,WACA,OACD;;;;;AAMD,MAAa,yBAAyB;;;;;;;;;;;;;AActC,MAAa,oBACX,YACW;AACX,KAAI,YAAY,OAAW,QAAO;AAClC,KAAI,OAAO,YAAY,SAAU,QAAO;AAExC,QAAO,OAAO,KAAK,QAAQ,CACxB,MAAM,CACN,KAAK,UAAU,GAAG,MAAM,GAAG,QAAQ,SAAS,CAC5C,KAAK,IAAI;;;;;;;AAQd,MAAa,+BACX,eAC8B;CAC9B,MAAM,qBAAgD,EAAE;AAExD,KAAI,WAAW,YAAY,OAAW,oBAAmB,KAAK,UAAU;AACxE,KAAI,OAAO,WAAW,SAAS,SAAU,oBAAmB,KAAK,OAAO;AAExE,QAAO;;;;;;;;;AAUT,MAAa,4BACX,YACA,kBACuB;AACvB,KAAI,kBAAkB,UACpB,QAAO,WAAW,YAAY,SAC1B,SACA,iBAAiB,WAAW,QAAQ;AAE1C,QAAO,WAAW,SAAS,SAAY,SAAY,OAAO,WAAW,KAAK;;;;;;;AAQ5E,MAAa,kCACX,YACA,mBACyB;CACzB,MAAM,WAAqB,EAAE;AA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type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n DictionaryVariantValue,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Canonical order of qualifier dimensions. A key that declares both dimensions\n * always nests them in this order, with `item` innermost so it can act as the\n * collection (array) axis.\n */\nexport const QUALIFIER_ORDER = [\n 'variant',\n 'item',\n] as const satisfies readonly DictionaryQualifierType[];\n\n/**\n * Separator joining per-dimension ids into a composite entry id. Also used as\n * the chunk path separator in dynamic mode.\n */\nexport const COMPOSITE_ID_SEPARATOR = '/';\n\n/**\n * Characters kept verbatim in an encoded qualifier segment. Everything else is\n * percent-encoded so a segment can never contain the composite-id separator\n * (`/`), path-hostile characters (`\\` `:` `*` `?` `\"` `<` `>` `|`, control\n * chars), or characters that would break the generated loader modules (`'`).\n */\nconst SEGMENT_UNSAFE_CHARS = /[^A-Za-z0-9._&=-]/g;\n\n/**\n * Stricter set for the components of an object variant: also encodes `&` and\n * `=` so the `field=value&field=value` serialization stays unambiguous.\n */\nconst COMPONENT_UNSAFE_CHARS = /[^A-Za-z0-9._-]/g;\n\n/** Percent-encodes one UTF-16 code unit as a fixed-width `%XXXX` run. */\nconst percentEncodeChar = (char: string): string =>\n `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}`;\n\nconst encodeSegmentText = (raw: string, unsafeChars: RegExp): string => {\n // Bare '%' cannot be produced by encoding (every encoded run is %XXXX),\n // so it is a safe stand-in for the empty string.\n if (raw === '') return '%';\n\n const encoded = raw.replace(unsafeChars, percentEncodeChar);\n\n // '.' and '..' are path navigation on every filesystem — encode the dots.\n if (encoded === '.' || encoded === '..') {\n return encoded.replace(/\\./g, '%002E');\n }\n\n return encoded;\n};\n\n/**\n * Canonical serialization of a single variant value into its identity string —\n * the variant segment of a composite id, the chunk directory name in dynamic\n * mode, and the runtime matching key.\n *\n * - `undefined` → `'default'` (the implicit fallback variant)\n * - a string → the string itself (a named variant)\n * - an object → its sorted `key=value` pairs joined by `&`\n * (e.g. `{ userId: '123', id: 'abc' }` → `'id=abc&userId=123'`)\n *\n * Characters that are unsafe in file paths or generated code are\n * percent-encoded (fixed-width `%XXXX` runs, injective). Common names —\n * letters, digits, `-` `_` `.` — are left untouched. Both the declaration and\n * the selector go through this function, so encoding never affects matching.\n *\n * Two variants resolve to the same entry iff their serializations are equal, so\n * an object variant in a selector must equal the one declared on the dictionary.\n */\nexport const serializeVariant = (\n variant: DictionaryVariantValue | undefined\n): string => {\n if (variant === undefined) return 'default';\n if (typeof variant === 'string') {\n return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);\n }\n\n return Object.keys(variant)\n .sort()\n .map(\n (field) =>\n `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`\n )\n .join('&');\n};\n\n/**\n * Normalizes the `variant` field of a dictionary into the list of variant ids\n * the declaration registers under. A single value yields one id; an **array**\n * fans out into one id per element (duplicates collapsed). Returns `undefined`\n * when the dictionary does not declare the variant dimension (no `variant`\n * field, or an empty array).\n */\nexport const getVariantIds = (\n variant: Dictionary['variant']\n): string[] | undefined => {\n if (variant === undefined) return undefined;\n\n const values = Array.isArray(variant) ? variant : [variant];\n if (values.length === 0) return undefined;\n\n return [...new Set(values.map(serializeVariant))];\n};\n\n/**\n * Returns the qualifier dimensions declared on a dictionary, in canonical\n * order (`variant → item`). Empty when the dictionary is unqualified\n * (plain dictionary or shared base content of a qualified group).\n */\nexport const getDictionaryQualifierTypes = (\n dictionary: Dictionary\n): DictionaryQualifierType[] => {\n const declaredQualifiers: DictionaryQualifierType[] = [];\n\n if (getVariantIds(dictionary.variant) !== undefined) {\n declaredQualifiers.push('variant');\n }\n if (typeof dictionary.item === 'number') declaredQualifiers.push('item');\n\n return declaredQualifiers;\n};\n\n/**\n * Returns the qualifier identifiers of a dictionary for the given qualifier\n * dimension — the candidate segments of the composite entry ids.\n *\n * - 'variant' → the serialized variant id(s); an array variant yields one id\n * per element (declaration-side fan-out)\n * - 'item' → the item index as a single-element list\n */\nexport const getDictionaryQualifierIds = (\n dictionary: Dictionary,\n qualifierType: DictionaryQualifierType\n): string[] | undefined => {\n if (qualifierType === 'variant') {\n return getVariantIds(dictionary.variant);\n }\n return dictionary.item === undefined ? undefined : [String(dictionary.item)];\n};\n\n/**\n * Builds every composite entry id of a dictionary — the cartesian product of\n * its per-dimension id lists, joined in canonical order. A dictionary with a\n * plain (non-array) variant yields exactly one id; an array variant fans out\n * into one id per element. `undefined` when a dimension of the set is missing.\n */\nexport const getDictionaryCompositeIds = (\n dictionary: Dictionary,\n qualifierTypes: DictionaryQualifierType[]\n): string[] | undefined => {\n let compositeIds: string[] = [''];\n\n for (const qualifierType of qualifierTypes) {\n const ids = getDictionaryQualifierIds(dictionary, qualifierType);\n if (ids === undefined) return undefined;\n\n compositeIds = compositeIds.flatMap((prefix) =>\n ids.map((id) =>\n prefix === '' ? id : `${prefix}${COMPOSITE_ID_SEPARATOR}${id}`\n )\n );\n }\n\n return compositeIds;\n};\n\n/**\n * Tests whether a composite entry id matches a selector across every declared\n * dimension. Segments are compared in their encoded form (both the stored id\n * and the selector go through {@link serializeVariant}). The `item` dimension\n * matches any value when the selector does not provide one (open collection\n * axis).\n */\nconst compositeIdMatchesSelector = (\n compositeId: string,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined\n): boolean => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n return qualifierTypes.every((qualifierType, index) => {\n if (qualifierType === 'variant') {\n return segments[index] === serializeVariant(selector?.variant);\n }\n\n // qualifierType === 'item'\n return (\n selector?.item === undefined || segments[index] === String(selector.item)\n );\n });\n};\n\n/**\n * Type guard discriminating a `QualifiedDictionaryGroup` (merge output of a\n * qualified key) from a plain `Dictionary`. Both carry a `content` field; only\n * the group declares `qualifierTypes`, which is therefore the discriminator.\n */\nexport const isQualifiedDictionaryGroup = (\n value: unknown\n): value is QualifiedDictionaryGroup =>\n typeof value === 'object' &&\n value !== null &&\n 'qualifierTypes' in value &&\n Array.isArray((value as { qualifierTypes: unknown }).qualifierTypes) &&\n 'content' in value;\n\n/**\n * Reconstructs a resolvable {@link Dictionary} from a single entry of a\n * qualified group: the content node stored under its composite id, plus the\n * qualifier coordinates decoded from that id (`variant`, `item`).\n *\n * This keeps the resolver's transform code unchanged: it still sees a\n * `{ key, content, variant?, item? }` shape, even though the stored format no\n * longer duplicates those fields per entry. The `variant` coordinate stays in\n * its serialized (encoded) form, e.g. `'id=abc&userId=123'` — matching happens\n * on the composite id segments, never on this reconstructed field.\n */\nexport const reconstructQualifiedEntry = (\n group: QualifiedDictionaryGroup,\n compositeId: string\n): Dictionary => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n const entry = {\n key: group.key,\n content: group.content[compositeId],\n } as Dictionary;\n\n group.qualifierTypes.forEach((qualifierType, index) => {\n if (qualifierType === 'variant') {\n entry.variant = segments[index];\n } else if (qualifierType === 'item') {\n entry.item = Number(segments[index]);\n }\n });\n\n return entry;\n};\n\n/**\n * Resolves a dictionary (or qualified dictionary group) against a selector,\n * across every declared dimension.\n *\n * - Plain dictionary → returned as-is (selector ignored)\n * - `item` declared but not selected → every matching entry ordered by index\n * - `item` selected → the matching entry or null\n * - `variant` defaults to the `default` entry when not selected; an object\n * variant resolves only when the selector provides an equal object\n *\n * Dimensions compose: e.g. a variant × item key with `{ variant: 'promo' }`\n * returns every promo item as an array; adding `{ item: 2 }` narrows to one.\n */\nexport const resolveQualifiedDictionary = (\n dictionaryOrGroup: Dictionary | QualifiedDictionaryGroup,\n selector?: DictionarySelector\n): Dictionary | Dictionary[] | null => {\n if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) {\n return dictionaryOrGroup;\n }\n\n const { qualifierTypes, content } = dictionaryOrGroup;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n const matchedEntries = Object.keys(content)\n .filter((compositeId) =>\n compositeIdMatchesSelector(compositeId, qualifierTypes, selector)\n )\n .map((compositeId) =>\n reconstructQualifiedEntry(dictionaryOrGroup, compositeId)\n );\n\n if (itemAxisOpen) {\n return matchedEntries.sort(\n (left, right) => (left.item ?? 0) - (right.item ?? 0)\n );\n }\n\n return matchedEntries[0] ?? null;\n};\n\n/**\n * Splits the second argument of `getIntlayer` / `getDictionary` into the\n * effective locale and the selector object (if any).\n */\nexport const parseDictionarySelector = <L extends LocalesValues>(\n localeOrSelector?: L | DictionarySelector\n): { locale?: L; selector?: DictionarySelector } => {\n if (typeof localeOrSelector === 'object' && localeOrSelector !== null) {\n return {\n locale: localeOrSelector.locale as L | undefined,\n selector: localeOrSelector,\n };\n }\n\n return { locale: localeOrSelector };\n};\n\n/**\n * Builds a stable string identity of a selector (excluding `locale`), suitable\n * for cache keys and memoization dependencies.\n */\nexport const getDictionarySelectorCacheKey = (\n selector?: DictionarySelector\n): string => {\n if (!selector) return '';\n\n return Object.keys(selector)\n .filter((selectorKey) => selectorKey !== 'locale')\n .sort()\n .map((selectorKey) => {\n const value = selector[selectorKey as keyof DictionarySelector];\n const serialized =\n selectorKey === 'variant'\n ? serializeVariant(value as Parameters<typeof serializeVariant>[0])\n : String(value);\n return `${selectorKey}:${serialized}`;\n })\n .join('|');\n};\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Its presence distinguishes a qualified group loader map (a nested tree\n * of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed\n * and unlikely to collide with a real locale code.\n */\nexport const QUALIFIER_DYNAMIC_TYPES_KEY = '__intlayerQualifierTypes';\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/**\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n const segment =\n dimension === 'variant'\n ? serializeVariant(selector?.variant)\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` defaults to `default` (or descends by the\n * serialized object identity), and `item` either narrows to the selected index\n * or — when no item is given — expands into every sibling chunk (the collection\n * axis). Semantics mirror {@link resolveQualifiedDictionary} so dynamic and\n * static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;AAcA,MAAa,kBAAkB,CAC7B,WACA,OACD;;;;;AAMD,MAAa,yBAAyB;;;;;;;AAQtC,MAAM,uBAAuB;;;;;AAM7B,MAAM,yBAAyB;;AAG/B,MAAM,qBAAqB,SACz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ateNodeChildren = require('./dictionaryMa
|
|
|
64
64
|
const require_utils_checkIsURLAbsolute = require('./utils/checkIsURLAbsolute.cjs');
|
|
65
65
|
const require_localization_getPathWithoutLocale = require('./localization/getPathWithoutLocale.cjs');
|
|
66
66
|
const require_localization_comparePaths = require('./localization/comparePaths.cjs');
|
|
67
|
+
const require_localization_domainUtils = require('./localization/domainUtils.cjs');
|
|
67
68
|
const require_localization_getPrefix = require('./localization/getPrefix.cjs');
|
|
68
69
|
const require_localization_rewriteUtils = require('./localization/rewriteUtils.cjs');
|
|
69
70
|
const require_localization_getLocalizedUrl = require('./localization/getLocalizedUrl.cjs');
|
|
@@ -88,6 +89,7 @@ const require_markdown_renderer = require('./markdown/renderer.cjs');
|
|
|
88
89
|
const require_markdown_compiler = require('./markdown/compiler.cjs');
|
|
89
90
|
const require_messageFormat_ICU = require('./messageFormat/ICU.cjs');
|
|
90
91
|
const require_messageFormat_i18next = require('./messageFormat/i18next.cjs');
|
|
92
|
+
const require_messageFormat_navigatePath = require('./messageFormat/navigatePath.cjs');
|
|
91
93
|
const require_messageFormat_po = require('./messageFormat/po.cjs');
|
|
92
94
|
const require_messageFormat_vue_i18n = require('./messageFormat/vue-i18n.cjs');
|
|
93
95
|
const require_messageFormat_resolveMessage = require('./messageFormat/resolveMessage.cjs');
|
|
@@ -225,11 +227,12 @@ exports.getContentNodeByKeyPath = require_dictionaryManipulator_getContentNodeBy
|
|
|
225
227
|
exports.getCookie = require_utils_getCookie.getCookie;
|
|
226
228
|
exports.getDefaultNode = require_dictionaryManipulator_getDefaultNode.getDefaultNode;
|
|
227
229
|
exports.getDictionary = require_interpreter_getDictionary.getDictionary;
|
|
228
|
-
exports.
|
|
229
|
-
exports.
|
|
230
|
-
exports.getDictionaryQualifierSegments = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierSegments;
|
|
230
|
+
exports.getDictionaryCompositeIds = require_dictionaryManipulator_qualifiedDictionary.getDictionaryCompositeIds;
|
|
231
|
+
exports.getDictionaryQualifierIds = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierIds;
|
|
231
232
|
exports.getDictionaryQualifierTypes = require_dictionaryManipulator_qualifiedDictionary.getDictionaryQualifierTypes;
|
|
232
233
|
exports.getDictionarySelectorCacheKey = require_dictionaryManipulator_qualifiedDictionary.getDictionarySelectorCacheKey;
|
|
234
|
+
exports.getDomainHostname = require_localization_domainUtils.getDomainHostname;
|
|
235
|
+
exports.getDomainOrigin = require_localization_domainUtils.getDomainOrigin;
|
|
233
236
|
exports.getEditedContent = require_deepTransformPlugins_getEditedContent.getEditedContent;
|
|
234
237
|
exports.getEditedDictionary = require_deepTransformPlugins_getEditedContent.getEditedDictionary;
|
|
235
238
|
exports.getEmptyNode = require_dictionaryManipulator_getEmptyNode.getEmptyNode;
|
|
@@ -246,6 +249,7 @@ exports.getInsertionValues = require_transpiler_insertion_getInsertionValues.get
|
|
|
246
249
|
exports.getInternalPath = require_localization_rewriteUtils.getInternalPath;
|
|
247
250
|
exports.getIntlayer = require_interpreter_getIntlayer.getIntlayer;
|
|
248
251
|
exports.getLocale = require_localization_getLocale.getLocale;
|
|
252
|
+
exports.getLocaleFromDomain = require_localization_domainUtils.getLocaleFromDomain;
|
|
249
253
|
exports.getLocaleFromPath = require_localization_getLocaleFromPath.getLocaleFromPath;
|
|
250
254
|
exports.getLocaleFromStorage = require_utils_localeStorage.getLocaleFromStorage;
|
|
251
255
|
exports.getLocaleFromStorageClient = require_utils_localeStorage.getLocaleFromStorageClient;
|
|
@@ -274,6 +278,7 @@ exports.getRewriteRules = require_localization_rewriteUtils.getRewriteRules;
|
|
|
274
278
|
exports.getSplittedContent = require_deepTransformPlugins_getSplittedContent.getSplittedContent;
|
|
275
279
|
exports.getSplittedDictionaryContent = require_deepTransformPlugins_getSplittedContent.getSplittedDictionaryContent;
|
|
276
280
|
exports.getTranslation = require_interpreter_getTranslation.getTranslation;
|
|
281
|
+
exports.getVariantIds = require_dictionaryManipulator_qualifiedDictionary.getVariantIds;
|
|
277
282
|
exports.html = require_transpiler_html_html.html;
|
|
278
283
|
exports.i18nextToIntlayerFormatter = require_messageFormat_i18next.i18nextToIntlayerFormatter;
|
|
279
284
|
exports.icuToIntlayerFormatter = require_messageFormat_ICU.icuToIntlayerFormatter;
|
|
@@ -286,6 +291,7 @@ exports.intlayerToI18nextFormatter = require_messageFormat_i18next.intlayerToI18
|
|
|
286
291
|
exports.intlayerToICUFormatter = require_messageFormat_ICU.intlayerToICUFormatter;
|
|
287
292
|
exports.intlayerToPortableObjectFormatter = require_messageFormat_po.intlayerToPortableObjectFormatter;
|
|
288
293
|
exports.intlayerToVueI18nFormatter = require_messageFormat_vue_i18n.intlayerToVueI18nFormatter;
|
|
294
|
+
exports.isLocaleExclusiveOnDomain = require_localization_domainUtils.isLocaleExclusiveOnDomain;
|
|
289
295
|
exports.isQualifiedDictionaryGroup = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDictionaryGroup;
|
|
290
296
|
exports.isQualifiedDynamicLoaderMap = require_dictionaryManipulator_qualifiedDictionary.isQualifiedDynamicLoaderMap;
|
|
291
297
|
exports.isSameKeyPath = require_utils_isSameKeyPath.isSameKeyPath;
|
|
@@ -300,6 +306,7 @@ exports.localeStorageOptions = require_utils_localeStorage.localeStorageOptions;
|
|
|
300
306
|
exports.md = require_transpiler_markdown_markdown.md;
|
|
301
307
|
exports.mergeDictionaries = require_dictionaryManipulator_mergeDictionaries.mergeDictionaries;
|
|
302
308
|
exports.mergeQualifiedDictionaries = require_dictionaryManipulator_mergeQualifiedDictionaries.mergeQualifiedDictionaries;
|
|
309
|
+
exports.navigatePath = require_messageFormat_navigatePath.navigatePath;
|
|
303
310
|
exports.nest = require_transpiler_nesting_nesting.nest;
|
|
304
311
|
exports.nestedPlugin = require_interpreter_getContent_plugins.nestedPlugin;
|
|
305
312
|
exports.normalizeAttributeKey = require_markdown_utils.normalizeAttributeKey;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
//#region src/localization/domainUtils.ts
|
|
4
|
+
/**
|
|
5
|
+
* Strips the protocol from a domain string and returns only the hostname.
|
|
6
|
+
*
|
|
7
|
+
* Example:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* getDomainHostname('https://intlayer.cn') // 'intlayer.cn'
|
|
11
|
+
* getDomainHostname('intlayer.cn') // 'intlayer.cn'
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @param domain - A domain value from `routing.domains`, with or without protocol.
|
|
15
|
+
* @returns The bare hostname.
|
|
16
|
+
*/
|
|
17
|
+
const getDomainHostname = (domain) => {
|
|
18
|
+
try {
|
|
19
|
+
return /^https?:\/\//.test(domain) ? new URL(domain).hostname : domain;
|
|
20
|
+
} catch {
|
|
21
|
+
return domain;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Returns the absolute origin for a domain value, prepending `https://`
|
|
26
|
+
* when no protocol is present.
|
|
27
|
+
*
|
|
28
|
+
* Example:
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* getDomainOrigin('intlayer.cn') // 'https://intlayer.cn'
|
|
32
|
+
* getDomainOrigin('http://intlayer.cn') // 'http://intlayer.cn'
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @param domain - A domain value from `routing.domains`, with or without protocol.
|
|
36
|
+
* @returns The origin usable as a URL base.
|
|
37
|
+
*/
|
|
38
|
+
const getDomainOrigin = (domain) => /^https?:\/\//.test(domain) ? domain : `https://${domain}`;
|
|
39
|
+
/**
|
|
40
|
+
* Returns the locale exclusively mapped to a given hostname via `routing.domains`,
|
|
41
|
+
* or `undefined` when zero or more than one locale share that hostname.
|
|
42
|
+
*
|
|
43
|
+
* Example: with `domains = { zh: 'intlayer.cn', en: 'intlayer.org', fr: 'intlayer.org' }`
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* getLocaleFromDomain('intlayer.cn', domains) // 'zh'
|
|
47
|
+
* getLocaleFromDomain('intlayer.org', domains) // undefined (en and fr share it)
|
|
48
|
+
* getLocaleFromDomain('example.com', domains) // undefined (not mapped)
|
|
49
|
+
* ```
|
|
50
|
+
*
|
|
51
|
+
* @param hostname - The bare hostname of the incoming request.
|
|
52
|
+
* @param domains - The configured locale → domain map.
|
|
53
|
+
* @returns The exclusively mapped locale, or `undefined`.
|
|
54
|
+
*/
|
|
55
|
+
const getLocaleFromDomain = (hostname, domains) => {
|
|
56
|
+
if (!domains) return void 0;
|
|
57
|
+
const matchingLocales = Object.entries(domains).filter(([, domain]) => typeof domain === "string" && getDomainHostname(domain) === hostname);
|
|
58
|
+
return matchingLocales.length === 1 ? matchingLocales[0]?.[0] : void 0;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Checks whether a locale is the only locale mapped to its configured domain.
|
|
62
|
+
* When true, the domain alone identifies the locale and no URL prefix is needed.
|
|
63
|
+
* Hostnames are compared after protocol stripping, so
|
|
64
|
+
* `{ en: 'https://intlayer.org', fr: 'intlayer.org' }` counts as a shared domain.
|
|
65
|
+
*
|
|
66
|
+
* @param locale - The locale to check.
|
|
67
|
+
* @param domains - The configured locale → domain map.
|
|
68
|
+
* @returns `true` when the locale has a domain shared with no other locale.
|
|
69
|
+
*/
|
|
70
|
+
const isLocaleExclusiveOnDomain = (locale, domains) => {
|
|
71
|
+
const localeDomain = domains?.[locale];
|
|
72
|
+
if (!localeDomain) return false;
|
|
73
|
+
const localeHostname = getDomainHostname(localeDomain);
|
|
74
|
+
return Object.values(domains).filter((domain) => typeof domain === "string" && getDomainHostname(domain) === localeHostname).length === 1;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
exports.getDomainHostname = getDomainHostname;
|
|
79
|
+
exports.getDomainOrigin = getDomainOrigin;
|
|
80
|
+
exports.getLocaleFromDomain = getLocaleFromDomain;
|
|
81
|
+
exports.isLocaleExclusiveOnDomain = isLocaleExclusiveOnDomain;
|
|
82
|
+
//# sourceMappingURL=domainUtils.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"domainUtils.cjs","names":[],"sources":["../../../src/localization/domainUtils.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { RoutingConfig } from '@intlayer/types/config';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * The locale → domain map configured under `routing.domains`\n * (e.g. `{ en: 'intlayer.org', zh: 'intlayer.cn' }`).\n */\nexport type LocaleDomainMap = RoutingConfig['domains'];\n\n/**\n * Strips the protocol from a domain string and returns only the hostname.\n *\n * Example:\n *\n * ```ts\n * getDomainHostname('https://intlayer.cn') // 'intlayer.cn'\n * getDomainHostname('intlayer.cn') // 'intlayer.cn'\n * ```\n *\n * @param domain - A domain value from `routing.domains`, with or without protocol.\n * @returns The bare hostname.\n */\nexport const getDomainHostname = (domain: string): string => {\n try {\n return /^https?:\\/\\//.test(domain) ? new URL(domain).hostname : domain;\n } catch {\n return domain;\n }\n};\n\n/**\n * Returns the absolute origin for a domain value, prepending `https://`\n * when no protocol is present.\n *\n * Example:\n *\n * ```ts\n * getDomainOrigin('intlayer.cn') // 'https://intlayer.cn'\n * getDomainOrigin('http://intlayer.cn') // 'http://intlayer.cn'\n * ```\n *\n * @param domain - A domain value from `routing.domains`, with or without protocol.\n * @returns The origin usable as a URL base.\n */\nexport const getDomainOrigin = (domain: string): string =>\n /^https?:\\/\\//.test(domain) ? domain : `https://${domain}`;\n\n/**\n * Returns the locale exclusively mapped to a given hostname via `routing.domains`,\n * or `undefined` when zero or more than one locale share that hostname.\n *\n * Example: with `domains = { zh: 'intlayer.cn', en: 'intlayer.org', fr: 'intlayer.org' }`\n *\n * ```ts\n * getLocaleFromDomain('intlayer.cn', domains) // 'zh'\n * getLocaleFromDomain('intlayer.org', domains) // undefined (en and fr share it)\n * getLocaleFromDomain('example.com', domains) // undefined (not mapped)\n * ```\n *\n * @param hostname - The bare hostname of the incoming request.\n * @param domains - The configured locale → domain map.\n * @returns The exclusively mapped locale, or `undefined`.\n */\nexport const getLocaleFromDomain = (\n hostname: string,\n domains: LocaleDomainMap\n): Locale | undefined => {\n if (!domains) return undefined;\n\n const matchingLocales = Object.entries(domains).filter(\n ([, domain]) =>\n typeof domain === 'string' && getDomainHostname(domain) === hostname\n );\n\n return matchingLocales.length === 1\n ? (matchingLocales[0]?.[0] as Locale)\n : undefined;\n};\n\n/**\n * Checks whether a locale is the only locale mapped to its configured domain.\n * When true, the domain alone identifies the locale and no URL prefix is needed.\n * Hostnames are compared after protocol stripping, so\n * `{ en: 'https://intlayer.org', fr: 'intlayer.org' }` counts as a shared domain.\n *\n * @param locale - The locale to check.\n * @param domains - The configured locale → domain map.\n * @returns `true` when the locale has a domain shared with no other locale.\n */\nexport const isLocaleExclusiveOnDomain = (\n locale: LocalesValues,\n domains: LocaleDomainMap\n): boolean => {\n const localeDomain = domains?.[locale];\n\n if (!localeDomain) return false;\n\n const localeHostname = getDomainHostname(localeDomain);\n\n const localesOnSameDomain = Object.values(domains).filter(\n (domain) =>\n typeof domain === 'string' && getDomainHostname(domain) === localeHostname\n ).length;\n\n return localesOnSameDomain === 1;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAa,qBAAqB,WAA2B;AAC3D,KAAI;AACF,SAAO,eAAe,KAAK,OAAO,GAAG,IAAI,IAAI,OAAO,CAAC,WAAW;SAC1D;AACN,SAAO;;;;;;;;;;;;;;;;;AAkBX,MAAa,mBAAmB,WAC9B,eAAe,KAAK,OAAO,GAAG,SAAS,WAAW;;;;;;;;;;;;;;;;;AAkBpD,MAAa,uBACX,UACA,YACuB;AACvB,KAAI,CAAC,QAAS,QAAO;CAErB,MAAM,kBAAkB,OAAO,QAAQ,QAAQ,CAAC,QAC7C,GAAG,YACF,OAAO,WAAW,YAAY,kBAAkB,OAAO,KAAK,SAC/D;AAED,QAAO,gBAAgB,WAAW,IAC7B,gBAAgB,KAAK,KACtB;;;;;;;;;;;;AAaN,MAAa,6BACX,QACA,YACY;CACZ,MAAM,eAAe,UAAU;AAE/B,KAAI,CAAC,aAAc,QAAO;CAE1B,MAAM,iBAAiB,kBAAkB,aAAa;AAOtD,QAL4B,OAAO,OAAO,QAAQ,CAAC,QAChD,WACC,OAAO,WAAW,YAAY,kBAAkB,OAAO,KAAK,eAC/D,CAAC,WAE6B"}
|
|
@@ -2,19 +2,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
|
|
4
4
|
const require_localization_getPathWithoutLocale = require('./getPathWithoutLocale.cjs');
|
|
5
|
+
const require_localization_domainUtils = require('./domainUtils.cjs');
|
|
5
6
|
const require_localization_getPrefix = require('./getPrefix.cjs');
|
|
6
7
|
const require_localization_rewriteUtils = require('./rewriteUtils.cjs');
|
|
7
8
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
8
9
|
|
|
9
10
|
//#region src/localization/getLocalizedUrl.ts
|
|
10
|
-
/** Strips the protocol and returns the bare hostname of a domain string. */
|
|
11
|
-
const extractHostname = (domain) => {
|
|
12
|
-
try {
|
|
13
|
-
return /^https?:\/\//.test(domain) ? new URL(domain).hostname : domain;
|
|
14
|
-
} catch {
|
|
15
|
-
return domain;
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
11
|
/**
|
|
19
12
|
* Generate URL by prefixing the given URL with the referenced locale or adding search parameters
|
|
20
13
|
* based on the routing mode. Handles both absolute and relative URLs appropriately.
|
|
@@ -67,10 +60,10 @@ const getLocalizedUrl = (url, currentLocale = _intlayer_config_built.internation
|
|
|
67
60
|
const isAbsoluteUrl = require_utils_checkIsURLAbsolute.checkIsURLAbsolute(urlWithoutLocale);
|
|
68
61
|
const parsedUrl = isAbsoluteUrl ? new URL(urlWithoutLocale) : new URL(urlWithoutLocale, "http://example.com");
|
|
69
62
|
const translatedPathname = require_localization_rewriteUtils.getLocalizedPath(require_localization_rewriteUtils.getCanonicalPath(parsedUrl.pathname, void 0, rewriteRules), currentLocale, rewriteRules).path;
|
|
70
|
-
const detectedCurrentHostname = process.env.INTLAYER_ROUTING_DOMAINS !== "false" ?
|
|
63
|
+
const detectedCurrentHostname = process.env.INTLAYER_ROUTING_DOMAINS !== "false" ? require_localization_domainUtils.getDomainHostname(currentDomain ?? (isAbsoluteUrl ? parsedUrl.hostname : void 0) ?? (typeof window !== "undefined" ? window?.location?.hostname : void 0) ?? "") || null : null;
|
|
71
64
|
const localeDomain = process.env.INTLAYER_ROUTING_DOMAINS !== "false" ? domains?.[currentLocale] : void 0;
|
|
72
|
-
const localeDomainHostname = localeDomain ?
|
|
73
|
-
const normalizedDomain = localeDomainHostname !== null && detectedCurrentHostname
|
|
65
|
+
const localeDomainHostname = localeDomain ? require_localization_domainUtils.getDomainHostname(localeDomain) : null;
|
|
66
|
+
const normalizedDomain = localeDomainHostname !== null && (detectedCurrentHostname === null || localeDomainHostname !== detectedCurrentHostname) && localeDomain ? require_localization_domainUtils.getDomainOrigin(localeDomain) : null;
|
|
74
67
|
const baseUrl = normalizedDomain ? normalizedDomain : isAbsoluteUrl ? `${parsedUrl.protocol}//${parsedUrl.host}` : "";
|
|
75
68
|
if (!(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && mode === "search-params") {
|
|
76
69
|
const searchParams = new URLSearchParams(parsedUrl.search);
|