@intlayer/babel 5.5.2 → 5.5.3

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.
@@ -28,163 +28,127 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var babel_plugin_intlayer_exports = {};
30
30
  __export(babel_plugin_intlayer_exports, {
31
- babelPluginIntlayer: () => babelPluginIntlayer
31
+ intlayerBabelPlugin: () => intlayerBabelPlugin
32
32
  });
33
33
  module.exports = __toCommonJS(babel_plugin_intlayer_exports);
34
- var import_parser = require("@babel/parser");
35
34
  var t = __toESM(require("@babel/types"));
36
35
  var import_chokidar = require("@intlayer/chokidar");
37
- var import_config = require("@intlayer/config");
38
- var import_path = require("path");
36
+ var import_node_path = require("node:path");
39
37
  const PACKAGE_LIST = [
38
+ "intlayer",
39
+ "@intlayer/core",
40
40
  "react-intlayer",
41
41
  "react-intlayer/client",
42
42
  "react-intlayer/server",
43
43
  "next-intlayer",
44
- "next-intlayer/server",
45
44
  "next-intlayer/client",
45
+ "next-intlayer/server",
46
46
  "svelte-intlayer",
47
47
  "vue-intlayer",
48
48
  "angular-intlayer",
49
49
  "preact-intlayer",
50
- "solid-inltayer"
50
+ "solid-intlayer"
51
51
  ];
52
52
  const CALLER_LIST = ["useIntlayer", "getIntlayer"];
