@intlayer/babel 9.4.4 → 9.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +0 -2
  2. package/dist/cjs/analyzeContentUsage.cjs +301 -0
  3. package/dist/cjs/analyzeContentUsage.cjs.map +1 -0
  4. package/dist/cjs/babel-plugin-intlayer-field-rename.cjs +5 -4
  5. package/dist/cjs/babel-plugin-intlayer-field-rename.cjs.map +1 -1
  6. package/dist/cjs/babel-plugin-intlayer-optimize.cjs +171 -282
  7. package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
  8. package/dist/cjs/babel-plugin-intlayer-purge.cjs +4 -3
  9. package/dist/cjs/babel-plugin-intlayer-purge.cjs.map +1 -1
  10. package/dist/cjs/babel-plugin-intlayer-usage-analyzer.cjs +49 -699
  11. package/dist/cjs/babel-plugin-intlayer-usage-analyzer.cjs.map +1 -1
  12. package/dist/cjs/compat/namespaceResolution.cjs +124 -0
  13. package/dist/cjs/compat/namespaceResolution.cjs.map +1 -0
  14. package/dist/cjs/compat/optimizePass.cjs +144 -0
  15. package/dist/cjs/compat/optimizePass.cjs.map +1 -0
  16. package/dist/cjs/compat/usageAnalysis.cjs +195 -0
  17. package/dist/cjs/compat/usageAnalysis.cjs.map +1 -0
  18. package/dist/cjs/dictionaryImports.cjs +40 -0
  19. package/dist/cjs/dictionaryImports.cjs.map +1 -0
  20. package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs +1 -1
  21. package/dist/cjs/getExtractPluginOptions.cjs +1 -1
  22. package/dist/cjs/getOptimizePluginOptions.cjs +2 -6
  23. package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
  24. package/dist/cjs/getPurgePluginOptions.cjs +1 -1
  25. package/dist/cjs/index.cjs +9 -5
  26. package/dist/cjs/nativeCallers.cjs +41 -0
  27. package/dist/cjs/nativeCallers.cjs.map +1 -0
  28. package/dist/cjs/pruneContext.cjs +79 -0
  29. package/dist/cjs/pruneContext.cjs.map +1 -0
  30. package/dist/cjs/staticAstReaders.cjs +140 -0
  31. package/dist/cjs/staticAstReaders.cjs.map +1 -0
  32. package/dist/cjs/transformers.cjs +2 -1
  33. package/dist/cjs/transformers.cjs.map +1 -1
  34. package/dist/esm/analyzeContentUsage.mjs +300 -0
  35. package/dist/esm/analyzeContentUsage.mjs.map +1 -0
  36. package/dist/esm/babel-plugin-intlayer-field-rename.mjs +3 -2
  37. package/dist/esm/babel-plugin-intlayer-field-rename.mjs.map +1 -1
  38. package/dist/esm/babel-plugin-intlayer-optimize.mjs +171 -282
  39. package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
  40. package/dist/esm/babel-plugin-intlayer-purge.mjs +3 -2
  41. package/dist/esm/babel-plugin-intlayer-purge.mjs.map +1 -1
  42. package/dist/esm/babel-plugin-intlayer-usage-analyzer.mjs +43 -694
  43. package/dist/esm/babel-plugin-intlayer-usage-analyzer.mjs.map +1 -1
  44. package/dist/esm/compat/namespaceResolution.mjs +120 -0
  45. package/dist/esm/compat/namespaceResolution.mjs.map +1 -0
  46. package/dist/esm/compat/optimizePass.mjs +143 -0
  47. package/dist/esm/compat/optimizePass.mjs.map +1 -0
  48. package/dist/esm/compat/usageAnalysis.mjs +193 -0
  49. package/dist/esm/compat/usageAnalysis.mjs.map +1 -0
  50. package/dist/esm/dictionaryImports.mjs +38 -0
  51. package/dist/esm/dictionaryImports.mjs.map +1 -0
  52. package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs +1 -1
  53. package/dist/esm/getExtractPluginOptions.mjs +1 -1
  54. package/dist/esm/getOptimizePluginOptions.mjs +2 -6
  55. package/dist/esm/getOptimizePluginOptions.mjs.map +1 -1
  56. package/dist/esm/getPurgePluginOptions.mjs +1 -1
  57. package/dist/esm/index.mjs +5 -2
  58. package/dist/esm/nativeCallers.mjs +38 -0
  59. package/dist/esm/nativeCallers.mjs.map +1 -0
  60. package/dist/esm/pruneContext.mjs +76 -0
  61. package/dist/esm/pruneContext.mjs.map +1 -0
  62. package/dist/esm/staticAstReaders.mjs +129 -0
  63. package/dist/esm/staticAstReaders.mjs.map +1 -0
  64. package/dist/esm/transformers.mjs +2 -1
  65. package/dist/esm/transformers.mjs.map +1 -1
  66. package/dist/types/analyzeContentUsage.d.ts +18 -0
  67. package/dist/types/analyzeContentUsage.d.ts.map +1 -0
  68. package/dist/types/babel-plugin-intlayer-field-rename.d.ts +2 -1
  69. package/dist/types/babel-plugin-intlayer-field-rename.d.ts.map +1 -1
  70. package/dist/types/babel-plugin-intlayer-optimize.d.ts +9 -15
  71. package/dist/types/babel-plugin-intlayer-optimize.d.ts.map +1 -1
  72. package/dist/types/babel-plugin-intlayer-purge.d.ts +3 -2
  73. package/dist/types/babel-plugin-intlayer-purge.d.ts.map +1 -1
  74. package/dist/types/babel-plugin-intlayer-usage-analyzer.d.ts +20 -187
  75. package/dist/types/babel-plugin-intlayer-usage-analyzer.d.ts.map +1 -1
  76. package/dist/types/compat/namespaceResolution.d.ts +66 -0
  77. package/dist/types/compat/namespaceResolution.d.ts.map +1 -0
  78. package/dist/types/compat/optimizePass.d.ts +58 -0
  79. package/dist/types/compat/optimizePass.d.ts.map +1 -0
  80. package/dist/types/compat/usageAnalysis.d.ts +75 -0
  81. package/dist/types/compat/usageAnalysis.d.ts.map +1 -0
  82. package/dist/types/dictionaryImports.d.ts +46 -0
  83. package/dist/types/dictionaryImports.d.ts.map +1 -0
  84. package/dist/types/index.d.ts +5 -2
  85. package/dist/types/nativeCallers.d.ts +33 -0
  86. package/dist/types/nativeCallers.d.ts.map +1 -0
  87. package/dist/types/pruneContext.d.ts +152 -0
  88. package/dist/types/pruneContext.d.ts.map +1 -0
  89. package/dist/types/staticAstReaders.d.ts +84 -0
  90. package/dist/types/staticAstReaders.d.ts.map +1 -0
  91. package/dist/types/transformers.d.ts +2 -1
  92. package/dist/types/transformers.d.ts.map +1 -1
  93. package/package.json +10 -10
