@intlayer/babel 5.8.1 → 6.0.0-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/babel-plugin-intlayer.cjs +47 -34
- package/dist/cjs/babel-plugin-intlayer.cjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer.mjs +47 -34
- package/dist/esm/babel-plugin-intlayer.mjs.map +1 -1
- package/dist/types/babel-plugin-intlayer.d.ts +70 -34
- package/dist/types/babel-plugin-intlayer.d.ts.map +1 -1
- package/package.json +9 -9
|
@@ -33,6 +33,7 @@ __export(babel_plugin_intlayer_exports, {
|
|
|
33
33
|
module.exports = __toCommonJS(babel_plugin_intlayer_exports);
|
|
34
34
|
var t = __toESM(require("@babel/types"));
|
|
35
35
|
var import_chokidar = require("@intlayer/chokidar");
|
|
36
|
+
var import_config = require("@intlayer/config");
|
|
36
37
|
var import_node_path = require("node:path");
|
|
37
38
|
const PACKAGE_LIST = [
|
|
38
39
|
"intlayer",
|
|
@@ -67,8 +68,8 @@ const STATIC_IMPORT_FUNCTION = {
|
|
|
67
68
|
getIntlayer: "getDictionary",
|
|
68
69
|
useIntlayer: "useDictionary"
|
|
69
70
|
};
|
|
70
|
-
const
|
|
71
|
-
useIntlayer: "
|
|
71
|
+
const FETCH_IMPORT_FUNCTION = {
|
|
72
|
+
useIntlayer: "useDictionaryDynamic"
|
|
72
73
|
};
|
|
73
74
|
const DYNAMIC_IMPORT_FUNCTION = {
|
|
74
75
|
useIntlayer: "useDictionaryDynamic"
|
|
@@ -77,10 +78,19 @@ const makeIdent = (key) => {
|
|
|
77
78
|
const hash = (0, import_chokidar.getFileHash)(key);
|
|
78
79
|
return t.identifier(`_${hash}`);
|
|
79
80
|
};
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
81
|
+
const computeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, importMode) => {
|
|
82
|
+
let relativePath = (0, import_node_path.join)(dictionariesDir, `${key}.json`);
|
|
83
|
+
if (importMode === "live") {
|
|
84
|
+
relativePath = (0, import_node_path.join)(fetchDictionariesDir, `${key}.mjs`);
|
|
85
|
+
}
|
|
86
|
+
if (importMode === "dynamic") {
|
|
87
|
+
relativePath = (0, import_node_path.join)(dynamicDictionariesDir, `${key}.mjs`);
|
|
88
|
+
}
|
|
89
|
+
let rel = (0, import_node_path.relative)((0, import_node_path.dirname)(fromFile), relativePath);
|
|
90
|
+
rel = (0, import_config.normalizePath)(rel);
|
|
91
|
+
if (!rel.startsWith("./") && !rel.startsWith("../")) {
|
|
92
|
+
rel = `./${rel}`;
|
|
93
|
+
}
|
|
84
94
|
return rel;
|
|
85
95
|
};
|
|
86
96
|
const intlayerBabelPlugin = () => {
|
|
@@ -93,7 +103,6 @@ const intlayerBabelPlugin = () => {
|
|
|
93
103
|
this._hasValidImport = false;
|
|
94
104
|
this._isDictEntry = false;
|
|
95
105
|
this._useDynamicHelpers = false;
|
|
96
|
-
this._useAsyncHelpers = false;
|
|
97
106
|
const filename = this.file.opts.filename;
|
|
98
107
|
if (this.opts.filesList && filename) {
|
|
99
108
|
const isIncluded = this.opts.filesList.includes(filename);
|
|
@@ -124,15 +133,16 @@ const intlayerBabelPlugin = () => {
|
|
|
124
133
|
const file = state.file.opts.filename;
|
|
125
134
|
const dictionariesDir = state.opts.dictionariesDir;
|
|
126
135
|
const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
|
|
136
|
+
const fetchDictionariesDir = state.opts.fetchDictionariesDir;
|
|
127
137
|
const imports = [];
|
|
128
138
|
for (const [key, ident] of state._newStaticImports) {
|
|
129
|
-
const rel =
|
|
139
|
+
const rel = computeImport(
|
|
130
140
|
file,
|
|
131
141
|
dictionariesDir,
|
|
132
142
|
dynamicDictionariesDir,
|
|
143
|
+
fetchDictionariesDir,
|
|
133
144
|
key,
|
|
134
|
-
|
|
135
|
-
// Always static
|
|
145
|
+
"static"
|
|
136
146
|
);
|
|
137
147
|
const importDeclarationNode = t.importDeclaration(
|
|
138
148
|
[t.importDefaultSpecifier(t.identifier(ident.name))],
|
|
@@ -144,13 +154,16 @@ const intlayerBabelPlugin = () => {
|
|
|
144
154
|
imports.push(importDeclarationNode);
|
|
145
155
|
}
|
|
146
156
|
for (const [key, ident] of state._newDynamicImports) {
|
|
147
|
-
const
|
|
157
|
+
const modeForThisIdent = ident.name.endsWith(
|
|
158
|
+
"_fetch"
|
|
159
|
+
) ? "live" : "dynamic";
|
|
160
|
+
const rel = computeImport(
|
|
148
161
|
file,
|
|
149
162
|
dictionariesDir,
|
|
150
163
|
dynamicDictionariesDir,
|
|
164
|
+
fetchDictionariesDir,
|
|
151
165
|
key,
|
|
152
|
-
|
|
153
|
-
// Always dynamic
|
|
166
|
+
modeForThisIdent
|
|
154
167
|
);
|
|
155
168
|
imports.push(
|
|
156
169
|
t.importDeclaration(
|
|
@@ -183,21 +196,12 @@ const intlayerBabelPlugin = () => {
|
|
|
183
196
|
if (!t.isImportSpecifier(spec)) continue;
|
|
184
197
|
const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
|
|
185
198
|
const importMode = state.opts.importMode;
|
|
186
|
-
const shouldUseDynamicHelpers = importMode === "dynamic" && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
187
|
-
const shouldUseAsyncHelpers = importMode === "async" && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
199
|
+
const shouldUseDynamicHelpers = (importMode === "dynamic" || importMode === "live") && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
188
200
|
if (shouldUseDynamicHelpers) {
|
|
189
201
|
state._useDynamicHelpers = true;
|
|
190
202
|
}
|
|
191
|
-
if (shouldUseAsyncHelpers) {
|
|
192
|
-
state._useAsyncHelpers = true;
|
|
193
|
-
}
|
|
194
203
|
let helperMap;
|
|
195
|
-
if (
|
|
196
|
-
helperMap = {
|
|
197
|
-
...STATIC_IMPORT_FUNCTION,
|
|
198
|
-
...ASYNC_IMPORT_FUNCTION
|
|
199
|
-
};
|
|
200
|
-
} else if (shouldUseDynamicHelpers) {
|
|
204
|
+
if (shouldUseDynamicHelpers) {
|
|
201
205
|
helperMap = {
|
|
202
206
|
...STATIC_IMPORT_FUNCTION,
|
|
203
207
|
...DYNAMIC_IMPORT_FUNCTION
|
|
@@ -221,23 +225,32 @@ const intlayerBabelPlugin = () => {
|
|
|
221
225
|
const arg = path.node.arguments[0];
|
|
222
226
|
if (!arg || !t.isStringLiteral(arg)) return;
|
|
223
227
|
const key = arg.value;
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
+
const importMode = state.opts.importMode;
|
|
229
|
+
const isUseIntlayer = callee.name === "useIntlayer";
|
|
230
|
+
const useDynamicHelpers = Boolean(state._useDynamicHelpers);
|
|
231
|
+
let perCallMode = "static";
|
|
232
|
+
if (isUseIntlayer && useDynamicHelpers) {
|
|
233
|
+
if (importMode === "dynamic") {
|
|
234
|
+
perCallMode = "dynamic";
|
|
235
|
+
} else if (importMode === "live") {
|
|
236
|
+
const liveKeys = state.opts.liveSyncKeys ?? [];
|
|
237
|
+
perCallMode = liveKeys.includes(key) ? "live" : "dynamic";
|
|
238
|
+
}
|
|
239
|
+
}
|
|
228
240
|
let ident;
|
|
229
|
-
if (
|
|
241
|
+
if (perCallMode === "live") {
|
|
230
242
|
let dynamicIdent = state._newDynamicImports.get(key);
|
|
231
243
|
if (!dynamicIdent) {
|
|
232
244
|
const hash = (0, import_chokidar.getFileHash)(key);
|
|
233
|
-
dynamicIdent = t.identifier(`_${hash}
|
|
245
|
+
dynamicIdent = t.identifier(`_${hash}_fetch`);
|
|
234
246
|
state._newDynamicImports.set(key, dynamicIdent);
|
|
235
247
|
}
|
|
236
248
|
ident = dynamicIdent;
|
|
237
|
-
path.node.arguments
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
249
|
+
path.node.arguments = [
|
|
250
|
+
t.identifier(ident.name),
|
|
251
|
+
...path.node.arguments
|
|
252
|
+
];
|
|
253
|
+
} else if (perCallMode === "dynamic") {
|
|
241
254
|
let dynamicIdent = state._newDynamicImports.get(key);
|
|
242
255
|
if (!dynamicIdent) {
|
|
243
256
|
const hash = (0, import_chokidar.getFileHash)(key);
|
|
@@ -1 +1 @@
|
|
|
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/**\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 ASYNC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryAsync',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: 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' | 'async';\n /**\n * Files list to traverse.\n */\n filesList?: string[];\n };\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: 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 /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether async helpers are active for this file */\n _useAsyncHelpers?: 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 dictionariesDir: string,\n dynamicDictionariesDir: string,\n key: string,\n isDynamic = false\n): string => {\n const jsonPath = isDynamic\n ? join(dynamicDictionariesDir, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\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 *\n * This means cases like:\n *\n * ```ts\n * import { getIntlayer } from 'intlayer';\n * import { useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer('app');\n * const content2 = useIntlayer('app');\n * ```\n *\n * will be transformed into:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { getDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash)\n * ```\n *\n * If the `importMode = \"dynamic\"` option:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';\n *\n * import { useDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash_dyn, 'app');\n * ```\n *\n * Or if the `importMode = \"async\"` option:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { useDictionaryAsync as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = await useIntlayer(_dicHash_dyn);\n * ```\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\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 this._useAsyncHelpers = false;\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 /* 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 (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\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 if (!state._isIncluded) return; // early-out if file is not included\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n // Generate static imports (for getIntlayer and useIntlayer when not using dynamic)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n false // Always static\n );\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic imports (for useIntlayer when using dynamic helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n true // Always dynamic\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('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.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, ...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 const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers. We\n // only switch to the dynamic helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the dynamic\n // helpers.\n const shouldUseDynamicHelpers =\n importMode === 'dynamic' &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Determine whether this import should use the async helpers. We\n // only switch to the async helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the async\n // helpers.\n const shouldUseAsyncHelpers =\n importMode === 'async' && 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 // Remember for later (CallExpression) whether we are using the async helpers\n if (shouldUseAsyncHelpers) {\n state._useAsyncHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseAsyncHelpers) {\n // Use async helpers for useIntlayer when async mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...ASYNC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\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 const useDynamic = Boolean(state._useDynamicHelpers);\n const useAsync = Boolean(state._useAsyncHelpers);\n\n // Determine if this specific call should use dynamic imports\n const shouldUseDynamicForThisCall =\n callee.name === 'useIntlayer' && useDynamic;\n\n // Determine if this specific call should use async imports\n const shouldUseAsyncForThisCall =\n callee.name === 'useIntlayer' && useAsync;\n\n let ident: t.Identifier;\n\n if (shouldUseAsyncForThisCall) {\n // Use dynamic imports for useIntlayer when async helpers are enabled\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 // Async helper: first argument is the dictionary promise.\n path.node.arguments[0] = t.identifier(ident.name);\n\n // Wrap the call with await for async helpers\n const awaitExpression = t.awaitExpression(path.node);\n path.replaceWith(awaitExpression);\n } else if (shouldUseDynamicForThisCall) {\n // Use dynamic imports for useIntlayer when dynamic helpers are enabled\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);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\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;AAKjD,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,yBAAyB;AAAA,EAC7B,aAAa;AAAA,EACb,aAAa;AACf;AAEA,MAAM,wBAAwB;AAAA,EAC5B,aAAa;AACf;AAEA,MAAM,0BAA0B;AAAA,EAC9B,aAAa;AACf;AAwDA,MAAM,YAAY,CAAC,QAA8B;AAC/C,QAAM,WAAO,6BAAY,GAAG;AAC5B,SAAO,EAAE,WAAW,IAAI,IAAI,EAAE;AAChC;AAEA,MAAM,wBAAwB,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A,EACF;AACF;","names":[]}
|
|
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 { normalizePath } from '@intlayer/config';\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/**\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 FETCH_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 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 /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: 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 /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: 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 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 import.\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 intlayerBabelPlugin = (): PluginObj<State> => {\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 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 /* 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 (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\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 if (!state._isIncluded) return; // early-out if file is not included\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: t.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('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.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, ...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 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\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 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: t.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);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,QAAmB;AACnB,sBAA4B;AAC5B,oBAA8B;AAC9B,uBAAwC;AAIxC,MAAM,eAAe;AAAA,EACnB;AAAA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IAAI,IAAI,QAAQ;AAC5C,kBAAM,mBAAoB,IAAI,KAAK,YAAY;AAAA,UACjD;AACA,kBAAQ;AAGR,eAAK,KAAK,YAAY;AAAA,YACpB,EAAE,WAAW,MAAM,IAAI;AAAA,YACvB,GAAG,KAAK,KAAK;AAAA,UACf;AAAA,QACF,WAAW,gBAAgB,WAAW;AAEpC,cAAI,eAAe,MAAM,mBAAoB,IAAI,GAAG;AACpD,cAAI,CAAC,cAAc;AAEjB,kBAAM,WAAO,6BAAY,GAAG;AAC5B,2BAAe,EAAE,WAAW,IAAI,IAAI,MAAM;AAC1C,kBAAM,mBAAoB,IAAI,KAAK,YAAY;AAAA,UACjD;AACA,kBAAQ;AAGR,eAAK,KAAK,YAAY;AAAA,YACpB,EAAE,WAAW,MAAM,IAAI;AAAA,YACvB,GAAG,KAAK,KAAK;AAAA,UACf;AAAA,QACF,OAAO;AAEL,cAAI,cAAc,MAAM,kBAAmB,IAAI,GAAG;AAClD,cAAI,CAAC,aAAa;AAChB,0BAAc,UAAU,GAAG;AAC3B,kBAAM,kBAAmB,IAAI,KAAK,WAAW;AAAA,UAC/C;AACA,kBAAQ;AAGR,eAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as t from "@babel/types";
|
|
2
2
|
import { getFileHash } from "@intlayer/chokidar";
|
|
3
|
+
import { normalizePath } from "@intlayer/config";
|
|
3
4
|
import { dirname, join, relative } from "node:path";
|
|
4
5
|
const PACKAGE_LIST = [
|
|
5
6
|
"intlayer",
|
|
@@ -34,8 +35,8 @@ const STATIC_IMPORT_FUNCTION = {
|
|
|
34
35
|
getIntlayer: "getDictionary",
|
|
35
36
|
useIntlayer: "useDictionary"
|
|
36
37
|
};
|
|
37
|
-
const
|
|
38
|
-
useIntlayer: "
|
|
38
|
+
const FETCH_IMPORT_FUNCTION = {
|
|
39
|
+
useIntlayer: "useDictionaryDynamic"
|
|
39
40
|
};
|
|
40
41
|
const DYNAMIC_IMPORT_FUNCTION = {
|
|
41
42
|
useIntlayer: "useDictionaryDynamic"
|
|
@@ -44,10 +45,19 @@ const makeIdent = (key) => {
|
|
|
44
45
|
const hash = getFileHash(key);
|
|
45
46
|
return t.identifier(`_${hash}`);
|
|
46
47
|
};
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
const computeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, importMode) => {
|
|
49
|
+
let relativePath = join(dictionariesDir, `${key}.json`);
|
|
50
|
+
if (importMode === "live") {
|
|
51
|
+
relativePath = join(fetchDictionariesDir, `${key}.mjs`);
|
|
52
|
+
}
|
|
53
|
+
if (importMode === "dynamic") {
|
|
54
|
+
relativePath = join(dynamicDictionariesDir, `${key}.mjs`);
|
|
55
|
+
}
|
|
56
|
+
let rel = relative(dirname(fromFile), relativePath);
|
|
57
|
+
rel = normalizePath(rel);
|
|
58
|
+
if (!rel.startsWith("./") && !rel.startsWith("../")) {
|
|
59
|
+
rel = `./${rel}`;
|
|
60
|
+
}
|
|
51
61
|
return rel;
|
|
52
62
|
};
|
|
53
63
|
const intlayerBabelPlugin = () => {
|
|
@@ -60,7 +70,6 @@ const intlayerBabelPlugin = () => {
|
|
|
60
70
|
this._hasValidImport = false;
|
|
61
71
|
this._isDictEntry = false;
|
|
62
72
|
this._useDynamicHelpers = false;
|
|
63
|
-
this._useAsyncHelpers = false;
|
|
64
73
|
const filename = this.file.opts.filename;
|
|
65
74
|
if (this.opts.filesList && filename) {
|
|
66
75
|
const isIncluded = this.opts.filesList.includes(filename);
|
|
@@ -91,15 +100,16 @@ const intlayerBabelPlugin = () => {
|
|
|
91
100
|
const file = state.file.opts.filename;
|
|
92
101
|
const dictionariesDir = state.opts.dictionariesDir;
|
|
93
102
|
const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
|
|
103
|
+
const fetchDictionariesDir = state.opts.fetchDictionariesDir;
|
|
94
104
|
const imports = [];
|
|
95
105
|
for (const [key, ident] of state._newStaticImports) {
|
|
96
|
-
const rel =
|
|
106
|
+
const rel = computeImport(
|
|
97
107
|
file,
|
|
98
108
|
dictionariesDir,
|
|
99
109
|
dynamicDictionariesDir,
|
|
110
|
+
fetchDictionariesDir,
|
|
100
111
|
key,
|
|
101
|
-
|
|
102
|
-
// Always static
|
|
112
|
+
"static"
|
|
103
113
|
);
|
|
104
114
|
const importDeclarationNode = t.importDeclaration(
|
|
105
115
|
[t.importDefaultSpecifier(t.identifier(ident.name))],
|
|
@@ -111,13 +121,16 @@ const intlayerBabelPlugin = () => {
|
|
|
111
121
|
imports.push(importDeclarationNode);
|
|
112
122
|
}
|
|
113
123
|
for (const [key, ident] of state._newDynamicImports) {
|
|
114
|
-
const
|
|
124
|
+
const modeForThisIdent = ident.name.endsWith(
|
|
125
|
+
"_fetch"
|
|
126
|
+
) ? "live" : "dynamic";
|
|
127
|
+
const rel = computeImport(
|
|
115
128
|
file,
|
|
116
129
|
dictionariesDir,
|
|
117
130
|
dynamicDictionariesDir,
|
|
131
|
+
fetchDictionariesDir,
|
|
118
132
|
key,
|
|
119
|
-
|
|
120
|
-
// Always dynamic
|
|
133
|
+
modeForThisIdent
|
|
121
134
|
);
|
|
122
135
|
imports.push(
|
|
123
136
|
t.importDeclaration(
|
|
@@ -150,21 +163,12 @@ const intlayerBabelPlugin = () => {
|
|
|
150
163
|
if (!t.isImportSpecifier(spec)) continue;
|
|
151
164
|
const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
|
|
152
165
|
const importMode = state.opts.importMode;
|
|
153
|
-
const shouldUseDynamicHelpers = importMode === "dynamic" && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
154
|
-
const shouldUseAsyncHelpers = importMode === "async" && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
166
|
+
const shouldUseDynamicHelpers = (importMode === "dynamic" || importMode === "live") && PACKAGE_LIST_DYNAMIC.includes(src);
|
|
155
167
|
if (shouldUseDynamicHelpers) {
|
|
156
168
|
state._useDynamicHelpers = true;
|
|
157
169
|
}
|
|
158
|
-
if (shouldUseAsyncHelpers) {
|
|
159
|
-
state._useAsyncHelpers = true;
|
|
160
|
-
}
|
|
161
170
|
let helperMap;
|
|
162
|
-
if (
|
|
163
|
-
helperMap = {
|
|
164
|
-
...STATIC_IMPORT_FUNCTION,
|
|
165
|
-
...ASYNC_IMPORT_FUNCTION
|
|
166
|
-
};
|
|
167
|
-
} else if (shouldUseDynamicHelpers) {
|
|
171
|
+
if (shouldUseDynamicHelpers) {
|
|
168
172
|
helperMap = {
|
|
169
173
|
...STATIC_IMPORT_FUNCTION,
|
|
170
174
|
...DYNAMIC_IMPORT_FUNCTION
|
|
@@ -188,23 +192,32 @@ const intlayerBabelPlugin = () => {
|
|
|
188
192
|
const arg = path.node.arguments[0];
|
|
189
193
|
if (!arg || !t.isStringLiteral(arg)) return;
|
|
190
194
|
const key = arg.value;
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
+
const importMode = state.opts.importMode;
|
|
196
|
+
const isUseIntlayer = callee.name === "useIntlayer";
|
|
197
|
+
const useDynamicHelpers = Boolean(state._useDynamicHelpers);
|
|
198
|
+
let perCallMode = "static";
|
|
199
|
+
if (isUseIntlayer && useDynamicHelpers) {
|
|
200
|
+
if (importMode === "dynamic") {
|
|
201
|
+
perCallMode = "dynamic";
|
|
202
|
+
} else if (importMode === "live") {
|
|
203
|
+
const liveKeys = state.opts.liveSyncKeys ?? [];
|
|
204
|
+
perCallMode = liveKeys.includes(key) ? "live" : "dynamic";
|
|
205
|
+
}
|
|
206
|
+
}
|
|
195
207
|
let ident;
|
|
196
|
-
if (
|
|
208
|
+
if (perCallMode === "live") {
|
|
197
209
|
let dynamicIdent = state._newDynamicImports.get(key);
|
|
198
210
|
if (!dynamicIdent) {
|
|
199
211
|
const hash = getFileHash(key);
|
|
200
|
-
dynamicIdent = t.identifier(`_${hash}
|
|
212
|
+
dynamicIdent = t.identifier(`_${hash}_fetch`);
|
|
201
213
|
state._newDynamicImports.set(key, dynamicIdent);
|
|
202
214
|
}
|
|
203
215
|
ident = dynamicIdent;
|
|
204
|
-
path.node.arguments
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
216
|
+
path.node.arguments = [
|
|
217
|
+
t.identifier(ident.name),
|
|
218
|
+
...path.node.arguments
|
|
219
|
+
];
|
|
220
|
+
} else if (perCallMode === "dynamic") {
|
|
208
221
|
let dynamicIdent = state._newDynamicImports.get(key);
|
|
209
222
|
if (!dynamicIdent) {
|
|
210
223
|
const hash = getFileHash(key);
|
|
@@ -1 +1 @@
|
|
|
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/**\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 ASYNC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryAsync',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: 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' | 'async';\n /**\n * Files list to traverse.\n */\n filesList?: string[];\n };\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: 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 /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether async helpers are active for this file */\n _useAsyncHelpers?: 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 dictionariesDir: string,\n dynamicDictionariesDir: string,\n key: string,\n isDynamic = false\n): string => {\n const jsonPath = isDynamic\n ? join(dynamicDictionariesDir, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\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 *\n * This means cases like:\n *\n * ```ts\n * import { getIntlayer } from 'intlayer';\n * import { useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer('app');\n * const content2 = useIntlayer('app');\n * ```\n *\n * will be transformed into:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { getDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash)\n * ```\n *\n * If the `importMode = \"dynamic\"` option:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';\n *\n * import { useDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash_dyn, 'app');\n * ```\n *\n * Or if the `importMode = \"async\"` option:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { useDictionaryAsync as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = await useIntlayer(_dicHash_dyn);\n * ```\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\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 this._useAsyncHelpers = false;\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 /* 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 (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\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 if (!state._isIncluded) return; // early-out if file is not included\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n // Generate static imports (for getIntlayer and useIntlayer when not using dynamic)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n false // Always static\n );\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic imports (for useIntlayer when using dynamic helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n true // Always dynamic\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('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.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, ...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 const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers. We\n // only switch to the dynamic helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the dynamic\n // helpers.\n const shouldUseDynamicHelpers =\n importMode === 'dynamic' &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Determine whether this import should use the async helpers. We\n // only switch to the async helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the async\n // helpers.\n const shouldUseAsyncHelpers =\n importMode === 'async' && 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 // Remember for later (CallExpression) whether we are using the async helpers\n if (shouldUseAsyncHelpers) {\n state._useAsyncHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseAsyncHelpers) {\n // Use async helpers for useIntlayer when async mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...ASYNC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\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 const useDynamic = Boolean(state._useDynamicHelpers);\n const useAsync = Boolean(state._useAsyncHelpers);\n\n // Determine if this specific call should use dynamic imports\n const shouldUseDynamicForThisCall =\n callee.name === 'useIntlayer' && useDynamic;\n\n // Determine if this specific call should use async imports\n const shouldUseAsyncForThisCall =\n callee.name === 'useIntlayer' && useAsync;\n\n let ident: t.Identifier;\n\n if (shouldUseAsyncForThisCall) {\n // Use dynamic imports for useIntlayer when async helpers are enabled\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 // Async helper: first argument is the dictionary promise.\n path.node.arguments[0] = t.identifier(ident.name);\n\n // Wrap the call with await for async helpers\n const awaitExpression = t.awaitExpression(path.node);\n path.replaceWith(awaitExpression);\n } else if (shouldUseDynamicForThisCall) {\n // Use dynamic imports for useIntlayer when dynamic helpers are enabled\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);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\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;AAKjD,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,yBAAyB;A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,cAAI,cAAc,MAAM,kBAAmB,IAAI,GAAG;AAClD,cAAI,CAAC,aAAa;AAChB,0BAAc,UAAU,GAAG;AAC3B,kBAAM,kBAAmB,IAAI,KAAK,WAAW;AAAA,UAC/C;AACA,kBAAQ;AAGR,eAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
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 { normalizePath } from '@intlayer/config';\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/**\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 FETCH_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 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 /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: 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 /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: 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 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 import.\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 intlayerBabelPlugin = (): PluginObj<State> => {\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 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 /* 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 (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\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 if (!state._isIncluded) return; // early-out if file is not included\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: t.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('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.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, ...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 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\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 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: t.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);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n },\n };\n};\n"],"mappings":"AACA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,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;AAKjD,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,yBAAyB;AAAA,EAC7B,aAAa;AAAA,EACb,aAAa;AACf;AAEA,MAAM,wBAAwB;AAAA,EAC5B,aAAa;AACf;AAEA,MAAM,0BAA0B;AAAA,EAC9B,aAAa;AACf;AAmEA,MAAM,YAAY,CAAC,QAA8B;AAC/C,QAAM,OAAO,YAAY,GAAG;AAC5B,SAAO,EAAE,WAAW,IAAI,IAAI,EAAE;AAChC;AAEA,MAAM,gBAAgB,CACpB,UACA,iBACA,wBACA,sBACA,KACA,eACW;AACX,MAAI,eAAe,KAAK,iBAAiB,GAAG,GAAG,OAAO;AAEtD,MAAI,eAAe,QAAQ;AACzB,mBAAe,KAAK,sBAAsB,GAAG,GAAG,MAAM;AAAA,EACxD;AAEA,MAAI,eAAe,WAAW;AAC5B,mBAAe,KAAK,wBAAwB,GAAG,GAAG,MAAM;AAAA,EAC1D;AAEA,MAAI,MAAM,SAAS,QAAQ,QAAQ,GAAG,YAAY;AAGlD,QAAM,cAAc,GAAG;AAGvB,MAAI,CAAC,IAAI,WAAW,IAAI,KAAK,CAAC,IAAI,WAAW,KAAK,GAAG;AAC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SAAS,GAAG,IAAI,SAAS;AAAA,UAClD;AAAA,QACF;AAEA,YAAI;AAEJ,YAAI,gBAAgB,QAAQ;AAE1B,cAAI,eAAe,MAAM,mBAAoB,IAAI,GAAG;AACpD,cAAI,CAAC,cAAc;AACjB,kBAAM,OAAO,YAAY,GAAG;AAC5B,2BAAe,EAAE,WAAW,IAAI,IAAI,QAAQ;AAC5C,kBAAM,mBAAoB,IAAI,KAAK,YAAY;AAAA,UACjD;AACA,kBAAQ;AAGR,eAAK,KAAK,YAAY;AAAA,YACpB,EAAE,WAAW,MAAM,IAAI;AAAA,YACvB,GAAG,KAAK,KAAK;AAAA,UACf;AAAA,QACF,WAAW,gBAAgB,WAAW;AAEpC,cAAI,eAAe,MAAM,mBAAoB,IAAI,GAAG;AACpD,cAAI,CAAC,cAAc;AAEjB,kBAAM,OAAO,YAAY,GAAG;AAC5B,2BAAe,EAAE,WAAW,IAAI,IAAI,MAAM;AAC1C,kBAAM,mBAAoB,IAAI,KAAK,YAAY;AAAA,UACjD;AACA,kBAAQ;AAGR,eAAK,KAAK,YAAY;AAAA,YACpB,EAAE,WAAW,MAAM,IAAI;AAAA,YACvB,GAAG,KAAK,KAAK;AAAA,UACf;AAAA,QACF,OAAO;AAEL,cAAI,cAAc,MAAM,kBAAmB,IAAI,GAAG;AAClD,cAAI,CAAC,aAAa;AAChB,0BAAc,UAAU,GAAG;AAC3B,kBAAM,kBAAmB,IAAI,KAAK,WAAW;AAAA,UAC/C;AACA,kBAAQ;AAGR,eAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -18,18 +18,31 @@ type State = PluginPass & {
|
|
|
18
18
|
* The path to the dynamic dictionaries entry file.
|
|
19
19
|
*/
|
|
20
20
|
dynamicDictionariesEntryPath: string;
|
|
21
|
+
/**
|
|
22
|
+
* The path to the fetch dictionaries directory.
|
|
23
|
+
*/
|
|
24
|
+
fetchDictionariesDir: string;
|
|
25
|
+
/**
|
|
26
|
+
* The path to the fetch dictionaries entry file.
|
|
27
|
+
*/
|
|
28
|
+
fetchDictionariesEntryPath: string;
|
|
21
29
|
/**
|
|
22
30
|
* If true, the plugin will replace the dictionary entry file with `export default {}`.
|
|
23
31
|
*/
|
|
24
|
-
replaceDictionaryEntry
|
|
32
|
+
replaceDictionaryEntry: boolean;
|
|
25
33
|
/**
|
|
26
34
|
* If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.
|
|
27
35
|
*/
|
|
28
|
-
importMode
|
|
36
|
+
importMode: 'static' | 'dynamic' | 'live';
|
|
37
|
+
/**
|
|
38
|
+
* Activate the live sync of the dictionaries.
|
|
39
|
+
* If `importMode` is `live`, the plugin will activate the live sync of the dictionaries.
|
|
40
|
+
*/
|
|
41
|
+
liveSyncKeys: string[];
|
|
29
42
|
/**
|
|
30
43
|
* Files list to traverse.
|
|
31
44
|
*/
|
|
32
|
-
filesList
|
|
45
|
+
filesList: string[];
|
|
33
46
|
};
|
|
34
47
|
/** map key → generated ident (per-file) for static imports */
|
|
35
48
|
_newStaticImports?: Map<string, t.Identifier>;
|
|
@@ -41,64 +54,87 @@ type State = PluginPass & {
|
|
|
41
54
|
_isDictEntry?: boolean;
|
|
42
55
|
/** whether dynamic helpers are active for this file */
|
|
43
56
|
_useDynamicHelpers?: boolean;
|
|
44
|
-
/** whether async helpers are active for this file */
|
|
45
|
-
_useAsyncHelpers?: boolean;
|
|
46
57
|
};
|
|
47
58
|
/**
|
|
48
|
-
* Babel plugin that transforms
|
|
49
|
-
*
|
|
59
|
+
* Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.
|
|
60
|
+
*
|
|
61
|
+
* This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer
|
|
62
|
+
* packages into optimized dictionary access patterns, automatically importing the required
|
|
63
|
+
* dictionary files based on the configured import mode.
|
|
50
64
|
*
|
|
65
|
+
* ## Supported Input Patterns
|
|
51
66
|
*
|
|
52
|
-
*
|
|
67
|
+
* The plugin recognizes these function calls:
|
|
53
68
|
*
|
|
54
69
|
* ```ts
|
|
55
|
-
*
|
|
70
|
+
* // useIntlayer
|
|
56
71
|
* import { useIntlayer } from 'react-intlayer';
|
|
72
|
+
* import { useIntlayer } from 'next-intlayer';
|
|
57
73
|
*
|
|
58
|
-
* //
|
|
74
|
+
* // getIntlayer
|
|
75
|
+
* import { getIntlayer } from 'intlayer';
|
|
59
76
|
*
|
|
60
|
-
*
|
|
61
|
-
* const
|
|
77
|
+
* // Usage
|
|
78
|
+
* const content = useIntlayer('app');
|
|
79
|
+
* const content = getIntlayer('app');
|
|
62
80
|
* ```
|
|
63
81
|
*
|
|
64
|
-
*
|
|
82
|
+
* ## Transformation Modes
|
|
83
|
+
*
|
|
84
|
+
* ### Static Mode (default: `importMode = "static"`)
|
|
65
85
|
*
|
|
86
|
+
* Imports JSON dictionaries directly and replaces function calls with dictionary access:
|
|
87
|
+
*
|
|
88
|
+
* **Output:**
|
|
66
89
|
* ```ts
|
|
67
|
-
* import _dicHash from '../../.intlayer/dictionaries/app.
|
|
90
|
+
* import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
|
|
91
|
+
* import { useDictionary as useIntlayer } from 'react-intlayer';
|
|
68
92
|
* import { getDictionary as getIntlayer } from 'intlayer';
|
|
69
|
-
* import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
|
|
70
|
-
*
|
|
71
|
-
* // ...
|
|
72
93
|
*
|
|
73
|
-
* const content1 =
|
|
74
|
-
* const content2 =
|
|
94
|
+
* const content1 = useIntlayer(_dicHash);
|
|
95
|
+
* const content2 = getIntlayer(_dicHash);
|
|
75
96
|
* ```
|
|
76
97
|
*
|
|
77
|
-
*
|
|
98
|
+
* ### Dynamic Mode (`importMode = "dynamic"`)
|
|
78
99
|
*
|
|
79
|
-
*
|
|
80
|
-
* import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';
|
|
81
|
-
* import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';
|
|
100
|
+
* Uses dynamic dictionary loading with Suspense support:
|
|
82
101
|
*
|
|
83
|
-
*
|
|
102
|
+
* **Output:**
|
|
103
|
+
* ```ts
|
|
104
|
+
* import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
|
|
105
|
+
* import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';
|
|
84
106
|
* import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
|
|
107
|
+
* import { getDictionary as getIntlayer } from 'intlayer';
|
|
85
108
|
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
* const content1 = getIntlayer(_dicHash);
|
|
89
|
-
* const content2 = useIntlayer(_dicHash_dyn, 'app');
|
|
109
|
+
* const content1 = useIntlayer(_dicHash_dyn, 'app');
|
|
110
|
+
* const content2 = getIntlayer(_dicHash);
|
|
90
111
|
* ```
|
|
91
112
|
*
|
|
92
|
-
*
|
|
113
|
+
* ### Live Mode (`importMode = "live"`)
|
|
93
114
|
*
|
|
115
|
+
* Uses live-based dictionary loading for remote dictionaries:
|
|
116
|
+
*
|
|
117
|
+
* **Output if `liveSyncKeys` includes the key:**
|
|
94
118
|
* ```ts
|
|
95
|
-
* import _dicHash from '../../.intlayer/dictionaries/app.
|
|
96
|
-
* import
|
|
119
|
+
* import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
|
|
120
|
+
* import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';
|
|
121
|
+
* import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
|
|
122
|
+
* import { getDictionary as getIntlayer } from 'intlayer';
|
|
97
123
|
*
|
|
98
|
-
*
|
|
124
|
+
* const content1 = useIntlayer(_dicHash_fetch, "app");
|
|
125
|
+
* const content2 = getIntlayer(_dicHash);
|
|
126
|
+
* ```
|
|
127
|
+
*
|
|
128
|
+
* > If `liveSyncKeys` does not include the key, the plugin will fallback to the dynamic import.
|
|
129
|
+
*
|
|
130
|
+
* ```ts
|
|
131
|
+
* import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
|
|
132
|
+
* import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';
|
|
133
|
+
* import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
|
|
134
|
+
* import { getDictionary as getIntlayer } from 'intlayer';
|
|
99
135
|
*
|
|
100
|
-
* const content1 =
|
|
101
|
-
* const content2 =
|
|
136
|
+
* const content1 = useIntlayer(_dicHash_dyn, 'app');
|
|
137
|
+
* const content2 = getIntlayer(_dicHash);
|
|
102
138
|
* ```
|
|
103
139
|
*/
|
|
104
140
|
export declare const intlayerBabelPlugin: () => PluginObj<State>;
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AAyDlC,KAAK,KAAK,GAAG,UAAU,GAAG;IACxB,IAAI,EAAE;QACJ;;WAEG;QACH,eAAe,EAAE,MAAM,CAAC;QACxB;;WAEG;QACH,qBAAqB,EAAE,MAAM,CAAC;QAC9B;;WAEG;QACH,sBAAsB,EAAE,MAAM,CAAC;QAC/B;;WAEG;QACH,4BAA4B,EAAE,MAAM,CAAC;QACrC;;WAEG;QACH,oBAAoB,EAAE,MAAM,CAAC;QAC7B;;WAEG;QACH,0BAA0B,EAAE,MAAM,CAAC;QACnC;;WAEG;QACH,sBAAsB,EAAE,OAAO,CAAC;QAChC;;WAEG;QACH,UAAU,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,CAAC;QAC1C;;;WAGG;QACH,YAAY,EAAE,MAAM,EAAE,CAAC;QACvB;;WAEG;QACH,SAAS,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;IACF,8DAA8D;IAC9D,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;IAC9C,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;IAC/C,+DAA+D;IAC/D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gEAAgE;IAChE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uDAAuD;IACvD,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AA+CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiFG;AACH,eAAO,MAAM,mBAAmB,QAAO,SAAS,CAAC,KAAK,CAuQrD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/babel",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.0.0-canary.1",
|
|
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.5",
|
|
63
63
|
"@babel/parser": "^7.27.5",
|
|
64
64
|
"@babel/traverse": "^7.27.4",
|
|
65
|
-
"@intlayer/chokidar": "
|
|
66
|
-
"@intlayer/config": "
|
|
65
|
+
"@intlayer/chokidar": "6.0.0-canary.1",
|
|
66
|
+
"@intlayer/config": "6.0.0-canary.1"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"@babel/types": "^7.27.6",
|
|
@@ -76,21 +76,21 @@
|
|
|
76
76
|
"@types/node": "^24.2.1",
|
|
77
77
|
"@typescript-eslint/parser": "^8.33.1",
|
|
78
78
|
"concurrently": "^9.1.2",
|
|
79
|
-
"eslint": "^9.
|
|
80
|
-
"prettier": "^3.
|
|
79
|
+
"eslint": "^9.34.0",
|
|
80
|
+
"prettier": "^3.6.2",
|
|
81
81
|
"rimraf": "^6.0.1",
|
|
82
82
|
"tsc-alias": "^1.8.16",
|
|
83
83
|
"tsup": "^8.5.0",
|
|
84
84
|
"typescript": "^5.9.2",
|
|
85
|
-
"vitest": "^3.2.
|
|
86
|
-
"@utils/eslint-config": "1.0.4",
|
|
85
|
+
"vitest": "^3.2.4",
|
|
87
86
|
"@utils/ts-config": "1.0.4",
|
|
87
|
+
"@utils/eslint-config": "1.0.4",
|
|
88
88
|
"@utils/ts-config-types": "1.0.4",
|
|
89
89
|
"@utils/tsup-config": "1.0.4"
|
|
90
90
|
},
|
|
91
91
|
"peerDependencies": {
|
|
92
|
-
"@intlayer/chokidar": "
|
|
93
|
-
"@intlayer/config": "
|
|
92
|
+
"@intlayer/chokidar": "6.0.0-canary.1",
|
|
93
|
+
"@intlayer/config": "6.0.0-canary.1"
|
|
94
94
|
},
|
|
95
95
|
"engines": {
|
|
96
96
|
"node": ">=14.18"
|