53
- const globalUsedKeys = /* @__PURE__ */ new Set();
54
- let isThreeShakable = true;
55
- const isFileInContentDir = (filePath, contentDirs) => {
56
- return contentDirs.some((dir) => {
57
- const normalizedDir = dir.replace(/[/\\]+$/, "");
58
- return filePath.startsWith(normalizedDir);
59
- });
53
+ const makeIdent = (key) => {
54
+ const hash = (0, import_chokidar.getFileHash)(key);
55
+ return t.identifier(`_${hash}`);
60
56
  };
61
- const isValidIntlayerImport = (source) => {
62
- return PACKAGE_LIST.includes(source);
57
+ const computeRelativeImport = (fromFile, dictDir, key) => {
58
+ const jsonPath = (0, import_node_path.join)(dictDir, `${key}.json`);
59
+ let rel = (0, import_node_path.relative)((0, import_node_path.dirname)(fromFile), jsonPath).replace(/\\/g, "/");
60
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = `./${rel}`;
61
+ return rel;
63
62
  };
64
- const babelPluginIntlayer = () => {
65
- const configuration = (0, import_config.getConfiguration)();
66
- const dictionariesRoot = configuration.content.mainDir.replace(
67
- /[/\\]+$/,
68
- ""
69
- );
70
- const contentDir = configuration.content.contentDir;
71
- const appLogger = (0, import_config.getAppLogger)(configuration);
63
+ const intlayerBabelPlugin = () => {
72
64
  return {
73
- name: "babel-plugin-intlayer-prune",
65
+ name: "babel-plugin-intlayer-transform",
66
+ pre() {
67
+ this._newImports = /* @__PURE__ */ new Map();
68
+ this._hasValidImport = false;
69
+ this._isDictEntry = false;
70
+ },
74
71
  visitor: {
72
+ /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */
75
73
  Program: {
76
- enter(_programPath, state) {
77
- state.importedPackages = /* @__PURE__ */ new Set();
78
- state.hasValidIntlayerImport = false;
79
- const filePath = state.file.opts.filename ?? "";
80
- if (!isFileInContentDir(filePath, contentDir)) {
81
- return;
74
+ enter(programPath, state) {
75
+ const filename = state.file.opts.filename;
76
+ if (filename === state.opts.dictionariesEntryPath) {
77
+ state._isDictEntry = true;
78
+ programPath.node.body = [
79
+ t.exportDefaultDeclaration(t.objectExpression([]))
80
+ ];
81
+ programPath.stop();
82
82
  }
83
83
  },
84
- /*
85
- * After the whole file has been walked, decide if THIS file is the
86
- * dictionary entry-point. If it is, swap its body for the generated
87
- * code that imports only the used dictionaries.
88
- */
84
+ /* 3. After full traversal, inject the JSON dictionary imports. */
89
85
  exit(programPath, state) {
90
- const filePath = state.file.opts.filename ?? "";
91
- if (!isFileInContentDir(filePath, contentDir)) return;
92
- if (!isThreeShakable) return;
93
- if (!filePath.startsWith(dictionariesRoot)) return;
94
- const keys = Array.from(globalUsedKeys);
95
- if (!keys.length) return;
96
- const extension = (0, import_path.extname)(filePath);
97
- const format = extension === ".cjs" ? "cjs" : "esm";
98
- const dictionaries = (0, import_chokidar.getBuiltDictionariesPath)(configuration).filter(
99
- (p) => keys.some((k) => p.endsWith(`${import_path.sep}${k}.json`))
100
- );
101
- const generatedSrc = (0, import_chokidar.generateDictionaryListContent)(
102
- dictionaries,
103
- format,
104
- configuration
105
- );
106
- if (!generatedSrc) return;
107
- const newAst = (0, import_parser.parse)(generatedSrc, {
108
- sourceType: format === "cjs" ? "script" : "module",
109
- plugins: ["importMeta"]
110
- });
111
- appLogger("Unused dictionaries pruned to reduce bundle size", {
112
- level: "info"
113
- });
114
- programPath.node.body = [];
115
- programPath.pushContainer("body", newAst.program.body);
116
- state.file.metadata = {
117
- ...state.file.metadata,
118
- intlayerPruned: true
119
- };
86
+ if (state._isDictEntry) return;
87
+ if (!state._hasValidImport) return;
88
+ const file = state.file.opts.filename;
89
+ const dictDir = state.opts.dictionariesDir;
90
+ const imports = [];
91
+ for (const [key, ident] of state._newImports) {
92
+ const rel = computeRelativeImport(file, dictDir, key);
93
+ imports.push(
94
+ t.importDeclaration(
95
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
96
+ t.stringLiteral(rel)
97
+ )
98
+ );
99
+ }
100
+ if (!imports.length) return;
101
+ const bodyPaths = programPath.get("body");
102
+ let insertPos = 0;
103
+ for (const stmtPath of bodyPaths) {
104
+ const stmt = stmtPath.node;
105
+ if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && (stmt.expression.value === "use client" || stmt.expression.value === "use server")) {
106
+ insertPos += 1;
107
+ } else {
108
+ break;
109
+ }
110
+ }
111
+ programPath.node.body.splice(insertPos, 0, ...imports);
120
112
  }
121
113
  },
114
+ /* 1. Inspect *every* intlayer import. */
122
115
  ImportDeclaration(path, state) {
123
- const filePath = state.file.opts.filename ?? "";
124
- if (!isFileInContentDir(filePath, contentDir)) {
125
- return;
126
- }
127
- const source = path.node.source.value;
128
- state.importedPackages?.add(source);
129
- if (isValidIntlayerImport(source)) {
130
- const hasIntlayerFunction = path.node.specifiers.some((specifier) => {
131
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {
132
- return CALLER_LIST.includes(specifier.imported.name);
133
- }
134
- return false;
135
- });
136
- if (hasIntlayerFunction) {
137
- state.hasValidIntlayerImport = true;
116
+ if (state._isDictEntry) return;
117
+ const src = path.node.source.value;
118
+ if (!PACKAGE_LIST.includes(src)) return;
119
+ state._hasValidImport = true;
120
+ for (const spec of path.node.specifiers) {
121
+ if (!t.isImportSpecifier(spec)) continue;
122
+ const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
123
+ if (importedName === "useIntlayer") {
124
+ spec.imported = t.identifier("useDictionary");
125
+ } else if (importedName === "getIntlayer") {
126
+ spec.imported = t.identifier("getDictionary");
138
127
  }
139
128
  }
140
129
  },
130
+ /* 2. Replace calls: useIntlayer("foo") → useDictionary(_hash) */
141
131
  CallExpression(path, state) {
142
- const filePath = state.file.opts.filename ?? "";
143
- if (!isFileInContentDir(filePath, contentDir)) return;
144
- if (!isThreeShakable) return;
145
- const { node } = path;
146
- const renderError = (message) => {
147
- const filePath2 = state.file.opts.filename ?? "";
148
- const codeFrame = path.buildCodeFrameError("").message;
149
- console.info("");
150
- appLogger(message, {
151
- level: "error"
152
- });
153
- appLogger(`At ${(0, import_path.relative)(process.cwd(), filePath2)}`, {
154
- level: "error"
155
- });
156
- appLogger(codeFrame.split("\n").slice(1).join("\n"), {
157
- level: "error"
158
- });
159
- };
160
- if (t.isIdentifier(node.callee) && CALLER_LIST.includes(node.callee.name)) {
161
- if (!state.hasValidIntlayerImport) {
162
- isThreeShakable = false;
163
- renderError(
164
- `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(", ")}`
165
- );
166
- return;
167
- }
168
- if (!node.arguments.length) {
169
- isThreeShakable = false;
170
- renderError(`${node.callee.name} requires at least one argument`);
171
- return;
172
- }
173
- if (!t.isStringLiteral(node.arguments[0])) {
174
- isThreeShakable = false;
175
- renderError(
176
- `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`
177
- );
178
- return;
179
- }
180
- globalUsedKeys.add(node.arguments[0].value);
132
+ if (state._isDictEntry) return;
133
+ const callee = path.node.callee;
134
+ if (!t.isIdentifier(callee)) return;
135
+ if (!CALLER_LIST.includes(callee.name)) return;
136
+ state._hasValidImport = true;
137
+ const arg = path.node.arguments[0];
138
+ if (!arg || !t.isStringLiteral(arg)) return;
139
+ const key = arg.value;
140
+ let ident = state._newImports.get(key);
141
+ if (!ident) {
142
+ ident = makeIdent(key);
143
+ state._newImports.set(key, ident);
181
144
  }
145
+ path.node.arguments[0] = t.identifier(ident.name);
182
146
  }
183
147
  }
184
148
  };
185
149
  };
186
150
  // Annotate the CommonJS export names for ESM import in node:
187
151
  0 && (module.exports = {
188
- babelPluginIntlayer
152
+ intlayerBabelPlugin
189
153
  });
190
154
  //# sourceMappingURL=babel-plugin-intlayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n generateDictionaryListContent,\n getBuiltDictionariesPath,\n} from '@intlayer/chokidar';\nimport { getAppLogger, getConfiguration } from '@intlayer/config';\nimport { extname, relative, sep } from 'path';\n\ntype PluginState = PluginPass & {\n opts: {\n enableTransform?: boolean;\n };\n // Add tracking for imports per file\n importedPackages?: Set<string>;\n hasValidIntlayerImport?: boolean;\n};\n\n// ────────────────────────────────────────────────────────────\n// shared state across ALL files (1 build = 1 Node process)\nconst PACKAGE_LIST = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/server',\n 'next-intlayer/client',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-inltayer',\n];\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'];\nconst globalUsedKeys = new Set<string>();\nlet isThreeShakable = true;\n// ────────────────────────────────────────────────────────────\n\n// Helper function to check if file is in contentDir\nconst isFileInContentDir = (\n filePath: string,\n contentDirs: string[]\n): boolean => {\n return contentDirs.some((dir) => {\n const normalizedDir = dir.replace(/[/\\\\]+$/, '');\n return filePath.startsWith(normalizedDir);\n });\n};\n\n// Helper function to check if import is from valid package\nconst isValidIntlayerImport = (source: string): boolean => {\n return PACKAGE_LIST.includes(source);\n};\n\nexport const babelPluginIntlayer = (): PluginObj<PluginState> => {\n const configuration = getConfiguration();\n const dictionariesRoot: string = configuration.content.mainDir.replace(\n /[/\\\\]+$/,\n ''\n );\n const contentDir: string[] = configuration.content.contentDir;\n const appLogger = getAppLogger(configuration);\n\n return {\n name: 'babel-plugin-intlayer-prune',\n\n visitor: {\n Program: {\n enter(_programPath, state: PluginState) {\n // Initialize per-file state\n state.importedPackages = new Set<string>();\n state.hasValidIntlayerImport = false;\n\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n },\n\n /*\n * After the whole file has been walked, decide if THIS file is the\n * dictionary entry-point. If it is, swap its body for the generated\n * code that imports only the used dictionaries.\n */\n exit(programPath, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n\n // Skip files is bundle is not three-shakable\n if (!isThreeShakable) return;\n\n // Is this *the* entry-point we want to shrink?\n if (!filePath.startsWith(dictionariesRoot)) return;\n\n const keys = Array.from(globalUsedKeys);\n if (!keys.length) return; // nothing collected yet – leave the file untouched\n\n const extension = extname(filePath); // .js / .mjs / .cjs\n const format = extension === '.cjs' ? 'cjs' : 'esm';\n\n // Pick only the dictionaries whose basename matches a collected key\n const dictionaries = getBuiltDictionariesPath(configuration).filter(\n (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))\n );\n\n const generatedSrc = generateDictionaryListContent(\n dictionaries,\n format,\n configuration\n );\n if (!generatedSrc) return;\n\n // Replace the current AST with the new one\n const newAst = parse(generatedSrc, {\n sourceType: format === 'cjs' ? 'script' : 'module',\n plugins: ['importMeta'],\n });\n\n appLogger('Unused dictionaries pruned to reduce bundle size', {\n level: 'info',\n });\n\n // Clear and inject\n programPath.node.body = [];\n programPath.pushContainer('body', newAst.program.body);\n\n // Optional: mark the file as \"transformed\" for other tooling\n state.file.metadata = {\n ...state.file.metadata,\n intlayerPruned: true,\n };\n },\n },\n\n ImportDeclaration(\n path: NodePath<t.ImportDeclaration>,\n state: PluginState\n ) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n\n const source = path.node.source.value;\n state.importedPackages?.add(source);\n\n // Check if this import is from a valid intlayer package\n if (isValidIntlayerImport(source)) {\n // Check if any of the imported specifiers include useIntlayer or getIntlayer\n const hasIntlayerFunction = path.node.specifiers.some((specifier) => {\n if (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported)\n ) {\n return CALLER_LIST.includes(specifier.imported.name);\n }\n return false;\n });\n\n if (hasIntlayerFunction) {\n state.hasValidIntlayerImport = true;\n }\n }\n },\n\n CallExpression(path: NodePath<t.CallExpression>, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n if (!isThreeShakable) return;\n\n const { node } = path;\n\n const renderError = (message: string) => {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Generate code frame to show the error context\n const codeFrame = path.buildCodeFrameError('').message;\n\n console.info(''); // For formating\n appLogger(message, {\n level: 'error',\n });\n appLogger(`At ${relative(process.cwd(), filePath)}`, {\n level: 'error',\n });\n appLogger(codeFrame.split('\\n').slice(1).join('\\n'), {\n level: 'error',\n });\n };\n\n if (\n t.isIdentifier(node.callee) &&\n CALLER_LIST.includes(node.callee.name)\n ) {\n // Check if the function is imported from a valid package\n if (!state.hasValidIntlayerImport) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(', ')}`\n );\n return;\n }\n\n // Check if arguments exist\n if (!node.arguments.length) {\n isThreeShakable = false;\n\n renderError(`${node.callee.name} requires at least one argument`);\n\n return;\n }\n\n // Check if the first argument is a string literal\n if (!t.isStringLiteral(node.arguments[0])) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`\n );\n return;\n }\n\n globalUsedKeys.add(node.arguments[0].value);\n }\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAsB;AAEtB,QAAmB;AACnB,sBAGO;AACP,oBAA+C;AAC/C,kBAAuC;AAavC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,cAAc,CAAC,eAAe,aAAa;AACjD,MAAM,iBAAiB,oBAAI,IAAY;AACvC,IAAI,kBAAkB;AAItB,MAAM,qBAAqB,CACzB,UACA,gBACY;AACZ,SAAO,YAAY,KAAK,CAAC,QAAQ;AAC/B,UAAM,gBAAgB,IAAI,QAAQ,WAAW,EAAE;AAC/C,WAAO,SAAS,WAAW,aAAa;AAAA,EAC1C,CAAC;AACH;AAGA,MAAM,wBAAwB,CAAC,WAA4B;AACzD,SAAO,aAAa,SAAS,MAAM;AACrC;AAEO,MAAM,sBAAsB,MAA8B;AAC/D,QAAM,oBAAgB,gCAAiB;AACvC,QAAM,mBAA2B,cAAc,QAAQ,QAAQ;AAAA,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;AAEA,YACE,EAAE,aAAa,KAAK,MAAM,KAC1B,YAAY,SAAS,KAAK,OAAO,IAAI,GACrC;AAEA,cAAI,CAAC,MAAM,wBAAwB;AACjC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI,iDAAiD,aAAa,KAAK,IAAI,CAAC;AAAA,YAClI;AACA;AAAA,UACF;AAGA,cAAI,CAAC,KAAK,UAAU,QAAQ;AAC1B,8BAAkB;AAElB,wBAAY,GAAG,KAAK,OAAO,IAAI,iCAAiC;AAEhE;AAAA,UACF;AAGA,cAAI,CAAC,EAAE,gBAAgB,KAAK,UAAU,CAAC,CAAC,GAAG;AACzC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI;AAAA,YAC1D;AACA;AAAA,UACF;AAEA,yBAAe,IAAI,KAAK,UAAU,CAAC,EAAE,KAAK;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["filePath"]}
1
+ {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport * as t from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar';\nimport { dirname, join, relative } from 'node:path';\n\n/* ────────────────────────────────────────── constants ───────────────────── */\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: { dictionariesDir: string; dictionariesEntryPath: string };\n /** map key → generated ident (per-file) */\n _newImports?: Map<string, t.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (key: string): t.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeRelativeImport = (\n fromFile: string,\n dictDir: string,\n key: string\n): string => {\n const jsonPath = join(dictDir, `${key}.json`);\n let rel = relative(dirname(fromFile), jsonPath).replace(/\\\\/g, '/'); // win →\n if (!rel.startsWith('./') && !rel.startsWith('../')) rel = `./${rel}`;\n return rel;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Babel plugin that transforms `useIntlayer/getIntlayer` calls into\n * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.\n *\n * **New behaviour**: if the currently processed file matches `dictionariesEntryPath`,\n * its entire contents are replaced with a simple `export default {}` so that it\n * never contains stale or circular references.\n *\n * The **critical detail** (bug-fix) is that we still **only rewrite** an import\n * specifier when its *imported* name is `useIntlayer`/`getIntlayer`.\n *\n * This means cases like:\n * ```ts\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * ```\n * —where `useIntlayer` is merely an *alias* or re-export—are left untouched\n * because `imported.name` is `useDictionary`.\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newImports = new Map();\n this._hasValidImport = false;\n this._isDictEntry = false;\n },\n\n visitor: {\n /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n const filename = state.file.opts.filename!;\n if (filename === state.opts.dictionariesEntryPath) {\n state._isDictEntry = true;\n // Replace all existing statements with: export default {}\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n ];\n // Stop further traversal for this plugin – nothing else to transform\n programPath.stop();\n }\n },\n\n /* 3. After full traversal, inject the JSON dictionary imports. */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n if (!state._hasValidImport) return; // early-out if we touched nothing\n\n const file = state.file.opts.filename!;\n const dictDir = state.opts.dictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n for (const [key, ident] of state._newImports!) {\n const rel = computeRelativeImport(file, dictDir, key);\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get('body') as NodePath<t.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n (stmt.expression.value === 'use client' ||\n stmt.expression.value === 'use server')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, ...imports);\n },\n },\n\n /* 1. Inspect *every* intlayer import. */\n ImportDeclaration(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const src = path.node.source.value;\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file; this is\n // enough to know that we *might* need to inject runtime helpers later.\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n // ⚠️ We now key off *imported* name, *not* local name.\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as t.StringLiteral).value;\n\n if (importedName === 'useIntlayer') {\n spec.imported = t.identifier('useDictionary');\n } else if (importedName === 'getIntlayer') {\n spec.imported = t.identifier('getDictionary');\n }\n }\n },\n\n /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) */\n CallExpression(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n if (!CALLER_LIST.includes(callee.name as any)) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn’t import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n if (!arg || !t.isStringLiteral(arg)) return; // must be literal\n\n const key = arg.value;\n // per-file cache\n let ident = state._newImports!.get(key);\n if (!ident) {\n ident = makeIdent(key);\n state._newImports!.set(key, ident);\n }\n\n // replace first arg with ident\n path.node.arguments[0] = t.identifier(ident.name);\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,QAAmB;AACnB,sBAA4B;AAC5B,uBAAwC;AAIxC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,cAAc,CAAC,eAAe,aAAa;AAqBjD,MAAM,YAAY,CAAC,QAA8B;AAC/C,QAAM,WAAO,6BAAY,GAAG;AAC5B,SAAO,EAAE,WAAW,IAAI,IAAI,EAAE;AAChC;AAEA,MAAM,wBAAwB,CAC5B,UACA,SACA,QACW;AACX,QAAM,eAAW,uBAAK,SAAS,GAAG,GAAG,OAAO;AAC5C,MAAI,UAAM,+BAAS,0BAAQ,QAAQ,GAAG,QAAQ,EAAE,QAAQ,OAAO,GAAG;AAClE,MAAI,CAAC,IAAI,WAAW,IAAI,KAAK,CAAC,IAAI,WAAW,KAAK,EAAG,OAAM,KAAK,GAAG;AACnE,SAAO;AACT;AAsBO,MAAM,sBAAsB,MAAwB;AACzD,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MAAM;AACJ,WAAK,cAAc,oBAAI,IAAI;AAC3B,WAAK,kBAAkB;AACvB,WAAK,eAAe;AAAA,IACtB;AAAA,IAEA,SAAS;AAAA;AAAA,MAEP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AAC,aAAa,SAAS,GAAG,EAAG;AAIjC,cAAM,kBAAkB;AAExB,mBAAW,QAAQ,KAAK,KAAK,YAAY;AACvC,cAAI,CAAC,EAAE,kBAAkB,IAAI,EAAG;AAGhC,gBAAM,eAAe,EAAE,aAAa,KAAK,QAAQ,IAC7C,KAAK,SAAS,OACb,KAAK,SAA6B;AAEvC,cAAI,iBAAiB,eAAe;AAClC,iBAAK,WAAW,EAAE,WAAW,eAAe;AAAA,UAC9C,WAAW,iBAAiB,eAAe;AACzC,iBAAK,WAAW,EAAE,WAAW,eAAe;AAAA,UAC9C;AAAA,QACF;AAAA,MACF;AAAA;AAAA,MAGA,eAAe,MAAM,OAAO;AAC1B,YAAI,MAAM,aAAc;AAExB,cAAM,SAAS,KAAK,KAAK;AACzB,YAAI,CAAC,EAAE,aAAa,MAAM,EAAG;AAC7B,YAAI,CAAC,YAAY,SAAS,OAAO,IAAW,EAAG;AAK/C,cAAM,kBAAkB;AAExB,cAAM,MAAM,KAAK,KAAK,UAAU,CAAC;AACjC,YAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,EAAG;AAErC,cAAM,MAAM,IAAI;AAEhB,YAAI,QAAQ,MAAM,YAAa,IAAI,GAAG;AACtC,YAAI,CAAC,OAAO;AACV,kBAAQ,UAAU,GAAG;AACrB,gBAAM,YAAa,IAAI,KAAK,KAAK;AAAA,QACnC;AAGA,aAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,159 +1,120 @@
1
- import { parse } from "@babel/parser";
2
1
  import * as t from "@babel/types";
3
- import {
4
- generateDictionaryListContent,
5
- getBuiltDictionariesPath
6
- } from "@intlayer/chokidar";
7
- import { getAppLogger, getConfiguration } from "@intlayer/config";
8
- import { extname, relative, sep } from "path";
2
+ import { getFileHash } from "@intlayer/chokidar";
3
+ import { dirname, join, relative } from "node:path";
9
4
  const PACKAGE_LIST = [
5
+ "intlayer",
6
+ "@intlayer/core",
10
7
  "react-intlayer",
11
8
  "react-intlayer/client",
12
9
  "react-intlayer/server",
13
10
  "next-intlayer",
14
- "next-intlayer/server",
15
11
  "next-intlayer/client",
12
+ "next-intlayer/server",
16
13
  "svelte-intlayer",
17
14
  "vue-intlayer",
18
15
  "angular-intlayer",
19
16
  "preact-intlayer",
20
- "solid-inltayer"
17
+ "solid-intlayer"
21
18
  ];
22
19
  const CALLER_LIST = ["useIntlayer", "getIntlayer"];
23
- const globalUsedKeys = /* @__PURE__ */ new Set();
24
- let isThreeShakable = true;
25
- const isFileInContentDir = (filePath, contentDirs) => {
26
- return contentDirs.some((dir) => {
27
- const normalizedDir = dir.replace(/[/\\]+$/, "");
28
- return filePath.startsWith(normalizedDir);
29
- });
20
+ const makeIdent = (key) => {
21
+ const hash = getFileHash(key);
22
+ return t.identifier(`_${hash}`);
30
23
  };
31
- const isValidIntlayerImport = (source) => {
32
- return PACKAGE_LIST.includes(source);
24
+ const computeRelativeImport = (fromFile, dictDir, key) => {
25
+ const jsonPath = join(dictDir, `${key}.json`);
26
+ let rel = relative(dirname(fromFile), jsonPath).replace(/\\/g, "/");
27
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = `./${rel}`;
28
+ return rel;
33
29
  };
34
- const babelPluginIntlayer = () => {
35
- const configuration = getConfiguration();
36
- const dictionariesRoot = configuration.content.mainDir.replace(
37
- /[/\\]+$/,
38
- ""
39
- );
40
- const contentDir = configuration.content.contentDir;
41
- const appLogger = getAppLogger(configuration);
30
+ const intlayerBabelPlugin = () => {
42
31
  return {
43
- name: "babel-plugin-intlayer-prune",
32
+ name: "babel-plugin-intlayer-transform",
33
+ pre() {
34
+ this._newImports = /* @__PURE__ */ new Map();
35
+ this._hasValidImport = false;
36
+ this._isDictEntry = false;
37
+ },
44
38
  visitor: {
39
+ /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */
45
40
  Program: {
46
- enter(_programPath, state) {
47
- state.importedPackages = /* @__PURE__ */ new Set();
48
- state.hasValidIntlayerImport = false;
49
- const filePath = state.file.opts.filename ?? "";
50
- if (!isFileInContentDir(filePath, contentDir)) {
51
- return;
41
+ enter(programPath, state) {
42
+ const filename = state.file.opts.filename;
43
+ if (filename === state.opts.dictionariesEntryPath) {
44
+ state._isDictEntry = true;
45
+ programPath.node.body = [
46
+ t.exportDefaultDeclaration(t.objectExpression([]))
47
+ ];
48
+ programPath.stop();
52
49
  }
53
50
  },
54
- /*
55
- * After the whole file has been walked, decide if THIS file is the
56
- * dictionary entry-point. If it is, swap its body for the generated
57
- * code that imports only the used dictionaries.
58
- */
51
+ /* 3. After full traversal, inject the JSON dictionary imports. */
59
52
  exit(programPath, state) {
60
- const filePath = state.file.opts.filename ?? "";
61
- if (!isFileInContentDir(filePath, contentDir)) return;
62
- if (!isThreeShakable) return;
63
- if (!filePath.startsWith(dictionariesRoot)) return;
64
- const keys = Array.from(globalUsedKeys);
65
- if (!keys.length) return;
66
- const extension = extname(filePath);
67
- const format = extension === ".cjs" ? "cjs" : "esm";
68
- const dictionaries = getBuiltDictionariesPath(configuration).filter(
69
- (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))
70
- );
71
- const generatedSrc = generateDictionaryListContent(
72
- dictionaries,
73
- format,
74
- configuration
75
- );
76
- if (!generatedSrc) return;
77
- const newAst = parse(generatedSrc, {
78
- sourceType: format === "cjs" ? "script" : "module",
79
- plugins: ["importMeta"]
80
- });
81
- appLogger("Unused dictionaries pruned to reduce bundle size", {
82
- level: "info"
83
- });
84
- programPath.node.body = [];
85
- programPath.pushContainer("body", newAst.program.body);
86
- state.file.metadata = {
87
- ...state.file.metadata,
88
- intlayerPruned: true
89
- };
53
+ if (state._isDictEntry) return;
54
+ if (!state._hasValidImport) return;
55
+ const file = state.file.opts.filename;
56
+ const dictDir = state.opts.dictionariesDir;
57
+ const imports = [];
58
+ for (const [key, ident] of state._newImports) {
59
+ const rel = computeRelativeImport(file, dictDir, key);
60
+ imports.push(
61
+ t.importDeclaration(
62
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
63
+ t.stringLiteral(rel)
64
+ )
65
+ );
66
+ }
67
+ if (!imports.length) return;
68
+ const bodyPaths = programPath.get("body");
69
+ let insertPos = 0;
70
+ for (const stmtPath of bodyPaths) {
71
+ const stmt = stmtPath.node;
72
+ if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && (stmt.expression.value === "use client" || stmt.expression.value === "use server")) {
73
+ insertPos += 1;
74
+ } else {
75
+ break;
76
+ }
77
+ }
78
+ programPath.node.body.splice(insertPos, 0, ...imports);
90
79
  }
91
80
  },
81
+ /* 1. Inspect *every* intlayer import. */
92
82
  ImportDeclaration(path, state) {
93
- const filePath = state.file.opts.filename ?? "";
94
- if (!isFileInContentDir(filePath, contentDir)) {
95
- return;
96
- }
97
- const source = path.node.source.value;
98
- state.importedPackages?.add(source);
99
- if (isValidIntlayerImport(source)) {
100
- const hasIntlayerFunction = path.node.specifiers.some((specifier) => {
101
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {
102
- return CALLER_LIST.includes(specifier.imported.name);
103
- }
104
- return false;
105
- });
106
- if (hasIntlayerFunction) {
107
- state.hasValidIntlayerImport = true;
83
+ if (state._isDictEntry) return;
84
+ const src = path.node.source.value;
85
+ if (!PACKAGE_LIST.includes(src)) return;
86
+ state._hasValidImport = true;
87
+ for (const spec of path.node.specifiers) {
88
+ if (!t.isImportSpecifier(spec)) continue;
89
+ const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
90
+ if (importedName === "useIntlayer") {
91
+ spec.imported = t.identifier("useDictionary");
92
+ } else if (importedName === "getIntlayer") {
93
+ spec.imported = t.identifier("getDictionary");
108
94
  }
109
95
  }
110
96
  },
97
+ /* 2. Replace calls: useIntlayer("foo") → useDictionary(_hash) */
111
98
  CallExpression(path, state) {
112
- const filePath = state.file.opts.filename ?? "";
113
- if (!isFileInContentDir(filePath, contentDir)) return;
114
- if (!isThreeShakable) return;
115
- const { node } = path;
116
- const renderError = (message) => {
117
- const filePath2 = state.file.opts.filename ?? "";
118
- const codeFrame = path.buildCodeFrameError("").message;
119
- console.info("");
120
- appLogger(message, {
121
- level: "error"
122
- });
123
- appLogger(`At ${relative(process.cwd(), filePath2)}`, {
124
- level: "error"
125
- });
126
- appLogger(codeFrame.split("\n").slice(1).join("\n"), {
127
- level: "error"
128
- });
129
- };
130
- if (t.isIdentifier(node.callee) && CALLER_LIST.includes(node.callee.name)) {
131
- if (!state.hasValidIntlayerImport) {
132
- isThreeShakable = false;
133
- renderError(
134
- `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(", ")}`
135
- );
136
- return;
137
- }
138
- if (!node.arguments.length) {
139
- isThreeShakable = false;
140
- renderError(`${node.callee.name} requires at least one argument`);
141
- return;
142
- }
143
- if (!t.isStringLiteral(node.arguments[0])) {
144
- isThreeShakable = false;
145
- renderError(
146
- `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`
147
- );
148
- return;
149
- }
150
- globalUsedKeys.add(node.arguments[0].value);
99
+ if (state._isDictEntry) return;
100
+ const callee = path.node.callee;
101
+ if (!t.isIdentifier(callee)) return;
102
+ if (!CALLER_LIST.includes(callee.name)) return;
103
+ state._hasValidImport = true;
104
+ const arg = path.node.arguments[0];
105
+ if (!arg || !t.isStringLiteral(arg)) return;
106
+ const key = arg.value;
107
+ let ident = state._newImports.get(key);
108
+ if (!ident) {
109
+ ident = makeIdent(key);
110
+ state._newImports.set(key, ident);
151
111
  }
112
+ path.node.arguments[0] = t.identifier(ident.name);
152
113
  }
153
114
  }
154
115
  };
155
116
  };
156
117
  export {
157
- babelPluginIntlayer
118
+ intlayerBabelPlugin
158
119
  };
159
120
  //# sourceMappingURL=babel-plugin-intlayer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n generateDictionaryListContent,\n getBuiltDictionariesPath,\n} from '@intlayer/chokidar';\nimport { getAppLogger, getConfiguration } from '@intlayer/config';\nimport { extname, relative, sep } from 'path';\n\ntype PluginState = PluginPass & {\n opts: {\n enableTransform?: boolean;\n };\n // Add tracking for imports per file\n importedPackages?: Set<string>;\n hasValidIntlayerImport?: boolean;\n};\n\n// ────────────────────────────────────────────────────────────\n// shared state across ALL files (1 build = 1 Node process)\nconst PACKAGE_LIST = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/server',\n 'next-intlayer/client',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-inltayer',\n];\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'];\nconst globalUsedKeys = new Set<string>();\nlet isThreeShakable = true;\n// ────────────────────────────────────────────────────────────\n\n// Helper function to check if file is in contentDir\nconst isFileInContentDir = (\n filePath: string,\n contentDirs: string[]\n): boolean => {\n return contentDirs.some((dir) => {\n const normalizedDir = dir.replace(/[/\\\\]+$/, '');\n return filePath.startsWith(normalizedDir);\n });\n};\n\n// Helper function to check if import is from valid package\nconst isValidIntlayerImport = (source: string): boolean => {\n return PACKAGE_LIST.includes(source);\n};\n\nexport const babelPluginIntlayer = (): PluginObj<PluginState> => {\n const configuration = getConfiguration();\n const dictionariesRoot: string = configuration.content.mainDir.replace(\n /[/\\\\]+$/,\n ''\n );\n const contentDir: string[] = configuration.content.contentDir;\n const appLogger = getAppLogger(configuration);\n\n return {\n name: 'babel-plugin-intlayer-prune',\n\n visitor: {\n Program: {\n enter(_programPath, state: PluginState) {\n // Initialize per-file state\n state.importedPackages = new Set<string>();\n state.hasValidIntlayerImport = false;\n\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n },\n\n /*\n * After the whole file has been walked, decide if THIS file is the\n * dictionary entry-point. If it is, swap its body for the generated\n * code that imports only the used dictionaries.\n */\n exit(programPath, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n\n // Skip files is bundle is not three-shakable\n if (!isThreeShakable) return;\n\n // Is this *the* entry-point we want to shrink?\n if (!filePath.startsWith(dictionariesRoot)) return;\n\n const keys = Array.from(globalUsedKeys);\n if (!keys.length) return; // nothing collected yet – leave the file untouched\n\n const extension = extname(filePath); // .js / .mjs / .cjs\n const format = extension === '.cjs' ? 'cjs' : 'esm';\n\n // Pick only the dictionaries whose basename matches a collected key\n const dictionaries = getBuiltDictionariesPath(configuration).filter(\n (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))\n );\n\n const generatedSrc = generateDictionaryListContent(\n dictionaries,\n format,\n configuration\n );\n if (!generatedSrc) return;\n\n // Replace the current AST with the new one\n const newAst = parse(generatedSrc, {\n sourceType: format === 'cjs' ? 'script' : 'module',\n plugins: ['importMeta'],\n });\n\n appLogger('Unused dictionaries pruned to reduce bundle size', {\n level: 'info',\n });\n\n // Clear and inject\n programPath.node.body = [];\n programPath.pushContainer('body', newAst.program.body);\n\n // Optional: mark the file as \"transformed\" for other tooling\n state.file.metadata = {\n ...state.file.metadata,\n intlayerPruned: true,\n };\n },\n },\n\n ImportDeclaration(\n path: NodePath<t.ImportDeclaration>,\n state: PluginState\n ) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n\n const source = path.node.source.value;\n state.importedPackages?.add(source);\n\n // Check if this import is from a valid intlayer package\n if (isValidIntlayerImport(source)) {\n // Check if any of the imported specifiers include useIntlayer or getIntlayer\n const hasIntlayerFunction = path.node.specifiers.some((specifier) => {\n if (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported)\n ) {\n return CALLER_LIST.includes(specifier.imported.name);\n }\n return false;\n });\n\n if (hasIntlayerFunction) {\n state.hasValidIntlayerImport = true;\n }\n }\n },\n\n CallExpression(path: NodePath<t.CallExpression>, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n if (!isThreeShakable) return;\n\n const { node } = path;\n\n const renderError = (message: string) => {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Generate code frame to show the error context\n const codeFrame = path.buildCodeFrameError('').message;\n\n console.info(''); // For formating\n appLogger(message, {\n level: 'error',\n });\n appLogger(`At ${relative(process.cwd(), filePath)}`, {\n level: 'error',\n });\n appLogger(codeFrame.split('\\n').slice(1).join('\\n'), {\n level: 'error',\n });\n };\n\n if (\n t.isIdentifier(node.callee) &&\n CALLER_LIST.includes(node.callee.name)\n ) {\n // Check if the function is imported from a valid package\n if (!state.hasValidIntlayerImport) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(', ')}`\n );\n return;\n }\n\n // Check if arguments exist\n if (!node.arguments.length) {\n isThreeShakable = false;\n\n renderError(`${node.callee.name} requires at least one argument`);\n\n return;\n }\n\n // Check if the first argument is a string literal\n if (!t.isStringLiteral(node.arguments[0])) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`\n );\n return;\n }\n\n globalUsedKeys.add(node.arguments[0].value);\n }\n },\n },\n };\n};\n"],"mappings":"AACA,SAAS,aAAa;AAEtB,YAAY,OAAO;AACnB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc,wBAAwB;AAC/C,SAAS,SAAS,UAAU,WAAW;AAavC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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C/C,YAAI,CAAC,gBAAiB;AAEtB,cAAM,EAAE,KAAK,IAAI;AAEjB,cAAM,cAAc,CAAC,YAAoB;AACvC,gBAAMA,YAAmB,MAAM,KAAK,KAAK,YAAY;AAGrD,gBAAM,YAAY,KAAK,oBAAoB,EAAE,EAAE;AAE/C,kBAAQ,KAAK,EAAE;AACf,oBAAU,SAAS;AAAA,YACjB,OAAO;AAAA,UACT,CAAC;AACD,oBAAU,MAAM,SAAS,QAAQ,IAAI,GAAGA,SAAQ,CAAC,IAAI;AAAA,YACnD,OAAO;AAAA,UACT,CAAC;AACD,oBAAU,UAAU,MAAM,IAAI,EAAE,MAAM,CAAC,EAAE,KAAK,IAAI,GAAG;AAAA,YACnD,OAAO;AAAA,UACT,CAAC;AAAA,QACH;AAEA,YACE,EAAE,aAAa,KAAK,MAAM,KAC1B,YAAY,SAAS,KAAK,OAAO,IAAI,GACrC;AAEA,cAAI,CAAC,MAAM,wBAAwB;AACjC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI,iDAAiD,aAAa,KAAK,IAAI,CAAC;AAAA,YAClI;AACA;AAAA,UACF;AAGA,cAAI,CAAC,KAAK,UAAU,QAAQ;AAC1B,8BAAkB;AAElB,wBAAY,GAAG,KAAK,OAAO,IAAI,iCAAiC;AAEhE;AAAA,UACF;AAGA,cAAI,CAAC,EAAE,gBAAgB,KAAK,UAAU,CAAC,CAAC,GAAG;AACzC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI;AAAA,YAC1D;AACA;AAAA,UACF;AAEA,yBAAe,IAAI,KAAK,UAAU,CAAC,EAAE,KAAK;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["filePath"]}
1
+ {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport * as t from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar';\nimport { dirname, join, relative } from 'node:path';\n\n/* ────────────────────────────────────────── constants ───────────────────── */\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: { dictionariesDir: string; dictionariesEntryPath: string };\n /** map key → generated ident (per-file) */\n _newImports?: Map<string, t.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (key: string): t.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeRelativeImport = (\n fromFile: string,\n dictDir: string,\n key: string\n): string => {\n const jsonPath = join(dictDir, `${key}.json`);\n let rel = relative(dirname(fromFile), jsonPath).replace(/\\\\/g, '/'); // win →\n if (!rel.startsWith('./') && !rel.startsWith('../')) rel = `./${rel}`;\n return rel;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Babel plugin that transforms `useIntlayer/getIntlayer` calls into\n * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.\n *\n * **New behaviour**: if the currently processed file matches `dictionariesEntryPath`,\n * its entire contents are replaced with a simple `export default {}` so that it\n * never contains stale or circular references.\n *\n * The **critical detail** (bug-fix) is that we still **only rewrite** an import\n * specifier when its *imported* name is `useIntlayer`/`getIntlayer`.\n *\n * This means cases like:\n * ```ts\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * ```\n * —where `useIntlayer` is merely an *alias* or re-export—are left untouched\n * because `imported.name` is `useDictionary`.\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newImports = new Map();\n this._hasValidImport = false;\n this._isDictEntry = false;\n },\n\n visitor: {\n /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n const filename = state.file.opts.filename!;\n if (filename === state.opts.dictionariesEntryPath) {\n state._isDictEntry = true;\n // Replace all existing statements with: export default {}\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n ];\n // Stop further traversal for this plugin – nothing else to transform\n programPath.stop();\n }\n },\n\n /* 3. After full traversal, inject the JSON dictionary imports. */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n if (!state._hasValidImport) return; // early-out if we touched nothing\n\n const file = state.file.opts.filename!;\n const dictDir = state.opts.dictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n for (const [key, ident] of state._newImports!) {\n const rel = computeRelativeImport(file, dictDir, key);\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get('body') as NodePath<t.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n (stmt.expression.value === 'use client' ||\n stmt.expression.value === 'use server')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, ...imports);\n },\n },\n\n /* 1. Inspect *every* intlayer import. */\n ImportDeclaration(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const src = path.node.source.value;\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file; this is\n // enough to know that we *might* need to inject runtime helpers later.\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n // ⚠️ We now key off *imported* name, *not* local name.\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as t.StringLiteral).value;\n\n if (importedName === 'useIntlayer') {\n spec.imported = t.identifier('useDictionary');\n } else if (importedName === 'getIntlayer') {\n spec.imported = t.identifier('getDictionary');\n }\n }\n },\n\n /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) */\n CallExpression(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n if (!CALLER_LIST.includes(callee.name as any)) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn’t import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n if (!arg || !t.isStringLiteral(arg)) return; // must be literal\n\n const key = arg.value;\n // per-file cache\n let ident = state._newImports!.get(key);\n if (!ident) {\n ident = makeIdent(key);\n state._newImports!.set(key, ident);\n }\n\n // replace first arg with ident\n path.node.arguments[0] = t.identifier(ident.name);\n },\n },\n };\n};\n"],"mappings":"AACA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,SAAS,MAAM,gBAAgB;AAIxC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,cAAc,CAAC,eAAe,aAAa;AAqBjD,MAAM,YAAY,CAAC,QAA8B;AAC/C,QAAM,OAAO,YAAY,GAAG;AAC5B,SAAO,EAAE,WAAW,IAAI,IAAI,EAAE;AAChC;AAEA,MAAM,wBAAwB,CAC5B,U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Q,UAAU,GAAG;AACrB,gBAAM,YAAa,IAAI,KAAK,KAAK;AAAA,QACnC;AAGA,aAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,11 +1,35 @@
1
1
  import type { PluginObj, PluginPass } from '@babel/core';
2
- type PluginState = PluginPass & {
2
+ import * as t from '@babel/types';
3
+ type State = PluginPass & {
3
4
  opts: {
4
- enableTransform?: boolean;
5
+ dictionariesDir: string;
6
+ dictionariesEntryPath: string;
5
7
  };
6
- importedPackages?: Set<string>;
7
- hasValidIntlayerImport?: boolean;
8
+ /** map key → generated ident (per-file) */
9
+ _newImports?: Map<string, t.Identifier>;
10
+ /** whether the current file imported *any* intlayer package */
11
+ _hasValidImport?: boolean;
12
+ /** whether the current file *is* the dictionaries entry file */
13
+ _isDictEntry?: boolean;
8
14
  };
9
- export declare const babelPluginIntlayer: () => PluginObj<PluginState>;
15
+ /**
16
+ * Babel plugin that transforms `useIntlayer/getIntlayer` calls into
17
+ * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.
18
+ *
19
+ * **New behaviour**: if the currently processed file matches `dictionariesEntryPath`,
20
+ * its entire contents are replaced with a simple `export default {}` so that it
21
+ * never contains stale or circular references.
22
+ *
23
+ * The **critical detail** (bug-fix) is that we still **only rewrite** an import
24
+ * specifier when its *imported* name is `useIntlayer`/`getIntlayer`.
25
+ *
26
+ * This means cases like:
27
+ * ```ts
28
+ * import { useDictionary as useIntlayer } from 'react-intlayer';
29
+ * ```
30
+ * —where `useIntlayer` is merely an *alias* or re-export—are left untouched
31
+ * because `imported.name` is `useDictionary`.
32
+ */
33
+ export declare const intlayerBabelPlugin: () => PluginObj<State>;
10
34
  export {};
11
35
  //# sourceMappingURL=babel-plugin-intlayer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer.d.ts","sourceRoot":"","sources":["../../src/babel-plugin-intlayer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAWzD,KAAK,WAAW,GAAG,UAAU,GAAG;IAC9B,IAAI,EAAE;QACJ,eAAe,CAAC,EAAE,OAAO,CAAC;KAC3B,CAAC;IAEF,gBAAgB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC/B,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC,CAAC;AAsCF,eAAO,MAAM,mBAAmB,QAAO,SAAS,CAAC,WAAW,CAsL3D,CAAC"}
1
+ {"version":3,"file":"babel-plugin-intlayer.d.ts","sourceRoot":"","sources":["../../src/babel-plugin-intlayer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AA0BlC,KAAK,KAAK,GAAG,UAAU,GAAG;IACxB,IAAI,EAAE;QAAE,eAAe,EAAE,MAAM,CAAC;QAAC,qBAAqB,EAAE,MAAM,CAAA;KAAE,CAAC;IACjE,2CAA2C;IAC3C,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;IACxC,+DAA+D;IAC/D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gEAAgE;IAChE,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AA2BF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,QAAO,SAAS,CAAC,KAAK,CA4HrD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/babel",
3
- "version": "5.5.2",
3
+ "version": "5.5.3",
4
4
  "private": false,
5
5
  "description": "A Babel plugin for Intlayer that transforms declaration files and provides internationalization features during the build process according to the Intlayer configuration.",
6
6
  "keywords": [
@@ -62,8 +62,8 @@
62
62
  "@babel/generator": "^7.27.1",
63
63
  "@babel/parser": "^7.27.2",
64
64
  "@babel/traverse": "^7.27.1",
65
- "@intlayer/config": "5.5.2",
66
- "@intlayer/chokidar": "5.5.2"
65
+ "@intlayer/chokidar": "5.5.3",
66
+ "@intlayer/config": "5.5.3"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@babel/types": "^7.27.1",
@@ -82,14 +82,14 @@
82
82
  "tsc-alias": "^1.8.11",
83
83
  "tsup": "^8.4.0",
84
84
  "typescript": "^5.8.2",
85
- "@utils/eslint-config": "1.0.4",
86
85
  "@utils/ts-config-types": "1.0.4",
87
86
  "@utils/tsup-config": "1.0.4",
88
- "@utils/ts-config": "1.0.4"
87
+ "@utils/ts-config": "1.0.4",
88
+ "@utils/eslint-config": "1.0.4"
89
89
  },
90
90
  "peerDependencies": {
91
- "@intlayer/chokidar": "5.5.2",
92
- "@intlayer/config": "5.5.2"
91
+ "@intlayer/chokidar": "5.5.3",
92
+ "@intlayer/config": "5.5.3"
93
93
  },
94
94
  "engines": {
95
95
  "node": ">=14.18"