@@ -0,0 +1,129 @@
1
+ //#region src/staticAstReaders.ts
2
+ /**
3
+ * Static-value readers shared by every pass that has to decide, at build time,
4
+ * which dictionary a call site reads.
5
+ *
6
+ * They were previously duplicated — with small behavioural drifts — between
7
+ * `babel-plugin-intlayer-optimize` and `babel-plugin-intlayer-usage-analyzer`.
8
+ * Both now read through this module so a call site the analyser can attribute
9
+ * is exactly the one the optimizer can rewrite.
10
+ */
11
+ /**
12
+ * Reads a fully-static string from an AST node. Returns `undefined` for
13
+ * dynamic values (identifiers, expressions, template literals with
14
+ * interpolations, …).
15
+ */
16
+ const readStaticString = (babelTypes, node) => {
17
+ if (!node) return void 0;
18
+ if (babelTypes.isStringLiteral(node)) return node.value;
19
+ if (babelTypes.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
20
+ };
21
+ /** Returns the first dot-path segment of a key, e.g. `'a.b.c'` → `'a'`. */
22
+ const firstPathSegment = (path) => path.split(".")[0] ?? path;
23
+ /**
24
+ * Reads the static first dot-path segment from a message-id node.
25
+ *
26
+ * t('counter.label') → 'counter'
27
+ * t(`counter.${x}`) → 'counter' (static prefix before the first dot)
28
+ * t(`${x}.label`) → undefined (dynamic first segment)
29
+ * t(someVariable) → undefined
30
+ */
31
+ const readStaticFirstSegment = (babelTypes, node) => {
32
+ const staticString = readStaticString(babelTypes, node);
33
+ if (staticString !== void 0) return firstPathSegment(staticString);
34
+ if (babelTypes.isTemplateLiteral(node) && node.quasis.length > 0) {
35
+ const firstQuasi = node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
36
+ if (firstQuasi?.includes(".")) return firstPathSegment(firstQuasi);
37
+ }
38
+ };
39
+ /** Whether an object-property key (identifier or string literal) reads as `name`. */
40
+ const propertyKeyMatches = (babelTypes, property, name) => babelTypes.isIdentifier(property.key) && property.key.name === name || babelTypes.isStringLiteral(property.key) && property.key.value === name;
41
+ /**
42
+ * Returns the `ObjectProperty` named `propertyName`, or `undefined` when the
43
+ * object has no such property. Callers that need to mutate the property in
44
+ * place (rewriting or deleting it) use this rather than a value reader.
45
+ */
46
+ const findObjectProperty = (babelTypes, objectExpression, propertyName) => {
47
+ for (const property of objectExpression.properties) {
48
+ if (!babelTypes.isObjectProperty(property)) continue;
49
+ if (propertyKeyMatches(babelTypes, property, propertyName)) return property;
50
+ }
51
+ };
52
+ /**
53
+ * Marker returned by the reader helpers when the requested property or
54
+ * argument is simply absent — distinct from present-but-dynamic, which the
55
+ * callers must treat conservatively.
56
+ */
57
+ const ABSENT_VALUE = "__default__";
58
+ /**
59
+ * Reads a static string property from an object expression. Returns
60
+ * {@link ABSENT_VALUE} when the property is absent and `undefined` when
61
+ * present but dynamic.
62
+ */
63
+ const readObjectProperty = (babelTypes, objectExpression, propertyName) => {
64
+ const property = findObjectProperty(babelTypes, objectExpression, propertyName);
65
+ if (!property) return ABSENT_VALUE;
66
+ return readStaticString(babelTypes, property.value);
67
+ };
68
+ /**
69
+ * Returns the value *node* of a named property, so callers can apply their own
70
+ * reader to it (a full static string, or just its leading path segment).
71
+ * Returns {@link ABSENT_VALUE} when the property is absent.
72
+ */
73
+ const readObjectPropertyNode = (babelTypes, objectExpression, propertyName) => {
74
+ const property = findObjectProperty(babelTypes, objectExpression, propertyName);
75
+ if (!property) return ABSENT_VALUE;
76
+ return property.value;
77
+ };
78
+ /**
79
+ * Reads a named JSX attribute as a static string and returns it wrapped in a
80
+ * `StringLiteral` node so the result can be fed to the same namespace resolver
81
+ * as a call argument. Handles both `id="home.title"` and `id={'home.title'}`.
82
+ * Returns `undefined` when the attribute is absent or dynamic (`id={expr}`).
83
+ */
84
+ const readJsxAttributeString = (babelTypes, openingElement, attributeName) => {
85
+ for (const attribute of openingElement.attributes) {
86
+ if (!babelTypes.isJSXAttribute(attribute)) continue;
87
+ if (!babelTypes.isJSXIdentifier(attribute.name) || attribute.name.name !== attributeName) continue;
88
+ const value = attribute.value;
89
+ if (babelTypes.isStringLiteral(value)) return value;
90
+ if (babelTypes.isJSXExpressionContainer(value)) {
91
+ const staticString = readStaticString(babelTypes, value.expression);
92
+ if (staticString !== void 0) return babelTypes.stringLiteral(staticString);
93
+ }
94
+ return;
95
+ }
96
+ };
97
+ /**
98
+ * Splits a compat namespace at the first `.` to separate the dictionary key
99
+ * from an optional key prefix, mirroring the SWC plugin's `split_namespace`.
100
+ *
101
+ * `'about'` → `{ dictionaryKey: 'about', keyPrefix: '' }`
102
+ * `'about.counter'` → `{ dictionaryKey: 'about', keyPrefix: 'counter' }`
103
+ */
104
+ const splitNamespace = (namespace) => {
105
+ const dotPosition = namespace.indexOf(".");
106
+ if (dotPosition === -1) return {
107
+ dictionaryKey: namespace,
108
+ keyPrefix: ""
109
+ };
110
+ return {
111
+ dictionaryKey: namespace.slice(0, dotPosition),
112
+ keyPrefix: namespace.slice(dotPosition + 1)
113
+ };
114
+ };
115
+ /**
116
+ * Climbs past an enclosing `await` expression so that
117
+ * `const t = await getTranslations('ns')` — or `await getIntlayerAsync('key')`
118
+ * — is resolved to its variable declarator the same way the synchronous form
119
+ * is.
120
+ */
121
+ const unwrapAwait = (babelTypes, path) => {
122
+ const parentPath = path.parentPath;
123
+ if (parentPath && babelTypes.isAwaitExpression(parentPath.node)) return parentPath;
124
+ return path;
125
+ };
126
+
127
+ //#endregion
128
+ export { ABSENT_VALUE, findObjectProperty, firstPathSegment, propertyKeyMatches, readJsxAttributeString, readObjectProperty, readObjectPropertyNode, readStaticFirstSegment, readStaticString, splitNamespace, unwrapAwait };
129
+ //# sourceMappingURL=staticAstReaders.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"staticAstReaders.mjs","names":[],"sources":["../../src/staticAstReaders.ts"],"sourcesContent":["import type { NodePath } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\n\n/**\n * Static-value readers shared by every pass that has to decide, at build time,\n * which dictionary a call site reads.\n *\n * They were previously duplicated — with small behavioural drifts — between\n * `babel-plugin-intlayer-optimize` and `babel-plugin-intlayer-usage-analyzer`.\n * Both now read through this module so a call site the analyser can attribute\n * is exactly the one the optimizer can rewrite.\n */\n\n/**\n * Reads a fully-static string from an AST node. Returns `undefined` for\n * dynamic values (identifiers, expressions, template literals with\n * interpolations, …).\n */\nexport const readStaticString = (\n babelTypes: typeof BabelTypes,\n node: BabelTypes.Node | null | undefined\n): string | undefined => {\n if (!node) return undefined;\n if (babelTypes.isStringLiteral(node)) return node.value;\n if (\n babelTypes.isTemplateLiteral(node) &&\n node.expressions.length === 0 &&\n node.quasis.length === 1\n ) {\n return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;\n }\n return undefined;\n};\n\n/** Returns the first dot-path segment of a key, e.g. `'a.b.c'` → `'a'`. */\nexport const firstPathSegment = (path: string): string =>\n path.split('.')[0] ?? path;\n\n/**\n * Reads the static first dot-path segment from a message-id node.\n *\n * t('counter.label') → 'counter'\n * t(`counter.${x}`) → 'counter' (static prefix before the first dot)\n * t(`${x}.label`) → undefined (dynamic first segment)\n * t(someVariable) → undefined\n */\nexport const readStaticFirstSegment = (\n babelTypes: typeof BabelTypes,\n node: BabelTypes.Node | null | undefined\n): string | undefined => {\n const staticString = readStaticString(babelTypes, node);\n if (staticString !== undefined) return firstPathSegment(staticString);\n\n // Template literal whose first quasi already contains the dot delimiter, e.g.\n // `counter.${index}` → the leading `counter` segment is statically known.\n if (babelTypes.isTemplateLiteral(node) && node.quasis.length > 0) {\n const firstQuasi =\n node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;\n if (firstQuasi?.includes('.')) {\n return firstPathSegment(firstQuasi);\n }\n }\n return undefined;\n};\n\n/** Whether an object-property key (identifier or string literal) reads as `name`. */\nexport const propertyKeyMatches = (\n babelTypes: typeof BabelTypes,\n property: BabelTypes.ObjectProperty,\n name: string\n): boolean =>\n (babelTypes.isIdentifier(property.key) && property.key.name === name) ||\n (babelTypes.isStringLiteral(property.key) && property.key.value === name);\n\n/**\n * Returns the `ObjectProperty` named `propertyName`, or `undefined` when the\n * object has no such property. Callers that need to mutate the property in\n * place (rewriting or deleting it) use this rather than a value reader.\n */\nexport const findObjectProperty = (\n babelTypes: typeof BabelTypes,\n objectExpression: BabelTypes.ObjectExpression,\n propertyName: string\n): BabelTypes.ObjectProperty | undefined => {\n for (const property of objectExpression.properties) {\n if (!babelTypes.isObjectProperty(property)) continue;\n if (propertyKeyMatches(babelTypes, property, propertyName)) return property;\n }\n return undefined;\n};\n\n/**\n * Marker returned by the reader helpers when the requested property or\n * argument is simply absent — distinct from present-but-dynamic, which the\n * callers must treat conservatively.\n */\nexport const ABSENT_VALUE = '__default__' as const;\n\n/** Either a statically-known value, {@link ABSENT_VALUE}, or `undefined` (dynamic). */\nexport type StaticOrAbsent<T> = T | typeof ABSENT_VALUE | undefined;\n\n/**\n * Reads a static string property from an object expression. Returns\n * {@link ABSENT_VALUE} when the property is absent and `undefined` when\n * present but dynamic.\n */\nexport const readObjectProperty = (\n babelTypes: typeof BabelTypes,\n objectExpression: BabelTypes.ObjectExpression,\n propertyName: string\n): StaticOrAbsent<string> => {\n const property = findObjectProperty(\n babelTypes,\n objectExpression,\n propertyName\n );\n if (!property) return ABSENT_VALUE;\n return readStaticString(babelTypes, property.value); // present but dynamic → undefined\n};\n\n/**\n * Returns the value *node* of a named property, so callers can apply their own\n * reader to it (a full static string, or just its leading path segment).\n * Returns {@link ABSENT_VALUE} when the property is absent.\n */\nexport const readObjectPropertyNode = (\n babelTypes: typeof BabelTypes,\n objectExpression: BabelTypes.ObjectExpression,\n propertyName: string\n): StaticOrAbsent<BabelTypes.Node> => {\n const property = findObjectProperty(\n babelTypes,\n objectExpression,\n propertyName\n );\n if (!property) return ABSENT_VALUE;\n return property.value;\n};\n\n/**\n * Reads a named JSX attribute as a static string and returns it wrapped in a\n * `StringLiteral` node so the result can be fed to the same namespace resolver\n * as a call argument. Handles both `id=\"home.title\"` and `id={'home.title'}`.\n * Returns `undefined` when the attribute is absent or dynamic (`id={expr}`).\n */\nexport const readJsxAttributeString = (\n babelTypes: typeof BabelTypes,\n openingElement: BabelTypes.JSXOpeningElement,\n attributeName: string\n): BabelTypes.StringLiteral | undefined => {\n for (const attribute of openingElement.attributes) {\n if (!babelTypes.isJSXAttribute(attribute)) continue;\n if (\n !babelTypes.isJSXIdentifier(attribute.name) ||\n attribute.name.name !== attributeName\n ) {\n continue;\n }\n\n const value = attribute.value;\n // id=\"home.title\"\n if (babelTypes.isStringLiteral(value)) return value;\n // id={'home.title'} / id={`home.title`}\n if (babelTypes.isJSXExpressionContainer(value)) {\n const staticString = readStaticString(babelTypes, value.expression);\n if (staticString !== undefined) {\n return babelTypes.stringLiteral(staticString);\n }\n }\n return undefined; // attribute present but dynamic\n }\n return undefined; // attribute absent\n};\n\n/**\n * Splits a compat namespace at the first `.` to separate the dictionary key\n * from an optional key prefix, mirroring the SWC plugin's `split_namespace`.\n *\n * `'about'` → `{ dictionaryKey: 'about', keyPrefix: '' }`\n * `'about.counter'` → `{ dictionaryKey: 'about', keyPrefix: 'counter' }`\n */\nexport const splitNamespace = (\n namespace: string\n): { dictionaryKey: string; keyPrefix: string } => {\n const dotPosition = namespace.indexOf('.');\n if (dotPosition === -1) return { dictionaryKey: namespace, keyPrefix: '' };\n return {\n dictionaryKey: namespace.slice(0, dotPosition),\n keyPrefix: namespace.slice(dotPosition + 1),\n };\n};\n\n/**\n * Climbs past an enclosing `await` expression so that\n * `const t = await getTranslations('ns')` — or `await getIntlayerAsync('key')`\n * — is resolved to its variable declarator the same way the synchronous form\n * is.\n */\nexport const unwrapAwait = (\n babelTypes: typeof BabelTypes,\n path: NodePath<BabelTypes.Node>\n): NodePath<BabelTypes.Node> => {\n const parentPath = path.parentPath;\n if (parentPath && babelTypes.isAwaitExpression(parentPath.node)) {\n return parentPath;\n }\n return path;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,MAAa,oBACX,YACA,SACuB;CACvB,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,WAAW,gBAAgB,IAAI,GAAG,OAAO,KAAK;CAClD,IACE,WAAW,kBAAkB,IAAI,KACjC,KAAK,YAAY,WAAW,KAC5B,KAAK,OAAO,WAAW,GAEvB,OAAO,KAAK,OAAO,EAAE,EAAE,MAAM,UAAU,KAAK,OAAO,EAAE,EAAE,MAAM;AAGjE;;AAGA,MAAa,oBAAoB,SAC/B,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM;;;;;;;;;AAUxB,MAAa,0BACX,YACA,SACuB;CACvB,MAAM,eAAe,iBAAiB,YAAY,IAAI;CACtD,IAAI,iBAAiB,QAAW,OAAO,iBAAiB,YAAY;CAIpE,IAAI,WAAW,kBAAkB,IAAI,KAAK,KAAK,OAAO,SAAS,GAAG;EAChE,MAAM,aACJ,KAAK,OAAO,EAAE,EAAE,MAAM,UAAU,KAAK,OAAO,EAAE,EAAE,MAAM;EACxD,IAAI,YAAY,SAAS,GAAG,GAC1B,OAAO,iBAAiB,UAAU;CAEtC;AAEF;;AAGA,MAAa,sBACX,YACA,UACA,SAEC,WAAW,aAAa,SAAS,GAAG,KAAK,SAAS,IAAI,SAAS,QAC/D,WAAW,gBAAgB,SAAS,GAAG,KAAK,SAAS,IAAI,UAAU;;;;;;AAOtE,MAAa,sBACX,YACA,kBACA,iBAC0C;CAC1C,KAAK,MAAM,YAAY,iBAAiB,YAAY;EAClD,IAAI,CAAC,WAAW,iBAAiB,QAAQ,GAAG;EAC5C,IAAI,mBAAmB,YAAY,UAAU,YAAY,GAAG,OAAO;CACrE;AAEF;;;;;;AAOA,MAAa,eAAe;;;;;;AAU5B,MAAa,sBACX,YACA,kBACA,iBAC2B;CAC3B,MAAM,WAAW,mBACf,YACA,kBACA,YACF;CACA,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO,iBAAiB,YAAY,SAAS,KAAK;AACpD;;;;;;AAOA,MAAa,0BACX,YACA,kBACA,iBACoC;CACpC,MAAM,WAAW,mBACf,YACA,kBACA,YACF;CACA,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO,SAAS;AAClB;;;;;;;AAQA,MAAa,0BACX,YACA,gBACA,kBACyC;CACzC,KAAK,MAAM,aAAa,eAAe,YAAY;EACjD,IAAI,CAAC,WAAW,eAAe,SAAS,GAAG;EAC3C,IACE,CAAC,WAAW,gBAAgB,UAAU,IAAI,KAC1C,UAAU,KAAK,SAAS,eAExB;EAGF,MAAM,QAAQ,UAAU;EAExB,IAAI,WAAW,gBAAgB,KAAK,GAAG,OAAO;EAE9C,IAAI,WAAW,yBAAyB,KAAK,GAAG;GAC9C,MAAM,eAAe,iBAAiB,YAAY,MAAM,UAAU;GAClE,IAAI,iBAAiB,QACnB,OAAO,WAAW,cAAc,YAAY;EAEhD;EACA;CACF;AAEF;;;;;;;;AASA,MAAa,kBACX,cACiD;CACjD,MAAM,cAAc,UAAU,QAAQ,GAAG;CACzC,IAAI,gBAAgB,IAAI,OAAO;EAAE,eAAe;EAAW,WAAW;CAAG;CACzE,OAAO;EACL,eAAe,UAAU,MAAM,GAAG,WAAW;EAC7C,WAAW,UAAU,MAAM,cAAc,CAAC;CAC5C;AACF;;;;;;;AAQA,MAAa,eACX,YACA,SAC8B;CAC9B,MAAM,aAAa,KAAK;CACxB,IAAI,cAAc,WAAW,kBAAkB,WAAW,IAAI,GAC5D,OAAO;CAET,OAAO;AACT"}
@@ -1,4 +1,5 @@
1
- import { INTLAYER_CALLER_NAMES, makeUsageAnalyzerBabelPlugin } from "./babel-plugin-intlayer-usage-analyzer.mjs";
1
+ import { INTLAYER_CALLER_NAMES } from "./nativeCallers.mjs";
2
+ import { makeUsageAnalyzerBabelPlugin } from "./babel-plugin-intlayer-usage-analyzer.mjs";
2
3
  import { extractScriptBlocks, injectScriptBlocks } from "./extractScriptBlocks.mjs";
3
4
  import { makeFieldRenameBabelPlugin } from "./babel-plugin-intlayer-field-rename.mjs";
4
5
  import { intlayerOptimizeBabelPlugin } from "./babel-plugin-intlayer-optimize.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"transformers.mjs","names":[],"sources":["../../src/transformers.ts"],"sourcesContent":["import { transformAsync } from '@babel/core';\n// Typed from `@babel/parser` rather than `@babel/core`'s\n// `InputOptions['parserOpts']` (Babel 8's rename of `TransformOptions`): the\n// two describe the same shape, but naming `@babel/core` in an exported type\n// pulls its declaration file into every consumer's type-check, and that file\n// needs `@types/convert-source-map` to resolve.\nimport type { ParserOptions } from '@babel/parser';\nimport { makeFieldRenameBabelPlugin } from './babel-plugin-intlayer-field-rename';\nimport {\n intlayerOptimizeBabelPlugin,\n type OptimizePluginOptions,\n} from './babel-plugin-intlayer-optimize';\nimport {\n type CompatCallerConfig,\n INTLAYER_CALLER_NAMES,\n makeUsageAnalyzerBabelPlugin,\n type PruneContext,\n} from './babel-plugin-intlayer-usage-analyzer';\nimport { extractScriptBlocks, injectScriptBlocks } from './extractScriptBlocks';\n\n// ── Shared Babel parser configuration ─────────────────────────────────────────\n\n/**\n * Babel parser options covering the superset of syntaxes used across all\n * supported frameworks (React / Vue / Svelte / Angular / …).\n */\nexport const BABEL_PARSER_OPTIONS: ParserOptions = {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n};\n\n/**\n * Builds a fast pre-check regex that matches files potentially containing\n * native intlayer calls and/or the given compat namespace caller names.\n *\n * The result is used to skip files that definitely contain none of the\n * relevant function names, avoiding unnecessary Babel parsing.\n *\n * The native names come from {@link INTLAYER_CALLER_NAMES} rather than being\n * spelled out here: a name missing from this regex silently opts every file\n * using it out of the optimize, purge and minify passes, leaving its calls to\n * resolve through the dictionary registry — empty in browser bundles.\n *\n * Compat caller names are NOT hardcoded here — they are provided at runtime by\n * the compat adapter packages that configure the usage-analysis pipeline.\n *\n * @param extraCallerNames - Additional caller function names to match\n * (e.g. `['useTranslation', 'getFixedT']` from `@intlayer/react-i18next`).\n * @returns A `RegExp` matching any of the native or provided caller names.\n */\nexport const buildUsageCheckRegex = (extraCallerNames?: string[]): RegExp => {\n const callerNames = [...INTLAYER_CALLER_NAMES, ...(extraCallerNames ?? [])];\n const uniqueNames = [...new Set(callerNames)];\n return new RegExp(`\\\\b(${uniqueNames.join('|')})\\\\b`);\n};\n\n/**\n * Fast pre-check: matches files that could contain native intlayer calls\n * (`useIntlayer` / `getIntlayer` / `getIntlayerAsync`). Used by the\n * optimize/transform pass, which only rewrites native calls.\n */\nexport const INTLAYER_USAGE_REGEX = buildUsageCheckRegex();\n\n/** Usage-check regex covering only the native callers (no compat callers). */\nconst NATIVE_USAGE_CHECK_REGEX = INTLAYER_USAGE_REGEX;\n\n/** Cache of usage-check regexes, keyed by the compat-caller array reference. */\nconst usageCheckRegexCache = new WeakMap<\n readonly CompatCallerConfig[],\n RegExp\n>();\n\n/**\n * Returns the usage-check regex for the given compat callers, memoised by the\n * array reference. Plugins pass the same options array for every analysed\n * file, so the regex is built once per build instead of once per file.\n */\nexport const getUsageCheckRegex = (\n compatCallers?: readonly CompatCallerConfig[]\n): RegExp => {\n if (!compatCallers || compatCallers.length === 0) {\n return NATIVE_USAGE_CHECK_REGEX;\n }\n\n let usageCheckRegex = usageCheckRegexCache.get(compatCallers);\n if (!usageCheckRegex) {\n usageCheckRegex = buildUsageCheckRegex(\n compatCallers.map((caller) => caller.callerName)\n );\n usageCheckRegexCache.set(compatCallers, usageCheckRegex);\n }\n return usageCheckRegex;\n};\n\n/**\n * Matches source files that are valid targets for usage analysis and Babel\n * transformation. Excludes sourcemap files, declaration files, and other\n * non-source extensions.\n */\nexport const SOURCE_FILE_REGEX = /\\.(tsx?|[mc]?jsx?|vue|svelte|astro)$/;\n\n// ── High-level transformer functions ──────────────────────────────────────────\n\n/**\n * Runs the usage-analysis Babel plugin on a single JS/TS code string.\n *\n * This is analysis-only: the transformed code output is discarded.\n * Throws if Babel cannot parse the content.\n */\nconst analyzeScriptContent = async (\n scriptContent: string,\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): Promise<void> => {\n await transformAsync(scriptContent, {\n filename: sourceFilePath,\n plugins: [makeUsageAnalyzerBabelPlugin(pruneContext, { compatCallers })],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n code: false, // analysis only – no output needed\n });\n};\n\n/**\n * Runs the usage-analysis Babel plugin on a source file, accumulating\n * field-usage data into `pruneContext`.\n *\n * For Vue / Svelte SFC files, script blocks are extracted before analysis so\n * Babel does not attempt to parse the full SFC syntax (templates, styles, …).\n * For plain JS/TS files, the whole file content is analysed directly.\n *\n * This is analysis-only: the transformed code output is discarded.\n * Throws if Babel cannot parse the file (caller should handle and flag\n * `pruneContext.hasUnparsableSourceFiles`).\n */\nexport const analyzeFieldUsageInFile = async (\n sourceFilePath: string,\n code: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): Promise<void> => {\n const usageCheckRegex = getUsageCheckRegex(compatCallers);\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n\n // For SFC files (Vue / Svelte): scriptBlocks[0].contentStartOffset > 0\n // means we extracted actual <script> tags from the file.\n // For plain JS/TS: extractScriptBlocks returns the whole file as a single\n // block with offset 0, so we fall through to the same path.\n for (const block of scriptBlocks) {\n if (!usageCheckRegex.test(block.content)) continue;\n await analyzeScriptContent(\n block.content,\n sourceFilePath,\n pruneContext,\n compatCallers\n );\n }\n};\n\n/**\n * Applies field-renaming to a single JS/TS code string (not an SFC).\n *\n * Returns the renamed code string, or `null` if nothing changed or if\n * Babel failed to parse the input (caller should fall back to original code).\n */\nexport const renameFieldsInCode = async (\n code: string,\n sourceFilePath: string,\n pruneContext: PruneContext\n): Promise<string | null> => {\n try {\n const result = await transformAsync(code, {\n filename: sourceFilePath,\n plugins: [makeFieldRenameBabelPlugin(pruneContext)],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n });\n return result?.code ?? null;\n } catch {\n return null; // parse failure – caller falls back to original code\n }\n};\n\n/**\n * Applies field-renaming to a source file, correctly handling both plain\n * JS/TS files and SFC files (Vue / Svelte) by operating on each script block\n * individually and injecting the results back into the original source.\n *\n * Returns the renamed code string, or `null` if nothing changed.\n */\nexport const renameFieldsInSourceFile = async (\n sourceFilePath: string,\n code: string,\n pruneContext: PruneContext\n): Promise<string | null> => {\n if (pruneContext.dictionaryKeyToFieldRenameMap.size === 0) return null;\n if (!INTLAYER_USAGE_REGEX.test(code)) return null;\n\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n\n const isSFC =\n scriptBlocks.length > 0 &&\n ((scriptBlocks[0]?.contentStartOffset ?? 0) > 0 || scriptBlocks.length > 1);\n\n if (isSFC) {\n // Raw SFC: rename each script block individually and inject back.\n const modifications: Array<{\n block: (typeof scriptBlocks)[number];\n modifiedContent: string;\n }> = [];\n\n for (const block of scriptBlocks) {\n if (!INTLAYER_USAGE_REGEX.test(block.content)) continue;\n\n const renamedCode = await renameFieldsInCode(\n block.content,\n sourceFilePath,\n pruneContext\n );\n if (renamedCode && renamedCode !== block.content) {\n modifications.push({ block, modifiedContent: renamedCode });\n }\n }\n\n if (modifications.length === 0) return null;\n return injectScriptBlocks(code, modifications);\n }\n\n // Plain JS/TS or compiled SFC (no block delimiters) – rename the whole file.\n return renameFieldsInCode(code, sourceFilePath, pruneContext);\n};\n\n/**\n * Runs the intlayer optimize Babel plugin on a source file, transforming\n * `useIntlayer('key')` / `getIntlayer('key')` calls into `useDictionary(_hash)`\n * / `getDictionary(_hash)` and injecting the corresponding dictionary imports.\n *\n * Returns `{ code, map }` on success, or `null` if the transformation produced\n * no output.\n */\nexport const optimizeSourceFile = async (\n code: string,\n sourceFilePath: string,\n options: OptimizePluginOptions\n): Promise<{\n code: string;\n map: string | object | null | undefined;\n} | null> => {\n const result = await transformAsync(code, {\n filename: sourceFilePath,\n plugins: [[intlayerOptimizeBabelPlugin, options]],\n parserOpts: BABEL_PARSER_OPTIONS,\n });\n\n if (!result?.code) return null;\n\n return { code: result.code, map: result.map };\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"transformers.mjs","names":[],"sources":["../../src/transformers.ts"],"sourcesContent":["import { transformAsync } from '@babel/core';\n// Typed from `@babel/parser` rather than `@babel/core`'s\n// `InputOptions['parserOpts']` (Babel 8's rename of `TransformOptions`): the\n// two describe the same shape, but naming `@babel/core` in an exported type\n// pulls its declaration file into every consumer's type-check, and that file\n// needs `@types/convert-source-map` to resolve.\nimport type { ParserOptions } from '@babel/parser';\nimport { makeFieldRenameBabelPlugin } from './babel-plugin-intlayer-field-rename';\nimport {\n intlayerOptimizeBabelPlugin,\n type OptimizePluginOptions,\n} from './babel-plugin-intlayer-optimize';\nimport {\n type CompatCallerConfig,\n INTLAYER_CALLER_NAMES,\n makeUsageAnalyzerBabelPlugin,\n type PruneContext,\n} from './babel-plugin-intlayer-usage-analyzer';\nimport { extractScriptBlocks, injectScriptBlocks } from './extractScriptBlocks';\n\n// ── Shared Babel parser configuration ─────────────────────────────────────────\n\n/**\n * Babel parser options covering the superset of syntaxes used across all\n * supported frameworks (React / Vue / Svelte / Angular / …).\n */\nexport const BABEL_PARSER_OPTIONS: ParserOptions = {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n};\n\n/**\n * Builds a fast pre-check regex that matches files potentially containing\n * native intlayer calls and/or the given compat namespace caller names.\n *\n * The result is used to skip files that definitely contain none of the\n * relevant function names, avoiding unnecessary Babel parsing.\n *\n * The native names come from {@link INTLAYER_CALLER_NAMES} rather than being\n * spelled out here: a name missing from this regex silently opts every file\n * using it out of the optimize, purge and minify passes, leaving its calls to\n * resolve through the dictionary registry — empty in browser bundles.\n *\n * Compat caller names are NOT hardcoded here — they are provided at runtime by\n * the compat adapter packages that configure the usage-analysis pipeline.\n *\n * @param extraCallerNames - Additional caller function names to match\n * (e.g. `['useTranslation', 'getFixedT']` from `@intlayer/react-i18next`).\n * @returns A `RegExp` matching any of the native or provided caller names.\n */\nexport const buildUsageCheckRegex = (extraCallerNames?: string[]): RegExp => {\n const callerNames = [...INTLAYER_CALLER_NAMES, ...(extraCallerNames ?? [])];\n const uniqueNames = [...new Set(callerNames)];\n return new RegExp(`\\\\b(${uniqueNames.join('|')})\\\\b`);\n};\n\n/**\n * Fast pre-check: matches files that could contain native intlayer calls\n * (`useIntlayer` / `getIntlayer` / `getIntlayerAsync`). Used by the\n * optimize/transform pass, which only rewrites native calls.\n */\nexport const INTLAYER_USAGE_REGEX = buildUsageCheckRegex();\n\n/** Usage-check regex covering only the native callers (no compat callers). */\nconst NATIVE_USAGE_CHECK_REGEX = INTLAYER_USAGE_REGEX;\n\n/** Cache of usage-check regexes, keyed by the compat-caller array reference. */\nconst usageCheckRegexCache = new WeakMap<\n readonly CompatCallerConfig[],\n RegExp\n>();\n\n/**\n * Returns the usage-check regex for the given compat callers, memoised by the\n * array reference. Plugins pass the same options array for every analysed\n * file, so the regex is built once per build instead of once per file.\n */\nexport const getUsageCheckRegex = (\n compatCallers?: readonly CompatCallerConfig[]\n): RegExp => {\n if (!compatCallers || compatCallers.length === 0) {\n return NATIVE_USAGE_CHECK_REGEX;\n }\n\n let usageCheckRegex = usageCheckRegexCache.get(compatCallers);\n if (!usageCheckRegex) {\n usageCheckRegex = buildUsageCheckRegex(\n compatCallers.map((caller) => caller.callerName)\n );\n usageCheckRegexCache.set(compatCallers, usageCheckRegex);\n }\n return usageCheckRegex;\n};\n\n/**\n * Matches source files that are valid targets for usage analysis and Babel\n * transformation. Excludes sourcemap files, declaration files, and other\n * non-source extensions.\n */\nexport const SOURCE_FILE_REGEX = /\\.(tsx?|[mc]?jsx?|vue|svelte|astro)$/;\n\n// ── High-level transformer functions ──────────────────────────────────────────\n\n/**\n * Runs the usage-analysis Babel plugin on a single JS/TS code string.\n *\n * This is analysis-only: the transformed code output is discarded.\n * Throws if Babel cannot parse the content.\n */\nconst analyzeScriptContent = async (\n scriptContent: string,\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): Promise<void> => {\n await transformAsync(scriptContent, {\n filename: sourceFilePath,\n plugins: [makeUsageAnalyzerBabelPlugin(pruneContext, { compatCallers })],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n code: false, // analysis only – no output needed\n });\n};\n\n/**\n * Runs the usage-analysis Babel plugin on a source file, accumulating\n * field-usage data into `pruneContext`.\n *\n * For Vue / Svelte SFC files, script blocks are extracted before analysis so\n * Babel does not attempt to parse the full SFC syntax (templates, styles, …).\n * For plain JS/TS files, the whole file content is analysed directly.\n *\n * This is analysis-only: the transformed code output is discarded.\n * Throws if Babel cannot parse the file (caller should handle and flag\n * `pruneContext.hasUnparsableSourceFiles`).\n */\nexport const analyzeFieldUsageInFile = async (\n sourceFilePath: string,\n code: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): Promise<void> => {\n const usageCheckRegex = getUsageCheckRegex(compatCallers);\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n\n // For SFC files (Vue / Svelte): scriptBlocks[0].contentStartOffset > 0\n // means we extracted actual <script> tags from the file.\n // For plain JS/TS: extractScriptBlocks returns the whole file as a single\n // block with offset 0, so we fall through to the same path.\n for (const block of scriptBlocks) {\n if (!usageCheckRegex.test(block.content)) continue;\n await analyzeScriptContent(\n block.content,\n sourceFilePath,\n pruneContext,\n compatCallers\n );\n }\n};\n\n/**\n * Applies field-renaming to a single JS/TS code string (not an SFC).\n *\n * Returns the renamed code string, or `null` if nothing changed or if\n * Babel failed to parse the input (caller should fall back to original code).\n */\nexport const renameFieldsInCode = async (\n code: string,\n sourceFilePath: string,\n pruneContext: PruneContext\n): Promise<string | null> => {\n try {\n const result = await transformAsync(code, {\n filename: sourceFilePath,\n plugins: [makeFieldRenameBabelPlugin(pruneContext)],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n });\n return result?.code ?? null;\n } catch {\n return null; // parse failure – caller falls back to original code\n }\n};\n\n/**\n * Applies field-renaming to a source file, correctly handling both plain\n * JS/TS files and SFC files (Vue / Svelte) by operating on each script block\n * individually and injecting the results back into the original source.\n *\n * Returns the renamed code string, or `null` if nothing changed.\n */\nexport const renameFieldsInSourceFile = async (\n sourceFilePath: string,\n code: string,\n pruneContext: PruneContext\n): Promise<string | null> => {\n if (pruneContext.dictionaryKeyToFieldRenameMap.size === 0) return null;\n if (!INTLAYER_USAGE_REGEX.test(code)) return null;\n\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n\n const isSFC =\n scriptBlocks.length > 0 &&\n ((scriptBlocks[0]?.contentStartOffset ?? 0) > 0 || scriptBlocks.length > 1);\n\n if (isSFC) {\n // Raw SFC: rename each script block individually and inject back.\n const modifications: Array<{\n block: (typeof scriptBlocks)[number];\n modifiedContent: string;\n }> = [];\n\n for (const block of scriptBlocks) {\n if (!INTLAYER_USAGE_REGEX.test(block.content)) continue;\n\n const renamedCode = await renameFieldsInCode(\n block.content,\n sourceFilePath,\n pruneContext\n );\n if (renamedCode && renamedCode !== block.content) {\n modifications.push({ block, modifiedContent: renamedCode });\n }\n }\n\n if (modifications.length === 0) return null;\n return injectScriptBlocks(code, modifications);\n }\n\n // Plain JS/TS or compiled SFC (no block delimiters) – rename the whole file.\n return renameFieldsInCode(code, sourceFilePath, pruneContext);\n};\n\n/**\n * Runs the intlayer optimize Babel plugin on a source file, transforming\n * `useIntlayer('key')` / `getIntlayer('key')` calls into `useDictionary(_hash)`\n * / `getDictionary(_hash)` and injecting the corresponding dictionary imports.\n *\n * Returns `{ code, map }` on success, or `null` if the transformation produced\n * no output.\n */\nexport const optimizeSourceFile = async (\n code: string,\n sourceFilePath: string,\n options: OptimizePluginOptions\n): Promise<{\n code: string;\n map: string | object | null | undefined;\n} | null> => {\n const result = await transformAsync(code, {\n filename: sourceFilePath,\n plugins: [[intlayerOptimizeBabelPlugin, options]],\n parserOpts: BABEL_PARSER_OPTIONS,\n });\n\n if (!result?.code) return null;\n\n return { code: result.code, map: result.map };\n};\n"],"mappings":"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"}
@@ -0,0 +1,18 @@
1
+ import { PruneContext } from "./pruneContext.js";
2
+ import { NodePath } from "@babel/core";
3
+ import * as BabelTypes from "@babel/types";
4
+ //#region src/analyzeContentUsage.d.ts
5
+ /**
6
+ * Analyses how the result of a single `useIntlayer('key')` / `getIntlayer('key')`
7
+ * call expression is consumed, then records the field usage into `pruneContext`.
8
+ *
9
+ * Recognised patterns:
10
+ * const { fieldA, fieldB } = useIntlayer('key') → records {fieldA, fieldB}
11
+ * useIntlayer('key').fieldA → records {fieldA}
12
+ * useIntlayer('key')['fieldA'] → records {fieldA}
13
+ * const { ...rest } = useIntlayer('key') → records 'all' (spread)
14
+ * const result = useIntlayer('key') → records 'all' (untracked binding)
15
+ */
16
+ export declare const analyzeCallExpressionUsage: (babelTypes: typeof BabelTypes, pruneContext: PruneContext, callExpressionPath: NodePath<BabelTypes.CallExpression>, dictionaryKey: string, currentSourceFilePath: string, isSfcFile: boolean) => void;
17
+ //#endregion
18
+ //# sourceMappingURL=analyzeContentUsage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyzeContentUsage.d.ts","names":[],"sources":["../../src/analyzeContentUsage.ts"],"mappings":";;;;;;;;;;;;;;;qBAqBa,6BAA0B,mBAClB,YAAU,cACf,cAAY,oBACN,SAAS,WAAW,iBAAe,uBAClC,+BACQ"}
@@ -1,4 +1,5 @@
1
- import { NestedRenameEntry, NestedRenameMap, PruneContext } from "./babel-plugin-intlayer-usage-analyzer.js";
1
+ import { NestedRenameEntry, NestedRenameMap, PruneContext } from "./pruneContext.js";
2
+ import "./babel-plugin-intlayer-usage-analyzer.js";
2
3
  import { NodePath, PluginObject } from "@babel/core";
3
4
  import * as BabelTypes from "@babel/types";
4
5
  //#region src/babel-plugin-intlayer-field-rename.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-field-rename.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-field-rename.ts"],"mappings":";;;;;;;;qBA4Ba,yBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA0CtB,kCAA+B,0BAEzC;;;;;;;;;;;;qBA2EU,6BAA0B,WAC1B,iBAAe,iCAEzB;;;;;;;YAqBS;;EAEV;;EAEA,UAAU;;;YAIA,2BAA2B,eAErC;;;;;;;;;;;;;;qBAgCW,0BAAuB,cACpB,iBACb,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;qBA4aL,8BAA2B,mBACnB,YAAU,aAChB,SAAS,WAAW,UAAQ,cAC3B;;;;;;;;;;qBAsIH,6BAA0B,cACtB,oBAAY,OAAA;EACD,cAAc;MAAe"}
1
+ {"version":3,"file":"babel-plugin-intlayer-field-rename.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-field-rename.ts"],"mappings":";;;;;;;;;qBA2Ba,yBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA0CtB,kCAA+B,0BAEzC;;;;;;;;;;;;qBA2EU,6BAA0B,WAC1B,iBAAe,iCAEzB;;;;;;;YAqBS;;EAEV;;EAEA,UAAU;;;YAIA,2BAA2B,eAErC;;;;;;;;;;;;;;qBAgCW,0BAAuB,cACpB,iBACb,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;qBA4aL,8BAA2B,mBACnB,YAAU,aAChB,SAAS,WAAW,UAAQ,cAC3B;;;;;;;;;;qBAsIH,6BAA0B,cACtB,oBAAY,OAAA;EACD,cAAc;MAAe"}
@@ -2,7 +2,6 @@ import { PluginObject, PluginPass } from "@babel/core";
2
2
  import * as BabelTypes from "@babel/types";
