vite-intlayer 8.2.2 → 8.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/intlayerOptimizePlugin.mjs +2 -0
- package/dist/esm/intlayerOptimizePlugin.mjs.map +1 -0
- package/dist/esm/intlayerPlugin.mjs +1 -1
- package/dist/esm/intlayerPlugin.mjs.map +1 -1
- package/dist/esm/intlayerProxyPlugin.mjs +1 -1
- package/dist/esm/intlayerProxyPlugin.mjs.map +1 -1
- package/dist/esm/packages/@intlayer/svelte-compiler/dist/esm/index.mjs +1 -1
- package/dist/esm/packages/@intlayer/svelte-compiler/dist/esm/svelte-intlayer-extract.mjs +2 -2
- package/dist/esm/packages/@intlayer/svelte-compiler/dist/esm/svelte-intlayer-extract.mjs.map +1 -1
- package/dist/esm/packages/@intlayer/vue-compiler/dist/esm/index.mjs +1 -1
- package/dist/esm/packages/@intlayer/vue-compiler/dist/esm/vue-intlayer-extract.mjs +2 -2
- package/dist/esm/packages/@intlayer/vue-compiler/dist/esm/vue-intlayer-extract.mjs.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/intlayerOptimizePlugin.d.ts +8 -0
- package/dist/types/intlayerOptimizePlugin.d.ts.map +1 -0
- package/dist/types/intlayerPlugin.d.ts.map +1 -1
- package/dist/types/intlayerProxyPlugin.d.ts.map +1 -1
- package/package.json +11 -10
- package/dist/esm/intlayerPrunePlugin.mjs +0 -2
- package/dist/esm/intlayerPrunePlugin.mjs.map +0 -1
- package/dist/types/intlayerPrunePlugin.d.ts +0 -8
- package/dist/types/intlayerPrunePlugin.d.ts.map +0 -1
package/dist/esm/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{intlayerCompiler as e}from"./IntlayerCompilerPlugin.mjs";import{
|
|
1
|
+
import{intlayerCompiler as e}from"./IntlayerCompilerPlugin.mjs";import{intlayerOptimize as t}from"./intlayerOptimizePlugin.mjs";import{intLayerPlugin as n,intlayer as r,intlayerPlugin as i}from"./intlayerPlugin.mjs";import{intLayerMiddlewarePlugin as a,intlayerMiddleware as o,intlayerProxy as s}from"./intlayerProxyPlugin.mjs";export{a as intLayerMiddlewarePlugin,n as intLayerPlugin,r as intlayer,e as intlayerCompiler,o as intlayerMiddleware,t as intlayerOptimize,i as intlayerPlugin,s as intlayerProxy};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{intlayerVueAsyncPlugin as e}from"./intlayerVueAsyncPlugin.mjs";import{join as t}from"node:path";import{intlayerOptimizeBabelPlugin as n}from"@intlayer/babel";import{getComponentTransformPattern as r,runOnce as i}from"@intlayer/chokidar/utils";import{getAppLogger as a}from"@intlayer/config/logger";import{DefaultValues as o}from"@intlayer/config/client";import{getDictionaries as s}from"@intlayer/dictionaries-entry";const c=/\b(use|get)Intlayer\b/,l=async l=>{try{let u=await import(`@babel/core`),d=a(l),{optimize:f}=l.build,p=l.build.importMode??l.dictionary?.importMode,{dictionariesDir:m,dynamicDictionariesDir:h,unmergedDictionariesDir:g,fetchDictionariesDir:_,mainDir:v}=l.system,{baseDir:y}=l.content,b=await r(l),x=t(v,`dictionaries.mjs`),S=t(v,`unmerged_dictionaries.mjs`),C=t(v,`dynamic_dictionaries.mjs`),w=[...b,x,S],T=s(l),E={};return Object.values(T).forEach(e=>{E[e.key]=e.importMode??p??o.Dictionary.IMPORT_MODE}),[e(l,w),{name:`vite-intlayer-babel-transform`,enforce:`post`,apply:(e,n)=>{let r=n.command===`build`,a=f===void 0&&r||f===!0;return a&&i(t(y,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>d(`Build optimization enabled`),{cacheTimeoutMs:1e3*10}),a},transform(e,t){let r=t.split(`?`,1)[0];if(!w.includes(r))return null;let i=[x,S].includes(r);if(!(c.test(e)||i))return null;let a=u.transformSync(e,{filename:r,plugins:[[n,{optimize:f,dictionariesDir:m,dictionariesEntryPath:x,unmergedDictionariesEntryPath:S,unmergedDictionariesDir:g,dynamicDictionariesDir:h,dynamicDictionariesEntryPath:C,fetchDictionariesDir:_,importMode:p,filesList:w,replaceDictionaryEntry:!0,dictionaryModeMap:E}]],parserOpts:{sourceType:`module`,allowImportExportEverywhere:!0,plugins:[`typescript`,`jsx`,`decorators-legacy`,`classProperties`,`objectRestSpread`,`asyncGenerators`,`functionBind`,`exportDefaultFrom`,`exportNamespaceFrom`,`dynamicImport`,`nullishCoalescingOperator`,`optionalChaining`]}});if(a?.code)return{code:a.code,map:a.map}}}]}catch(e){return console.warn(`Failed to transform with Babel plugin:`,e),[]}};export{l as intlayerOptimize};
|
|
2
|
+
//# sourceMappingURL=intlayerOptimizePlugin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intlayerOptimizePlugin.mjs","names":[],"sources":["../../src/intlayerOptimizePlugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport {\n getComponentTransformPattern,\n runOnce,\n} from '@intlayer/chokidar/utils';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport type { PluginOption } from 'vite';\nimport { intlayerVueAsyncPlugin } from './intlayerVueAsyncPlugin';\n\nconst INTLAYER_USAGE_REGEX = /\\b(use|get)Intlayer\\b/;\n\nexport const intlayerOptimize = async (\n intlayerConfig: IntlayerConfig\n): Promise<PluginOption[]> => {\n try {\n const babel = await import('@babel/core');\n const logger = getAppLogger(intlayerConfig);\n\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.content;\n\n const filesListPattern = await getComponentTransformPattern(intlayerConfig);\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\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\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ??\n importMode ??\n DefaultValues.Dictionary.IMPORT_MODE;\n });\n\n return [\n intlayerVueAsyncPlugin(intlayerConfig, filesList),\n {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\n apply: (_config, env) => {\n // Only apply babel plugin if optimize is enabled\n\n const isBuild = env.command === 'build';\n const isEnabled =\n (optimize === undefined && isBuild) || optimize === true;\n\n if (isEnabled) {\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prune-plugin-enabled.lock'\n ),\n () => logger('Build optimization enabled'),\n {\n cacheTimeoutMs: 1000 * 10, // 10 seconds\n }\n );\n }\n\n return isEnabled;\n },\n transform(code, id) {\n /**\n * Transform file as\n * .../HelloWorld.vue?vue&type=script&setup=true&lang.ts\n * Into\n * .../HelloWorld.vue\n *\n * Prevention for virtual file\n */\n const filename = id.split('?', 1)[0];\n\n if (!filesList.includes(filename)) return null;\n\n const isDictionaryEntry = [\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ].includes(filename);\n\n const isUsingIntlayer = INTLAYER_USAGE_REGEX.test(code);\n\n const shouldTransform = isUsingIntlayer || isDictionaryEntry;\n\n if (!shouldTransform) return null;\n\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n },\n },\n ];\n } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return [];\n }\n};\n"],"mappings":"waAcA,MAAM,EAAuB,wBAEhB,EAAmB,KAC9B,IAC4B,CAC5B,GAAI,CACF,IAAM,EAAQ,MAAM,OAAO,eACrB,EAAS,EAAa,EAAe,CAErC,CAAE,YAAa,EAAe,MAC9B,EACJ,EAAe,MAAM,YAAc,EAAe,YAAY,WAE1D,CACJ,kBACA,yBACA,0BACA,uBACA,WACE,EAAe,OACb,CAAE,WAAY,EAAe,QAE7B,EAAmB,MAAM,EAA6B,EAAe,CAErE,EAAwB,EAAK,EAAS,mBAAmB,CACzD,EAAgC,EACpC,EACA,4BACD,CACK,EAA+B,EACnC,EACA,2BACD,CAEK,EAAY,CAChB,GAAG,EACH,EACA,EACD,CAEK,EAAe,EAAgB,EAAe,CAE9C,EACJ,EAAE,CASJ,OAPC,OAAO,OAAO,EAAa,CAAkB,QAAS,GAAe,CACpE,EAAkB,EAAW,KAC3B,EAAW,YACX,GACA,EAAc,WAAW,aAC3B,CAEK,CACL,EAAuB,EAAgB,EAAU,CACjD,CACE,KAAM,gCACN,QAAS,OACT,OAAQ,EAAS,IAAQ,CAGvB,IAAM,EAAU,EAAI,UAAY,QAC1B,EACH,IAAa,IAAA,IAAa,GAAY,IAAa,GAiBtD,OAfI,GACF,EACE,EACE,EACA,YACA,QACA,qCACD,KACK,EAAO,6BAA6B,CAC1C,CACE,eAAgB,IAAO,GACxB,CACF,CAGI,GAET,UAAU,EAAM,EAAI,CASlB,IAAM,EAAW,EAAG,MAAM,IAAK,EAAE,CAAC,GAElC,GAAI,CAAC,EAAU,SAAS,EAAS,CAAE,OAAO,KAE1C,IAAM,EAAoB,CACxB,EACA,EACD,CAAC,SAAS,EAAS,CAMpB,GAAI,EAJoB,EAAqB,KAAK,EAAK,EAEZ,GAErB,OAAO,KAE7B,IAAM,EAAS,EAAM,cAAc,EAAM,CACvC,WACA,QAAS,CACP,CACE,EACA,CACE,WACA,kBACA,wBACA,gCACA,0BACA,yBACA,+BACA,uBACA,aACA,YACA,uBAAwB,GACxB,oBACD,CACF,CACF,CACD,WAAY,CACV,WAAY,SACZ,4BAA6B,GAC7B,QAAS,CACP,aACA,MACA,oBACA,kBACA,mBACA,kBACA,eACA,oBACA,sBACA,gBACA,4BACA,mBACD,CACF,CACF,CAAC,CAEF,GAAI,GAAQ,KACV,MAAO,CACL,KAAM,EAAO,KACb,IAAK,EAAO,IACb,EAGN,CACF,OACM,EAAO,CAGd,OAFA,QAAQ,KAAK,yCAA0C,EAAM,CAEtD,EAAE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{intlayerOptimize as e}from"./intlayerOptimizePlugin.mjs";import{resolve as t}from"node:path";import{prepareIntlayer as n}from"@intlayer/chokidar/build";import{getConfiguration as r}from"@intlayer/config/node";import{logConfigDetails as i}from"@intlayer/chokidar/cli";import{watch as a}from"@intlayer/chokidar/watcher";import{getAlias as o}from"@intlayer/config/utils";const s=s=>{let c=r(s);i(s);let l=o({configuration:c,formatter:e=>t(e)}),u=Object.keys(l),d=[{name:`vite-intlayer-plugin`,config:async(e,t)=>{let{mode:r}=c.build,i=t.command===`serve`&&t.mode===`development`,a=t.command===`build`;if((i||a||r===`auto`)&&await n(c,{clean:a,cacheTimeoutMs:a?1e3*30:1e3*60*60}),e.resolve={...e.resolve,alias:{...e.resolve?.alias,...l}},e.optimizeDeps={...e.optimizeDeps,exclude:[...e.optimizeDeps?.exclude??[],...u]},e.ssr?.noExternal!==!0){let t=Array.isArray(e.ssr?.noExternal)?e.ssr.noExternal:e.ssr?.noExternal?[e.ssr.noExternal]:[];e.ssr={...e.ssr,noExternal:[...t,/(^@intlayer\/|intlayer$)/]}}return e},configureServer:async e=>{e.config.mode===`development`&&a({configuration:c})}}];return d.push(e(c)),d},c=s,l=s;export{l as intLayerPlugin,c as intlayer,s as intlayerPlugin};
|
|
2
2
|
//# sourceMappingURL=intlayerPlugin.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPlugin.mjs","names":[],"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { watch } from '@intlayer/chokidar/watcher';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getAlias } from '@intlayer/config/utils';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport type { PluginOption } from 'vite';\nimport {
|
|
1
|
+
{"version":3,"file":"intlayerPlugin.mjs","names":[],"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { watch } from '@intlayer/chokidar/watcher';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getAlias } from '@intlayer/config/utils';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport type { PluginOption } from 'vite';\nimport { intlayerOptimize } from './intlayerOptimizePlugin';\n\n/**\n * Vite plugin that integrates Intlayer into the Vite build process.\n *\n * It handles:\n * 1. Preparing Intlayer resources (dictionaries) before build.\n * 2. Configuring Vite aliases for dictionary access.\n * 3. Setting up dev-server watchers for content changes.\n * 4. Applying build optimizations (tree-shaking dictionaries).\n *\n * @param configOptions - Optional configuration to override default Intlayer settings.\n * @returns A Vite plugin option.\n *\n * @example\n * ```ts\n * import { intlayer } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayer()],\n * });\n * ```\n */\nexport const intlayerPlugin = (\n configOptions?: GetConfigurationOptions\n): PluginOption => {\n const intlayerConfig = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const alias = getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n });\n\n const aliasPackages = Object.keys(alias);\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: async (config, env) => {\n const { mode } = intlayerConfig.build;\n\n const isDevCommand =\n env.command === 'serve' && env.mode === 'development';\n const isBuildCommand = env.command === '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 (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 });\n }\n\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...alias,\n },\n };\n\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [...(config.optimizeDeps?.exclude ?? []), ...aliasPackages],\n };\n\n // Update Vite's SSR Externalization\n // We must ensure that intlayer packages are processed by Vite (bundled)\n // so that the aliases defined above are actually applied\n if (config.ssr?.noExternal !== true) {\n const currentNoExternal = Array.isArray(config.ssr?.noExternal)\n ? config.ssr.noExternal\n : config.ssr?.noExternal\n ? [config.ssr.noExternal]\n : [];\n\n config.ssr = {\n ...config.ssr,\n noExternal: [\n ...(currentNoExternal as (string | RegExp)[]),\n // Regex to bundle all intlayer related packages\n /(^@intlayer\\/|intlayer$)/,\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (server) => {\n if (server.config.mode === 'development') {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n plugins.push(intlayerOptimize(intlayerConfig));\n\n return plugins;\n};\n\n/**\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intlayer = intlayerPlugin;\n/**\n * @deprecated Rename to intlayer instead\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intLayerPlugin = intlayerPlugin;\n"],"mappings":"uXAkCA,MAAa,EACX,GACiB,CACjB,IAAM,EAAiB,EAAiB,EAAc,CACtD,EAAiB,EAAc,CAE/B,IAAM,EAAQ,EAAS,CACrB,cAAe,EACf,UAAY,GAAkB,EAAQ,EAAM,CAC7C,CAAC,CAEI,EAAgB,OAAO,KAAK,EAAM,CAElC,EAA0B,CAC9B,CACE,KAAM,uBAEN,OAAQ,MAAO,EAAQ,IAAQ,CAC7B,GAAM,CAAE,QAAS,EAAe,MAE1B,EACJ,EAAI,UAAY,SAAW,EAAI,OAAS,cACpC,EAAiB,EAAI,UAAY,QAgCvC,IA3BI,GAAgB,GAAkB,IAAS,SAE7C,MAAM,EAAgB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GACjB,CAAC,CAIJ,EAAO,QAAU,CACf,GAAG,EAAO,QACV,MAAO,CACL,GAAG,EAAO,SAAS,MACnB,GAAG,EACJ,CACF,CAED,EAAO,aAAe,CACpB,GAAG,EAAO,aACV,QAAS,CAAC,GAAI,EAAO,cAAc,SAAW,EAAE,CAAG,GAAG,EAAc,CACrE,CAKG,EAAO,KAAK,aAAe,GAAM,CACnC,IAAM,EAAoB,MAAM,QAAQ,EAAO,KAAK,WAAW,CAC3D,EAAO,IAAI,WACX,EAAO,KAAK,WACV,CAAC,EAAO,IAAI,WAAW,CACvB,EAAE,CAER,EAAO,IAAM,CACX,GAAG,EAAO,IACV,WAAY,CACV,GAAI,EAEJ,2BACD,CACF,CAGH,OAAO,GAGT,gBAAiB,KAAO,IAAW,CAC7B,EAAO,OAAO,OAAS,eAEzB,EAAM,CAAE,cAAe,EAAgB,CAAC,EAG7C,CACF,CAKD,OAFA,EAAQ,KAAK,EAAiB,EAAe,CAAC,CAEvC,GAaI,EAAW,EAaX,EAAiB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getConfiguration as e}from"@intlayer/config/node";import{DefaultValues as t}from"@intlayer/config/client";import{parse as n}from"node:url";import{getCanonicalPath as r,getLocalizedPath as i,getRewriteRules as a,localeDetector as o}from"@intlayer/core/localization";import{getCookie as s,getLocaleFromStorage as c,setLocaleInStorage as l}from"@intlayer/core/utils";const u=(u,d)=>{let{internationalization:f,routing:p}=e(u),{locales:m,defaultLocale:h}=f,{basePath:g=``,mode:_=t.Routing.ROUTING_MODE,rewrite:v}=p,y=new Map,b=_===`no-prefix`||_===`search-params`,x=_===`prefix-all`,S=a(v,`url`),C=e=>c({getCookie:t=>s(t,e.headers.cookie)}),w=(e,t)=>{if(_!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},T=e=>{let t=e.split(`/`).filter(Boolean)[0];if(t&&m.includes(t))return t},E=(e,t,n,r)=>{if(r){let i=(y.get(r)||0)+1;if(y.set(r,i),i>10)return console.error(`[REDIRECT LOOP DETECTED!]`,{originalUrl:r,redirectCount:i,lastRedirectTo:t,reason:n}),e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Redirect loop detected: ${i} redirects from ${r}`)}return e.writeHead(301,{Location:t}),e.end()},D=(e,t,n,r)=>{e.url!==n&&(e.url=n),r&&l(r,{setHeader:(n,r)=>{t.setHeader(n,r),e.headers[n]=r}})},O=(e,t,n)=>{let r=t.startsWith(`/${e}`)?t.slice(`/${e}`.length):t,i=g.startsWith(`/`)?g:`/${g}`,a=i.endsWith(`/`)?i.slice(0,-1):i;if(_===`no-prefix`||_===`search-params`)return n?`${r||`/`}${n}`:r||`/`;let o=`${a}${t.startsWith(`/${e}`)?t:`/${e}${t===`/`?``:t}`}`;return!x&&e===h&&(o=`${a}${r||`/`}`),n&&(o+=n),o},k=({req:e,res:t,next:n,originalPath:i,searchParams:a,storageLocale:s,originalUrl:c})=>{let l=T(i),u=s??h;if(s||(u=o(e.headers,m,h)),l){let e=r(i.slice(`/${l}`.length)||`/`,l,S),n=w(a,l);return E(t,n?`${e}${n}`:`${e}${a??``}`,void 0,c)}let d=r(i,u,S);if(_===`search-params`){if(new URLSearchParams(a??``).get(`locale`)===u)return D(e,t,`${`/${u}${d===`/`?``:d}`}${a??``}`,u),n();let r=w(a,u);return E(t,r?`${i}${r}`:`${i}${a??``}`,void 0,c)}let f=`/${u}${d===`/`?``:d}`,p=w(a,u);return D(e,t,p?`${f}${p}`:`${f}${a??``}`,u),n()},A=({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,storageLocale:o,originalUrl:s})=>{if(!a){j({req:e,res:t,next:n,originalPath:r,searchParams:i,storageLocale:o,originalUrl:s});return}M({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,originalUrl:s})},j=({req:e,res:t,next:n,originalPath:a,searchParams:s,storageLocale:c,originalUrl:l})=>{let u=c??o(e.headers,m,h);m.includes(u)||(u=h);let d=r(a,u,S),f=i(d,u,S),p=typeof f==`string`?f:f.path,g=w(s,u),_=O(u,p,g);return x||u!==h?E(t,_,void 0,l):(D(e,t,`/${u}${d===`/`?``:d}`,u),n())},M=({req:e,res:t,next:n,originalPath:i,searchParams:a,pathLocale:o,originalUrl:s})=>{let c=i.slice(`/${o}`.length),l=r(c,o,S);if(l!==c){let e=`/${o}${l===`/`?``:l}`;return E(t,a?`${e}${a}`:e,void 0,s)}N({req:e,res:t,next:n,searchParams:a,pathLocale:o,canonicalPath:l,originalUrl:s})},N=({req:e,res:t,next:n,searchParams:r,pathLocale:a,canonicalPath:o,originalUrl:s})=>{if(!x&&a===h){let e=i(o,a,S),n=typeof e==`string`?e:e.path,c=g.startsWith(`/`)?g:`/${g}`,l=c.endsWith(`/`)?c.slice(0,-1):c,u=n;return u.startsWith(`/`)&&(u=u.slice(1)),E(t,`${l}/${u}`.replace(/\/+/g,`/`)+(r??``),void 0,s)}let c=`/${a}${o===`/`?``:o}`;return D(e,t,r?`${c}${r}`:c,a),n()};return{name:`vite-intlayer-middleware-plugin`,configureServer:e=>{e.middlewares.use((e,t,r)=>{if((d?.ignore?.(e)??!1)||e.url?.startsWith(`/node_modules`)||e.url?.startsWith(`/@`)||e.url?.startsWith(`/_`)||e.url?.split(`?`)[0].match(/\.[a-z]+$/i))return r();let i=n(e.url??`/`,!0),a=i.pathname??`/`,o=i.search??``,s=T(a),c=C(e),l=s&&m.includes(s)?s:c,u=e.url;if(b){k({req:e,res:t,next:r,originalPath:a,searchParams:o,storageLocale:l,originalUrl:u});return}A({req:e,res:t,next:r,originalPath:a,searchParams:o,pathLocale:s,storageLocale:l,originalUrl:u})}),y.size>100&&y.clear()}}},d=u,f=u;export{f as intLayerMiddlewarePlugin,d as intlayerMiddleware,u as intlayerProxy};
|
|
1
|
+
import{getConfiguration as e}from"@intlayer/config/node";import{DefaultValues as t}from"@intlayer/config/client";import{parse as n}from"node:url";import{getCanonicalPath as r,getLocalizedPath as i,getRewriteRules as a,localeDetector as o}from"@intlayer/core/localization";import{getCookie as s,getLocaleFromStorage as c,setLocaleInStorage as l}from"@intlayer/core/utils";const u=(u,d)=>{let{internationalization:f,routing:p}=e(u),{locales:m,defaultLocale:h}=f,{basePath:g=``,mode:_=t.Routing.ROUTING_MODE,rewrite:v}=p,y=new Map,b=_===`no-prefix`||_===`search-params`,x=_===`prefix-all`,S=a(v,`url`),C=e=>c({getCookie:t=>s(t,e.headers.cookie)}),w=(e,t)=>{if(_!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},T=e=>{let t=e.split(`/`).filter(Boolean)[0];if(t&&m.includes(t))return t},E=(e,t,n,r)=>{if(r){let i=(y.get(r)||0)+1;if(y.set(r,i),i>10)return console.error(`[REDIRECT LOOP DETECTED!]`,{originalUrl:r,redirectCount:i,lastRedirectTo:t,reason:n}),e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Redirect loop detected: ${i} redirects from ${r}`)}return e.writeHead(301,{Location:t}),e.end()},D=(e,t,n,r)=>{e.url!==n&&(e.url=n),r&&l(r,{setHeader:(n,r)=>{t.setHeader(n,r),e.headers[n]=r}})},O=(e,t,n)=>{let r=t.startsWith(`/${e}`)?t.slice(`/${e}`.length):t,i=g.startsWith(`/`)?g:`/${g}`,a=i.endsWith(`/`)?i.slice(0,-1):i;if(_===`no-prefix`||_===`search-params`)return n?`${r||`/`}${n}`:r||`/`;let o=`${a}${t.startsWith(`/${e}`)?t:`/${e}${t===`/`?``:t}`}`;return!x&&e===h&&(o=`${a}${r||`/`}`),n&&(o+=n),o},k=({req:e,res:t,next:n,originalPath:i,searchParams:a,storageLocale:s,originalUrl:c})=>{let l=T(i),u=s??h;if(s||(u=o(e.headers,m,h)),l){let e=r(i.slice(`/${l}`.length)||`/`,l,S),n=w(a,l);return E(t,n?`${e}${n}`:`${e}${a??``}`,void 0,c)}let d=r(i,u,S);if(_===`search-params`){if(new URLSearchParams(a??``).get(`locale`)===u)return D(e,t,`${`/${u}${d===`/`?``:d}`}${a??``}`,u),n();let r=w(a,u);return E(t,r?`${i}${r}`:`${i}${a??``}`,void 0,c)}let f=`/${u}${d===`/`?``:d}`,p=w(a,u);return D(e,t,p?`${f}${p}`:`${f}${a??``}`,u),n()},A=({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,storageLocale:o,originalUrl:s})=>{if(!a){j({req:e,res:t,next:n,originalPath:r,searchParams:i,storageLocale:o,originalUrl:s});return}M({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,originalUrl:s})},j=({req:e,res:t,next:n,originalPath:a,searchParams:s,storageLocale:c,originalUrl:l})=>{let u=c??o(e.headers,m,h);m.includes(u)||(u=h);let d=r(a,u,S),f=i(d,u,S),p=typeof f==`string`?f:f.path,g=w(s,u),_=O(u,p,g);return x||u!==h?E(t,_,void 0,l):(D(e,t,`/${u}${d===`/`?``:d}${s}`,u),n())},M=({req:e,res:t,next:n,originalPath:i,searchParams:a,pathLocale:o,originalUrl:s})=>{let c=i.slice(`/${o}`.length),l=r(c,o,S);if(l!==c){let e=`/${o}${l===`/`?``:l}`;return E(t,a?`${e}${a}`:e,void 0,s)}N({req:e,res:t,next:n,searchParams:a,pathLocale:o,canonicalPath:l,originalUrl:s})},N=({req:e,res:t,next:n,searchParams:r,pathLocale:a,canonicalPath:o,originalUrl:s})=>{if(!x&&a===h){let e=i(o,a,S),n=typeof e==`string`?e:e.path,c=g.startsWith(`/`)?g:`/${g}`,l=c.endsWith(`/`)?c.slice(0,-1):c,u=n;return u.startsWith(`/`)&&(u=u.slice(1)),E(t,`${l}/${u}`.replace(/\/+/g,`/`)+(r??``),void 0,s)}let c=`/${a}${o===`/`?``:o}`;return D(e,t,r?`${c}${r}`:c,a),n()};return{name:`vite-intlayer-middleware-plugin`,configureServer:e=>{e.middlewares.use((e,t,r)=>{if((d?.ignore?.(e)??!1)||e.url?.startsWith(`/node_modules`)||e.url?.startsWith(`/@`)||e.url?.startsWith(`/_`)||e.url?.split(`?`)[0].match(/\.[a-z]+$/i))return r();let i=n(e.url??`/`,!0),a=i.pathname??`/`,o=i.search??``,s=T(a),c=C(e),l=s&&m.includes(s)?s:c,u=e.url;if(b){k({req:e,res:t,next:r,originalPath:a,searchParams:o,storageLocale:l,originalUrl:u});return}A({req:e,res:t,next:r,originalPath:a,searchParams:o,pathLocale:s,storageLocale:l,originalUrl:u})}),y.size>100&&y.clear()}}},d=u,f=u;export{f as intLayerMiddlewarePlugin,d as intlayerMiddleware,u as intlayerProxy};
|
|
2
2
|
//# sourceMappingURL=intlayerProxyPlugin.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n localeDetector,\n} from '@intlayer/core/localization';\nimport {\n getCookie,\n getLocaleFromStorage,\n setLocaleInStorage,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\ntype IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n};\n\n/**\n * Vite plugin that provides a development middleware for locale-based routing.\n *\n * This plugin mimics the behavior of the Intlayer middleware in Next.js,\n * handling locale detection, redirects, and rewrites during development.\n *\n * @param configOptions - Optional configuration for Intlayer.\n * @param options - Plugin-specific options, like ignoring certain paths.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n */\nexport const intlayerProxy = (\n configOptions?: GetConfigurationOptions,\n options?: IntlayerProxyPluginOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const {\n basePath = '',\n mode = DefaultValues.Routing.ROUTING_MODE,\n rewrite,\n } = routing;\n\n // Track redirect counts per request to detect loops\n const redirectCounts = new Map<string, number>();\n const MAX_REDIRECTS = 10;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => getCookie(name, req.headers.cookie),\n });\n return locale;\n };\n\n /**\n * Appends locale to search params when routing mode is 'search-params'.\n */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n reason?: string,\n originalUrl?: string\n ) => {\n // Track redirect count to detect loops\n if (originalUrl) {\n const count = (redirectCounts.get(originalUrl) || 0) + 1;\n redirectCounts.set(originalUrl, count);\n\n if (count > MAX_REDIRECTS) {\n console.error('[REDIRECT LOOP DETECTED!]', {\n originalUrl,\n redirectCount: count,\n lastRedirectTo: newUrl,\n reason,\n });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${count} redirects from ${originalUrl}`\n );\n }\n }\n\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n if (req.url !== newUrl) {\n req.url = newUrl;\n }\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n req.headers[name] = value;\n },\n });\n }\n };\n\n /**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath.slice(`/${locale}`.length)\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix' || mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix || '/'}${search}`\n : pathWithoutPrefix || '/';\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath === '/' ? '' : currentPath}`;\n\n let newPath = `${normalizedBasePath}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix || '/'}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n };\n\n /* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n /**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\n const handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n const pathLocale = getPathLocale(originalPath);\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${searchParams ?? ''}`;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n };\n\n /**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\n const handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n });\n };\n\n /**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\n const handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, targetLocalizedPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath, undefined, originalUrl);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place using canonical path for framework matching\n rewriteUrl(\n req,\n res,\n `/${locale}${canonicalPath === '/' ? '' : canonicalPath}`,\n locale\n );\n return next();\n };\n\n /**\n * Handles requests where the locale prefix is present in the pathname.\n */\n const handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n originalUrl?: string;\n }) => {\n const rawPath = originalPath.slice(`/${pathLocale}`.length);\n\n // Identify the Canonical Path (Internal path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // Redirect Pretty URL to Canonical URL (Vite Specific Requirement)\n // If request is /fr/a-props (Pretty) -> Redirect to /fr/about (Canonical)\n // This allows the SPA router to handle the route naturally.\n if (canonicalPath !== rawPath) {\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const redirectPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n });\n };\n\n /**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\n const handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n searchParams: string;\n pathLocale: Locale;\n canonicalPath: string;\n originalUrl?: string;\n }) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const cleanBasePath = basePath.startsWith('/')\n ? basePath\n : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${normalizedBasePath}/${finalPath}`.replace(\n /\\/+/g,\n '/'\n );\n\n return redirectUrl(\n res,\n fullPath + (searchParams ?? ''),\n undefined,\n originalUrl\n );\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite to canonical internally\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const newPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n };\n\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // Bypass assets and special Vite endpoints\n if (\n // Custom ignore function\n (options?.ignore?.(req) ?? false) ||\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/_') ||\n /**\n * ./myFile.js\n */\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // Check if there's a locale prefix in the path FIRST\n const pathLocale = getPathLocale(originalPath);\n\n // Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // CRITICAL FIX: If there's a valid pathLocale, it takes precedence over storage\n // This prevents race conditions when cookies are stale during locale switches\n const effectiveStorageLocale =\n pathLocale && supportedLocales.includes(pathLocale)\n ? pathLocale\n : storageLocale;\n\n // Store original URL for redirect tracking\n const originalUrl = req.url;\n\n // If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n return;\n }\n\n // Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n });\n\n // Clean up redirect counts periodically (every 100 requests)\n if (redirectCounts.size > 100) {\n redirectCounts.clear();\n }\n },\n };\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = intlayerProxy;\n"],"mappings":"mXA0DA,MAAa,GACX,EACA,IACW,CAGX,GAAM,CAAE,uBAAsB,WAFP,EAAiB,EAAc,CAGhD,CAAE,QAAS,EAAkB,iBAAkB,EAE/C,CACJ,WAAW,GACX,OAAO,EAAc,QAAQ,aAC7B,WACE,EAGE,EAAiB,IAAI,IAIrB,EAAW,IAAS,aAAe,IAAS,gBAC5C,EAAgB,IAAS,aAEzB,EAAe,EAAgB,EAAS,MAAM,CAU9C,EAAoB,GACT,EAAqB,CAClC,UAAY,GAAiB,EAAU,EAAM,EAAI,QAAQ,OAAO,CACjE,CAAC,CAOE,GACJ,EACA,IACuB,CACvB,GAAI,IAAS,gBAAiB,OAAO,EAErC,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAIhD,OAFA,EAAO,IAAI,SAAU,E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IH,IAAM,EAAc,IAAI,IACtB,IAAkB,IAAM,GAAK,IAO/B,OADA,EAAW,EAAK,EAJA,EACZ,GAAG,IAAc,IACjB,EAE0B,EAAW,CAClC,GAAM,EAGf,MAAO,CACL,KAAM,kCACN,gBAAkB,GAAW,CAC3B,EAAO,YAAY,KAAK,EAAK,EAAK,IAAS,CAEzC,IAEG,GAAS,SAAS,EAAI,EAAI,KAC3B,EAAI,KAAK,WAAW,gBAAgB,EAOpC,EAAI,KAAK,WAAW,KAAK,EAMzB,EAAI,KAAK,WAAW,KAAK,EAIzB,EAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,OAAO,GAAM,CAIf,IAAM,EAAY,EAAM,EAAI,KAAO,IAAK,GAAK,CACvC,EAAe,EAAU,UAAY,IACrC,EAAe,EAAU,QAAU,GAGnC,EAAa,EAAc,EAAa,CAGxC,EAAgB,EAAiB,EAAI,CAIrC,EACJ,GAAc,EAAiB,SAAS,EAAW,CAC/C,EACA,EAGA,EAAc,EAAI,IAGxB,GAAI,EAAU,CACZ,EAAe,CACb,MACA,MACA,OACA,eACA,eACA,cAAe,EACf,cACD,CAAC,CACF,OAIF,EAAa,CACX,MACA,MACA,OACA,eACA,eACA,aACA,cAAe,EACf,cACD,CAAC,EACF,CAGE,EAAe,KAAO,KACxB,EAAe,OAAO,EAG3B,EAeU,EAAqB,EAcrB,EAA2B"}
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n localeDetector,\n} from '@intlayer/core/localization';\nimport {\n getCookie,\n getLocaleFromStorage,\n setLocaleInStorage,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\ntype IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n};\n\n/**\n * Vite plugin that provides a development middleware for locale-based routing.\n *\n * This plugin mimics the behavior of the Intlayer middleware in Next.js,\n * handling locale detection, redirects, and rewrites during development.\n *\n * @param configOptions - Optional configuration for Intlayer.\n * @param options - Plugin-specific options, like ignoring certain paths.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n */\nexport const intlayerProxy = (\n configOptions?: GetConfigurationOptions,\n options?: IntlayerProxyPluginOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const {\n basePath = '',\n mode = DefaultValues.Routing.ROUTING_MODE,\n rewrite,\n } = routing;\n\n // Track redirect counts per request to detect loops\n const redirectCounts = new Map<string, number>();\n const MAX_REDIRECTS = 10;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => getCookie(name, req.headers.cookie),\n });\n return locale;\n };\n\n /**\n * Appends locale to search params when routing mode is 'search-params'.\n */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n reason?: string,\n originalUrl?: string\n ) => {\n // Track redirect count to detect loops\n if (originalUrl) {\n const count = (redirectCounts.get(originalUrl) || 0) + 1;\n redirectCounts.set(originalUrl, count);\n\n if (count > MAX_REDIRECTS) {\n console.error('[REDIRECT LOOP DETECTED!]', {\n originalUrl,\n redirectCount: count,\n lastRedirectTo: newUrl,\n reason,\n });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${count} redirects from ${originalUrl}`\n );\n }\n }\n\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n if (req.url !== newUrl) {\n req.url = newUrl;\n }\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n req.headers[name] = value;\n },\n });\n }\n };\n\n /**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath.slice(`/${locale}`.length)\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix' || mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix || '/'}${search}`\n : pathWithoutPrefix || '/';\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath === '/' ? '' : currentPath}`;\n\n let newPath = `${normalizedBasePath}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix || '/'}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n };\n\n /* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n /**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\n const handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n const pathLocale = getPathLocale(originalPath);\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${searchParams ?? ''}`;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n };\n\n /**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\n const handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n });\n };\n\n /**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\n const handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, targetLocalizedPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath, undefined, originalUrl);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place using canonical path for framework matching.\n // searchParams MUST be preserved here — dropping them causes the framework (e.g. TanStack Start) to\n // see a URL with no search params, trigger a validateSearch normalisation redirect to the prefixed URL\n // (e.g. /en?page=1&...), which the middleware then strips back to /?..., creating an infinite loop.\n rewriteUrl(\n req,\n res,\n `/${locale}${canonicalPath === '/' ? '' : canonicalPath}${searchParams}`,\n locale\n );\n return next();\n };\n\n /**\n * Handles requests where the locale prefix is present in the pathname.\n */\n const handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n originalUrl?: string;\n }) => {\n const rawPath = originalPath.slice(`/${pathLocale}`.length);\n\n // Identify the Canonical Path (Internal path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // Redirect Pretty URL to Canonical URL (Vite Specific Requirement)\n // If request is /fr/a-props (Pretty) -> Redirect to /fr/about (Canonical)\n // This allows the SPA router to handle the route naturally.\n if (canonicalPath !== rawPath) {\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const redirectPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n });\n };\n\n /**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\n const handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n searchParams: string;\n pathLocale: Locale;\n canonicalPath: string;\n originalUrl?: string;\n }) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const cleanBasePath = basePath.startsWith('/')\n ? basePath\n : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${normalizedBasePath}/${finalPath}`.replace(\n /\\/+/g,\n '/'\n );\n\n return redirectUrl(\n res,\n fullPath + (searchParams ?? ''),\n undefined,\n originalUrl\n );\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite to canonical internally\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const newPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n };\n\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // Bypass assets and special Vite endpoints\n if (\n // Custom ignore function\n (options?.ignore?.(req) ?? false) ||\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/_') ||\n /**\n * ./myFile.js\n */\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // Check if there's a locale prefix in the path FIRST\n const pathLocale = getPathLocale(originalPath);\n\n // Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // CRITICAL FIX: If there's a valid pathLocale, it takes precedence over storage\n // This prevents race conditions when cookies are stale during locale switches\n const effectiveStorageLocale =\n pathLocale && supportedLocales.includes(pathLocale)\n ? pathLocale\n : storageLocale;\n\n // Store original URL for redirect tracking\n const originalUrl = req.url;\n\n // If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n return;\n }\n\n // Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n });\n\n // Clean up redirect counts periodically (every 100 requests)\n if (redirectCounts.size > 100) {\n redirectCounts.clear();\n }\n },\n };\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = intlayerProxy;\n"],"mappings":"mXA0DA,MAAa,GACX,EACA,IACW,CAGX,GAAM,CAAE,uBAAsB,WAFP,EAAiB,EAAc,CAGhD,CAAE,QAAS,EAAkB,iBAAkB,EAE/C,CACJ,WAAW,GACX,OAAO,EAAc,QAAQ,aAC7B,WACE,EAGE,EAAiB,IAAI,IAIrB,EAAW,IAAS,aAAe,IAAS,gBAC5C,EAAgB,IAAS,aAEzB,EAAe,EAAgB,EAAS,MAAM,CAU9C,EAAoB,GACT,EAAqB,CAClC,UAAY,GAAiB,EAAU,EAAM,EAAI,QAAQ,OAAO,CACjE,CAAC,CAOE,GACJ,EACA,IACuB,CACvB,GAAI,IAAS,gBAAiB,OAAO,EAErC,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAIhD,OAFA,EAAO,IAAI,SAAU,EAAO,CAErB,IAAI,EAAO,UAAU,IAMxB,EAAiB,GAAyC,CAI9D,IAAM,EADW,EAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CACtB,GAC9B,GAAI,GAAgB,EAAiB,SAAS,EAAuB,CACnE,OAAO,GAQL,GACJ,EACA,EACA,EACA,IACG,CAEH,GAAI,EAAa,CACf,IAAM,GAAS,EAAe,IAAI,EAAY,EAAI,GAAK,EAGvD,GAFA,EAAe,IAAI,EAAa,EAAM,CAElC,EAAQ,GAQV,OAPA,QAAQ,MAAM,4BAA6B,CACzC,cACA,cAAe,EACf,eAAgB,EAChB,SACD,CAAC,CACF,EAAI,UAAU,IAAK,CAAE,eAAgB,aAAc,CAAC,CAC7C,EAAI,IACT,2BAA2B,EAAM,kBAAkB,IACpD,CAKL,OADA,EAAI,UAAU,IAAK,CAAE,SAAU,EAAQ,CAAC,CACjC,EAAI,KAAK,EAOZ,GACJ,EACA,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AI,CAIrC,EACJ,GAAc,EAAiB,SAAS,EAAW,CAC/C,EACA,EAGA,EAAc,EAAI,IAGxB,GAAI,EAAU,CACZ,EAAe,CACb,MACA,MACA,OACA,eACA,eACA,cAAe,EACf,cACD,CAAC,CACF,OAIF,EAAa,CACX,MACA,MACA,OACA,eACA,eACA,aACA,cAAe,EACf,cACD,CAAC,EACF,CAGE,EAAe,KAAO,KACxB,EAAe,OAAO,EAG3B,EAeU,EAAqB,EAcrB,EAA2B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e
|
|
1
|
+
import{c as e}from"./svelte-intlayer-extract.mjs";export{e as intlayerSvelteExtract};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
`)}\n`;if(D){let t=D.index+D[0].indexOf(`>`)+1;v.appendLeft(t,e)}else v.prepend(`<script>\n ${N}\n ${O?`import { get } from 'svelte/store';`:``}\n ${F}\n<\/script>\n\n`)}return p&&p({dictionaryKey:x,filePath:
|
|
1
|
+
import"node:fs/promises";import e from"/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs";import{parse as t,traverse as n,types as r}from"@babel/core";import{parse as i}from"/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/svelte@5.0.0/node_modules/svelte/src/compiler/index.js";const a=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\/g,`/`);return t.some(e=>e.replace(/\\/g,`/`)===n)},o=(o,s,c={})=>{let{defaultLocale:l=`en`,packageName:u=`svelte-intlayer`,filesList:d,shouldExtract:f,onExtract:p,dictionaryKey:m,attributesToExtract:h=[],extractDictionaryKeyFromPath:g,generateKey:_}=c;if(!a(s,d)||!s.endsWith(`.svelte`))return null;let v=new e(o),y={},b=new Set,x=m??g?.(s)??``,S=[],C;try{C=i(o)}catch(e){return console.warn(`Svelte extraction: Failed to parse Svelte AST for ${s}`,e),null}let w=e=>e.type===`Text`||e.type===3,T=e=>e.type===`Attribute`||e.type===6,E=e=>{if(w(e)){let t=e.data??e.content??``;if(f?.(t)&&_){let n=_(t,b);b.add(n),S.push({start:e.start,end:e.end,replacement:`{$content.${n}}`,key:n,value:t.replace(/\s+/g,` `).trim()})}}else if(T(e)&&h.includes(e.name)&&e.value&&e.value.length===1&&w(e.value[0])){let t=e.value[0].data??e.value[0].content??``;if(f?.(t)&&_){let n=_(t,b);b.add(n),S.push({start:e.start,end:e.end,replacement:`${e.name}={$content.${n}}`,key:n,value:t.trim()})}}let t=e.children??e.fragment?.nodes??e.fragment?.children;t&&t.forEach(E),e.attributes&&e.attributes.forEach(E)};C.html&&E(C.html);let D=/<script[^>]*>([\s\S]*?)<\/script>/.exec(o),O=!1,k=D?D[1]:``;if(D){let e=D[0].indexOf(`>`)+1,i=D.index+e;try{let e=t(k,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}});e&&n(e,{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let t=e.parentPath.node.callee;if(r.isMemberExpression(t)&&r.isIdentifier(t.object)&&t.object.name===`console`||r.isIdentifier(t)&&(t.name===`useIntlayer`||t.name===`t`)||t.type===`Import`||r.isIdentifier(t)&&t.name===`require`)return}let t=e.node.value;if(f?.(t)&&_){let n=_(t,b);b.add(n),O=!0,e.node.start!=null&&e.node.end!=null&&S.push({start:i+e.node.start,end:i+e.node.end,replacement:`get(content).${n}`,key:n,value:t.trim()})}}})}catch(e){console.warn(`Svelte extraction: Failed to parse script content for ${s}`,e)}}if(S.length===0)return null;S.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of S)v.overwrite(e,t,n),y[r]=i;let A=/import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(k)||/import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(k),j=/import\s*{[^}]*get[^}]*}\s*from\s*['"]svelte\/store['"]/.test(k),M=/const\s+content\s*=\s*useIntlayer\s*\(/.test(k),N=A?``:`import { useIntlayer } from '${u}';`,P=O&&!j?`import { get } from 'svelte/store';`:``,F=M?``:`const content = useIntlayer('${x}');`,I=[N,P,F].filter(Boolean);if(I.length>0){let e=`\n ${I.join(`
|
|
2
|
+
`)}\n`;if(D){let t=D.index+D[0].indexOf(`>`)+1;v.appendLeft(t,e)}else v.prepend(`<script>\n ${N}\n ${O?`import { get } from 'svelte/store';`:``}\n ${F}\n<\/script>\n\n`)}return p&&p({dictionaryKey:x,filePath:s,content:{...y},locale:l}),{code:v.toString(),map:v.generateMap({source:s,includeContent:!0}),extracted:!0}};export{o as c,a as s};
|
|
3
3
|
//# sourceMappingURL=svelte-intlayer-extract.mjs.map
|
package/dist/esm/packages/@intlayer/svelte-compiler/dist/esm/svelte-intlayer-extract.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svelte-intlayer-extract.mjs","names":["n","r","i","e","t"],"sources":["../../../../../../../../@intlayer/svelte-compiler/dist/esm/svelte-intlayer-extract.mjs"],"sourcesContent":["import{readFile as e,writeFile as t}from\"node:fs/promises\";import{parse as n,traverse as r,types as i}from\"@babel/core\";import a from\"magic-string\";import
|
|
1
|
+
{"version":3,"file":"svelte-intlayer-extract.mjs","names":["o","n","r","i","e","t"],"sources":["../../../../../../../../@intlayer/svelte-compiler/dist/esm/svelte-intlayer-extract.mjs"],"sourcesContent":["import{readFile as e,writeFile as t}from\"node:fs/promises\";import{parse as n,traverse as r,types as i}from\"@babel/core\";import a from\"magic-string\";import{parse as o}from\"svelte/compiler\";const s=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\\\/g,`/`);return t.some(e=>e.replace(/\\\\/g,`/`)===n)},c=(e,t,c={})=>{let{defaultLocale:l=`en`,packageName:u=`svelte-intlayer`,filesList:d,shouldExtract:f,onExtract:p,dictionaryKey:m,attributesToExtract:h=[],extractDictionaryKeyFromPath:g,generateKey:_}=c;if(!s(t,d)||!t.endsWith(`.svelte`))return null;let v=new a(e),y={},b=new Set,x=m??g?.(t)??``,S=[],C;try{C=o(e)}catch(e){return console.warn(`Svelte extraction: Failed to parse Svelte AST for ${t}`,e),null}let w=e=>e.type===`Text`||e.type===3,T=e=>e.type===`Attribute`||e.type===6,E=e=>{if(w(e)){let t=e.data??e.content??``;if(f?.(t)&&_){let n=_(t,b);b.add(n),S.push({start:e.start,end:e.end,replacement:`{$content.${n}}`,key:n,value:t.replace(/\\s+/g,` `).trim()})}}else if(T(e)&&h.includes(e.name)&&e.value&&e.value.length===1&&w(e.value[0])){let t=e.value[0].data??e.value[0].content??``;if(f?.(t)&&_){let n=_(t,b);b.add(n),S.push({start:e.start,end:e.end,replacement:`${e.name}={$content.${n}}`,key:n,value:t.trim()})}}let t=e.children??e.fragment?.nodes??e.fragment?.children;t&&t.forEach(E),e.attributes&&e.attributes.forEach(E)};C.html&&E(C.html);let D=/<script[^>]*>([\\s\\S]*?)<\\/script>/.exec(e),O=!1,k=D?D[1]:``;if(D){let e=D[0].indexOf(`>`)+1,a=D.index+e;try{let e=n(k,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}});e&&r(e,{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let t=e.parentPath.node.callee;if(i.isMemberExpression(t)&&i.isIdentifier(t.object)&&t.object.name===`console`||i.isIdentifier(t)&&(t.name===`useIntlayer`||t.name===`t`)||t.type===`Import`||i.isIdentifier(t)&&t.name===`require`)return}let t=e.node.value;if(f?.(t)&&_){let n=_(t,b);b.add(n),O=!0,e.node.start!=null&&e.node.end!=null&&S.push({start:a+e.node.start,end:a+e.node.end,replacement:`get(content).${n}`,key:n,value:t.trim()})}}})}catch(e){console.warn(`Svelte extraction: Failed to parse script content for ${t}`,e)}}if(S.length===0)return null;S.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of S)v.overwrite(e,t,n),y[r]=i;let A=/import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(k)||/import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(k),j=/import\\s*{[^}]*get[^}]*}\\s*from\\s*['\"]svelte\\/store['\"]/.test(k),M=/const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(k),N=A?``:`import { useIntlayer } from '${u}';`,P=O&&!j?`import { get } from 'svelte/store';`:``,F=M?``:`const content = useIntlayer('${x}');`,I=[N,P,F].filter(Boolean);if(I.length>0){let e=`\\n ${I.join(`\n `)}\\n`;if(D){let t=D.index+D[0].indexOf(`>`)+1;v.appendLeft(t,e)}else v.prepend(`<script>\\n ${N}\\n ${O?`import { get } from 'svelte/store';`:``}\\n ${F}\\n<\\/script>\\n\\n`)}return p&&p({dictionaryKey:x,filePath:t,content:{...y},locale:l}),{code:v.toString(),map:v.generateMap({source:t,includeContent:!0}),extracted:!0}},l=async(n,r,i,a,o=!0)=>{let s=await e(n,`utf-8`),l=null,u=c(s,n,{packageName:i,dictionaryKey:r,shouldExtract:a.shouldExtract,generateKey:a.generateKey,extractDictionaryKeyFromPath:a.extractDictionaryKeyFromPath,attributesToExtract:a.attributesToExtract,onExtract:e=>{l=e.content}});return u?(o&&await t(n,u.code),l):null};export{c as intlayerSvelteExtract,l as processSvelteFile,s as shouldProcessFile};\n//# sourceMappingURL=svelte-intlayer-extract.mjs.map"],"mappings":"kXAA4L,MAAM,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,MAAM,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,EAAE,QAAQ,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Y,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e
|
|
1
|
+
import{c as e}from"./vue-intlayer-extract.mjs";export{e as intlayerVueExtract};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
`)}\n`;b.descriptor.scriptSetup?x.appendLeft(b.descriptor.scriptSetup.loc.start.offset,e):b.descriptor.script?x.appendLeft(b.descriptor.script.loc.start.offset,e):x.prepend(`<script setup>\n${A}\n${j}\n<\/script>\n`)}return p&&p({dictionaryKey:w,filePath:
|
|
1
|
+
import"node:fs/promises";import{parse as e,traverse as t,types as n}from"@babel/core";import r from"/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/@vue+compiler-sfc@3.5.29/node_modules/@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js";const i=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\/g,`/`);return t.some(e=>e.replace(/\\/g,`/`)===n)},a={TEXT:2,ELEMENT:1,ATTRIBUTE:6},o=async(o,s,c={})=>{let{defaultLocale:l=`en`,packageName:u=`vue-intlayer`,filesList:d,shouldExtract:f,onExtract:p,dictionaryKey:m,attributesToExtract:h=[],extractDictionaryKeyFromPath:g,generateKey:_}=c;if(!i(s,d)||!s.endsWith(`.vue`))return null;let v,y;try{v=r.parse}catch{return console.warn(`Vue extraction: @vue/compiler-sfc not found.`),null}try{y=(await import(`/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs`)).default}catch{return console.warn(`Vue extraction: magic-string not found.`),null}let b=v(o),x=new y(o),S={},C=new Set,w=m??g?.(s)??``,T=[];if(b.descriptor.template){let e=t=>{if(t.type===a.TEXT){let e=t.content??``;if(f?.(e)&&_){let n=_(e,C);C.add(n),T.push({start:t.loc.start.offset,end:t.loc.end.offset,replacement:`{{ content.${n} }}`,key:n,value:e.replace(/\s+/g,` `).trim()})}}else t.type===a.ELEMENT&&t.props?.forEach(e=>{if(e.type===a.ATTRIBUTE&&h.includes(e.name)&&e.value){let t=e.value.content;if(f?.(t)&&_){let n=_(t,C);C.add(n),T.push({start:e.loc.start.offset,end:e.loc.end.offset,replacement:`:${e.name}="content.${n}"`,key:n,value:t.trim()})}}});t.children&&t.children.forEach(e)};e(b.descriptor.template.ast)}let E=b.descriptor.scriptSetup??b.descriptor.script;if(E){let r=E.content,i=E.loc.start.offset;try{let a=e(r,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}});a&&t(a,{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let t=e.parentPath.node.callee;if(n.isMemberExpression(t)&&n.isIdentifier(t.object)&&t.object.name===`console`||n.isIdentifier(t)&&(t.name===`useIntlayer`||t.name===`t`)||t.type===`Import`||n.isIdentifier(t)&&t.name===`require`)return}let t=e.node.value;if(f?.(t)&&_){let n=_(t,C);C.add(n),e.node.start!=null&&e.node.end!=null&&T.push({start:i+e.node.start,end:i+e.node.end,replacement:`content.${n}`,key:n,value:t.trim()})}}})}catch(e){console.warn(`Vue extraction: Failed to parse script content for ${s}`,e)}}if(T.length===0)return null;T.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of T)x.overwrite(e,t,n),S[r]=i;let D=E?.content??``,O=/import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(D)||/import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(D),k=/const\s+content\s*=\s*useIntlayer\s*\(/.test(D),A=O?``:`import { useIntlayer } from '${u}';`,j=k?``:`const content = useIntlayer('${w}');`,M=[A,j].filter(Boolean);if(M.length>0){let e=`\n${M.join(`
|
|
2
|
+
`)}\n`;b.descriptor.scriptSetup?x.appendLeft(b.descriptor.scriptSetup.loc.start.offset,e):b.descriptor.script?x.appendLeft(b.descriptor.script.loc.start.offset,e):x.prepend(`<script setup>\n${A}\n${j}\n<\/script>\n`)}return p&&p({dictionaryKey:w,filePath:s,content:{...S},locale:l}),{code:x.toString(),map:x.generateMap({source:s,includeContent:!0}),extracted:!0}};export{o as c,i as o};
|
|
3
3
|
//# sourceMappingURL=vue-intlayer-extract.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vue-intlayer-extract.mjs","names":["n","r","i","e","t"],"sources":["../../../../../../../../@intlayer/vue-compiler/dist/esm/vue-intlayer-extract.mjs"],"sourcesContent":["import{readFile as e,writeFile as t}from\"node:fs/promises\";import{parse as n,traverse as r,types as i}from\"@babel/core\";import a from\"@vue/compiler-sfc\";const o=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\\\/g,`/`);return t.some(e=>e.replace(/\\\\/g,`/`)===n)},s={TEXT:2,ELEMENT:1,ATTRIBUTE:6},c=async(e,t,c={})=>{let{defaultLocale:l=`en`,packageName:u=`vue-intlayer`,filesList:d,shouldExtract:f,onExtract:p,dictionaryKey:m,attributesToExtract:h=[],extractDictionaryKeyFromPath:g,generateKey:_}=c;if(!o(t,d)||!t.endsWith(`.vue`))return null;let v,y;try{v=a.parse}catch{return console.warn(`Vue extraction: @vue/compiler-sfc not found.`),null}try{y=(await import(`magic-string`)).default}catch{return console.warn(`Vue extraction: magic-string not found.`),null}let b=v(e),x=new y(e),S={},C=new Set,w=m??g?.(t)??``,T=[];if(b.descriptor.template){let e=t=>{if(t.type===s.TEXT){let e=t.content??``;if(f?.(e)&&_){let n=_(e,C);C.add(n),T.push({start:t.loc.start.offset,end:t.loc.end.offset,replacement:`{{ content.${n} }}`,key:n,value:e.replace(/\\s+/g,` `).trim()})}}else t.type===s.ELEMENT&&t.props?.forEach(e=>{if(e.type===s.ATTRIBUTE&&h.includes(e.name)&&e.value){let t=e.value.content;if(f?.(t)&&_){let n=_(t,C);C.add(n),T.push({start:e.loc.start.offset,end:e.loc.end.offset,replacement:`:${e.name}=\"content.${n}\"`,key:n,value:t.trim()})}}});t.children&&t.children.forEach(e)};e(b.descriptor.template.ast)}let E=b.descriptor.scriptSetup??b.descriptor.script;if(E){let e=E.content,a=E.loc.start.offset;try{let t=n(e,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}});t&&r(t,{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let t=e.parentPath.node.callee;if(i.isMemberExpression(t)&&i.isIdentifier(t.object)&&t.object.name===`console`||i.isIdentifier(t)&&(t.name===`useIntlayer`||t.name===`t`)||t.type===`Import`||i.isIdentifier(t)&&t.name===`require`)return}let t=e.node.value;if(f?.(t)&&_){let n=_(t,C);C.add(n),e.node.start!=null&&e.node.end!=null&&T.push({start:a+e.node.start,end:a+e.node.end,replacement:`content.${n}`,key:n,value:t.trim()})}}})}catch(e){console.warn(`Vue extraction: Failed to parse script content for ${t}`,e)}}if(T.length===0)return null;T.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of T)x.overwrite(e,t,n),S[r]=i;let D=E?.content??``,O=/import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(D)||/import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(D),k=/const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(D),A=O?``:`import { useIntlayer } from '${u}';`,j=k?``:`const content = useIntlayer('${w}');`,M=[A,j].filter(Boolean);if(M.length>0){let e=`\\n${M.join(`\n`)}\\n`;b.descriptor.scriptSetup?x.appendLeft(b.descriptor.scriptSetup.loc.start.offset,e):b.descriptor.script?x.appendLeft(b.descriptor.script.loc.start.offset,e):x.prepend(`<script setup>\\n${A}\\n${j}\\n<\\/script>\\n`)}return p&&p({dictionaryKey:w,filePath:t,content:{...S},locale:l}),{code:x.toString(),map:x.generateMap({source:t,includeContent:!0}),extracted:!0}},l=async(n,r,i,a,o=!0)=>{let s=await e(n,`utf-8`),l={},u=await c(s,n,{packageName:i,dictionaryKey:r,shouldExtract:a.shouldExtract,generateKey:a.generateKey,extractDictionaryKeyFromPath:a.extractDictionaryKeyFromPath,attributesToExtract:a.attributesToExtract,onExtract:e=>{l=e.content}});return u?(o&&await t(n,u.code),l):null};export{c as intlayerVueExtract,l as processVueFile,o as shouldProcessFile};\n//# sourceMappingURL=vue-intlayer-extract.mjs.map"],"mappings":"
|
|
1
|
+
{"version":3,"file":"vue-intlayer-extract.mjs","names":["n","r","i","e","t"],"sources":["../../../../../../../../@intlayer/vue-compiler/dist/esm/vue-intlayer-extract.mjs"],"sourcesContent":["import{readFile as e,writeFile as t}from\"node:fs/promises\";import{parse as n,traverse as r,types as i}from\"@babel/core\";import a from\"@vue/compiler-sfc\";const o=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\\\/g,`/`);return t.some(e=>e.replace(/\\\\/g,`/`)===n)},s={TEXT:2,ELEMENT:1,ATTRIBUTE:6},c=async(e,t,c={})=>{let{defaultLocale:l=`en`,packageName:u=`vue-intlayer`,filesList:d,shouldExtract:f,onExtract:p,dictionaryKey:m,attributesToExtract:h=[],extractDictionaryKeyFromPath:g,generateKey:_}=c;if(!o(t,d)||!t.endsWith(`.vue`))return null;let v,y;try{v=a.parse}catch{return console.warn(`Vue extraction: @vue/compiler-sfc not found.`),null}try{y=(await import(`magic-string`)).default}catch{return console.warn(`Vue extraction: magic-string not found.`),null}let b=v(e),x=new y(e),S={},C=new Set,w=m??g?.(t)??``,T=[];if(b.descriptor.template){let e=t=>{if(t.type===s.TEXT){let e=t.content??``;if(f?.(e)&&_){let n=_(e,C);C.add(n),T.push({start:t.loc.start.offset,end:t.loc.end.offset,replacement:`{{ content.${n} }}`,key:n,value:e.replace(/\\s+/g,` `).trim()})}}else t.type===s.ELEMENT&&t.props?.forEach(e=>{if(e.type===s.ATTRIBUTE&&h.includes(e.name)&&e.value){let t=e.value.content;if(f?.(t)&&_){let n=_(t,C);C.add(n),T.push({start:e.loc.start.offset,end:e.loc.end.offset,replacement:`:${e.name}=\"content.${n}\"`,key:n,value:t.trim()})}}});t.children&&t.children.forEach(e)};e(b.descriptor.template.ast)}let E=b.descriptor.scriptSetup??b.descriptor.script;if(E){let e=E.content,a=E.loc.start.offset;try{let t=n(e,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}});t&&r(t,{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let t=e.parentPath.node.callee;if(i.isMemberExpression(t)&&i.isIdentifier(t.object)&&t.object.name===`console`||i.isIdentifier(t)&&(t.name===`useIntlayer`||t.name===`t`)||t.type===`Import`||i.isIdentifier(t)&&t.name===`require`)return}let t=e.node.value;if(f?.(t)&&_){let n=_(t,C);C.add(n),e.node.start!=null&&e.node.end!=null&&T.push({start:a+e.node.start,end:a+e.node.end,replacement:`content.${n}`,key:n,value:t.trim()})}}})}catch(e){console.warn(`Vue extraction: Failed to parse script content for ${t}`,e)}}if(T.length===0)return null;T.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of T)x.overwrite(e,t,n),S[r]=i;let D=E?.content??``,O=/import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(D)||/import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(D),k=/const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(D),A=O?``:`import { useIntlayer } from '${u}';`,j=k?``:`const content = useIntlayer('${w}');`,M=[A,j].filter(Boolean);if(M.length>0){let e=`\\n${M.join(`\n`)}\\n`;b.descriptor.scriptSetup?x.appendLeft(b.descriptor.scriptSetup.loc.start.offset,e):b.descriptor.script?x.appendLeft(b.descriptor.script.loc.start.offset,e):x.prepend(`<script setup>\\n${A}\\n${j}\\n<\\/script>\\n`)}return p&&p({dictionaryKey:w,filePath:t,content:{...S},locale:l}),{code:x.toString(),map:x.generateMap({source:t,includeContent:!0}),extracted:!0}},l=async(n,r,i,a,o=!0)=>{let s=await e(n,`utf-8`),l={},u=await c(s,n,{packageName:i,dictionaryKey:r,shouldExtract:a.shouldExtract,generateKey:a.generateKey,extractDictionaryKeyFromPath:a.extractDictionaryKeyFromPath,attributesToExtract:a.attributesToExtract,onExtract:e=>{l=e.content}});return u?(o&&await t(n,u.code),l):null};export{c as intlayerVueExtract,l as processVueFile,o as shouldProcessFile};\n//# sourceMappingURL=vue-intlayer-extract.mjs.map"],"mappings":"yPAAyJ,MAAM,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,MAAM,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,EAAE,QAAQ,MAAM,IAAI,GAAG,EAAE,EAAE,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,YAAY,EAAE,eAAe,UAAU,EAAE,cAAc,EAAE,UAAU,EAAE,cAAc,EAAE,oBAAoB,EAAE,EAAE,CAAC,6BAA6B,EAAE,YAAY,GAAG,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,SAAS,OAAO,CAAC,OAAO,KAAK,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,WAAW,CAAC,OAAO,QAAQ,KAAK,+CAA+C,CAAC,KAAK,GAAG,CAAC,GAAG,MAAM,OAAO,uIAAiB,aAAa,CAAC,OAAO,Q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AE,EAAE,+CAA+C,KAAK,EAAE,CAAC,EAAE,yCAAyC,KAAK,EAAE,CAAC,EAAE,EAAE,GAAG,gCAAgC,EAAE,IAAI,EAAE,EAAE,GAAG,gCAAgC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,OAAO,QAAQ,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK;EACrwF,CAAC,IAAI,EAAE,WAAW,YAAY,EAAE,WAAW,EAAE,WAAW,YAAY,IAAI,MAAM,OAAO,EAAE,CAAC,EAAE,WAAW,OAAO,EAAE,WAAW,EAAE,WAAW,OAAO,IAAI,MAAM,OAAO,EAAE,CAAC,EAAE,QAAQ,mBAAmB,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,GAAG,EAAE,CAAC,cAAc,EAAE,SAAS,EAAE,QAAQ,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,UAAU,CAAC,IAAI,EAAE,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,EAAE"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CompilerMode, IntlayerCompilerOptions, intlayerCompiler } from "./IntlayerCompilerPlugin.js";
|
|
2
|
+
import { intlayerOptimize } from "./intlayerOptimizePlugin.js";
|
|
2
3
|
import { intLayerPlugin, intlayer, intlayerPlugin } from "./intlayerPlugin.js";
|
|
3
4
|
import { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy } from "./intlayerProxyPlugin.js";
|
|
4
|
-
|
|
5
|
-
export { CompilerMode, IntlayerCompilerOptions, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerCompiler, intlayerMiddleware, intlayerPlugin, intlayerProxy, intlayerPrune };
|
|
5
|
+
export { CompilerMode, IntlayerCompilerOptions, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerCompiler, intlayerMiddleware, intlayerOptimize, intlayerPlugin, intlayerProxy };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { IntlayerConfig } from "@intlayer/types";
|
|
2
|
+
import { PluginOption } from "vite";
|
|
3
|
+
|
|
4
|
+
//#region src/intlayerOptimizePlugin.d.ts
|
|
5
|
+
declare const intlayerOptimize: (intlayerConfig: IntlayerConfig) => Promise<PluginOption[]>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { intlayerOptimize };
|
|
8
|
+
//# sourceMappingURL=intlayerOptimizePlugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intlayerOptimizePlugin.d.ts","names":[],"sources":["../../src/intlayerOptimizePlugin.ts"],"mappings":";;;;cAgBa,gBAAA,GACX,cAAA,EAAgB,cAAA,KACf,OAAA,CAAQ,YAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPlugin.d.ts","names":[],"sources":["../../src/intlayerPlugin.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"intlayerPlugin.d.ts","names":[],"sources":["../../src/intlayerPlugin.ts"],"mappings":";;;;;;AAkCA;;;;;;;;;AAmGA;;;;;;;;;AAaA;cAhHa,cAAA,GACX,aAAA,GAAgB,uBAAA,KACf,YAAA;;;;;;;;;;;cAiGU,QAAA,GAAQ,aAAA,GAlGH,uBAAA,KACf,YAAA;;;;;;;;;;;;;cA8GU,cAAA,GAAc,aAAA,GA/GT,uBAAA,KACf,YAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"mappings":";;;;;KAsBK,0BAAA;;AAFuC;;;;;;;;;AAsC5C;;;EAtBE,MAAA,IAAU,GAAA,EAAK,eAAA;AAAA;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"mappings":";;;;;KAsBK,0BAAA;;AAFuC;;;;;;;;;AAsC5C;;;EAtBE,MAAA,IAAU,GAAA,EAAK,eAAA;AAAA;;;;;;;;;;;AAyoBjB;;;;;;;;;cAnnBa,aAAA,GACX,aAAA,GAAgB,uBAAA,EAChB,OAAA,GAAU,0BAAA,KACT,MAAA;;;;;;AA8nBH;;;;;;;cAda,kBAAA,GAAkB,aAAA,GAlnBb,uBAAA,EAAuB,OAAA,GAC7B,0BAAA,KACT,MAAA;;;;;;;;;;;;;cA8nBU,wBAAA,GAAwB,aAAA,GAhoBnB,uBAAA,EAAuB,OAAA,GAC7B,0BAAA,KACT,MAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-intlayer",
|
|
3
|
-
"version": "8.2.
|
|
3
|
+
"version": "8.2.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration",
|
|
6
6
|
"keywords": [
|
|
@@ -77,21 +77,22 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@babel/core": "7.29.0",
|
|
80
|
-
"@intlayer/babel": "8.2.
|
|
81
|
-
"@intlayer/chokidar": "8.2.
|
|
82
|
-
"@intlayer/config": "8.2.
|
|
83
|
-
"@intlayer/core": "8.2.
|
|
84
|
-
"@intlayer/dictionaries-entry": "8.2.
|
|
85
|
-
"@intlayer/types": "8.2.
|
|
86
|
-
"intlayer": "8.2.
|
|
80
|
+
"@intlayer/babel": "8.2.3",
|
|
81
|
+
"@intlayer/chokidar": "8.2.3",
|
|
82
|
+
"@intlayer/config": "8.2.3",
|
|
83
|
+
"@intlayer/core": "8.2.3",
|
|
84
|
+
"@intlayer/dictionaries-entry": "8.2.3",
|
|
85
|
+
"@intlayer/types": "8.2.3",
|
|
86
|
+
"intlayer": "8.2.3"
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"@types/
|
|
89
|
+
"@types/babel__core": "7.20.5",
|
|
90
|
+
"@types/node": "25.3.5",
|
|
90
91
|
"@utils/ts-config": "1.0.4",
|
|
91
92
|
"@utils/ts-config-types": "1.0.4",
|
|
92
93
|
"@utils/tsdown-config": "1.0.4",
|
|
93
94
|
"rimraf": "6.1.3",
|
|
94
|
-
"tsdown": "0.
|
|
95
|
+
"tsdown": "0.21.0",
|
|
95
96
|
"typescript": "5.9.3",
|
|
96
97
|
"vitest": "4.0.18"
|
|
97
98
|
},
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{intlayerVueAsyncPlugin as e}from"./intlayerVueAsyncPlugin.mjs";import{join as t}from"node:path";import{intlayerOptimizeBabelPlugin as n}from"@intlayer/babel";import{getComponentTransformPattern as r,runOnce as i}from"@intlayer/chokidar/utils";import{getAppLogger as a}from"@intlayer/config/logger";import{createRequire as o}from"node:module";import{DefaultValues as s}from"@intlayer/config/client";import{getDictionaries as c}from"@intlayer/dictionaries-entry";const l=/\b(use|get)Intlayer\b/,u=async u=>{try{let d=o(import.meta.url)(`@babel/core`),f=a(u),{optimize:p}=u.build,m=u.build.importMode??u.dictionary?.importMode,{dictionariesDir:h,dynamicDictionariesDir:g,unmergedDictionariesDir:_,fetchDictionariesDir:v,mainDir:y}=u.system,{baseDir:b}=u.content,x=await r(u),S=t(y,`dictionaries.mjs`),C=t(y,`unmerged_dictionaries.mjs`),w=t(y,`dynamic_dictionaries.mjs`),T=[...x,S,C],E=c(u),D={};return Object.values(E).forEach(e=>{D[e.key]=e.importMode??m??s.Dictionary.IMPORT_MODE}),[e(u,T),{name:`vite-intlayer-babel-transform`,enforce:`post`,apply:(e,n)=>{let r=n.command===`build`,a=p===void 0&&r||p===!0;return a&&i(t(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>f(`Build optimization enabled`),{cacheTimeoutMs:1e3*10}),a},transform(e,t){let r=t.split(`?`,1)[0];if(!T.includes(r))return null;let i=[S,C].includes(r);if(!(l.test(e)||i))return null;let a=d.transformSync(e,{filename:r,plugins:[[n,{optimize:p,dictionariesDir:h,dictionariesEntryPath:S,unmergedDictionariesEntryPath:C,unmergedDictionariesDir:_,dynamicDictionariesDir:g,dynamicDictionariesEntryPath:w,fetchDictionariesDir:v,importMode:m,filesList:T,replaceDictionaryEntry:!0,dictionaryModeMap:D}]],parserOpts:{sourceType:`module`,allowImportExportEverywhere:!0,plugins:[`typescript`,`jsx`,`decorators-legacy`,`classProperties`,`objectRestSpread`,`asyncGenerators`,`functionBind`,`exportDefaultFrom`,`exportNamespaceFrom`,`dynamicImport`,`nullishCoalescingOperator`,`optionalChaining`]}});if(a?.code)return{code:a.code,map:a.map}}}]}catch(e){return console.warn(`Failed to transform with Babel plugin:`,e),[]}};export{u as intlayerPrune};
|
|
2
|
-
//# sourceMappingURL=intlayerPrunePlugin.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPrunePlugin.mjs","names":[],"sources":["../../src/intlayerPrunePlugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport {\n getComponentTransformPattern,\n runOnce,\n} from '@intlayer/chokidar/utils';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport type { PluginOption } from 'vite';\nimport { intlayerVueAsyncPlugin } from './intlayerVueAsyncPlugin';\n\nconst INTLAYER_USAGE_REGEX = /\\b(use|get)Intlayer\\b/;\n\nexport const intlayerPrune = async (\n intlayerConfig: IntlayerConfig\n): Promise<PluginOption[]> => {\n try {\n const localeRequire = createRequire(import.meta.url);\n const babel = localeRequire('@babel/core');\n const logger = getAppLogger(intlayerConfig);\n\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.content;\n\n const filesListPattern = await getComponentTransformPattern(intlayerConfig);\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\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\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ??\n importMode ??\n DefaultValues.Dictionary.IMPORT_MODE;\n });\n\n return [\n intlayerVueAsyncPlugin(intlayerConfig, filesList),\n {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\n apply: (_config, env) => {\n // Only apply babel plugin if optimize is enabled\n\n const isBuild = env.command === 'build';\n const isEnabled =\n (optimize === undefined && isBuild) || optimize === true;\n\n if (isEnabled) {\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prune-plugin-enabled.lock'\n ),\n () => logger('Build optimization enabled'),\n {\n cacheTimeoutMs: 1000 * 10, // 10 seconds\n }\n );\n }\n\n return isEnabled;\n },\n transform(code, id) {\n /**\n * Transform file as\n * .../HelloWorld.vue?vue&type=script&setup=true&lang.ts\n * Into\n * .../HelloWorld.vue\n *\n * Prevention for virtual file\n */\n const filename = id.split('?', 1)[0];\n\n if (!filesList.includes(filename)) return null;\n\n const isDictionaryEntry = [\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ].includes(filename);\n\n const isUsingIntlayer = INTLAYER_USAGE_REGEX.test(code);\n\n const shouldTransform = isUsingIntlayer || isDictionaryEntry;\n\n if (!shouldTransform) return null;\n\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n },\n },\n ];\n } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return [];\n }\n};\n"],"mappings":"odAcA,MAAM,EAAuB,wBAEhB,EAAgB,KAC3B,IAC4B,CAC5B,GAAI,CAEF,IAAM,EADgB,EAAc,OAAO,KAAK,IAAI,CACxB,cAAc,CACpC,EAAS,EAAa,EAAe,CAErC,CAAE,YAAa,EAAe,MAC9B,EACJ,EAAe,MAAM,YAAc,EAAe,YAAY,WAE1D,CACJ,kBACA,yBACA,0BACA,uBACA,WACE,EAAe,OACb,CAAE,WAAY,EAAe,QAE7B,EAAmB,MAAM,EAA6B,EAAe,CAErE,EAAwB,EAAK,EAAS,mBAAmB,CACzD,EAAgC,EACpC,EACA,4BACD,CACK,EAA+B,EACnC,EACA,2BACD,CAEK,EAAY,CAChB,GAAG,EACH,EACA,EACD,CAEK,EAAe,EAAgB,EAAe,CAE9C,EACJ,EAAE,CASJ,OAPC,OAAO,OAAO,EAAa,CAAkB,QAAS,GAAe,CACpE,EAAkB,EAAW,KAC3B,EAAW,YACX,GACA,EAAc,WAAW,aAC3B,CAEK,CACL,EAAuB,EAAgB,EAAU,CACjD,CACE,KAAM,gCACN,QAAS,OACT,OAAQ,EAAS,IAAQ,CAGvB,IAAM,EAAU,EAAI,UAAY,QAC1B,EACH,IAAa,IAAA,IAAa,GAAY,IAAa,GAiBtD,OAfI,GACF,EACE,EACE,EACA,YACA,QACA,qCACD,KACK,EAAO,6BAA6B,CAC1C,CACE,eAAgB,IAAO,GACxB,CACF,CAGI,GAET,UAAU,EAAM,EAAI,CASlB,IAAM,EAAW,EAAG,MAAM,IAAK,EAAE,CAAC,GAElC,GAAI,CAAC,EAAU,SAAS,EAAS,CAAE,OAAO,KAE1C,IAAM,EAAoB,CACxB,EACA,EACD,CAAC,SAAS,EAAS,CAMpB,GAAI,EAJoB,EAAqB,KAAK,EAAK,EAEZ,GAErB,OAAO,KAE7B,IAAM,EAAS,EAAM,cAAc,EAAM,CACvC,WACA,QAAS,CACP,CACE,EACA,CACE,WACA,kBACA,wBACA,gCACA,0BACA,yBACA,+BACA,uBACA,aACA,YACA,uBAAwB,GACxB,oBACD,CACF,CACF,CACD,WAAY,CACV,WAAY,SACZ,4BAA6B,GAC7B,QAAS,CACP,aACA,MACA,oBACA,kBACA,mBACA,kBACA,eACA,oBACA,sBACA,gBACA,4BACA,mBACD,CACF,CACF,CAAC,CAEF,GAAI,GAAQ,KACV,MAAO,CACL,KAAM,EAAO,KACb,IAAK,EAAO,IACb,EAGN,CACF,OACM,EAAO,CAGd,OAFA,QAAQ,KAAK,yCAA0C,EAAM,CAEtD,EAAE"}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { IntlayerConfig } from "@intlayer/types";
|
|
2
|
-
import { PluginOption } from "vite";
|
|
3
|
-
|
|
4
|
-
//#region src/intlayerPrunePlugin.d.ts
|
|
5
|
-
declare const intlayerPrune: (intlayerConfig: IntlayerConfig) => Promise<PluginOption[]>;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { intlayerPrune };
|
|
8
|
-
//# sourceMappingURL=intlayerPrunePlugin.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPrunePlugin.d.ts","names":[],"sources":["../../src/intlayerPrunePlugin.ts"],"mappings":";;;;cAgBa,aAAA,GACX,cAAA,EAAgB,cAAA,KACf,OAAA,CAAQ,YAAA"}
|