@intlayer/babel 7.3.0 → 7.3.2-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -2
- package/dist/cjs/_virtual/rolldown_runtime.cjs +29 -0
- package/dist/cjs/babel-plugin-intlayer-extract.cjs +242 -0
- package/dist/cjs/babel-plugin-intlayer-extract.cjs.map +1 -0
- package/dist/cjs/{babel-plugin-intlayer.cjs → babel-plugin-intlayer-optimize.cjs} +114 -111
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -0
- package/dist/cjs/getExtractPluginOptions.cjs +80 -0
- package/dist/cjs/getExtractPluginOptions.cjs.map +1 -0
- package/dist/cjs/getOptimizePluginOptions.cjs +60 -0
- package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -0
- package/dist/cjs/index.cjs +8 -2
- package/dist/esm/_virtual/rolldown_runtime.mjs +8 -0
- package/dist/esm/babel-plugin-intlayer-extract.mjs +241 -0
- package/dist/esm/babel-plugin-intlayer-extract.mjs.map +1 -0
- package/dist/esm/{babel-plugin-intlayer.mjs → babel-plugin-intlayer-optimize.mjs} +113 -111
- package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -0
- package/dist/esm/getExtractPluginOptions.mjs +79 -0
- package/dist/esm/getExtractPluginOptions.mjs.map +1 -0
- package/dist/esm/getOptimizePluginOptions.mjs +59 -0
- package/dist/esm/getOptimizePluginOptions.mjs.map +1 -0
- package/dist/esm/index.mjs +5 -2
- package/dist/types/babel-plugin-intlayer-extract.d.ts +133 -0
- package/dist/types/babel-plugin-intlayer-extract.d.ts.map +1 -0
- package/dist/types/{babel-plugin-intlayer.d.ts → babel-plugin-intlayer-optimize.d.ts} +64 -55
- package/dist/types/babel-plugin-intlayer-optimize.d.ts.map +1 -0
- package/dist/types/getExtractPluginOptions.d.ts +13 -0
- package/dist/types/getExtractPluginOptions.d.ts.map +1 -0
- package/dist/types/getOptimizePluginOptions.d.ts +28 -0
- package/dist/types/getOptimizePluginOptions.d.ts.map +1 -0
- package/dist/types/index.d.ts +5 -2
- package/package.json +17 -6
- package/dist/cjs/babel-plugin-intlayer.cjs.map +0 -1
- package/dist/esm/babel-plugin-intlayer.mjs.map +0 -1
- package/dist/types/babel-plugin-intlayer.d.ts.map +0 -1
|
@@ -2,7 +2,7 @@ import { dirname, join, relative } from "node:path";
|
|
|
2
2
|
import { getFileHash } from "@intlayer/chokidar";
|
|
3
3
|
import { normalizePath } from "@intlayer/config";
|
|
4
4
|
|
|
5
|
-
//#region src/babel-plugin-intlayer.ts
|
|
5
|
+
//#region src/babel-plugin-intlayer-optimize.ts
|
|
6
6
|
const PACKAGE_LIST = [
|
|
7
7
|
"intlayer",
|
|
8
8
|
"@intlayer/core",
|
|
@@ -140,7 +140,7 @@ const computeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, fetchD
|
|
|
140
140
|
* const content2 = getIntlayer(_dicHash);
|
|
141
141
|
* ```
|
|
142
142
|
*/
|
|
143
|
-
const
|
|
143
|
+
const intlayerOptimizeBabelPlugin = (babel) => {
|
|
144
144
|
const { types: t } = babel;
|
|
145
145
|
return {
|
|
146
146
|
name: "babel-plugin-intlayer-transform",
|
|
@@ -151,6 +151,10 @@ const intlayerBabelPlugin = (babel) => {
|
|
|
151
151
|
this._hasValidImport = false;
|
|
152
152
|
this._isDictEntry = false;
|
|
153
153
|
this._useDynamicHelpers = false;
|
|
154
|
+
if (this.opts.optimize === false) {
|
|
155
|
+
this._isIncluded = false;
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
154
158
|
const filename = this.file.opts.filename;
|
|
155
159
|
if (this.opts.filesList && filename) {
|
|
156
160
|
if (!this.opts.filesList.includes(filename)) {
|
|
@@ -159,123 +163,121 @@ const intlayerBabelPlugin = (babel) => {
|
|
|
159
163
|
}
|
|
160
164
|
}
|
|
161
165
|
},
|
|
162
|
-
visitor: {
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
},
|
|
178
|
-
exit(programPath, state) {
|
|
179
|
-
if (state._isDictEntry) return;
|
|
180
|
-
if (!state._hasValidImport) return;
|
|
181
|
-
if (!state._isIncluded) return;
|
|
182
|
-
const file = state.file.opts.filename;
|
|
183
|
-
const dictionariesDir = state.opts.dictionariesDir;
|
|
184
|
-
const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
|
|
185
|
-
const fetchDictionariesDir = state.opts.fetchDictionariesDir;
|
|
186
|
-
const imports = [];
|
|
187
|
-
for (const [key, ident] of state._newStaticImports) {
|
|
188
|
-
const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, "static");
|
|
189
|
-
const importDeclarationNode = t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel));
|
|
190
|
-
importDeclarationNode.attributes = [t.importAttribute(t.identifier("type"), t.stringLiteral("json"))];
|
|
191
|
-
imports.push(importDeclarationNode);
|
|
192
|
-
}
|
|
193
|
-
for (const [key, ident] of state._newDynamicImports) {
|
|
194
|
-
const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, ident.name.endsWith("_fetch") ? "live" : "dynamic");
|
|
195
|
-
imports.push(t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel)));
|
|
196
|
-
}
|
|
197
|
-
if (!imports.length) return;
|
|
198
|
-
const bodyPaths = programPath.get("body");
|
|
199
|
-
let insertPos = 0;
|
|
200
|
-
for (const stmtPath of bodyPaths) {
|
|
201
|
-
const stmt = stmtPath.node;
|
|
202
|
-
if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && !stmt.expression.value.startsWith("import") && !stmt.expression.value.startsWith("require")) insertPos += 1;
|
|
203
|
-
else break;
|
|
204
|
-
}
|
|
205
|
-
programPath.node.body.splice(insertPos, 0, ...imports);
|
|
166
|
+
visitor: { Program: {
|
|
167
|
+
enter(programPath, state) {
|
|
168
|
+
const filename = state.file.opts.filename;
|
|
169
|
+
if (state.opts.replaceDictionaryEntry && filename === state.opts.dictionariesEntryPath) {
|
|
170
|
+
state._isDictEntry = true;
|
|
171
|
+
programPath.traverse({
|
|
172
|
+
ImportDeclaration(path) {
|
|
173
|
+
path.remove();
|
|
174
|
+
},
|
|
175
|
+
VariableDeclarator(path) {
|
|
176
|
+
if (t.isObjectExpression(path.node.init)) path.node.init.properties = [];
|
|
177
|
+
}
|
|
178
|
+
});
|
|
206
179
|
}
|
|
207
180
|
},
|
|
208
|
-
|
|
181
|
+
exit(programPath, state) {
|
|
209
182
|
if (state._isDictEntry) return;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
183
|
+
if (!state._isIncluded) return;
|
|
184
|
+
programPath.traverse({
|
|
185
|
+
ImportDeclaration(path) {
|
|
186
|
+
const src = path.node.source.value;
|
|
187
|
+
if (!PACKAGE_LIST.includes(src)) return;
|
|
188
|
+
state._hasValidImport = true;
|
|
189
|
+
for (const spec of path.node.specifiers) {
|
|
190
|
+
if (!t.isImportSpecifier(spec)) continue;
|
|
191
|
+
const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
|
|
192
|
+
const importMode = state.opts.importMode;
|
|
193
|
+
const shouldUseDynamicHelpers = (importMode === "dynamic" || importMode === "live") && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
194
|
+
if (shouldUseDynamicHelpers) state._useDynamicHelpers = true;
|
|
195
|
+
let helperMap;
|
|
196
|
+
if (shouldUseDynamicHelpers) helperMap = {
|
|
197
|
+
...STATIC_IMPORT_FUNCTION,
|
|
198
|
+
...DYNAMIC_IMPORT_FUNCTION
|
|
199
|
+
};
|
|
200
|
+
else helperMap = STATIC_IMPORT_FUNCTION;
|
|
201
|
+
const newIdentifier = helperMap[importedName];
|
|
202
|
+
if (newIdentifier) spec.imported = t.identifier(newIdentifier);
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
CallExpression(path) {
|
|
206
|
+
const callee = path.node.callee;
|
|
207
|
+
if (!t.isIdentifier(callee)) return;
|
|
208
|
+
if (!CALLER_LIST.includes(callee.name)) return;
|
|
209
|
+
state._hasValidImport = true;
|
|
210
|
+
const arg = path.node.arguments[0];
|
|
211
|
+
if (!arg || !t.isStringLiteral(arg)) return;
|
|
212
|
+
const key = arg.value;
|
|
213
|
+
const importMode = state.opts.importMode;
|
|
214
|
+
const isUseIntlayer = callee.name === "useIntlayer";
|
|
215
|
+
const useDynamicHelpers = Boolean(state._useDynamicHelpers);
|
|
216
|
+
let perCallMode = "static";
|
|
217
|
+
if (isUseIntlayer && useDynamicHelpers) {
|
|
218
|
+
if (importMode === "dynamic") perCallMode = "dynamic";
|
|
219
|
+
else if (importMode === "live") perCallMode = (state.opts.liveSyncKeys ?? []).includes(key) ? "live" : "dynamic";
|
|
220
|
+
}
|
|
221
|
+
let ident;
|
|
222
|
+
if (perCallMode === "live") {
|
|
223
|
+
let dynamicIdent = state._newDynamicImports?.get(key);
|
|
224
|
+
if (!dynamicIdent) {
|
|
225
|
+
const hash = getFileHash(key);
|
|
226
|
+
dynamicIdent = t.identifier(`_${hash}_fetch`);
|
|
227
|
+
state._newDynamicImports?.set(key, dynamicIdent);
|
|
228
|
+
}
|
|
229
|
+
ident = dynamicIdent;
|
|
230
|
+
path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
|
|
231
|
+
} else if (perCallMode === "dynamic") {
|
|
232
|
+
let dynamicIdent = state._newDynamicImports?.get(key);
|
|
233
|
+
if (!dynamicIdent) {
|
|
234
|
+
const hash = getFileHash(key);
|
|
235
|
+
dynamicIdent = t.identifier(`_${hash}_dyn`);
|
|
236
|
+
state._newDynamicImports?.set(key, dynamicIdent);
|
|
237
|
+
}
|
|
238
|
+
ident = dynamicIdent;
|
|
239
|
+
path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
|
|
240
|
+
} else {
|
|
241
|
+
let staticIdent = state._newStaticImports?.get(key);
|
|
242
|
+
if (!staticIdent) {
|
|
243
|
+
staticIdent = makeIdent(key, t);
|
|
244
|
+
state._newStaticImports?.set(key, staticIdent);
|
|
245
|
+
}
|
|
246
|
+
ident = staticIdent;
|
|
247
|
+
path.node.arguments[0] = t.identifier(ident.name);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
if (!state._hasValidImport) return;
|
|
252
|
+
const file = state.file.opts.filename;
|
|
253
|
+
const dictionariesDir = state.opts.dictionariesDir;
|
|
254
|
+
const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
|
|
255
|
+
const fetchDictionariesDir = state.opts.fetchDictionariesDir;
|
|
256
|
+
const imports = [];
|
|
257
|
+
for (const [key, ident] of state._newStaticImports) {
|
|
258
|
+
const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, "static");
|
|
259
|
+
const importDeclarationNode = t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel));
|
|
260
|
+
importDeclarationNode.attributes = [t.importAttribute(t.identifier("type"), t.stringLiteral("json"))];
|
|
261
|
+
imports.push(importDeclarationNode);
|
|
227
262
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const callee = path.node.callee;
|
|
232
|
-
if (!t.isIdentifier(callee)) return;
|
|
233
|
-
if (!CALLER_LIST.includes(callee.name)) return;
|
|
234
|
-
state._hasValidImport = true;
|
|
235
|
-
const arg = path.node.arguments[0];
|
|
236
|
-
if (!arg || !t.isStringLiteral(arg)) return;
|
|
237
|
-
const key = arg.value;
|
|
238
|
-
const importMode = state.opts.importMode;
|
|
239
|
-
const isUseIntlayer = callee.name === "useIntlayer";
|
|
240
|
-
const useDynamicHelpers = Boolean(state._useDynamicHelpers);
|
|
241
|
-
let perCallMode = "static";
|
|
242
|
-
if (isUseIntlayer && useDynamicHelpers) {
|
|
243
|
-
if (importMode === "dynamic") perCallMode = "dynamic";
|
|
244
|
-
else if (importMode === "live") perCallMode = (state.opts.liveSyncKeys ?? []).includes(key) ? "live" : "dynamic";
|
|
263
|
+
for (const [key, ident] of state._newDynamicImports) {
|
|
264
|
+
const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, ident.name.endsWith("_fetch") ? "live" : "dynamic");
|
|
265
|
+
imports.push(t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel)));
|
|
245
266
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
}
|
|
254
|
-
ident = dynamicIdent;
|
|
255
|
-
path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
|
|
256
|
-
} else if (perCallMode === "dynamic") {
|
|
257
|
-
let dynamicIdent = state._newDynamicImports?.get(key);
|
|
258
|
-
if (!dynamicIdent) {
|
|
259
|
-
const hash = getFileHash(key);
|
|
260
|
-
dynamicIdent = t.identifier(`_${hash}_dyn`);
|
|
261
|
-
state._newDynamicImports?.set(key, dynamicIdent);
|
|
262
|
-
}
|
|
263
|
-
ident = dynamicIdent;
|
|
264
|
-
path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
|
|
265
|
-
} else {
|
|
266
|
-
let staticIdent = state._newStaticImports?.get(key);
|
|
267
|
-
if (!staticIdent) {
|
|
268
|
-
staticIdent = makeIdent(key, t);
|
|
269
|
-
state._newStaticImports?.set(key, staticIdent);
|
|
270
|
-
}
|
|
271
|
-
ident = staticIdent;
|
|
272
|
-
path.node.arguments[0] = t.identifier(ident.name);
|
|
267
|
+
if (!imports.length) return;
|
|
268
|
+
const bodyPaths = programPath.get("body");
|
|
269
|
+
let insertPos = 0;
|
|
270
|
+
for (const stmtPath of bodyPaths) {
|
|
271
|
+
const stmt = stmtPath.node;
|
|
272
|
+
if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && !stmt.expression.value.startsWith("import") && !stmt.expression.value.startsWith("require")) insertPos += 1;
|
|
273
|
+
else break;
|
|
273
274
|
}
|
|
275
|
+
programPath.node.body.splice(insertPos, 0, ...imports);
|
|
274
276
|
}
|
|
275
|
-
}
|
|
277
|
+
} }
|
|
276
278
|
};
|
|
277
279
|
};
|
|
278
280
|
|
|
279
281
|
//#endregion
|
|
280
|
-
export {
|
|
281
|
-
//# sourceMappingURL=babel-plugin-intlayer.mjs.map
|
|
282
|
+
export { intlayerOptimizeBabelPlugin };
|
|
283
|
+
//# sourceMappingURL=babel-plugin-intlayer-optimize.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-optimize.mjs","names":["helperMap: Record<string, string>","perCallMode: 'static' | 'dynamic' | 'live'","ident: BabelTypes.Identifier","imports: BabelTypes.ImportDeclaration[]"],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar';\nimport { normalizePath } from '@intlayer/config';\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/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n] as const;\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'live';\n /**\n * Activate the live sync of the dictionaries.\n * If `importMode` is `live`, the plugin will activate the live sync of the dictionaries.\n */\n liveSyncKeys: string[];\n /**\n * Files list to traverse.\n */\n filesList: string[];\n};\n\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, BabelTypes.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, BabelTypes.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 /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether the current file is included in the filesList */\n _isIncluded?: 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 = (\n key: string,\n t: typeof BabelTypes\n): BabelTypes.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'live'\n): string => {\n let relativePath = join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'live') {\n relativePath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n relativePath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n let rel = relative(dirname(fromFile), relativePath);\n\n // Fix windows path\n rel = normalizePath(rel);\n\n // Fix relative path\n if (!rel.startsWith('./') && !rel.startsWith('../')) {\n rel = `./${rel}`;\n }\n\n return rel;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer\n * packages into optimized dictionary access patterns, automatically importing the required\n * dictionary files based on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer\n * import { getIntlayer } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Live Mode (`importMode = \"live\"`)\n *\n * Uses live-based dictionary loading for remote dictionaries:\n *\n * **Output if `liveSyncKeys` includes the key:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `liveSyncKeys` does not include the key, the plugin will fallback to the dynamic impor\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename;\n if (this.opts.filesList && filename) {\n const isIncluded = this.opts.filesList.includes(filename);\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename;\n\n // Check if this is the correct file to transform\n if (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n\n // Traverse the program to surgically remove/edit specific parts\n programPath.traverse({\n // Remove all import statements (cleaning up 'sssss.json')\n ImportDeclaration(path) {\n path.remove();\n },\n\n // Find the variable definition and empty the object\n VariableDeclarator(path) {\n // We look for: const x = { ... }\n if (t.isObjectExpression(path.node.init)) {\n // Set the object properties to an empty array: {}\n path.node.init.properties = [];\n }\n },\n });\n\n // (Optional) Stop other plugins from processing this file further if needed\n // programPath.stop();\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n if (!state._isIncluded) return; // early-out if file is not included\n\n // Manual traversal to process imports and call expressions\n // This runs AFTER all other plugins' visitors have completed\n programPath.traverse({\n /* Inspect every intlayer import */\n ImportDeclaration(path) {\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\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 BabelTypes.StringLiteral).value;\n\n const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers.\n const shouldUseDynamicHelpers =\n (importMode === 'dynamic' || importMode === 'live') &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseDynamicHelpers) {\n // Use dynamic helpers for useIntlayer when dynamic mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else {\n // Use static helpers by default\n helperMap = STATIC_IMPORT_FUNCTION as Record<string, string>;\n }\n\n const newIdentifier = helperMap[importedName];\n\n // Only rewrite when we actually have a mapping for the imported\n // specifier (ignore unrelated named imports).\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n },\n\n /* Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path) {\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 const importMode = state.opts.importMode;\n const isUseIntlayer = callee.name === 'useIntlayer';\n const useDynamicHelpers = Boolean(state._useDynamicHelpers);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'live'\n let perCallMode: 'static' | 'dynamic' | 'live' = 'static';\n if (isUseIntlayer && useDynamicHelpers) {\n if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'live') {\n const liveKeys = state.opts.liveSyncKeys ?? [];\n perCallMode = liveKeys.includes(key) ? 'live' : 'dynamic';\n }\n }\n\n let ident: BabelTypes.Identifier;\n\n if (perCallMode === 'live') {\n // Use fetch dictionaries entry (live mode for selected keys)\n let dynamicIdent = state._newDynamicImports?.get(key);\n if (!dynamicIdent) {\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_fetch`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Helper: first argument is the dictionary entry, second is the key\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else if (perCallMode === 'dynamic') {\n // Use dynamic dictionaries entry\n let dynamicIdent = state._newDynamicImports?.get(key);\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_dyn`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Dynamic helper: first argument is the dictionary, second is the key.\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else {\n // Use static imports for getIntlayer or useIntlayer when not using dynamic helpers\n let staticIdent = state._newStaticImports?.get(key);\n if (!staticIdent) {\n staticIdent = makeIdent(key, t);\n state._newStaticImports?.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with iden\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n });\n\n // Early-out if we touched nothing\n if (!state._hasValidImport) return;\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const fetchDictionariesDir = state.opts.fetchDictionariesDir;\n const imports: BabelTypes.ImportDeclaration[] = [];\n\n // Generate static JSON imports (getIntlayer always uses JSON dictionaries)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static'\n );\n\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n // Add 'type: json' attribute for JSON files\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic/fetch imports (for useIntlayer when using dynamic/live helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const modeForThisIdent: 'dynamic' | 'live' = ident.name.endsWith(\n '_fetch'\n )\n ? 'live'\n : 'dynamic';\n\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n modeForThisIdent\n );\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(\n 'body'\n ) as NodePath<BabelTypes.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.startsWith('import') &&\n !stmt.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0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;SAEb;;AAIJ,gBAAY,KAAK,KAAK,OAAO,WAAW,GAAG,GAAG,QAAQ;;GAEzD,EACF;EACF"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { join, relative } from "node:path";
|
|
2
|
+
import { buildDictionary, writeContentDeclaration } from "@intlayer/chokidar";
|
|
3
|
+
import { getConfiguration } from "@intlayer/config";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
|
|
7
|
+
//#region src/getExtractPluginOptions.ts
|
|
8
|
+
/**
|
|
9
|
+
* Get the options for the Intlayer Babel extraction plugin
|
|
10
|
+
* This function loads the Intlayer configuration and sets up the onExtract callback
|
|
11
|
+
* to write dictionaries to the filesystem.
|
|
12
|
+
*/
|
|
13
|
+
const getExtractPluginOptions = () => {
|
|
14
|
+
const config = getConfiguration();
|
|
15
|
+
const { baseDir } = config.content;
|
|
16
|
+
const compilerDir = join(baseDir, config.compiler?.outputDir ?? "compiler");
|
|
17
|
+
/**
|
|
18
|
+
* Read existing dictionary file if it exists
|
|
19
|
+
*/
|
|
20
|
+
const readExistingDictionary = async (dictionaryPath) => {
|
|
21
|
+
try {
|
|
22
|
+
if (!existsSync(dictionaryPath)) return null;
|
|
23
|
+
const content = await readFile(dictionaryPath, "utf-8");
|
|
24
|
+
return JSON.parse(content);
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Merge extracted content with existing dictionary, preserving translations.
|
|
31
|
+
* - Keys in extracted but not in existing: added with default locale only
|
|
32
|
+
* - Keys in both: preserve existing translations, update default locale value
|
|
33
|
+
* - Keys in existing but not in extracted: removed (no longer in source)
|
|
34
|
+
*/
|
|
35
|
+
const mergeWithExistingDictionary = (extractedContent, existingDictionary, defaultLocale) => {
|
|
36
|
+
const mergedContent = {};
|
|
37
|
+
const existingContent = existingDictionary?.content;
|
|
38
|
+
for (const [key, value] of Object.entries(extractedContent)) {
|
|
39
|
+
const existingEntry = existingContent?.[key];
|
|
40
|
+
if (existingEntry && existingEntry.nodeType === "translation" && existingEntry.translation) mergedContent[key] = {
|
|
41
|
+
nodeType: "translation",
|
|
42
|
+
translation: {
|
|
43
|
+
...existingEntry.translation,
|
|
44
|
+
[defaultLocale]: value
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
else mergedContent[key] = {
|
|
48
|
+
nodeType: "translation",
|
|
49
|
+
translation: { [defaultLocale]: value }
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return mergedContent;
|
|
53
|
+
};
|
|
54
|
+
const handleExtractedContent = async (result) => {
|
|
55
|
+
const { dictionaryKey, content, locale } = result;
|
|
56
|
+
try {
|
|
57
|
+
const dictionary = {
|
|
58
|
+
key: dictionaryKey,
|
|
59
|
+
content: mergeWithExistingDictionary(content, await readExistingDictionary(join(compilerDir, `${dictionaryKey}.content.json`)), locale),
|
|
60
|
+
filePath: join(relative(baseDir, compilerDir), `${dictionaryKey}.content.json`)
|
|
61
|
+
};
|
|
62
|
+
const writeResult = await writeContentDeclaration(dictionary, config, { newDictionariesPath: relative(baseDir, compilerDir) });
|
|
63
|
+
await buildDictionary([{
|
|
64
|
+
...dictionary,
|
|
65
|
+
filePath: relative(baseDir, writeResult.path)
|
|
66
|
+
}], config);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
console.error(`[intlayer] Failed to process extracted content for ${dictionaryKey}:`, error);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
defaultLocale: config.internationalization.defaultLocale,
|
|
73
|
+
onExtract: handleExtractedContent
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
export { getExtractPluginOptions };
|
|
79
|
+
//# sourceMappingURL=getExtractPluginOptions.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getExtractPluginOptions.mjs","names":["mergedContent: DictionaryContentMap","dictionary: Dictionary"],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { buildDictionary, writeContentDeclaration } from '@intlayer/chokidar';\nimport { getConfiguration } from '@intlayer/config';\nimport type { Dictionary } from '@intlayer/types';\nimport type {\n ExtractPluginOptions,\n ExtractResult,\n} from './babel-plugin-intlayer-extract';\n\n/**\n * Translation node structure used in dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\n/**\n * Dictionary content structure - map of keys to translation nodes\n */\ntype DictionaryContentMap = Record<string, TranslationNode>;\n\n/**\n * Get the options for the Intlayer Babel extraction plugin\n * This function loads the Intlayer configuration and sets up the onExtract callback\n * to write dictionaries to the filesystem.\n */\nexport const getExtractPluginOptions = (): ExtractPluginOptions => {\n const config = getConfiguration();\n const { baseDir } = config.content;\n const compilerDir = join(baseDir, config.compiler?.outputDir ?? 'compiler');\n\n /**\n * Read existing dictionary file if it exists\n */\n const readExistingDictionary = async (\n dictionaryPath: string\n ): Promise<Dictionary | null> => {\n try {\n if (!existsSync(dictionaryPath)) {\n return null;\n }\n const content = await readFile(dictionaryPath, 'utf-8');\n return JSON.parse(content) as Dictionary;\n } catch {\n return null;\n }\n };\n\n /**\n * Merge extracted content with existing dictionary, preserving translations.\n * - Keys in extracted but not in existing: added with default locale only\n * - Keys in both: preserve existing translations, update default locale value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\n const mergeWithExistingDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null,\n defaultLocale: string\n ): DictionaryContentMap => {\n const mergedContent: DictionaryContentMap = {};\n const existingContent = existingDictionary?.content as\n | DictionaryContentMap\n | undefined;\n\n for (const [key, value] of Object.entries(extractedContent)) {\n const existingEntry = existingContent?.[key];\n\n if (\n existingEntry &&\n existingEntry.nodeType === 'translation' &&\n existingEntry.translation\n ) {\n // Key exists in both - preserve existing translations, update default locale\n mergedContent[key] = {\n nodeType: 'translation',\n translation: {\n ...existingEntry.translation,\n [defaultLocale]: value,\n },\n };\n } else {\n // New key - add with default locale only\n mergedContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n }\n\n return mergedContent;\n };\n\n const handleExtractedContent = async (result: ExtractResult) => {\n const { dictionaryKey, content, locale } = result;\n\n try {\n const dictionaryPath = join(compilerDir, `${dictionaryKey}.content.json`);\n\n // Read existing dictionary to preserve translations\n const existingDictionary = await readExistingDictionary(dictionaryPath);\n\n // Merge extracted content with existing translations\n const mergedContent = mergeWithExistingDictionary(\n content,\n existingDictionary,\n locale\n );\n\n const dictionary: Dictionary = {\n key: dictionaryKey,\n content: mergedContent,\n filePath: join(\n relative(baseDir, compilerDir),\n `${dictionaryKey}.content.json`\n ),\n };\n\n const writeResult = await writeContentDeclaration(dictionary, config, {\n newDictionariesPath: relative(baseDir, compilerDir),\n });\n\n // Build the dictionary immediately\n const dictionaryToBuild: Dictionary = {\n ...dictionary,\n filePath: relative(baseDir, writeResult.path),\n };\n\n await buildDictionary([dictionaryToBuild], config);\n } catch (error) {\n console.error(\n `[intlayer] Failed to process extracted content for ${dictionaryKey}:`,\n error\n );\n }\n };\n\n return {\n defaultLocale: config.internationalization.defaultLocale,\n // filesList can be passed if needed, but usually handled by include/exclude in build tool\n onExtract: handleExtractedContent,\n };\n};\n"],"mappings":";;;;;;;;;;;;AA6BA,MAAa,gCAAsD;CACjE,MAAM,SAAS,kBAAkB;CACjC,MAAM,EAAE,YAAY,OAAO;CAC3B,MAAM,cAAc,KAAK,SAAS,OAAO,UAAU,aAAa,WAAW;;;;CAK3E,MAAM,yBAAyB,OAC7B,mBAC+B;AAC/B,MAAI;AACF,OAAI,CAAC,WAAW,eAAe,CAC7B,QAAO;GAET,MAAM,UAAU,MAAM,SAAS,gBAAgB,QAAQ;AACvD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN,UAAO;;;;;;;;;CAUX,MAAM,+BACJ,kBACA,oBACA,kBACyB;EACzB,MAAMA,gBAAsC,EAAE;EAC9C,MAAM,kBAAkB,oBAAoB;AAI5C,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,iBAAiB,EAAE;GAC3D,MAAM,gBAAgB,kBAAkB;AAExC,OACE,iBACA,cAAc,aAAa,iBAC3B,cAAc,YAGd,eAAc,OAAO;IACnB,UAAU;IACV,aAAa;KACX,GAAG,cAAc;MAChB,gBAAgB;KAClB;IACF;OAGD,eAAc,OAAO;IACnB,UAAU;IACV,aAAa,GACV,gBAAgB,OAClB;IACF;;AAIL,SAAO;;CAGT,MAAM,yBAAyB,OAAO,WAA0B;EAC9D,MAAM,EAAE,eAAe,SAAS,WAAW;AAE3C,MAAI;GAaF,MAAMC,aAAyB;IAC7B,KAAK;IACL,SARoB,4BACpB,SAJyB,MAAM,uBAHV,KAAK,aAAa,GAAG,cAAc,eAAe,CAGF,EAMrE,OACD;IAKC,UAAU,KACR,SAAS,SAAS,YAAY,EAC9B,GAAG,cAAc,eAClB;IACF;GAED,MAAM,cAAc,MAAM,wBAAwB,YAAY,QAAQ,EACpE,qBAAqB,SAAS,SAAS,YAAY,EACpD,CAAC;AAQF,SAAM,gBAAgB,CALgB;IACpC,GAAG;IACH,UAAU,SAAS,SAAS,YAAY,KAAK;IAC9C,CAEwC,EAAE,OAAO;WAC3C,OAAO;AACd,WAAQ,MACN,sDAAsD,cAAc,IACpE,MACD;;;AAIL,QAAO;EACL,eAAe,OAAO,qBAAqB;EAE3C,WAAW;EACZ"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { __require } from "./_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getConfiguration } from "@intlayer/config";
|
|
4
|
+
import fg from "fast-glob";
|
|
5
|
+
|
|
6
|
+
//#region src/getOptimizePluginOptions.ts
|
|
7
|
+
/**
|
|
8
|
+
* Load dictionaries from the dictionaries-entry package
|
|
9
|
+
*/
|
|
10
|
+
const loadDictionaries = (config) => {
|
|
11
|
+
try {
|
|
12
|
+
const { getDictionaries } = __require("@intlayer/dictionaries-entry");
|
|
13
|
+
const dictionariesRecord = getDictionaries(config);
|
|
14
|
+
return Object.values(dictionariesRecord);
|
|
15
|
+
} catch {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Get the options for the Intlayer Babel optimization plugin
|
|
21
|
+
* This function loads the Intlayer configuration and returns the paths
|
|
22
|
+
* needed for dictionary optimization and import rewriting.
|
|
23
|
+
*/
|
|
24
|
+
const getOptimizePluginOptions = (params) => {
|
|
25
|
+
const { configOptions, dictionaries: providedDictionaries, overrides } = params ?? {};
|
|
26
|
+
const config = getConfiguration(configOptions);
|
|
27
|
+
const { mainDir, baseDir, dictionariesDir, unmergedDictionariesDir, dynamicDictionariesDir, fetchDictionariesDir } = config.content;
|
|
28
|
+
const { importMode, traversePattern, optimize } = config.build;
|
|
29
|
+
const filesListPattern = fg.sync(traversePattern, { cwd: baseDir }).map((file) => join(baseDir, file));
|
|
30
|
+
const dictionariesEntryPath = join(mainDir, "dictionaries.mjs");
|
|
31
|
+
const unmergedDictionariesEntryPath = join(mainDir, "unmerged_dictionaries.mjs");
|
|
32
|
+
const dynamicDictionariesEntryPath = join(mainDir, "dynamic_dictionaries.mjs");
|
|
33
|
+
const fetchDictionariesEntryPath = join(mainDir, "fetch_dictionaries.mjs");
|
|
34
|
+
const filesList = [
|
|
35
|
+
...filesListPattern,
|
|
36
|
+
dictionariesEntryPath,
|
|
37
|
+
unmergedDictionariesEntryPath
|
|
38
|
+
];
|
|
39
|
+
return {
|
|
40
|
+
optimize,
|
|
41
|
+
dictionariesDir,
|
|
42
|
+
dictionariesEntryPath,
|
|
43
|
+
unmergedDictionariesDir,
|
|
44
|
+
unmergedDictionariesEntryPath,
|
|
45
|
+
dynamicDictionariesDir,
|
|
46
|
+
dynamicDictionariesEntryPath,
|
|
47
|
+
fetchDictionariesDir,
|
|
48
|
+
fetchDictionariesEntryPath,
|
|
49
|
+
replaceDictionaryEntry: true,
|
|
50
|
+
importMode,
|
|
51
|
+
liveSyncKeys: (providedDictionaries ?? loadDictionaries(config)).filter((dictionary) => dictionary.live).map((dictionary) => dictionary.key),
|
|
52
|
+
filesList,
|
|
53
|
+
...overrides
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
58
|
+
export { getOptimizePluginOptions };
|
|
59
|
+
//# sourceMappingURL=getOptimizePluginOptions.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getOptimizePluginOptions.mjs","names":[],"sources":["../../src/getOptimizePluginOptions.ts"],"sourcesContent":["import { join } from 'node:path';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport type { OptimizePluginOptions } from './babel-plugin-intlayer-optimize';\n\ntype GetOptimizePluginOptionsParams = {\n /**\n * Configuration options for loading intlayer config\n */\n configOptions?: GetConfigurationOptions;\n /**\n * Pre-loaded dictionaries (optional - will be loaded if not provided)\n */\n dictionaries?: Dictionary[];\n /**\n * Override specific options\n */\n overrides?: Partial<OptimizePluginOptions>;\n};\n\n/**\n * Load dictionaries from the dictionaries-entry package\n */\nconst loadDictionaries = (config: IntlayerConfig): Dictionary[] => {\n try {\n // Dynamic require to avoid build-time dependency issues\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { getDictionaries } = require('@intlayer/dictionaries-entry');\n const dictionariesRecord = getDictionaries(config) as Record<\n string,\n Dictionary\n >;\n return Object.values(dictionariesRecord);\n } catch {\n // If dictionaries-entry is not available, return empty array\n return [];\n }\n};\n\n/**\n * Get the options for the Intlayer Babel optimization plugin\n * This function loads the Intlayer configuration and returns the paths\n * needed for dictionary optimization and import rewriting.\n */\nexport const getOptimizePluginOptions = (\n params?: GetOptimizePluginOptionsParams\n): OptimizePluginOptions => {\n const {\n configOptions,\n dictionaries: providedDictionaries,\n overrides,\n } = params ?? {};\n\n const config = getConfiguration(configOptions);\n const {\n mainDir,\n baseDir,\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n } = config.content;\n const { importMode, traversePattern, optimize } = config.build;\n\n // Build files list from traverse pattern\n const filesListPattern = fg\n .sync(traversePattern, {\n cwd: baseDir,\n })\n .map((file) => join(baseDir, file));\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by an empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by an empty object if import made dynamic\n ];\n\n // Load dictionaries if not provided\n const dictionaries = providedDictionaries ?? loadDictionaries(config);\n\n const liveSyncKeys = dictionaries\n .filter((dictionary) => dictionary.live)\n .map((dictionary) => dictionary.key);\n\n return {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesDir,\n unmergedDictionariesEntryPath,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n replaceDictionaryEntry: true,\n importMode,\n liveSyncKeys,\n filesList,\n ...overrides,\n };\n};\n"],"mappings":";;;;;;;;;AA2BA,MAAM,oBAAoB,WAAyC;AACjE,KAAI;EAGF,MAAM,EAAE,8BAA4B,+BAA+B;EACnE,MAAM,qBAAqB,gBAAgB,OAAO;AAIlD,SAAO,OAAO,OAAO,mBAAmB;SAClC;AAEN,SAAO,EAAE;;;;;;;;AASb,MAAa,4BACX,WAC0B;CAC1B,MAAM,EACJ,eACA,cAAc,sBACd,cACE,UAAU,EAAE;CAEhB,MAAM,SAAS,iBAAiB,cAAc;CAC9C,MAAM,EACJ,SACA,SACA,iBACA,yBACA,wBACA,yBACE,OAAO;CACX,MAAM,EAAE,YAAY,iBAAiB,aAAa,OAAO;CAGzD,MAAM,mBAAmB,GACtB,KAAK,iBAAiB,EACrB,KAAK,SACN,CAAC,CACD,KAAK,SAAS,KAAK,SAAS,KAAK,CAAC;CAErC,MAAM,wBAAwB,KAAK,SAAS,mBAAmB;CAC/D,MAAM,gCAAgC,KACpC,SACA,4BACD;CACD,MAAM,+BAA+B,KACnC,SACA,2BACD;CACD,MAAM,6BAA6B,KAAK,SAAS,yBAAyB;CAE1E,MAAM,YAAY;EAChB,GAAG;EACH;EACA;EACD;AASD,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,wBAAwB;EACxB;EACA,eAlBmB,wBAAwB,iBAAiB,OAAO,EAGlE,QAAQ,eAAe,WAAW,KAAK,CACvC,KAAK,eAAe,WAAW,IAAI;EAepC;EACA,GAAG;EACJ"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { intlayerExtractBabelPlugin } from "./babel-plugin-intlayer-extract.mjs";
|
|
2
|
+
import { intlayerOptimizeBabelPlugin } from "./babel-plugin-intlayer-optimize.mjs";
|
|
3
|
+
import { getExtractPluginOptions } from "./getExtractPluginOptions.mjs";
|
|
4
|
+
import { getOptimizePluginOptions } from "./getOptimizePluginOptions.mjs";
|
|
2
5
|
|
|
3
|
-
export {
|
|
6
|
+
export { getExtractPluginOptions, getOptimizePluginOptions, intlayerExtractBabelPlugin, intlayerOptimizeBabelPlugin };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { PluginObj, PluginPass } from "@babel/core";
|
|
2
|
+
import * as BabelTypes from "@babel/types";
|
|
3
|
+
|
|
4
|
+
//#region src/babel-plugin-intlayer-extract.d.ts
|
|
5
|
+
type ExtractedContent = Record<string, string>;
|
|
6
|
+
/**
|
|
7
|
+
* Extracted content result from a file transformation
|
|
8
|
+
*/
|
|
9
|
+
type ExtractResult = {
|
|
10
|
+
/** Dictionary key derived from the file path */
|
|
11
|
+
dictionaryKey: string;
|
|
12
|
+
/** File path that was processed */
|
|
13
|
+
filePath: string;
|
|
14
|
+
/** Extracted content key-value pairs */
|
|
15
|
+
content: ExtractedContent;
|
|
16
|
+
/** Default locale used */
|
|
17
|
+
locale: string;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Options for the extraction Babel plugin
|
|
21
|
+
*/
|
|
22
|
+
type ExtractPluginOptions = {
|
|
23
|
+
/**
|
|
24
|
+
* The default locale for the extracted content
|
|
25
|
+
*/
|
|
26
|
+
defaultLocale?: string;
|
|
27
|
+
/**
|
|
28
|
+
* The package to import useIntlayer from
|
|
29
|
+
* @default 'react-intlayer'
|
|
30
|
+
*/
|
|
31
|
+
packageName?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Files list to traverse. If provided, only files in this list will be processed.
|
|
34
|
+
*/
|
|
35
|
+
filesList?: string[];
|
|
36
|
+
/**
|
|
37
|
+
* Custom function to determine if a string should be extracted
|
|
38
|
+
*/
|
|
39
|
+
shouldExtract?: (text: string) => boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Callback function called when content is extracted from a file.
|
|
42
|
+
* This allows the compiler to capture the extracted content and write it to files.
|
|
43
|
+
* The dictionary will be updated: new keys added, unused keys removed.
|
|
44
|
+
*/
|
|
45
|
+
onExtract?: (result: ExtractResult) => void;
|
|
46
|
+
};
|
|
47
|
+
type State = PluginPass & {
|
|
48
|
+
opts: ExtractPluginOptions;
|
|
49
|
+
/** Extracted content from this file */
|
|
50
|
+
_extractedContent?: ExtractedContent;
|
|
51
|
+
/** Set of existing keys to avoid duplicates */
|
|
52
|
+
_existingKeys?: Set<string>;
|
|
53
|
+
/** The dictionary key for this file */
|
|
54
|
+
_dictionaryKey?: string;
|
|
55
|
+
/** whether the current file is included in the filesList */
|
|
56
|
+
_isIncluded?: boolean;
|
|
57
|
+
/** Whether this file has JSX (React component) */
|
|
58
|
+
_hasJSX?: boolean;
|
|
59
|
+
/** Whether we already have useIntlayer imported */
|
|
60
|
+
_hasUseIntlayerImport?: boolean;
|
|
61
|
+
/** The local name for useIntlayer (in case it's aliased) */
|
|
62
|
+
_useIntlayerLocalName?: string;
|
|
63
|
+
/** The variable name to use for content (content or _compContent if content is already used) */
|
|
64
|
+
_contentVarName?: string;
|
|
65
|
+
/** Set of function start positions that have extracted content (only inject hooks into these) */
|
|
66
|
+
_functionsWithExtractedContent?: Set<number>;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Autonomous Babel plugin that extracts content and transforms JSX to use useIntlayer.
|
|
70
|
+
*
|
|
71
|
+
* This plugin:
|
|
72
|
+
* 1. Scans files for extractable text (JSX text, attributes)
|
|
73
|
+
* 2. Auto-injects useIntlayer import and hook call
|
|
74
|
+
* 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)
|
|
75
|
+
* 4. Replaces extractable strings with content references
|
|
76
|
+
*
|
|
77
|
+
* ## Input
|
|
78
|
+
* ```tsx
|
|
79
|
+
* export const MyComponent = () => {
|
|
80
|
+
* return <div>Hello World</div>;
|
|
81
|
+
* };
|
|
82
|
+
* ```
|
|
83
|
+
*
|
|
84
|
+
* ## Output
|
|
85
|
+
* ```tsx
|
|
86
|
+
* import { useIntlayer } from 'react-intlayer';
|
|
87
|
+
*
|
|
88
|
+
* export const MyComponent = () => {
|
|
89
|
+
* const content = useIntlayer('comp-my-component');
|
|
90
|
+
* return <div>{content.helloWorld}</div>;
|
|
91
|
+
* };
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* ## When useIntlayer is already present
|
|
95
|
+
*
|
|
96
|
+
* If the component already has a `content` variable from an existing `useIntlayer` call,
|
|
97
|
+
* the plugin will use `_compContent` to avoid naming conflicts:
|
|
98
|
+
*
|
|
99
|
+
* ### Input
|
|
100
|
+
* ```tsx
|
|
101
|
+
* export const Page = () => {
|
|
102
|
+
* const content = useIntlayer('page');
|
|
103
|
+
* return <div>{content.title} - Hello World</div>;
|
|
104
|
+
* };
|
|
105
|
+
* ```
|
|
106
|
+
*
|
|
107
|
+
* ### Output
|
|
108
|
+
* ```tsx
|
|
109
|
+
* export const Page = () => {
|
|
110
|
+
* const _compContent = useIntlayer('comp-page');
|
|
111
|
+
* const content = useIntlayer('page');
|
|
112
|
+
* return <div>{content.title} - {_compContent.helloWorld}</div>;
|
|
113
|
+
* };
|
|
114
|
+
* ```
|
|
115
|
+
*
|
|
116
|
+
* The extracted content is reported via the `onExtract` callback, allowing the
|
|
117
|
+
* compiler to write the dictionary to disk separately:
|
|
118
|
+
* ```json
|
|
119
|
+
* // my-component.content.json (written by compiler)
|
|
120
|
+
* {
|
|
121
|
+
* "key": "comp-my-component",
|
|
122
|
+
* "content": {
|
|
123
|
+
* "helloWorld": { "nodeType": "translation", "translation": { "en": "Hello World" } }
|
|
124
|
+
* }
|
|
125
|
+
* }
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
declare const intlayerExtractBabelPlugin: (babel: {
|
|
129
|
+
types: typeof BabelTypes;
|
|
130
|
+
}) => PluginObj<State>;
|
|
131
|
+
//#endregion
|
|
132
|
+
export { ExtractPluginOptions, ExtractResult, intlayerExtractBabelPlugin };
|
|
133
|
+
//# sourceMappingURL=babel-plugin-intlayer-extract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-extract.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":[],"mappings":";;;;KASK,gBAAA,GAAmB;;AAPwB;AAYhD;AAcY,KAdA,aAAA,GAcoB;EA0B3B;EAAQ,aAAA,EAAA,MAAA;EACL;EAEc,QAAA,EAAA,MAAA;EAEJ;EAciB,OAAA,EArDxB,gBAqDwB;EAAG;EAuFzB,MAAA,EAAA,MAAA;CACG;;;;KArIJ,oBAAA;;;;;;;;;;;;;;;;;;;;;;;uBAuBW;;KAGlB,KAAA,GAAQ;QACL;;sBAEc;;kBAEJ;;;;;;;;;;;;;;mCAciB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuFtB;gBACG;MACZ,UAAU"}
|