vite-intlayer 7.0.6 → 7.0.8-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/intlayerPlugin.cjs +0 -3
- package/dist/cjs/intlayerPlugin.cjs.map +1 -1
- package/dist/cjs/intlayerProxyPlugin.cjs +0 -4
- package/dist/cjs/intlayerProxyPlugin.cjs.map +1 -1
- package/dist/cjs/intlayerPrunePlugin.cjs +0 -4
- package/dist/cjs/intlayerPrunePlugin.cjs.map +1 -1
- package/package.json +20 -20
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_intlayerPrunePlugin = require('./intlayerPrunePlugin.cjs');
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
5
4
|
let __intlayer_chokidar = require("@intlayer/chokidar");
|
|
6
|
-
__intlayer_chokidar = require_rolldown_runtime.__toESM(__intlayer_chokidar);
|
|
7
5
|
let __intlayer_config = require("@intlayer/config");
|
|
8
|
-
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
9
6
|
|
|
10
7
|
//#region src/intlayerPlugin.ts
|
|
11
8
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPlugin.cjs","names":["plugins: PluginOption[]","intlayerPrune"],"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { prepareIntlayer, watch } from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getAlias,\n getConfiguration,\n} from '@intlayer/config';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport type { PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\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 = (\n configOptions?: GetConfigurationOptions\n): PluginOption => {\n const intlayerConfig = getConfiguration(configOptions);\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (_server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n // Code to run when Vite build starts\n await prepareIntlayer(intlayerConfig);\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\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":"
|
|
1
|
+
{"version":3,"file":"intlayerPlugin.cjs","names":["plugins: PluginOption[]","intlayerPrune"],"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { prepareIntlayer, watch } from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getAlias,\n getConfiguration,\n} from '@intlayer/config';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport type { PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\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 = (\n configOptions?: GetConfigurationOptions\n): PluginOption => {\n const intlayerConfig = getConfiguration(configOptions);\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (_server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n // Code to run when Vite build starts\n await prepareIntlayer(intlayerConfig);\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\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":";;;;;;;;;;;;;;;;;;;AAuBA,MAAa,kBACX,kBACiB;CACjB,MAAM,yDAAkC,cAAc;CACtD,MAAM,EAAE,OAAO,gBAAgB,eAAe;CAC9C,MAAM,EAAE,aAAa,eAAe;CAEpC,MAAMA,UAA0B,CAC9B;EACE,MAAM;EAEN,SAAS,WAAW;AAElB,UAAO,UAAU;IACf,GAAG,OAAO;IACV,OAAO;KACL,GAAG,OAAO,SAAS;KACnB,mCAAY;MACV,eAAe;MACf,YAAY,iCAA0B,MAAM;MAC7C,CAAC;KACH;IACF;AAED,OAAI,YACF,QAAO,eAAe;IACpB,GAAG,OAAO;IACV,SAAS;KACP,GAAI,OAAO,cAAc,WAAW,EAAE;KACtC;KACA;KACD;IACF;AAGH,UAAO;;EAGT,iBAAiB,OAAO,YAAY;AAClC,OAAI,eAAe,QAAQ,MAEzB,gCAAM,EAAE,eAAe,gBAAgB,CAAC;;EAI5C,YAAY,YAAY;AAEtB,kDAAsB,eAAe;;EAExC,CACF;AAGD,KAAI,SACF,SAAQ,KAAKC,0CAAc,eAAe,CAAC;AAG7C,QAAO;;;;;;;;;;;;AAaT,MAAa,WAAW;;;;;;;;;;;;;AAaxB,MAAa,iBAAiB"}
|
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
let __intlayer_config = require("@intlayer/config");
|
|
3
|
-
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
4
3
|
let node_url = require("node:url");
|
|
5
|
-
node_url = require_rolldown_runtime.__toESM(node_url);
|
|
6
4
|
let __intlayer_config_client = require("@intlayer/config/client");
|
|
7
|
-
__intlayer_config_client = require_rolldown_runtime.__toESM(__intlayer_config_client);
|
|
8
5
|
let __intlayer_core = require("@intlayer/core");
|
|
9
|
-
__intlayer_core = require_rolldown_runtime.__toESM(__intlayer_core);
|
|
10
6
|
|
|
11
7
|
//#region src/intlayerProxyPlugin.ts
|
|
12
8
|
const { internationalization, routing } = (0, __intlayer_config.getConfiguration)();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxyPlugin.cjs","names":["DefaultValues","search"],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getLocaleFromStorage,\n localeDetector,\n setLocaleInStorage,\n} from '@intlayer/core';\nimport type { Locale } from '@intlayer/types';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - routing.mode\n// - routing.storage\n// - routing.headerName\n// - routing.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, routing } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst { basePath = '', mode = DefaultValues.Routing.ROUTING_MODE } = routing;\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin() ],\n * });\n */\nexport const intlayerProxy = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\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\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. 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 // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. 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,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\n const cookieHeader = req.headers.cookie ?? '';\n const cookies = cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n return cookies[name] ?? null;\n },\n });\n return locale;\n};\n\n/**\n * Appends locale to search params when routing mode is 'search-params'.\n */\nconst 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 params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst 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 */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\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 */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n) => {\n req.url = newUrl;\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) => res.setHeader(name, value),\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 */\nconst 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 // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n if (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}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n\n let newPath = `${normalizedBasePath}${basePathTrailingSlash ? '' : ''}${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 */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\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 // 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}${originalPath}`;\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);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${originalPath}`;\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 */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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}) => {\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 });\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 });\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 */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\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 // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, originalPath, 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);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\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 originalPath,\n searchParams,\n pathLocale,\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 */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n let newPath = originalPath.replace(`/${defaultLocale}`, '') || '/';\n // In prefix modes, don't add locale to search params\n // Just preserve the original search params if they exist\n if (searchParams) {\n newPath += searchParams;\n }\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n // Preserve original search params without adding locale\n const newPath = searchParams\n ? `${originalPath}${searchParams}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\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":";;;;;;;;;;;AAuBA,MAAM,EAAE,sBAAsB,qDADW;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,OAAOA,uCAAc,QAAQ,iBAAiB;AAGrE,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;AAW/B,MAAa,sBAA8B;AACzC,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IAOpC,IAAI,KAAK,WAAW,KAAK,IAMzB,IAAI,KAAK,WAAW,MAAM,IAI1B,IAAI,KACA,MAAM,IAAI,CAAC,GACZ,MAAM,aAAa,CAEtB,QAAO,MAAM;IAIf,MAAM,gCAAkB,IAAI,OAAO,KAAK,KAAK;IAC7C,MAAM,eAAe,UAAU,YAAY;IAC3C,MAAM,eAAe,UAAU,UAAU;IAGzC,MAAM,gBAAgB,iBAAiB,IAAI;IAG3C,MAAM,aAAa,cAAc,aAAa;AAG9C,QAAI,UAAU;AACZ,oBAAe;MACb;MACA;MACA;MACA;MACA;MACA;MACD,CAAC;AACF;;AAIF,iBAAa;KACX;KACA;KACA;KACA;KACA;KACA;KACA;KACD,CAAC;KACF;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AIX,MAAM,SAAS,2BAA2B,cAAc,OAAO;CAC/D,MAAM,UAAU,cAAc,QAAQ,cAAc,OAAO;AAI3D,KAAI,iBAAiB,WAAW,cAC9B,QAAO,YAAY,KAAK,QAAQ;AAIlC,YAAW,KAAK,KAAK,SAAS,OAAO;AACrC,QAAO,MAAM;;;;;AAMf,MAAM,4BAA4B,EAChC,KACA,KACA,MACA,cACA,cACA,iBAQI;AAGJ,6BAA4B;EAC1B;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;;;;;AAMJ,MAAM,+BAA+B,EACnC,KACA,KACA,MACA,cACA,cACA,iBAQI;AAEJ,KAAI,CAAC,iBAAiB,eAAe,eAAe;EAElD,IAAI,UAAU,aAAa,QAAQ,IAAI,iBAAiB,GAAG,IAAI;AAG/D,MAAI,aACF,YAAW;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;AAQf,YAAW,KAAK,KAHA,eACZ,GAAG,eAAe,iBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;;;AAef,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.cjs","names":["DefaultValues","search"],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getLocaleFromStorage,\n localeDetector,\n setLocaleInStorage,\n} from '@intlayer/core';\nimport type { Locale } from '@intlayer/types';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - routing.mode\n// - routing.storage\n// - routing.headerName\n// - routing.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, routing } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst { basePath = '', mode = DefaultValues.Routing.ROUTING_MODE } = routing;\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin() ],\n * });\n */\nexport const intlayerProxy = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\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\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. 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 // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. 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,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\n const cookieHeader = req.headers.cookie ?? '';\n const cookies = cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n return cookies[name] ?? null;\n },\n });\n return locale;\n};\n\n/**\n * Appends locale to search params when routing mode is 'search-params'.\n */\nconst 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 params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst 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 */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\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 */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n) => {\n req.url = newUrl;\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) => res.setHeader(name, value),\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 */\nconst 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 // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n if (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}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n\n let newPath = `${normalizedBasePath}${basePathTrailingSlash ? '' : ''}${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 */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\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 // 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}${originalPath}`;\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);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${originalPath}`;\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 */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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}) => {\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 });\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 });\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 */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\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 // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, originalPath, 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);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\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 originalPath,\n searchParams,\n pathLocale,\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 */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n let newPath = originalPath.replace(`/${defaultLocale}`, '') || '/';\n // In prefix modes, don't add locale to search params\n // Just preserve the original search params if they exist\n if (searchParams) {\n newPath += searchParams;\n }\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n // Preserve original search params without adding locale\n const newPath = searchParams\n ? `${originalPath}${searchParams}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\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":";;;;;;;AAuBA,MAAM,EAAE,sBAAsB,qDADW;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,OAAOA,uCAAc,QAAQ,iBAAiB;AAGrE,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;AAW/B,MAAa,sBAA8B;AACzC,QAAO;EACL,MAAM;EACN,kBAAkB,W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MAAa,2BAA2B"}
|
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
let node_path = require("node:path");
|
|
3
|
-
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
4
3
|
let node_module = require("node:module");
|
|
5
|
-
node_module = require_rolldown_runtime.__toESM(node_module);
|
|
6
4
|
let __intlayer_babel = require("@intlayer/babel");
|
|
7
|
-
__intlayer_babel = require_rolldown_runtime.__toESM(__intlayer_babel);
|
|
8
5
|
let __intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
9
|
-
__intlayer_dictionaries_entry = require_rolldown_runtime.__toESM(__intlayer_dictionaries_entry);
|
|
10
6
|
let fast_glob = require("fast-glob");
|
|
11
7
|
fast_glob = require_rolldown_runtime.__toESM(fast_glob);
|
|
12
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPrunePlugin.cjs","names":["fg","intlayerBabelPlugin"],"sources":["../../src/intlayerPrunePlugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { intlayerBabelPlugin } from '@intlayer/babel';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport type { PluginOption } from 'vite';\n\nexport const intlayerPrune = (intlayerConfig: IntlayerConfig): PluginOption => {\n try {\n const localeRequire = createRequire(import.meta.url);\n const babel = localeRequire('@babel/core');\n\n const { optimize, importMode, traversePattern } = intlayerConfig.build;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n baseDir,\n } = intlayerConfig.content;\n\n const filesListPattern = fg\n .sync(traversePattern, {\n cwd: baseDir,\n })\n .map((file) => join(baseDir, file));\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const 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 ];\n\n const dictionaries = getDictionaries();\n const liveSyncKeys = Object.values(dictionaries)\n .filter((dictionary) => dictionary.live)\n .map((dictionary) => dictionary.key);\n\n return {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\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 if (!filesList.includes(filename)) return null;\n if (!optimize) return null;\n\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerBabelPlugin,\n {\n dictionariesDir,\n dictionariesEntryPath,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: false,\n liveSyncKeys,\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 } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return null;\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"intlayerPrunePlugin.cjs","names":["fg","intlayerBabelPlugin"],"sources":["../../src/intlayerPrunePlugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { intlayerBabelPlugin } from '@intlayer/babel';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport type { PluginOption } from 'vite';\n\nexport const intlayerPrune = (intlayerConfig: IntlayerConfig): PluginOption => {\n try {\n const localeRequire = createRequire(import.meta.url);\n const babel = localeRequire('@babel/core');\n\n const { optimize, importMode, traversePattern } = intlayerConfig.build;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n baseDir,\n } = intlayerConfig.content;\n\n const filesListPattern = fg\n .sync(traversePattern, {\n cwd: baseDir,\n })\n .map((file) => join(baseDir, file));\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const 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 ];\n\n const dictionaries = getDictionaries();\n const liveSyncKeys = Object.values(dictionaries)\n .filter((dictionary) => dictionary.live)\n .map((dictionary) => dictionary.key);\n\n return {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\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 if (!filesList.includes(filename)) return null;\n if (!optimize) return null;\n\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerBabelPlugin,\n {\n dictionariesDir,\n dictionariesEntryPath,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: false,\n liveSyncKeys,\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 } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return null;\n }\n};\n"],"mappings":";;;;;;;;;AAQA,MAAa,iBAAiB,mBAAiD;AAC7E,KAAI;EAEF,MAAM,qFAD8C,CACxB,cAAc;EAE1C,MAAM,EAAE,UAAU,YAAY,oBAAoB,eAAe;EAEjE,MAAM,EACJ,iBACA,wBACA,sBACA,SACA,YACE,eAAe;EAEnB,MAAM,mBAAmBA,kBACtB,KAAK,iBAAiB,EACrB,KAAK,SACN,CAAC,CACD,KAAK,6BAAc,SAAS,KAAK,CAAC;EAErC,MAAM,4CAA6B,SAAS,mBAAmB;EAC/D,MAAM,mDACJ,SACA,2BACD;EAED,MAAM,YAAY,CAChB,GAAG,kBACH,sBACD;EAED,MAAM,mEAAgC;EACtC,MAAM,eAAe,OAAO,OAAO,aAAa,CAC7C,QAAQ,eAAe,WAAW,KAAK,CACvC,KAAK,eAAe,WAAW,IAAI;AAEtC,SAAO;GACL,MAAM;GACN,SAAS;GACT,UAAU,MAAM,IAAI;;;;;;;;;IASlB,MAAM,WAAW,GAAG,MAAM,KAAK,EAAE,CAAC;AAClC,QAAI,CAAC,UAAU,SAAS,SAAS,CAAE,QAAO;AAC1C,QAAI,CAAC,SAAU,QAAO;IAEtB,MAAM,SAAS,MAAM,cAAc,MAAM;KACvC;KACA,SAAS,CACP,CACEC,sCACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA,wBAAwB;MACxB;MACD,CACF,CACF;KACD,YAAY;MACV,YAAY;MACZ,6BAA6B;MAC7B,SAAS;OACP;OACA;OACA;OACA;OACA;OACA;OACA;OACA;OACA;OACA;OACA;OACA;OACD;MACF;KACF,CAAC;AAEF,QAAI,QAAQ,KACV,QAAO;KACL,MAAM,OAAO;KACb,KAAK,OAAO;KACb;;GAGN;UACM,OAAO;AACd,UAAQ,KAAK,0CAA0C,MAAM;AAE7D,SAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-intlayer",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.8-canary.0",
|
|
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": [
|
|
@@ -73,32 +73,32 @@
|
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
75
|
"@babel/core": "7.28.4",
|
|
76
|
-
"@intlayer/babel": "7.0.
|
|
77
|
-
"@intlayer/chokidar": "7.0.
|
|
78
|
-
"@intlayer/config": "7.0.
|
|
79
|
-
"@intlayer/core": "7.0.
|
|
80
|
-
"@intlayer/dictionaries-entry": "7.0.
|
|
81
|
-
"@intlayer/types": "7.0.
|
|
76
|
+
"@intlayer/babel": "7.0.8-canary.0",
|
|
77
|
+
"@intlayer/chokidar": "7.0.8-canary.0",
|
|
78
|
+
"@intlayer/config": "7.0.8-canary.0",
|
|
79
|
+
"@intlayer/core": "7.0.8-canary.0",
|
|
80
|
+
"@intlayer/dictionaries-entry": "7.0.8-canary.0",
|
|
81
|
+
"@intlayer/types": "7.0.8-canary.0",
|
|
82
82
|
"fast-glob": "3.3.3",
|
|
83
|
-
"intlayer": "7.0.
|
|
83
|
+
"intlayer": "7.0.8-canary.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
|
-
"@types/node": "24.
|
|
87
|
-
"@utils/ts-config": "7.0.
|
|
88
|
-
"@utils/ts-config-types": "7.0.
|
|
89
|
-
"@utils/tsdown-config": "7.0.
|
|
90
|
-
"rimraf": "6.0
|
|
91
|
-
"tsdown": "0.
|
|
86
|
+
"@types/node": "24.10.0",
|
|
87
|
+
"@utils/ts-config": "7.0.8-canary.0",
|
|
88
|
+
"@utils/ts-config-types": "7.0.8-canary.0",
|
|
89
|
+
"@utils/tsdown-config": "7.0.8-canary.0",
|
|
90
|
+
"rimraf": "6.1.0",
|
|
91
|
+
"tsdown": "0.16.0",
|
|
92
92
|
"typescript": "5.9.3",
|
|
93
|
-
"vitest": "4.0.
|
|
93
|
+
"vitest": "4.0.7"
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
96
96
|
"@babel/core": ">=6.0.0",
|
|
97
|
-
"@intlayer/chokidar": "7.0.
|
|
98
|
-
"@intlayer/config": "7.0.
|
|
99
|
-
"@intlayer/core": "7.0.
|
|
100
|
-
"@intlayer/dictionaries-entry": "7.0.
|
|
101
|
-
"@intlayer/types": "7.0.
|
|
97
|
+
"@intlayer/chokidar": "7.0.8-canary.0",
|
|
98
|
+
"@intlayer/config": "7.0.8-canary.0",
|
|
99
|
+
"@intlayer/core": "7.0.8-canary.0",
|
|
100
|
+
"@intlayer/dictionaries-entry": "7.0.8-canary.0",
|
|
101
|
+
"@intlayer/types": "7.0.8-canary.0",
|
|
102
102
|
"vite": ">=4.0.0"
|
|
103
103
|
},
|
|
104
104
|
"peerDependenciesMeta": {
|