vite-intlayer 7.0.0-canary.3 → 7.0.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/index.cjs +4 -4
- package/dist/cjs/intlayerMiddlewarePlugin.cjs +2 -2
- package/dist/cjs/intlayerMiddlewarePlugin.cjs.map +1 -1
- package/dist/cjs/intlayerPlugin.cjs +2 -2
- package/dist/cjs/intlayerProxyPlugin.cjs +240 -0
- package/dist/cjs/intlayerProxyPlugin.cjs.map +1 -0
- package/dist/cjs/intlayerPrunePlugin.cjs +2 -2
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/intlayerMiddlewarePlugin.mjs +3 -3
- package/dist/esm/intlayerMiddlewarePlugin.mjs.map +1 -1
- package/dist/esm/intlayerPlugin.mjs +1 -1
- package/dist/esm/intlayerProxyPlugin.mjs +233 -0
- package/dist/esm/intlayerProxyPlugin.mjs.map +1 -0
- package/dist/esm/intlayerPrunePlugin.mjs +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/intlayerMiddlewarePlugin.d.ts.map +1 -1
- package/dist/types/intlayerPlugin.d.ts +1 -1
- package/dist/types/intlayerProxyPlugin.d.ts +43 -0
- package/dist/types/intlayerProxyPlugin.d.ts.map +1 -0
- package/package.json +16 -16
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const require_intlayerMiddlewarePlugin = require('./intlayerMiddlewarePlugin.cjs');
|
|
2
1
|
const require_intlayerPrunePlugin = require('./intlayerPrunePlugin.cjs');
|
|
3
2
|
const require_intlayerPlugin = require('./intlayerPlugin.cjs');
|
|
3
|
+
const require_intlayerProxyPlugin = require('./intlayerProxyPlugin.cjs');
|
|
4
4
|
|
|
5
|
-
exports.
|
|
5
|
+
exports.intLayerMiddlewarePlugin = require_intlayerProxyPlugin.intLayerMiddlewarePlugin;
|
|
6
6
|
exports.intLayerPlugin = require_intlayerPlugin.intLayerPlugin;
|
|
7
7
|
exports.intlayer = require_intlayerPlugin.intlayer;
|
|
8
|
-
exports.intlayerMiddleware =
|
|
9
|
-
exports.intlayerMiddlewarePlugin = require_intlayerMiddlewarePlugin.intlayerMiddlewarePlugin;
|
|
8
|
+
exports.intlayerMiddleware = require_intlayerProxyPlugin.intlayerMiddleware;
|
|
10
9
|
exports.intlayerPlugin = require_intlayerPlugin.intlayerPlugin;
|
|
10
|
+
exports.intlayerProxy = require_intlayerProxyPlugin.intlayerProxy;
|
|
11
11
|
exports.intlayerPrune = require_intlayerPrunePlugin.intlayerPrune;
|
|
@@ -9,7 +9,7 @@ __intlayer_core = require_rolldown_runtime.__toESM(__intlayer_core);
|
|
|
9
9
|
//#region src/intlayerMiddlewarePlugin.ts
|
|
10
10
|
const { internationalization, routing } = (0, __intlayer_config.getConfiguration)();
|
|
11
11
|
const { locales: supportedLocales, defaultLocale } = internationalization;
|
|
12
|
-
const {
|
|
12
|
+
const { basePath = "", mode } = routing;
|
|
13
13
|
const noPrefix = mode === "no-prefix" || mode === "search-params";
|
|
14
14
|
const prefixDefault = mode === "prefix-all";
|
|
15
15
|
/**
|
|
@@ -98,7 +98,7 @@ const redirectUrl = (res, newUrl) => {
|
|
|
98
98
|
*/
|
|
99
99
|
const rewriteUrl = (req, res, newUrl, locale) => {
|
|
100
100
|
req.url = newUrl;
|
|
101
|
-
if (locale
|
|
101
|
+
if (locale) (0, __intlayer_core.setLocaleInStorage)(locale, { setHeader: (name, value) => res.setHeader(name, value) });
|
|
102
102
|
};
|
|
103
103
|
/**
|
|
104
104
|
* Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerMiddlewarePlugin.cjs","names":["locale","searchWithLocale"],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\nimport { getLocaleFromStorage, localeDetector } 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 { headerName, basePath = '', 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 * @deprecated Rename to intlayerMiddleware instead\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: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): 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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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 && headerName) {\n res.setHeader(headerName, locale);\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 // 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' mode, we do not prefix the path with the locale\n const pathWithLocalePrefix =\n mode === 'search-params' ? currentPath : `/${locale}${currentPath}`;\n\n // Combine basePath + locale prefix + the rest of the path\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 && mode !== 'search-params') {\n newPath = `${normalizedBasePath}${currentPath}`;\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 // Construct the new path with locale in search params if needed\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, newPath, locale);\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 possible mismatch with storage\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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 // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the storage locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locale;\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\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\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\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 * We verify if the storage locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\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 the storage locale is set and differs from the path locale, redirect\n if (storageLocale && storageLocale !== pathLocale) {\n // We want to swap out the pathLocale with the storageLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${storageLocale}`);\n const finalPath = constructPath(\n storageLocale,\n newPath.replace(/^\\/+/, '/'),\n appendLocaleSearchIfNeeded(searchParams, storageLocale)\n );\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\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 const searchWithLocale = appendLocaleSearchIfNeeded(\n searchParams,\n pathLocale\n );\n if (searchWithLocale) {\n newPath += searchWithLocale;\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 const searchWithLocale = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n const newPath = searchWithLocale\n ? `${originalPath}${searchWithLocale}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\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 = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware 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 = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;;;;;AAkBA,MAAM,EAAE,sBAAsB,qDADW;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,YAAY,WAAW,IAAI,SAAS;AAG5C,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;;AAY/B,MAAa,iCAAyC;AACpD,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IACpC,IAAI,KAAK,WAAW,KAAK,IACzB,IAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,QAAO,MAAM;IAIf,MAAM,gCAAkB,IAAI,OAAO,KAAK,KAAK;IAC7C,MAAM,eAAe,UAAU,YAA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;AACrC,QAAO,MAAM;;;;;;AAOf,MAAM,4BAA4B,EAChC,KACA,KACA,MACA,cACA,cACA,YACA,oBASI;AAEJ,KAAI,iBAAiB,kBAAkB,WAQrC,QAAO,YAAY,KALD,cAChB,eAFc,aAAa,QAAQ,IAAI,cAAc,IAAI,gBAAgB,CAGjE,QAAQ,QAAQ,IAAI,EAC5B,2BAA2B,cAAc,cAAc,CACxD,CACiC;AAIpC,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;EAC/D,MAAMC,qBAAmB,2BACvB,cACA,WACD;AACD,MAAIA,mBACF,YAAWA;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;CAIf,MAAM,mBAAmB,2BAA2B,cAAc,WAAW;AAI7E,YAAW,KAAK,KAHA,mBACZ,GAAG,eAAe,qBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;AAaf,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"intlayerMiddlewarePlugin.cjs","names":["locale","searchWithLocale"],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\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 } = routing;\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\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: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): 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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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 // 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' mode, we do not prefix the path with the locale\n const pathWithLocalePrefix =\n mode === 'search-params' ? currentPath : `/${locale}${currentPath}`;\n\n // Combine basePath + locale prefix + the rest of the path\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 && mode !== 'search-params') {\n newPath = `${normalizedBasePath}${currentPath}`;\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 // Construct the new path with locale in search params if needed\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, newPath, locale);\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 possible mismatch with storage\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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 // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the storage locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locale;\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\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\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\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 * We verify if the storage locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\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 the storage locale is set and differs from the path locale, redirect\n if (storageLocale && storageLocale !== pathLocale) {\n // We want to swap out the pathLocale with the storageLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${storageLocale}`);\n const finalPath = constructPath(\n storageLocale,\n newPath.replace(/^\\/+/, '/'),\n appendLocaleSearchIfNeeded(searchParams, storageLocale)\n );\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\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 const searchWithLocale = appendLocaleSearchIfNeeded(\n searchParams,\n pathLocale\n );\n if (searchWithLocale) {\n newPath += searchWithLocale;\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 const searchWithLocale = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n const newPath = searchWithLocale\n ? `${originalPath}${searchWithLocale}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\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 = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware 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 = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;;;;;AAsBA,MAAM,EAAE,sBAAsB,qDADW;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,SAAS;AAGhC,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;;AAY/B,MAAa,iCAAyC;AACpD,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IACpC,IAAI,KAAK,WAAW,KAAK,IACzB,IAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,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,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cAChB,eAFc,aAAa,QAAQ,IAAI,cAAc,IAAI,gBAAgB,CAGjE,QAAQ,QAAQ,IAAI,EAC5B,2BAA2B,cAAc,cAAc,CACxD,CACiC;AAIpC,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;EAC/D,MAAMC,qBAAmB,2BACvB,cACA,WACD;AACD,MAAIA,mBACF,YAAWA;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;CAIf,MAAM,mBAAmB,2BAA2B,cAAc,WAAW;AAI7E,YAAW,KAAK,KAHA,mBACZ,GAAG,eAAe,qBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;AAaf,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,qBAAqB"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_intlayerPrunePlugin = require('./intlayerPrunePlugin.cjs');
|
|
3
|
-
let __intlayer_config = require("@intlayer/config");
|
|
4
|
-
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
5
3
|
let node_path = require("node:path");
|
|
6
4
|
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
7
5
|
let __intlayer_chokidar = require("@intlayer/chokidar");
|
|
8
6
|
__intlayer_chokidar = require_rolldown_runtime.__toESM(__intlayer_chokidar);
|
|
7
|
+
let __intlayer_config = require("@intlayer/config");
|
|
8
|
+
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
9
9
|
|
|
10
10
|
//#region src/intlayerPlugin.ts
|
|
11
11
|
/**
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let __intlayer_config = require("@intlayer/config");
|
|
3
|
+
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
4
|
+
let node_url = require("node:url");
|
|
5
|
+
node_url = require_rolldown_runtime.__toESM(node_url);
|
|
6
|
+
let __intlayer_config_client = require("@intlayer/config/client");
|
|
7
|
+
__intlayer_config_client = require_rolldown_runtime.__toESM(__intlayer_config_client);
|
|
8
|
+
let __intlayer_core = require("@intlayer/core");
|
|
9
|
+
__intlayer_core = require_rolldown_runtime.__toESM(__intlayer_core);
|
|
10
|
+
|
|
11
|
+
//#region src/intlayerProxyPlugin.ts
|
|
12
|
+
const { internationalization, routing } = (0, __intlayer_config.getConfiguration)();
|
|
13
|
+
const { locales: supportedLocales, defaultLocale } = internationalization;
|
|
14
|
+
const { basePath = "", mode = __intlayer_config_client.DefaultValues.Routing.ROUTING_MODE } = routing;
|
|
15
|
+
const noPrefix = mode === "no-prefix" || mode === "search-params";
|
|
16
|
+
const prefixDefault = mode === "prefix-all";
|
|
17
|
+
/**
|
|
18
|
+
*
|
|
19
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
20
|
+
*
|
|
21
|
+
* // Example usage of the plugin in a Vite configuration
|
|
22
|
+
* export default defineConfig({
|
|
23
|
+
* plugins: [ intlayerProxyPlugin() ],
|
|
24
|
+
* });
|
|
25
|
+
*/
|
|
26
|
+
const intlayerProxy = () => {
|
|
27
|
+
return {
|
|
28
|
+
name: "vite-intlayer-middleware-plugin",
|
|
29
|
+
configureServer: (server) => {
|
|
30
|
+
server.middlewares.use((req, res, next) => {
|
|
31
|
+
if (req.url?.startsWith("/node_modules") || req.url?.startsWith("/@") || req.url?.split("?")[0].match(/\.[a-z]+$/i)) return next();
|
|
32
|
+
const parsedUrl = (0, node_url.parse)(req.url ?? "/", true);
|
|
33
|
+
const originalPath = parsedUrl.pathname ?? "/";
|
|
34
|
+
const searchParams = parsedUrl.search ?? "";
|
|
35
|
+
const storageLocale = getStorageLocale(req);
|
|
36
|
+
const pathLocale = getPathLocale(originalPath);
|
|
37
|
+
if (noPrefix) {
|
|
38
|
+
handleNoPrefix({
|
|
39
|
+
req,
|
|
40
|
+
res,
|
|
41
|
+
next,
|
|
42
|
+
originalPath,
|
|
43
|
+
searchParams,
|
|
44
|
+
storageLocale
|
|
45
|
+
});
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
handlePrefix({
|
|
49
|
+
req,
|
|
50
|
+
res,
|
|
51
|
+
next,
|
|
52
|
+
originalPath,
|
|
53
|
+
searchParams,
|
|
54
|
+
pathLocale,
|
|
55
|
+
storageLocale
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Retrieves the locale from storage (cookies, localStorage, sessionStorage).
|
|
63
|
+
*/
|
|
64
|
+
const getStorageLocale = (req) => {
|
|
65
|
+
return (0, __intlayer_core.getLocaleFromStorage)({ getCookie: (name) => {
|
|
66
|
+
return (req.headers.cookie ?? "").split(";").reduce((acc, cookie) => {
|
|
67
|
+
const [key, val] = cookie.trim().split("=");
|
|
68
|
+
acc[key] = val;
|
|
69
|
+
return acc;
|
|
70
|
+
}, {})[name] ?? null;
|
|
71
|
+
} });
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Appends locale to search params when routing mode is 'search-params'.
|
|
75
|
+
*/
|
|
76
|
+
const appendLocaleSearchIfNeeded = (search, locale) => {
|
|
77
|
+
if (mode !== "search-params") return search;
|
|
78
|
+
const params = new URLSearchParams(search ?? "");
|
|
79
|
+
params.set("locale", locale);
|
|
80
|
+
return `?${params.toString()}`;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Extracts the locale from the URL pathname if present as the first segment.
|
|
84
|
+
*/
|
|
85
|
+
const getPathLocale = (pathname) => {
|
|
86
|
+
const firstSegment = pathname.split("/").filter(Boolean)[0];
|
|
87
|
+
if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Writes a 301 redirect response with the given new URL.
|
|
91
|
+
*/
|
|
92
|
+
const redirectUrl = (res, newUrl) => {
|
|
93
|
+
res.writeHead(301, { Location: newUrl });
|
|
94
|
+
return res.end();
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* "Rewrite" the request internally by adjusting req.url;
|
|
98
|
+
* we also set the locale in the response header if needed.
|
|
99
|
+
*/
|
|
100
|
+
const rewriteUrl = (req, res, newUrl, locale) => {
|
|
101
|
+
req.url = newUrl;
|
|
102
|
+
if (locale) (0, __intlayer_core.setLocaleInStorage)(locale, { setHeader: (name, value) => res.setHeader(name, value) });
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
|
|
106
|
+
* - basePath: (e.g., '/myapp')
|
|
107
|
+
* - locale: (e.g., 'en')
|
|
108
|
+
* - currentPath:(e.g., '/products/shoes')
|
|
109
|
+
* - search: (e.g., '?foo=bar')
|
|
110
|
+
*/
|
|
111
|
+
const constructPath = (locale, currentPath, search) => {
|
|
112
|
+
const pathWithoutPrefix = currentPath.startsWith(`/${locale}`) ? currentPath.slice(`/${locale}`.length) ?? "/" : currentPath;
|
|
113
|
+
const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
|
|
114
|
+
const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
|
|
115
|
+
if (mode === "no-prefix") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
|
|
116
|
+
if (mode === "search-params") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
|
|
117
|
+
const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`) ? currentPath : `/${locale}${currentPath}`;
|
|
118
|
+
let newPath = `${normalizedBasePath}${basePath.endsWith("/") ? "" : ""}${pathWithLocalePrefix}`;
|
|
119
|
+
if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix}`;
|
|
120
|
+
if (search) newPath += search;
|
|
121
|
+
return newPath;
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* If `noPrefix` is true, we never prefix the locale in the URL.
|
|
125
|
+
* We simply rewrite the request to the same path, but with the best-chosen locale
|
|
126
|
+
* in a header or search params if desired.
|
|
127
|
+
*/
|
|
128
|
+
const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
|
|
129
|
+
let locale = storageLocale ?? defaultLocale;
|
|
130
|
+
if (!storageLocale) locale = (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
|
|
131
|
+
if (mode === "search-params") {
|
|
132
|
+
if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
|
|
133
|
+
rewriteUrl(req, res, `${`/${locale}${originalPath}`}${searchParams ?? ""}`, locale);
|
|
134
|
+
return next();
|
|
135
|
+
}
|
|
136
|
+
const search$1 = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
137
|
+
return redirectUrl(res, search$1 ? `${originalPath}${search$1}` : `${originalPath}${searchParams ?? ""}`);
|
|
138
|
+
}
|
|
139
|
+
const internalPath = `/${locale}${originalPath}`;
|
|
140
|
+
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
141
|
+
rewriteUrl(req, res, search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`, locale);
|
|
142
|
+
return next();
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* The main prefix logic:
|
|
146
|
+
* - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite
|
|
147
|
+
* - If there is a pathLocale, handle storage mismatch or default locale special cases
|
|
148
|
+
*/
|
|
149
|
+
const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale }) => {
|
|
150
|
+
if (!pathLocale) {
|
|
151
|
+
handleMissingPathLocale({
|
|
152
|
+
req,
|
|
153
|
+
res,
|
|
154
|
+
next,
|
|
155
|
+
originalPath,
|
|
156
|
+
searchParams,
|
|
157
|
+
storageLocale
|
|
158
|
+
});
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
handleExistingPathLocale({
|
|
162
|
+
req,
|
|
163
|
+
res,
|
|
164
|
+
next,
|
|
165
|
+
originalPath,
|
|
166
|
+
searchParams,
|
|
167
|
+
pathLocale
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Handles requests where the locale is missing from the URL pathname.
|
|
172
|
+
* We detect a locale from storage / headers / default, then either redirect or rewrite.
|
|
173
|
+
*/
|
|
174
|
+
const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
|
|
175
|
+
let locale = storageLocale ?? (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
|
|
176
|
+
if (!supportedLocales.includes(locale)) locale = defaultLocale;
|
|
177
|
+
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
178
|
+
const newPath = constructPath(locale, originalPath, search);
|
|
179
|
+
if (prefixDefault || locale !== defaultLocale) return redirectUrl(res, newPath);
|
|
180
|
+
rewriteUrl(req, res, newPath, locale);
|
|
181
|
+
return next();
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Handles requests where the locale prefix is present in the pathname.
|
|
185
|
+
*/
|
|
186
|
+
const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
|
|
187
|
+
handleDefaultLocaleRedirect({
|
|
188
|
+
req,
|
|
189
|
+
res,
|
|
190
|
+
next,
|
|
191
|
+
originalPath,
|
|
192
|
+
searchParams,
|
|
193
|
+
pathLocale
|
|
194
|
+
});
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* If the path locale is the default locale but we don't want to prefix the default, remove it.
|
|
198
|
+
*/
|
|
199
|
+
const handleDefaultLocaleRedirect = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
|
|
200
|
+
if (!prefixDefault && pathLocale === defaultLocale) {
|
|
201
|
+
let newPath = originalPath.replace(`/${defaultLocale}`, "") || "/";
|
|
202
|
+
if (searchParams) newPath += searchParams;
|
|
203
|
+
rewriteUrl(req, res, newPath, pathLocale);
|
|
204
|
+
return next();
|
|
205
|
+
}
|
|
206
|
+
rewriteUrl(req, res, searchParams ? `${originalPath}${searchParams}` : originalPath, pathLocale);
|
|
207
|
+
return next();
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* @deprecated Rename to intlayerProxy instead
|
|
211
|
+
*
|
|
212
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
213
|
+
*
|
|
214
|
+
* ```ts
|
|
215
|
+
* // Example usage of the plugin in a Vite configuration
|
|
216
|
+
* export default defineConfig({
|
|
217
|
+
* plugins: [ intlayerMiddleware() ],
|
|
218
|
+
* });
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
const intlayerMiddleware = intlayerProxy;
|
|
222
|
+
/**
|
|
223
|
+
* @deprecated Rename to intlayerProxy instead
|
|
224
|
+
*
|
|
225
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
226
|
+
|
|
227
|
+
* ```ts
|
|
228
|
+
* // Example usage of the plugin in a Vite configuration
|
|
229
|
+
* export default defineConfig({
|
|
230
|
+
* plugins: [ intlayerMiddleware() ],
|
|
231
|
+
* });
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
const intLayerMiddlewarePlugin = intlayerProxy;
|
|
235
|
+
|
|
236
|
+
//#endregion
|
|
237
|
+
exports.intLayerMiddlewarePlugin = intLayerMiddlewarePlugin;
|
|
238
|
+
exports.intlayerMiddleware = intlayerMiddleware;
|
|
239
|
+
exports.intlayerProxy = intlayerProxy;
|
|
240
|
+
//# sourceMappingURL=intlayerProxyPlugin.cjs.map
|
|
@@ -0,0 +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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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,EAA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AAI;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,8 +1,8 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let __intlayer_config = require("@intlayer/config");
|
|
3
|
-
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
4
2
|
let node_path = require("node:path");
|
|
5
3
|
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
4
|
+
let __intlayer_config = require("@intlayer/config");
|
|
5
|
+
__intlayer_config = require_rolldown_runtime.__toESM(__intlayer_config);
|
|
6
6
|
let node_module = require("node:module");
|
|
7
7
|
node_module = require_rolldown_runtime.__toESM(node_module);
|
|
8
8
|
let __intlayer_babel = require("@intlayer/babel");
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { intLayerMiddleware, intlayerMiddleware, intlayerMiddlewarePlugin } from "./intlayerMiddlewarePlugin.mjs";
|
|
2
1
|
import { intlayerPrune } from "./intlayerPrunePlugin.mjs";
|
|
3
2
|
import { intLayerPlugin, intlayer, intlayerPlugin } from "./intlayerPlugin.mjs";
|
|
3
|
+
import { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy } from "./intlayerProxyPlugin.mjs";
|
|
4
4
|
|
|
5
|
-
export {
|
|
5
|
+
export { intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerMiddleware, intlayerPlugin, intlayerProxy, intlayerPrune };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { parse } from "node:url";
|
|
2
2
|
import { getConfiguration } from "@intlayer/config";
|
|
3
|
-
import { getLocaleFromStorage, localeDetector } from "@intlayer/core";
|
|
3
|
+
import { getLocaleFromStorage, localeDetector, setLocaleInStorage } from "@intlayer/core";
|
|
4
4
|
|
|
5
5
|
//#region src/intlayerMiddlewarePlugin.ts
|
|
6
6
|
const { internationalization, routing } = getConfiguration();
|
|
7
7
|
const { locales: supportedLocales, defaultLocale } = internationalization;
|
|
8
|
-
const {
|
|
8
|
+
const { basePath = "", mode } = routing;
|
|
9
9
|
const noPrefix = mode === "no-prefix" || mode === "search-params";
|
|
10
10
|
const prefixDefault = mode === "prefix-all";
|
|
11
11
|
/**
|
|
@@ -94,7 +94,7 @@ const redirectUrl = (res, newUrl) => {
|
|
|
94
94
|
*/
|
|
95
95
|
const rewriteUrl = (req, res, newUrl, locale) => {
|
|
96
96
|
req.url = newUrl;
|
|
97
|
-
if (locale
|
|
97
|
+
if (locale) setLocaleInStorage(locale, { setHeader: (name, value) => res.setHeader(name, value) });
|
|
98
98
|
};
|
|
99
99
|
/**
|
|
100
100
|
* Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerMiddlewarePlugin.mjs","names":["locale","searchWithLocale"],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\nimport { getLocaleFromStorage, localeDetector } 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 { headerName, basePath = '', 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 * @deprecated Rename to intlayerMiddleware instead\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: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): 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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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 && headerName) {\n res.setHeader(headerName, locale);\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 // 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' mode, we do not prefix the path with the locale\n const pathWithLocalePrefix =\n mode === 'search-params' ? currentPath : `/${locale}${currentPath}`;\n\n // Combine basePath + locale prefix + the rest of the path\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 && mode !== 'search-params') {\n newPath = `${normalizedBasePath}${currentPath}`;\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 // Construct the new path with locale in search params if needed\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, newPath, locale);\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 possible mismatch with storage\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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 // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the storage locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locale;\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\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\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\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 * We verify if the storage locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\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 the storage locale is set and differs from the path locale, redirect\n if (storageLocale && storageLocale !== pathLocale) {\n // We want to swap out the pathLocale with the storageLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${storageLocale}`);\n const finalPath = constructPath(\n storageLocale,\n newPath.replace(/^\\/+/, '/'),\n appendLocaleSearchIfNeeded(searchParams, storageLocale)\n );\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\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 const searchWithLocale = appendLocaleSearchIfNeeded(\n searchParams,\n pathLocale\n );\n if (searchWithLocale) {\n newPath += searchWithLocale;\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 const searchWithLocale = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n const newPath = searchWithLocale\n ? `${originalPath}${searchWithLocale}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\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 = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware 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 = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;AAkBA,MAAM,EAAE,sBAAsB,YADP,kBAAkB;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,YAAY,WAAW,IAAI,SAAS;AAG5C,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;;AAY/B,MAAa,iCAAyC;AACpD,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IACpC,IAAI,KAAK,WAAW,KAAK,IACzB,IAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,QAAO,MAAM;IAIf,MAAM,YAAY,MAAM,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;;EAEL;;;;;AAWH,MAAM,oBAAoB,QAA6C;AAerE,QAde,qBAAqB,EAClC,YAAY,SAAiB;AAU3B,UATqB,IAAI,QAAQ,UAAU,I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A+B,EACnC,KACA,KACA,MACA,cACA,cACA,iBAQI;AAEJ,KAAI,CAAC,iBAAiB,eAAe,eAAe;EAElD,IAAI,UAAU,aAAa,QAAQ,IAAI,iBAAiB,GAAG,IAAI;EAC/D,MAAMC,qBAAmB,2BACvB,cACA,WACD;AACD,MAAIA,mBACF,YAAWA;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;CAIf,MAAM,mBAAmB,2BAA2B,cAAc,WAAW;AAI7E,YAAW,KAAK,KAHA,mBACZ,GAAG,eAAe,qBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;AAaf,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"intlayerMiddlewarePlugin.mjs","names":["locale","searchWithLocale"],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\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 } = routing;\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\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: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): 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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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 // 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' mode, we do not prefix the path with the locale\n const pathWithLocalePrefix =\n mode === 'search-params' ? currentPath : `/${locale}${currentPath}`;\n\n // Combine basePath + locale prefix + the rest of the path\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 && mode !== 'search-params') {\n newPath = `${normalizedBasePath}${currentPath}`;\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 // Construct the new path with locale in search params if needed\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, newPath, locale);\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 possible mismatch with storage\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\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 // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the storage locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locale;\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\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\n const newPath = constructPath(\n locale,\n originalPath,\n appendLocaleSearchIfNeeded(searchParams, locale)\n );\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 * We verify if the storage locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\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 the storage locale is set and differs from the path locale, redirect\n if (storageLocale && storageLocale !== pathLocale) {\n // We want to swap out the pathLocale with the storageLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${storageLocale}`);\n const finalPath = constructPath(\n storageLocale,\n newPath.replace(/^\\/+/, '/'),\n appendLocaleSearchIfNeeded(searchParams, storageLocale)\n );\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\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 const searchWithLocale = appendLocaleSearchIfNeeded(\n searchParams,\n pathLocale\n );\n if (searchWithLocale) {\n newPath += searchWithLocale;\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 const searchWithLocale = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n const newPath = searchWithLocale\n ? `${originalPath}${searchWithLocale}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\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 = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware 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 = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;AAsBA,MAAM,EAAE,sBAAsB,YADP,kBAAkB;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,SAAS;AAGhC,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;;AAY/B,MAAa,iCAAyC;AACpD,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IACpC,IAAI,KAAK,WAAW,KAAK,IACzB,IAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,QAAO,MAAM;IAIf,MAAM,YAAY,MAAM,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;;EAEL;;;;;AAWH,MAAM,oBAAoB,QAA6C;AAerE,QAde,qBAAqB,EAClC,YAAY,SAAiB;AAU3B,UATqB,IAAI,QAAQ,UAAU,IACd,MAAM,IAAI,CAAC,QACrC,KAAK,WAAW;GACf,MAAM,CAAC,KAAK,OAAO,OAAO,MAAM,CAAC,MAAM,IAAI;AAC3C,OAAI,OAAO;AACX,UAAO;KAET,EAAE,CACH,CACc,SAAS;IAE3B,CA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BAAiB,GAAG,IAAI;EAC/D,MAAMC,qBAAmB,2BACvB,cACA,WACD;AACD,MAAIA,mBACF,YAAWA;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;CAIf,MAAM,mBAAmB,2BAA2B,cAAc,WAAW;AAI7E,YAAW,KAAK,KAHA,mBACZ,GAAG,eAAe,qBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;AAaf,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,qBAAqB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { intlayerPrune } from "./intlayerPrunePlugin.mjs";
|
|
2
|
-
import { getAlias, getConfiguration } from "@intlayer/config";
|
|
3
2
|
import { resolve } from "node:path";
|
|
4
3
|
import { prepareIntlayer, watch } from "@intlayer/chokidar";
|
|
4
|
+
import { getAlias, getConfiguration } from "@intlayer/config";
|
|
5
5
|
|
|
6
6
|
//#region src/intlayerPlugin.ts
|
|
7
7
|
/**
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { getConfiguration } from "@intlayer/config";
|
|
2
|
+
import { parse } from "node:url";
|
|
3
|
+
import { DefaultValues } from "@intlayer/config/client";
|
|
4
|
+
import { getLocaleFromStorage, localeDetector, setLocaleInStorage } from "@intlayer/core";
|
|
5
|
+
|
|
6
|
+
//#region src/intlayerProxyPlugin.ts
|
|
7
|
+
const { internationalization, routing } = getConfiguration();
|
|
8
|
+
const { locales: supportedLocales, defaultLocale } = internationalization;
|
|
9
|
+
const { basePath = "", mode = DefaultValues.Routing.ROUTING_MODE } = routing;
|
|
10
|
+
const noPrefix = mode === "no-prefix" || mode === "search-params";
|
|
11
|
+
const prefixDefault = mode === "prefix-all";
|
|
12
|
+
/**
|
|
13
|
+
*
|
|
14
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
15
|
+
*
|
|
16
|
+
* // Example usage of the plugin in a Vite configuration
|
|
17
|
+
* export default defineConfig({
|
|
18
|
+
* plugins: [ intlayerProxyPlugin() ],
|
|
19
|
+
* });
|
|
20
|
+
*/
|
|
21
|
+
const intlayerProxy = () => {
|
|
22
|
+
return {
|
|
23
|
+
name: "vite-intlayer-middleware-plugin",
|
|
24
|
+
configureServer: (server) => {
|
|
25
|
+
server.middlewares.use((req, res, next) => {
|
|
26
|
+
if (req.url?.startsWith("/node_modules") || req.url?.startsWith("/@") || req.url?.split("?")[0].match(/\.[a-z]+$/i)) return next();
|
|
27
|
+
const parsedUrl = parse(req.url ?? "/", true);
|
|
28
|
+
const originalPath = parsedUrl.pathname ?? "/";
|
|
29
|
+
const searchParams = parsedUrl.search ?? "";
|
|
30
|
+
const storageLocale = getStorageLocale(req);
|
|
31
|
+
const pathLocale = getPathLocale(originalPath);
|
|
32
|
+
if (noPrefix) {
|
|
33
|
+
handleNoPrefix({
|
|
34
|
+
req,
|
|
35
|
+
res,
|
|
36
|
+
next,
|
|
37
|
+
originalPath,
|
|
38
|
+
searchParams,
|
|
39
|
+
storageLocale
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
handlePrefix({
|
|
44
|
+
req,
|
|
45
|
+
res,
|
|
46
|
+
next,
|
|
47
|
+
originalPath,
|
|
48
|
+
searchParams,
|
|
49
|
+
pathLocale,
|
|
50
|
+
storageLocale
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Retrieves the locale from storage (cookies, localStorage, sessionStorage).
|
|
58
|
+
*/
|
|
59
|
+
const getStorageLocale = (req) => {
|
|
60
|
+
return getLocaleFromStorage({ getCookie: (name) => {
|
|
61
|
+
return (req.headers.cookie ?? "").split(";").reduce((acc, cookie) => {
|
|
62
|
+
const [key, val] = cookie.trim().split("=");
|
|
63
|
+
acc[key] = val;
|
|
64
|
+
return acc;
|
|
65
|
+
}, {})[name] ?? null;
|
|
66
|
+
} });
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Appends locale to search params when routing mode is 'search-params'.
|
|
70
|
+
*/
|
|
71
|
+
const appendLocaleSearchIfNeeded = (search, locale) => {
|
|
72
|
+
if (mode !== "search-params") return search;
|
|
73
|
+
const params = new URLSearchParams(search ?? "");
|
|
74
|
+
params.set("locale", locale);
|
|
75
|
+
return `?${params.toString()}`;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Extracts the locale from the URL pathname if present as the first segment.
|
|
79
|
+
*/
|
|
80
|
+
const getPathLocale = (pathname) => {
|
|
81
|
+
const firstSegment = pathname.split("/").filter(Boolean)[0];
|
|
82
|
+
if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Writes a 301 redirect response with the given new URL.
|
|
86
|
+
*/
|
|
87
|
+
const redirectUrl = (res, newUrl) => {
|
|
88
|
+
res.writeHead(301, { Location: newUrl });
|
|
89
|
+
return res.end();
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* "Rewrite" the request internally by adjusting req.url;
|
|
93
|
+
* we also set the locale in the response header if needed.
|
|
94
|
+
*/
|
|
95
|
+
const rewriteUrl = (req, res, newUrl, locale) => {
|
|
96
|
+
req.url = newUrl;
|
|
97
|
+
if (locale) setLocaleInStorage(locale, { setHeader: (name, value) => res.setHeader(name, value) });
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
|
|
101
|
+
* - basePath: (e.g., '/myapp')
|
|
102
|
+
* - locale: (e.g., 'en')
|
|
103
|
+
* - currentPath:(e.g., '/products/shoes')
|
|
104
|
+
* - search: (e.g., '?foo=bar')
|
|
105
|
+
*/
|
|
106
|
+
const constructPath = (locale, currentPath, search) => {
|
|
107
|
+
const pathWithoutPrefix = currentPath.startsWith(`/${locale}`) ? currentPath.slice(`/${locale}`.length) ?? "/" : currentPath;
|
|
108
|
+
const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
|
|
109
|
+
const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
|
|
110
|
+
if (mode === "no-prefix") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
|
|
111
|
+
if (mode === "search-params") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
|
|
112
|
+
const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`) ? currentPath : `/${locale}${currentPath}`;
|
|
113
|
+
let newPath = `${normalizedBasePath}${basePath.endsWith("/") ? "" : ""}${pathWithLocalePrefix}`;
|
|
114
|
+
if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix}`;
|
|
115
|
+
if (search) newPath += search;
|
|
116
|
+
return newPath;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* If `noPrefix` is true, we never prefix the locale in the URL.
|
|
120
|
+
* We simply rewrite the request to the same path, but with the best-chosen locale
|
|
121
|
+
* in a header or search params if desired.
|
|
122
|
+
*/
|
|
123
|
+
const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
|
|
124
|
+
let locale = storageLocale ?? defaultLocale;
|
|
125
|
+
if (!storageLocale) locale = localeDetector(req.headers, supportedLocales, defaultLocale);
|
|
126
|
+
if (mode === "search-params") {
|
|
127
|
+
if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
|
|
128
|
+
rewriteUrl(req, res, `${`/${locale}${originalPath}`}${searchParams ?? ""}`, locale);
|
|
129
|
+
return next();
|
|
130
|
+
}
|
|
131
|
+
const search$1 = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
132
|
+
return redirectUrl(res, search$1 ? `${originalPath}${search$1}` : `${originalPath}${searchParams ?? ""}`);
|
|
133
|
+
}
|
|
134
|
+
const internalPath = `/${locale}${originalPath}`;
|
|
135
|
+
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
136
|
+
rewriteUrl(req, res, search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`, locale);
|
|
137
|
+
return next();
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* The main prefix logic:
|
|
141
|
+
* - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite
|
|
142
|
+
* - If there is a pathLocale, handle storage mismatch or default locale special cases
|
|
143
|
+
*/
|
|
144
|
+
const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale }) => {
|
|
145
|
+
if (!pathLocale) {
|
|
146
|
+
handleMissingPathLocale({
|
|
147
|
+
req,
|
|
148
|
+
res,
|
|
149
|
+
next,
|
|
150
|
+
originalPath,
|
|
151
|
+
searchParams,
|
|
152
|
+
storageLocale
|
|
153
|
+
});
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
handleExistingPathLocale({
|
|
157
|
+
req,
|
|
158
|
+
res,
|
|
159
|
+
next,
|
|
160
|
+
originalPath,
|
|
161
|
+
searchParams,
|
|
162
|
+
pathLocale
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Handles requests where the locale is missing from the URL pathname.
|
|
167
|
+
* We detect a locale from storage / headers / default, then either redirect or rewrite.
|
|
168
|
+
*/
|
|
169
|
+
const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
|
|
170
|
+
let locale = storageLocale ?? localeDetector(req.headers, supportedLocales, defaultLocale);
|
|
171
|
+
if (!supportedLocales.includes(locale)) locale = defaultLocale;
|
|
172
|
+
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
173
|
+
const newPath = constructPath(locale, originalPath, search);
|
|
174
|
+
if (prefixDefault || locale !== defaultLocale) return redirectUrl(res, newPath);
|
|
175
|
+
rewriteUrl(req, res, newPath, locale);
|
|
176
|
+
return next();
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* Handles requests where the locale prefix is present in the pathname.
|
|
180
|
+
*/
|
|
181
|
+
const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
|
|
182
|
+
handleDefaultLocaleRedirect({
|
|
183
|
+
req,
|
|
184
|
+
res,
|
|
185
|
+
next,
|
|
186
|
+
originalPath,
|
|
187
|
+
searchParams,
|
|
188
|
+
pathLocale
|
|
189
|
+
});
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* If the path locale is the default locale but we don't want to prefix the default, remove it.
|
|
193
|
+
*/
|
|
194
|
+
const handleDefaultLocaleRedirect = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
|
|
195
|
+
if (!prefixDefault && pathLocale === defaultLocale) {
|
|
196
|
+
let newPath = originalPath.replace(`/${defaultLocale}`, "") || "/";
|
|
197
|
+
if (searchParams) newPath += searchParams;
|
|
198
|
+
rewriteUrl(req, res, newPath, pathLocale);
|
|
199
|
+
return next();
|
|
200
|
+
}
|
|
201
|
+
rewriteUrl(req, res, searchParams ? `${originalPath}${searchParams}` : originalPath, pathLocale);
|
|
202
|
+
return next();
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* @deprecated Rename to intlayerProxy instead
|
|
206
|
+
*
|
|
207
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
208
|
+
*
|
|
209
|
+
* ```ts
|
|
210
|
+
* // Example usage of the plugin in a Vite configuration
|
|
211
|
+
* export default defineConfig({
|
|
212
|
+
* plugins: [ intlayerMiddleware() ],
|
|
213
|
+
* });
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
const intlayerMiddleware = intlayerProxy;
|
|
217
|
+
/**
|
|
218
|
+
* @deprecated Rename to intlayerProxy instead
|
|
219
|
+
*
|
|
220
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
221
|
+
|
|
222
|
+
* ```ts
|
|
223
|
+
* // Example usage of the plugin in a Vite configuration
|
|
224
|
+
* export default defineConfig({
|
|
225
|
+
* plugins: [ intlayerMiddleware() ],
|
|
226
|
+
* });
|
|
227
|
+
* ```
|
|
228
|
+
*/
|
|
229
|
+
const intLayerMiddlewarePlugin = intlayerProxy;
|
|
230
|
+
|
|
231
|
+
//#endregion
|
|
232
|
+
export { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy };
|
|
233
|
+
//# sourceMappingURL=intlayerProxyPlugin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.mjs","names":["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 req.url?.startsWith('/@') ||\n req.url?.split('?')[0].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,YADP,kBAAkB;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,OAAO,cAAc,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,IACpC,IAAI,KAAK,WAAW,KAAK,IACzB,IAAI,KAAK,MAAM,IAAI,CAAC,GAAG,MAAM,aAAa,CAE1C,QAAO,MAAM;IAIf,MAAM,YAAY,MAAM,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;;EAEL;;;;;AAWH,MAAM,oBAAoB,QAA6C;AAerE,QAde,qBAAqB,EAClC,YAAY,SAAiB;AAU3B,UATqB,IAAI,QAAQ,UAAU,IACd,MAAM,IAAI,CAAC,QACrC,KAAK,WAAW;GACf,MAAM,CAAC,KAAK,OAAO,OAAO,MAAM,CAAC,MAAM,IAAI;AAC3C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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,6 +1,6 @@
|
|
|
1
1
|
import { __require } from "./_virtual/rolldown_runtime.mjs";
|
|
2
|
-
import { isESModule } from "@intlayer/config";
|
|
3
2
|
import { join } from "node:path";
|
|
3
|
+
import { isESModule } from "@intlayer/config";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { intlayerBabelPlugin } from "@intlayer/babel";
|
|
6
6
|
import { getDictionaries } from "@intlayer/dictionaries-entry";
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { intLayerMiddleware, intlayerMiddleware, intlayerMiddlewarePlugin } from "./intlayerMiddlewarePlugin.js";
|
|
2
1
|
import { intLayerPlugin, intlayer, intlayerPlugin } from "./intlayerPlugin.js";
|
|
2
|
+
import { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy } from "./intlayerProxyPlugin.js";
|
|
3
3
|
import { intlayerPrune } from "./intlayerPrunePlugin.js";
|
|
4
|
-
export {
|
|
4
|
+
export { intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerMiddleware, intlayerPlugin, intlayerProxy, intlayerPrune };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerMiddlewarePlugin.d.ts","names":[],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"intlayerMiddlewarePlugin.d.ts","names":[],"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":[],"mappings":";;;;;;AAyCA;AAubA;AAcA;;;;;;cArca,gCAA+B;;;;;;;;;;;cAub/B,0BAvb+B;;;;;;;;;;;;;cAqc/B,0BArc+B"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
|
|
3
|
+
//#region src/intlayerProxyPlugin.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
*
|
|
7
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
8
|
+
*
|
|
9
|
+
* // Example usage of the plugin in a Vite configuration
|
|
10
|
+
* export default defineConfig({
|
|
11
|
+
* plugins: [ intlayerProxyPlugin() ],
|
|
12
|
+
* });
|
|
13
|
+
*/
|
|
14
|
+
declare const intlayerProxy: () => Plugin;
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated Rename to intlayerProxy instead
|
|
17
|
+
*
|
|
18
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* // Example usage of the plugin in a Vite configuration
|
|
22
|
+
* export default defineConfig({
|
|
23
|
+
* plugins: [ intlayerMiddleware() ],
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
declare const intlayerMiddleware: () => Plugin;
|
|
28
|
+
/**
|
|
29
|
+
* @deprecated Rename to intlayerProxy instead
|
|
30
|
+
*
|
|
31
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
32
|
+
|
|
33
|
+
* ```ts
|
|
34
|
+
* // Example usage of the plugin in a Vite configuration
|
|
35
|
+
* export default defineConfig({
|
|
36
|
+
* plugins: [ intlayerMiddleware() ],
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
declare const intLayerMiddlewarePlugin: () => Plugin;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy };
|
|
43
|
+
//# sourceMappingURL=intlayerProxyPlugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":[],"mappings":";;;;;;AAyCA;AAgcA;AAcA;;;;;cA9ca,qBAAoB;;;;;;;;;;;;;cAgcpB,0BAhcoB;;;;;;;;;;;;;cA8cpB,gCA9coB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-intlayer",
|
|
3
|
-
"version": "7.0.0
|
|
3
|
+
"version": "7.0.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,20 +73,20 @@
|
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
75
|
"@babel/core": "7.28.4",
|
|
76
|
-
"@intlayer/babel": "7.0.0
|
|
77
|
-
"@intlayer/chokidar": "7.0.0
|
|
78
|
-
"@intlayer/config": "7.0.0
|
|
79
|
-
"@intlayer/core": "7.0.0
|
|
80
|
-
"@intlayer/dictionaries-entry": "7.0.0
|
|
81
|
-
"@intlayer/types": "7.0.0
|
|
76
|
+
"@intlayer/babel": "7.0.0",
|
|
77
|
+
"@intlayer/chokidar": "7.0.0",
|
|
78
|
+
"@intlayer/config": "7.0.0",
|
|
79
|
+
"@intlayer/core": "7.0.0",
|
|
80
|
+
"@intlayer/dictionaries-entry": "7.0.0",
|
|
81
|
+
"@intlayer/types": "7.0.0",
|
|
82
82
|
"fast-glob": "3.3.3",
|
|
83
|
-
"intlayer": "7.0.0
|
|
83
|
+
"intlayer": "7.0.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
86
|
"@types/node": "24.9.1",
|
|
87
|
-
"@utils/ts-config": "7.0.0
|
|
88
|
-
"@utils/ts-config-types": "7.0.0
|
|
89
|
-
"@utils/tsdown-config": "7.0.0
|
|
87
|
+
"@utils/ts-config": "7.0.0",
|
|
88
|
+
"@utils/ts-config-types": "7.0.0",
|
|
89
|
+
"@utils/tsdown-config": "7.0.0",
|
|
90
90
|
"rimraf": "6.0.1",
|
|
91
91
|
"tsdown": "0.15.9",
|
|
92
92
|
"typescript": "5.9.3",
|
|
@@ -94,11 +94,11 @@
|
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
96
96
|
"@babel/core": ">=6.0.0",
|
|
97
|
-
"@intlayer/chokidar": "7.0.0
|
|
98
|
-
"@intlayer/config": "7.0.0
|
|
99
|
-
"@intlayer/core": "7.0.0
|
|
100
|
-
"@intlayer/dictionaries-entry": "7.0.0
|
|
101
|
-
"@intlayer/types": "7.0.0
|
|
97
|
+
"@intlayer/chokidar": "7.0.0",
|
|
98
|
+
"@intlayer/config": "7.0.0",
|
|
99
|
+
"@intlayer/core": "7.0.0",
|
|
100
|
+
"@intlayer/dictionaries-entry": "7.0.0",
|
|
101
|
+
"@intlayer/types": "7.0.0",
|
|
102
102
|
"vite": ">=4.0.0"
|
|
103
103
|
},
|
|
104
104
|
"peerDependenciesMeta": {
|