@intlayer/core 9.5.9-canary.0 → 9.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
  2. package/dist/cjs/index.cjs +4 -0
  3. package/dist/cjs/interpreter/getContent/deepTransform.cjs +17 -22
  4. package/dist/cjs/interpreter/getContent/deepTransform.cjs.map +1 -1
  5. package/dist/cjs/interpreter/getContent/getContent.cjs +2 -1
  6. package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
  7. package/dist/cjs/interpreter/getContent/plugins.cjs +32 -37
  8. package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
  9. package/dist/cjs/interpreter/getDictionary.cjs +20 -5
  10. package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
  11. package/dist/cjs/interpreter/getTranslation.cjs +31 -27
  12. package/dist/cjs/interpreter/getTranslation.cjs.map +1 -1
  13. package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
  14. package/dist/cjs/localization/localeResolver.cjs +1 -0
  15. package/dist/cjs/localization/localeResolver.cjs.map +1 -1
  16. package/dist/cjs/markdown/compiler.cjs +12 -3
  17. package/dist/cjs/markdown/compiler.cjs.map +1 -1
  18. package/dist/cjs/markdown/constants.cjs +3 -0
  19. package/dist/cjs/markdown/constants.cjs.map +1 -1
  20. package/dist/cjs/markdown/index.cjs +1 -0
  21. package/dist/cjs/markdown/utils.cjs +1 -1
  22. package/dist/cjs/markdown/utils.cjs.map +1 -1
  23. package/dist/cjs/messageFormat/ICU.cjs +10 -10
  24. package/dist/cjs/messageFormat/ICU.cjs.map +1 -1
  25. package/dist/cjs/messageFormat/i18next.cjs +7 -7
  26. package/dist/cjs/messageFormat/i18next.cjs.map +1 -1
  27. package/dist/cjs/messageFormat/po.cjs +1 -1
  28. package/dist/cjs/messageFormat/po.cjs.map +1 -1
  29. package/dist/cjs/messageFormat/resolveMessage.cjs +2 -2
  30. package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
  31. package/dist/cjs/messageFormat/verify-icu-format.cjs +4 -4
  32. package/dist/cjs/messageFormat/verify-icu-format.cjs.map +1 -1
  33. package/dist/cjs/messageFormat/vue-i18n.cjs +4 -4
  34. package/dist/cjs/messageFormat/vue-i18n.cjs.map +1 -1
  35. package/dist/cjs/utils/index.cjs +3 -0
  36. package/dist/cjs/utils/intlayerNodePrototype.cjs +66 -0
  37. package/dist/cjs/utils/intlayerNodePrototype.cjs.map +1 -0
  38. package/dist/cjs/utils/localeStorage.cjs +20 -0
  39. package/dist/cjs/utils/localeStorage.cjs.map +1 -1
  40. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
  41. package/dist/esm/index.mjs +4 -3
  42. package/dist/esm/interpreter/getContent/deepTransform.mjs +17 -22
  43. package/dist/esm/interpreter/getContent/deepTransform.mjs.map +1 -1
  44. package/dist/esm/interpreter/getContent/getContent.mjs +3 -2
  45. package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
  46. package/dist/esm/interpreter/getContent/plugins.mjs +32 -37
  47. package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
  48. package/dist/esm/interpreter/getDictionary.mjs +20 -5
  49. package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
  50. package/dist/esm/interpreter/getTranslation.mjs +31 -27
  51. package/dist/esm/interpreter/getTranslation.mjs.map +1 -1
  52. package/dist/esm/localization/getPathWithoutLocale.mjs.map +1 -1
  53. package/dist/esm/localization/localeResolver.mjs +1 -0
  54. package/dist/esm/localization/localeResolver.mjs.map +1 -1
  55. package/dist/esm/markdown/compiler.mjs +13 -4
  56. package/dist/esm/markdown/compiler.mjs.map +1 -1
  57. package/dist/esm/markdown/constants.mjs +3 -1
  58. package/dist/esm/markdown/constants.mjs.map +1 -1
  59. package/dist/esm/markdown/index.mjs +2 -2
  60. package/dist/esm/markdown/utils.mjs +1 -1
  61. package/dist/esm/markdown/utils.mjs.map +1 -1
  62. package/dist/esm/messageFormat/ICU.mjs +10 -10
  63. package/dist/esm/messageFormat/ICU.mjs.map +1 -1
  64. package/dist/esm/messageFormat/i18next.mjs +7 -7
  65. package/dist/esm/messageFormat/i18next.mjs.map +1 -1
  66. package/dist/esm/messageFormat/po.mjs +1 -1
  67. package/dist/esm/messageFormat/po.mjs.map +1 -1
  68. package/dist/esm/messageFormat/resolveMessage.mjs +2 -2
  69. package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
  70. package/dist/esm/messageFormat/verify-icu-format.mjs +4 -4
  71. package/dist/esm/messageFormat/verify-icu-format.mjs.map +1 -1
  72. package/dist/esm/messageFormat/vue-i18n.mjs +4 -4
  73. package/dist/esm/messageFormat/vue-i18n.mjs.map +1 -1
  74. package/dist/esm/utils/index.mjs +3 -2
  75. package/dist/esm/utils/intlayerNodePrototype.mjs +65 -0
  76. package/dist/esm/utils/intlayerNodePrototype.mjs.map +1 -0
  77. package/dist/esm/utils/localeStorage.mjs +20 -1
  78. package/dist/esm/utils/localeStorage.mjs.map +1 -1
  79. package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +1 -1
  80. package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +1 -1
  81. package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +1 -1
  82. package/dist/types/index.d.ts +4 -3
  83. package/dist/types/interpreter/getContent/deepTransform.d.ts.map +1 -1
  84. package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
  85. package/dist/types/interpreter/getContent/plugins.d.ts +3 -1
  86. package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
  87. package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
  88. package/dist/types/interpreter/getTranslation.d.ts.map +1 -1
  89. package/dist/types/markdown/compiler.d.ts +1 -0
  90. package/dist/types/markdown/compiler.d.ts.map +1 -1
  91. package/dist/types/markdown/constants.d.ts +2 -0
  92. package/dist/types/markdown/constants.d.ts.map +1 -1
  93. package/dist/types/markdown/index.d.ts +2 -2
  94. package/dist/types/messageFormat/ICU.d.ts.map +1 -1
  95. package/dist/types/messageFormat/i18next.d.ts.map +1 -1
  96. package/dist/types/messageFormat/vue-i18n.d.ts.map +1 -1
  97. package/dist/types/utils/index.d.ts +3 -2
  98. package/dist/types/utils/intlayerNodePrototype.d.ts +15 -0
  99. package/dist/types/utils/intlayerNodePrototype.d.ts.map +1 -0
  100. package/dist/types/utils/localeStorage.d.ts +9 -0
  101. package/dist/types/utils/localeStorage.d.ts.map +1 -1
  102. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.mjs","names":["getNestingOptimized"],"sources":["../../../../src/interpreter/getContent/plugins.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type {\n ConditionContent,\n EnumerationContent,\n FileContent,\n Gender,\n GenderContent,\n InsertionContent,\n NestedContent,\n PluralContent,\n PluralContentState,\n SelectContent,\n TranslationContent,\n} from '../../transpiler';\nimport { getCondition } from '../getCondition';\nimport { getEnumeration } from '../getEnumeration';\nimport { getGender } from '../getGender';\nimport { getInsertion } from '../getInsertion';\nimport { type GetNestingResult, getNesting } from '../getNesting';\nimport { getNesting as getNestingOptimized } from '../getNesting.optimized';\nimport { getPlural } from '../getPlural';\nimport { getSelect } from '../getSelect';\nimport { getTranslation } from '../getTranslation';\nimport {\n isInterpolableWrapperNode,\n transformInterpolableNode,\n} from '../interpolableNode';\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\n/** ---------------------------------------------\n * PLUGIN DEFINITION\n * --------------------------------------------- */\n\n/**\n * A plugin/transformer that can optionally transform a node during a single DFS pass.\n * - `canHandle` decides if the node is transformable by this plugin.\n * - `transform` returns the transformed node (and does not recurse further).\n *\n * > `transformFn` is a function that can be used to deeply transform inside the plugin.\n */\nexport type Plugins = {\n id: string;\n canHandle: (node: any) => boolean;\n transform: (\n node: any,\n props: NodeProps,\n transformFn: (node: any, props: NodeProps) => any\n ) => any;\n};\n\n/** ---------------------------------------------\n * FALLBACK PLUGIN\n *\n * Used to fallback a tree-shaken plugin\n * --------------------------------------------- */\n\nexport const fallbackPlugin: Plugins = {\n id: 'fallback-plugin',\n canHandle: () => false,\n transform: (node) => node,\n};\n\n/** ---------------------------------------------\n * TRANSLATION PLUGIN\n * --------------------------------------------- */\n\nexport type UnionKeys<T> = T extends unknown ? keyof T : never;\nexport type ValueAtKey<T, K> = T extends unknown\n ? K extends keyof T\n ? T[K]\n : never\n : never;\n\nexport type TranslationCond<T, S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.TRANSLATION]: infer U;\n}\n ? U extends Record<PropertyKey, unknown>\n ? U[keyof U] extends Record<PropertyKey, unknown>\n ? {\n [K in UnionKeys<U[keyof U]>]: L extends keyof U\n ? K extends keyof U[L]\n ? U[L][K]\n : ValueAtKey<U[keyof U], K>\n : ValueAtKey<U[keyof U], K>;\n } extends infer Content\n ? DeepTransformContent<Content, S>\n : never\n : (L extends keyof U ? U[L] : U[keyof U]) extends infer Content\n ? DeepTransformContent<Content, S>\n : never\n : never\n : never;\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const translationPlugin = (\n locale: LocalesValues,\n fallback?: LocalesValues\n): Plugins =>\n process.env.INTLAYER_NODE_TYPE_TRANSLATION === 'false'\n ? fallbackPlugin\n : {\n id: 'translation-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.TRANSLATION,\n transform: (node: TranslationContent, props, deepTransformNode) => {\n const original = node[NodeTypes.TRANSLATION] ?? {};\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const childProps = {\n ...props,\n children: original[key as keyof typeof original],\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.TRANSLATION, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(\n original[key as keyof typeof original],\n childProps\n );\n }\n\n return getTranslation(result, locale, fallback);\n },\n };\n\n/** ---------------------------------------------\n * ENUMERATION PLUGIN\n * --------------------------------------------- */\n\nexport type EnumerationCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.ENUMERATION]: object;\n}\n ? (\n quantity: number\n ) => DeepTransformContent<\n T[typeof NodeTypes.ENUMERATION][keyof T[typeof NodeTypes.ENUMERATION]],\n S\n >\n : never;\n\n/** Enumeration plugin. Replaces node with a function that takes quantity => string. */\nexport const enumerationPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_ENUMERATION === 'false'\n ? fallbackPlugin\n : {\n id: 'enumeration-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.ENUMERATION,\n transform: (node: EnumerationContent, props, deepTransformNode) => {\n const original = node[NodeTypes.ENUMERATION];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as unknown as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.ENUMERATION, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: number | { count: number }) => {\n const quantity = typeof arg === 'number' ? arg : arg.count;\n const subResult = getEnumeration(result, quantity);\n\n if (typeof subResult === 'function' && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * PLURAL PLUGIN\n * --------------------------------------------- */\n\n/**\n * A plural branch wrapped in an `insertion` node (auto-transformed\n * `{{count}}`) resolves to its inner content: the plural applies the values.\n */\ntype PluralBranch<Branch> = Branch extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer InsertionContent;\n fields: readonly string[];\n}\n ? InsertionContent\n : Branch;\n\nexport type PluralCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.PLURAL]: object;\n}\n ? (\n arg: number | { count: number; [key: string]: unknown }\n ) => DeepTransformContent<\n PluralBranch<\n T[typeof NodeTypes.PLURAL][keyof T[typeof NodeTypes.PLURAL]]\n >,\n S\n >\n : never;\n\ntype SubResultFunction = (values: Record<string, string | number>) => string;\n\n/**\n * Plural plugin. Replaces node with a function that takes a count (or\n * `{ count, ...values }`) => string, picking the matching CLDR plural form\n * for the active locale and interpolating `{{count}}` (and other values).\n */\nexport const pluralPlugin = (locale?: LocalesValues): Plugins =>\n process.env.INTLAYER_NODE_TYPE_PLURAL === 'false'\n ? fallbackPlugin\n : {\n id: 'plural-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.PLURAL,\n transform: (node: PluralContent, props, deepTransformNode) => {\n const original = node[NodeTypes.PLURAL];\n const result: Record<string, any> = {};\n // The plural interpolates its own branches. A string plugin from an\n // enclosing `insert()` would turn them into functions first.\n const branchPlugins = (props.plugins ?? []).filter(\n (plugin) => plugin.id !== 'insertion-string-plugin'\n );\n\n /** String plugin for plural. Replaces string node with a component that renders the insertion. */\n const pluralStringPlugin: Plugins = {\n id: 'plural-string-plugin',\n canHandle: (node) =>\n typeof node === 'string' || isInterpolableWrapperNode(node),\n transform: (node, subProps, deepTransformNode) => {\n // An `insertion` node below the plural (e.g. auto-transformed\n // `{{count}}` branches) already returns `(values) => …`. Leave its\n // strings untouched, or its template would become a function.\n const isInsideInsertion = subProps.keyPath\n .slice(props.keyPath.length)\n .some((keyPath) => keyPath.type === NodeTypes.INSERTION);\n\n if (isInsideInsertion) {\n return deepTransformNode(node, {\n ...subProps,\n plugins: subProps.plugins?.filter(\n (plugin) => plugin.id !== 'plural-string-plugin'\n ),\n });\n }\n\n // `html()`/`markdown()` nodes carry their `{{count}}` placeholders\n // inside a raw string. Interpolate into that string, then re-run\n // the transform so the html/markdown renderer applies afterwards.\n if (isInterpolableWrapperNode(node)) {\n return (values: { [k: string]: string | number }) =>\n transformInterpolableNode(\n node,\n values,\n subProps,\n branchPlugins,\n deepTransformNode\n );\n }\n\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...branchPlugins.filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (values: { [k: string]: string | number }) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: branchPlugins,\n children,\n });\n };\n },\n };\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.PLURAL, key } as KeyPath,\n ],\n plugins: [pluralStringPlugin, ...branchPlugins],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n const effectiveLocale = String(locale ?? props.locale ?? 'en');\n\n return (arg: number | { count: number; [key: string]: unknown }) => {\n const count = typeof arg === 'number' ? arg : arg.count;\n const values =\n typeof arg === 'number'\n ? { count: arg }\n : (arg as { count: number; [key: string]: unknown });\n\n const subResult: string | SubResultFunction = getPlural(\n result as PluralContent['plural'] as PluralContentState<string>,\n count,\n effectiveLocale\n );\n\n if (typeof subResult === 'function') {\n return (subResult as SubResultFunction)(values);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * CONDITION PLUGIN\n * --------------------------------------------- */\n\nexport type ConditionCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.CONDITION]: object;\n}\n ? (\n value: boolean | { value: boolean }\n ) => DeepTransformContent<\n T[typeof NodeTypes.CONDITION][keyof T[typeof NodeTypes.CONDITION]],\n S\n >\n : never;\n\n/** Condition plugin. Replaces node with a function that takes boolean => string. */\nexport const conditionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_CONDITION === 'false'\n ? fallbackPlugin\n : {\n id: 'condition-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.CONDITION,\n transform: (node: ConditionContent, props, deepTransformNode) => {\n const original = node[NodeTypes.CONDITION];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.CONDITION, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: boolean | { value: boolean }) => {\n const value = typeof arg === 'boolean' ? arg : arg.value;\n const subResult = getCondition(result as any, value);\n\n if (typeof subResult === 'function' && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer I;\n fields: readonly string[];\n}\n ? (\n values: {\n [K in T['fields'][number]]: string | number;\n }\n ) => I extends string\n ? DeepTransformContent<string, S>\n : DeepTransformContent<I, S>\n : never;\n\n/** Insertion plugin. Replaces node with a function that takes quantity => string. */\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeTypes.INSERTION,\n },\n ];\n\n const children = node[NodeTypes.INSERTION];\n\n /** Insertion string plugin. Replaces string node with a component that render the insertion. */\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) =>\n typeof node === 'string' || isInterpolableWrapperNode(node),\n transform: (node, subProps, deepTransformNode) => {\n // `html()`/`markdown()` nodes carry their `{{ … }}` placeholders\n // inside a raw string. Interpolate into that string, then re-run\n // the transform so the html/markdown renderer applies afterwards.\n if (isInterpolableWrapperNode(node)) {\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) =>\n transformInterpolableNode(\n node,\n values,\n subProps,\n props.plugins,\n deepTransformNode\n );\n }\n\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...(props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: props.plugins,\n children,\n });\n };\n },\n };\n\n const result = deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n\n return resolveInsertedSelector(children, result);\n },\n };\n\n/** Container nodes resolved by a selector call: `enu(3)`, `cond(true)`, … */\nconst selectorNodeTypes: string[] = [\n NodeTypes.ENUMERATION,\n NodeTypes.CONDITION,\n NodeTypes.PLURAL,\n NodeTypes.GENDER,\n NodeTypes.SELECT,\n];\n\n/** Whether `insert()` wraps a selector node that resolved to a function. */\nconst isInsertedSelector = (\n children: unknown,\n result: unknown\n): result is (selector: unknown) => unknown => {\n const nodeType =\n typeof children === 'object' && children !== null\n ? (children as { nodeType?: unknown }).nodeType\n : undefined;\n\n return (\n typeof result === 'function' &&\n typeof nodeType === 'string' &&\n selectorNodeTypes.includes(nodeType)\n );\n};\n\n/**\n * Binds the values of an `insert()` to the selector node it wraps, returning\n * `(selector) => content`. Any other child result is returned unchanged.\n *\n * `areBranchesInterpolated` is set by frameworks that interpolate the branch\n * strings as soon as the values are known: the selected branch is then final\n * content and is never called with the values.\n */\nexport const bindInsertedValues = (\n children: unknown,\n result: unknown,\n values: Record<string, unknown>,\n areBranchesInterpolated = false\n): unknown => {\n if (!isInsertedSelector(children, result)) {\n return result;\n }\n\n const isPlural =\n (children as { nodeType: string }).nodeType === NodeTypes.PLURAL;\n const isEnumeration =\n (children as { nodeType: string }).nodeType === NodeTypes.ENUMERATION;\n\n return (selector: unknown) => {\n // Object selectors (`{ count }`, `{ value }`) carry the values along.\n if (typeof selector === 'object' && selector !== null) {\n return result({ ...values, ...selector });\n }\n\n // Plural interpolates its own branches, `{{count}}` included.\n if (isPlural) {\n return result({ ...values, count: selector });\n }\n\n // Enumeration selector is a numeric count (or count range)\n if (isEnumeration && typeof selector === 'number') {\n const mergedValues = { count: selector, ...values };\n const selected = result(mergedValues);\n\n return !areBranchesInterpolated && typeof selected === 'function'\n ? selected(mergedValues)\n : selected;\n }\n\n const selected = result(selector);\n\n return !areBranchesInterpolated && typeof selected === 'function'\n ? selected(values)\n : selected;\n };\n};\n\n/**\n * Shapes the result of `insert()` wrapping a selector node as\n * `(values) => (selector) => content`, so the values reach the selected\n * branch. Any other child result is returned unchanged.\n */\nexport const resolveInsertedSelector = (\n children: unknown,\n result: unknown\n): unknown =>\n isInsertedSelector(children, result)\n ? (values: Record<string, unknown>) =>\n bindInsertedValues(children, result, values)\n : result;\n\n/** ---------------------------------------------\n * GENDER PLUGIN\n * --------------------------------------------- */\n\nexport type GenderCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.GENDER]: object;\n}\n ? (\n value: Gender\n ) => DeepTransformContent<\n T[typeof NodeTypes.GENDER][keyof T[typeof NodeTypes.GENDER]],\n S\n >\n : never;\n\n/** Gender plugin. Replaces node with a function that takes gender => string. */\nexport const genderPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_GENDER === 'false'\n ? fallbackPlugin\n : {\n id: 'gender-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.GENDER,\n transform: (node: GenderContent, props, deepTransformNode) => {\n const original = node[NodeTypes.GENDER];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.GENDER, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (value: Gender) => getGender(result as any, value);\n },\n };\n\n/** ---------------------------------------------\n * SELECT PLUGIN\n * --------------------------------------------- */\n\n/**\n * Accepted selector for a select node.\n *\n * When the node declares a `fallback` case, any string is accepted (the\n * fallback covers the unmatched values) while the declared cases still\n * autocomplete. Without a `fallback`, only the declared cases are accepted.\n */\nexport type SelectSelector<States> = 'fallback' extends keyof States\n ? Exclude<keyof States & string, 'fallback'> | (string & {})\n : keyof States & string;\n\nexport type SelectCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.SELECT]: object;\n}\n ? (\n value:\n | SelectSelector<T[typeof NodeTypes.SELECT]>\n | { value: SelectSelector<T[typeof NodeTypes.SELECT]> }\n ) => DeepTransformContent<\n T[typeof NodeTypes.SELECT][keyof T[typeof NodeTypes.SELECT]],\n S\n >\n : never;\n\n/** Select plugin. Replaces node with a function that takes a string => content. */\nexport const selectPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_SELECT === 'false'\n ? fallbackPlugin\n : {\n id: 'select-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.SELECT,\n transform: (node: SelectContent, props, deepTransformNode) => {\n const original = node[NodeTypes.SELECT];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.SELECT, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: string | { value: string }) => {\n const value = typeof arg === 'string' ? arg : arg?.value;\n const subResult = getSelect(result, value);\n\n if (typeof subResult === 'function' && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * NESTED PLUGIN\n * --------------------------------------------- */\n\nexport type NestedCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.NESTED]: infer U;\n}\n ? U extends {\n dictionaryKey: infer K extends DictionaryKeys;\n path?: infer P;\n }\n ? GetNestingResult<K, P, S>\n : never\n : never;\n\n/**\n * Resolver used to turn a nested node into content.\n *\n * Optimized builds set `INTLAYER_OPTIMIZED_NESTING` so bundlers fold this to\n * the local resolver and dead-code-eliminate the registry-based one — together\n * with its `getIntlayer` import, and therefore the whole\n * `@intlayer/dictionaries-entry` module. That is what allows the dictionaries\n * entry to be emptied while `nest()` keeps working.\n */\nconst resolveNesting =\n process.env.INTLAYER_OPTIMIZED_NESTING === 'true'\n ? getNestingOptimized\n : getNesting;\n\n/** Nested plugin. Replaces node with the result of `getNesting`. */\nexport const nestedPlugin = (locale?: LocalesValues): Plugins =>\n process.env.INTLAYER_NODE_TYPE_NESTED === 'false'\n ? fallbackPlugin\n : {\n id: 'nested-plugin',\n canHandle: (node) =>\n typeof node === 'object' &&\n (node?.nodeType === NodeTypes.NESTED || node?.nodeType === 'n'),\n transform: (node: NestedContent, props) =>\n resolveNesting(\n node[NodeTypes.NESTED].dictionaryKey,\n node[NodeTypes.NESTED].path,\n {\n ...props,\n locale: (locale ?? props.locale) as Locale,\n }\n ),\n };\n\n/** ---------------------------------------------\n * FILE PLUGIN\n * --------------------------------------------- */\n\nexport type FileCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.FILE]: string;\n content?: string;\n}\n ? DeepTransformContent<string, S>\n : never;\n\n/** File plugin. Replaces node with the result of `getNesting`. */\nexport const filePlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_FILE === 'false'\n ? fallbackPlugin\n : {\n id: 'file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.FILE,\n transform: (node: FileContent, props, deepTransform) =>\n deepTransform(node.content, {\n ...props,\n children: node.content,\n }),\n };\n\n/**\n * PLUGIN RESULT\n */\n\n/**\n * Interface that defines the properties of a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface NodeProps {\n dictionaryKey: string;\n keyPath: KeyPath[];\n plugins?: Plugins[];\n locale?: Locale;\n dictionaryPath?: string;\n children?: any;\n /**\n * Dictionaries referenced through `nest()`, attached to the consuming\n * dictionary by the build optimization and threaded down by\n * `deepTransformNode`.\n *\n * Present only in optimized builds, where the global dictionary registry is\n * stripped and `getNesting` resolves from this map instead. See\n * `getNesting.optimized.ts`.\n */\n nestedDictionaries?: Record<string, unknown>;\n /**\n * Forces eager traversal of plain objects in `deepTransformNode`. By default\n * traversal is lazy (property getters), so callers that discard the returned\n * value never trigger plugins on nested nodes. Set this when running plugins\n * for their side effects only (e.g. missing-locale detection).\n */\n eager?: boolean;\n}\n\n/**\n * Interface that defines the plugins that can be used to transform a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface IInterpreterPlugin<T, S, L extends LocalesValues> {\n translation: TranslationCond<T, S, L>;\n enumeration: EnumerationCond<T, S, L>;\n plural: PluralCond<T, S, L>;\n condition: ConditionCond<T, S, L>;\n insertion: InsertionCond<T, S, L>;\n gender: GenderCond<T, S, L>;\n select: SelectCond<T, S, L>;\n nested: NestedCond<T, S, L>;\n file: FileCond<T, S, L>;\n}\n\n/**\n * Allow to avoid overwriting import from `intlayer` package when `IInterpreterPlugin<T>` interface is augmented in another package, such as `react-intlayer`.\n */\nexport type IInterpreterPluginState = {\n translation: true;\n enumeration: true;\n plural: true;\n condition: true;\n insertion: true;\n gender: true;\n select: true;\n nested: true;\n file: true;\n};\n\n/**\n * Utility type to check if a plugin can be applied to a node.\n */\ntype CheckApplyPlugin<\n T,\n K extends keyof IInterpreterPlugin<T, S, L>,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = K extends keyof S // Test if the key is a key of S.\n ? // Test if the key of S is true. Then the plugin can be applied.\n S[K] extends true\n ? // Test if the key of S exist\n IInterpreterPlugin<T, S, L>[K] extends never\n ? never\n : // Test if the plugin condition is true (if it's not, the plugin is skipped for this node)\n IInterpreterPlugin<T, S, L>[K]\n : never\n : never;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\ntype Traverse<T, S, L extends LocalesValues = DeclaredLocales> =\n T extends ReadonlyArray<infer U> // Turn any read-only array into a plain mutable array\n ? Array<DeepTransformContent<U, S, L>>\n : T extends object\n ? { [K in keyof T]: DeepTransformContent<T[K], S, L> }\n : T;\n\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\nexport type DeepTransformContent<\n T,\n S = IInterpreterPluginState,\n L extends LocalesValues = DeclaredLocales,\n> =\n IsAny<T> extends true\n ? T\n : CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S, L> extends never // Check if there is a plugin for T:\n ? // No plugin was found, so try to transform T recursively:\n Traverse<T, S, L>\n : // A plugin was found – use the plugin's transformation.\n CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S, L>;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmEA,MAAa,iBAA0B;CACrC,IAAI;CACJ,iBAAiB;CACjB,YAAY,SAAS;AACvB;;AAmCA,MAAa,qBACX,QACA,aAEA,QAAQ,IAAI,mCAAmC,UAC3C,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,UAAU;CAC3D,YAAY,MAA0B,OAAO,sBAAsB;EACjE,MAAM,WAAW,KAAK,UAAU,gBAAgB,CAAC;EACjD,MAAM,SAA8B,CAAC;EAErC,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,aAAa;IACjB,GAAG;IACH,UAAU,SAAS;IACnB,SAAS,CACP,GAAG,MAAM,SACT;KAAE,MAAM,UAAU;KAAa;IAAI,CACrC;GACF;GACA,OAAO,OAAO,kBACZ,SAAS,MACT,UACF;EACF;EAEA,OAAO,eAAe,QAAQ,QAAQ,QAAQ;CAChD;AACF;;AAmBN,MAAa,oBACX,QAAQ,IAAI,mCAAmC,UAC3C,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,UAAU;CAC3D,Y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1B,GAAG;EACH,UAAU,KAAK;CACjB,CAAC;AACL"}
1
+ {"version":3,"file":"plugins.mjs","names":["getNestingOptimized"],"sources":["../../../../src/interpreter/getContent/plugins.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type {\n ConditionContent,\n EnumerationContent,\n FileContent,\n Gender,\n GenderContent,\n InsertionContent,\n NestedContent,\n PluralContent,\n PluralContentState,\n SelectContent,\n TranslationContent,\n} from '../../transpiler';\nimport { getCondition } from '../getCondition';\nimport { getEnumeration } from '../getEnumeration';\nimport { getGender } from '../getGender';\nimport { getInsertion } from '../getInsertion';\nimport { type GetNestingResult, getNesting } from '../getNesting';\nimport { getNesting as getNestingOptimized } from '../getNesting.optimized';\nimport { getPlural } from '../getPlural';\nimport { getSelect } from '../getSelect';\nimport { getTranslation } from '../getTranslation';\nimport {\n isInterpolableWrapperNode,\n transformInterpolableNode,\n} from '../interpolableNode';\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\n/** ---------------------------------------------\n * PLUGIN DEFINITION\n * --------------------------------------------- */\n\n/**\n * A plugin/transformer that can optionally transform a node during a single DFS pass.\n * - `canHandle` decides if the node is transformable by this plugin.\n * - `transform` returns the transformed node (and does not recurse further).\n *\n * > `transformFn` is a function that can be used to deeply transform inside the plugin.\n */\nexport type Plugins = {\n id: string;\n canHandle: (node: any) => boolean;\n transform: (\n node: any,\n props: NodeProps,\n transformFn: (node: any, props: NodeProps) => any\n ) => any;\n};\n\n/** ---------------------------------------------\n * FALLBACK PLUGIN\n *\n * Used to fallback a tree-shaken plugin\n * --------------------------------------------- */\n\nexport const fallbackPlugin: Plugins = {\n id: 'fallback-plugin',\n canHandle: () => false,\n transform: (node) => node,\n};\n\n/**\n * Whether a resolved branch still expects insertion values.\n *\n * Some renderers return callable nodes (Svelte components, Angular proxies)\n * exposing their content on `.value`: those are final and must not be called\n * with the values. A pending insertion either has no `.value` or a function\n * one.\n */\nconst isAwaitingValues = (\n branch: unknown\n): branch is (values: Record<string, unknown>) => unknown => {\n if (typeof branch !== 'function') return false;\n\n const { value } = branch as { value?: unknown };\n\n return value === undefined || typeof value === 'function';\n};\n\n/** ---------------------------------------------\n * TRANSLATION PLUGIN\n * --------------------------------------------- */\n\nexport type UnionKeys<T> = T extends unknown ? keyof T : never;\nexport type ValueAtKey<T, K> = T extends unknown\n ? K extends keyof T\n ? T[K]\n : never\n : never;\n\nexport type TranslationCond<T, S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.TRANSLATION]: infer U;\n}\n ? U extends Record<PropertyKey, unknown>\n ? U[keyof U] extends Record<PropertyKey, unknown>\n ? {\n [K in UnionKeys<U[keyof U]>]: L extends keyof U\n ? K extends keyof U[L]\n ? U[L][K]\n : ValueAtKey<U[keyof U], K>\n : ValueAtKey<U[keyof U], K>;\n } extends infer Content\n ? DeepTransformContent<Content, S>\n : never\n : (L extends keyof U ? U[L] : U[keyof U]) extends infer Content\n ? DeepTransformContent<Content, S>\n : never\n : never\n : never;\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const translationPlugin = (\n locale: LocalesValues,\n fallback?: LocalesValues\n): Plugins =>\n process.env.INTLAYER_NODE_TYPE_TRANSLATION === 'false'\n ? fallbackPlugin\n : {\n id: 'translation-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.TRANSLATION,\n transform: (node: TranslationContent, props, deepTransformNode) => {\n // Resolve on the raw content first: only the displayed locale (and\n // the fallback keys it lacks) is ever transformed\n const content = getTranslation(\n node[NodeTypes.TRANSLATION] ?? {},\n locale,\n fallback\n );\n\n return deepTransformNode(content, {\n ...props,\n children: content,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.TRANSLATION, key: locale } as KeyPath,\n ],\n });\n },\n };\n\n/** ---------------------------------------------\n * ENUMERATION PLUGIN\n * --------------------------------------------- */\n\nexport type EnumerationCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.ENUMERATION]: object;\n}\n ? (\n quantity: number\n ) => DeepTransformContent<\n T[typeof NodeTypes.ENUMERATION][keyof T[typeof NodeTypes.ENUMERATION]],\n S\n >\n : never;\n\n/** Enumeration plugin. Replaces node with a function that takes quantity => string. */\nexport const enumerationPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_ENUMERATION === 'false'\n ? fallbackPlugin\n : {\n id: 'enumeration-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.ENUMERATION,\n transform: (node: EnumerationContent, props, deepTransformNode) => {\n const original = node[NodeTypes.ENUMERATION];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as unknown as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.ENUMERATION, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: number | { count: number }) => {\n const quantity = typeof arg === 'number' ? arg : arg.count;\n const subResult = getEnumeration(result, quantity);\n\n if (isAwaitingValues(subResult) && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * PLURAL PLUGIN\n * --------------------------------------------- */\n\n/**\n * A plural branch wrapped in an `insertion` node (auto-transformed\n * `{{count}}`) resolves to its inner content: the plural applies the values.\n */\ntype PluralBranch<Branch> = Branch extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer InsertionContent;\n fields: readonly string[];\n}\n ? InsertionContent\n : Branch;\n\nexport type PluralCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.PLURAL]: object;\n}\n ? (\n arg: number | { count: number; [key: string]: unknown }\n ) => DeepTransformContent<\n PluralBranch<\n T[typeof NodeTypes.PLURAL][keyof T[typeof NodeTypes.PLURAL]]\n >,\n S\n >\n : never;\n\ntype SubResultFunction = (values: Record<string, string | number>) => string;\n\n/**\n * Plural plugin. Replaces node with a function that takes a count (or\n * `{ count, ...values }`) => string, picking the matching CLDR plural form\n * for the active locale and interpolating `{{count}}` (and other values).\n */\nexport const pluralPlugin = (locale?: LocalesValues): Plugins =>\n process.env.INTLAYER_NODE_TYPE_PLURAL === 'false'\n ? fallbackPlugin\n : {\n id: 'plural-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.PLURAL,\n transform: (node: PluralContent, props, deepTransformNode) => {\n const original = node[NodeTypes.PLURAL];\n const result: Record<string, any> = {};\n // The plural interpolates its own branches. A string plugin from an\n // enclosing `insert()` would turn them into functions first.\n const branchPlugins = (props.plugins ?? []).filter(\n (plugin) => plugin.id !== 'insertion-string-plugin'\n );\n\n /** String plugin for plural. Replaces string node with a component that renders the insertion. */\n const pluralStringPlugin: Plugins = {\n id: 'plural-string-plugin',\n canHandle: (node) =>\n typeof node === 'string' || isInterpolableWrapperNode(node),\n transform: (node, subProps, deepTransformNode) => {\n // An `insertion` node below the plural (e.g. auto-transformed\n // `{{count}}` branches) already returns `(values) => …`. Leave its\n // strings untouched, or its template would become a function.\n const isInsideInsertion = subProps.keyPath\n .slice(props.keyPath.length)\n .some((keyPath) => keyPath.type === NodeTypes.INSERTION);\n\n if (isInsideInsertion) {\n return deepTransformNode(node, {\n ...subProps,\n plugins: subProps.plugins?.filter(\n (plugin) => plugin.id !== 'plural-string-plugin'\n ),\n });\n }\n\n // `html()`/`markdown()` nodes carry their `{{count}}` placeholders\n // inside a raw string. Interpolate into that string, then re-run\n // the transform so the html/markdown renderer applies afterwards.\n if (isInterpolableWrapperNode(node)) {\n return (values: { [k: string]: string | number }) =>\n transformInterpolableNode(\n node,\n values,\n subProps,\n branchPlugins,\n deepTransformNode\n );\n }\n\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...branchPlugins.filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (values: { [k: string]: string | number }) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: branchPlugins,\n children,\n });\n };\n },\n };\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.PLURAL, key } as KeyPath,\n ],\n plugins: [pluralStringPlugin, ...branchPlugins],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n const effectiveLocale = String(locale ?? props.locale ?? 'en');\n\n return (arg: number | { count: number; [key: string]: unknown }) => {\n const count = typeof arg === 'number' ? arg : arg.count;\n const values =\n typeof arg === 'number'\n ? { count: arg }\n : (arg as { count: number; [key: string]: unknown });\n\n const subResult: string | SubResultFunction = getPlural(\n result as PluralContent['plural'] as PluralContentState<string>,\n count,\n effectiveLocale\n );\n\n if (isAwaitingValues(subResult)) {\n return (subResult as SubResultFunction)(values);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * CONDITION PLUGIN\n * --------------------------------------------- */\n\nexport type ConditionCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.CONDITION]: object;\n}\n ? (\n value: boolean | { value: boolean }\n ) => DeepTransformContent<\n T[typeof NodeTypes.CONDITION][keyof T[typeof NodeTypes.CONDITION]],\n S\n >\n : never;\n\n/** Condition plugin. Replaces node with a function that takes boolean => string. */\nexport const conditionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_CONDITION === 'false'\n ? fallbackPlugin\n : {\n id: 'condition-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.CONDITION,\n transform: (node: ConditionContent, props, deepTransformNode) => {\n const original = node[NodeTypes.CONDITION];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.CONDITION, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: boolean | { value: boolean }) => {\n const value = typeof arg === 'boolean' ? arg : arg.value;\n const subResult = getCondition(result as any, value);\n\n if (isAwaitingValues(subResult) && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer I;\n fields: readonly string[];\n}\n ? (\n values: {\n [K in T['fields'][number]]: string | number;\n }\n ) => I extends string\n ? DeepTransformContent<string, S>\n : DeepTransformContent<I, S>\n : never;\n\n/** Insertion plugin. Replaces node with a function that takes quantity => string. */\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeTypes.INSERTION,\n },\n ];\n\n const children = node[NodeTypes.INSERTION];\n\n /** Insertion string plugin. Replaces string node with a component that render the insertion. */\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) =>\n typeof node === 'string' || isInterpolableWrapperNode(node),\n transform: (node, subProps, deepTransformNode) => {\n // `html()`/`markdown()` nodes carry their `{{ … }}` placeholders\n // inside a raw string. Interpolate into that string, then re-run\n // the transform so the html/markdown renderer applies afterwards.\n if (isInterpolableWrapperNode(node)) {\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) =>\n transformInterpolableNode(\n node,\n values,\n subProps,\n props.plugins,\n deepTransformNode\n );\n }\n\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...(props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: props.plugins,\n children,\n });\n };\n },\n };\n\n const result = deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n\n return resolveInsertedSelector(children, result);\n },\n };\n\n/** Container nodes resolved by a selector call: `enu(3)`, `cond(true)`, … */\nconst selectorNodeTypes: string[] = [\n NodeTypes.ENUMERATION,\n NodeTypes.CONDITION,\n NodeTypes.PLURAL,\n NodeTypes.GENDER,\n NodeTypes.SELECT,\n];\n\n/**\n * Binds the values of an `insert()` to the selector node it wraps, returning\n * `(selector) => content`. Any other child result is returned unchanged.\n *\n * `areBranchesInterpolated` is set by frameworks that interpolate the branch\n * strings as soon as the values are known: the selected branch is then final\n * content and is never called with the values.\n */\nexport const bindInsertedValues = (\n children: unknown,\n result: unknown,\n values: Record<string, unknown>,\n areBranchesInterpolated = false\n): unknown => {\n const nodeType = (children as { nodeType?: string })?.nodeType;\n if (\n typeof result !== 'function' ||\n !nodeType ||\n !selectorNodeTypes.includes(nodeType)\n ) {\n return result;\n }\n\n const isCountSelector =\n nodeType === NodeTypes.PLURAL || nodeType === NodeTypes.ENUMERATION;\n\n return (selector: unknown) => {\n // Object selectors (`{ count }`, `{ value }`) carry the values along.\n if (typeof selector === 'object' && selector !== null) {\n return result({ ...values, ...selector });\n }\n\n // The count both selects the branch and fills `{{count}}`: the selector\n // wins over a `count` passed with the values.\n if (isCountSelector) {\n return result({ ...values, count: selector });\n }\n\n const selected = result(selector);\n\n return !areBranchesInterpolated && isAwaitingValues(selected)\n ? selected(values)\n : selected;\n };\n};\n\n/**\n * Shapes the result of `insert()` wrapping a selector node as\n * `(values) => (selector) => content`, so the values reach the selected\n * branch. Any other child result is returned unchanged.\n */\nexport const resolveInsertedSelector = (\n children: unknown,\n result: unknown\n): unknown =>\n typeof result === 'function' &&\n selectorNodeTypes.includes(\n (children as { nodeType?: string })?.nodeType ?? ''\n )\n ? (values: Record<string, unknown>) =>\n bindInsertedValues(children, result, values)\n : result;\n\n/** ---------------------------------------------\n * GENDER PLUGIN\n * --------------------------------------------- */\n\nexport type GenderCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.GENDER]: object;\n}\n ? (\n value: Gender\n ) => DeepTransformContent<\n T[typeof NodeTypes.GENDER][keyof T[typeof NodeTypes.GENDER]],\n S\n >\n : never;\n\n/** Gender plugin. Replaces node with a function that takes gender => string. */\nexport const genderPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_GENDER === 'false'\n ? fallbackPlugin\n : {\n id: 'gender-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.GENDER,\n transform: (node: GenderContent, props, deepTransformNode) => {\n const original = node[NodeTypes.GENDER];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.GENDER, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (value: Gender) => getGender(result as any, value);\n },\n };\n\n/** ---------------------------------------------\n * SELECT PLUGIN\n * --------------------------------------------- */\n\n/**\n * Accepted selector for a select node.\n *\n * When the node declares a `fallback` case, any string is accepted (the\n * fallback covers the unmatched values) while the declared cases still\n * autocomplete. Without a `fallback`, only the declared cases are accepted.\n */\nexport type SelectSelector<States> = 'fallback' extends keyof States\n ? Exclude<keyof States & string, 'fallback'> | (string & {})\n : keyof States & string;\n\nexport type SelectCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.SELECT]: object;\n}\n ? (\n value:\n | SelectSelector<T[typeof NodeTypes.SELECT]>\n | { value: SelectSelector<T[typeof NodeTypes.SELECT]> }\n ) => DeepTransformContent<\n T[typeof NodeTypes.SELECT][keyof T[typeof NodeTypes.SELECT]],\n S\n >\n : never;\n\n/** Select plugin. Replaces node with a function that takes a string => content. */\nexport const selectPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_SELECT === 'false'\n ? fallbackPlugin\n : {\n id: 'select-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.SELECT,\n transform: (node: SelectContent, props, deepTransformNode) => {\n const original = node[NodeTypes.SELECT];\n const result: Record<string, any> = {};\n\n for (const key in original) {\n const child = original[key as keyof typeof original];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeTypes.SELECT, key } as KeyPath,\n ],\n };\n result[key] = deepTransformNode(child, childProps);\n }\n\n return (arg: string | { value: string }) => {\n const value = typeof arg === 'string' ? arg : arg?.value;\n const subResult = getSelect(result, value);\n\n if (isAwaitingValues(subResult) && typeof arg === 'object') {\n return subResult(arg);\n }\n\n return subResult;\n };\n },\n };\n\n/** ---------------------------------------------\n * NESTED PLUGIN\n * --------------------------------------------- */\n\nexport type NestedCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.NESTED]: infer U;\n}\n ? U extends {\n dictionaryKey: infer K extends DictionaryKeys;\n path?: infer P;\n }\n ? GetNestingResult<K, P, S>\n : never\n : never;\n\n/**\n * Resolver used to turn a nested node into content.\n *\n * Optimized builds set `INTLAYER_OPTIMIZED_NESTING` so bundlers fold this to\n * the local resolver and dead-code-eliminate the registry-based one — together\n * with its `getIntlayer` import, and therefore the whole\n * `@intlayer/dictionaries-entry` module. That is what allows the dictionaries\n * entry to be emptied while `nest()` keeps working.\n */\nconst resolveNesting =\n process.env.INTLAYER_OPTIMIZED_NESTING === 'true'\n ? getNestingOptimized\n : getNesting;\n\n/** Nested plugin. Replaces node with the result of `getNesting`. */\nexport const nestedPlugin = (locale?: LocalesValues): Plugins =>\n process.env.INTLAYER_NODE_TYPE_NESTED === 'false'\n ? fallbackPlugin\n : {\n id: 'nested-plugin',\n canHandle: (node) =>\n typeof node === 'object' &&\n (node?.nodeType === NodeTypes.NESTED || node?.nodeType === 'n'),\n transform: (node: NestedContent, props) =>\n resolveNesting(\n node[NodeTypes.NESTED].dictionaryKey,\n node[NodeTypes.NESTED].path,\n {\n ...props,\n locale: (locale ?? props.locale) as Locale,\n }\n ),\n };\n\n/** ---------------------------------------------\n * FILE PLUGIN\n * --------------------------------------------- */\n\nexport type FileCond<T, S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.FILE]: string;\n content?: string;\n}\n ? DeepTransformContent<string, S>\n : never;\n\n/** File plugin. Replaces node with the result of `getNesting`. */\nexport const filePlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_FILE === 'false'\n ? fallbackPlugin\n : {\n id: 'file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.FILE,\n transform: (node: FileContent, props, deepTransform) =>\n deepTransform(node.content, {\n ...props,\n children: node.content,\n }),\n };\n\n/**\n * PLUGIN RESULT\n */\n\n/**\n * Interface that defines the properties of a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface NodeProps {\n dictionaryKey: string;\n keyPath: KeyPath[];\n plugins?: Plugins[];\n locale?: Locale;\n dictionaryPath?: string;\n children?: any;\n /**\n * Dictionaries referenced through `nest()`, attached to the consuming\n * dictionary by the build optimization and threaded down by\n * `deepTransformNode`.\n *\n * Present only in optimized builds, where the global dictionary registry is\n * stripped and `getNesting` resolves from this map instead. See\n * `getNesting.optimized.ts`.\n */\n nestedDictionaries?: Record<string, unknown>;\n /**\n * Forces eager traversal of plain objects in `deepTransformNode`. By default\n * traversal is lazy (property getters), so callers that discard the returned\n * value never trigger plugins on nested nodes. Set this when running plugins\n * for their side effects only (e.g. missing-locale detection), or when most\n * of the content is read anyway: defining a getter per key, then redefining\n * it on first read, costs more than transforming the key outright.\n */\n eager?: boolean;\n}\n\n/**\n * Interface that defines the plugins that can be used to transform a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface IInterpreterPlugin<T, S, L extends LocalesValues> {\n translation: TranslationCond<T, S, L>;\n enumeration: EnumerationCond<T, S, L>;\n plural: PluralCond<T, S, L>;\n condition: ConditionCond<T, S, L>;\n insertion: InsertionCond<T, S, L>;\n gender: GenderCond<T, S, L>;\n select: SelectCond<T, S, L>;\n nested: NestedCond<T, S, L>;\n file: FileCond<T, S, L>;\n}\n\n/**\n * Allow to avoid overwriting import from `intlayer` package when `IInterpreterPlugin<T>` interface is augmented in another package, such as `react-intlayer`.\n */\nexport type IInterpreterPluginState = {\n translation: true;\n enumeration: true;\n plural: true;\n condition: true;\n insertion: true;\n gender: true;\n select: true;\n nested: true;\n file: true;\n};\n\n/**\n * Utility type to check if a plugin can be applied to a node.\n */\ntype CheckApplyPlugin<\n T,\n K extends keyof IInterpreterPlugin<T, S, L>,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = K extends keyof S // Test if the key is a key of S.\n ? // Test if the key of S is true. Then the plugin can be applied.\n S[K] extends true\n ? // Test if the key of S exist\n IInterpreterPlugin<T, S, L>[K] extends never\n ? never\n : // Test if the plugin condition is true (if it's not, the plugin is skipped for this node)\n IInterpreterPlugin<T, S, L>[K]\n : never\n : never;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\ntype Traverse<T, S, L extends LocalesValues = DeclaredLocales> =\n T extends ReadonlyArray<infer U> // Turn any read-only array into a plain mutable array\n ? Array<DeepTransformContent<U, S, L>>\n : T extends object\n ? { [K in keyof T]: DeepTransformContent<T[K], S, L> }\n : T;\n\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\nexport type DeepTransformContent<\n T,\n S = IInterpreterPluginState,\n L extends LocalesValues = DeclaredLocales,\n> =\n IsAny<T> extends true\n ? T\n : CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S, L> extends never // Check if there is a plugin for T:\n ? // No plugin was found, so try to transform T recursively:\n Traverse<T, S, L>\n : // A plugin was found – use the plugin's transformation.\n CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S, L>;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmEA,MAAa,iBAA0B;CACrC,IAAI;CACJ,iBAAiB;CACjB,YAAY,SAAS;AACvB;;;;;;;;;AAUA,MAAM,oBACJ,WAC2D;CAC3D,IAAI,OAAO,WAAW,YAAY,OAAO;CAEzC,MAAM,EAAE,UAAU;CAElB,OAAO,UAAU,UAAa,OAAO,UAAU;AACjD;;AAmCA,MAAa,qBACX,QACA,aAEA,QAAQ,IAAI,mCAAmC,UAC3C,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,UAAU;CAC3D,YAAY,MAA0B,OAAO,sBAAsB;EAGjE,MAAM,UAAU,eACd,KAAK,UAAU,gBAAgB,CAAC,GAChC,QACA,QACF;EAEA,OAAO,kBAAkB,SAAS;GAChC,GAAG;GACH,UAAU;GACV,SAAS,CACP,GAAG,MAAM,SACT;IAAE,MAAM,UAAU;IAAa,KAAK;GAAO,CAC7C;EACF,CAAC;CACH;AACF;;AAmBN,MAAa,oBACX,QAAQ,IAAI,mCAAmC,UAC3C,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,UAAU;CAC3D,YAAY,MAA0B,OAAO,sBAAsB;EACjE,MAAM,WAAW,KAAK,UAAU;EAChC,MAAM,SAA8B,CAAC;EAErC,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,QAAQ,SAAS;GASvB,OAAO,OAAO,kBAAkB,OAAO;IAPrC,GAAG;IACH,UAAU;IACV,SAAS,CACP,GAAG,MAAM,SACT;KAAE,MAAM,UAAU;KAAa;IAAI,CACrC;GAE8C,CAAC;EACnD;EA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AAK;GACnD,MAAM,YAAY,UAAU,QAAQ,KAAK;GAEzC,IAAI,iBAAiB,SAAS,KAAK,OAAO,QAAQ,UAChD,OAAO,UAAU,GAAG;GAGtB,OAAO;EACT;CACF;AACF;;;;;;;;;;AA2BN,MAAM,iBACJ,QAAQ,IAAI,+BAA+B,SACvCA,eACA;;AAGN,MAAa,gBAAgB,WAC3B,QAAQ,IAAI,8BAA8B,UACtC,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,aACf,MAAM,aAAa,UAAU,UAAU,MAAM,aAAa;CAC7D,YAAY,MAAqB,UAC/B,eACE,KAAK,UAAU,OAAO,CAAC,eACvB,KAAK,UAAU,OAAO,CAAC,MACvB;EACE,GAAG;EACH,QAAS,UAAU,MAAM;CAC3B,CACF;AACJ;;AAeN,MAAa,aACX,QAAQ,IAAI,4BAA4B,UACpC,iBACA;CACE,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,UAAU;CAC3D,YAAY,MAAmB,OAAO,kBACpC,cAAc,KAAK,SAAS;EAC1B,GAAG;EACH,UAAU,KAAK;CACjB,CAAC;AACL"}
@@ -5,6 +5,12 @@ import { internationalization } from "@intlayer/config/built";
5
5
 
6
6
  //#region src/interpreter/getDictionary.ts
7
7
  /**
8
+ * Dictionaries whose transform is running. Content is transformed eagerly, so a
9
+ * dictionary reached again through a `nest()` cycle is transformed lazily
10
+ * instead: its nodes then resolve on read, and the cycle unwinds.
11
+ */
12
+ const transformsInProgress = /* @__PURE__ */ new WeakSet();
13
+ /**
8
14
  * Transforms a dictionary in a single pass, applying each plugin as needed.
9
15
  *
10
16
  * @param dictionary The dictionary (or qualified dictionary group) to transform.
@@ -14,21 +20,30 @@ import { internationalization } from "@intlayer/config/built";
14
20
  * If omitted, we’ll use a default set of plugins.
15
21
  */
16
22
  const getDictionary = (dictionary, localeOrSelector, plugins) => {
17
- const { locale, selector } = parseDictionarySelector(localeOrSelector);
18
- const cacheKey = getDictionaryTransformCacheKey(locale ?? internationalization.defaultLocale, getDictionarySelectorCacheKey(selector), plugins);
23
+ const { locale, selector } = process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? parseDictionarySelector(localeOrSelector) : {
24
+ locale: localeOrSelector,
25
+ selector: void 0
26
+ };
27
+ const cacheKey = getDictionaryTransformCacheKey(locale ?? internationalization.defaultLocale, process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? getDictionarySelectorCacheKey(selector) : "", plugins);
19
28
  const cached = readTransformCache(dictionary, cacheKey);
20
29
  if (cached.hit) return cached.content;
21
30
  const appliedPlugins = plugins ?? getBasePlugins(locale);
22
- const resolved = resolveQualifiedDictionary(dictionary, selector);
31
+ const resolved = process.env.INTLAYER_DICTIONARY_SELECTOR !== "false" ? resolveQualifiedDictionary(dictionary, selector) : dictionary;
23
32
  const transformDictionary = (resolvedDictionary) => {
24
33
  const props = {
25
34
  dictionaryKey: resolvedDictionary.key,
26
35
  dictionaryPath: resolvedDictionary.filePath,
27
36
  keyPath: [],
28
37
  plugins: appliedPlugins,
29
- nestedDictionaries: resolvedDictionary.nestedDictionaries
38
+ nestedDictionaries: resolvedDictionary.nestedDictionaries,
39
+ eager: !transformsInProgress.has(resolvedDictionary)
30
40
  };
31
- return getContent(resolvedDictionary.content, props, appliedPlugins);
41
+ transformsInProgress.add(resolvedDictionary);
42
+ try {
43
+ return getContent(resolvedDictionary.content, props, appliedPlugins);
44
+ } finally {
45
+ if (props.eager) transformsInProgress.delete(resolvedDictionary);
46
+ }
32
47
  };
33
48
  if (resolved === null) return writeTransformCache(dictionary, cacheKey, null);
34
49
  if (Array.isArray(resolved)) return writeTransformCache(dictionary, cacheKey, resolved.map(transformDictionary));
@@ -1 +1 @@
1
- {"version":3,"file":"getDictionary.mjs","names":[],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n Dictionary,\n DictionarySelector,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n getDictionarySelectorCacheKey,\n parseDictionarySelector,\n resolveQualifiedDictionary,\n} from '../dictionaryManipulator/qualifiedDictionary';\nimport {\n getDictionaryTransformCacheKey,\n readTransformCache,\n writeTransformCache,\n} from './dictionaryTransformCache';\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 (or qualified dictionary group) to transform.\n * @param localeOrSelector The locale, or a selector object (`{ item }`,\n * `{ variant }`, optionally with `locale`).\n * @param plugins 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 | QualifiedDictionaryGroup,\n const A extends LocalesValues | DictionarySelector = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A,\n plugins?: Plugins[]\n): DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n IInterpreterPluginState,\n ExtractSelectorLocale<A>\n> => {\n const { locale, selector } = parseDictionarySelector(localeOrSelector);\n\n // The base plugins are rebuilt on every call, so they cannot identify\n // themselves — but they are fully determined by the locale, which the key\n // already carries. Only an explicitly passed array needs its own identity.\n const cacheKey = getDictionaryTransformCacheKey(\n locale ?? internationalization.defaultLocale,\n getDictionarySelectorCacheKey(selector),\n plugins\n );\n\n const cached = readTransformCache<any>(dictionary, cacheKey);\n if (cached.hit) return cached.content;\n\n const appliedPlugins = plugins ?? getBasePlugins(locale);\n\n const resolved = resolveQualifiedDictionary(dictionary, selector);\n\n const transformDictionary = (resolvedDictionary: Dictionary) => {\n const props: NodeProps = {\n dictionaryKey: resolvedDictionary.key,\n dictionaryPath: resolvedDictionary.filePath,\n keyPath: [],\n plugins: appliedPlugins,\n // Attached by the build optimization so `nest()` resolves without the\n // global registry. Undefined in unoptimized builds, where the\n // registry-based resolver is used instead.\n nestedDictionaries: resolvedDictionary.nestedDictionaries,\n };\n\n return getContent(resolvedDictionary.content, props, appliedPlugins);\n };\n\n if (resolved === null) return writeTransformCache(dictionary, cacheKey, null);\n\n if (Array.isArray(resolved)) {\n return writeTransformCache(\n dictionary,\n cacheKey,\n resolved.map(transformDictionary)\n ) as any;\n }\n\n return writeTransformCache(\n dictionary,\n cacheKey,\n transformDictionary(resolved)\n ) as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAa,iBAIX,YACA,kBACA,YAKG;CACH,MAAM,EAAE,QAAQ,aAAa,wBAAwB,gBAAgB;CAKrE,MAAM,WAAW,+BACf,UAAU,qBAAqB,eAC/B,8BAA8B,QAAQ,GACtC,OACF;CAEA,MAAM,SAAS,mBAAwB,YAAY,QAAQ;CAC3D,IAAI,OAAO,KAAK,OAAO,OAAO;CAE9B,MAAM,iBAAiB,WAAW,eAAe,MAAM;CAEvD,MAAM,WAAW,2BAA2B,YAAY,QAAQ;CAEhE,MAAM,uBAAuB,uBAAmC;EAC9D,MAAM,QAAmB;GACvB,eAAe,mBAAmB;GAClC,gBAAgB,mBAAmB;GACnC,SAAS,CAAC;GACV,SAAS;GAIT,oBAAoB,mBAAmB;EACzC;EAEA,OAAO,WAAW,mBAAmB,SAAS,OAAO,cAAc;CACrE;CAEA,IAAI,aAAa,MAAM,OAAO,oBAAoB,YAAY,UAAU,IAAI;CAE5E,IAAI,MAAM,QAAQ,QAAQ,GACxB,OAAO,oBACL,YACA,UACA,SAAS,IAAI,mBAAmB,CAClC;CAGF,OAAO,oBACL,YACA,UACA,oBAAoB,QAAQ,CAC9B;AACF"}
1
+ {"version":3,"file":"getDictionary.mjs","names":[],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n Dictionary,\n DictionarySelector,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n getDictionarySelectorCacheKey,\n parseDictionarySelector,\n resolveQualifiedDictionary,\n} from '../dictionaryManipulator/qualifiedDictionary';\nimport {\n getDictionaryTransformCacheKey,\n readTransformCache,\n writeTransformCache,\n} from './dictionaryTransformCache';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n Plugins,\n} from './getContent';\nimport { getBasePlugins, getContent } from './getContent/getContent';\n\n/**\n * Dictionaries whose transform is running. Content is transformed eagerly, so a\n * dictionary reached again through a `nest()` cycle is transformed lazily\n * instead: its nodes then resolve on read, and the cycle unwinds.\n */\nconst transformsInProgress = new WeakSet<object>();\n\n/**\n * Transforms a dictionary in a single pass, applying each plugin as needed.\n *\n * @param dictionary The dictionary (or qualified dictionary group) to transform.\n * @param localeOrSelector The locale, or a selector object (`{ item }`,\n * `{ variant }`, optionally with `locale`).\n * @param plugins 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 | QualifiedDictionaryGroup,\n const A extends LocalesValues | DictionarySelector = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A,\n plugins?: Plugins[]\n): DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n IInterpreterPluginState,\n ExtractSelectorLocale<A>\n> => {\n // The selector checks stay inline so bundlers can drop the whole\n // qualified-dictionary module when no dictionary declares a qualifier.\n const { locale, selector } =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false'\n ? parseDictionarySelector(localeOrSelector)\n : {\n locale: localeOrSelector as LocalesValues | undefined,\n selector: undefined,\n };\n\n // The base plugins are rebuilt on every call, so they cannot identify\n // themselves — but they are fully determined by the locale, which the key\n // already carries. Only an explicitly passed array needs its own identity.\n const cacheKey = getDictionaryTransformCacheKey(\n locale ?? internationalization.defaultLocale,\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false'\n ? getDictionarySelectorCacheKey(selector)\n : '',\n plugins\n );\n\n const cached = readTransformCache<any>(dictionary, cacheKey);\n if (cached.hit) return cached.content;\n\n const appliedPlugins = plugins ?? getBasePlugins(locale);\n\n const resolved =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false'\n ? resolveQualifiedDictionary(dictionary, selector)\n : (dictionary as Dictionary);\n\n const transformDictionary = (resolvedDictionary: Dictionary) => {\n const props: NodeProps = {\n dictionaryKey: resolvedDictionary.key,\n dictionaryPath: resolvedDictionary.filePath,\n keyPath: [],\n plugins: appliedPlugins,\n // Attached by the build optimization so `nest()` resolves without the\n // global registry. Undefined in unoptimized builds, where the\n // registry-based resolver is used instead.\n nestedDictionaries: resolvedDictionary.nestedDictionaries,\n eager: !transformsInProgress.has(resolvedDictionary),\n };\n\n transformsInProgress.add(resolvedDictionary);\n\n try {\n return getContent(resolvedDictionary.content, props, appliedPlugins);\n } finally {\n if (props.eager) transformsInProgress.delete(resolvedDictionary);\n }\n };\n\n if (resolved === null)\n return writeTransformCache(dictionary, cacheKey, null)!;\n\n if (Array.isArray(resolved)) {\n return writeTransformCache(\n dictionary,\n cacheKey,\n resolved.map(transformDictionary)\n ) as any;\n }\n\n return writeTransformCache(\n dictionary,\n cacheKey,\n transformDictionary(resolved)\n ) as any;\n};\n"],"mappings":";;;;;;;;;;;AAmCA,MAAM,uCAAuB,IAAI,QAAgB;;;;;;;;;;AAWjD,MAAa,iBAIX,YACA,kBACA,YAKG;CAGH,MAAM,EAAE,QAAQ,aACd,QAAQ,IAAI,iCAAiC,UACzC,wBAAwB,gBAAgB,IACxC;EACE,QAAQ;EACR,UAAU;CACZ;CAKN,MAAM,WAAW,+BACf,UAAU,qBAAqB,eAC/B,QAAQ,IAAI,iCAAiC,UACzC,8BAA8B,QAAQ,IACtC,IACJ,OACF;CAEA,MAAM,SAAS,mBAAwB,YAAY,QAAQ;CAC3D,IAAI,OAAO,KAAK,OAAO,OAAO;CAE9B,MAAM,iBAAiB,WAAW,eAAe,MAAM;CAEvD,MAAM,WACJ,QAAQ,IAAI,iCAAiC,UACzC,2BAA2B,YAAY,QAAQ,IAC9C;CAEP,MAAM,uBAAuB,uBAAmC;EAC9D,MAAM,QAAmB;GACvB,eAAe,mBAAmB;GAClC,gBAAgB,mBAAmB;GACnC,SAAS,CAAC;GACV,SAAS;GAIT,oBAAoB,mBAAmB;GACvC,OAAO,CAAC,qBAAqB,IAAI,kBAAkB;EACrD;EAEA,qBAAqB,IAAI,kBAAkB;EAE3C,IAAI;GACF,OAAO,WAAW,mBAAmB,SAAS,OAAO,cAAc;EACrE,UAAU;GACR,IAAI,MAAM,OAAO,qBAAqB,OAAO,kBAAkB;EACjE;CACF;CAEA,IAAI,aAAa,MACf,OAAO,oBAAoB,YAAY,UAAU,IAAI;CAEvD,IAAI,MAAM,QAAQ,QAAQ,GACxB,OAAO,oBACL,YACA,UACA,SAAS,IAAI,mBAAmB,CAClC;CAGF,OAAO,oBACL,YACA,UACA,oBAAoB,QAAQ,CAC9B;AACF"}
@@ -13,20 +13,26 @@ const isPlainObject = (value) => {
13
13
  /**
14
14
  * Recursively merges two objects, skipping undefined source values.
15
15
  * First argument takes precedence. Arrays replace rather than merge.
16
+ *
17
+ * Copy-on-write: an object the source adds nothing to is returned as-is, so a
18
+ * complete translation costs a read-only walk instead of a full copy.
16
19
  */
17
20
  const deepMerge = (target, source) => {
18
21
  if (target === void 0) return source;
19
22
  if (source === void 0) return target;
20
23
  if (Array.isArray(target)) return target;
21
- if (isPlainObject(target) && isPlainObject(source)) {
22
- const result = { ...target };
23
- for (const key of Object.keys(source)) {
24
- if (key === "__proto__" || key === "constructor" || source[key] === void 0) continue;
25
- result[key] = target[key] !== void 0 ? deepMerge(target[key], source[key]) : source[key];
26
- }
27
- return result;
24
+ if (!isPlainObject(target) || !isPlainObject(source)) return target;
25
+ let result = target;
26
+ for (const key of Object.keys(source)) {
27
+ const sourceValue = source[key];
28
+ if (key === "__proto__" || key === "constructor" || sourceValue === void 0) continue;
29
+ const targetValue = target[key];
30
+ const merged = targetValue === void 0 ? sourceValue : typeof targetValue === "object" ? deepMerge(targetValue, sourceValue) : targetValue;
31
+ if (merged === targetValue) continue;
32
+ if (result === target) result = { ...target };
33
+ result[key] = merged;
28
34
  }
29
- return target;
35
+ return result;
30
36
  };
31
37
  /**
32
38
  * Picks the appropriate content from a locale map based on the provided locale.
@@ -52,28 +58,26 @@ const deepMerge = (target, source) => {
52
58
  * ```
53
59
  */
54
60
  const getTranslation = (languageContent, locale, fallback) => {
55
- const get = (loc) => languageContent[loc];
56
- const seen = /* @__PURE__ */ new Set();
57
- const locales = [];
58
- const addLocale = (loc) => {
59
- if (loc && !seen.has(loc)) {
60
- seen.add(loc);
61
- locales.push(loc);
62
- }
63
- };
64
- addLocale(locale);
65
- if (locale.includes("-")) addLocale(locale.split("-")[0]);
66
- addLocale(fallback);
67
- if (fallback?.includes("-")) addLocale(fallback.split("-")[0]);
61
+ const get = (localeEl) => languageContent[localeEl];
62
+ const exactMatch = get(locale);
63
+ if (typeof exactMatch === "string") return exactMatch;
64
+ const candidates = [
65
+ locale,
66
+ locale.split("-")[0],
67
+ fallback,
68
+ fallback?.split("-")[0]
69
+ ];
68
70
  const results = [];
69
- for (const loc of locales) {
70
- const val = get(loc);
71
- if (val === void 0) continue;
72
- if (typeof val === "string") {
73
- if (results.length === 0) return val;
71
+ for (let index = 0; index < candidates.length; index++) {
72
+ const candidate = candidates[index];
73
+ if (!candidate || candidates.indexOf(candidate) < index) continue;
74
+ const value = get(candidate);
75
+ if (value === void 0) continue;
76
+ if (typeof value === "string") {
77
+ if (results.length === 0) return value;
74
78
  continue;
75
79
  }
76
- results.push(val);
80
+ results.push(value);
77
81
  }
78
82
  if (results.length === 0) return void 0;
79
83
  if (results.length === 1) return results[0];
@@ -1 +1 @@
1
- {"version":3,"file":"getTranslation.mjs","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,CAAC,CAAC,EAAE;CAExD,UAAU,QAAQ;CAClB,IAAI,UAAU,SAAS,GAAG,GAAG,UAAU,SAAS,MAAM,GAAG,CAAC,CAAC,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.mjs","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 *\n * Copy-on-write: an object the source adds nothing to is returned as-is, so a\n * complete translation costs a read-only walk instead of a full copy.\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)) return target;\n\n let result = target;\n\n for (const key of Object.keys(source)) {\n const sourceValue = source[key];\n\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n sourceValue === undefined\n )\n continue;\n\n const targetValue = target[key];\n\n // Only objects need a recursive merge: a primitive the target holds wins\n const merged =\n targetValue === undefined\n ? sourceValue\n : typeof targetValue === 'object'\n ? deepMerge(targetValue, sourceValue)\n : targetValue;\n\n if (merged === targetValue) continue;\n\n if (result === target) result = { ...target };\n result[key] = merged;\n }\n\n return result;\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 = (localeEl: string): Content | undefined =>\n languageContent[localeEl as keyof typeof languageContent];\n\n // Fast path for the common case: a string for the exact locale always wins,\n // so the candidate chain below would return it anyway.\n const exactMatch = get(locale);\n if (typeof exactMatch === 'string') return exactMatch;\n\n // Priority-ordered locale candidates, most specific first\n const candidates = [\n locale,\n locale.split('-')[0],\n fallback,\n fallback?.split('-')[0],\n ];\n\n // Strings exit early (unless a higher-priority object was found), objects\n // are accumulated for deep merging\n const results: Content[] = [];\n\n for (let index = 0; index < candidates.length; index++) {\n const candidate = candidates[index];\n\n // Skip empty and repeated candidates\n if (!candidate || candidates.indexOf(candidate) < index) continue;\n\n const value = get(candidate);\n\n if (value === undefined) continue;\n if (typeof value === 'string') {\n if (results.length === 0) return value;\n continue; // an object at higher priority takes precedence\n }\n\n results.push(value);\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;;;;;;;;AASA,MAAM,aAAa,QAAa,WAAqB;CACnD,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,CAAC,cAAc,MAAM,KAAK,CA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3,"file":"getPathWithoutLocale.mjs","names":[],"sources":["../../../src/localization/getPathWithoutLocale.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\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all' &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-no-default';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params';\n\nimport type {\n DeclaredLocales,\n LocalesValues,\n PathWithoutLocale,\n} from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\n\n/**\n * Removes the locale segment from the given URL or pathname if present.\n * Also removes locale from search parameters if present.\n *\n * This function get the locales from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * getPathWithoutLocale('/en/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/fr/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('dashboard') // Returns 'dashboard'\n * getPathWithoutLocale('/dashboard?locale=fr') // Returns '/dashboard'\n * getPathWithoutLocale('https://example.com/en/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/fr/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard?locale=fr') // Returns 'https://example.com/dashboard'\n * ```\n *\n * @param inputUrl - The complete URL string or pathname to process.\n * @param locales - Optional array of supported locales. Defaults to `localesDefault`.\n * @returns The URL string or pathname without the locale segment or locale search parameter.\n */\n/**\n * The return type is narrowed to a template-literal type when both `inputUrl`\n * and `locales` are string literals known at compile time. Absolute URLs fall\n * back to `string`.\n */\nexport const getPathWithoutLocale = <\n const T extends string,\n const L extends LocalesValues = DeclaredLocales,\n>(\n inputUrl: T,\n locales: L[] = internationalization?.locales as L[]\n): PathWithoutLocale<T, L> => {\n // Determine if the original URL is absolute (includes protocol)\n const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);\n\n let fixedInputUrl = inputUrl;\n\n if (inputUrl?.endsWith('/')) {\n fixedInputUrl = inputUrl.slice(0, -1);\n }\n\n // Initialize a URL object if the URL is absolute\n // For relative URLs, use a dummy base to leverage the URL API\n const url = isAbsoluteUrl\n ? new URL(fixedInputUrl)\n : new URL(fixedInputUrl, 'http://e.com');\n\n const pathname = url.pathname;\n\n // Ensure the pathname starts with '/'\n if (!pathname.startsWith('/')) {\n // If not, return the URL as is\n url.pathname = `/${pathname}`;\n }\n\n // Only strip locale path prefix in prefix-based routing modes\n if (!TREE_SHAKE_PREFIX_MODES) {\n // Split the pathname to extract the first segment\n const pathSegments = pathname.split('/');\n const firstSegment = pathSegments[1]; // The segment after the first '/'\n\n // Check if the first segment is a supported locale\n if (locales?.includes(firstSegment as L)) {\n // Remove the locale segment from the pathname\n pathSegments.splice(1, 1); // Remove the first segment\n\n // Reconstruct the pathname\n const newPathname = pathSegments.join('/') ?? '/';\n url.pathname = newPathname;\n }\n }\n\n // Only strip locale from search parameters in search-params routing mode\n if (!TREE_SHAKE_SEARCH_PARAMS) {\n const searchParams = new URLSearchParams(url.search);\n if (searchParams.has('locale')) {\n searchParams.delete('locale');\n url.search = searchParams.toString();\n }\n }\n\n if (isAbsoluteUrl) {\n return url.toString() as PathWithoutLocale<T, L>;\n }\n\n return url.toString().replace('http://e.com', '') as PathWithoutLocale<T, L>;\n};\n"],"mappings":";;;;;;;;AAUA,MAAM,0BACJ,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,gBACtC,QAAQ,IAAI,0BAA0B;;;;AAKxC,MAAM,2BACJ,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxC,MAAa,wBAIX,UACA,UAAe,sBAAsB,YACT;CAE5B,MAAM,gBAAgB,mBAAmB,QAAQ;CAEjD,IAAI,gBAAgB;CAEpB,IAAI,UAAU,SAAS,GAAG,GACxB,gBAAgB,SAAS,MAAM,GAAG,EAAE;CAKtC,MAAM,MAAM,gBACR,IAAI,IAAI,aAAa,IACrB,IAAI,IAAI,eAAe,cAAc;CAEzC,MAAM,WAAW,IAAI;CAGrB,IAAI,CAAC,SAAS,WAAW,GAAG,GAE1B,IAAI,WAAW,IAAI;CAIrB,IAAI,CAAC,yBAAyB;EAE5B,MAAM,eAAe,SAAS,MAAM,GAAG;EACvC,MAAM,eAAe,aAAa;EAGlC,IAAI,SAAS,SAAS,YAAiB,GAAG;GAExC,aAAa,OAAO,GAAG,CAAC;GAIxB,IAAI,WADgB,aAAa,KAAK,GAAG,KAAK;EAEhD;CACF;CAGA,IAAI,CAAC,0BAA0B;EAC7B,MAAM,eAAe,IAAI,gBAAgB,IAAI,MAAM;EACnD,IAAI,aAAa,IAAI,QAAQ,GAAG;GAC9B,aAAa,OAAO,QAAQ;GAC5B,IAAI,SAAS,aAAa,SAAS;EACrC;CACF;CAEA,IAAI,eACF,OAAO,IAAI,SAAS;CAGtB,OAAO,IAAI,SAAS,CAAC,CAAC,QAAQ,gBAAgB,EAAE;AAClD"}
1
+ {"version":3,"file":"getPathWithoutLocale.mjs","names":[],"sources":["../../../src/localization/getPathWithoutLocale.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\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all' &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-no-default';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params';\n\nimport type {\n DeclaredLocales,\n LocalesValues,\n PathWithoutLocale,\n} from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\n\n/**\n * Removes the locale segment from the given URL or pathname if present.\n * Also removes locale from search parameters if present.\n *\n * This function get the locales from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * getPathWithoutLocale('/en/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/fr/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('dashboard') // Returns 'dashboard'\n * getPathWithoutLocale('/dashboard?locale=fr') // Returns '/dashboard'\n * getPathWithoutLocale('https://example.com/en/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/fr/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard?locale=fr') // Returns 'https://example.com/dashboard'\n * ```\n *\n * @param inputUrl - The complete URL string or pathname to process.\n * @param locales - Optional array of supported locales. Defaults to `localesDefault`.\n * @returns The URL string or pathname without the locale segment or locale search parameter.\n */\n/**\n * The return type is narrowed to a template-literal type when both `inputUrl`\n * and `locales` are string literals known at compile time. Absolute URLs fall\n * back to `string`.\n */\nexport const getPathWithoutLocale = <\n const T extends string,\n const L extends LocalesValues = DeclaredLocales,\n>(\n inputUrl: T,\n locales: L[] = internationalization?.locales as L[]\n): PathWithoutLocale<T, L> => {\n // Determine if the original URL is absolute (includes protocol)\n const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);\n\n let fixedInputUrl: string = inputUrl;\n\n if (inputUrl?.endsWith('/')) {\n fixedInputUrl = inputUrl.slice(0, -1);\n }\n\n // Initialize a URL object if the URL is absolute\n // For relative URLs, use a dummy base to leverage the URL API\n const url = isAbsoluteUrl\n ? new URL(fixedInputUrl)\n : new URL(fixedInputUrl, 'http://e.com');\n\n const pathname = url.pathname;\n\n // Ensure the pathname starts with '/'\n if (!pathname.startsWith('/')) {\n // If not, return the URL as is\n url.pathname = `/${pathname}`;\n }\n\n // Only strip locale path prefix in prefix-based routing modes\n if (!TREE_SHAKE_PREFIX_MODES) {\n // Split the pathname to extract the first segment\n const pathSegments = pathname.split('/');\n const firstSegment = pathSegments[1]; // The segment after the first '/'\n\n // Check if the first segment is a supported locale\n if (locales?.includes(firstSegment as L)) {\n // Remove the locale segment from the pathname\n pathSegments.splice(1, 1); // Remove the first segment\n\n // Reconstruct the pathname\n const newPathname = pathSegments.join('/') ?? '/';\n url.pathname = newPathname;\n }\n }\n\n // Only strip locale from search parameters in search-params routing mode\n if (!TREE_SHAKE_SEARCH_PARAMS) {\n const searchParams = new URLSearchParams(url.search);\n if (searchParams.has('locale')) {\n searchParams.delete('locale');\n url.search = searchParams.toString();\n }\n }\n\n if (isAbsoluteUrl) {\n return url.toString() as PathWithoutLocale<T, L>;\n }\n\n return url.toString().replace('http://e.com', '') as PathWithoutLocale<T, L>;\n};\n"],"mappings":";;;;;;;;AAUA,MAAM,0BACJ,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,gBACtC,QAAQ,IAAI,0BAA0B;;;;AAKxC,MAAM,2BACJ,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxC,MAAa,wBAIX,UACA,UAAe,sBAAsB,YACT;CAE5B,MAAM,gBAAgB,mBAAmB,QAAQ;CAEjD,IAAI,gBAAwB;CAE5B,IAAI,UAAU,SAAS,GAAG,GACxB,gBAAgB,SAAS,MAAM,GAAG,EAAE;CAKtC,MAAM,MAAM,gBACR,IAAI,IAAI,aAAa,IACrB,IAAI,IAAI,eAAe,cAAc;CAEzC,MAAM,WAAW,IAAI;CAGrB,IAAI,CAAC,SAAS,WAAW,GAAG,GAE1B,IAAI,WAAW,IAAI;CAIrB,IAAI,CAAC,yBAAyB;EAE5B,MAAM,eAAe,SAAS,MAAM,GAAG;EACvC,MAAM,eAAe,aAAa;EAGlC,IAAI,SAAS,SAAS,YAAiB,GAAG;GAExC,aAAa,OAAO,GAAG,CAAC;GAIxB,IAAI,WADgB,aAAa,KAAK,GAAG,KAAK;EAEhD;CACF;CAGA,IAAI,CAAC,0BAA0B;EAC7B,MAAM,eAAe,IAAI,gBAAgB,IAAI,MAAM;EACnD,IAAI,aAAa,IAAI,QAAQ,GAAG;GAC9B,aAAa,OAAO,QAAQ;GAC5B,IAAI,SAAS,aAAa,SAAS;EACrC;CACF;CAEA,IAAI,eACF,OAAO,IAAI,SAAS;CAGtB,OAAO,IAAI,SAAS,CAAC,CAAC,QAAQ,gBAAgB,EAAE;AAClD"}
@@ -6,6 +6,7 @@ import { internationalization } from "@intlayer/config/built";
6
6
  * or falls back to the default locale if no match is found.
7
7
  */
8
8
  const localeResolver = (selectedLocale, locales = internationalization?.locales, defaultLocale = internationalization?.defaultLocale) => {
9
+ if (locales?.includes(selectedLocale)) return selectedLocale;
9
10
  const requestedLocales = [selectedLocale].flat();
10
11
  const normalize = (locale) => locale.trim().toLowerCase();
11
12
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"localeResolver.mjs","names":[],"sources":["../../../src/localization/localeResolver.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Resolves the most specific locale from a user-provided list,\n * or falls back to the default locale if no match is found.\n */\nexport const localeResolver = (\n selectedLocale: LocalesValues | LocalesValues[],\n locales: LocalesValues[] = internationalization?.locales,\n defaultLocale: LocalesValues = internationalization?.defaultLocale\n): DeclaredLocales => {\n // Ensure we can handle both a single locale or an array of locales uniformly\n const requestedLocales = [selectedLocale].flat();\n\n // Simple helper to normalize locale strings (e.g. \"en-US\" => \"en-us\")\n const normalize = (locale: string): string => locale.trim().toLowerCase();\n\n try {\n // Check each requested locale in order\n for (const requested of requestedLocales) {\n const normalizedRequested = normalize(requested);\n\n // Attempt exact match\n const exactMatch = locales.find(\n (locale) => normalize(locale) === normalizedRequested\n );\n if (exactMatch) {\n return exactMatch as DeclaredLocales;\n }\n\n // Attempt partial match on language subtag\n // e.g. if requested is \"en-US\" and not found,\n // see if \"en\" is available among locales\n const [requestedLang] = normalizedRequested.split('-');\n const partialMatch = locales.find(\n (locale) => normalize(locale).split('-')[0] === requestedLang\n );\n if (partialMatch) {\n return partialMatch as DeclaredLocales;\n }\n }\n } catch {\n // If anything unexpected happened, fall back to default\n }\n\n // If no match was found, return the default\n return defaultLocale as DeclaredLocales;\n};\n"],"mappings":";;;;;;;AAUA,MAAa,kBACX,gBACA,UAA2B,sBAAsB,SACjD,gBAA+B,sBAAsB,kBACjC;CAEpB,MAAM,mBAAmB,CAAC,cAAc,CAAC,CAAC,KAAK;CAG/C,MAAM,aAAa,WAA2B,OAAO,KAAK,CAAC,CAAC,YAAY;CAExE,IAAI;EAEF,KAAK,MAAM,aAAa,kBAAkB;GACxC,MAAM,sBAAsB,UAAU,SAAS;GAG/C,MAAM,aAAa,QAAQ,MACxB,WAAW,UAAU,MAAM,MAAM,mBACpC;GACA,IAAI,YACF,OAAO;GAMT,MAAM,CAAC,iBAAiB,oBAAoB,MAAM,GAAG;GACrD,MAAM,eAAe,QAAQ,MAC1B,WAAW,UAAU,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,aAClD;GACA,IAAI,cACF,OAAO;EAEX;CACF,QAAQ,CAER;CAGA,OAAO;AACT"}
1
+ {"version":3,"file":"localeResolver.mjs","names":[],"sources":["../../../src/localization/localeResolver.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Resolves the most specific locale from a user-provided list,\n * or falls back to the default locale if no match is found.\n */\nexport const localeResolver = (\n selectedLocale: LocalesValues | LocalesValues[],\n locales: LocalesValues[] = internationalization?.locales,\n defaultLocale: LocalesValues = internationalization?.defaultLocale\n): DeclaredLocales => {\n // Fast path: an already-declared locale needs no normalization\n if (locales?.includes(selectedLocale as LocalesValues)) {\n return selectedLocale as DeclaredLocales;\n }\n\n // Ensure we can handle both a single locale or an array of locales uniformly\n const requestedLocales = [selectedLocale].flat();\n\n // Simple helper to normalize locale strings (e.g. \"en-US\" => \"en-us\")\n const normalize = (locale: string): string => locale.trim().toLowerCase();\n\n try {\n // Check each requested locale in order\n for (const requested of requestedLocales) {\n const normalizedRequested = normalize(requested);\n\n // Attempt exact match\n const exactMatch = locales.find(\n (locale) => normalize(locale) === normalizedRequested\n );\n if (exactMatch) {\n return exactMatch as DeclaredLocales;\n }\n\n // Attempt partial match on language subtag\n // e.g. if requested is \"en-US\" and not found,\n // see if \"en\" is available among locales\n const [requestedLang] = normalizedRequested.split('-');\n const partialMatch = locales.find(\n (locale) => normalize(locale).split('-')[0] === requestedLang\n );\n if (partialMatch) {\n return partialMatch as DeclaredLocales;\n }\n }\n } catch {\n // If anything unexpected happened, fall back to default\n }\n\n // If no match was found, return the default\n return defaultLocale as DeclaredLocales;\n};\n"],"mappings":";;;;;;;AAUA,MAAa,kBACX,gBACA,UAA2B,sBAAsB,SACjD,gBAA+B,sBAAsB,kBACjC;CAEpB,IAAI,SAAS,SAAS,cAA+B,GACnD,OAAO;CAIT,MAAM,mBAAmB,CAAC,cAAc,CAAC,CAAC,KAAK;CAG/C,MAAM,aAAa,WAA2B,OAAO,KAAK,CAAC,CAAC,YAAY;CAExE,IAAI;EAEF,KAAK,MAAM,aAAa,kBAAkB;GACxC,MAAM,sBAAsB,UAAU,SAAS;GAG/C,MAAM,aAAa,QAAQ,MACxB,WAAW,UAAU,MAAM,MAAM,mBACpC;GACA,IAAI,YACF,OAAO;GAMT,MAAM,CAAC,iBAAiB,oBAAoB,MAAM,GAAG;GACrD,MAAM,eAAe,QAAQ,MAC1B,WAAW,UAAU,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,aAClD;GACA,IAAI,cACF,OAAO;EAEX;CACF,QAAQ,CAER;CAGA,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, DO_NOT_PROCESS_HTML_ELEMENTS, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_LEFT_TRIM_AMOUNT_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNORDERED, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R } from "./constants.mjs";
1
+ import { ATTRIBUTE_NAME_START_R, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, DO_NOT_PROCESS_HTML_ELEMENTS, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_LEFT_TRIM_AMOUNT_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNORDERED, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R } from "./constants.mjs";
2
2
  import { matchCustomComponent, matchHtmlBlockElement, matchSelfClosingElement, startsWithCustomComponent, startsWithElement, startsWithHtmlBlockElement, startsWithSelfClosingElement } from "./elementScanner.mjs";
3
3
  import { allowInline, anyScopeRegex, attributeValueToNodePropValue, blockRegex, captureNothing, cx, get, inlineRegex, normalizeAttributeKey, parseBlock, parseCaptureInline, parseInline, parseSimpleInline, parseTableAlign, parseTableCells, parseTableRow, renderNothing, sanitizer, simpleInlineRegex, slugify, some, startsWith, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, unquote } from "./utils.mjs";
4
4
  import { parserFor } from "./parser.mjs";
@@ -106,7 +106,8 @@ const createElementFactory = (ctx, options) => {
106
106
  };
107
107
  const createDocumentScope = () => ({
108
108
  footnotes: [],
109
- references: {}
109
+ references: {},
110
+ slugCounts: /* @__PURE__ */ new Map()
110
111
  });
111
112
  /**
112
113
  * Small enough to scan linearly, large enough that an app mixing a few option
@@ -521,9 +522,17 @@ const createRules = (createElement, ctx, options, scope, attrStringToMap, contai
521
522
  _order: Priority.HIGH,
522
523
  _parse(capture, parse, state) {
523
524
  const text = capture[2] ?? "";
525
+ const baseSlug = slug(text) || "section";
526
+ const counts = scope.current.slugCounts;
527
+ let id = baseSlug;
528
+ if (counts) {
529
+ const count = counts.get(baseSlug) ?? 0;
530
+ counts.set(baseSlug, count + 1);
531
+ if (count > 0) id = `${baseSlug}-${count}`;
532
+ }
524
533
  return {
525
534
  children: parseInline(parse, text, state),
526
- id: slug(text),
535
+ id,
527
536
  level: capture[1]?.length ?? 1
528
537
  };
529
538
  },
@@ -980,7 +989,7 @@ const createDocumentRules = (createElement, ctx, options, scope) => {
980
989
  if (mappedKey === "ref") return map;
981
990
  map[mappedKey] = attributeValueToNodePropValue(tag, key, value, ctx.sanitizer ?? sanitizer);
982
991
  if (typeof map[mappedKey] === "string" && startsWithElement(map[mappedKey])) map[mappedKey] = parseMarkdown(map[mappedKey].trim(), ctx, options).ast;
983
- } else if (raw !== "style") map[ATTRIBUTE_TO_NODE_PROP_MAP[raw] ?? raw] = true;
992
+ } else if (raw !== "style" && ATTRIBUTE_NAME_START_R.test(raw)) map[ATTRIBUTE_TO_NODE_PROP_MAP[raw] ?? raw] = true;
984
993
  return map;
985
994
  }, {});
986
995
  };