@intlayer/babel 7.6.0-canary.1 → 8.0.0-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/dist/cjs/babel-plugin-intlayer-extract.cjs +108 -229
- package/dist/cjs/babel-plugin-intlayer-extract.cjs.map +1 -1
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs +20 -5
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
- package/dist/cjs/getOptimizePluginOptions.cjs +7 -2
- package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-extract.mjs +108 -229
- package/dist/esm/babel-plugin-intlayer-extract.mjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-optimize.mjs +20 -5
- package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
- package/dist/esm/getOptimizePluginOptions.mjs +7 -2
- package/dist/esm/getOptimizePluginOptions.mjs.map +1 -1
- package/dist/types/babel-plugin-intlayer-extract.d.ts +0 -62
- package/dist/types/babel-plugin-intlayer-extract.d.ts.map +1 -1
- package/dist/types/babel-plugin-intlayer-optimize.d.ts +4 -5
- package/dist/types/babel-plugin-intlayer-optimize.d.ts.map +1 -1
- package/dist/types/getOptimizePluginOptions.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"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\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/**\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/**\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/**\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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GAAG,GAAG,QAAQ;;GAEzD,EACF;EACF"}
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"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\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/**\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 * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<string, 'static' | 'dynamic' | 'live'>;\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/**\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/**\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 `dictionaryModeMap` includes the key with \"live\" value:**\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 `dictionaryModeMap` does not include the key with \"live\" value, 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\n // Pre-pass to determine if we should use dynamic helpers\n let fileHasDynamicCall = false;\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n if (callee.name !== 'useIntlayer') return;\n\n const arg = path.node.arguments[0];\n if (!arg || !t.isStringLiteral(arg)) return;\n\n const key = arg.value;\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'live'\n ) {\n fileHasDynamicCall = true;\n }\n },\n });\n\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' ||\n importMode === 'live' ||\n fileHasDynamicCall) &&\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\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (isUseIntlayer && useDynamicHelpers) {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'live') {\n perCallMode = 'live';\n }\n } else if (isUseIntlayer && !useDynamicHelpers) {\n // If dynamic helpers are NOT active (global mode is static),\n // we STILL might want to force dynamic/live for this specific call\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'live'\n ) {\n perCallMode = dictionaryOverrideMode;\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, ...imports);\n },\n },\n },\n };\n};\n"],"mappings":";;;;;AAMA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,cAAc,CAAC,eAAe,cAAc;;;;AAKlD,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CAC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AW;KAChC,MAAM,OAAO,SAAS;AACtB,SACE,EAAE,sBAAsB,KAAK,IAC7B,EAAE,gBAAgB,KAAK,WAAW,IAClC,CAAC,KAAK,WAAW,MAAM,WAAW,SAAS,IAC3C,CAAC,KAAK,WAAW,MAAM,WAAW,UAAU,CAE5C,cAAa;SAEb;;AAIJ,gBAAY,KAAK,KAAK,OAAO,WAAW,GAAG,GAAG,QAAQ;;GAEzD,EACF;EACF"}
|
|
@@ -23,7 +23,7 @@ const loadDictionaries = (config) => {
|
|
|
23
23
|
const getOptimizePluginOptions = (params) => {
|
|
24
24
|
const { configOptions, dictionaries: providedDictionaries, overrides } = params ?? {};
|
|
25
25
|
const config = (0, _intlayer_config.getConfiguration)(configOptions);
|
|
26
|
-
const { mainDir, dictionariesDir, unmergedDictionariesDir, dynamicDictionariesDir, fetchDictionariesDir } = config.
|
|
26
|
+
const { mainDir, dictionariesDir, unmergedDictionariesDir, dynamicDictionariesDir, fetchDictionariesDir } = config.system;
|
|
27
27
|
const { importMode, optimize } = config.build;
|
|
28
28
|
const filesListPattern = (0, _intlayer_chokidar.getComponentTransformPatternSync)(config);
|
|
29
29
|
const dictionariesEntryPath = (0, node_path.join)(mainDir, "dictionaries.mjs");
|
|
@@ -35,6 +35,11 @@ const getOptimizePluginOptions = (params) => {
|
|
|
35
35
|
dictionariesEntryPath,
|
|
36
36
|
unmergedDictionariesEntryPath
|
|
37
37
|
];
|
|
38
|
+
const dictionaries = providedDictionaries ?? loadDictionaries(config);
|
|
39
|
+
const dictionaryModeMap = {};
|
|
40
|
+
dictionaries.forEach((dictionary) => {
|
|
41
|
+
dictionaryModeMap[dictionary.key] = dictionary.importMode ?? importMode;
|
|
42
|
+
});
|
|
38
43
|
return {
|
|
39
44
|
optimize,
|
|
40
45
|
dictionariesDir,
|
|
@@ -47,7 +52,7 @@ const getOptimizePluginOptions = (params) => {
|
|
|
47
52
|
fetchDictionariesEntryPath,
|
|
48
53
|
replaceDictionaryEntry: true,
|
|
49
54
|
importMode,
|
|
50
|
-
|
|
55
|
+
dictionaryModeMap,
|
|
51
56
|
filesList,
|
|
52
57
|
...overrides
|
|
53
58
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOptimizePluginOptions.cjs","names":[],"sources":["../../src/getOptimizePluginOptions.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { getComponentTransformPatternSync } from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\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 dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n } = config.
|
|
1
|
+
{"version":3,"file":"getOptimizePluginOptions.cjs","names":[],"sources":["../../src/getOptimizePluginOptions.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { getComponentTransformPatternSync } from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\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 dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n } = config.system;\n const { importMode, optimize } = config.build;\n\n // Build files list from traverse pattern\n const filesListPattern = getComponentTransformPatternSync(config);\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 dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'live'> = {};\n\n dictionaries.forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] = dictionary.importMode ?? importMode;\n });\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 dictionaryModeMap,\n filesList,\n ...overrides,\n };\n};\n"],"mappings":";;;;;;;;AA2BA,MAAM,oBAAoB,WAAyC;AACjE,KAAI;EAGF,MAAM,EAAE,oBAAoB,QAAQ,+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,gDAA0B,cAAc;CAC9C,MAAM,EACJ,SACA,iBACA,yBACA,wBACA,yBACE,OAAO;CACX,MAAM,EAAE,YAAY,aAAa,OAAO;CAGxC,MAAM,4EAAoD,OAAO;CAEjE,MAAM,4CAA6B,SAAS,mBAAmB;CAC/D,MAAM,oDACJ,SACA,4BACD;CACD,MAAM,mDACJ,SACA,2BACD;CACD,MAAM,iDAAkC,SAAS,yBAAyB;CAE1E,MAAM,YAAY;EAChB,GAAG;EACH;EACA;EACD;CAGD,MAAM,eAAe,wBAAwB,iBAAiB,OAAO;CAErE,MAAM,oBAAmE,EAAE;AAE3E,cAAa,SAAS,eAAe;AACnC,oBAAkB,WAAW,OAAO,WAAW,cAAc;GAC7D;AAEF,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,wBAAwB;EACxB;EACA;EACA;EACA,GAAG;EACJ"}
|
|
@@ -2,74 +2,16 @@ import { basename, dirname, extname } from "node:path";
|
|
|
2
2
|
import { ATTRIBUTES_TO_EXTRACT, generateKey, shouldExtract } from "@intlayer/chokidar";
|
|
3
3
|
|
|
4
4
|
//#region src/babel-plugin-intlayer-extract.ts
|
|
5
|
-
/**
|
|
6
|
-
* Extract dictionary key from file path
|
|
7
|
-
*/
|
|
8
5
|
const extractDictionaryKeyFromPath = (filePath) => {
|
|
9
6
|
let baseName = basename(filePath, extname(filePath));
|
|
10
7
|
if (baseName === "index") baseName = basename(dirname(filePath));
|
|
11
8
|
return `comp-${baseName.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase()}`;
|
|
12
9
|
};
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
* 2. Auto-injects useIntlayer import and hook call
|
|
19
|
-
* 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)
|
|
20
|
-
* 4. Replaces extractable strings with content references
|
|
21
|
-
*
|
|
22
|
-
* ## Input
|
|
23
|
-
* ```tsx
|
|
24
|
-
* export const MyComponent = () => {
|
|
25
|
-
* return <div>Hello World</div>;
|
|
26
|
-
* };
|
|
27
|
-
* ```
|
|
28
|
-
*
|
|
29
|
-
* ## Output
|
|
30
|
-
* ```tsx
|
|
31
|
-
* import { useIntlayer } from 'react-intlayer';
|
|
32
|
-
*
|
|
33
|
-
* export const MyComponent = () => {
|
|
34
|
-
* const content = useIntlayer('comp-my-component');
|
|
35
|
-
* return <div>{content.helloWorld}</div>;
|
|
36
|
-
* };
|
|
37
|
-
* ```
|
|
38
|
-
*
|
|
39
|
-
* ## When useIntlayer is already present
|
|
40
|
-
*
|
|
41
|
-
* If the component already has a `content` variable from an existing `useIntlayer` call,
|
|
42
|
-
* the plugin will use `_compContent` to avoid naming conflicts:
|
|
43
|
-
*
|
|
44
|
-
* ### Input
|
|
45
|
-
* ```tsx
|
|
46
|
-
* export const Page = () => {
|
|
47
|
-
* const content = useIntlayer('page');
|
|
48
|
-
* return <div>{content.title} - Hello World</div>;
|
|
49
|
-
* };
|
|
50
|
-
* ```
|
|
51
|
-
*
|
|
52
|
-
* ### Output
|
|
53
|
-
* ```tsx
|
|
54
|
-
* export const Page = () => {
|
|
55
|
-
* const _compContent = useIntlayer('comp-page');
|
|
56
|
-
* const content = useIntlayer('page');
|
|
57
|
-
* return <div>{content.title} - {_compContent.helloWorld}</div>;
|
|
58
|
-
* };
|
|
59
|
-
* ```
|
|
60
|
-
*
|
|
61
|
-
* The extracted content is reported via the `onExtract` callback, allowing the
|
|
62
|
-
* compiler to write the dictionary to disk separately:
|
|
63
|
-
* ```json
|
|
64
|
-
* // my-component.content.json (written by compiler)
|
|
65
|
-
* {
|
|
66
|
-
* "key": "comp-my-component",
|
|
67
|
-
* "content": {
|
|
68
|
-
* "helloWorld": { "nodeType": "translation", "translation": { "en": "Hello World" } }
|
|
69
|
-
* }
|
|
70
|
-
* }
|
|
71
|
-
* ```
|
|
72
|
-
*/
|
|
10
|
+
const unwrapParentheses = (node, t) => {
|
|
11
|
+
let current = node;
|
|
12
|
+
while (t.isParenthesizedExpression(current)) current = current.expression;
|
|
13
|
+
return current;
|
|
14
|
+
};
|
|
73
15
|
const intlayerExtractBabelPlugin = (babel) => {
|
|
74
16
|
const { types: t } = babel;
|
|
75
17
|
return {
|
|
@@ -77,7 +19,6 @@ const intlayerExtractBabelPlugin = (babel) => {
|
|
|
77
19
|
pre() {
|
|
78
20
|
this._extractedContent = {};
|
|
79
21
|
this._existingKeys = /* @__PURE__ */ new Set();
|
|
80
|
-
this._functionsWithExtractedContent = /* @__PURE__ */ new Set();
|
|
81
22
|
this._isIncluded = true;
|
|
82
23
|
this._hasJSX = false;
|
|
83
24
|
this._hasUseIntlayerImport = false;
|
|
@@ -88,12 +29,7 @@ const intlayerExtractBabelPlugin = (babel) => {
|
|
|
88
29
|
const filename = this.file.opts.filename;
|
|
89
30
|
if (this.opts.filesList && filename) {
|
|
90
31
|
const normalizedFilename = filename.replace(/\\/g, "/");
|
|
91
|
-
|
|
92
|
-
return f.replace(/\\/g, "/") === normalizedFilename;
|
|
93
|
-
})) {
|
|
94
|
-
this._isIncluded = false;
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
32
|
+
this._isIncluded = this.opts.filesList.some((f) => f.replace(/\\/g, "/") === normalizedFilename);
|
|
97
33
|
}
|
|
98
34
|
if (filename) this._dictionaryKey = extractDictionaryKeyFromPath(filename);
|
|
99
35
|
},
|
|
@@ -117,63 +53,6 @@ const intlayerExtractBabelPlugin = (babel) => {
|
|
|
117
53
|
if (!state._isIncluded) return;
|
|
118
54
|
state._hasJSX = true;
|
|
119
55
|
},
|
|
120
|
-
JSXText(path, state) {
|
|
121
|
-
if (!state._isIncluded) return;
|
|
122
|
-
const text = path.node.value;
|
|
123
|
-
if ((state.opts.shouldExtract ?? shouldExtract)(text)) {
|
|
124
|
-
const key = generateKey(text, state._existingKeys);
|
|
125
|
-
state._existingKeys.add(key);
|
|
126
|
-
state._extractedContent[key] = text.replace(/\s+/g, " ").trim();
|
|
127
|
-
const funcParent = path.getFunctionParent();
|
|
128
|
-
if (funcParent?.node.start != null) state._functionsWithExtractedContent.add(funcParent.node.start);
|
|
129
|
-
path.replaceWith(t.jsxExpressionContainer(t.memberExpression(t.identifier(state._contentVarName), t.identifier(key), false)));
|
|
130
|
-
}
|
|
131
|
-
},
|
|
132
|
-
JSXAttribute(path, state) {
|
|
133
|
-
if (!state._isIncluded) return;
|
|
134
|
-
const name = path.node.name;
|
|
135
|
-
if (!t.isJSXIdentifier(name)) return;
|
|
136
|
-
const attrName = name.name;
|
|
137
|
-
if (!ATTRIBUTES_TO_EXTRACT.includes(attrName)) return;
|
|
138
|
-
const value = path.node.value;
|
|
139
|
-
let text = null;
|
|
140
|
-
if (t.isStringLiteral(value)) text = value.value;
|
|
141
|
-
else if (t.isJSXExpressionContainer(value) && t.isStringLiteral(value.expression)) text = value.expression.value;
|
|
142
|
-
if (text === null) return;
|
|
143
|
-
if ((state.opts.shouldExtract ?? shouldExtract)(text)) {
|
|
144
|
-
const key = generateKey(text, state._existingKeys);
|
|
145
|
-
state._existingKeys.add(key);
|
|
146
|
-
state._extractedContent[key] = text.trim();
|
|
147
|
-
const funcParent = path.getFunctionParent();
|
|
148
|
-
if (funcParent?.node.start != null) state._functionsWithExtractedContent.add(funcParent.node.start);
|
|
149
|
-
path.node.value = t.jsxExpressionContainer(t.memberExpression(t.memberExpression(t.identifier(state._contentVarName), t.identifier(key), false), t.identifier("value"), false));
|
|
150
|
-
}
|
|
151
|
-
},
|
|
152
|
-
StringLiteral(path, state) {
|
|
153
|
-
if (!state._isIncluded) return;
|
|
154
|
-
if (path.parentPath.isJSXAttribute()) return;
|
|
155
|
-
if (path.parentPath.isImportDeclaration()) return;
|
|
156
|
-
if (path.parentPath.isExportDeclaration()) return;
|
|
157
|
-
if (path.parentPath.isImportSpecifier()) return;
|
|
158
|
-
if (path.parentPath.isObjectProperty() && path.key === "key") return;
|
|
159
|
-
if (path.parentPath.isCallExpression()) {
|
|
160
|
-
const callee = path.parentPath.node.callee;
|
|
161
|
-
if (t.isMemberExpression(callee) && t.isIdentifier(callee.object) && callee.object.name === "console") return;
|
|
162
|
-
if (t.isIdentifier(callee) && callee.name === state._useIntlayerLocalName) return;
|
|
163
|
-
if (t.isIdentifier(callee) && callee.name === state._getIntlayerLocalName) return;
|
|
164
|
-
if (callee.type === "Import") return;
|
|
165
|
-
if (t.isIdentifier(callee) && callee.name === "require") return;
|
|
166
|
-
}
|
|
167
|
-
const text = path.node.value;
|
|
168
|
-
if ((state.opts.shouldExtract ?? shouldExtract)(text)) {
|
|
169
|
-
const key = generateKey(text, state._existingKeys);
|
|
170
|
-
state._existingKeys.add(key);
|
|
171
|
-
state._extractedContent[key] = text.trim();
|
|
172
|
-
const funcParent = path.getFunctionParent();
|
|
173
|
-
if (funcParent?.node.start != null) state._functionsWithExtractedContent.add(funcParent.node.start);
|
|
174
|
-
path.replaceWith(t.memberExpression(t.identifier(state._contentVarName), t.identifier(key), false));
|
|
175
|
-
}
|
|
176
|
-
},
|
|
177
56
|
Program: {
|
|
178
57
|
enter(programPath, state) {
|
|
179
58
|
if (!state._isIncluded) return;
|
|
@@ -184,125 +63,125 @@ const intlayerExtractBabelPlugin = (babel) => {
|
|
|
184
63
|
state._contentVarName = contentVarUsed ? "_compContent" : "content";
|
|
185
64
|
},
|
|
186
65
|
exit(programPath, state) {
|
|
187
|
-
if (!state._isIncluded) return;
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const defaultLocale = state.opts.defaultLocale;
|
|
192
|
-
const packageName = state.opts.packageName;
|
|
193
|
-
if (state.opts.onExtract && state._dictionaryKey && hasExtractedContent) state.opts.onExtract({
|
|
194
|
-
dictionaryKey: state._dictionaryKey,
|
|
195
|
-
filePath: state.file.opts.filename,
|
|
196
|
-
content: { ...state._extractedContent },
|
|
197
|
-
locale: defaultLocale
|
|
198
|
-
});
|
|
199
|
-
let needsUseIntlayer = false;
|
|
200
|
-
let needsGetIntlayer = false;
|
|
201
|
-
const functionsWithContent = state._functionsWithExtractedContent;
|
|
66
|
+
if (!state._isIncluded || !state._hasJSX) return;
|
|
67
|
+
const extractionTargets = [];
|
|
68
|
+
const functionsToInject = /* @__PURE__ */ new Set();
|
|
69
|
+
const shouldExtract$1 = state.opts.shouldExtract ?? shouldExtract;
|
|
202
70
|
programPath.traverse({
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
71
|
+
JSXText(path) {
|
|
72
|
+
const text = path.node.value;
|
|
73
|
+
if (shouldExtract$1(text)) {
|
|
74
|
+
const key = generateKey(text, state._existingKeys);
|
|
75
|
+
state._existingKeys.add(key);
|
|
76
|
+
state._extractedContent[key] = text.replace(/\s+/g, " ").trim();
|
|
77
|
+
extractionTargets.push({
|
|
78
|
+
path,
|
|
79
|
+
key,
|
|
80
|
+
isAttribute: false
|
|
81
|
+
});
|
|
82
|
+
const func = path.getFunctionParent();
|
|
83
|
+
if (func) functionsToInject.add(func);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
JSXAttribute(path) {
|
|
87
|
+
const attrName = path.node.name;
|
|
88
|
+
if (!t.isJSXIdentifier(attrName)) return;
|
|
89
|
+
const isKey = attrName.name === "key";
|
|
90
|
+
if (!ATTRIBUTES_TO_EXTRACT.includes(attrName.name) && !isKey) return;
|
|
91
|
+
const value = path.node.value;
|
|
92
|
+
let text = null;
|
|
93
|
+
if (t.isStringLiteral(value)) text = value.value;
|
|
94
|
+
else if (t.isJSXExpressionContainer(value) && t.isStringLiteral(value.expression)) text = value.expression.value;
|
|
95
|
+
if (text && shouldExtract$1(text)) {
|
|
96
|
+
const key = generateKey(text, state._existingKeys);
|
|
97
|
+
state._existingKeys.add(key);
|
|
98
|
+
state._extractedContent[key] = text.trim();
|
|
99
|
+
extractionTargets.push({
|
|
100
|
+
path,
|
|
101
|
+
key,
|
|
102
|
+
isAttribute: true
|
|
103
|
+
});
|
|
104
|
+
const func = path.getFunctionParent();
|
|
105
|
+
if (func) functionsToInject.add(func);
|
|
208
106
|
}
|
|
209
107
|
},
|
|
210
|
-
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
108
|
+
StringLiteral(path) {
|
|
109
|
+
const parent = path.parentPath;
|
|
110
|
+
if (parent.isJSXAttribute() || parent.isImportDeclaration() || parent.isExportDeclaration() || parent.isImportSpecifier()) return;
|
|
111
|
+
if (parent.isObjectProperty() && path.key === "key") return;
|
|
112
|
+
if (parent.isCallExpression()) {
|
|
113
|
+
const callee = parent.node.callee;
|
|
114
|
+
if (t.isMemberExpression(callee) && t.isIdentifier(callee.object) && callee.object.name === "console" || t.isIdentifier(callee) && (callee.name === state._useIntlayerLocalName || callee.name === state._getIntlayerLocalName || callee.name === "require") || callee.type === "Import") return;
|
|
115
|
+
}
|
|
116
|
+
const text = path.node.value;
|
|
117
|
+
if (shouldExtract$1(text)) {
|
|
118
|
+
const key = generateKey(text, state._existingKeys);
|
|
119
|
+
state._existingKeys.add(key);
|
|
120
|
+
state._extractedContent[key] = text.trim();
|
|
121
|
+
extractionTargets.push({
|
|
122
|
+
path,
|
|
123
|
+
key,
|
|
124
|
+
isAttribute: false
|
|
125
|
+
});
|
|
126
|
+
const func = path.getFunctionParent();
|
|
127
|
+
if (func) functionsToInject.add(func);
|
|
218
128
|
}
|
|
219
129
|
}
|
|
220
130
|
});
|
|
131
|
+
if (extractionTargets.length === 0) return;
|
|
132
|
+
for (const { path, key, isAttribute } of extractionTargets) if (isAttribute) {
|
|
133
|
+
const member = t.memberExpression(t.identifier(state._contentVarName), t.identifier(key));
|
|
134
|
+
path.node.value = t.jsxExpressionContainer(t.memberExpression(member, t.identifier("value")));
|
|
135
|
+
} else if (path.isJSXText()) path.replaceWith(t.jsxExpressionContainer(t.memberExpression(t.identifier(state._contentVarName), t.identifier(key))));
|
|
136
|
+
else path.replaceWith(t.memberExpression(t.identifier(state._contentVarName), t.identifier(key)));
|
|
137
|
+
if (state.opts.onExtract && state._dictionaryKey) state.opts.onExtract({
|
|
138
|
+
dictionaryKey: state._dictionaryKey,
|
|
139
|
+
filePath: state.file.opts.filename,
|
|
140
|
+
content: { ...state._extractedContent },
|
|
141
|
+
locale: state.opts.defaultLocale
|
|
142
|
+
});
|
|
143
|
+
let needsUseIntlayer = false;
|
|
144
|
+
let needsGetIntlayer = false;
|
|
145
|
+
for (const funcPath of functionsToInject) {
|
|
146
|
+
const type = injectHook(funcPath, state, t);
|
|
147
|
+
if (type === "hook") needsUseIntlayer = true;
|
|
148
|
+
if (type === "core") needsGetIntlayer = true;
|
|
149
|
+
}
|
|
221
150
|
if (needsUseIntlayer || needsGetIntlayer) {
|
|
222
|
-
const
|
|
223
|
-
let
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
break;
|
|
231
|
-
}
|
|
232
|
-
if (needsUseIntlayer && !state._hasUseIntlayerImport) {
|
|
233
|
-
const importDeclaration = t.importDeclaration([t.importSpecifier(t.identifier("useIntlayer"), t.identifier("useIntlayer"))], t.stringLiteral(packageName));
|
|
234
|
-
programPath.node.body.splice(importInsertPos, 0, importDeclaration);
|
|
235
|
-
importInsertPos++;
|
|
236
|
-
}
|
|
237
|
-
if (needsGetIntlayer && !state._hasGetIntlayerImport) {
|
|
238
|
-
const importDeclaration = t.importDeclaration([t.importSpecifier(t.identifier("getIntlayer"), t.identifier("getIntlayer"))], t.stringLiteral(packageName));
|
|
239
|
-
programPath.node.body.splice(importInsertPos, 0, importDeclaration);
|
|
240
|
-
}
|
|
151
|
+
const pkg = state.opts.packageName;
|
|
152
|
+
let pos = 0;
|
|
153
|
+
const body = programPath.node.body;
|
|
154
|
+
while (pos < body.length && t.isExpressionStatement(body[pos]) && t.isStringLiteral(body[pos].expression)) pos++;
|
|
155
|
+
if (needsUseIntlayer && !state._hasUseIntlayerImport) body.splice(pos++, 0, t.importDeclaration([t.importSpecifier(t.identifier("useIntlayer"), t.identifier("useIntlayer"))], t.stringLiteral(pkg)));
|
|
156
|
+
if (needsGetIntlayer && !state._hasGetIntlayerImport) body.splice(pos, 0, t.importDeclaration([t.importSpecifier(t.identifier("getIntlayer"), t.identifier("getIntlayer"))], t.stringLiteral(pkg)));
|
|
241
157
|
}
|
|
242
158
|
}
|
|
243
159
|
}
|
|
244
160
|
}
|
|
245
161
|
};
|
|
246
162
|
};
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
* Returns 'hook' if useIntlayer was injected (or needed), 'core' if getIntlayer was injected, or null.
|
|
250
|
-
*/
|
|
251
|
-
const injectHookIntoFunction = (funcPath, state, t) => {
|
|
252
|
-
const body = funcPath.node.body;
|
|
253
|
-
if (!t.isBlockStatement(body)) return null;
|
|
254
|
-
let returnsJSX = false;
|
|
255
|
-
funcPath.traverse({ ReturnStatement(returnPath) {
|
|
256
|
-
const arg = returnPath.node.argument;
|
|
257
|
-
if (t.isJSXElement(arg) || t.isJSXFragment(arg)) returnsJSX = true;
|
|
258
|
-
} });
|
|
259
|
-
const contentVarName = state._contentVarName;
|
|
260
|
-
if (returnsJSX) {
|
|
261
|
-
if (body.body.some((stmt) => t.isVariableDeclaration(stmt) && stmt.declarations.some((decl) => t.isIdentifier(decl.id) && decl.id.name === contentVarName && t.isCallExpression(decl.init) && t.isIdentifier(decl.init.callee) && decl.init.callee.name === state._useIntlayerLocalName))) return "hook";
|
|
262
|
-
const hookCall = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(contentVarName), t.callExpression(t.identifier(state._useIntlayerLocalName), [t.stringLiteral(state._dictionaryKey)]))]);
|
|
263
|
-
body.body.unshift(hookCall);
|
|
264
|
-
return "hook";
|
|
265
|
-
} else {
|
|
266
|
-
if (body.body.some((stmt) => t.isVariableDeclaration(stmt) && stmt.declarations.some((decl) => t.isIdentifier(decl.id) && decl.id.name === contentVarName && t.isCallExpression(decl.init) && t.isIdentifier(decl.init.callee) && decl.init.callee.name === state._getIntlayerLocalName))) return "core";
|
|
267
|
-
const call = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(contentVarName), t.callExpression(t.identifier(state._getIntlayerLocalName), [t.stringLiteral(state._dictionaryKey)]))]);
|
|
268
|
-
body.body.unshift(call);
|
|
269
|
-
return "core";
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
/**
|
|
273
|
-
* Inject useIntlayer hook into an arrow function or function expression
|
|
274
|
-
*/
|
|
275
|
-
const injectHookIntoArrowOrExpression = (varPath, init, state, t) => {
|
|
276
|
-
const body = init.body;
|
|
163
|
+
const injectHook = (path, state, t) => {
|
|
164
|
+
const node = path.node;
|
|
277
165
|
const contentVarName = state._contentVarName;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
const returnStmt = t.returnStatement(body);
|
|
287
|
-
init.body = t.blockStatement([call, returnStmt]);
|
|
288
|
-
return "core";
|
|
166
|
+
const dictionaryKey = state._dictionaryKey;
|
|
167
|
+
if (!t.isBlockStatement(node.body)) {
|
|
168
|
+
const unwrapped = unwrapParentheses(node.body, t);
|
|
169
|
+
const isJSX = t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped);
|
|
170
|
+
const hookName$1 = isJSX ? state._useIntlayerLocalName : state._getIntlayerLocalName;
|
|
171
|
+
const hookCall = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(contentVarName), t.callExpression(t.identifier(hookName$1), [t.stringLiteral(dictionaryKey)]))]);
|
|
172
|
+
node.body = t.blockStatement([hookCall, t.returnStatement(node.body)]);
|
|
173
|
+
return isJSX ? "hook" : "core";
|
|
289
174
|
}
|
|
290
175
|
let returnsJSX = false;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
176
|
+
path.traverse({ ReturnStatement(p) {
|
|
177
|
+
if (p.node.argument) {
|
|
178
|
+
const unwrapped = unwrapParentheses(p.node.argument, t);
|
|
179
|
+
if (t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped)) returnsJSX = true;
|
|
180
|
+
}
|
|
294
181
|
} });
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
body.body.unshift(hookCall);
|
|
299
|
-
return "hook";
|
|
300
|
-
} else {
|
|
301
|
-
if (body.body.some((stmt) => t.isVariableDeclaration(stmt) && stmt.declarations.some((decl) => t.isIdentifier(decl.id) && decl.id.name === contentVarName && t.isCallExpression(decl.init) && t.isIdentifier(decl.init.callee) && decl.init.callee.name === state._getIntlayerLocalName))) return "core";
|
|
302
|
-
const call = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(contentVarName), t.callExpression(t.identifier(state._getIntlayerLocalName), [t.stringLiteral(state._dictionaryKey)]))]);
|
|
303
|
-
body.body.unshift(call);
|
|
304
|
-
return "core";
|
|
305
|
-
}
|
|
182
|
+
const hookName = returnsJSX ? state._useIntlayerLocalName : state._getIntlayerLocalName;
|
|
183
|
+
if (!node.body.body.some((s) => t.isVariableDeclaration(s) && s.declarations.some((d) => t.isIdentifier(d.id) && d.id.name === contentVarName))) node.body.body.unshift(t.variableDeclaration("const", [t.variableDeclarator(t.identifier(contentVarName), t.callExpression(t.identifier(hookName), [t.stringLiteral(dictionaryKey)]))]));
|
|
184
|
+
return returnsJSX ? "hook" : "core";
|
|
306
185
|
};
|
|
307
186
|
|
|
308
187
|
//#endregion
|