3
3
  import { CallerDescriptor } from "@intlayer/config/callers";
4
4
  //#region src/babel-plugin-intlayer-optimize.d.ts
5
- declare const CALLER_LIST: readonly ['useIntlayer', 'getIntlayer', 'getIntlayerAsync'];
6
5
  /**
7
6
  * Options for the optimization Babel plugin
8
7
  */
@@ -93,23 +92,18 @@ export type OptimizePluginOptions = {
93
92
  */
94
93
  compatCallers?: CallerDescriptor[];
95
94
  };
95
+ /**
96
+ * Per-file plugin state.
97
+ *
98
+ * Only the two flags that have to survive from `pre` / `Program.enter` into
99
+ * `Program.exit` live here — the caller maps and the import registry are built
100
+ * and consumed inside `exit`, so they stay local to it.
101
+ */
96
102
  type State = PluginPass & {
97
103
  opts: OptimizePluginOptions;
98
- /** map key → generated ident (per-file) for static imports */
99
- _newStaticImports?: Map<string, BabelTypes.Identifier>;
100
- /** map key → generated ident (per-file) for dynamic imports */
101
- _newDynamicImports?: Map<string, BabelTypes.Identifier>;
102
- /** whether the current file imported *any* intlayer package */
103
- _hasValidImport?: boolean;
104
- /** map from local identifier name to the imported intlayer func name ('useIntlayer' | 'getIntlayer') */
105
- _callerMap?: Map<string, (typeof CALLER_LIST)[number]>;
106
- /** map from local identifier name to the intlayer package it was imported from */
107
- _callerPackageMap?: Map<string, string>;
108
- /** map from local identifier name to the compat caller descriptor it was imported as */
109
- _compatCallerMap?: Map<string, CallerDescriptor>;
110
- /** whether the current file *is* the dictionaries entry file */
104
+ /** Whether the current file *is* a generated dictionaries entry file. */
111
105
  _isDictEntry?: boolean;
112
- /** whether the current file is included in the filesList */
106
+ /** Whether the current file is covered by the `filesList` allowlist. */
113
107
  _isIncluded?: boolean;
114
108
  };
