next-intlayer 9.3.0 → 9.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -24
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/client/format/index.cjs +0 -1
- package/dist/cjs/client/useLocale.cjs +29 -28
- package/dist/cjs/client/useLocale.cjs.map +1 -1
- package/dist/cjs/client/useLocalePageRouter.cjs +11 -10
- package/dist/cjs/client/useLocalePageRouter.cjs.map +1 -1
- package/dist/cjs/client/usePathname.cjs.map +1 -1
- package/dist/cjs/proxy/intlayerProxy.cjs +4 -2
- package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
- package/dist/cjs/proxy/localeDetector.cjs.map +1 -1
- package/dist/cjs/server/format/index.cjs +0 -1
- package/dist/cjs/server/getLocale.cjs.map +1 -1
- package/dist/cjs/server/prepareSwcOptimization.cjs +2 -2
- package/dist/cjs/server/prepareSwcOptimization.cjs.map +1 -1
- package/dist/cjs/server/swcPluginCompatibility.cjs.map +1 -1
- package/dist/cjs/server/useDictionary.cjs +2 -1
- package/dist/cjs/server/useDictionary.cjs.map +1 -1
- package/dist/cjs/server/useDictionaryAsync.cjs +2 -1
- package/dist/cjs/server/useDictionaryAsync.cjs.map +1 -1
- package/dist/cjs/server/useDictionaryDynamic.cjs +2 -1
- package/dist/cjs/server/useDictionaryDynamic.cjs.map +1 -1
- package/dist/cjs/server/useIntlayer.cjs +2 -1
- package/dist/cjs/server/useIntlayer.cjs.map +1 -1
- package/dist/cjs/server/withIntlayer.cjs +19 -17
- package/dist/cjs/server/withIntlayer.cjs.map +1 -1
- package/dist/esm/client/useLocale.mjs +29 -28
- package/dist/esm/client/useLocale.mjs.map +1 -1
- package/dist/esm/client/useLocalePageRouter.mjs +11 -10
- package/dist/esm/client/useLocalePageRouter.mjs.map +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs +4 -2
- package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
- package/dist/esm/server/prepareSwcOptimization.mjs +2 -2
- package/dist/esm/server/prepareSwcOptimization.mjs.map +1 -1
- package/dist/esm/server/useDictionary.mjs +2 -1
- package/dist/esm/server/useDictionary.mjs.map +1 -1
- package/dist/esm/server/useDictionaryAsync.mjs +2 -1
- package/dist/esm/server/useDictionaryAsync.mjs.map +1 -1
- package/dist/esm/server/useDictionaryDynamic.mjs +2 -1
- package/dist/esm/server/useDictionaryDynamic.mjs.map +1 -1
- package/dist/esm/server/useIntlayer.mjs +2 -1
- package/dist/esm/server/useIntlayer.mjs.map +1 -1
- package/dist/esm/server/withIntlayer.mjs +19 -17
- package/dist/esm/server/withIntlayer.mjs.map +1 -1
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-extract.d.ts +5 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-field-rename.d.ts +21 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-field-rename.d.ts.map +1 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-minify.d.ts +2 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-optimize.d.ts +3 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-purge.d.ts +5 -0
- package/dist/types/@intlayer/babel/dist/types/babel-plugin-intlayer-usage-analyzer.d.ts +4 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/contentWriter.d.ts +2 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/extractContent.d.ts +3 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/index.d.ts +4 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/utils/extractDictionaryInfo.d.ts +3 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/utils/getComponentName.d.ts +1 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts +2 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/utils/index.d.ts +4 -0
- package/dist/types/@intlayer/babel/dist/types/extractContent/utils/resolveDictionaryKey.d.ts +1 -0
- package/dist/types/@intlayer/babel/dist/types/getExtractPluginOptions.d.ts +2 -0
- package/dist/types/@intlayer/babel/dist/types/getOptimizePluginOptions.d.ts +3 -0
- package/dist/types/@intlayer/babel/dist/types/getPurgePluginOptions.d.ts +4 -0
- package/dist/types/@intlayer/babel/dist/types/index.d.ts +16 -0
- package/dist/types/@intlayer/babel/dist/types/transformers.d.ts +3 -0
- package/dist/types/server/prepareSwcOptimization.d.ts +2 -1
- package/dist/types/server/prepareSwcOptimization.d.ts.map +1 -1
- package/dist/types/server/useDictionaryDynamic.d.ts +1 -1
- package/package.json +8 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareSwcOptimization.cjs","names":["ANSIColors"],"sources":["../../../src/server/prepareSwcOptimization.ts"],"sourcesContent":["import { readFileSync, rmSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type {\n getPurgePluginOptions as GetPurgePluginOptions,\n runIntlayerPurgePipeline as RunIntlayerPurgePipeline,\n SerializedFieldRenameMap,\n serializeFieldRenameMap as SerializeFieldRenameMap,\n} from '@intlayer/babel';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type { GetConfigurationOptions } from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport { runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\n\n/**\n * Field-rename tables keyed by dictionary key, forwarded to the\n * `@intlayer/swc` plugin's `fieldRenameMap` option.\n */\nexport type FieldRenameMapByDictionaryKey = Record<\n string,\n SerializedFieldRenameMap\n>;\n\n/** Verbosity forwarded to the `@intlayer/swc` plugin's `logLevel` option. */\nexport type SwcLogLevel = 'off' | 'info' | 'debug';\n\n/**\n * Subset of `@intlayer/babel` this module needs. The package is only an\n * optional runtime dependency, so it is required lazily and never imported at\n * module scope.\n */\ntype IntlayerBabelModule = {\n getPurgePluginOptions: typeof GetPurgePluginOptions;\n runIntlayerPurgePipeline: typeof RunIntlayerPurgePipeline;\n serializeFieldRenameMap: typeof SerializeFieldRenameMap;\n};\n\n/**\n * Opt-in to the SWC plugin's per-file tracing.\n *\n * The plugin transforms one file at a time with no cross-file state, so all it\n * can report is a line per file — hundreds of them on a real project, and with\n * no counterpart in the Vite build output. The purge and minify summaries that\n * `log.mode` does control are emitted by the pipeline itself, in Node; this\n * variable is purely a debugging aid on top.\n */\nconst SWC_LOG_LEVEL_ENV_VAR = 'INTLAYER_SWC_LOG_LEVEL';\n\n/** Sentinel coordinating the pipeline across the processes of one build. */\nconst PURGE_SENTINEL_FILE_NAME = 'intlayer-swc-purge.lock';\n\n/** Where the serialised field-rename tables are cached between processes. */\nconst FIELD_RENAME_MAP_FILE_NAME = 'swc-field-rename-map.json';\n\n/**\n * Next.js evaluates `next.config.*` in the main build process and again in each\n * Turbopack/webpack worker. The dictionary rewrite must happen exactly once —\n * a second run would derive the short aliases from the already-renamed JSON —\n * so the sentinel window has to cover a whole build startup.\n */\nconst PURGE_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/** Absolute path of a file in the intlayer cache directory. */\nconst getCacheFilePath = (\n intlayerConfig: IntlayerConfig,\n fileName: string\n): string =>\n join(intlayerConfig.system.baseDir, '.intlayer', 'cache', fileName);\n\n/**\n * Resolves the verbosity the `@intlayer/swc` plugin should report at.\n *\n * Off unless {@link SWC_LOG_LEVEL_ENV_VAR} asks for tracing: `log.mode` governs\n * the purge and minify reporting, which the pipeline emits in Node so the\n * Next.js build reads the same as the Vite one.\n */\nexport const resolveSwcLogLevel = (\n intlayerConfig: IntlayerConfig\n): SwcLogLevel => {\n if (intlayerConfig.log.mode === 'disabled') return 'off';\n\n const requestedLogLevel = process.env[SWC_LOG_LEVEL_ENV_VAR];\n\n return requestedLogLevel === 'info' || requestedLogLevel === 'debug'\n ? requestedLogLevel\n : 'off';\n};\n\n/**\n * Whether the purge / minify pipeline should run for this build.\n *\n * Compat-adapter callers disable it: their descriptors reach `withIntlayer`\n * only in the SWC plugin's lossy wire format, so the usage analyser would not\n * recognise `useTranslation(...)` & co. and would purge fields those call sites\n * still read.\n */\nconst getIsPurgePipelineEnabled = (\n intlayerConfig: IntlayerConfig,\n swcExtraCallers: SwcExtraCallerConfig[] | undefined,\n isSwcPluginUsable: boolean\n): boolean => {\n const { purge, minify, optimize } = intlayerConfig.build;\n\n if (optimize === false) return false;\n if (!purge && !minify) return false;\n\n // The pipeline rewrites the compiled dictionaries in place — dropping unused\n // fields and renaming the rest to short aliases. Only the SWC plugin rewrites\n // the matching source accesses, so running this without it would ship\n // dictionaries whose keys no longer match the code reading them.\n if (!isSwcPluginUsable) return false;\n\n // `editor.enabled` is deliberately not checked here: the pipeline stands down\n // on its own and explains why, the same way the Vite build does.\n\n if (swcExtraCallers && swcExtraCallers.length > 0) {\n getAppLogger(intlayerConfig)(\n [\n 'Dictionary purge and minification are',\n colorize('disabled', ANSIColors.GREY_DARK),\n 'because compat-adapter callers are configured — their call sites are',\n 'not visible to the usage analyser.',\n ],\n { level: 'warn' }\n );\n return false;\n }\n\n return true;\n};\n\n/**\n * Exports this module needs from `@intlayer/babel`. Checked one by one so a\n * version predating the purge pipeline is rejected like a missing package,\n * instead of failing later with `runIntlayerPurgePipeline is not a function`.\n */\nconst REQUIRED_BABEL_EXPORTS = [\n 'getPurgePluginOptions',\n 'runIntlayerPurgePipeline',\n 'serializeFieldRenameMap',\n] as const satisfies readonly (keyof IntlayerBabelModule)[];\n\n/**\n * Lazily loads `@intlayer/babel`, or `null` when it is not installed or too old\n * to expose the purge pipeline.\n */\nconst loadIntlayerBabel = (\n intlayerConfig: IntlayerConfig\n): IntlayerBabelModule | null => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n\n const intlayerBabel = requireFunction(\n '@intlayer/babel'\n ) as Partial<IntlayerBabelModule>;\n\n const hasEveryRequiredExport = REQUIRED_BABEL_EXPORTS.every(\n (exportName) => typeof intlayerBabel?.[exportName] === 'function'\n );\n\n if (!hasEveryRequiredExport) return null;\n\n return intlayerBabel as IntlayerBabelModule;\n } catch {\n return null;\n }\n};\n\n/**\n * Whether the purge / minify pipeline can run at all, i.e. whether a usable\n * `@intlayer/babel` is resolvable from the project.\n *\n * Used by `withIntlayer` to keep the build report honest: announcing\n * `Dictionary minification enabled` while the pipeline cannot load would describe a\n * pass that never happens.\n */\nexport const getIsPurgePipelineAvailable = (\n intlayerConfig: IntlayerConfig\n): boolean => loadIntlayerBabel(intlayerConfig) !== null;\n\n/**\n * Runs the purge / minify pipeline and writes the resulting field-rename\n * tables to the cache file so every process of the build reads the same ones.\n */\nconst runPurgePipelineOnce = async (\n intlayerConfig: IntlayerConfig,\n configOptions: GetConfigurationOptions | undefined,\n dictionaries: Dictionary[] | undefined,\n fieldRenameMapFilePath: string\n): Promise<void> => {\n const appLogger = getAppLogger(intlayerConfig);\n\n const intlayerBabel = loadIntlayerBabel(intlayerConfig);\n\n if (!intlayerBabel) {\n // Not verbose: the build asked for purge / minify and is silently getting\n // neither, which is exactly the kind of thing a default build must report.\n appLogger(\n [\n 'Dictionary purge and minification are',\n colorize('disabled', ANSIColors.GREY_DARK),\n 'because',\n colorize('@intlayer/babel', ANSIColors.GREY_LIGHT),\n 'is missing or too old to expose the purge pipeline — install it in',\n 'this project to enable them.',\n ],\n { level: 'warn' }\n );\n return;\n }\n\n const {\n getPurgePluginOptions,\n runIntlayerPurgePipeline,\n serializeFieldRenameMap,\n } = intlayerBabel;\n\n // `runOnce` discards whatever this callback throws, so a pipeline failure\n // would otherwise leave the build with no dictionaries rewritten and no\n // explanation of why.\n let fieldRenameMap: FieldRenameMapByDictionaryKey;\n\n try {\n // The pipeline reports what it purged and minified through the intlayer\n // logger, matching the Vite build output.\n const pruneContext = runIntlayerPurgePipeline(\n getPurgePluginOptions({ configOptions, dictionaries })\n );\n\n fieldRenameMap = serializeFieldRenameMap(pruneContext);\n } catch (pipelineError) {\n appLogger(\n [\n 'Dictionary purge and minification',\n colorize('failed', ANSIColors.RED),\n '— the compiled dictionaries are left untouched.',\n pipelineError instanceof Error\n ? `(${pipelineError.message})`\n : String(pipelineError),\n ],\n { level: 'error' }\n );\n return;\n }\n\n await mkdir(dirname(fieldRenameMapFilePath), { recursive: true });\n await writeFile(\n fieldRenameMapFilePath,\n JSON.stringify(fieldRenameMap),\n 'utf-8'\n );\n};\n\n/** Reads the cached field-rename tables, or `{}` when none were written. */\nconst readFieldRenameMapFile = (\n fieldRenameMapFilePath: string\n): FieldRenameMapByDictionaryKey => {\n try {\n return JSON.parse(\n readFileSync(fieldRenameMapFilePath, 'utf-8')\n ) as FieldRenameMapByDictionaryKey;\n } catch {\n return {};\n }\n};\n\n/** Removes the cached field-rename tables, ignoring a missing file. */\nconst removeFieldRenameMapFile = (fieldRenameMapFilePath: string): void => {\n try {\n rmSync(fieldRenameMapFilePath, { force: true });\n } catch {\n // Nothing to clean up.\n }\n};\n\ntype PrepareSwcOptimizationParams = {\n /** Options forwarded to the intlayer configuration loader. */\n configOptions?: GetConfigurationOptions;\n /** Pre-loaded dictionaries, to avoid a second `getDictionaries` call. */\n dictionaries?: Dictionary[];\n /** Compat-adapter callers declared by the consuming plugin, if any. */\n swcExtraCallers?: SwcExtraCallerConfig[];\n /**\n * Whether the `@intlayer/swc` plugin is installed *and* the resolved Next.js\n * version can load it. False leaves the compiled dictionaries untouched.\n */\n isSwcPluginUsable: boolean;\n};\n\n/**\n * Prepares the parts of the build optimisation the `@intlayer/swc` plugin\n * cannot do itself, and returns the field-rename tables it needs.\n *\n * Removing unused content fields (`build.purge`) and assigning short field\n * aliases (`build.minify`) require reading every component source file and\n * rewriting the compiled dictionary JSON — file I/O and cross-file state that a\n * per-file Wasm transform has no access to. That analysis therefore runs here,\n * in Node, through `@intlayer/babel`; the plugin only receives the resulting\n * tables and rewrites the matching source accesses\n * (`content.title` → `content.a`).\n *\n * The work is coordinated by a sentinel file: Next.js loads `next.config.*` in\n * several processes per build, and running the minify pass twice would derive\n * the aliases from the already-renamed dictionaries. Processes that lose the\n * race read the tables the winner cached.\n *\n * @returns The field-rename tables, keyed by dictionary key. Empty when the\n * pipeline is disabled, unavailable, or renamed nothing.\n */\nexport const prepareSwcOptimization = async (\n intlayerConfig: IntlayerConfig,\n params: PrepareSwcOptimizationParams\n): Promise<FieldRenameMapByDictionaryKey> => {\n const { configOptions, dictionaries, swcExtraCallers, isSwcPluginUsable } =\n params;\n\n const fieldRenameMapFilePath = getCacheFilePath(\n intlayerConfig,\n FIELD_RENAME_MAP_FILE_NAME\n );\n\n // A stale file from an earlier build would rename source accesses that the\n // dictionaries no longer match.\n if (\n !getIsPurgePipelineEnabled(\n intlayerConfig,\n swcExtraCallers,\n isSwcPluginUsable\n )\n ) {\n removeFieldRenameMapFile(fieldRenameMapFilePath);\n return {};\n }\n\n await runOnce(\n getCacheFilePath(intlayerConfig, PURGE_SENTINEL_FILE_NAME),\n () =>\n runPurgePipelineOnce(\n intlayerConfig,\n configOptions,\n dictionaries,\n fieldRenameMapFilePath\n ),\n { cacheTimeoutMs: PURGE_CACHE_TIMEOUT_MS }\n );\n\n return readFieldRenameMapFile(fieldRenameMapFilePath);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,wBAAwB;;AAG9B,MAAM,2BAA2B;;AAGjC,MAAM,6BAA6B;;;;;;;AAQnC,MAAM,yBAAyB,KAAK;;AAGpC,MAAM,oBACJ,gBACA,iCAEK,eAAe,OAAO,SAAS,aAAa,SAAS,QAAQ;;;;;;;;AASpE,MAAa,sBACX,mBACgB;CAChB,IAAI,eAAe,IAAI,SAAS,YAAY,OAAO;CAEnD,MAAM,oBAAoB,QAAQ,IAAI;CAEtC,OAAO,sBAAsB,UAAU,sBAAsB,UACzD,oBACA;AACN;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AQ,KAC1B,OAAO,aAAa;EAC1B,GACA,EAAE,OAAO,QAAQ,CACnB;EACA;CACF;CAEA,yDAAoB,sBAAsB,GAAG,EAAE,WAAW,KAAK,CAAC;CAChE,sCACE,wBACA,KAAK,UAAU,cAAc,GAC7B,OACF;AACF;;AAGA,MAAM,0BACJ,2BACkC;CAClC,IAAI;EACF,OAAO,KAAK,gCACG,wBAAwB,OAAO,CAC9C;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,MAAM,4BAA4B,2BAAyC;CACzE,IAAI;EACF,oBAAO,wBAAwB,EAAE,OAAO,KAAK,CAAC;CAChD,QAAQ,CAER;AACF;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,yBAAyB,OACpC,gBACA,WAC2C;CAC3C,MAAM,EAAE,eAAe,cAAc,iBAAiB,sBACpD;CAEF,MAAM,yBAAyB,iBAC7B,gBACA,0BACF;CAIA,IACE,CAAC,0BACC,gBACA,iBACA,iBACF,GACA;EACA,yBAAyB,sBAAsB;EAC/C,OAAO,CAAC;CACV;CAEA,0CACE,iBAAiB,gBAAgB,wBAAwB,SAEvD,qBACE,gBACA,eACA,cACA,sBACF,GACF,EAAE,gBAAgB,uBAAuB,CAC3C;CAEA,OAAO,uBAAuB,sBAAsB;AACtD"}
|
|
1
|
+
{"version":3,"file":"prepareSwcOptimization.cjs","names":["join","colorize","ANSIColors","getProjectRequire","getAppLogger","mkdir","dirname","writeFile","readFileSync","runOnce"],"sources":["../../../src/server/prepareSwcOptimization.ts"],"sourcesContent":["import { readFileSync, rmSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type {\n getPurgePluginOptions as GetPurgePluginOptions,\n runIntlayerPurgePipeline as RunIntlayerPurgePipeline,\n SerializedFieldRenameMap,\n serializeFieldRenameMap as SerializeFieldRenameMap,\n} from '@intlayer/babel';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type { GetConfigurationOptions } from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport { runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\n\n/**\n * Field-rename tables keyed by dictionary key, forwarded to the\n * `@intlayer/swc` plugin's `fieldRenameMap` option.\n */\nexport type FieldRenameMapByDictionaryKey = Record<\n string,\n SerializedFieldRenameMap\n>;\n\n/** Verbosity forwarded to the `@intlayer/swc` plugin's `logLevel` option. */\nexport type SwcLogLevel = 'off' | 'info' | 'debug';\n\n/**\n * Subset of `@intlayer/babel` this module needs. The package is only an\n * optional runtime dependency, so it is required lazily and never imported at\n * module scope.\n */\ntype IntlayerBabelModule = {\n getPurgePluginOptions: typeof GetPurgePluginOptions;\n runIntlayerPurgePipeline: typeof RunIntlayerPurgePipeline;\n serializeFieldRenameMap: typeof SerializeFieldRenameMap;\n};\n\n/**\n * Opt-in to the SWC plugin's per-file tracing.\n *\n * The plugin transforms one file at a time with no cross-file state, so all it\n * can report is a line per file — hundreds of them on a real project, and with\n * no counterpart in the Vite build output. The purge and minify summaries that\n * `log.mode` does control are emitted by the pipeline itself, in Node; this\n * variable is purely a debugging aid on top.\n */\nconst SWC_LOG_LEVEL_ENV_VAR = 'INTLAYER_SWC_LOG_LEVEL';\n\n/** Sentinel coordinating the pipeline across the processes of one build. */\nconst PURGE_SENTINEL_FILE_NAME = 'intlayer-swc-purge.lock';\n\n/** Where the serialised field-rename tables are cached between processes. */\nconst FIELD_RENAME_MAP_FILE_NAME = 'swc-field-rename-map.json';\n\n/**\n * Next.js evaluates `next.config.*` in the main build process and again in each\n * Turbopack/webpack worker. The dictionary rewrite must happen exactly once —\n * a second run would derive the short aliases from the already-renamed JSON —\n * so the sentinel window has to cover a whole build startup.\n */\nconst PURGE_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/** Absolute path of a file in the intlayer cache directory. */\nconst getCacheFilePath = (\n intlayerConfig: IntlayerConfig,\n fileName: string\n): string =>\n join(intlayerConfig.system.baseDir, '.intlayer', 'cache', fileName);\n\n/**\n * Resolves the verbosity the `@intlayer/swc` plugin should report at.\n *\n * Off unless {@link SWC_LOG_LEVEL_ENV_VAR} asks for tracing: `log.mode` governs\n * the purge and minify reporting, which the pipeline emits in Node so the\n * Next.js build reads the same as the Vite one.\n */\nexport const resolveSwcLogLevel = (\n intlayerConfig: IntlayerConfig\n): SwcLogLevel => {\n if (intlayerConfig.log.mode === 'disabled') return 'off';\n\n const requestedLogLevel = process.env[SWC_LOG_LEVEL_ENV_VAR];\n\n return requestedLogLevel === 'info' || requestedLogLevel === 'debug'\n ? requestedLogLevel\n : 'off';\n};\n\n/**\n * Whether the purge / minify pipeline should run for this build.\n *\n * Compat-adapter callers disable it: their descriptors reach `withIntlayer`\n * only in the SWC plugin's lossy wire format, so the usage analyser would not\n * recognise `useTranslation(...)` & co. and would purge fields those call sites\n * still read.\n */\nconst getIsPurgePipelineEnabled = (\n intlayerConfig: IntlayerConfig,\n swcExtraCallers: SwcExtraCallerConfig[] | undefined,\n isSwcPluginUsable: boolean\n): boolean => {\n const { purge, minify, optimize } = intlayerConfig.build;\n\n if (optimize === false) return false;\n if (!purge && !minify) return false;\n\n // The pipeline rewrites the compiled dictionaries in place — dropping unused\n // fields and renaming the rest to short aliases. Only the SWC plugin rewrites\n // the matching source accesses, so running this without it would ship\n // dictionaries whose keys no longer match the code reading them.\n if (!isSwcPluginUsable) return false;\n\n // `editor.enabled` is deliberately not checked here: the pipeline stands down\n // on its own and explains why, the same way the Vite build does.\n\n if (swcExtraCallers && swcExtraCallers.length > 0) {\n getAppLogger(intlayerConfig)(\n [\n 'Dictionary purge and minification are',\n colorize('disabled', ANSIColors.GREY_DARK),\n 'because compat-adapter callers are configured — their call sites are',\n 'not visible to the usage analyser.',\n ],\n { level: 'warn' }\n );\n return false;\n }\n\n return true;\n};\n\n/**\n * Exports this module needs from `@intlayer/babel`. Checked one by one so a\n * version predating the purge pipeline is rejected like a missing package,\n * instead of failing later with `runIntlayerPurgePipeline is not a function`.\n */\nconst REQUIRED_BABEL_EXPORTS = [\n 'getPurgePluginOptions',\n 'runIntlayerPurgePipeline',\n 'serializeFieldRenameMap',\n] as const satisfies readonly (keyof IntlayerBabelModule)[];\n\n/**\n * Lazily loads `@intlayer/babel`, or `null` when it is not installed or too old\n * to expose the purge pipeline.\n */\nconst loadIntlayerBabel = (\n intlayerConfig: IntlayerConfig\n): IntlayerBabelModule | null => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n\n const intlayerBabel = requireFunction(\n '@intlayer/babel'\n ) as Partial<IntlayerBabelModule>;\n\n const hasEveryRequiredExport = REQUIRED_BABEL_EXPORTS.every(\n (exportName) => typeof intlayerBabel?.[exportName] === 'function'\n );\n\n if (!hasEveryRequiredExport) return null;\n\n return intlayerBabel as IntlayerBabelModule;\n } catch {\n return null;\n }\n};\n\n/**\n * Whether the purge / minify pipeline can run at all, i.e. whether a usable\n * `@intlayer/babel` is resolvable from the project.\n *\n * Used by `withIntlayer` to keep the build report honest: announcing\n * `Dictionary minification enabled` while the pipeline cannot load would describe a\n * pass that never happens.\n */\nexport const getIsPurgePipelineAvailable = (\n intlayerConfig: IntlayerConfig\n): boolean => loadIntlayerBabel(intlayerConfig) !== null;\n\n/**\n * Runs the purge / minify pipeline and writes the resulting field-rename\n * tables to the cache file so every process of the build reads the same ones.\n */\nconst runPurgePipelineOnce = async (\n intlayerConfig: IntlayerConfig,\n configOptions: GetConfigurationOptions | undefined,\n dictionaries: Dictionary[] | undefined,\n fieldRenameMapFilePath: string\n): Promise<void> => {\n const appLogger = getAppLogger(intlayerConfig);\n\n const intlayerBabel = loadIntlayerBabel(intlayerConfig);\n\n if (!intlayerBabel) {\n // Not verbose: the build asked for purge / minify and is silently getting\n // neither, which is exactly the kind of thing a default build must report.\n appLogger(\n [\n 'Dictionary purge and minification are',\n colorize('disabled', ANSIColors.GREY_DARK),\n 'because',\n colorize('@intlayer/babel', ANSIColors.GREY_LIGHT),\n 'is missing or too old to expose the purge pipeline — install it in',\n 'this project to enable them.',\n ],\n { level: 'warn' }\n );\n return;\n }\n\n const {\n getPurgePluginOptions,\n runIntlayerPurgePipeline,\n serializeFieldRenameMap,\n } = intlayerBabel;\n\n // `runOnce` discards whatever this callback throws, so a pipeline failure\n // would otherwise leave the build with no dictionaries rewritten and no\n // explanation of why.\n let fieldRenameMap: FieldRenameMapByDictionaryKey;\n\n try {\n // The pipeline reports what it purged and minified through the intlayer\n // logger, matching the Vite build output.\n const pruneContext = runIntlayerPurgePipeline(\n getPurgePluginOptions({ configOptions, dictionaries })\n );\n\n fieldRenameMap = serializeFieldRenameMap(pruneContext);\n } catch (pipelineError) {\n appLogger(\n [\n 'Dictionary purge and minification',\n colorize('failed', ANSIColors.RED),\n '— the compiled dictionaries are left untouched.',\n pipelineError instanceof Error\n ? `(${pipelineError.message})`\n : String(pipelineError),\n ],\n { level: 'error' }\n );\n return;\n }\n\n await mkdir(dirname(fieldRenameMapFilePath), { recursive: true });\n await writeFile(\n fieldRenameMapFilePath,\n JSON.stringify(fieldRenameMap),\n 'utf-8'\n );\n};\n\n/** Reads the cached field-rename tables, or `{}` when none were written. */\nconst readFieldRenameMapFile = (\n fieldRenameMapFilePath: string\n): FieldRenameMapByDictionaryKey => {\n try {\n return JSON.parse(\n readFileSync(fieldRenameMapFilePath, 'utf-8')\n ) as FieldRenameMapByDictionaryKey;\n } catch {\n return {};\n }\n};\n\n/** Removes the cached field-rename tables, ignoring a missing file. */\nconst removeFieldRenameMapFile = (fieldRenameMapFilePath: string): void => {\n try {\n rmSync(fieldRenameMapFilePath, { force: true });\n } catch {\n // Nothing to clean up.\n }\n};\n\ntype PrepareSwcOptimizationParams = {\n /** Options forwarded to the intlayer configuration loader. */\n configOptions?: GetConfigurationOptions;\n /** Pre-loaded dictionaries, to avoid a second `getDictionaries` call. */\n dictionaries?: Dictionary[];\n /** Compat-adapter callers declared by the consuming plugin, if any. */\n swcExtraCallers?: SwcExtraCallerConfig[];\n /**\n * Whether the `@intlayer/swc` plugin is installed *and* the resolved Next.js\n * version can load it. False leaves the compiled dictionaries untouched.\n */\n isSwcPluginUsable: boolean;\n};\n\n/**\n * Prepares the parts of the build optimisation the `@intlayer/swc` plugin\n * cannot do itself, and returns the field-rename tables it needs.\n *\n * Removing unused content fields (`build.purge`) and assigning short field\n * aliases (`build.minify`) require reading every component source file and\n * rewriting the compiled dictionary JSON — file I/O and cross-file state that a\n * per-file Wasm transform has no access to. That analysis therefore runs here,\n * in Node, through `@intlayer/babel`; the plugin only receives the resulting\n * tables and rewrites the matching source accesses\n * (`content.title` → `content.a`).\n *\n * The work is coordinated by a sentinel file: Next.js loads `next.config.*` in\n * several processes per build, and running the minify pass twice would derive\n * the aliases from the already-renamed dictionaries. Processes that lose the\n * race read the tables the winner cached.\n *\n * @returns The field-rename tables, keyed by dictionary key. Empty when the\n * pipeline is disabled, unavailable, or renamed nothing.\n */\nexport const prepareSwcOptimization = async (\n intlayerConfig: IntlayerConfig,\n params: PrepareSwcOptimizationParams\n): Promise<FieldRenameMapByDictionaryKey> => {\n const { configOptions, dictionaries, swcExtraCallers, isSwcPluginUsable } =\n params;\n\n const fieldRenameMapFilePath = getCacheFilePath(\n intlayerConfig,\n FIELD_RENAME_MAP_FILE_NAME\n );\n\n // A stale file from an earlier build would rename source accesses that the\n // dictionaries no longer match.\n if (\n !getIsPurgePipelineEnabled(\n intlayerConfig,\n swcExtraCallers,\n isSwcPluginUsable\n )\n ) {\n removeFieldRenameMapFile(fieldRenameMapFilePath);\n return {};\n }\n\n await runOnce(\n getCacheFilePath(intlayerConfig, PURGE_SENTINEL_FILE_NAME),\n () =>\n runPurgePipelineOnce(\n intlayerConfig,\n configOptions,\n dictionaries,\n fieldRenameMapFilePath\n ),\n { cacheTimeoutMs: PURGE_CACHE_TIMEOUT_MS }\n );\n\n return readF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gB,uBAAuB,CAC3C;CAEA,OAAO,uBAAuB,sBAAsB;AACtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swcPluginCompatibility.cjs","names":[],"sources":["../../../src/server/swcPluginCompatibility.ts"],"sourcesContent":["import { compareVersions } from '@intlayer/config/utils';\n\n/**\n * Oldest Next.js release whose bundled SWC can load the `@intlayer/swc` Wasm\n * plugin.\n *\n * A Wasm plugin only loads in a host that speaks its `swc_ecma_ast` schema.\n * Next.js 16.1.0 is the first release built on SWC's forward-compatible plugin\n * ABI — the AST travels as self-describing CBOR instead of rkyv, so a plugin\n * compiled against an older `swc_core` keeps loading in newer hosts. Every\n * earlier release uses the rkyv ABI, which requires an exact schema match and\n * rejects the plugin outright, failing the build with `failed to invoke\n * plugin`.\n *\n * Verified by driving `transformSync` on the shipped `@next/swc` binaries with\n * the plugin attached:\n *\n * | Next.js | swc_ecma_ast | plugin loads |\n * | ------- | ------------ | ------------ |\n * | 14.2.x | 0.112.7 | no |\n * | 15.5.x | 14.0.0 | no |\n * | 16.0.x | 16.0.0 | no |\n * | 16.1.x | 19.0.0 | yes |\n * | 16.2.x | 20.0.1 | yes |\n * | 16.3.x | 25.0.0 | yes |\n *\n * Keep in sync with the `swc_core` pin in\n * `packages/@intlayer/swc/Cargo.toml`: the plugin must stay on the\n * `swc_ecma_ast` version this Next.js release ships, never a newer one, or the\n * floor moves up with it.\n */\nexport const MINIMUM_SWC_PLUGIN_NEXT_VERSION = '16.1.0';\n\n/**\n * Whether `nextVersion` bundles an SWC able to load the `@intlayer/swc` Wasm\n * plugin.\n *\n * Pre-releases of a supported version (`16.1.0-canary.4`, `16.3.0-preview.5`)\n * count as supported: they track the release they lead to, and opting into a\n * canary already means opting into its churn.\n *\n * @param nextVersion - Version string read from the project's `next/package.json`.\n * @returns `true` when the plugin can be registered in `experimental.swcPlugins`.\n *\n * @example\n * ```ts\n * getIsSwcPluginSupported('16.3.0'); // true\n * getIsSwcPluginSupported('15.5.18'); // false\n * ```\n */\nexport const getIsSwcPluginSupported = (nextVersion: string): boolean =>\n compareVersions(nextVersion, '≥', MINIMUM_SWC_PLUGIN_NEXT_VERSION);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;AAmB/C,MAAa,2BAA2B,
|
|
1
|
+
{"version":3,"file":"swcPluginCompatibility.cjs","names":["compareVersions"],"sources":["../../../src/server/swcPluginCompatibility.ts"],"sourcesContent":["import { compareVersions } from '@intlayer/config/utils';\n\n/**\n * Oldest Next.js release whose bundled SWC can load the `@intlayer/swc` Wasm\n * plugin.\n *\n * A Wasm plugin only loads in a host that speaks its `swc_ecma_ast` schema.\n * Next.js 16.1.0 is the first release built on SWC's forward-compatible plugin\n * ABI — the AST travels as self-describing CBOR instead of rkyv, so a plugin\n * compiled against an older `swc_core` keeps loading in newer hosts. Every\n * earlier release uses the rkyv ABI, which requires an exact schema match and\n * rejects the plugin outright, failing the build with `failed to invoke\n * plugin`.\n *\n * Verified by driving `transformSync` on the shipped `@next/swc` binaries with\n * the plugin attached:\n *\n * | Next.js | swc_ecma_ast | plugin loads |\n * | ------- | ------------ | ------------ |\n * | 14.2.x | 0.112.7 | no |\n * | 15.5.x | 14.0.0 | no |\n * | 16.0.x | 16.0.0 | no |\n * | 16.1.x | 19.0.0 | yes |\n * | 16.2.x | 20.0.1 | yes |\n * | 16.3.x | 25.0.0 | yes |\n *\n * Keep in sync with the `swc_core` pin in\n * `packages/@intlayer/swc/Cargo.toml`: the plugin must stay on the\n * `swc_ecma_ast` version this Next.js release ships, never a newer one, or the\n * floor moves up with it.\n */\nexport const MINIMUM_SWC_PLUGIN_NEXT_VERSION = '16.1.0';\n\n/**\n * Whether `nextVersion` bundles an SWC able to load the `@intlayer/swc` Wasm\n * plugin.\n *\n * Pre-releases of a supported version (`16.1.0-canary.4`, `16.3.0-preview.5`)\n * count as supported: they track the release they lead to, and opting into a\n * canary already means opting into its churn.\n *\n * @param nextVersion - Version string read from the project's `next/package.json`.\n * @returns `true` when the plugin can be registered in `experimental.swcPlugins`.\n *\n * @example\n * ```ts\n * getIsSwcPluginSupported('16.3.0'); // true\n * getIsSwcPluginSupported('15.5.18'); // false\n * ```\n */\nexport const getIsSwcPluginSupported = (nextVersion: string): boolean =>\n compareVersions(nextVersion, '≥', MINIMUM_SWC_PLUGIN_NEXT_VERSION);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;AAmB/C,MAAa,2BAA2B,oBACtCA,wCAAgB,aAAa,KAAK,+BAA+B"}
|
|
@@ -10,7 +10,8 @@ let react_intlayer_server = require("react-intlayer/server");
|
|
|
10
10
|
* If the locale is not provided, it will use the locale from the server context.
|
|
11
11
|
*/
|
|
12
12
|
const useDictionary = (dictionary, localeOrSelector) => {
|
|
13
|
-
|
|
13
|
+
const storedLocale = require_server_useIntlayer.safeUseLocale();
|
|
14
|
+
return (0, react_intlayer_server.useDictionary)(dictionary, localeOrSelector, storedLocale);
|
|
14
15
|
};
|
|
15
16
|
|
|
16
17
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionary.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionary as useDictionaryBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that transforms a dictionary (or qualified\n * dictionary group) and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryBase<T, A>(dictionary, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAC+C;
|
|
1
|
+
{"version":3,"file":"useDictionary.cjs","names":["safeUseLocale","useDictionaryBase"],"sources":["../../../src/server/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionary as useDictionaryBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that transforms a dictionary (or qualified\n * dictionary group) and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryBase<T, A>(dictionary, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAC+C;CAC/C,MAAM,eAAeA,yCAAc;CAEnC,WAAOC,qCAAwB,YAAY,kBAAkB,YAAY;AAC3E"}
|
|
@@ -9,7 +9,8 @@ let react_intlayer_server = require("react-intlayer/server");
|
|
|
9
9
|
* If the locale is not provided, it will use the locale from the server context
|
|
10
10
|
*/
|
|
11
11
|
const useDictionaryAsync = async (dictionaryPromise, locale) => {
|
|
12
|
-
|
|
12
|
+
const storedLocale = await require_server_getLocale.getLocale();
|
|
13
|
+
return (0, react_intlayer_server.useDictionaryAsync)(dictionaryPromise, locale, storedLocale);
|
|
13
14
|
};
|
|
14
15
|
|
|
15
16
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionaryAsync.cjs","names":["getLocale"],"sources":["../../../src/server/useDictionaryAsync.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryAsync as useDictionaryAsyncBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\n/**\n * On the server side, Hook that transform a dictionary and return the content\n *\n * If the locale is not provided, it will use the locale from the server context\n */\nexport const useDictionaryAsync = async <\n const T extends Dictionary,\n const L extends DeclaredLocales = DeclaredLocales,\n>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n locale?: L\n): ReturnType<typeof useDictionaryAsyncBase<T, L>> => {\n const storedLocale = await getLocale();\n\n return useDictionaryAsyncBase<T, L>(dictionaryPromise, locale, storedLocale);\n};\n"],"mappings":";;;;;;;;;;AAaA,MAAa,qBAAqB,OAIhC,mBACA,WACoD;
|
|
1
|
+
{"version":3,"file":"useDictionaryAsync.cjs","names":["getLocale","useDictionaryAsyncBase"],"sources":["../../../src/server/useDictionaryAsync.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryAsync as useDictionaryAsyncBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\n/**\n * On the server side, Hook that transform a dictionary and return the content\n *\n * If the locale is not provided, it will use the locale from the server context\n */\nexport const useDictionaryAsync = async <\n const T extends Dictionary,\n const L extends DeclaredLocales = DeclaredLocales,\n>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n locale?: L\n): ReturnType<typeof useDictionaryAsyncBase<T, L>> => {\n const storedLocale = await getLocale();\n\n return useDictionaryAsyncBase<T, L>(dictionaryPromise, locale, storedLocale);\n};\n"],"mappings":";;;;;;;;;;AAaA,MAAa,qBAAqB,OAIhC,mBACA,WACoD;CACpD,MAAM,eAAe,MAAMA,mCAAU;CAErC,WAAOC,0CAA6B,mBAAmB,QAAQ,YAAY;AAC7E"}
|
|
@@ -10,7 +10,8 @@ let react_intlayer_server = require("react-intlayer/server");
|
|
|
10
10
|
* If the locale is not provided, it will use the locale from the server context.
|
|
11
11
|
*/
|
|
12
12
|
const useDictionaryDynamic = (dictionaryPromise, key, localeOrSelector) => {
|
|
13
|
-
|
|
13
|
+
const storedLocale = require_server_useIntlayer.safeUseLocale();
|
|
14
|
+
return (0, react_intlayer_server.useDictionaryDynamic)(dictionaryPromise, key, localeOrSelector, storedLocale);
|
|
14
15
|
};
|
|
15
16
|
|
|
16
17
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionaryDynamic.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionaryDynamic.ts"],"sourcesContent":["import type { QualifiedDynamicLoaderMap } from '@intlayer/core/dictionaryManipulator';\nimport type {\n Dictionary,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryDynamic as useDictionaryDynamicBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that lazily loads a dictionary (plain or qualified)\n * and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const A extends LocalesValues | DictionarySelector = DeclaredLocales,\n>(\n dictionaryPromise:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: string,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryDynamicBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryDynamicBase<T, A>(\n dictionaryPromise,\n key,\n localeOrSelector,\n storedLocale\n );\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,wBAIX,mBAGA,KACA,qBACsD;
|
|
1
|
+
{"version":3,"file":"useDictionaryDynamic.cjs","names":["safeUseLocale","useDictionaryDynamicBase"],"sources":["../../../src/server/useDictionaryDynamic.ts"],"sourcesContent":["import type { QualifiedDynamicLoaderMap } from '@intlayer/core/dictionaryManipulator';\nimport type {\n Dictionary,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryDynamic as useDictionaryDynamicBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that lazily loads a dictionary (plain or qualified)\n * and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const A extends LocalesValues | DictionarySelector = DeclaredLocales,\n>(\n dictionaryPromise:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: string,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryDynamicBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryDynamicBase<T, A>(\n dictionaryPromise,\n key,\n localeOrSelector,\n storedLocale\n );\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,wBAIX,mBAGA,KACA,qBACsD;CACtD,MAAM,eAAeA,yCAAc;CAEnC,WAAOC,4CACL,mBACA,KACA,kBACA,YACF;AACF"}
|
|
@@ -23,7 +23,8 @@ const safeUseLocale = () => {
|
|
|
23
23
|
* If the locale is not provided, it will use the locale from the server context.
|
|
24
24
|
*/
|
|
25
25
|
const useIntlayer = (key, localeOrSelector) => {
|
|
26
|
-
|
|
26
|
+
const storedLocale = safeUseLocale();
|
|
27
|
+
return (0, react_intlayer_server.useIntlayer)(key, localeOrSelector, storedLocale);
|
|
27
28
|
};
|
|
28
29
|
|
|
29
30
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIntlayer.cjs","names":["React","getLocale"],"sources":["../../../src/server/useIntlayer.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport React from 'react';\nimport { useIntlayer as useIntlayerBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\nconst getCachedLocale =\n typeof React.cache === 'function' ? React.cache(getLocale) : getLocale;\n\nexport const safeUseLocale = (): Locale | undefined => {\n // getLocale returns a Promise based on your TS error\n const localeData = getCachedLocale() as Promise<Locale> | Locale;\n\n if (localeData instanceof Promise) {\n if (typeof React.use === 'function') {\n return React.use(localeData); // Safely unwraps in React 19+\n }\n\n // React < 19 cannot synchronously unwrap Promises in hooks.\n // Return undefined to trigger the localeTarget fallback.\n return undefined;\n }\n\n return localeData;\n};\n\n/**\n * On the server side, hook that picks one dictionary by its key and returns the\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): ReturnType<typeof useIntlayerBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useIntlayerBase<T, A>(key, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;AAWA,MAAM,kBACJ,OAAOA,cAAM,UAAU,aAAaA,cAAM,MAAMC,kCAAS,IAAIA;AAE/D,MAAa,sBAA0C;CAErD,MAAM,aAAa,gBAAgB;CAEnC,IAAI,sBAAsB,SAAS;EACjC,IAAI,OAAOD,cAAM,QAAQ,YACvB,OAAOA,cAAM,IAAI,UAAU;EAK7B;CACF;CAEA,OAAO;AACT;;;;;;;;AASA,MAAa,eAIX,KACA,qBAC6C;
|
|
1
|
+
{"version":3,"file":"useIntlayer.cjs","names":["React","getLocale","useIntlayerBase"],"sources":["../../../src/server/useIntlayer.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport React from 'react';\nimport { useIntlayer as useIntlayerBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\nconst getCachedLocale =\n typeof React.cache === 'function' ? React.cache(getLocale) : getLocale;\n\nexport const safeUseLocale = (): Locale | undefined => {\n // getLocale returns a Promise based on your TS error\n const localeData = getCachedLocale() as Promise<Locale> | Locale;\n\n if (localeData instanceof Promise) {\n if (typeof React.use === 'function') {\n return React.use(localeData); // Safely unwraps in React 19+\n }\n\n // React < 19 cannot synchronously unwrap Promises in hooks.\n // Return undefined to trigger the localeTarget fallback.\n return undefined;\n }\n\n return localeData;\n};\n\n/**\n * On the server side, hook that picks one dictionary by its key and returns the\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): ReturnType<typeof useIntlayerBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useIntlayerBase<T, A>(key, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;AAWA,MAAM,kBACJ,OAAOA,cAAM,UAAU,aAAaA,cAAM,MAAMC,kCAAS,IAAIA;AAE/D,MAAa,sBAA0C;CAErD,MAAM,aAAa,gBAAgB;CAEnC,IAAI,sBAAsB,SAAS;EACjC,IAAI,OAAOD,cAAM,QAAQ,YACvB,OAAOA,cAAM,IAAI,UAAU;EAK7B;CACF;CAEA,OAAO;AACT;;;;;;;;AASA,MAAa,eAIX,KACA,qBAC6C;CAC7C,MAAM,eAAe,cAAc;CAEnC,WAAOE,mCAAsB,KAAK,kBAAkB,YAAY;AAClE"}
|
|
@@ -3,11 +3,11 @@ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
|
3
3
|
const require_server_prepareSwcOptimization = require('./prepareSwcOptimization.cjs');
|
|
4
4
|
const require_server_swcPluginCompatibility = require('./swcPluginCompatibility.cjs');
|
|
5
5
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
6
|
-
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
7
6
|
let node_path = require("node:path");
|
|
8
7
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
9
8
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
10
9
|
let _intlayer_config_envVars = require("@intlayer/config/envVars");
|
|
10
|
+
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
11
11
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
12
12
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
13
13
|
let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
|
|
@@ -101,14 +101,14 @@ const getPruneConfig = ({ intlayerConfig, isBuildCommand, isTurbopackEnabled, is
|
|
|
101
101
|
(0, _intlayer_config_logger.colorize)("package to enable build optimization. See documentation:", _intlayer_config_colors.GREY),
|
|
102
102
|
(0, _intlayer_config_logger.colorize)("https://intlayer.org/docs/bundle-optimization", _intlayer_config_colors.GREY_LIGHT)
|
|
103
103
|
]);
|
|
104
|
-
}, { cacheTimeoutMs:
|
|
104
|
+
}, { cacheTimeoutMs: 3e4 });
|
|
105
105
|
(0, _intlayer_engine_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-compiler-plugin-enabled.lock"), () => {
|
|
106
106
|
if (getIsBabelExtractPluginAvailable(intlayerConfig)) {
|
|
107
107
|
let isEnabled = intlayerConfig.compiler?.enabled ?? true;
|
|
108
108
|
if (isEnabled === "build-only") isEnabled = !isDevCommand;
|
|
109
109
|
if (isEnabled) logger("Intlayer compiler enabled");
|
|
110
110
|
}
|
|
111
|
-
}, { cacheTimeoutMs:
|
|
111
|
+
}, { cacheTimeoutMs: 3e4 });
|
|
112
112
|
if (!isSwcPluginAvailable || !isSwcPluginSupported) return {};
|
|
113
113
|
const dictionariesEntryPath = (0, node_path.join)(mainDir, "dictionaries.mjs");
|
|
114
114
|
const dynamicDictionariesEntryPath = (0, node_path.join)(mainDir, "dynamic_dictionaries.mjs");
|
|
@@ -255,18 +255,19 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
|
|
|
255
255
|
serverComponentsExternalPackages: serverExternalPackages
|
|
256
256
|
}
|
|
257
257
|
};
|
|
258
|
-
if (isTurbopackEnabled)
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
258
|
+
if (isTurbopackEnabled) {
|
|
259
|
+
if (isGteNext15 && isTurbopackStable) config = {
|
|
260
|
+
...config,
|
|
261
|
+
turbopack: turboConfig
|
|
262
|
+
};
|
|
263
|
+
else config = {
|
|
264
|
+
...config,
|
|
265
|
+
experimental: {
|
|
266
|
+
...config?.experimental ?? {},
|
|
267
|
+
turbo: turboConfig
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
} else config = {
|
|
270
271
|
...config,
|
|
271
272
|
webpack: (config, options) => {
|
|
272
273
|
const { isServer, nextRuntime } = options;
|
|
@@ -313,7 +314,8 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
|
|
|
313
314
|
swcExtraCallers: configOptions?.swcExtraCallers,
|
|
314
315
|
fieldRenameMap: configOptions?.fieldRenameMap
|
|
315
316
|
});
|
|
316
|
-
|
|
317
|
+
const intlayerNextConfig = (0, defu.defu)(getNewConfig(), pruneConfig);
|
|
318
|
+
return (0, defu.defu)(intlayerNextConfig, nextConfig);
|
|
317
319
|
};
|
|
318
320
|
/**
|
|
319
321
|
* A Next.js plugin that adds the intlayer configuration to the webpack configuration
|
|
@@ -338,7 +340,7 @@ const withIntlayer = async (nextConfig = {}, configOptions) => {
|
|
|
338
340
|
const { mode } = intlayerConfig.build;
|
|
339
341
|
if (!isStartCommand && (isDevCommand || isBuildCommand || mode === "auto")) await (0, _intlayer_engine_build.prepareIntlayer)(intlayerConfig, {
|
|
340
342
|
clean: isBuildCommand,
|
|
341
|
-
cacheTimeoutMs: isBuildCommand ?
|
|
343
|
+
cacheTimeoutMs: isBuildCommand ? 3e4 : 36e5,
|
|
342
344
|
env: isBuildCommand ? "prod" : "dev"
|
|
343
345
|
});
|
|
344
346
|
const { isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","getIsSwcPluginSupported","ANSIColors","MINIMUM_SWC_PLUGIN_NEXT_VERSION","IMPORT_MODE","getIsPurgePipelineAvailable","resolveSwcLogLevel","IntlayerPlugin","prepareSwcOptimization"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n formatOptimizedNestingEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getNestedDictionaryGraph } from '@intlayer/core/dictionaryManipulator';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\nimport {\n type FieldRenameMapByDictionaryKey,\n getIsPurgePipelineAvailable,\n prepareSwcOptimization,\n resolveSwcLogLevel,\n} from './prepareSwcOptimization';\nimport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\nexport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n nextVersion,\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n /**\n * Whether this Next.js release can load the `@intlayer/swc` Wasm plugin.\n * See {@link MINIMUM_SWC_PLUGIN_NEXT_VERSION}.\n */\n isSwcPluginSupported: getIsSwcPluginSupported(nextVersion),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\ntype GetPruneConfigParams = {\n intlayerConfig: IntlayerConfig;\n isBuildCommand: boolean;\n isTurbopackEnabled: boolean;\n isDevCommand: boolean;\n isGteNext13: boolean;\n /** Whether the resolved Next.js version can load the Wasm plugin. */\n isSwcPluginSupported: boolean;\n /** Resolved Next.js version, reported when the plugin has to stand down. */\n nextVersion: string;\n swcExtraCallers?: SwcExtraCallerConfig[];\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\nconst getPruneConfig = ({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers,\n fieldRenameMap,\n}: GetPruneConfigParams): Partial<NextConfig> => {\n const { optimize, minify, purge } = intlayerConfig.build;\n const editorEnabled = intlayerConfig.editor.enabled;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable && !isSwcPluginSupported) {\n logger(\n [\n `Build optimization ${colorize('disabled', ANSIColors.GREY_DARK)}:`,\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n `cannot run on Next.js ${nextVersion} — its bundled SWC predates the`,\n ANSIColors.GREY\n ),\n colorize(\n 'stable Wasm plugin ABI. Upgrade to Next.js',\n ANSIColors.GREY\n ),\n colorize(MINIMUM_SWC_PLUGIN_NEXT_VERSION, ANSIColors.BLUE),\n colorize('or later to enable it.', ANSIColors.GREY),\n ],\n { level: 'warn' }\n );\n } else if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n\n // The purge / minify pipeline stands down — with its own explanation —\n // when the editor needs full dictionary content, when compat-adapter\n // callers hide call sites from the usage analyser, or when\n // `@intlayer/babel` (which runs it) is not resolvable.\n const isPurgePipelineEnabled =\n !editorEnabled &&\n !swcExtraCallers?.length &&\n getIsPurgePipelineAvailable(intlayerConfig);\n\n if (isPurgePipelineEnabled && minify) {\n logger(\n `Dictionary minification ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n\n if (isPurgePipelineEnabled && purge) {\n logger(\n `Dictionary purge unused keys ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n // Only the enabled state is reported: disabling the compiler is an\n // explicit configuration choice, so announcing it on every build adds\n // noise without telling the user anything they did not ask for.\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n // Registering the plugin on a host that cannot load it is not a degraded\n // build but a failed one: SWC aborts with `failed to invoke plugin`. Standing\n // down leaves the app running off the runtime dictionary registry, which the\n // transform would otherwise have emptied.\n if (!isSwcPluginAvailable || !isSwcPluginSupported) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n // Dictionaries holding `nest()` references: their static import is re-pointed\n // at the companion module carrying the nest targets.\n const nestingDictionaryKeys = [\n ...getNestedDictionaryGraph(Object.values(dictionaries)).keys(),\n ];\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n nestingDictionaryKeys,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n // Rewrites `content.title` → `content.a` to match the compiled\n // dictionaries the `build.minify` pass already renamed.\n fieldRenameMap: fieldRenameMap ?? {},\n logLevel: resolveSwcLogLevel(intlayerConfig),\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n\n /**\n * Field-rename tables produced by the purge / minify pipeline, forwarded to\n * the `@intlayer/swc` plugin so it rewrites source accesses to match the\n * renamed dictionaries.\n *\n * @internal Set by {@link withIntlayer}; `withIntlayerSync` on its own runs\n * no dictionary rewrite, so it leaves this unset and no rename is applied.\n */\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\n/**\n * Pin the env file used to resolve the Intlayer configuration to the Next.js\n * command being run (`dev` → `development`, `build`/`start` → `production`).\n *\n * Next.js loads the config file in several processes during a single command\n * (the main `build` process plus one or more Turbopack/webpack workers), and\n * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of\n * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file\n * (`.env.development.local` vs `.env.production.local`), those processes could\n * otherwise resolve *different* env values (e.g. `applicationURL`,\n * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between\n * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a\n * redundant full dictionary rebuild.\n *\n * Passing an explicit `env` keeps configuration resolution deterministic across\n * every process of the command. An `env` already set by the caller is\n * respected, and when the command cannot be determined we fall back to\n * `getConfiguration`'s own default (i.e. leave `env` unset).\n */\nconst resolveConfigOptions = (\n configOptions?: WithIntlayerOptions\n): WithIntlayerOptions | undefined => {\n // Respect an explicit override from the caller (idempotent on re-entry).\n if (configOptions?.env) return configOptions;\n\n const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();\n\n const env = isDevCommand\n ? 'development'\n : isBuildCommand || isStartCommand\n ? 'production'\n : undefined;\n\n if (!env) return configOptions;\n\n return {\n ...configOptions,\n env,\n };\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n logConfigDetails(resolvedConfigOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const {\n nextVersion,\n isGteNext13,\n isGteNext15,\n isGteNext16,\n isTurbopackStable,\n isSwcPluginSupported,\n } = getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/engine',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Selects the local `nest()` resolver, which reads the nest targets\n // attached to each dictionary by the optimize transform instead of the\n // registry that transform empties.\n ...formatOptimizedNestingEnvVar(intlayerConfig.build.optimize !== false),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/engine', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled: isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers: configOptions?.swcExtraCallers,\n fieldRenameMap: configOptions?.fieldRenameMap,\n });\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n // Remove unused content fields and rename the remaining ones to short\n // aliases, then hand the rename tables to `withIntlayerSync` so the SWC\n // plugin rewrites the matching source accesses. Only meaningful for a\n // production build — the optimize pipeline is off during `next dev`.\n //\n // `isSwcPluginUsable` gates the dictionary rewrite on the plugin actually\n // running: it is the only half that fixes up the source, so minifying without\n // it would leave the code reading field names the dictionaries no longer have.\n const { isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);\n\n const fieldRenameMap = isBuildCommand\n ? await prepareSwcOptimization(intlayerConfig, {\n configOptions: resolvedConfigOptions,\n swcExtraCallers: configOptions?.swcExtraCallers,\n isSwcPluginUsable:\n isSwcPluginSupported && getIsSwcPluginAvailable(intlayerConfig),\n })\n : {};\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, {\n ...resolvedConfigOptions,\n fieldRenameMap,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;CAElC,IAAI;EAIF,eAFE,eAAe,OAAO,yDAA6B,EAC1B,CAAC,mBACZ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AgB,UAE9C,OAAO,QAAQ,KAAK,IAAIK,iCAAe,cAAc,CAAC;IAGxD,OAAO;GACT;EACF;EAGF,OAAO;CACT;CAEA,MAAM,cAAmC,eAAe;EACtD;EACA;EACA,oBAAoB,sBAAsB;EAC1C;EACA;EACA;EACA;EACA,iBAAiB,eAAe;EAChC,gBAAgB,eAAe;CACjC,CAAC;CAUD,qCAPE,aAAa,GACb,WAImC,GAAG,UAE5B;AACd;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,OAC1B,aAA6B,CAAC,GAC9B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,iBAAiB;CAE1E,QAAQ,IAAI,0BAA0B,eAAe,SAAS;CAE9D,MAAM,wBAAwB,qBAAqB,aAAa;CAEhE,MAAM,6DAAkC,qBAAqB;CAE7D,MAAM,EAAE,SAAS,eAAe;CAKhC,IAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,SAEjE,kDAAsB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;CACjC,CAAC;CAWH,MAAM,EAAE,yBAAyB,oBAAoB,cAAc;CAEnE,MAAM,iBAAiB,iBACnB,MAAMC,6DAAuB,gBAAgB;EAC3C,eAAe;EACf,iBAAiB,eAAe;EAChC,mBACE,wBAAwB,wBAAwB,cAAc;CAClE,CAAC,IACD,CAAC;CAEL,MAAM,qBAAqB,MAAM;CAEjC,OAAO,iBAAiB,oBAAoB;EAC1C,GAAG;EACH;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","getProjectRequire","compareVersions","getIsSwcPluginSupported","normalizePath","relative","getAppLogger","join","colorize","ANSIColors","MINIMUM_SWC_PLUGIN_NEXT_VERSION","IMPORT_MODE","getIsPurgePipelineAvailable","buildComponentFilesList","getDictionaries","getNestedDictionaryGraph","resolveSwcLogLevel","getConfiguration","getAlias","getUnusedNodeTypes","formatNodeTypeToEnvVar","formatOptimizedNestingEnvVar","formatDictionarySelectorEnvVar","getHasDictionarySelector","getConfigEnvVars","resolve","IntlayerPlugin","prepareIntlayer","prepareSwcOptimization"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n formatOptimizedNestingEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getNestedDictionaryGraph } from '@intlayer/core/dictionaryManipulator';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\nimport {\n type FieldRenameMapByDictionaryKey,\n getIsPurgePipelineAvailable,\n prepareSwcOptimization,\n resolveSwcLogLevel,\n} from './prepareSwcOptimization';\nimport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\nexport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n nextVersion,\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n /**\n * Whether this Next.js release can load the `@intlayer/swc` Wasm plugin.\n * See {@link MINIMUM_SWC_PLUGIN_NEXT_VERSION}.\n */\n isSwcPluginSupported: getIsSwcPluginSupported(nextVersion),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\ntype GetPruneConfigParams = {\n intlayerConfig: IntlayerConfig;\n isBuildCommand: boolean;\n isTurbopackEnabled: boolean;\n isDevCommand: boolean;\n isGteNext13: boolean;\n /** Whether the resolved Next.js version can load the Wasm plugin. */\n isSwcPluginSupported: boolean;\n /** Resolved Next.js version, reported when the plugin has to stand down. */\n nextVersion: string;\n swcExtraCallers?: SwcExtraCallerConfig[];\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\nconst getPruneConfig = ({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers,\n fieldRenameMap,\n}: GetPruneConfigParams): Partial<NextConfig> => {\n const { optimize, minify, purge } = intlayerConfig.build;\n const editorEnabled = intlayerConfig.editor.enabled;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable && !isSwcPluginSupported) {\n logger(\n [\n `Build optimization ${colorize('disabled', ANSIColors.GREY_DARK)}:`,\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n `cannot run on Next.js ${nextVersion} — its bundled SWC predates the`,\n ANSIColors.GREY\n ),\n colorize(\n 'stable Wasm plugin ABI. Upgrade to Next.js',\n ANSIColors.GREY\n ),\n colorize(MINIMUM_SWC_PLUGIN_NEXT_VERSION, ANSIColors.BLUE),\n colorize('or later to enable it.', ANSIColors.GREY),\n ],\n { level: 'warn' }\n );\n } else if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n\n // The purge / minify pipeline stands down — with its own explanation —\n // when the editor needs full dictionary content, when compat-adapter\n // callers hide call sites from the usage analyser, or when\n // `@intlayer/babel` (which runs it) is not resolvable.\n const isPurgePipelineEnabled =\n !editorEnabled &&\n !swcExtraCallers?.length &&\n getIsPurgePipelineAvailable(intlayerConfig);\n\n if (isPurgePipelineEnabled && minify) {\n logger(\n `Dictionary minification ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n\n if (isPurgePipelineEnabled && purge) {\n logger(\n `Dictionary purge unused keys ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n // Only the enabled state is reported: disabling the compiler is an\n // explicit configuration choice, so announcing it on every build adds\n // noise without telling the user anything they did not ask for.\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n // Registering the plugin on a host that cannot load it is not a degraded\n // build but a failed one: SWC aborts with `failed to invoke plugin`. Standing\n // down leaves the app running off the runtime dictionary registry, which the\n // transform would otherwise have emptied.\n if (!isSwcPluginAvailable || !isSwcPluginSupported) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n // Dictionaries holding `nest()` references: their static import is re-pointed\n // at the companion module carrying the nest targets.\n const nestingDictionaryKeys = [\n ...getNestedDictionaryGraph(Object.values(dictionaries)).keys(),\n ];\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n nestingDictionaryKeys,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n // Rewrites `content.title` → `content.a` to match the compiled\n // dictionaries the `build.minify` pass already renamed.\n fieldRenameMap: fieldRenameMap ?? {},\n logLevel: resolveSwcLogLevel(intlayerConfig),\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n\n /**\n * Field-rename tables produced by the purge / minify pipeline, forwarded to\n * the `@intlayer/swc` plugin so it rewrites source accesses to match the\n * renamed dictionaries.\n *\n * @internal Set by {@link withIntlayer}; `withIntlayerSync` on its own runs\n * no dictionary rewrite, so it leaves this unset and no rename is applied.\n */\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\n/**\n * Pin the env file used to resolve the Intlayer configuration to the Next.js\n * command being run (`dev` → `development`, `build`/`start` → `production`).\n *\n * Next.js loads the config file in several processes during a single command\n * (the main `build` process plus one or more Turbopack/webpack workers), and\n * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of\n * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file\n * (`.env.development.local` vs `.env.production.local`), those processes could\n * otherwise resolve *different* env values (e.g. `applicationURL`,\n * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between\n * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a\n * redundant full dictionary rebuild.\n *\n * Passing an explicit `env` keeps configuration resolution deterministic across\n * every process of the command. An `env` already set by the caller is\n * respected, and when the command cannot be determined we fall back to\n * `getConfiguration`'s own default (i.e. leave `env` unset).\n */\nconst resolveConfigOptions = (\n configOptions?: WithIntlayerOptions\n): WithIntlayerOptions | undefined => {\n // Respect an explicit override from the caller (idempotent on re-entry).\n if (configOptions?.env) return configOptions;\n\n const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();\n\n const env = isDevCommand\n ? 'development'\n : isBuildCommand || isStartCommand\n ? 'production'\n : undefined;\n\n if (!env) return configOptions;\n\n return {\n ...configOptions,\n env,\n };\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n logConfigDetails(resolvedConfigOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const {\n nextVersion,\n isGteNext13,\n isGteNext15,\n isGteNext16,\n isTurbopackStable,\n isSwcPluginSupported,\n } = getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/engine',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Selects the local `nest()` resolver, which reads the nest targets\n // attached to each dictionary by the optimize transform instead of the\n // registry that transform empties.\n ...formatOptimizedNestingEnvVar(intlayerConfig.build.optimize !== false),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/engine', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled: isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers: configOptions?.swcExtraCallers,\n fieldRenameMap: configOptions?.fieldRenameMap,\n });\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n // Remove unused content fields and rename the remaining ones to short\n // aliases, then hand the rename tables to `withIntlayerSync` so the SWC\n // plugin rewrites the matching source accesses. Only meaningful for a\n // production build — the optimize pipeline is off during `next dev`.\n //\n // `isSwcPluginUsable` gates the dictionary rewrite on the plugin actually\n // running: it is the only half that fixes up the source, so minifying without\n // it would leave the code reading field names the dictionaries no longer have.\n const { isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);\n\n const fieldRenameMap = isBuildCommand\n ? await prepareSwcOptimization(intlayerConfig, {\n configOptions: resolvedConfigOptions,\n swcExtraCallers: configOptions?.swcExtraCallers,\n isSwcPluginUsable:\n isSwcPluginSupported && getIsSwcPluginAvailable(intlayerConfig),\n })\n : {};\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, {\n ...resolvedConfigOptions,\n fieldRenameMap,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;CAElC,IAAI;EAIF,eAFE,eAAe,OAAO,eAAWC,0CAAkB,EAC1B,CAAC,mBACZ,CAAC,CAAC;CACpB,QAAQ,CAER;CAEA,OAAO;EACL;EACA,iBAAaC,wCAAgB,aAAa,KAAK,QAAQ;EACvD,iBAAaA,wCAAgB,aAAa,KAAK,QAAQ;EACvD,iBAAaA,wCAAgB,aAAa,KAAK,QAAQ;EACvD,uBAAmBA,wCAAgB,aAAa,KAAK,QAAQ;;;;;EAK7D,sBAAsBC,8DAAwB,WAAW;CAC3D;AACF;AAGA,MAAM,2BAA2B,mBAAmC;CAClE,IAAI;EAGF,CADE,eAAe,OAAO,eAAWF,0CAAkB,EACtC,CAAC,QAAQ,eAAe;EACvC,OAAO;CACT,SAAS,IAAI;EACX,OAAO;CACT;AACF;AAGA,MAAM,oCAAoC,mBAAmC;CAC3E,IAAI;EAGF,CADE,eAAe,OAAO,eAAWA,0CAAkB,EACtC,CAAC,QAAQ,iBAAiB;EACzC,OAAO;CACT,SAAS,IAAI;EACX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Ae;EAChC,gBAAgB,eAAe;CACjC,CAAC;CAED,MAAM,yBAA0C,WAC9C,aAAa,GACb,WACF;CAKA,WAFe,WAAK,oBAAoB,UAE5B;AACd;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,OAC1B,aAA6B,CAAC,GAC9B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,iBAAiB;CAE1E,QAAQ,IAAI,0BAA0B,eAAe,SAAS;CAE9D,MAAM,wBAAwB,qBAAqB,aAAa;CAEhE,MAAM,qBAAiBT,wCAAiB,qBAAqB;CAE7D,MAAM,EAAE,SAAS,eAAe;CAKhC,IAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,SAEjE,UAAMU,wCAAgB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MACA;EACJ,KAAK,iBAAiB,SAAS;CACjC,CAAC;CAWH,MAAM,EAAE,yBAAyB,oBAAoB,cAAc;CAEnE,MAAM,iBAAiB,iBACnB,MAAMC,6DAAuB,gBAAgB;EAC3C,eAAe;EACf,iBAAiB,eAAe;EAChC,mBACE,wBAAwB,wBAAwB,cAAc;CAClE,CAAC,IACD,CAAC;CAEL,MAAM,qBAAqB,MAAM;CAEjC,OAAO,iBAAiB,oBAAoB;EAC1C,GAAG;EACH;CACF,CAAC;AACH"}
|
|
@@ -35,36 +35,37 @@ import { useCallback } from "react";
|
|
|
35
35
|
const useLocale = ({ onChange = "replace", onLocaleChange, isCookieEnabled } = {}) => {
|
|
36
36
|
const { replace, push } = useRouter();
|
|
37
37
|
const pathWithoutLocale = usePathname$1();
|
|
38
|
+
const redirectionFunction = useCallback((locale) => {
|
|
39
|
+
if (!onChange) return;
|
|
40
|
+
const currentDomain = process.env.INTLAYER_ROUTING_DOMAINS !== "false" && typeof window !== "undefined" ? window.location.hostname : void 0;
|
|
41
|
+
const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, { currentDomain });
|
|
42
|
+
if (typeof onChange === "function") {
|
|
43
|
+
onChange({
|
|
44
|
+
locale,
|
|
45
|
+
path: pathWithLocale
|
|
46
|
+
});
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && checkIsURLAbsolute(pathWithLocale)) {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = new URL(pathWithLocale);
|
|
52
|
+
if (parsed.protocol === "http:" || parsed.protocol === "https:") window.location.href = pathWithLocale;
|
|
53
|
+
} catch {}
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (onChange === "replace") replace(pathWithLocale);
|
|
57
|
+
if (onChange === "push") push(pathWithLocale);
|
|
58
|
+
onLocaleChange?.(locale);
|
|
59
|
+
}, [
|
|
60
|
+
replace,
|
|
61
|
+
push,
|
|
62
|
+
pathWithoutLocale,
|
|
63
|
+
onChange,
|
|
64
|
+
onLocaleChange
|
|
65
|
+
]);
|
|
38
66
|
return {
|
|
39
67
|
...useLocale$1({
|
|
40
|
-
onLocaleChange:
|
|
41
|
-
if (!onChange) return;
|
|
42
|
-
const currentDomain = process.env.INTLAYER_ROUTING_DOMAINS !== "false" && typeof window !== "undefined" ? window.location.hostname : void 0;
|
|
43
|
-
const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, { currentDomain });
|
|
44
|
-
if (typeof onChange === "function") {
|
|
45
|
-
onChange({
|
|
46
|
-
locale,
|
|
47
|
-
path: pathWithLocale
|
|
48
|
-
});
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && checkIsURLAbsolute(pathWithLocale)) {
|
|
52
|
-
try {
|
|
53
|
-
const parsed = new URL(pathWithLocale);
|
|
54
|
-
if (parsed.protocol === "http:" || parsed.protocol === "https:") window.location.href = pathWithLocale;
|
|
55
|
-
} catch {}
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
if (onChange === "replace") replace(pathWithLocale);
|
|
59
|
-
if (onChange === "push") push(pathWithLocale);
|
|
60
|
-
onLocaleChange?.(locale);
|
|
61
|
-
}, [
|
|
62
|
-
replace,
|
|
63
|
-
push,
|
|
64
|
-
pathWithoutLocale,
|
|
65
|
-
onChange,
|
|
66
|
-
onLocaleChange
|
|
67
|
-
]),
|
|
68
|
+
onLocaleChange: redirectionFunction,
|
|
68
69
|
isCookieEnabled
|
|
69
70
|
}),
|
|
70
71
|
pathWithoutLocale
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocale.mjs","names":["usePathname","useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa,EACxB,WAAW,WACX,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,SAAS,SAAS,UAAU;CACpC,MAAM,oBAAoBA,cAAY;
|
|
1
|
+
{"version":3,"file":"useLocale.mjs","names":["usePathname","useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa,EACxB,WAAW,WACX,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,SAAS,SAAS,UAAU;CACpC,MAAM,oBAAoBA,cAAY;CAEtC,MAAM,sBAAsB,aACzB,WAA0B;EACzB,IAAI,CAAC,UAAU;EAEf,MAAM,gBACJ,QAAQ,IAAI,6BAA6B,WACzC,OAAO,WAAW,cACd,OAAO,SAAS,WAChB;EAEN,MAAM,iBAAiB,gBAAgB,mBAAmB,QAAQ,EAChE,cACF,CAAC;EAED,IAAI,OAAO,aAAa,YAAY;GAClC,SAAS;IAAE;IAAQ,MAAM;GAAe,CAAC;GACzC;EACF;EAIA,IACE,QAAQ,IAAI,6BAA6B,WACzC,mBAAmB,cAAc,GACjC;GACA,IAAI;IACF,MAAM,SAAS,IAAI,IAAI,cAAc;IACrC,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACrD,OAAO,SAAS,OAAO;GAE3B,QAAQ,CAER;GACA;EACF;EAEA,IAAI,aAAa,WACf,QAAQ,cAAc;EAExB,IAAI,aAAa,QACf,KAAK,cAAc;EAGrB,iBAAiB,MAAyB;CAC5C,GACA;EAAC;EAAS;EAAM;EAAmB;EAAU;CAAc,CAC7D;CAOA,OAAO;EACL,GANsBC,YAAe;GACrC,gBAAgB;GAChB;EACF,CAGmB;EACjB;CACF;AACF"}
|
|
@@ -30,18 +30,19 @@ import { useRouter } from "next/router.js";
|
|
|
30
30
|
const useLocalePageRouter = ({ onLocaleChange, isCookieEnabled } = {}) => {
|
|
31
31
|
const { push, pathname, reload } = useRouter();
|
|
32
32
|
const pathWithoutLocale = useMemo(() => getPathWithoutLocale(pathname), [pathname]);
|
|
33
|
+
const redirectionFunction = useCallback((locale) => {
|
|
34
|
+
const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);
|
|
35
|
+
push(pathWithLocale);
|
|
36
|
+
onLocaleChange?.(locale);
|
|
37
|
+
return reload();
|
|
38
|
+
}, [
|
|
39
|
+
pathWithoutLocale,
|
|
40
|
+
onLocaleChange,
|
|
41
|
+
reload
|
|
42
|
+
]);
|
|
33
43
|
return {
|
|
34
44
|
...useLocale({
|
|
35
|
-
onLocaleChange:
|
|
36
|
-
const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);
|
|
37
|
-
push(pathWithLocale);
|
|
38
|
-
onLocaleChange?.(locale);
|
|
39
|
-
return reload();
|
|
40
|
-
}, [
|
|
41
|
-
pathWithoutLocale,
|
|
42
|
-
onLocaleChange,
|
|
43
|
-
reload
|
|
44
|
-
]),
|
|
45
|
+
onLocaleChange: redirectionFunction,
|
|
45
46
|
isCookieEnabled
|
|
46
47
|
}),
|
|
47
48
|
pathWithoutLocale
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocalePageRouter.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,uBAAuB,EAClC,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,MAAM,UAAU,WAAW,UAAU;CAC7C,MAAM,oBAAoB,cAClB,qBAAqB,QAAQ,GACnC,CAAC,QAAQ,CACX;
|
|
1
|
+
{"version":3,"file":"useLocalePageRouter.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,uBAAuB,EAClC,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,MAAM,UAAU,WAAW,UAAU;CAC7C,MAAM,oBAAoB,cAClB,qBAAqB,QAAQ,GACnC,CAAC,QAAQ,CACX;CAEA,MAAM,sBAAsB,aACzB,WAA0B;EACzB,MAAM,iBAAiB,gBAAgB,mBAAmB,MAAM;EAEhE,KAAK,cAAc;EAEnB,iBAAiB,MAAgB;EAEjC,OAAO,OAAO;CAChB,GACA;EAAC;EAAmB;EAAgB;CAAM,CAC5C;CAOA,OAAO;EACL,GANsBA,UAAe;GACrC,gBAAgB;GAChB;EACF,CAGmB;EACjB;CACF;AACF"}
|
|
@@ -90,7 +90,8 @@ const intlayerProxy = (request, _event, _response) => {
|
|
|
90
90
|
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && !pathLocale) {
|
|
91
91
|
const domainLocale = getLocaleFromDomain(request.nextUrl.hostname, domains);
|
|
92
92
|
if (domainLocale) {
|
|
93
|
-
const
|
|
93
|
+
const canonicalPath = getCanonicalPath(pathname, domainLocale, rewriteRules);
|
|
94
|
+
const internalPath = getInternalPath(canonicalPath, domainLocale);
|
|
94
95
|
return rewriteUrl(request, internalPath + (request.nextUrl.search ?? ""), domainLocale);
|
|
95
96
|
}
|
|
96
97
|
}
|
|
@@ -119,7 +120,8 @@ const getLocalLocale = (request) => {
|
|
|
119
120
|
const handleNoPrefix = (request, localLocale, pathname) => {
|
|
120
121
|
const pathLocale = getPathLocale(pathname);
|
|
121
122
|
if (pathLocale) {
|
|
122
|
-
const
|
|
123
|
+
const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || "/";
|
|
124
|
+
const canonicalPath = getCanonicalPath(pathWithoutLocale, pathLocale, rewriteRules);
|
|
123
125
|
const search = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
|
|
124
126
|
const redirectPath = search ? `${canonicalPath}${search}` : `${canonicalPath}${request.nextUrl.search ?? ""}`;
|
|
125
127
|
return redirectUrl(request, redirectPath, pathLocale);
|