@intlayer/core 8.11.1 → 8.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +0 -1
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs +0 -1
- package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs.map +1 -1
- package/dist/cjs/formatters/compact.cjs +0 -1
- package/dist/cjs/formatters/compact.cjs.map +1 -1
- package/dist/cjs/formatters/currency.cjs +0 -1
- package/dist/cjs/formatters/currency.cjs.map +1 -1
- package/dist/cjs/formatters/date.cjs +0 -1
- package/dist/cjs/formatters/date.cjs.map +1 -1
- package/dist/cjs/formatters/list.cjs +0 -1
- package/dist/cjs/formatters/list.cjs.map +1 -1
- package/dist/cjs/formatters/number.cjs +0 -1
- package/dist/cjs/formatters/number.cjs.map +1 -1
- package/dist/cjs/formatters/percentage.cjs +0 -1
- package/dist/cjs/formatters/percentage.cjs.map +1 -1
- package/dist/cjs/formatters/relativeTime.cjs +0 -1
- package/dist/cjs/formatters/relativeTime.cjs.map +1 -1
- package/dist/cjs/formatters/units.cjs +0 -1
- package/dist/cjs/formatters/units.cjs.map +1 -1
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/interpreter/getCondition.cjs.map +1 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs +0 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
- package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
- package/dist/cjs/interpreter/getEnumeration.cjs.map +1 -1
- package/dist/cjs/interpreter/getGender.cjs.map +1 -1
- package/dist/cjs/interpreter/getIntlayer.cjs +0 -1
- package/dist/cjs/interpreter/getIntlayer.cjs.map +1 -1
- package/dist/cjs/interpreter/getNesting.cjs.map +1 -1
- package/dist/cjs/interpreter/getPlural.cjs.map +1 -1
- package/dist/cjs/interpreter/getTranslation.cjs.map +1 -1
- package/dist/cjs/localization/getBrowserLocale.cjs +0 -1
- package/dist/cjs/localization/getBrowserLocale.cjs.map +1 -1
- package/dist/cjs/localization/getLocale.cjs +0 -1
- package/dist/cjs/localization/getLocale.cjs.map +1 -1
- package/dist/cjs/localization/getLocalizedUrl.cjs +0 -1
- package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
- package/dist/cjs/localization/getPathWithoutLocale.cjs +0 -1
- package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
- package/dist/cjs/localization/getPrefix.cjs +0 -1
- package/dist/cjs/localization/getPrefix.cjs.map +1 -1
- package/dist/cjs/localization/localeMapper.cjs +0 -1
- package/dist/cjs/localization/localeMapper.cjs.map +1 -1
- package/dist/cjs/localization/localeResolver.cjs +0 -1
- package/dist/cjs/localization/localeResolver.cjs.map +1 -1
- package/dist/cjs/markdown/compiler.cjs +53 -31
- package/dist/cjs/markdown/compiler.cjs.map +1 -1
- package/dist/cjs/markdown/index.cjs +2 -0
- package/dist/cjs/transpiler/condition/condition.cjs +0 -1
- package/dist/cjs/transpiler/condition/condition.cjs.map +1 -1
- package/dist/cjs/transpiler/enumeration/enumeration.cjs +0 -1
- package/dist/cjs/transpiler/enumeration/enumeration.cjs.map +1 -1
- package/dist/cjs/transpiler/file/file.cjs +0 -1
- package/dist/cjs/transpiler/file/file.cjs.map +1 -1
- package/dist/cjs/transpiler/gender/gender.cjs +0 -1
- package/dist/cjs/transpiler/gender/gender.cjs.map +1 -1
- package/dist/cjs/transpiler/html/html.cjs +0 -1
- package/dist/cjs/transpiler/html/html.cjs.map +1 -1
- package/dist/cjs/transpiler/insertion/insertion.cjs +0 -1
- package/dist/cjs/transpiler/insertion/insertion.cjs.map +1 -1
- package/dist/cjs/transpiler/markdown/markdown.cjs +0 -1
- package/dist/cjs/transpiler/markdown/markdown.cjs.map +1 -1
- package/dist/cjs/transpiler/nesting/nesting.cjs +0 -1
- package/dist/cjs/transpiler/nesting/nesting.cjs.map +1 -1
- package/dist/cjs/transpiler/plural/plural.cjs +0 -1
- package/dist/cjs/transpiler/plural/plural.cjs.map +1 -1
- package/dist/cjs/transpiler/translation/translation.cjs +0 -1
- package/dist/cjs/transpiler/translation/translation.cjs.map +1 -1
- package/dist/cjs/utils/intl.cjs +0 -1
- package/dist/cjs/utils/intl.cjs.map +1 -1
- package/dist/cjs/utils/localeStorage.cjs +0 -1
- package/dist/cjs/utils/localeStorage.cjs.map +1 -1
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/interpreter/getCondition.mjs.map +1 -1
- package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
- package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
- package/dist/esm/interpreter/getEnumeration.mjs.map +1 -1
- package/dist/esm/interpreter/getGender.mjs.map +1 -1
- package/dist/esm/interpreter/getIntlayer.mjs.map +1 -1
- package/dist/esm/interpreter/getNesting.mjs.map +1 -1
- package/dist/esm/interpreter/getPlural.mjs.map +1 -1
- package/dist/esm/interpreter/getTranslation.mjs.map +1 -1
- package/dist/esm/markdown/compiler.mjs +44 -24
- package/dist/esm/markdown/compiler.mjs.map +1 -1
- package/dist/esm/markdown/index.mjs +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/interpreter/getCondition.d.ts +1 -1
- package/dist/types/interpreter/getCondition.d.ts.map +1 -1
- package/dist/types/interpreter/getContent/getContent.d.ts +1 -1
- package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
- package/dist/types/interpreter/getDictionary.d.ts +1 -1
- package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
- package/dist/types/interpreter/getEnumeration.d.ts +2 -2
- package/dist/types/interpreter/getEnumeration.d.ts.map +1 -1
- package/dist/types/interpreter/getGender.d.ts +1 -1
- package/dist/types/interpreter/getGender.d.ts.map +1 -1
- package/dist/types/interpreter/getIntlayer.d.ts +1 -1
- package/dist/types/interpreter/getIntlayer.d.ts.map +1 -1
- package/dist/types/interpreter/getNesting.d.ts +1 -1
- package/dist/types/interpreter/getNesting.d.ts.map +1 -1
- package/dist/types/interpreter/getPlural.d.ts +1 -1
- package/dist/types/interpreter/getPlural.d.ts.map +1 -1
- package/dist/types/interpreter/getTranslation.d.ts +1 -1
- package/dist/types/interpreter/getTranslation.d.ts.map +1 -1
- package/dist/types/localization/getPrefix.d.ts +5 -5
- package/dist/types/localization/getPrefix.d.ts.map +1 -1
- package/dist/types/markdown/compiler.d.ts +12 -1
- package/dist/types/markdown/compiler.d.ts.map +1 -1
- package/dist/types/markdown/index.d.ts +2 -2
- package/package.json +7 -7
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_deepTransformPlugins_getMultilingualDictionary = require('../deepTransformPlugins/getMultilingualDictionary.cjs');
|
|
4
3
|
const require_dictionaryManipulator_getNodeType = require('./getNodeType.cjs');
|
|
5
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeDictionaries.cjs","names":["getNodeType","getMultilingualDictionary"],"sources":["../../../src/dictionaryManipulator/mergeDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport { getMultilingualDictionary } from '../deepTransformPlugins';\nimport { getNodeType } from './getNodeType';\n\n// Extended type that includes arrays for internal merge operations\ntype MergeableContent = ContentNode | ContentNode[];\n\nconst checkTypesMatch = (\n object1: ContentNode,\n object2: ContentNode,\n object2LocalId: LocalDictionaryId | undefined,\n dictionaryKey: string,\n path: string[] = []\n): void => {\n const appLogger = getAppLogger({ log });\n\n // If either side is missing/undefined, allow merge without error\n if (\n object1 === undefined ||\n object1 === null ||\n object2 === undefined ||\n object2 === null\n )\n return;\n\n const type1 = getNodeType(object1);\n const type2 = getNodeType(object2);\n\n // Unknown types are treated as flexible; skip strict mismatch reporting\n if (type1 === 'unknown' || type2 === 'unknown') return;\n\n if (type1 !== type2) {\n appLogger(\n [\n `Error: Dictionary ${colorizeKey(dictionaryKey)} has a multiple content files with type mismatch at path \"${path.join('.')}\": Cannot merge ${type1} with ${type2} while merging ${object2LocalId}`,\n ],\n {\n level: 'error',\n }\n );\n\n return;\n }\n};\n\n// Custom merge function that prefers destination (first dictionary) values\nconst customMerge = (\n destination: ContentNode,\n source: ContentNode\n): MergeableContent => {\n // If destination is undefined/null, use source\n if (destination === undefined || destination === null) {\n return source;\n }\n\n // If source is undefined/null, use destination\n if (source === undefined || source === null) {\n return destination;\n }\n\n // For primitive values, prefer destination (first dictionary)\n if (typeof destination !== 'object' || typeof source !== 'object') {\n return destination;\n }\n\n // For arrays, use our custom array merge\n if (Array.isArray(destination) && Array.isArray(source)) {\n return arrayMerge(\n destination as ContentNode[],\n source as ContentNode[]\n ) as MergeableContent;\n }\n\n // For objects, recursively merge with our custom logic\n if (typeof destination === 'object' && typeof source === 'object') {\n const result: Record<string, MergeableContent> = {};\n const allKeys = new Set([\n ...Object.keys(destination as unknown as Record<string, ContentNode>),\n ...Object.keys(source as unknown as Record<string, ContentNode>),\n ]);\n\n for (const key of allKeys) {\n result[key] = customMerge(\n (destination as unknown as Record<string, ContentNode>)[key],\n (source as unknown as Record<string, ContentNode>)[key]\n );\n }\n\n return result as unknown as MergeableContent;\n }\n\n // Fallback to destination\n return destination;\n};\n\n// Custom array merge strategy that merges arrays by key when present, otherwise by index\nconst arrayMerge = (\n destinationArray: ContentNode[],\n sourceArray: ContentNode[]\n): MergeableContent[] => {\n // Check if both arrays contain only primitives\n const destHasOnlyPrimitives = destinationArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n const sourceHasOnlyPrimitives = sourceArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n\n // If both arrays contain only primitives, use the source array (second dictionary)\n if (destHasOnlyPrimitives && sourceHasOnlyPrimitives) {\n return sourceArray;\n }\n\n // Otherwise, merge by index with object merging logic\n const result: MergeableContent[] = [];\n const maxLength = Math.max(destinationArray.length, sourceArray.length);\n\n for (let i = 0; i < maxLength; i++) {\n const destItem = destinationArray[i];\n const sourceItem = sourceArray[i];\n\n if (destItem === undefined && sourceItem === undefined) {\n } else if (destItem === undefined) {\n // Only source exists, add it\n result.push(sourceItem);\n } else if (sourceItem === undefined) {\n // Only destination exists, add it\n result.push(destItem);\n } else {\n // Both exist, merge them\n if (\n typeof destItem === 'object' &&\n typeof sourceItem === 'object' &&\n destItem !== null &&\n sourceItem !== null\n ) {\n // Check if both objects have a 'key' property for keyed merging\n if (\n 'key' in destItem &&\n 'key' in sourceItem &&\n (destItem as Record<string, string>).key ===\n (sourceItem as Record<string, string>).key\n ) {\n // Merge objects with same key, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n } else {\n // Merge objects by index, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n }\n } else {\n // For primitives or non-objects, use destination value (first dictionary)\n result.push(destItem);\n }\n }\n }\n\n return result;\n};\n\nexport const mergeDictionaries = (dictionaries: Dictionary[]): Dictionary => {\n const localIds = Array.from(\n new Set<LocalDictionaryId>(\n dictionaries.filter((dict) => dict.localId).map((dict) => dict.localId!)\n )\n );\n\n 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 // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n const currentDictionary = getMultilingualDictionary(dictionaries[i]);\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":"
|
|
1
|
+
{"version":3,"file":"mergeDictionaries.cjs","names":["getNodeType","getMultilingualDictionary"],"sources":["../../../src/dictionaryManipulator/mergeDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport { getMultilingualDictionary } from '../deepTransformPlugins';\nimport { getNodeType } from './getNodeType';\n\n// Extended type that includes arrays for internal merge operations\ntype MergeableContent = ContentNode | ContentNode[];\n\nconst checkTypesMatch = (\n object1: ContentNode,\n object2: ContentNode,\n object2LocalId: LocalDictionaryId | undefined,\n dictionaryKey: string,\n path: string[] = []\n): void => {\n const appLogger = getAppLogger({ log });\n\n // If either side is missing/undefined, allow merge without error\n if (\n object1 === undefined ||\n object1 === null ||\n object2 === undefined ||\n object2 === null\n )\n return;\n\n const type1 = getNodeType(object1);\n const type2 = getNodeType(object2);\n\n // Unknown types are treated as flexible; skip strict mismatch reporting\n if (type1 === 'unknown' || type2 === 'unknown') return;\n\n if (type1 !== type2) {\n appLogger(\n [\n `Error: Dictionary ${colorizeKey(dictionaryKey)} has a multiple content files with type mismatch at path \"${path.join('.')}\": Cannot merge ${type1} with ${type2} while merging ${object2LocalId}`,\n ],\n {\n level: 'error',\n }\n );\n\n return;\n }\n};\n\n// Custom merge function that prefers destination (first dictionary) values\nconst customMerge = (\n destination: ContentNode,\n source: ContentNode\n): MergeableContent => {\n // If destination is undefined/null, use source\n if (destination === undefined || destination === null) {\n return source;\n }\n\n // If source is undefined/null, use destination\n if (source === undefined || source === null) {\n return destination;\n }\n\n // For primitive values, prefer destination (first dictionary)\n if (typeof destination !== 'object' || typeof source !== 'object') {\n return destination;\n }\n\n // For arrays, use our custom array merge\n if (Array.isArray(destination) && Array.isArray(source)) {\n return arrayMerge(\n destination as ContentNode[],\n source as ContentNode[]\n ) as MergeableContent;\n }\n\n // For objects, recursively merge with our custom logic\n if (typeof destination === 'object' && typeof source === 'object') {\n const result: Record<string, MergeableContent> = {};\n const allKeys = new Set([\n ...Object.keys(destination as unknown as Record<string, ContentNode>),\n ...Object.keys(source as unknown as Record<string, ContentNode>),\n ]);\n\n for (const key of allKeys) {\n result[key] = customMerge(\n (destination as unknown as Record<string, ContentNode>)[key],\n (source as unknown as Record<string, ContentNode>)[key]\n );\n }\n\n return result as unknown as MergeableContent;\n }\n\n // Fallback to destination\n return destination;\n};\n\n// Custom array merge strategy that merges arrays by key when present, otherwise by index\nconst arrayMerge = (\n destinationArray: ContentNode[],\n sourceArray: ContentNode[]\n): MergeableContent[] => {\n // Check if both arrays contain only primitives\n const destHasOnlyPrimitives = destinationArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n const sourceHasOnlyPrimitives = sourceArray.every(\n (item) => typeof item !== 'object' || item === null\n );\n\n // If both arrays contain only primitives, use the source array (second dictionary)\n if (destHasOnlyPrimitives && sourceHasOnlyPrimitives) {\n return sourceArray;\n }\n\n // Otherwise, merge by index with object merging logic\n const result: MergeableContent[] = [];\n const maxLength = Math.max(destinationArray.length, sourceArray.length);\n\n for (let i = 0; i < maxLength; i++) {\n const destItem = destinationArray[i];\n const sourceItem = sourceArray[i];\n\n if (destItem === undefined && sourceItem === undefined) {\n } else if (destItem === undefined) {\n // Only source exists, add it\n result.push(sourceItem);\n } else if (sourceItem === undefined) {\n // Only destination exists, add it\n result.push(destItem);\n } else {\n // Both exist, merge them\n if (\n typeof destItem === 'object' &&\n typeof sourceItem === 'object' &&\n destItem !== null &&\n sourceItem !== null\n ) {\n // Check if both objects have a 'key' property for keyed merging\n if (\n 'key' in destItem &&\n 'key' in sourceItem &&\n (destItem as Record<string, string>).key ===\n (sourceItem as Record<string, string>).key\n ) {\n // Merge objects with same key, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n } else {\n // Merge objects by index, preferring destination (first dictionary) values\n result.push(customMerge(destItem, sourceItem));\n }\n } else {\n // For primitives or non-objects, use destination value (first dictionary)\n result.push(destItem);\n }\n }\n }\n\n return result;\n};\n\nexport const mergeDictionaries = (dictionaries: Dictionary[]): Dictionary => {\n const localIds = Array.from(\n new Set<LocalDictionaryId>(\n dictionaries.filter((dict) => dict.localId).map((dict) => dict.localId!)\n )\n );\n\n 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 // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n const currentDictionary = getMultilingualDictionary(dictionaries[i]);\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,sDAAyB,EAAE,gCAAI,CAAC;CAGtC,IACE,YAAY,UACZ,YAAY,QACZ,YAAY,UACZ,YAAY,MAEZ;CAEF,MAAM,QAAQA,sDAAY,OAAO;CACjC,MAAM,QAAQA,sDAAY,OAAO;CAGjC,IAAI,UAAU,aAAa,UAAU,WAAW;CAEhD,IAAI,UAAU,OAAO;EACnB,UACE,CACE,8DAAiC,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,WAAW,UAAa,WAAW,MACrC,OAAO;CAIT,IAAI,OAAO,gBAAgB,YAAY,OAAO,WAAW,UACvD,OAAO;CAIT,IAAI,MAAM,QAAQ,WAAW,KAAK,MAAM,QAAQ,MAAM,GACpD,OAAO,WACL,aACA,MACF;CAIF,IAAI,OAAO,gBAAgB,YAAY,OAAO,WAAW,UAAU;EACjE,MAAM,SAA2C,CAAC;EAClD,MAAM,UAAU,IAAI,IAAI,CACtB,GAAG,OAAO,KAAK,WAAqD,GACpE,GAAG,OAAO,KAAK,MAAgD,CACjE,CAAC;EAED,KAAK,MAAM,OAAO,SAChB,OAAO,OAAO,YACX,YAAuD,MACvD,OAAkD,IACrD;EAGF,OAAO;CACT;CAGA,OAAO;AACT;AAGA,MAAM,cACJ,kBACA,gBACuB;CAEvB,MAAM,wBAAwB,iBAAiB,OAC5C,SAAS,OAAO,SAAS,YAAY,SAAS,IACjD;CACA,MAAM,0BAA0B,YAAY,OACzC,SAAS,OAAO,SAAS,YAAY,SAAS,IACjD;CAGA,IAAI,yBAAyB,yBAC3B,OAAO;CAIT,MAAM,SAA6B,CAAC;CACpC,MAAM,YAAY,KAAK,IAAI,iBAAiB,QAAQ,YAAY,MAAM;CAEtE,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,KAAK;EAClC,MAAM,WAAW,iBAAiB;EAClC,MAAM,aAAa,YAAY;EAE/B,IAAI,aAAa,UAAa,eAAe,QAAW,CACxD,OAAO,IAAI,aAAa,QAEtB,OAAO,KAAK,UAAU;OACjB,IAAI,eAAe,QAExB,OAAO,KAAK,QAAQ;OAGpB,IACE,OAAO,aAAa,YACpB,OAAO,eAAe,YACtB,aAAa,QACb,eAAe,MAGf,IACE,SAAS,YACT,SAAS,cACR,SAAoC,QAClC,WAAsC,KAGzC,OAAO,KAAK,YAAY,UAAU,UAAU,CAAC;OAG7C,OAAO,KAAK,YAAY,UAAU,UAAU,CAAC;OAI/C,OAAO,KAAK,QAAQ;CAG1B;CAEA,OAAO;AACT;AAEA,MAAa,qBAAqB,iBAA2C;CAC3E,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aAAa,QAAQ,SAAS,KAAK,OAAO,EAAE,KAAK,SAAS,KAAK,OAAQ,CACzE,CACF;CAEA,MAAM,mBAAmB,aAAa,KAAK,SAAS,KAAK,GAAG;CAG5D,IAAI,IAAI,IAAI,gBAAgB,EAAE,SAAS,GACrC,MAAM,IAAI,MAAM,yCAAyC;CAG3D,IAAI,gBAAuC,aAAa,GAAG;CAE3D,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;EAE5C,MAAM,oBAAoBC,iFAA0B,aAAa,EAAE;EAGnE,gBACE,eACA,kBAAkB,SAClB,kBAAkB,SAClB,kBAAkB,KAClB,CAAC,CACH;EAEA,gBAAgB,YACd,eACA,kBAAkB,OACpB;CACF;CAQA,OAAO;EALL,KAAK,aAAa,GAAG;EACrB,SAAS;EACT;CAGoB;AACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orderDictionaries.cjs","names":["editor"],"sources":["../../../src/dictionaryManipulator/orderDictionaries.ts"],"sourcesContent":["import { editor } from '@intlayer/config/built';\nimport type { Dictionary } from '@intlayer/types/dictionary';\n\n/**\n * Orders dictionaries based on the dictionary priority strategy.\n *\n * @param dictionaries - Array of dictionaries to order\n * @param priorityStrategy - The priority strategy ('local_first' or 'distant_first')\n * @returns Ordered array of dictionaries\n */\nexport const orderDictionaries = (\n dictionaries: Dictionary[],\n config?: {\n editor: {\n dictionaryPriorityStrategy: 'local_first' | 'distant_first';\n };\n }\n): Dictionary[] => {\n const dictionaryPriorityStrategy =\n config?.editor?.dictionaryPriorityStrategy ??\n editor.dictionaryPriorityStrategy;\n\n if (dictionaries.length <= 1) {\n return dictionaries;\n }\n\n // Stabilize original indices to preserve relative order for complete ties\n const withIndex = dictionaries.map((dictionary, index) => ({\n dictionary,\n index,\n }));\n\n const getPriority = (dictionary: Dictionary): number => {\n const p = dictionary.priority ?? 0;\n\n return Number.isFinite(p) ? p : 0;\n };\n\n const getLocationWeight = (d: Dictionary): number => {\n const location = d.location;\n\n // undefined location should always be last\n if (location === undefined) {\n return 2;\n }\n\n if (dictionaryPriorityStrategy === 'distant_first') {\n // distant should come first\n return location === 'remote' ? 0 : 1;\n }\n // default: local_first\n return location === 'local' ? 0 : 1;\n };\n\n withIndex.sort((a, b) => {\n // 1) Non-autoFilled before autoFilled (autoFilled have lower precedence)\n const aAuto = a.dictionary.filled ? 1 : 0;\n const bAuto = b.dictionary.filled ? 1 : 0;\n if (aAuto !== bAuto) return aAuto - bAuto; // 0 before 1\n\n // 2) Higher priority first (larger number wins)\n const aP = getPriority(a.dictionary);\n const bP = getPriority(b.dictionary);\n if (aP !== bP) return bP - aP; // descending\n\n // 3) Location according to strategy\n const aLocation = getLocationWeight(a.dictionary);\n const bLocation = getLocationWeight(b.dictionary);\n if (aLocation !== bLocation) return aLocation - bLocation;\n\n // 4) Stable fallback by original index\n return a.index - b.index;\n });\n\n return withIndex.map(({ dictionary }) => dictionary);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"orderDictionaries.cjs","names":["editor"],"sources":["../../../src/dictionaryManipulator/orderDictionaries.ts"],"sourcesContent":["import { editor } from '@intlayer/config/built';\nimport type { Dictionary } from '@intlayer/types/dictionary';\n\n/**\n * Orders dictionaries based on the dictionary priority strategy.\n *\n * @param dictionaries - Array of dictionaries to order\n * @param priorityStrategy - The priority strategy ('local_first' or 'distant_first')\n * @returns Ordered array of dictionaries\n */\nexport const orderDictionaries = (\n dictionaries: Dictionary[],\n config?: {\n editor: {\n dictionaryPriorityStrategy: 'local_first' | 'distant_first';\n };\n }\n): Dictionary[] => {\n const dictionaryPriorityStrategy =\n config?.editor?.dictionaryPriorityStrategy ??\n editor.dictionaryPriorityStrategy;\n\n if (dictionaries.length <= 1) {\n return dictionaries;\n }\n\n // Stabilize original indices to preserve relative order for complete ties\n const withIndex = dictionaries.map((dictionary, index) => ({\n dictionary,\n index,\n }));\n\n const getPriority = (dictionary: Dictionary): number => {\n const p = dictionary.priority ?? 0;\n\n return Number.isFinite(p) ? p : 0;\n };\n\n const getLocationWeight = (d: Dictionary): number => {\n const location = d.location;\n\n // undefined location should always be last\n if (location === undefined) {\n return 2;\n }\n\n if (dictionaryPriorityStrategy === 'distant_first') {\n // distant should come first\n return location === 'remote' ? 0 : 1;\n }\n // default: local_first\n return location === 'local' ? 0 : 1;\n };\n\n withIndex.sort((a, b) => {\n // 1) Non-autoFilled before autoFilled (autoFilled have lower precedence)\n const aAuto = a.dictionary.filled ? 1 : 0;\n const bAuto = b.dictionary.filled ? 1 : 0;\n if (aAuto !== bAuto) return aAuto - bAuto; // 0 before 1\n\n // 2) Higher priority first (larger number wins)\n const aP = getPriority(a.dictionary);\n const bP = getPriority(b.dictionary);\n if (aP !== bP) return bP - aP; // descending\n\n // 3) Location according to strategy\n const aLocation = getLocationWeight(a.dictionary);\n const bLocation = getLocationWeight(b.dictionary);\n if (aLocation !== bLocation) return aLocation - bLocation;\n\n // 4) Stable fallback by original index\n return a.index - b.index;\n });\n\n return withIndex.map(({ dictionary }) => dictionary);\n};\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,qBACX,cACA,WAKiB;CACjB,MAAM,6BACJ,QAAQ,QAAQ,8BAChBA,8BAAO;CAET,IAAI,aAAa,UAAU,GACzB,OAAO;CAIT,MAAM,YAAY,aAAa,KAAK,YAAY,WAAW;EACzD;EACA;CACF,EAAE;CAEF,MAAM,eAAe,eAAmC;EACtD,MAAM,IAAI,WAAW,YAAY;EAEjC,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;CAClC;CAEA,MAAM,qBAAqB,MAA0B;EACnD,MAAM,WAAW,EAAE;EAGnB,IAAI,aAAa,QACf,OAAO;EAGT,IAAI,+BAA+B,iBAEjC,OAAO,aAAa,WAAW,IAAI;EAGrC,OAAO,aAAa,UAAU,IAAI;CACpC;CAEA,UAAU,MAAM,GAAG,MAAM;EAEvB,MAAM,QAAQ,EAAE,WAAW,SAAS,IAAI;EACxC,MAAM,QAAQ,EAAE,WAAW,SAAS,IAAI;EACxC,IAAI,UAAU,OAAO,OAAO,QAAQ;EAGpC,MAAM,KAAK,YAAY,EAAE,UAAU;EACnC,MAAM,KAAK,YAAY,EAAE,UAAU;EACnC,IAAI,OAAO,IAAI,OAAO,KAAK;EAG3B,MAAM,YAAY,kBAAkB,EAAE,UAAU;EAChD,MAAM,YAAY,kBAAkB,EAAE,UAAU;EAChD,IAAI,cAAc,WAAW,OAAO,YAAY;EAGhD,OAAO,EAAE,QAAQ,EAAE;CACrB,CAAC;CAED,OAAO,UAAU,KAAK,EAAE,iBAAiB,UAAU;AACrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compact.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/compact.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value using compact notation (e.g., 1K, 1M, 1B)\n * based on locale and formatting options.\n *\n * @example\n * compact(1200); // \"1.2K\"\n *\n * @example\n * compact(\"1000000\", { locale: Locales.FRENCH, compactDisplay: \"long\" });\n * // \"1 million\"\n */\nexport const compact = (\n value: string | number,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n ...options,\n notation: 'compact',\n }\n ).format(Number(value));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"compact.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/compact.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value using compact notation (e.g., 1K, 1M, 1B)\n * based on locale and formatting options.\n *\n * @example\n * compact(1200); // \"1.2K\"\n *\n * @example\n * compact(\"1000000\", { locale: Locales.FRENCH, compactDisplay: \"long\" });\n * // \"1 million\"\n */\nexport const compact = (\n value: string | number,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n ...options,\n notation: 'compact',\n }\n ).format(Number(value));\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,WACX,OACA,YAEAA,iCACE,KAAK,cACL,SAAS,UAAUC,6CAAsB,eAEzC;CACE,GAAG;CACH,UAAU;AACZ,CACF,EAAE,OAAO,OAAO,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/currency.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric or string value into a localized currency string using the Intl API.\n *\n * @example\n * currency(1234.5, { currency: 'EUR' });\n * // \"€1,234.50\"\n *\n * @example\n * currency(\"5000\", { locale: Locales.FRENCH, currency: \"CAD\", currencyDisplay: \"code\" });\n * // \"5 000,00 CAD\"\n */\nexport const currency = (\n value: string | number,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n style: 'currency',\n currency: options?.currency ?? 'USD',\n currencyDisplay: options?.currencyDisplay ?? 'symbol',\n minimumFractionDigits: options?.minimumFractionDigits ?? 2,\n maximumFractionDigits: options?.maximumFractionDigits ?? 2,\n ...options,\n }\n ).format(Number(value));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"currency.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/currency.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric or string value into a localized currency string using the Intl API.\n *\n * @example\n * currency(1234.5, { currency: 'EUR' });\n * // \"€1,234.50\"\n *\n * @example\n * currency(\"5000\", { locale: Locales.FRENCH, currency: \"CAD\", currencyDisplay: \"code\" });\n * // \"5 000,00 CAD\"\n */\nexport const currency = (\n value: string | number,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n style: 'currency',\n currency: options?.currency ?? 'USD',\n currencyDisplay: options?.currencyDisplay ?? 'symbol',\n minimumFractionDigits: options?.minimumFractionDigits ?? 2,\n maximumFractionDigits: options?.maximumFractionDigits ?? 2,\n ...options,\n }\n ).format(Number(value));\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,YACX,OACA,YAEAA,iCACE,KAAK,cACL,SAAS,UAAUC,6CAAsB,eAEzC;CACE,OAAO;CACP,UAAU,SAAS,YAAY;CAC/B,iBAAiB,SAAS,mBAAmB;CAC7C,uBAAuB,SAAS,yBAAyB;CACzD,uBAAuB,SAAS,yBAAyB;CACzD,GAAG;AACL,CACF,EAAE,OAAO,OAAO,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"date.cjs","names":["internationalization","getCachedIntl"],"sources":["../../../src/formatters/date.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\nexport type DateTimePreset =\n | 'short'\n | 'long'\n | 'dateOnly'\n | 'timeOnly'\n | 'full';\n\nexport const presets: Record<DateTimePreset, Intl.DateTimeFormatOptions> = {\n short: {\n year: '2-digit',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n },\n long: {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n },\n full: {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n hour12: false,\n },\n dateOnly: {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n timeOnly: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n },\n};\n\n/**\n * Formats a date/time value into a localized string using Intl.DateTimeFormat.\n *\n * @example\n * date(new Date('2025-08-02T14:30:00Z'), { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });\n * // \"08/02/25, 14:30\"\n *\n * @example\n * date(\"2025-08-02T14:30:00Z\", { locale: Locales.FRENCH, month: \"long\", day: \"numeric\" });\n * // \"2 août\"\n */\nexport const date = (\n date: Date | string | number,\n options?:\n | (Intl.DateTimeFormatOptions & { locale?: LocalesValues })\n | DateTimePreset\n): string => {\n const dateTime = new Date(date);\n\n const resolvedOptions =\n typeof options === 'string' ? (presets[options] ?? {}) : options;\n\n const locale =\n (typeof options === 'object' ? options?.locale : undefined) ??\n internationalization?.defaultLocale;\n\n const formatter = getCachedIntl(Intl.DateTimeFormat, locale, resolvedOptions);\n\n return formatter.format(dateTime);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"date.cjs","names":["internationalization","getCachedIntl"],"sources":["../../../src/formatters/date.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\nexport type DateTimePreset =\n | 'short'\n | 'long'\n | 'dateOnly'\n | 'timeOnly'\n | 'full';\n\nexport const presets: Record<DateTimePreset, Intl.DateTimeFormatOptions> = {\n short: {\n year: '2-digit',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n },\n long: {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n },\n full: {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n hour12: false,\n },\n dateOnly: {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n timeOnly: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n },\n};\n\n/**\n * Formats a date/time value into a localized string using Intl.DateTimeFormat.\n *\n * @example\n * date(new Date('2025-08-02T14:30:00Z'), { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });\n * // \"08/02/25, 14:30\"\n *\n * @example\n * date(\"2025-08-02T14:30:00Z\", { locale: Locales.FRENCH, month: \"long\", day: \"numeric\" });\n * // \"2 août\"\n */\nexport const date = (\n date: Date | string | number,\n options?:\n | (Intl.DateTimeFormatOptions & { locale?: LocalesValues })\n | DateTimePreset\n): string => {\n const dateTime = new Date(date);\n\n const resolvedOptions =\n typeof options === 'string' ? (presets[options] ?? {}) : options;\n\n const locale =\n (typeof options === 'object' ? options?.locale : undefined) ??\n internationalization?.defaultLocale;\n\n const formatter = getCachedIntl(Intl.DateTimeFormat, locale, resolvedOptions);\n\n return formatter.format(dateTime);\n};\n"],"mappings":";;;;;AAWA,MAAa,UAA8D;CACzE,OAAO;EACL,MAAM;EACN,OAAO;EACP,KAAK;EACL,MAAM;EACN,QAAQ;CACV;CACA,MAAM;EACJ,MAAM;EACN,OAAO;EACP,KAAK;EACL,MAAM;EACN,QAAQ;CACV;CACA,MAAM;EACJ,MAAM;EACN,OAAO;EACP,KAAK;EACL,MAAM;EACN,QAAQ;EACR,QAAQ;CACV;CACA,UAAU;EACR,MAAM;EACN,OAAO;EACP,KAAK;CACP;CACA,UAAU;EACR,MAAM;EACN,QAAQ;EACR,QAAQ;CACV;AACF;;;;;;;;;;;;AAaA,MAAa,QACX,MACA,YAGW;CACX,MAAM,WAAW,IAAI,KAAK,IAAI;CAE9B,MAAM,kBACJ,OAAO,YAAY,WAAY,QAAQ,YAAY,CAAC,IAAK;CAE3D,MAAM,UACH,OAAO,YAAY,WAAW,SAAS,SAAS,WACjDA,6CAAsB;CAIxB,OAFkBC,iCAAc,KAAK,gBAAgB,QAAQ,eAE9C,EAAE,OAAO,QAAQ;AAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/list.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/** Locally defined subset of Intl.ListFormatOptions so consumers don't need ES2021.Intl in their lib. */\ntype ListFormatOptions = {\n localeMatcher?: 'lookup' | 'best fit';\n type?: 'conjunction' | 'disjunction' | 'unit';\n style?: 'long' | 'short' | 'narrow';\n};\n\n/**\n * Formats an array of values into a localized list string using the Intl API.\n *\n * @example\n * list(['apple', 'banana', 'orange']);\n * // \"apple, banana, and orange\"\n *\n * @example\n * list(['red', 'green', 'blue'], { locale: Locales.FRENCH, type: 'disjunction' });\n * // \"rouge, vert ou bleu\"\n *\n * @example\n * list([1, 2, 3], { type: 'unit' });\n * // \"1, 2, 3\"\n */\nexport const list = (\n values: (string | number)[],\n options?: ListFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n (Intl as any).ListFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n type: options?.type ?? 'conjunction',\n style: options?.style ?? 'long',\n ...options,\n }\n ).format(values.map(String));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"list.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/list.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/** Locally defined subset of Intl.ListFormatOptions so consumers don't need ES2021.Intl in their lib. */\ntype ListFormatOptions = {\n localeMatcher?: 'lookup' | 'best fit';\n type?: 'conjunction' | 'disjunction' | 'unit';\n style?: 'long' | 'short' | 'narrow';\n};\n\n/**\n * Formats an array of values into a localized list string using the Intl API.\n *\n * @example\n * list(['apple', 'banana', 'orange']);\n * // \"apple, banana, and orange\"\n *\n * @example\n * list(['red', 'green', 'blue'], { locale: Locales.FRENCH, type: 'disjunction' });\n * // \"rouge, vert ou bleu\"\n *\n * @example\n * list([1, 2, 3], { type: 'unit' });\n * // \"1, 2, 3\"\n */\nexport const list = (\n values: (string | number)[],\n options?: ListFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n (Intl as any).ListFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n type: options?.type ?? 'conjunction',\n style: options?.style ?? 'long',\n ...options,\n }\n ).format(values.map(String));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,QACX,QACA,YAEAA,iCACG,KAAa,YACd,SAAS,UAAUC,6CAAsB,eAEzC;CACE,MAAM,SAAS,QAAQ;CACvB,OAAO,SAAS,SAAS;CACzB,GAAG;AACL,CACF,EAAE,OAAO,OAAO,IAAI,MAAM,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/number.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value using locale-aware formatting.\n *\n * @example\n * number(123456.789); // \"123,456.789\"\n *\n * @example\n * number(\"1000000\", { locale: Locales.FRENCH }); // \"1 000 000\"\n */\nexport const number = (\n value: string | number,\n {\n locale,\n ...options\n }: Intl.NumberFormatOptions & { locale?: LocalesValues } = {}\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n locale ?? internationalization?.defaultLocale,\n\n options\n ).format(Number(value));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"number.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/number.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value using locale-aware formatting.\n *\n * @example\n * number(123456.789); // \"123,456.789\"\n *\n * @example\n * number(\"1000000\", { locale: Locales.FRENCH }); // \"1 000 000\"\n */\nexport const number = (\n value: string | number,\n {\n locale,\n ...options\n }: Intl.NumberFormatOptions & { locale?: LocalesValues } = {}\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n locale ?? internationalization?.defaultLocale,\n\n options\n ).format(Number(value));\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAa,UACX,OACA,EACE,QACA,GAAG,YACsD,CAAC,MAE5DA,iCACE,KAAK,cACL,UAAUC,6CAAsB,eAEhC,OACF,EAAE,OAAO,OAAO,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"percentage.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/percentage.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a number as a percentage string (e.g., 0.25 → \"25%\").\n *\n * @example\n * percentage(0.25); // \"25%\"\n *\n * @example\n * percentage(0.25, { minimumFractionDigits: 2 }); // \"25.00%\"\n */\nexport const percentage = (\n value: string | number,\n {\n locale,\n ...options\n }: Intl.NumberFormatOptions & { locale?: LocalesValues } = {}\n): string => {\n let numericValue = Number(value);\n\n // Normalize: if user passes 10, treat it as 10% instead of 1000%\n if (numericValue > 1) {\n numericValue /= 100;\n }\n\n const formatter = getCachedIntl(\n Intl.NumberFormat,\n locale ?? internationalization?.defaultLocale,\n\n {\n style: 'percent',\n ...options,\n }\n );\n\n return formatter.format(Number(numericValue));\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"percentage.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/percentage.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a number as a percentage string (e.g., 0.25 → \"25%\").\n *\n * @example\n * percentage(0.25); // \"25%\"\n *\n * @example\n * percentage(0.25, { minimumFractionDigits: 2 }); // \"25.00%\"\n */\nexport const percentage = (\n value: string | number,\n {\n locale,\n ...options\n }: Intl.NumberFormatOptions & { locale?: LocalesValues } = {}\n): string => {\n let numericValue = Number(value);\n\n // Normalize: if user passes 10, treat it as 10% instead of 1000%\n if (numericValue > 1) {\n numericValue /= 100;\n }\n\n const formatter = getCachedIntl(\n Intl.NumberFormat,\n locale ?? internationalization?.defaultLocale,\n\n {\n style: 'percent',\n ...options,\n }\n );\n\n return formatter.format(Number(numericValue));\n};\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAa,cACX,OACA,EACE,QACA,GAAG,YACsD,CAAC,MACjD;CACX,IAAI,eAAe,OAAO,KAAK;CAG/B,IAAI,eAAe,GACjB,gBAAgB;CAalB,OAVkBA,iCAChB,KAAK,cACL,UAAUC,6CAAsB,eAEhC;EACE,OAAO;EACP,GAAG;CACL,CAGa,EAAE,OAAO,OAAO,YAAY,CAAC;AAC9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relativeTime.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/relativeTime.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\ntype RelativeTimeUnit = Intl.RelativeTimeFormatUnit;\n\n/**\n * Calculate the difference between 2 dates in the given unit.\n */\nconst diffInUnit = (from: Date, to: Date, unit: RelativeTimeUnit): number => {\n const msDiff = to.getTime() - from.getTime();\n const sec = msDiff / 1000;\n\n switch (unit) {\n case 'second':\n return sec;\n case 'minute':\n return sec / 60;\n case 'hour':\n return sec / 3600;\n case 'day':\n return sec / 86400;\n case 'month':\n return sec / (30 * 86400); // approx\n case 'quarter':\n return sec / (3 * 30 * 86400); // 3 months approx\n case 'year':\n return sec / (365 * 86400); // approx\n default:\n return sec;\n }\n};\n\n/**\n * Formats the difference between two dates as a localized relative time string.\n *\n * @example\n * relativeTime(new Date(Date.now() - 30000)); // \"30 seconds ago\"\n *\n * @example\n * relativeTime(\"2025-01-01\", new Date(), { locale: Locales.FRENCH, unit: \"day\" });\n * // \"il y a 443 jours\"\n */\nexport const relativeTime = (\n from: Date | string | number,\n to: Date | string | number = new Date(),\n options?: Intl.RelativeTimeFormatOptions & {\n locale?: LocalesValues;\n unit?: RelativeTimeUnit;\n }\n): string => {\n const fromDate = new Date(from);\n const toDate = new Date(to);\n const unit = options?.unit ?? 'second';\n\n const value = diffInUnit(fromDate, toDate, unit);\n\n return getCachedIntl(\n Intl.RelativeTimeFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n options\n ).format(Math.round(value), unit);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"relativeTime.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/relativeTime.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\ntype RelativeTimeUnit = Intl.RelativeTimeFormatUnit;\n\n/**\n * Calculate the difference between 2 dates in the given unit.\n */\nconst diffInUnit = (from: Date, to: Date, unit: RelativeTimeUnit): number => {\n const msDiff = to.getTime() - from.getTime();\n const sec = msDiff / 1000;\n\n switch (unit) {\n case 'second':\n return sec;\n case 'minute':\n return sec / 60;\n case 'hour':\n return sec / 3600;\n case 'day':\n return sec / 86400;\n case 'month':\n return sec / (30 * 86400); // approx\n case 'quarter':\n return sec / (3 * 30 * 86400); // 3 months approx\n case 'year':\n return sec / (365 * 86400); // approx\n default:\n return sec;\n }\n};\n\n/**\n * Formats the difference between two dates as a localized relative time string.\n *\n * @example\n * relativeTime(new Date(Date.now() - 30000)); // \"30 seconds ago\"\n *\n * @example\n * relativeTime(\"2025-01-01\", new Date(), { locale: Locales.FRENCH, unit: \"day\" });\n * // \"il y a 443 jours\"\n */\nexport const relativeTime = (\n from: Date | string | number,\n to: Date | string | number = new Date(),\n options?: Intl.RelativeTimeFormatOptions & {\n locale?: LocalesValues;\n unit?: RelativeTimeUnit;\n }\n): string => {\n const fromDate = new Date(from);\n const toDate = new Date(to);\n const unit = options?.unit ?? 'second';\n\n const value = diffInUnit(fromDate, toDate, unit);\n\n return getCachedIntl(\n Intl.RelativeTimeFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n options\n ).format(Math.round(value), unit);\n};\n"],"mappings":";;;;;;;;AASA,MAAM,cAAc,MAAY,IAAU,SAAmC;CAE3E,MAAM,OADS,GAAG,QAAQ,IAAI,KAAK,QAAQ,KACtB;CAErB,QAAQ,MAAR;EACE,KAAK,UACH,OAAO;EACT,KAAK,UACH,OAAO,MAAM;EACf,KAAK,QACH,OAAO,MAAM;EACf,KAAK,OACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,OAAO,KAAK;EACrB,KAAK,WACH,OAAO,OAAO,KAAS;EACzB,KAAK,QACH,OAAO,OAAO,MAAM;EACtB,SACE,OAAO;CACX;AACF;;;;;;;;;;;AAYA,MAAa,gBACX,MACA,qBAA6B,IAAI,KAAK,GACtC,YAIW;CACX,MAAM,WAAW,IAAI,KAAK,IAAI;CAC9B,MAAM,SAAS,IAAI,KAAK,EAAE;CAC1B,MAAM,OAAO,SAAS,QAAQ;CAE9B,MAAM,QAAQ,WAAW,UAAU,QAAQ,IAAI;CAE/C,OAAOA,iCACL,KAAK,oBACL,SAAS,UAAUC,6CAAsB,eAEzC,OACF,EAAE,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI;AAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"units.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/units.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value as a localized unit string.\n *\n * @example\n * units(5, { unit: \"kilometer\", unitDisplay: \"long\", locale: \"en-GB\" });\n * // \"5 kilometers\"\n */\nexport const units = (\n value: number | string,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n style: 'unit',\n unit: options?.unit ?? 'day',\n unitDisplay: options?.unitDisplay ?? 'short',\n useGrouping: options?.useGrouping ?? false,\n }\n ).format(Number(value));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"units.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/units.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value as a localized unit string.\n *\n * @example\n * units(5, { unit: \"kilometer\", unitDisplay: \"long\", locale: \"en-GB\" });\n * // \"5 kilometers\"\n */\nexport const units = (\n value: number | string,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n style: 'unit',\n unit: options?.unit ?? 'day',\n unitDisplay: options?.unitDisplay ?? 'short',\n useGrouping: options?.useGrouping ?? false,\n }\n ).format(Number(value));\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,SACX,OACA,YAEAA,iCACE,KAAK,cACL,SAAS,UAAUC,6CAAsB,eAEzC;CACE,OAAO;CACP,MAAM,SAAS,QAAQ;CACvB,aAAa,SAAS,eAAe;CACrC,aAAa,SAAS,eAAe;AACvC,CACF,EAAE,OAAO,OAAO,KAAK,CAAC"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -291,6 +291,7 @@ exports.orderDictionaries = require_dictionaryManipulator_orderDictionaries.orde
|
|
|
291
291
|
exports.parseBlock = require_markdown_utils.parseBlock;
|
|
292
292
|
exports.parseCaptureInline = require_markdown_utils.parseCaptureInline;
|
|
293
293
|
exports.parseInline = require_markdown_utils.parseInline;
|
|
294
|
+
exports.parseMarkdown = require_markdown_compiler.parseMarkdown;
|
|
294
295
|
exports.parseSimpleInline = require_markdown_utils.parseSimpleInline;
|
|
295
296
|
exports.parseStyleAttribute = require_markdown_utils.parseStyleAttribute;
|
|
296
297
|
exports.parseTableAlign = require_markdown_utils.parseTableAlign;
|
|
@@ -309,6 +310,7 @@ exports.relativeTime = require_formatters_relativeTime.relativeTime;
|
|
|
309
310
|
exports.removeContentNodeByKeyPath = require_dictionaryManipulator_removeContentNodeByKeyPath.removeContentNodeByKeyPath;
|
|
310
311
|
exports.renameContentNodeByKeyPath = require_dictionaryManipulator_renameContentNodeByKeyPath.renameContentNodeByKeyPath;
|
|
311
312
|
exports.renderFor = require_markdown_renderer.renderFor;
|
|
313
|
+
exports.renderMarkdownAst = require_markdown_compiler.renderMarkdownAst;
|
|
312
314
|
exports.renderNothing = require_markdown_utils.renderNothing;
|
|
313
315
|
exports.sanitizer = require_markdown_utils.sanitizer;
|
|
314
316
|
exports.setLocaleInStorage = require_utils_localeStorage.setLocaleInStorage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getCondition.cjs","names":[],"sources":["../../../src/interpreter/getCondition.ts"],"sourcesContent":["import type { ConditionContentStates } from '../transpiler';\n\n/**\n * Picks content based on a boolean condition.\n *\n * @param conditionContent - A map with 'true', 'false', and optionally 'fallback' keys.\n * @param state - The boolean state to match.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getCondition({\n * 'true': 'The condition is validated',\n * 'false': 'The condition is not validated',\n * }, true);\n * // 'The condition is validated'\n * ```\n */\nexport const getCondition = <Content>(\n conditionContent: ConditionContentStates<Content>,\n state?: boolean\n): Content => {\n const stateList = Object.keys(conditionContent);\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof conditionContent;\n\n // Default or error handling if no keys match\n return (\n conditionContent[`${state}` as keyof typeof conditionContent] ??\n conditionContent.fallback ??\n (conditionContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,MAAa,gBACX,kBACA,UACY;CACZ,MAAM,YAAY,OAAO,KAAK,gBAAgB;CAC9C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAIrB,OACE,iBAAiB,GAAG,YACpB,iBAAiB,YAChB,iBAAiB;AAEtB"}
|
|
1
|
+
{"version":3,"file":"getCondition.cjs","names":[],"sources":["../../../src/interpreter/getCondition.ts"],"sourcesContent":["import type { ConditionContentStates } from '../transpiler';\n\n/**\n * Picks content based on a boolean condition.\n *\n * @param conditionContent - A map with 'true', 'false', and optionally 'fallback' keys.\n * @param state - The boolean state to match.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getCondition({\n * 'true': 'The condition is validated',\n * 'false': 'The condition is not validated',\n * }, true);\n * // 'The condition is validated'\n * ```\n */\nexport const getCondition = <const Content>(\n conditionContent: ConditionContentStates<Content>,\n state?: boolean\n): Content => {\n const stateList = Object.keys(conditionContent);\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof conditionContent;\n\n // Default or error handling if no keys match\n return (\n conditionContent[`${state}` as keyof typeof conditionContent] ??\n conditionContent.fallback ??\n (conditionContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,MAAa,gBACX,kBACA,UACY;CACZ,MAAM,YAAY,OAAO,KAAK,gBAAgB;CAC9C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAIrB,OACE,iBAAiB,GAAG,YACpB,iBAAiB,YAChB,iBAAiB;AAEtB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_interpreter_getContent_deepTransform = require('./deepTransform.cjs');
|
|
4
3
|
const require_interpreter_getContent_plugins = require('./plugins.cjs');
|
|
5
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getContent.cjs","names":["translationPlugin","internationalization","enumerationPlugin","conditionPlugin","insertionPlugin","nestedPlugin","filePlugin","genderPlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getContent.cjs","names":["translationPlugin","internationalization","enumerationPlugin","conditionPlugin","insertionPlugin","nestedPlugin","filePlugin","genderPlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n const T extends ContentNode,\n const L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;;AAqBA,MAAa,kBACX,QACA,WAAoB,SAEpB;CACEA,yDACE,UAAUC,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,MAClD;CACAC;CACAC;CACAC;CACAC,oDAAa,UAAUJ,4CAAqB,aAAa;CACzDK;CACAC;AACF;;;;;;;AAQF,MAAa,cAIX,MACA,WACA,UAAqB,CAAC,MAEtBC,+DAAkB,MAAM;CACtB,GAAG;CACH;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDictionary.cjs","names":["getBasePlugins","getContent"],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n Plugins,\n} from './getContent';\nimport { getBasePlugins, getContent } from './getContent/getContent';\n\n/**\n * Transforms a dictionary in a single pass, applying each plugin as needed.\n *\n * @param dictionary The dictionary to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n * @param additionalPlugins An array of NodeTransformer that define how to transform recognized nodes.\n * If omitted, we’ll use a default set of plugins.\n */\nexport const getDictionary = <\n T extends Dictionary,\n L extends LocalesValues = DeclaredLocales,\n>(\n dictionary: T,\n locale?: L,\n plugins: Plugins[] = getBasePlugins(locale)\n): DeepTransformContent<T['content'], IInterpreterPluginState, L> => {\n const props: NodeProps = {\n dictionaryKey: dictionary.key,\n dictionaryPath: dictionary.filePath,\n keyPath: [],\n plugins,\n };\n\n return getContent(dictionary.content, props, plugins);\n};\n"],"mappings":";;;;;;;;;;;;AAqBA,MAAa,iBAIX,YACA,QACA,UAAqBA,yDAAe,MAAM,MACyB;CACnE,MAAM,QAAmB;EACvB,eAAe,WAAW;EAC1B,gBAAgB,WAAW;EAC3B,SAAS,CAAC;EACV;CACF;CAEA,OAAOC,qDAAW,WAAW,SAAS,OAAO,OAAO;AACtD"}
|
|
1
|
+
{"version":3,"file":"getDictionary.cjs","names":["getBasePlugins","getContent"],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n Plugins,\n} from './getContent';\nimport { getBasePlugins, getContent } from './getContent/getContent';\n\n/**\n * Transforms a dictionary in a single pass, applying each plugin as needed.\n *\n * @param dictionary The dictionary to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n * @param additionalPlugins An array of NodeTransformer that define how to transform recognized nodes.\n * If omitted, we’ll use a default set of plugins.\n */\nexport const getDictionary = <\n const T extends Dictionary,\n const L extends LocalesValues = DeclaredLocales,\n>(\n dictionary: T,\n locale?: L,\n plugins: Plugins[] = getBasePlugins(locale)\n): DeepTransformContent<T['content'], IInterpreterPluginState, L> => {\n const props: NodeProps = {\n dictionaryKey: dictionary.key,\n dictionaryPath: dictionary.filePath,\n keyPath: [],\n plugins,\n };\n\n return getContent(dictionary.content, props, plugins);\n};\n"],"mappings":";;;;;;;;;;;;AAqBA,MAAa,iBAIX,YACA,QACA,UAAqBA,yDAAe,MAAM,MACyB;CACnE,MAAM,QAAmB;EACvB,eAAe,WAAW;EAC1B,gBAAgB,WAAW;EAC3B,SAAS,CAAC;EACV;CACF;CAEA,OAAOC,qDAAW,WAAW,SAAS,OAAO,OAAO;AACtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getEnumeration.cjs","names":[],"sources":["../../../src/interpreter/getEnumeration.ts"],"sourcesContent":["import type { EnterFormat, EnumerationContentState } from '../transpiler';\n\n/**\n * Find the matching condition for a quantity.\n *\n * Usage:\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<=-2.3': 'You have less than -2.3',\n * '<1': 'You have less than one',\n * '2': 'You have two',\n * '>=3': 'You have three or more',\n * }, 2);\n * // '2'\n * ```\n *\n * The order of the keys will define the priority of the content.\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<4': 'You have less than four',\n * '2': 'You have two',\n * }, 2);\n * // '<4'\n * ```\n *\n * If no keys match, the default key is '1'.\n */\nexport const findMatchingCondition = <Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): EnterFormat | undefined => {\n const numericKeys = Object.keys(enumerationContent);\n\n for (const key of numericKeys) {\n const isEqual =\n (!key.startsWith('>') &&\n !key.startsWith('<') &&\n !key.startsWith('=') &&\n parseFloat(key) === quantity) ||\n (key.startsWith('=') && parseFloat(key.slice(1)) === quantity);\n const isSuperior =\n key.startsWith('>') && quantity > parseFloat(key.slice(1));\n const isSuperiorOrEqual =\n key.startsWith('>=') && quantity >= parseFloat(key.slice(2));\n const isInferior =\n key.startsWith('<') && quantity < parseFloat(key.slice(1));\n const isInferiorOrEqual =\n key.startsWith('<=') && quantity <= parseFloat(key.slice(2));\n\n if (\n isEqual ||\n isSuperior ||\n isSuperiorOrEqual ||\n isInferior ||\n isInferiorOrEqual\n ) {\n return key as EnterFormat;\n }\n }\n};\n\n/**\n * Picks content from an enumeration map based on a provided quantity.\n *\n * Supported keys in the enumeration map:\n * - Specific numbers: '0', '1', '2'\n * - Comparison operators: '<5', '>=10', '<=2'\n * - Fallback: 'fallback'\n *\n * The first matching key in the object's iteration order will be selected.\n *\n * @param enumerationContent - A map of conditions/quantities to content.\n * @param quantity - The number to match against the conditions.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getEnumeration({\n * '0': 'No items',\n * '1': 'One item',\n * '>1': 'Many items',\n * }, 5);\n * // 'Many items'\n * ```\n */\nexport const getEnumeration = <Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): Content => {\n const key =\n findMatchingCondition<Content>(enumerationContent, quantity) ?? 'fallback';\n\n // Default or error handling if no keys match\n return enumerationContent[key] as Content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,yBACX,oBACA,aAC4B;CAC5B,MAAM,cAAc,OAAO,KAAK,kBAAkB;CAElD,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,UACH,CAAC,IAAI,WAAW,GAAG,KAClB,CAAC,IAAI,WAAW,GAAG,KACnB,CAAC,IAAI,WAAW,GAAG,KACnB,WAAW,GAAG,MAAM,YACrB,IAAI,WAAW,GAAG,KAAK,WAAW,IAAI,MAAM,CAAC,CAAC,MAAM;EACvD,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAC7D,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAE7D,IACE,WACA,cACA,qBACA,cACA,mBAEA,OAAO;CAEX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBACX,oBACA,aACY;CAKZ,OAAO,mBAHL,sBAA+B,oBAAoB,QAAQ,KAAK;AAIpE"}
|
|
1
|
+
{"version":3,"file":"getEnumeration.cjs","names":[],"sources":["../../../src/interpreter/getEnumeration.ts"],"sourcesContent":["import type { EnterFormat, EnumerationContentState } from '../transpiler';\n\n/**\n * Find the matching condition for a quantity.\n *\n * Usage:\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<=-2.3': 'You have less than -2.3',\n * '<1': 'You have less than one',\n * '2': 'You have two',\n * '>=3': 'You have three or more',\n * }, 2);\n * // '2'\n * ```\n *\n * The order of the keys will define the priority of the content.\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<4': 'You have less than four',\n * '2': 'You have two',\n * }, 2);\n * // '<4'\n * ```\n *\n * If no keys match, the default key is '1'.\n */\nexport const findMatchingCondition = <const Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): EnterFormat | undefined => {\n const numericKeys = Object.keys(enumerationContent);\n\n for (const key of numericKeys) {\n const isEqual =\n (!key.startsWith('>') &&\n !key.startsWith('<') &&\n !key.startsWith('=') &&\n parseFloat(key) === quantity) ||\n (key.startsWith('=') && parseFloat(key.slice(1)) === quantity);\n const isSuperior =\n key.startsWith('>') && quantity > parseFloat(key.slice(1));\n const isSuperiorOrEqual =\n key.startsWith('>=') && quantity >= parseFloat(key.slice(2));\n const isInferior =\n key.startsWith('<') && quantity < parseFloat(key.slice(1));\n const isInferiorOrEqual =\n key.startsWith('<=') && quantity <= parseFloat(key.slice(2));\n\n if (\n isEqual ||\n isSuperior ||\n isSuperiorOrEqual ||\n isInferior ||\n isInferiorOrEqual\n ) {\n return key as EnterFormat;\n }\n }\n};\n\n/**\n * Picks content from an enumeration map based on a provided quantity.\n *\n * Supported keys in the enumeration map:\n * - Specific numbers: '0', '1', '2'\n * - Comparison operators: '<5', '>=10', '<=2'\n * - Fallback: 'fallback'\n *\n * The first matching key in the object's iteration order will be selected.\n *\n * @param enumerationContent - A map of conditions/quantities to content.\n * @param quantity - The number to match against the conditions.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getEnumeration({\n * '0': 'No items',\n * '1': 'One item',\n * '>1': 'Many items',\n * }, 5);\n * // 'Many items'\n * ```\n */\nexport const getEnumeration = <const Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): Content => {\n const key =\n findMatchingCondition<Content>(enumerationContent, quantity) ?? 'fallback';\n\n // Default or error handling if no keys match\n return enumerationContent[key] as Content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,yBACX,oBACA,aAC4B;CAC5B,MAAM,cAAc,OAAO,KAAK,kBAAkB;CAElD,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,UACH,CAAC,IAAI,WAAW,GAAG,KAClB,CAAC,IAAI,WAAW,GAAG,KACnB,CAAC,IAAI,WAAW,GAAG,KACnB,WAAW,GAAG,MAAM,YACrB,IAAI,WAAW,GAAG,KAAK,WAAW,IAAI,MAAM,CAAC,CAAC,MAAM;EACvD,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAC7D,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAE7D,IACE,WACA,cACA,qBACA,cACA,mBAEA,OAAO;CAEX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBACX,oBACA,aACY;CAKZ,OAAO,mBAHL,sBAA+B,oBAAoB,QAAQ,KAAK;AAIpE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getGender.cjs","names":[],"sources":["../../../src/interpreter/getGender.ts"],"sourcesContent":["import type { Gender, GenderContentStates } from '../transpiler';\n\ntype GenderEntry = Gender | 'm' | 'f';\n\nconst getGenderEntry = (gender: GenderEntry): Gender => {\n if (gender === 'm' || gender === 'male') return 'male';\n if (gender === 'f' || gender === 'female') return 'female';\n return 'fallback';\n};\n\n/**\n * Allow to pick a content based on a gender.\n *\n * Usage:\n *\n * ```ts\n * const content = getGender({\n * 'true': 'The gender is validated',\n * 'false': 'The gender is not validated',\n * }, true);\n * // 'The gender is validated'\n * ```\n *\n * The last key provided will be used as the fallback value.\n *\n * ```ts\n * const content = getGender({\n * 'false': 'The gender is not validated',\n * 'true': 'The gender is validated',\n * }, undefined);\n * // 'The gender is validated'\n */\nexport const getGender = <Content>(\n genderContent: GenderContentStates<Content>,\n gender: GenderEntry\n): Content => {\n const stateList = Object.keys(genderContent);\n\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof genderContent;\n\n const genderEntry = getGenderEntry(gender);\n\n // Default or error handling if no keys match\n return (\n genderContent[genderEntry as keyof typeof genderContent] ??\n genderContent.fallback ??\n (genderContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;AAIA,MAAM,kBAAkB,WAAgC;CACtD,IAAI,WAAW,OAAO,WAAW,QAAQ,OAAO;CAChD,IAAI,WAAW,OAAO,WAAW,UAAU,OAAO;CAClD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,aACX,eACA,WACY;CACZ,MAAM,YAAY,OAAO,KAAK,aAAa;CAE3C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAMrB,OACE,cAJkB,eAAe,MAIT,MACxB,cAAc,YACb,cAAc;AAEnB"}
|
|
1
|
+
{"version":3,"file":"getGender.cjs","names":[],"sources":["../../../src/interpreter/getGender.ts"],"sourcesContent":["import type { Gender, GenderContentStates } from '../transpiler';\n\ntype GenderEntry = Gender | 'm' | 'f';\n\nconst getGenderEntry = (gender: GenderEntry): Gender => {\n if (gender === 'm' || gender === 'male') return 'male';\n if (gender === 'f' || gender === 'female') return 'female';\n return 'fallback';\n};\n\n/**\n * Allow to pick a content based on a gender.\n *\n * Usage:\n *\n * ```ts\n * const content = getGender({\n * 'true': 'The gender is validated',\n * 'false': 'The gender is not validated',\n * }, true);\n * // 'The gender is validated'\n * ```\n *\n * The last key provided will be used as the fallback value.\n *\n * ```ts\n * const content = getGender({\n * 'false': 'The gender is not validated',\n * 'true': 'The gender is validated',\n * }, undefined);\n * // 'The gender is validated'\n */\nexport const getGender = <const Content>(\n genderContent: GenderContentStates<Content>,\n gender: GenderEntry\n): Content => {\n const stateList = Object.keys(genderContent);\n\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof genderContent;\n\n const genderEntry = getGenderEntry(gender);\n\n // Default or error handling if no keys match\n return (\n genderContent[genderEntry as keyof typeof genderContent] ??\n genderContent.fallback ??\n (genderContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;AAIA,MAAM,kBAAkB,WAAgC;CACtD,IAAI,WAAW,OAAO,WAAW,QAAQ,OAAO;CAChD,IAAI,WAAW,OAAO,WAAW,UAAU,OAAO;CAClD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,aACX,eACA,WACY;CACZ,MAAM,YAAY,OAAO,KAAK,aAAa;CAE3C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAMrB,OACE,cAJkB,eAAe,MAIT,MACxB,cAAc,YACb,cAAc;AAEnB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_interpreter_getDictionary = require('./getDictionary.cjs');
|
|
4
3
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
4
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayer.cjs","names":["getDictionary"],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryContent,\n DictionaryRegistryElement,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\nexport const getIntlayer = <\n T extends DictionaryKeys,\n L extends LocalesValues = DeclaredLocales,\n>(\n key: T,\n locale?: L,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryContent<T>,\n IInterpreterPluginState,\n L\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T] as DictionaryRegistryElement<T>;\n\n if (!dictionary && process.env.NODE_ENV === 'development') {\n if (!warnedMissingDictionaries.has(key as string)) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n typeof window === 'undefined'\n ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.`\n : `Dictionary ${key} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n }\n );\n warnedMissingDictionaries.add(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n const cacheKey = `${key}_${locale ?? 'default'}_${plugins ? 'custom_plugins' : 'default_plugins'}`;\n\n if (dictionaryCache.has(cacheKey)) {\n return dictionaryCache.get(cacheKey);\n }\n\n const result = getDictionary<DictionaryRegistryElement<T>, L>(\n dictionary,\n locale,\n plugins\n );\n\n dictionaryCache.set(cacheKey, result);\n\n return result;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getIntlayer.cjs","names":["getDictionary"],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryContent,\n DictionaryRegistryElement,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const L extends LocalesValues = DeclaredLocales,\n>(\n key: T,\n locale?: L,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryContent<T>,\n IInterpreterPluginState,\n L\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T] as DictionaryRegistryElement<T>;\n\n if (!dictionary && process.env.NODE_ENV === 'development') {\n if (!warnedMissingDictionaries.has(key as string)) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n typeof window === 'undefined'\n ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.`\n : `Dictionary ${key} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n }\n );\n warnedMissingDictionaries.add(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n const cacheKey = `${key}_${locale ?? 'default'}_${plugins ? 'custom_plugins' : 'default_plugins'}`;\n\n if (dictionaryCache.has(cacheKey)) {\n return dictionaryCache.get(cacheKey);\n }\n\n const result = getDictionary<DictionaryRegistryElement<T>, L>(\n dictionary,\n locale,\n plugins\n );\n\n dictionaryCache.set(cacheKey, result);\n\n return result;\n};\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,sBAAsB,OAAO,OAAY;CAC7C,OAAO,IAAI,MAAM,CAAC,GAAuC,EACvD,MAAM,SAAS,SAAS;EACtB,IACE,SAAS,YACT,SAAS,OAAO,eAChB,SAAS,cACT,SAAS,WAET,aAAa;EAEf,IAAI,SAAS,QACX;EAEF,IAAI,SAAS,OAAO,UAClB,OAAO,aAAa;GAClB,MAAM;EACR;EAKF,OAAO,mBADU,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,MAAM,OAAO,IAAI,CAC7B;CACpC,EACF,CAAC;AACH;AAEA,MAAM,kCAAkB,IAAI,IAAiB;AAC7C,MAAM,4CAA4B,IAAI,IAAY;AAElD,MAAa,eAIX,KACA,QACA,YAKG;CAEH,MAAM,+DAAwB,EAAE;CAEhC,IAAI,CAAC,cAAc,QAAQ,IAAI,aAAa,eAAe;EACzD,IAAI,CAAC,0BAA0B,IAAI,GAAa,GAAG;GAGjD,0CAD4B,EAAE,gCAAI,CAC7B,EACH,OAAO,WAAW,cACd,uDAA0B,GAAG,EAAE,yCAC/B,cAAc,IAAI,wCACtB,EACE,OAAO,OACT,CACF;GACA,0BAA0B,IAAI,GAAa;EAC7C;EAEA,OAAO,mBAAmB,GAAa;CACzC;CAEA,MAAM,WAAW,GAAG,IAAI,GAAG,UAAU,UAAU,GAAG,UAAU,mBAAmB;CAE/E,IAAI,gBAAgB,IAAI,QAAQ,GAC9B,OAAO,gBAAgB,IAAI,QAAQ;CAGrC,MAAM,SAASA,gDACb,YACA,QACA,OACF;CAEA,gBAAgB,IAAI,UAAU,MAAM;CAEpC,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getNesting.cjs","names":["getIntlayer"],"sources":["../../../src/interpreter/getNesting.ts"],"sourcesContent":["import type { GetSubPath } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionaryRegistryContent,\n} from '@intlayer/types/module_augmentation';\nimport type { ValidDotPathsFor } from '../transpiler';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n} from './getContent';\nimport { getIntlayer } from './getIntlayer';\n\nexport type GetNestingResult<\n K extends DictionaryKeys,\n P = undefined,\n S = IInterpreterPluginState,\n> = GetSubPath<DeepTransformContent<DictionaryRegistryContent<K>, S>, P>;\n\n/**\n * Extracts content from another dictionary by its key and an optional path.\n *\n * This allows for reusing content across different dictionaries.\n *\n * @param dictionaryKey - The key of the dictionary to nest.\n * @param path - Optional dot-separated path to a specific field within the nested dictionary.\n * @param props - Optional properties like locale and plugins.\n * @returns The nested content.\n *\n * @example\n * ```ts\n * const content = getNesting(\"common\", \"buttons.save\");\n * // 'Save'\n * ```\n */\nexport const getNesting = <K extends DictionaryKeys, P>(\n dictionaryKey: K,\n path?: P extends ValidDotPathsFor<K> ? P : never,\n props?: NodeProps\n): GetNestingResult<K, P> => {\n const dictionary = getIntlayer(dictionaryKey, props?.locale, props?.plugins);\n\n if (typeof path === 'string') {\n const pathArray = (path as string).split('.');\n let current: any = dictionary;\n\n for (const key of pathArray) {\n // Safely traverse down the object using the path\n current = current?.[key];\n // If we cannot find the path, return the whole dictionary as a fallback\n if (current === undefined) {\n return dictionary as any;\n }\n }\n\n return current;\n }\n\n // Default or error handling if path is not a string or otherwise undefined\n return dictionary as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cACX,eACA,MACA,UAC2B;CAC3B,MAAM,aAAaA,4CAAY,eAAe,OAAO,QAAQ,OAAO,OAAO;CAE3E,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,YAAa,KAAgB,MAAM,GAAG;EAC5C,IAAI,UAAe;EAEnB,KAAK,MAAM,OAAO,WAAW;GAE3B,UAAU,UAAU;GAEpB,IAAI,YAAY,QACd,OAAO;EAEX;EAEA,OAAO;CACT;CAGA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"getNesting.cjs","names":["getIntlayer"],"sources":["../../../src/interpreter/getNesting.ts"],"sourcesContent":["import type { GetSubPath } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionaryRegistryContent,\n} from '@intlayer/types/module_augmentation';\nimport type { ValidDotPathsFor } from '../transpiler';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n} from './getContent';\nimport { getIntlayer } from './getIntlayer';\n\nexport type GetNestingResult<\n K extends DictionaryKeys,\n P = undefined,\n S = IInterpreterPluginState,\n> = GetSubPath<DeepTransformContent<DictionaryRegistryContent<K>, S>, P>;\n\n/**\n * Extracts content from another dictionary by its key and an optional path.\n *\n * This allows for reusing content across different dictionaries.\n *\n * @param dictionaryKey - The key of the dictionary to nest.\n * @param path - Optional dot-separated path to a specific field within the nested dictionary.\n * @param props - Optional properties like locale and plugins.\n * @returns The nested content.\n *\n * @example\n * ```ts\n * const content = getNesting(\"common\", \"buttons.save\");\n * // 'Save'\n * ```\n */\nexport const getNesting = <const K extends DictionaryKeys, const P>(\n dictionaryKey: K,\n path?: P extends ValidDotPathsFor<K> ? P : never,\n props?: NodeProps\n): GetNestingResult<K, P> => {\n const dictionary = getIntlayer(dictionaryKey, props?.locale, props?.plugins);\n\n if (typeof path === 'string') {\n const pathArray = (path as string).split('.');\n let current: any = dictionary;\n\n for (const key of pathArray) {\n // Safely traverse down the object using the path\n current = current?.[key];\n // If we cannot find the path, return the whole dictionary as a fallback\n if (current === undefined) {\n return dictionary as any;\n }\n }\n\n return current;\n }\n\n // Default or error handling if path is not a string or otherwise undefined\n return dictionary as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cACX,eACA,MACA,UAC2B;CAC3B,MAAM,aAAaA,4CAAY,eAAe,OAAO,QAAQ,OAAO,OAAO;CAE3E,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,YAAa,KAAgB,MAAM,GAAG;EAC5C,IAAI,UAAe;EAEnB,KAAK,MAAM,OAAO,WAAW;GAE3B,UAAU,UAAU;GAEpB,IAAI,YAAY,QACd,OAAO;EAEX;EAEA,OAAO;CACT;CAGA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPlural.cjs","names":["getCachedIntl"],"sources":["../../../src/interpreter/getPlural.ts"],"sourcesContent":["import type { DeclaredLocales } from '@intlayer/types';\nimport type { LocalesValues } from 'intlayer';\nimport { getCachedIntl } from '../formatters';\nimport type {\n PluralCategory,\n PluralContentState,\n} from '../transpiler/plural/plural';\n\n/**\n * Picks content from a plural map based on a count and locale, using CLDR\n * pluralization rules (`Intl.PluralRules`).\n *\n * Falls back to the `other` category when no specific category matches.\n *\n * @example\n * ```ts\n * getPlural({\n * one: 'one item',\n * other: '{{count}} items',\n * }, 5, 'en');\n * // '{{count}} items'\n * ```\n */\nexport const getPlural = <L extends LocalesValues = DeclaredLocales>(\n pluralContent: PluralContentState<string>,\n count: number,\n locale: L\n): string => {\n const category = getCachedIntl(Intl.PluralRules, locale).select(\n count\n ) as PluralCategory;\n\n return pluralContent[category] ?? pluralContent.other;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAa,aACX,eACA,OACA,WACW;CAKX,OAAO,cAJUA,iCAAc,KAAK,aAAa,MAAM,EAAE,OACvD,KAG0B,MAAM,cAAc;AAClD"}
|
|
1
|
+
{"version":3,"file":"getPlural.cjs","names":["getCachedIntl"],"sources":["../../../src/interpreter/getPlural.ts"],"sourcesContent":["import type { DeclaredLocales } from '@intlayer/types';\nimport type { LocalesValues } from 'intlayer';\nimport { getCachedIntl } from '../formatters';\nimport type {\n PluralCategory,\n PluralContentState,\n} from '../transpiler/plural/plural';\n\n/**\n * Picks content from a plural map based on a count and locale, using CLDR\n * pluralization rules (`Intl.PluralRules`).\n *\n * Falls back to the `other` category when no specific category matches.\n *\n * @example\n * ```ts\n * getPlural({\n * one: 'one item',\n * other: '{{count}} items',\n * }, 5, 'en');\n * // '{{count}} items'\n * ```\n */\nexport const getPlural = <const L extends LocalesValues = DeclaredLocales>(\n pluralContent: PluralContentState<string>,\n count: number,\n locale: L\n): string => {\n const category = getCachedIntl(Intl.PluralRules, locale).select(\n count\n ) as PluralCategory;\n\n return pluralContent[category] ?? pluralContent.other;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAa,aACX,eACA,OACA,WACW;CAKX,OAAO,cAJUA,iCAAc,KAAK,aAAa,MAAM,EAAE,OACvD,KAG0B,MAAM,cAAc;AAClD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTranslation.cjs","names":[],"sources":["../../../src/interpreter/getTranslation.ts"],"sourcesContent":["import type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Check if a value is a plain object that can be safely merged.\n * Returns false for Promises, React elements, class instances, etc.\n */\nconst isPlainObject = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') return false;\n if (typeof (value as any).then === 'function') return false;\n if (\n (value as any).$$typeof !== undefined ||\n (value as any).__v_isVNode !== undefined ||\n (value as any)._isVNode !== undefined ||\n (value as any).isJSX !== undefined\n ) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null || Array.isArray(value);\n};\n\n/**\n * Recursively merges two objects, skipping undefined source values.\n * First argument takes precedence. Arrays replace rather than merge.\n */\nconst deepMerge = (target: any, source: any): any => {\n if (target === undefined) return source;\n if (source === undefined) return target;\n if (Array.isArray(target)) return target;\n if (isPlainObject(target) && isPlainObject(source)) {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n source[key] === undefined\n )\n continue;\n result[key] =\n target[key] !== undefined\n ? deepMerge(target[key], source[key])\n : source[key];\n }\n return result;\n }\n return target;\n};\n\n/**\n * Picks the appropriate content from a locale map based on the provided locale.\n *\n * It handles:\n * 1. Exact locale match (e.g., 'en-US').\n * 2. Generic locale fallback (e.g., 'en' if 'en-US' is not found).\n * 3. Explicit fallback locale.\n * 4. Deep merging of objects to ensure partial translations are complemented by fallbacks.\n *\n * @param languageContent - A map of locales to content.\n * @param locale - The target locale to retrieve.\n * @param fallback - Optional fallback locale if the target is not found.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * const content = getTranslation({\n * en: 'Hello',\n * fr: 'Bonjour',\n * }, 'fr');\n * // 'Bonjour'\n * ```\n */\nexport const getTranslation = <Content = string>(\n languageContent: StrictModeLocaleMap<Content>,\n locale: LocalesValues,\n fallback?: LocalesValues\n): Content => {\n const get = (loc: string): Content | undefined =>\n languageContent[loc as keyof typeof languageContent];\n\n // Build priority-ordered locale candidates (most specific first), deduped\n const seen = new Set<string>();\n const locales: string[] = [];\n const addLocale = (loc: string | undefined) => {\n if (loc && !seen.has(loc)) {\n seen.add(loc);\n locales.push(loc);\n }\n };\n\n addLocale(locale);\n if (locale.includes('-')) addLocale(locale.split('-')[0]);\n\n addLocale(fallback);\n if (fallback?.includes('-')) addLocale(fallback.split('-')[0]);\n\n // Collect results: strings exit early (if no higher-priority object was found),\n // objects are accumulated for deep merging.\n const results: Content[] = [];\n\n for (const loc of locales) {\n const val = get(loc);\n\n if (val === undefined) continue;\n if (typeof val === 'string') {\n if (results.length === 0) return val;\n continue; // an object at higher priority takes precedence\n }\n\n results.push(val);\n }\n\n if (results.length === 0) return undefined as Content;\n if (results.length === 1) return results[0];\n if (Array.isArray(results[0])) return results[0];\n\n // Merge objects: first result (most specific) takes precedence\n return (results as object[]).reduce((acc, curr) =>\n deepMerge(acc, curr)\n ) as Content;\n};\n"],"mappings":";;;;;;;AASA,MAAM,iBAAiB,UAA4B;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,OAAQ,MAAc,SAAS,YAAY,OAAO;CACtD,IACG,MAAc,aAAa,UAC3B,MAAc,gBAAgB,UAC9B,MAAc,aAAa,UAC3B,MAAc,UAAU,QAEzB,OAAO;CAET,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU,QAAQ,MAAM,QAAQ,KAAK;AAC5E;;;;;AAMA,MAAM,aAAa,QAAa,WAAqB;CACnD,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,cAAc,MAAM,KAAK,cAAc,MAAM,GAAG;EAClD,MAAM,SAAS,EAAE,GAAG,OAAO;EAE3B,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;GACrC,IACE,QAAQ,eACR,QAAQ,iBACR,OAAO,SAAS,QAEhB;GACF,OAAO,OACL,OAAO,SAAS,SACZ,UAAU,OAAO,MAAM,OAAO,IAAI,IAClC,OAAO;EACf;EACA,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kBACX,iBACA,QACA,aACY;CACZ,MAAM,OAAO,QACX,gBAAgB;CAGlB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,UAAoB,CAAC;CAC3B,MAAM,aAAa,QAA4B;EAC7C,IAAI,OAAO,CAAC,KAAK,IAAI,GAAG,GAAG;GACzB,KAAK,IAAI,GAAG;GACZ,QAAQ,KAAK,GAAG;EAClB;CACF;CAEA,UAAU,MAAM;CAChB,IAAI,OAAO,SAAS,GAAG,GAAG,UAAU,OAAO,MAAM,GAAG,EAAE,EAAE;CAExD,UAAU,QAAQ;CAClB,IAAI,UAAU,SAAS,GAAG,GAAG,UAAU,SAAS,MAAM,GAAG,EAAE,EAAE;CAI7D,MAAM,UAAqB,CAAC;CAE5B,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,MAAM,IAAI,GAAG;EAEnB,IAAI,QAAQ,QAAW;EACvB,IAAI,OAAO,QAAQ,UAAU;GAC3B,IAAI,QAAQ,WAAW,GAAG,OAAO;GACjC;EACF;EAEA,QAAQ,KAAK,GAAG;CAClB;CAEA,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;CACzC,IAAI,MAAM,QAAQ,QAAQ,EAAE,GAAG,OAAO,QAAQ;CAG9C,OAAQ,QAAqB,QAAQ,KAAK,SACxC,UAAU,KAAK,IAAI,CACrB;AACF"}
|
|
1
|
+
{"version":3,"file":"getTranslation.cjs","names":[],"sources":["../../../src/interpreter/getTranslation.ts"],"sourcesContent":["import type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Check if a value is a plain object that can be safely merged.\n * Returns false for Promises, React elements, class instances, etc.\n */\nconst isPlainObject = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') return false;\n if (typeof (value as any).then === 'function') return false;\n if (\n (value as any).$$typeof !== undefined ||\n (value as any).__v_isVNode !== undefined ||\n (value as any)._isVNode !== undefined ||\n (value as any).isJSX !== undefined\n ) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null || Array.isArray(value);\n};\n\n/**\n * Recursively merges two objects, skipping undefined source values.\n * First argument takes precedence. Arrays replace rather than merge.\n */\nconst deepMerge = (target: any, source: any): any => {\n if (target === undefined) return source;\n if (source === undefined) return target;\n if (Array.isArray(target)) return target;\n if (isPlainObject(target) && isPlainObject(source)) {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n source[key] === undefined\n )\n continue;\n result[key] =\n target[key] !== undefined\n ? deepMerge(target[key], source[key])\n : source[key];\n }\n return result;\n }\n return target;\n};\n\n/**\n * Picks the appropriate content from a locale map based on the provided locale.\n *\n * It handles:\n * 1. Exact locale match (e.g., 'en-US').\n * 2. Generic locale fallback (e.g., 'en' if 'en-US' is not found).\n * 3. Explicit fallback locale.\n * 4. Deep merging of objects to ensure partial translations are complemented by fallbacks.\n *\n * @param languageContent - A map of locales to content.\n * @param locale - The target locale to retrieve.\n * @param fallback - Optional fallback locale if the target is not found.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * const content = getTranslation({\n * en: 'Hello',\n * fr: 'Bonjour',\n * }, 'fr');\n * // 'Bonjour'\n * ```\n */\nexport const getTranslation = <const Content = string>(\n languageContent: StrictModeLocaleMap<Content>,\n locale: LocalesValues,\n fallback?: LocalesValues\n): Content => {\n const get = (loc: string): Content | undefined =>\n languageContent[loc as keyof typeof languageContent];\n\n // Build priority-ordered locale candidates (most specific first), deduped\n const seen = new Set<string>();\n const locales: string[] = [];\n const addLocale = (loc: string | undefined) => {\n if (loc && !seen.has(loc)) {\n seen.add(loc);\n locales.push(loc);\n }\n };\n\n addLocale(locale);\n if (locale.includes('-')) addLocale(locale.split('-')[0]);\n\n addLocale(fallback);\n if (fallback?.includes('-')) addLocale(fallback.split('-')[0]);\n\n // Collect results: strings exit early (if no higher-priority object was found),\n // objects are accumulated for deep merging.\n const results: Content[] = [];\n\n for (const loc of locales) {\n const val = get(loc);\n\n if (val === undefined) continue;\n if (typeof val === 'string') {\n if (results.length === 0) return val;\n continue; // an object at higher priority takes precedence\n }\n\n results.push(val);\n }\n\n if (results.length === 0) return undefined as Content;\n if (results.length === 1) return results[0];\n if (Array.isArray(results[0])) return results[0];\n\n // Merge objects: first result (most specific) takes precedence\n return (results as object[]).reduce((acc, curr) =>\n deepMerge(acc, curr)\n ) as Content;\n};\n"],"mappings":";;;;;;;AASA,MAAM,iBAAiB,UAA4B;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,OAAQ,MAAc,SAAS,YAAY,OAAO;CACtD,IACG,MAAc,aAAa,UAC3B,MAAc,gBAAgB,UAC9B,MAAc,aAAa,UAC3B,MAAc,UAAU,QAEzB,OAAO;CAET,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU,QAAQ,MAAM,QAAQ,KAAK;AAC5E;;;;;AAMA,MAAM,aAAa,QAAa,WAAqB;CACnD,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,cAAc,MAAM,KAAK,cAAc,MAAM,GAAG;EAClD,MAAM,SAAS,EAAE,GAAG,OAAO;EAE3B,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;GACrC,IACE,QAAQ,eACR,QAAQ,iBACR,OAAO,SAAS,QAEhB;GACF,OAAO,OACL,OAAO,SAAS,SACZ,UAAU,OAAO,MAAM,OAAO,IAAI,IAClC,OAAO;EACf;EACA,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kBACX,iBACA,QACA,aACY;CACZ,MAAM,OAAO,QACX,gBAAgB;CAGlB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,UAAoB,CAAC;CAC3B,MAAM,aAAa,QAA4B;EAC7C,IAAI,OAAO,CAAC,KAAK,IAAI,GAAG,GAAG;GACzB,KAAK,IAAI,GAAG;GACZ,QAAQ,KAAK,GAAG;EAClB;CACF;CAEA,UAAU,MAAM;CAChB,IAAI,OAAO,SAAS,GAAG,GAAG,UAAU,OAAO,MAAM,GAAG,EAAE,EAAE;CAExD,UAAU,QAAQ;CAClB,IAAI,UAAU,SAAS,GAAG,GAAG,UAAU,SAAS,MAAM,GAAG,EAAE,EAAE;CAI7D,MAAM,UAAqB,CAAC;CAE5B,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,MAAM,IAAI,GAAG;EAEnB,IAAI,QAAQ,QAAW;EACvB,IAAI,OAAO,QAAQ,UAAU;GAC3B,IAAI,QAAQ,WAAW,GAAG,OAAO;GACjC;EACF;EAEA,QAAQ,KAAK,GAAG;CAClB;CAEA,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;CACzC,IAAI,MAAM,QAAQ,QAAQ,EAAE,GAAG,OAAO,QAAQ;CAG9C,OAAQ,QAAqB,QAAQ,KAAK,SACxC,UAAU,KAAK,IAAI,CACrB;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_utils_localeStorage = require('../utils/localeStorage.cjs');
|
|
4
3
|
const require_localization_localeDetector = require('./localeDetector.cjs');
|
|
5
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBrowserLocale.cjs","names":["getLocaleFromStorageClient","localeDetector","internationalization","DEFAULT_LOCALE"],"sources":["../../../src/localization/getBrowserLocale.tsx"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageClient } from '../utils/localeStorage';\nimport { localeDetector } from './localeDetector';\n\nexport enum LanguageDetector {\n Querystring = 'querystring',\n Storage = 'storage',\n Navigator = 'navigator',\n HtmlTag = 'htmlTag',\n}\n\n// Default settings for the language detector\ntype LanguageDetectorOptions = {\n order?: LanguageDetector[];\n lookupQuerystring?: string;\n htmlTag?: HTMLElement | null;\n};\n\nconst getDefaultsOptions = (): LanguageDetectorOptions => {\n return {\n order: [\n LanguageDetector.Querystring,\n LanguageDetector.Storage,\n LanguageDetector.Navigator,\n LanguageDetector.HtmlTag,\n ],\n lookupQuerystring: 'locale',\n htmlTag: typeof document !== 'undefined' ? document.documentElement : null,\n };\n};\n\nconst detectLanguage = (\n order: string[],\n options: LanguageDetectorOptions\n): Record<LanguageDetector, Locale | undefined> => {\n const detected: Record<LanguageDetector, Locale | undefined> = {} as Record<\n LanguageDetector,\n Locale | undefined\n >;\n\n const queryStringDetector = () => {\n if (typeof window === 'undefined') return;\n const search = window.location.search || '';\n const params = new URLSearchParams(search);\n const value = params.get(options.lookupQuerystring ?? '');\n if (value) {\n detected[LanguageDetector.Querystring] = value as Locale;\n }\n };\n\n const storageDetector = () => {\n if (typeof window === 'undefined') return;\n\n const locale = getLocaleFromStorageClient({\n getCookie: (name: string) => {\n try {\n const cookies = document.cookie.split(';');\n const cookieName = `${name}=`;\n\n const cookie = cookies.find((cookie) =>\n cookie.trim().startsWith(cookieName)\n );\n\n if (cookie) {\n return cookie.split('=')[1].trim();\n }\n } catch {}\n return undefined;\n },\n getSessionStorage: (name: string) => {\n try {\n return window.sessionStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n getLocaleStorage: (name: string) => {\n try {\n return window.localStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n });\n\n if (locale) {\n detected[LanguageDetector.Storage] = locale;\n }\n };\n\n const navigatorDetector = () => {\n if (typeof navigator === 'undefined') return;\n\n const languages = navigator.languages ?? [navigator.language];\n\n // Use localeDetector to find the best matching locale\n const locale = localeDetector(\n { 'accept-language': languages.join(',') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n if (locale) {\n detected[LanguageDetector.Navigator] = locale;\n }\n };\n\n const htmlTagDetector = () => {\n const htmlTag = options.htmlTag;\n if (htmlTag && typeof htmlTag.getAttribute === 'function') {\n const lang = htmlTag.getAttribute('lang');\n if (lang) {\n // Validate and resolve the locale\n\n const locale = localeDetector(\n { 'accept-language': lang },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n detected[LanguageDetector.HtmlTag] = locale;\n }\n }\n };\n\n // Map detector names to their corresponding functions\n const detectors: Record<string, () => void> = {\n [LanguageDetector.Querystring]: queryStringDetector,\n [LanguageDetector.Storage]: storageDetector,\n [LanguageDetector.Navigator]: navigatorDetector,\n [LanguageDetector.HtmlTag]: htmlTagDetector,\n };\n\n // Use the provided order to run each detector\n order.forEach((detectorName) => {\n detectors[detectorName]?.();\n });\n\n return detected;\n};\n\nconst getFirstAvailableLocale = (\n locales: Record<LanguageDetector, Locale | undefined>,\n order: LanguageDetector[]\n): Locale => {\n for (const detector of order) {\n const locale = locales[detector];\n\n if (locale && internationalization.locales.includes(locale)) {\n return locale;\n }\n }\n\n return internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n};\n\n/**\n * Core language detector function for browser environments.\n *\n * Detects the user's preferred locale by checking multiple sources in order:\n * 1. Query string parameter\n * 2. Storage (cookies, localStorage, sessionStorage) - uses getLocaleFromStorage\n * 3. Navigator languages - uses localeDetector\n * 4. HTML lang attribute - uses localeDetector\n *\n * @param userOptions - Optional configuration for detection order and lookup keys\n * @returns The detected locale or the default locale\n *\n * @example\n * const locale = getBrowserLocale({ order: [LanguageDetector.Storage, LanguageDetector.Navigator] });\n */\nexport const getBrowserLocale = (\n userOptions: LanguageDetectorOptions | undefined = {}\n): Locale => {\n const options = { ...getDefaultsOptions(), ...userOptions };\n\n const locales = detectLanguage(options.order ?? [], options);\n\n return getFirstAvailableLocale(locales, options.order ?? []);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getBrowserLocale.cjs","names":["getLocaleFromStorageClient","localeDetector","internationalization","DEFAULT_LOCALE"],"sources":["../../../src/localization/getBrowserLocale.tsx"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageClient } from '../utils/localeStorage';\nimport { localeDetector } from './localeDetector';\n\nexport enum LanguageDetector {\n Querystring = 'querystring',\n Storage = 'storage',\n Navigator = 'navigator',\n HtmlTag = 'htmlTag',\n}\n\n// Default settings for the language detector\ntype LanguageDetectorOptions = {\n order?: LanguageDetector[];\n lookupQuerystring?: string;\n htmlTag?: HTMLElement | null;\n};\n\nconst getDefaultsOptions = (): LanguageDetectorOptions => {\n return {\n order: [\n LanguageDetector.Querystring,\n LanguageDetector.Storage,\n LanguageDetector.Navigator,\n LanguageDetector.HtmlTag,\n ],\n lookupQuerystring: 'locale',\n htmlTag: typeof document !== 'undefined' ? document.documentElement : null,\n };\n};\n\nconst detectLanguage = (\n order: string[],\n options: LanguageDetectorOptions\n): Record<LanguageDetector, Locale | undefined> => {\n const detected: Record<LanguageDetector, Locale | undefined> = {} as Record<\n LanguageDetector,\n Locale | undefined\n >;\n\n const queryStringDetector = () => {\n if (typeof window === 'undefined') return;\n const search = window.location.search || '';\n const params = new URLSearchParams(search);\n const value = params.get(options.lookupQuerystring ?? '');\n if (value) {\n detected[LanguageDetector.Querystring] = value as Locale;\n }\n };\n\n const storageDetector = () => {\n if (typeof window === 'undefined') return;\n\n const locale = getLocaleFromStorageClient({\n getCookie: (name: string) => {\n try {\n const cookies = document.cookie.split(';');\n const cookieName = `${name}=`;\n\n const cookie = cookies.find((cookie) =>\n cookie.trim().startsWith(cookieName)\n );\n\n if (cookie) {\n return cookie.split('=')[1].trim();\n }\n } catch {}\n return undefined;\n },\n getSessionStorage: (name: string) => {\n try {\n return window.sessionStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n getLocaleStorage: (name: string) => {\n try {\n return window.localStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n });\n\n if (locale) {\n detected[LanguageDetector.Storage] = locale;\n }\n };\n\n const navigatorDetector = () => {\n if (typeof navigator === 'undefined') return;\n\n const languages = navigator.languages ?? [navigator.language];\n\n // Use localeDetector to find the best matching locale\n const locale = localeDetector(\n { 'accept-language': languages.join(',') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n if (locale) {\n detected[LanguageDetector.Navigator] = locale;\n }\n };\n\n const htmlTagDetector = () => {\n const htmlTag = options.htmlTag;\n if (htmlTag && typeof htmlTag.getAttribute === 'function') {\n const lang = htmlTag.getAttribute('lang');\n if (lang) {\n // Validate and resolve the locale\n\n const locale = localeDetector(\n { 'accept-language': lang },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n detected[LanguageDetector.HtmlTag] = locale;\n }\n }\n };\n\n // Map detector names to their corresponding functions\n const detectors: Record<string, () => void> = {\n [LanguageDetector.Querystring]: queryStringDetector,\n [LanguageDetector.Storage]: storageDetector,\n [LanguageDetector.Navigator]: navigatorDetector,\n [LanguageDetector.HtmlTag]: htmlTagDetector,\n };\n\n // Use the provided order to run each detector\n order.forEach((detectorName) => {\n detectors[detectorName]?.();\n });\n\n return detected;\n};\n\nconst getFirstAvailableLocale = (\n locales: Record<LanguageDetector, Locale | undefined>,\n order: LanguageDetector[]\n): Locale => {\n for (const detector of order) {\n const locale = locales[detector];\n\n if (locale && internationalization.locales.includes(locale)) {\n return locale;\n }\n }\n\n return internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n};\n\n/**\n * Core language detector function for browser environments.\n *\n * Detects the user's preferred locale by checking multiple sources in order:\n * 1. Query string parameter\n * 2. Storage (cookies, localStorage, sessionStorage) - uses getLocaleFromStorage\n * 3. Navigator languages - uses localeDetector\n * 4. HTML lang attribute - uses localeDetector\n *\n * @param userOptions - Optional configuration for detection order and lookup keys\n * @returns The detected locale or the default locale\n *\n * @example\n * const locale = getBrowserLocale({ order: [LanguageDetector.Storage, LanguageDetector.Navigator] });\n */\nexport const getBrowserLocale = (\n userOptions: LanguageDetectorOptions | undefined = {}\n): Locale => {\n const options = { ...getDefaultsOptions(), ...userOptions };\n\n const locales = detectLanguage(options.order ?? [], options);\n\n return getFirstAvailableLocale(locales, options.order ?? []);\n};\n"],"mappings":";;;;;;;AAMA,IAAY,mBAAL;CACL;CACA;CACA;CACA;;AACF;AASA,MAAM,2BAAoD;CACxD,OAAO;EACL,OAAO;;;;;EAKP;EACA,mBAAmB;EACnB,SAAS,OAAO,aAAa,cAAc,SAAS,kBAAkB;CACxE;AACF;AAEA,MAAM,kBACJ,OACA,YACiD;CACjD,MAAM,WAAyD,CAAC;CAKhE,MAAM,4BAA4B;EAChC,IAAI,OAAO,WAAW,aAAa;EACnC,MAAM,SAAS,OAAO,SAAS,UAAU;EAEzC,MAAM,QAAQ,IADK,gBAAgB,MAChB,EAAE,IAAI,QAAQ,qBAAqB,EAAE;EACxD,IAAI,OACF,0BAAyC;CAE7C;CAEA,MAAM,wBAAwB;EAC5B,IAAI,OAAO,WAAW,aAAa;EAEnC,MAAM,SAASA,uDAA2B;GACxC,YAAY,SAAiB;IAC3B,IAAI;KACF,MAAM,UAAU,SAAS,OAAO,MAAM,GAAG;KACzC,MAAM,aAAa,GAAG,KAAK;KAE3B,MAAM,SAAS,QAAQ,MAAM,WAC3B,OAAO,KAAK,EAAE,WAAW,UAAU,CACrC;KAEA,IAAI,QACF,OAAO,OAAO,MAAM,GAAG,EAAE,GAAG,KAAK;IAErC,QAAQ,CAAC;GAEX;GACA,oBAAoB,SAAiB;IACnC,IAAI;KACF,OAAO,OAAO,eAAe,QAAQ,IAAI,KAAK;IAChD,QAAQ,CAAC;GAEX;GACA,mBAAmB,SAAiB;IAClC,IAAI;KACF,OAAO,OAAO,aAAa,QAAQ,IAAI,KAAK;IAC9C,QAAQ,CAAC;GAEX;EACF,CAAC;EAED,IAAI,QACF,sBAAqC;CAEzC;CAEA,MAAM,0BAA0B;EAC9B,IAAI,OAAO,cAAc,aAAa;EAKtC,MAAM,SAASC,mDACb,EAAE,oBAJc,UAAU,aAAa,CAAC,UAAU,QAAQ,GAI3B,KAAK,GAAG,EAAE,GACzCC,4CAAqB,SACrBA,4CAAqB,aACvB;EAEA,IAAI,QACF,wBAAuC;CAE3C;CAEA,MAAM,wBAAwB;EAC5B,MAAM,UAAU,QAAQ;EACxB,IAAI,WAAW,OAAO,QAAQ,iBAAiB,YAAY;GACzD,MAAM,OAAO,QAAQ,aAAa,MAAM;GACxC,IAAI,MASF,sBANeD,mDACb,EAAE,mBAAmB,KAAK,GAC1BC,4CAAqB,SACrBA,4CAAqB,aAGmB;EAE9C;CACF;CAGA,MAAM,YAAwC;mBACZ;eACJ;iBACE;eACF;CAC9B;CAGA,MAAM,SAAS,iBAAiB;EAC9B,UAAU,gBAAgB;CAC5B,CAAC;CAED,OAAO;AACT;AAEA,MAAM,2BACJ,SACA,UACW;CACX,KAAK,MAAM,YAAY,OAAO;EAC5B,MAAM,SAAS,QAAQ;EAEvB,IAAI,UAAUA,4CAAqB,QAAQ,SAAS,MAAM,GACxD,OAAO;CAEX;CAEA,OAAOA,6CAAsB,iBAAiBC;AAChD;;;;;;;;;;;;;;;;AAiBA,MAAa,oBACX,cAAmD,CAAC,MACzC;CACX,MAAM,UAAU;EAAE,GAAG,mBAAmB;EAAG,GAAG;CAAY;CAI1D,OAAO,wBAFS,eAAe,QAAQ,SAAS,CAAC,GAAG,OAEf,GAAG,QAAQ,SAAS,CAAC,CAAC;AAC7D"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_utils_localeStorage = require('../utils/localeStorage.cjs');
|
|
4
3
|
const require_localization_localeResolver = require('./localeResolver.cjs');
|
|
5
4
|
const require_localization_localeDetector = require('./localeDetector.cjs');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE","LOCALES","getLocaleFromStorageServer","localeResolver","getPreferredLanguages"],"sources":["../../../src/localization/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE, LOCALES } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageServer } from '../utils/localeStorage';\nimport { getPreferredLanguages } from './localeDetector';\nimport { localeResolver } from './localeResolver';\n\nexport type RequestContext = {\n getHeader?: (name: string) => string | null | undefined;\n getCookie?: (name: string) => string | null | undefined;\n};\n\nexport const getLocale = async (ctx: RequestContext = {}): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n const availableLocales = internationalization?.locales ?? LOCALES;\n\n // Try locale from storage (cookie or header)\n const storedLocale = getLocaleFromStorageServer({\n getCookie: ctx.getCookie,\n getHeader: ctx.getHeader,\n });\n\n if (storedLocale) {\n return storedLocale;\n }\n\n // Fallback to Accept-Language negotiation\n const acceptLanguageHeader = ctx.getHeader?.('accept-language');\n\n if (!acceptLanguageHeader) {\n return defaultLocale;\n }\n\n const preferredLocaleStrings = getPreferredLanguages(\n acceptLanguageHeader,\n availableLocales\n );\n\n const userFallbackLocale = localeResolver(\n preferredLocaleStrings,\n availableLocales,\n defaultLocale\n );\n\n if (userFallbackLocale) {\n return userFallbackLocale;\n }\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE","LOCALES","getLocaleFromStorageServer","localeResolver","getPreferredLanguages"],"sources":["../../../src/localization/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE, LOCALES } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageServer } from '../utils/localeStorage';\nimport { getPreferredLanguages } from './localeDetector';\nimport { localeResolver } from './localeResolver';\n\nexport type RequestContext = {\n getHeader?: (name: string) => string | null | undefined;\n getCookie?: (name: string) => string | null | undefined;\n};\n\nexport const getLocale = async (ctx: RequestContext = {}): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n const availableLocales = internationalization?.locales ?? LOCALES;\n\n // Try locale from storage (cookie or header)\n const storedLocale = getLocaleFromStorageServer({\n getCookie: ctx.getCookie,\n getHeader: ctx.getHeader,\n });\n\n if (storedLocale) {\n return storedLocale;\n }\n\n // Fallback to Accept-Language negotiation\n const acceptLanguageHeader = ctx.getHeader?.('accept-language');\n\n if (!acceptLanguageHeader) {\n return defaultLocale;\n }\n\n const preferredLocaleStrings = getPreferredLanguages(\n acceptLanguageHeader,\n availableLocales\n );\n\n const userFallbackLocale = localeResolver(\n preferredLocaleStrings,\n availableLocales,\n defaultLocale\n );\n\n if (userFallbackLocale) {\n return userFallbackLocale;\n }\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;AAYA,MAAa,YAAY,OAAO,MAAsB,CAAC,MAAuB;CAC5E,MAAM,gBAAgBA,6CAAsB,iBAAiBC;CAC7D,MAAM,mBAAmBD,6CAAsB,WAAWE;CAG1D,MAAM,eAAeC,uDAA2B;EAC9C,WAAW,IAAI;EACf,WAAW,IAAI;CACjB,CAAC;CAED,IAAI,cACF,OAAO;CAIT,MAAM,uBAAuB,IAAI,YAAY,iBAAiB;CAE9D,IAAI,CAAC,sBACH,OAAO;CAQT,MAAM,qBAAqBC,mDALIC,0DAC7B,sBACA,gBAIqB,GACrB,kBACA,aACF;CAEA,IAAI,oBACF,OAAO;CAIT,OAAO;AACT"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
|
|
4
3
|
const require_localization_getPathWithoutLocale = require('./getPathWithoutLocale.cjs');
|
|
5
4
|
const require_localization_getPrefix = require('./getPrefix.cjs');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocalizedUrl.cjs","names":["internationalization","resolveRoutingConfig","getPathWithoutLocale","getRewriteRules","getLocalizedPath","getCanonicalPath","checkIsURLAbsolute","getPrefix"],"sources":["../../../src/localization/getLocalizedUrl.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\nimport {\n getPrefix,\n type RoutingOptions,\n resolveRoutingConfig,\n} from './getPrefix';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from './rewriteUtils';\n\nexport type { RoutingOptions };\n\n/** Strips the protocol and returns the bare hostname of a domain string. */\nconst extractHostname = (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 * Generate URL by prefixing the given URL with the referenced locale or adding search parameters\n * based on the routing mode. Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' });\n * // Returns '/fr/about' for the French locale\n * // Returns '/about' for the English locale (default)\n *\n * // prefix-all mode\n * getLocalizedUrl('/about', 'en', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' });\n * // Returns '/en/about' for the English locale\n * // Returns '/fr/about' for the French locale\n *\n * // search-params mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' });\n * // Returns '/about?locale=fr' for the French locale\n *\n * // no-prefix mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' });\n * // Returns '/about' for any locale\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param currentLocale - The current locale.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @param options.currentDomain - Hostname of the page being rendered. Used to decide\n * whether to emit a relative URL (same domain) or an absolute URL (cross-domain).\n * Auto-detected from the input URL or `window.location` when omitted.\n * @returns The localized URL for the current locale.\n */\nexport const getLocalizedUrl = (\n url: string,\n currentLocale: LocalesValues = internationalization?.defaultLocale,\n options: RoutingOptions = {}\n): string => {\n const { defaultLocale, mode, locales, rewrite, domains, currentDomain } =\n resolveRoutingConfig(options);\n\n const urlWithoutLocale = getPathWithoutLocale(url, locales);\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n if (\n !(\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix'\n ) &&\n mode === 'no-prefix'\n ) {\n return getLocalizedPath(\n getCanonicalPath(urlWithoutLocale, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n }\n\n const isAbsoluteUrl = checkIsURLAbsolute(urlWithoutLocale);\n const parsedUrl = isAbsoluteUrl\n ? new URL(urlWithoutLocale)\n : new URL(urlWithoutLocale, 'http://example.com');\n\n const translatedPathname = getLocalizedPath(\n getCanonicalPath(parsedUrl.pathname, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n\n // ── Domain routing ────────────────────────────────────────────────────────\n // Resolve the \"current\" hostname so we can choose between a relative URL\n // (same domain) and an absolute URL (cross-domain).\n //\n // Detection priority:\n // 1. Explicit `currentDomain` option passed by the caller.\n // 2. Hostname extracted from an absolute input URL.\n // 3. `window.location.hostname` in browser environments.\n // When none of these is available we fall back to always generating an\n // absolute URL (the previous behaviour, safe for SSR/static generation).\n const detectedCurrentHostname =\n process.env['INTLAYER_ROUTING_DOMAINS'] !== 'false'\n ? extractHostname(\n currentDomain ??\n (isAbsoluteUrl ? parsedUrl.hostname : undefined) ??\n (typeof window !== 'undefined'\n ? window?.location?.hostname\n : undefined) ??\n ''\n ) || null\n : null;\n\n const localeDomain =\n process.env['INTLAYER_ROUTING_DOMAINS'] !== 'false'\n ? domains?.[currentLocale as LocalesValues]\n : undefined;\n\n const localeDomainHostname = localeDomain\n ? extractHostname(localeDomain)\n : null;\n\n // Only prepend the locale's domain when it differs from the current hostname.\n const isCrossDomain =\n localeDomainHostname !== null &&\n detectedCurrentHostname !== null &&\n localeDomainHostname !== detectedCurrentHostname;\n\n const normalizedDomain =\n isCrossDomain && localeDomain\n ? /^https?:\\/\\//.test(localeDomain)\n ? localeDomain\n : `https://${localeDomain}`\n : null;\n\n const baseUrl = normalizedDomain\n ? normalizedDomain\n : isAbsoluteUrl\n ? `${parsedUrl.protocol}//${parsedUrl.host}`\n : '';\n // ─────────────────────────────────────────────────────────────────────────\n\n if (\n !(\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params'\n ) &&\n mode === 'search-params'\n ) {\n const searchParams = new URLSearchParams(parsedUrl.search);\n\n searchParams.set('locale', currentLocale.toString());\n\n const queryParams = searchParams.toString();\n const path = queryParams\n ? `${translatedPathname}?${queryParams}`\n : translatedPathname;\n\n return `${baseUrl}${path}${parsedUrl.hash}`;\n }\n\n const { prefix } = getPrefix(currentLocale, {\n defaultLocale,\n mode,\n locales,\n domains,\n });\n\n let localizedPath = `/${prefix}${translatedPathname}`.replace(/\\/+/g, '/');\n\n if (localizedPath.length > 1 && localizedPath.endsWith('/')) {\n localizedPath = localizedPath.slice(0, -1);\n }\n\n return `${baseUrl}${localizedPath}${parsedUrl.search}${parsedUrl.hash}`;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getLocalizedUrl.cjs","names":["internationalization","resolveRoutingConfig","getPathWithoutLocale","getRewriteRules","getLocalizedPath","getCanonicalPath","checkIsURLAbsolute","getPrefix"],"sources":["../../../src/localization/getLocalizedUrl.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\nimport {\n getPrefix,\n type RoutingOptions,\n resolveRoutingConfig,\n} from './getPrefix';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from './rewriteUtils';\n\nexport type { RoutingOptions };\n\n/** Strips the protocol and returns the bare hostname of a domain string. */\nconst extractHostname = (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 * Generate URL by prefixing the given URL with the referenced locale or adding search parameters\n * based on the routing mode. Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' });\n * // Returns '/fr/about' for the French locale\n * // Returns '/about' for the English locale (default)\n *\n * // prefix-all mode\n * getLocalizedUrl('/about', 'en', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' });\n * // Returns '/en/about' for the English locale\n * // Returns '/fr/about' for the French locale\n *\n * // search-params mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' });\n * // Returns '/about?locale=fr' for the French locale\n *\n * // no-prefix mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' });\n * // Returns '/about' for any locale\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param currentLocale - The current locale.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @param options.currentDomain - Hostname of the page being rendered. Used to decide\n * whether to emit a relative URL (same domain) or an absolute URL (cross-domain).\n * Auto-detected from the input URL or `window.location` when omitted.\n * @returns The localized URL for the current locale.\n */\nexport const getLocalizedUrl = (\n url: string,\n currentLocale: LocalesValues = internationalization?.defaultLocale,\n options: RoutingOptions = {}\n): string => {\n const { defaultLocale, mode, locales, rewrite, domains, currentDomain } =\n resolveRoutingConfig(options);\n\n const urlWithoutLocale = getPathWithoutLocale(url, locales);\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n if (\n !(\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix'\n ) &&\n mode === 'no-prefix'\n ) {\n return getLocalizedPath(\n getCanonicalPath(urlWithoutLocale, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n }\n\n const isAbsoluteUrl = checkIsURLAbsolute(urlWithoutLocale);\n const parsedUrl = isAbsoluteUrl\n ? new URL(urlWithoutLocale)\n : new URL(urlWithoutLocale, 'http://example.com');\n\n const translatedPathname = getLocalizedPath(\n getCanonicalPath(parsedUrl.pathname, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n\n // ── Domain routing ────────────────────────────────────────────────────────\n // Resolve the \"current\" hostname so we can choose between a relative URL\n // (same domain) and an absolute URL (cross-domain).\n //\n // Detection priority:\n // 1. Explicit `currentDomain` option passed by the caller.\n // 2. Hostname extracted from an absolute input URL.\n // 3. `window.location.hostname` in browser environments.\n // When none of these is available we fall back to always generating an\n // absolute URL (the previous behaviour, safe for SSR/static generation).\n const detectedCurrentHostname =\n process.env['INTLAYER_ROUTING_DOMAINS'] !== 'false'\n ? extractHostname(\n currentDomain ??\n (isAbsoluteUrl ? parsedUrl.hostname : undefined) ??\n (typeof window !== 'undefined'\n ? window?.location?.hostname\n : undefined) ??\n ''\n ) || null\n : null;\n\n const localeDomain =\n process.env['INTLAYER_ROUTING_DOMAINS'] !== 'false'\n ? domains?.[currentLocale as LocalesValues]\n : undefined;\n\n const localeDomainHostname = localeDomain\n ? extractHostname(localeDomain)\n : null;\n\n // Only prepend the locale's domain when it differs from the current hostname.\n const isCrossDomain =\n localeDomainHostname !== null &&\n detectedCurrentHostname !== null &&\n localeDomainHostname !== detectedCurrentHostname;\n\n const normalizedDomain =\n isCrossDomain && localeDomain\n ? /^https?:\\/\\//.test(localeDomain)\n ? localeDomain\n : `https://${localeDomain}`\n : null;\n\n const baseUrl = normalizedDomain\n ? normalizedDomain\n : isAbsoluteUrl\n ? `${parsedUrl.protocol}//${parsedUrl.host}`\n : '';\n // ─────────────────────────────────────────────────────────────────────────\n\n if (\n !(\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params'\n ) &&\n mode === 'search-params'\n ) {\n const searchParams = new URLSearchParams(parsedUrl.search);\n\n searchParams.set('locale', currentLocale.toString());\n\n const queryParams = searchParams.toString();\n const path = queryParams\n ? `${translatedPathname}?${queryParams}`\n : translatedPathname;\n\n return `${baseUrl}${path}${parsedUrl.hash}`;\n }\n\n const { prefix } = getPrefix(currentLocale, {\n defaultLocale,\n mode,\n locales,\n domains,\n });\n\n let localizedPath = `/${prefix}${translatedPathname}`.replace(/\\/+/g, '/');\n\n if (localizedPath.length > 1 && localizedPath.endsWith('/')) {\n localizedPath = localizedPath.slice(0, -1);\n }\n\n return `${baseUrl}${localizedPath}${parsedUrl.search}${parsedUrl.hash}`;\n};\n"],"mappings":";;;;;;;;;AAwBA,MAAM,mBAAmB,WAA2B;CAClD,IAAI;EACF,OAAO,eAAe,KAAK,MAAM,IAAI,IAAI,IAAI,MAAM,EAAE,WAAW;CAClE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,mBACX,KACA,gBAA+BA,6CAAsB,eACrD,UAA0B,CAAC,MAChB;CACX,MAAM,EAAE,eAAe,MAAM,SAAS,SAAS,SAAS,kBACtDC,oDAAqB,OAAO;CAE9B,MAAM,mBAAmBC,+DAAqB,KAAK,OAAO;CAC1D,MAAM,eAAeC,kDAAgB,SAAS,KAAK;CAEnD,IACE,EACE,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBAE3C,SAAS,aAET,OAAOC,mDACLC,mDAAiB,kBAAkB,QAAW,YAAY,GAC1D,eACA,YACF,EAAE;CAGJ,MAAM,gBAAgBC,oDAAmB,gBAAgB;CACzD,MAAM,YAAY,gBACd,IAAI,IAAI,gBAAgB,IACxB,IAAI,IAAI,kBAAkB,oBAAoB;CAElD,MAAM,qBAAqBF,mDACzBC,mDAAiB,UAAU,UAAU,QAAW,YAAY,GAC5D,eACA,YACF,EAAE;CAYF,MAAM,0BACJ,QAAQ,IAAI,gCAAgC,UACxC,gBACE,kBACG,gBAAgB,UAAU,WAAW,YACrC,OAAO,WAAW,cACf,QAAQ,UAAU,WAClB,WACJ,EACJ,KAAK,OACL;CAEN,MAAM,eACJ,QAAQ,IAAI,gCAAgC,UACxC,UAAU,iBACV;CAEN,MAAM,uBAAuB,eACzB,gBAAgB,YAAY,IAC5B;CAQJ,MAAM,mBAJJ,yBAAyB,QACzB,4BAA4B,QAC5B,yBAAyB,2BAGR,eACb,eAAe,KAAK,YAAY,IAC9B,eACA,WAAW,iBACb;CAEN,MAAM,UAAU,mBACZ,mBACA,gBACE,GAAG,UAAU,SAAS,IAAI,UAAU,SACpC;CAGN,IACE,EACE,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,oBAE3C,SAAS,iBACT;EACA,MAAM,eAAe,IAAI,gBAAgB,UAAU,MAAM;EAEzD,aAAa,IAAI,UAAU,cAAc,SAAS,CAAC;EAEnD,MAAM,cAAc,aAAa,SAAS;EAK1C,OAAO,GAAG,UAJG,cACT,GAAG,mBAAmB,GAAG,gBACzB,qBAEuB,UAAU;CACvC;CAEA,MAAM,EAAE,WAAWE,yCAAU,eAAe;EAC1C;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,gBAAgB,IAAI,SAAS,qBAAqB,QAAQ,QAAQ,GAAG;CAEzE,IAAI,cAAc,SAAS,KAAK,cAAc,SAAS,GAAG,GACxD,gBAAgB,cAAc,MAAM,GAAG,EAAE;CAG3C,OAAO,GAAG,UAAU,gBAAgB,UAAU,SAAS,UAAU;AACnE"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
|
|
4
3
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
4
|
|