115
109
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-optimize.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"mappings":";;;;cA8BM;;;;YAwDM;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;;;;;;;;;;;;EAeA;;;;EAIA;;;;EAIA,oBAAoB;;;;EAOpB;;;;EAIA;;;;;;;;;;;;;;EAcA,gBAAgB;;KAGb,QAAQ;EACX,MAAM;;EAEN,oBAAoB,YAAY,WAAW;;EAE3C,qBAAqB,YAAY,WAAW;;EAE5C;;EAEA,aAAa,oBAAoB;;EAEjC,oBAAoB;;EAEpB,mBAAmB,YAAY;;EAE/B;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+TW,8BAA2B;EACtC,cAAc;MACZ,aAAa"}
1
+ {"version":3,"file":"babel-plugin-intlayer-optimize.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"mappings":";;;;;;;YA8FY;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;;;;;;;;;;;;EAeA;;;;EAIA;;;;EAIA,oBAAoB;;;;EAOpB;;;;EAIA;;;;;;;;;;;;;;EAcA,gBAAgB;;;;;;;;;KAUb,QAAQ;EACX,MAAM;;EAEN;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAgTW,8BAA2B;EACtC,cAAc;MACZ,aAAa"}
@@ -1,8 +1,9 @@
1
- import { CompatCallerConfig, PruneContext } from "./babel-plugin-intlayer-usage-analyzer.js";
1
+ import { PruneContext } from "./pruneContext.js";
2
+ import { CompatCallerConfig } from "./babel-plugin-intlayer-usage-analyzer.js";
2
3
  import { PluginObject } from "@babel/core";
3
4
  import * as BabelTypes from "@babel/types";
4
- import { IntlayerConfig } from "@intlayer/types/config";
5
5
  import { NestedFieldReferences } from "@intlayer/core/dictionaryManipulator";
6
+ import { IntlayerConfig } from "@intlayer/types/config";
6
7
  //#region src/babel-plugin-intlayer-purge.d.ts
7
8
  /**
8
9
  * Pre-resolved options accepted by {@link intlayerPurgeBabelPlugin}.
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-purge.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-purge.ts"],"mappings":";;;;;;;;;;;;;YA2CY;;;;;;EAMV;;;;;EAMA;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA;;;;;EAMA;;;;;EAMA;;;;;;EAOA;;;;;;;;EASA,6BAA6B,YAAY;;;;;;EAOzC,8BAA8B;;;;;;;;;;;;EAgB9B,gBAAgB;;;;;;;EAQhB,YAAY,KAAK;;;;;;;;;;qBAwBN,wBAAqB,oBAAsB;;;;;;;;;;;;;;;;;;qBA0rB3C,2BAAwB,SAC1B,uBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmIU,2BAAwB;EACnC,cAAc;MACZ"}
1
+ {"version":3,"file":"babel-plugin-intlayer-purge.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-purge.ts"],"mappings":";;;;;;;;;;;;;;YA2CY;;;;;;EAMV;;;;;EAMA;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA;;;;;EAMA;;;;;EAMA;;;;;;EAOA;;;;;;;;EASA,6BAA6B,YAAY;;;;;;EAOzC,8BAA8B;;;;;;;;;;;;EAgB9B,gBAAgB;;;;;;;EAQhB,YAAY,KAAK;;;;;;;;;;qBAwBN,wBAAqB,oBAAsB;;;;;;;;;;;;;;;;;;qBA0rB3C,2BAAwB,SAC1B,uBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmIU,2BAAwB;EACnC,cAAc;MACZ"}
@@ -1,169 +1,10 @@
1
- import { NodePath, PluginObject } from "@babel/core";
1
+ import { DictionaryFieldUsage, NestedRenameEntry, NestedRenameMap, OpaqueFieldOccurrence, PruneContext, createPruneContext, preserveNestedDictionaryFields } from "./pruneContext.js";
2
+ import { CHAINABLE_RUNTIME_METHOD_NAMES, INTLAYER_CALLER_NAMES, IntlayerCallerName, NATIVE_CALLER_NAME_SET } from "./nativeCallers.js";
3
+ import { unwrapAwait } from "./staticAstReaders.js";
4
+ import { PluginObject } from "@babel/core";
2
5
  import * as BabelTypes from "@babel/types";
3
6
  import { CallerDescriptor, CallerDescriptor as CallerDescriptor$1, CallerResultShape, CallerValueSource } from "@intlayer/config/callers";
4
- import { NestedFieldReferences } from "@intlayer/core/dictionaryManipulator";
5
7
  //#region src/babel-plugin-intlayer-usage-analyzer.d.ts
6
- /**
7
- * Dictionary field usage result for a single dictionary key.
8
- *
9
- * 'all' → could not determine statically which fields are used;
10
- * keep every field (no pruning possible).
11
- * Set<string> → the exact top-level content field names that were accessed.
12
- */
13
- export type DictionaryFieldUsage = Set<string> | 'all';
14
- /**
15
- * One node in the nested field-rename tree.
16
- *
17
- * shortName – the compact alias assigned to this field name.
18
- * children – rename table for the next level of user-defined keys inside
19
- * this field's value (empty when the value is a leaf / primitive).
20
- */
21
- export type NestedRenameEntry = {
22
- shortName: string;
23
- children: NestedRenameMap;
24
- };
25
- /** A level of the field-rename tree, mapping original field names to entries. */
26
- export type NestedRenameMap = Map<string, NestedRenameEntry>;
27
- /**
28
- * One opaque consumption of a dictionary content value: the value at
29
- * `fieldPath` escapes static analysis (passed as-is to a child component or a
30
- * function argument), so its children must keep their original key names in
31
- * the compiled JSON.
32
- */
33
- export type OpaqueFieldOccurrence = {
34
- /**
35
- * Original (pre-rename) user-defined field names from the content root to
36
- * the escaping value, e.g. `['sections', 'hero']` for
37
- * `<Card data={content.sections.hero} />`.
38
- */
39
- fieldPath: string[];
40
- /** Source locations (`filePath:line`) where the value escapes. */
41
- locations: string[];
42
- };
43
- /**
44
- * Shared mutable state created once by the vite plugin and passed by reference
45
- * to the usage-analyzer (writer) and the prune/minify plugins (readers).
46
- *
47
- * All mutations happen during the usage-analysis `buildStart` phase; readers
48
- * only access this state during the subsequent `transform` phase.
49
- */
50
- export type PruneContext = {
51
- /**
52
- * Maps every dictionary key seen in source files to the set of top-level
53
- * content fields statically accessed, or `'all'` when the access pattern
54
- * could not be determined.
55
- */
56
- dictionaryKeyToFieldUsageMap: Map<string, DictionaryFieldUsage>;
57
- /**
58
- * Dictionary keys for which the prune/minify step must be skipped entirely
59
- * because an edge case was detected during analysis or structure recognition.
60
- */
61
- dictionariesWithEdgeCases: Set<string>;
62
- /**
63
- * True if at least one source file failed to parse during the analysis phase.
64
- * The prune plugin uses this flag conservatively: any dictionary key without
65
- * a usage entry might have been referenced by the unparsable file.
66
- */
67
- hasUnparsableSourceFiles: boolean;
68
- /**
69
- * Maps dictionary keys to the source file paths where the result of
70
- * `useIntlayer` / `getIntlayer` was assigned to a plain variable, making
71
- * static field analysis impossible.
72
- */
73
- dictionaryKeysWithUntrackedBindings: Map<string, string[]>;
74
- /**
75
- * Maps each dictionary key to a nested field-rename tree built after the
76
- * usage analysis phase (only populated when `build.minify` is active and
77
- * the field usage for that dictionary is a finite `Set<string>`).
78
- */
79
- dictionaryKeyToFieldRenameMap: Map<string, NestedRenameMap>;
80
- /**
81
- * Maps each dictionary key to the content field paths whose values are
82
- * consumed "opaquely" (passed as-is to a child component or function
83
- * argument). When an opaque value has nested user-defined structure, its
84
- * children must not be renamed.
85
- *
86
- * The inner map is keyed by the dot-joined field path for de-duplication
87
- * only; the authoritative path is {@link OpaqueFieldOccurrence.fieldPath}.
88
- *
89
- * Structure: dictionaryKey → joinedFieldPath → { fieldPath, locations }
90
- */
91
- dictionaryKeysWithOpaqueFields: Map<string, Map<string, OpaqueFieldOccurrence>>;
92
- /**
93
- * Dictionary keys for which field-key renaming must be skipped even if a
94
- * finite field-usage set was determined.
95
- *
96
- * Populated for dictionaries whose plain-variable bindings were resolved by
97
- * the framework-specific extractor (Vue / Svelte SFCs), because the Babel
98
- * rename plugin cannot update the source-code property accesses for those
99
- * indirect patterns (Vue `.value.field` / Svelte `$store.field`).
100
- *
101
- * Pruning and basic minification still apply; only field-key renaming is
102
- * suppressed.
103
- */
104
- dictionariesSkippingFieldRename: Set<string>;
105
- /**
106
- * Plain variable bindings that require a framework-specific secondary pass.
107
- *
108
- * Populated during the Babel analysis phase for `.vue` and `.svelte` source
109
- * files where direct field access is not visible to Babel scope analysis:
110
- * - Vue: `content.value.fieldName` – the `.value` ref-accessor is hidden
111
- * - Svelte: `$varName.fieldName` – the `$` prefix creates a new identifier
112
- *
113
- * Structure: filePath → [{variableName, dictionaryKey}, …]
114
- */
115
- pendingFrameworkAnalysis: Map<string, {
116
- variableName: string;
117
- dictionaryKey: string;
118
- }[]>;
119
- };
120
- export declare const createPruneContext: () => PruneContext;
121
- /**
122
- * Records `nest()` references in a prune context so nest targets stay
123
- * resolvable — and no larger than they need to be — after purge and minify.
124
- *
125
- * A nested node stores the ORIGINAL dot path of the field it reads
126
- * (`nest('common', 'period')` → `'period'`) and `getNesting` resolves it at
127
- * runtime against the compiled JSON. That drives three adjustments:
128
- *
129
- * - Nest targets never take part in field renaming, since the stored path
130
- * would no longer match the renamed keys.
131
- * - A target already consumed by a call site keeps its analysed fields plus
132
- * the nested ones, so neither consumer loses content.
133
- * - A target reached *only* through `nest()` is given a usage entry holding
134
- * exactly the nested fields. Without one, the purge pass leaves the whole
135
- * dictionary untouched; with one, it trims the dictionary down to what the
136
- * nest references actually read. This matters most for `dynamic` / `fetch`
137
- * dictionaries, whose full static snapshot would otherwise be pulled into
138
- * the eager bundle just to satisfy a single nested field.
139
- *
140
- * Seeding is skipped when a source file failed to parse: that file could
141
- * reference the dictionary in a way the analysis never saw, which is the same
142
- * guard the purge pass applies to keys with no usage entry.
143
- *
144
- * @param pruneContext - Shared analysis state to update in place.
145
- * @param nestedDictionaryReferences - Nest-target key → referenced top-level
146
- * fields, as returned by `getNestedDictionaryReferences`.
147
- */
148
- export declare const preserveNestedDictionaryFields: (pruneContext: PruneContext, nestedDictionaryReferences: Map<string, NestedFieldReferences>) => void;
149
- /**
150
- * Methods the runtime attaches to a resolved content object rather than fields
151
- * declared in a `.content` file.
152
- *
153
- * `vanilla-intlayer`'s `useIntlayer` / `useDictionary` assign `onChange` onto
154
- * the content they return, so `useIntlayer('app').onChange(cb)` is a
155
- * subscription — not a read of a field named `onChange`. Without this list the
156
- * analyser records `onChange` as the only consumed field and the purge pass
157
- * strips every real field from the compiled dictionary.
158
- *
159
- * The analyser looks *through* these calls: the callback parameter is analysed
160
- * as a fresh content root, and the call result is analysed again because the
161
- * helpers return the content object for chaining.
162
- */
163
- export declare const CHAINABLE_RUNTIME_METHOD_NAMES: Set<string>;
164
- /** Canonical intlayer caller names that trigger usage analysis. */
165
- export declare const INTLAYER_CALLER_NAMES: readonly ['useIntlayer', 'getIntlayer', 'getIntlayerAsync'];
166
- export type IntlayerCallerName = (typeof INTLAYER_CALLER_NAMES)[number];
167
8
  /**
168
9
  * Configuration entry for a single compat namespace caller.
169
10
  *
@@ -172,42 +13,34 @@ export type IntlayerCallerName = (typeof INTLAYER_CALLER_NAMES)[number];
172
13
  */
173
14
  export type CompatCallerConfig = CallerDescriptor$1;
174
15
  /**
175
- * Default registry of compat namespace callers.
176
- *
177
- * Intentionally empty — compat-specific caller configurations belong in their
178
- * respective adapter packages (e.g. `@intlayer/react-i18next/plugin`,
179
- * `@intlayer/vue-i18n/plugin`) and are injected into `makeUsageAnalyzerBabelPlugin`
180
- * via the `compatCallers` option. Centralising them here would couple the
181
- * core `@intlayer/babel` package to every compat adapter, which violates the
182
- * design principle that compat logic lives in compat packages.
183
- */
184
- export declare const DEFAULT_COMPAT_CALLERS: CompatCallerConfig[];
185
- /**
186
- * Climbs past an enclosing `await` expression so that
187
- * `const t = await getTranslations('ns')` — or `await getIntlayerAsync('key')`
188
- * — is resolved to its variable declarator the same way the synchronous form
189
- * is.
16
+ * @deprecated Always empty. Compat callers are injected per build through
17
+ * `options.compatCallers`; there is no default registry to fall back to.
190
18
  */
191
- export declare const unwrapAwait: (babelTypes: typeof BabelTypes, path: NodePath<BabelTypes.Node>) => NodePath<BabelTypes.Node>;
19
+ export declare const DEFAULT_COMPAT_CALLERS: CallerDescriptor$1[];
192
20
  /**
193
21
  * Creates a Babel plugin that traverses source files and records which
194
- * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site —
195
- * and each configured compat namespace caller — accesses. Results are
196
- * accumulated into `pruneContext`.
22
+ * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site
23
+ * accesses. Results are accumulated into `pruneContext`.
24
+ *
25
+ * Compat-adapter callers (`useTranslation`, `useTranslations`, `formatMessage`,
26
+ * …) are *not* known to this plugin. Each compat package's bundler plugin
27
+ * injects its own descriptors through `options.compatCallers`, and the whole
28
+ * compat analysis then runs behind {@link createCompatUsageAnalyzer}. With no
29
+ * descriptors injected — the default — none of that code is reached, so a
30
+ * plain intlayer build behaves exactly as if the adapters did not exist.
197
31
  *
198
32
  * This plugin is analysis-only: it does not transform the code (`code: false`
199
33
  * should be passed to `transformAsync` when using it).
200
34
  *
201
35
  * @param pruneContext - Shared mutable state written by this plugin.
202
- * @param options - Optional overrides. `compatCallers` defaults to
203
- * {@link DEFAULT_COMPAT_CALLERS}; pass `[]` to disable
204
- * compat-adapter analysis entirely.
36
+ * @param options - Optional overrides. `compatCallers` defaults to an
37
+ * empty registry, disabling compat-adapter analysis.
205
38
  */
206
39
  export declare const makeUsageAnalyzerBabelPlugin: (pruneContext: PruneContext, options?: {
207
- compatCallers?: CompatCallerConfig[];
40
+ compatCallers?: readonly CallerDescriptor$1[];
208
41
  }) => ({ types: babelTypes }: {
209
42
  types: typeof BabelTypes;
210
43
  }) => PluginObject;
211
44
  //#endregion
212
- export type { CallerDescriptor, CallerResultShape, CallerValueSource };
45
+ export { CHAINABLE_RUNTIME_METHOD_NAMES, type CallerDescriptor, type CallerResultShape, type CallerValueSource, type DictionaryFieldUsage, INTLAYER_CALLER_NAMES, type IntlayerCallerName, NATIVE_CALLER_NAME_SET, type NestedRenameEntry, type NestedRenameMap, type OpaqueFieldOccurrence, type PruneContext, createPruneContext, preserveNestedDictionaryFields, unwrapAwait };
213
46
  //# sourceMappingURL=babel-plugin-intlayer-usage-analyzer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-usage-analyzer.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-usage-analyzer.ts"],"mappings":";;;;;;;;;;;;YAiBY,uBAAuB;;;;;;;;YASvB;EACV;EACA,UAAU;;;YAIA,kBAAkB,YAAY;;;;;;;YAQ9B;;;;;;EAMV;;EAGA;;;;;;;;;YAUU;;;;;;EAMV,8BAA8B,YAAY;;;;;EAM1C,2BAA2B;;;;;;EAO3B;;;;;;EAOA,qCAAqC;;;;;;EAOrC,+BAA+B,YAAY;;;;;;;;;;;;EAa3C,gCAAgC,YAE9B,YAAY;;;;;;;;;;;;;EAed,iCAAiC;;;;;;;;;;;EAYjC,0BAA0B;IAEtB;IAAsB;;;qBAIf,0BAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAyCzB,iCAA8B,cAC3B,cAAY,4BACE,YAAY;;;;;;;;;;;;;;;qBAqD7B,gCAA8B;;qBAG9B;YAKD,6BAA6B;;;;;;;YAmB7B,qBAAqB;;;;;;;;;;;qBAYpB,wBAAwB;;;;;;;qBAWxB,cAAW,mBACH,YAAU,MACvB,SAAS,WAAW,UACzB,SAAS,WAAW;;;;;;;;;;;;;;;qBA8rCV,+BAA4B,cAEvB,cAAY;EACd,gBAAgB;SAAsB,OAAA;EAE1B,cAAc;MAAe"}
1
+ {"version":3,"file":"babel-plugin-intlayer-usage-analyzer.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-usage-analyzer.ts"],"mappings":";;;;;;;;;;;;;YAuCY,qBAAqB;;;;;qBAMpB,wBAAwB;;;;;;;;;;;;;;;;;;;;qBAqBxB,+BAA4B,cAEvB,cAAY;EACd,yBAAyB;SAAoB,OAAA;EAEjC,cAAc;MAAe"}
@@ -0,0 +1,66 @@
1
+ import { StaticOrAbsent } from "../staticAstReaders.js";
2
+ import * as BabelTypes from "@babel/types";
3
+ import { CallerDescriptor, CallerValueSource } from "@intlayer/config/callers";
4
+ //#region src/compat/namespaceResolution.d.ts
5
+ /**
6
+ * Resolution of a compat caller's namespace from its
7
+ * {@link CallerValueSource} list.
8
+ *
9
+ * Two flavours coexist on purpose, because the two passes ask different
10
+ * questions of the same descriptor:
11
+ *
12
+ * - {@link resolveNamespaceForAnalysis} answers *which dictionary does this
13
+ * call read* — used by the usage analyser, which only needs to attribute a
14
+ * call to a dictionary and may fall back to the caller's default namespace.
15
+ * - {@link resolveNamespaceForRewrite} answers *can this call be rewritten,
16
+ * and where do I edit it* — used by the optimize pass, which needs an exact
17
+ * static namespace plus a handle on the node it must replace. It has no
18
+ * default-namespace fallback: rewriting a call whose namespace is only
19
+ * implied would bind the wrong dictionary.
20
+ */
21
+ /** Namespace used by compat callers when no namespace argument is given. */
22
+ export declare const DEFAULT_COMPAT_NAMESPACE = "translation";
23
+ /**
24
+ * Resolves the namespace from a list of `CallerValueSource`s, tried in
25
+ * declaration order. The first source yielding a static string wins.
26
+ * Returns {@link ABSENT_VALUE} when every source reports an absent value, and
27
+ * `undefined` when the namespace is present somewhere but dynamic.
28
+ */
29
+ export declare const resolveNamespaceForAnalysis: (babelTypes: typeof BabelTypes, callArguments: BabelTypes.CallExpression['arguments'], sources: CallerValueSource[]) => StaticOrAbsent<string>;
30
+ /**
31
+ * Resolves an optional `keyPrefix` for a compat caller. Returns the static
32
+ * prefix string, `null` when no prefix is configured/present, or `undefined`
33
+ * when a prefix is present but dynamic.
34
+ */
35
+ export declare const resolveKeyPrefixForAnalysis: (babelTypes: typeof BabelTypes, callArguments: BabelTypes.CallExpression['arguments'], sources: CallerValueSource[] | undefined) => string | null | undefined;
36
+ /**
37
+ * Result of statically resolving the namespace of a compat caller call-site
38
+ * for rewriting, carrying the handles the optimize pass mutates.
39
+ */
40
+ export type RewritableNamespaceMatch = {
41
+ /** The full namespace string, e.g. `'about.counter'`. */
42
+ fullNamespace: string;
43
+ /** Index of the positional namespace argument, when read from an argument. */
44
+ argumentIndex?: number;
45
+ /**
46
+ * The options-object property holding the namespace, when read from an
47
+ * option. The rewrite mutates it in place (key-prefix remainder) or removes
48
+ * it from `optionsObject`.
49
+ */
50
+ optionProperty?: BabelTypes.ObjectProperty;
51
+ /** The options object owning `optionProperty`. */
52
+ optionsObject?: BabelTypes.ObjectExpression;
53
+ };
54
+ /**
55
+ * Statically resolves the namespace of a compat caller call-site for the
56
+ * optimize pass. Only the `argument` / `option` / `fixed` sources qualify: the
57
+ * per-message-id `path-first-segment` form cannot bind one dictionary to the
58
+ * call site and is skipped.
59
+ *
60
+ * Returns `undefined` when the namespace is absent or dynamic, in which case
61
+ * the call is left untouched and resolves through the runtime dictionary
62
+ * registry.
63
+ */
64
+ export declare const resolveNamespaceForRewrite: (babelTypes: typeof BabelTypes, callArguments: BabelTypes.CallExpression['arguments'], descriptor: CallerDescriptor) => RewritableNamespaceMatch | undefined;
65
+ //#endregion
66
+ //# sourceMappingURL=namespaceResolution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespaceResolution.d.ts","names":[],"sources":["../../../src/compat/namespaceResolution.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAiCa;;;;;;;qBAoEA,8BAA2B,mBACnB,YAAU,eACd,WAAW,6BAA2B,SAC5C,wBACR;;;;;;qBAuBU,8BAA2B,mBACnB,YAAU,eACd,WAAW,6BAA2B,SAC5C;;;;;YAiBC;;EAEV;;EAEA;;;;;;EAMA,iBAAiB,WAAW;;EAE5B,gBAAgB,WAAW;;;;;;;;;;;;qBAahB,6BAA0B,mBAClB,YAAU,eACd,WAAW,6BAA2B,YACzC,qBACX"}