vite-intlayer 7.1.6 → 7.1.8-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,11 +5,6 @@ let __intlayer_config_client = require("@intlayer/config/client");
5
5
  let __intlayer_core = require("@intlayer/core");
6
6
 
7
7
  //#region src/intlayerProxyPlugin.ts
8
- const { internationalization, routing } = (0, __intlayer_config.getConfiguration)();
9
- const { locales: supportedLocales, defaultLocale } = internationalization;
10
- const { basePath = "", mode = __intlayer_config_client.DefaultValues.Routing.ROUTING_MODE } = routing;
11
- const noPrefix = mode === "no-prefix" || mode === "search-params";
12
- const prefixDefault = mode === "prefix-all";
13
8
  /**
14
9
  *
15
10
  * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
@@ -19,7 +14,160 @@ const prefixDefault = mode === "prefix-all";
19
14
  * plugins: [ intlayerProxyPlugin() ],
20
15
  * });
21
16
  */
22
- const intlayerProxy = () => {
17
+ const intlayerProxy = (configOptions) => {
18
+ const { internationalization, routing } = (0, __intlayer_config.getConfiguration)(configOptions);
19
+ const { locales: supportedLocales, defaultLocale } = internationalization;
20
+ const { basePath = "", mode = __intlayer_config_client.DefaultValues.Routing.ROUTING_MODE } = routing;
21
+ const noPrefix = mode === "no-prefix" || mode === "search-params";
22
+ const prefixDefault = mode === "prefix-all";
23
+ /**
24
+ * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
25
+ */
26
+ const getStorageLocale = (req) => {
27
+ return (0, __intlayer_core.getLocaleFromStorage)({ getCookie: (name) => {
28
+ return (req.headers.cookie ?? "").split(";").reduce((acc, cookie) => {
29
+ const [key, val] = cookie.trim().split("=");
30
+ acc[key] = val;
31
+ return acc;
32
+ }, {})[name] ?? null;
33
+ } });
34
+ };
35
+ /**
36
+ * Appends locale to search params when routing mode is 'search-params'.
37
+ */
38
+ const appendLocaleSearchIfNeeded = (search, locale) => {
39
+ if (mode !== "search-params") return search;
40
+ const params = new URLSearchParams(search ?? "");
41
+ params.set("locale", locale);
42
+ return `?${params.toString()}`;
43
+ };
44
+ /**
45
+ * Extracts the locale from the URL pathname if present as the first segment.
46
+ */
47
+ const getPathLocale = (pathname) => {
48
+ const firstSegment = pathname.split("/").filter(Boolean)[0];
49
+ if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
50
+ };
51
+ /**
52
+ * Writes a 301 redirect response with the given new URL.
53
+ */
54
+ const redirectUrl = (res, newUrl) => {
55
+ res.writeHead(301, { Location: newUrl });
56
+ return res.end();
57
+ };
58
+ /**
59
+ * "Rewrite" the request internally by adjusting req.url;
60
+ * we also set the locale in the response header if needed.
61
+ */
62
+ const rewriteUrl = (req, res, newUrl, locale) => {
63
+ req.url = newUrl;
64
+ if (locale) (0, __intlayer_core.setLocaleInStorage)(locale, { setHeader: (name, value) => res.setHeader(name, value) });
65
+ };
66
+ /**
67
+ * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
68
+ * - basePath: (e.g., '/myapp')
69
+ * - locale: (e.g., 'en')
70
+ * - currentPath:(e.g., '/products/shoes')
71
+ * - search: (e.g., '?foo=bar')
72
+ */
73
+ const constructPath = (locale, currentPath, search) => {
74
+ const pathWithoutPrefix = currentPath.startsWith(`/${locale}`) ? currentPath.slice(`/${locale}`.length) ?? "/" : currentPath;
75
+ const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
76
+ const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
77
+ if (mode === "no-prefix") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
78
+ if (mode === "search-params") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
79
+ const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`) ? currentPath : `/${locale}${currentPath}`;
80
+ let newPath = `${normalizedBasePath}${basePath.endsWith("/") ? "" : ""}${pathWithLocalePrefix}`;
81
+ if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix}`;
82
+ if (search) newPath += search;
83
+ return newPath;
84
+ };
85
+ /**
86
+ * If `noPrefix` is true, we never prefix the locale in the URL.
87
+ * We simply rewrite the request to the same path, but with the best-chosen locale
88
+ * in a header or search params if desired.
89
+ */
90
+ const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
91
+ let locale = storageLocale ?? defaultLocale;
92
+ if (!storageLocale) locale = (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
93
+ if (mode === "search-params") {
94
+ if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
95
+ rewriteUrl(req, res, `${`/${locale}${originalPath}`}${searchParams ?? ""}`, locale);
96
+ return next();
97
+ }
98
+ const search$1 = appendLocaleSearchIfNeeded(searchParams, locale);
99
+ return redirectUrl(res, search$1 ? `${originalPath}${search$1}` : `${originalPath}${searchParams ?? ""}`);
100
+ }
101
+ const internalPath = `/${locale}${originalPath}`;
102
+ const search = appendLocaleSearchIfNeeded(searchParams, locale);
103
+ rewriteUrl(req, res, search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`, locale);
104
+ return next();
105
+ };
106
+ /**
107
+ * The main prefix logic:
108
+ * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite
109
+ * - If there is a pathLocale, handle storage mismatch or default locale special cases
110
+ */
111
+ const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale }) => {
112
+ if (!pathLocale) {
113
+ handleMissingPathLocale({
114
+ req,
115
+ res,
116
+ next,
117
+ originalPath,
118
+ searchParams,
119
+ storageLocale
120
+ });
121
+ return;
122
+ }
123
+ handleExistingPathLocale({
124
+ req,
125
+ res,
126
+ next,
127
+ originalPath,
128
+ searchParams,
129
+ pathLocale
130
+ });
131
+ };
132
+ /**
133
+ * Handles requests where the locale is missing from the URL pathname.
134
+ * We detect a locale from storage / headers / default, then either redirect or rewrite.
135
+ */
136
+ const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
137
+ let locale = storageLocale ?? (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
138
+ if (!supportedLocales.includes(locale)) locale = defaultLocale;
139
+ const search = appendLocaleSearchIfNeeded(searchParams, locale);
140
+ const newPath = constructPath(locale, originalPath, search);
141
+ if (prefixDefault || locale !== defaultLocale) return redirectUrl(res, newPath);
142
+ rewriteUrl(req, res, newPath, locale);
143
+ return next();
144
+ };
145
+ /**
146
+ * Handles requests where the locale prefix is present in the pathname.
147
+ */
148
+ const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
149
+ handleDefaultLocaleRedirect({
150
+ req,
151
+ res,
152
+ next,
153
+ originalPath,
154
+ searchParams,
155
+ pathLocale
156
+ });
157
+ };
158
+ /**
159
+ * If the path locale is the default locale but we don't want to prefix the default, remove it.
160
+ */
161
+ const handleDefaultLocaleRedirect = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
162
+ if (!prefixDefault && pathLocale === defaultLocale) {
163
+ let newPath = originalPath.replace(`/${defaultLocale}`, "") || "/";
164
+ if (searchParams) newPath += searchParams;
165
+ rewriteUrl(req, res, newPath, pathLocale);
166
+ return next();
167
+ }
168
+ rewriteUrl(req, res, searchParams ? `${originalPath}${searchParams}` : originalPath, pathLocale);
169
+ return next();
170
+ };
23
171
  return {
24
172
  name: "vite-intlayer-middleware-plugin",
25
173
  configureServer: (server) => {
@@ -55,154 +203,6 @@ const intlayerProxy = () => {
55
203
  };
56
204
  };
57
205
  /**
58
- * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
59
- */
60
- const getStorageLocale = (req) => {
61
- return (0, __intlayer_core.getLocaleFromStorage)({ getCookie: (name) => {
62
- return (req.headers.cookie ?? "").split(";").reduce((acc, cookie) => {
63
- const [key, val] = cookie.trim().split("=");
64
- acc[key] = val;
65
- return acc;
66
- }, {})[name] ?? null;
67
- } });
68
- };
69
- /**
70
- * Appends locale to search params when routing mode is 'search-params'.
71
- */
72
- const appendLocaleSearchIfNeeded = (search, locale) => {
73
- if (mode !== "search-params") return search;
74
- const params = new URLSearchParams(search ?? "");
75
- params.set("locale", locale);
76
- return `?${params.toString()}`;
77
- };
78
- /**
79
- * Extracts the locale from the URL pathname if present as the first segment.
80
- */
81
- const getPathLocale = (pathname) => {
82
- const firstSegment = pathname.split("/").filter(Boolean)[0];
83
- if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
84
- };
85
- /**
86
- * Writes a 301 redirect response with the given new URL.
87
- */
88
- const redirectUrl = (res, newUrl) => {
89
- res.writeHead(301, { Location: newUrl });
90
- return res.end();
91
- };
92
- /**
93
- * "Rewrite" the request internally by adjusting req.url;
94
- * we also set the locale in the response header if needed.
95
- */
96
- const rewriteUrl = (req, res, newUrl, locale) => {
97
- req.url = newUrl;
98
- if (locale) (0, __intlayer_core.setLocaleInStorage)(locale, { setHeader: (name, value) => res.setHeader(name, value) });
99
- };
100
- /**
101
- * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
102
- * - basePath: (e.g., '/myapp')
103
- * - locale: (e.g., 'en')
104
- * - currentPath:(e.g., '/products/shoes')
105
- * - search: (e.g., '?foo=bar')
106
- */
107
- const constructPath = (locale, currentPath, search) => {
108
- const pathWithoutPrefix = currentPath.startsWith(`/${locale}`) ? currentPath.slice(`/${locale}`.length) ?? "/" : currentPath;
109
- const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
110
- const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
111
- if (mode === "no-prefix") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
112
- if (mode === "search-params") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
113
- const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`) ? currentPath : `/${locale}${currentPath}`;
114
- let newPath = `${normalizedBasePath}${basePath.endsWith("/") ? "" : ""}${pathWithLocalePrefix}`;
115
- if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix}`;
116
- if (search) newPath += search;
117
- return newPath;
118
- };
119
- /**
120
- * If `noPrefix` is true, we never prefix the locale in the URL.
121
- * We simply rewrite the request to the same path, but with the best-chosen locale
122
- * in a header or search params if desired.
123
- */
124
- const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
125
- let locale = storageLocale ?? defaultLocale;
126
- if (!storageLocale) locale = (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
127
- if (mode === "search-params") {
128
- if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
129
- rewriteUrl(req, res, `${`/${locale}${originalPath}`}${searchParams ?? ""}`, locale);
130
- return next();
131
- }
132
- const search$1 = appendLocaleSearchIfNeeded(searchParams, locale);
133
- return redirectUrl(res, search$1 ? `${originalPath}${search$1}` : `${originalPath}${searchParams ?? ""}`);
134
- }
135
- const internalPath = `/${locale}${originalPath}`;
136
- const search = appendLocaleSearchIfNeeded(searchParams, locale);
137
- rewriteUrl(req, res, search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`, locale);
138
- return next();
139
- };
140
- /**
141
- * The main prefix logic:
142
- * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite
143
- * - If there is a pathLocale, handle storage mismatch or default locale special cases
144
- */
145
- const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale }) => {
146
- if (!pathLocale) {
147
- handleMissingPathLocale({
148
- req,
149
- res,
150
- next,
151
- originalPath,
152
- searchParams,
153
- storageLocale
154
- });
155
- return;
156
- }
157
- handleExistingPathLocale({
158
- req,
159
- res,
160
- next,
161
- originalPath,
162
- searchParams,
163
- pathLocale
164
- });
165
- };
166
- /**
167
- * Handles requests where the locale is missing from the URL pathname.
168
- * We detect a locale from storage / headers / default, then either redirect or rewrite.
169
- */
170
- const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
171
- let locale = storageLocale ?? (0, __intlayer_core.localeDetector)(req.headers, supportedLocales, defaultLocale);
172
- if (!supportedLocales.includes(locale)) locale = defaultLocale;
173
- const search = appendLocaleSearchIfNeeded(searchParams, locale);
174
- const newPath = constructPath(locale, originalPath, search);
175
- if (prefixDefault || locale !== defaultLocale) return redirectUrl(res, newPath);
176
- rewriteUrl(req, res, newPath, locale);
177
- return next();
178
- };
179
- /**
180
- * Handles requests where the locale prefix is present in the pathname.
181
- */
182
- const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
183
- handleDefaultLocaleRedirect({
184
- req,
185
- res,
186
- next,
187
- originalPath,
188
- searchParams,
189
- pathLocale
190
- });
191
- };
192
- /**
193
- * If the path locale is the default locale but we don't want to prefix the default, remove it.
194
- */
195
- const handleDefaultLocaleRedirect = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
196
- if (!prefixDefault && pathLocale === defaultLocale) {
197
- let newPath = originalPath.replace(`/${defaultLocale}`, "") || "/";
198
- if (searchParams) newPath += searchParams;
199
- rewriteUrl(req, res, newPath, pathLocale);
200
- return next();
201
- }
202
- rewriteUrl(req, res, searchParams ? `${originalPath}${searchParams}` : originalPath, pathLocale);
203
- return next();
204
- };
205
- /**
206
206
  * @deprecated Rename to intlayerProxy instead
207
207
  *
208
208
  * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxyPlugin.cjs","names":["DefaultValues","search"],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { getConfiguration } from '@intlayer/config';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getLocaleFromStorage,\n localeDetector,\n setLocaleInStorage,\n} from '@intlayer/core';\nimport type { Locale } from '@intlayer/types';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - routing.mode\n// - routing.storage\n// - routing.headerName\n// - routing.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, routing } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst { basePath = '', mode = DefaultValues.Routing.ROUTING_MODE } = routing;\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin() ],\n * });\n */\nexport const intlayerProxy = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/__') ||\n /**\n * ./myFile.js\n */\n req.url\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\n const cookieHeader = req.headers.cookie ?? '';\n const cookies = cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n return cookies[name] ?? null;\n },\n });\n return locale;\n};\n\n/**\n * Appends locale to search params when routing mode is 'search-params'.\n */\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => res.setHeader(name, value),\n });\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\nconst constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? (currentPath.slice(`/${locale}`.length) ?? '/')\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n if (mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n\n let newPath = `${normalizedBasePath}${basePathTrailingSlash ? '' : ''}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${originalPath}`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${originalPath}`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, originalPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n let newPath = originalPath.replace(`/${defaultLocale}`, '') || '/';\n // In prefix modes, don't add locale to search params\n // Just preserve the original search params if they exist\n if (searchParams) {\n newPath += searchParams;\n }\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n // Preserve original search params without adding locale\n const newPath = searchParams\n ? `${originalPath}${searchParams}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = intlayerProxy;\n"],"mappings":";;;;;;;AAuBA,MAAM,EAAE,sBAAsB,qDADW;AAEzC,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;AAErD,MAAM,EAAE,WAAW,IAAI,OAAOA,uCAAc,QAAQ,iBAAiB;AAGrE,MAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAM,gBAAgB,SAAS;;;;;;;;;;AAW/B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;;;;;;;;;;;AAef,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
1
+ {"version":3,"file":"intlayerProxyPlugin.cjs","names":["DefaultValues","search"],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} 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/**\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 = (\n configOptions?: GetConfigurationOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const { basePath = '', mode = DefaultValues.Routing.ROUTING_MODE } = routing;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\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 */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n 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 */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string\n ) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n 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 */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? (currentPath.slice(`/${locale}`.length) ?? '/')\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // 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 */\n const 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 */\n const 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 */\n const 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 */\n const 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 */\n const 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 return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/__') ||\n /**\n * ./myFile.js\n */\n req.url\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/**\n * @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":";;;;;;;;;;;;;;;;AAyBA,MAAa,iBACX,kBACW;CAGX,MAAM,EAAE,sBAAsB,oDAFU,cAAc;CAGtD,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;CAErD,MAAM,EAAE,WAAW,IAAI,OAAOA,uCAAc,QAAQ,iBAAiB;CAGrE,MAAM,WAAW,SAAS,eAAe,SAAS;CAClD,MAAM,gBAAgB,SAAS;;;;CAU/B,MAAM,oBAAoB,QAA6C;AAerE,mDAdoC,EAClC,YAAY,SAAiB;AAU3B,WATqB,IAAI,QAAQ,UAAU,IACd,MAAM,IAAI,CAAC,QACrC,KAAK,WAAW;IACf,MAAM,CAAC,KAAK,OAAO,OAAO,MAAM,CAAC,MAAM,IAAI;AAC3C,QAAI,OAAO;AACX,WAAO;MAET,EAAE,CACH,CACc,SAAS;KAE3B,CAAC;;;;;CAOJ,MAAM,8BACJ,QACA,WACuB;AACvB,MAAI,SAAS,gBAAiB,QAAO;EAErC,MAAM,SAAS,IAAI,gBAAgB,UAAU,GAAG;AAChD,SAAO,IAAI,UAAU,OAAO;AAC5B,SAAO,IAAI,OAAO,UAAU;;;;;CAM9B,MAAM,iBAAiB,aAAyC;EAI9D,MAAM,eADW,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CACtB;AAC9B,MAAI,gBAAgB,iBAAiB,SAAS,aAAuB,CACnE,QAAO;;;;;CAQX,MAAM,eACJ,KACA,WACG;AACH,MAAI,UAAU,KAAK,EAAE,UAAU,QAAQ,CAAC;AACxC,SAAO,IAAI,KAAK;;;;;;CAOlB,MAAM,cACJ,KACA,KACA,QACA,WACG;AACH,MAAI,MAAM;AAEV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AAK,WAAW,KAAK,IAMzB,IAAI,KAAK,WAAW,MAAM,IAI1B,IAAI,KACA,MAAM,IAAI,CAAC,GACZ,MAAM,aAAa,CAEtB,QAAO,MAAM;IAIf,MAAM,gCAAkB,IAAI,OAAO,KAAK,KAAK;IAC7C,MAAM,eAAe,UAAU,YAAY;IAC3C,MAAM,eAAe,UAAU,UAAU;IAGzC,MAAM,gBAAgB,iBAAiB,IAAI;IAG3C,MAAM,aAAa,cAAc,aAAa;AAG9C,QAAI,UAAU;AACZ,oBAAe;MACb;MACA;MACA;MACA;MACA;MACA;MACD,CAAC;AACF;;AAIF,iBAAa;KACX;KACA;KACA;KACA;KACA;KACA;KACA;KACD,CAAC;KACF;;EAEL;;;;;;;;;;;;;;AAeH,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
@@ -4,11 +4,6 @@ import { DefaultValues } from "@intlayer/config/client";
4
4
  import { getLocaleFromStorage, localeDetector, setLocaleInStorage } from "@intlayer/core";
5
5
 
6
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
7
  /**
13
8
  *
14
9
  * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
@@ -18,7 +13,160 @@ const prefixDefault = mode === "prefix-all";
18
13
  * plugins: [ intlayerProxyPlugin() ],
19
14
  * });
20
15
  */
21
- const intlayerProxy = () => {
16
+ const intlayerProxy = (configOptions) => {
17
+ const { internationalization, routing } = getConfiguration(configOptions);
18
+ const { locales: supportedLocales, defaultLocale } = internationalization;
19
+ const { basePath = "", mode = DefaultValues.Routing.ROUTING_MODE } = routing;
20
+ const noPrefix = mode === "no-prefix" || mode === "search-params";
21
+ const prefixDefault = mode === "prefix-all";
22
+ /**
23
+ * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
24
+ */
25
+ const getStorageLocale = (req) => {
26
+ return getLocaleFromStorage({ getCookie: (name) => {
27
+ return (req.headers.cookie ?? "").split(";").reduce((acc, cookie) => {
28
+ const [key, val] = cookie.trim().split("=");
29
+ acc[key] = val;
30
+ return acc;
31
+ }, {})[name] ?? null;
32
+ } });
33
+ };
34
+ /**
35
+ * Appends locale to search params when routing mode is 'search-params'.
36
+ */
37
+ const appendLocaleSearchIfNeeded = (search, locale) => {
38
+ if (mode !== "search-params") return search;
39
+ const params = new URLSearchParams(search ?? "");
40
+ params.set("locale", locale);
41
+ return `?${params.toString()}`;
42
+ };
43
+ /**
44
+ * Extracts the locale from the URL pathname if present as the first segment.
45
+ */
46
+ const getPathLocale = (pathname) => {
47
+ const firstSegment = pathname.split("/").filter(Boolean)[0];
48
+ if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
49
+ };
50
+ /**
51
+ * Writes a 301 redirect response with the given new URL.
52
+ */
53
+ const redirectUrl = (res, newUrl) => {
54
+ res.writeHead(301, { Location: newUrl });
55
+ return res.end();
56
+ };
57
+ /**
58
+ * "Rewrite" the request internally by adjusting req.url;
59
+ * we also set the locale in the response header if needed.
60
+ */
61
+ const rewriteUrl = (req, res, newUrl, locale) => {
62
+ req.url = newUrl;
63
+ if (locale) setLocaleInStorage(locale, { setHeader: (name, value) => res.setHeader(name, value) });
64
+ };
65
+ /**
66
+ * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
67
+ * - basePath: (e.g., '/myapp')
68
+ * - locale: (e.g., 'en')
69
+ * - currentPath:(e.g., '/products/shoes')
70
+ * - search: (e.g., '?foo=bar')
71
+ */
72
+ const constructPath = (locale, currentPath, search) => {
73
+ const pathWithoutPrefix = currentPath.startsWith(`/${locale}`) ? currentPath.slice(`/${locale}`.length) ?? "/" : currentPath;
74
+ const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
75
+ const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
76
+ if (mode === "no-prefix") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
77
+ if (mode === "search-params") return search ? `${pathWithoutPrefix}${search}` : pathWithoutPrefix;
78
+ const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`) ? currentPath : `/${locale}${currentPath}`;
79
+ let newPath = `${normalizedBasePath}${basePath.endsWith("/") ? "" : ""}${pathWithLocalePrefix}`;
80
+ if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix}`;
81
+ if (search) newPath += search;
82
+ return newPath;
83
+ };
84
+ /**
85
+ * If `noPrefix` is true, we never prefix the locale in the URL.
86
+ * We simply rewrite the request to the same path, but with the best-chosen locale
87
+ * in a header or search params if desired.
88
+ */
89
+ const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
90
+ let locale = storageLocale ?? defaultLocale;
91
+ if (!storageLocale) locale = localeDetector(req.headers, supportedLocales, defaultLocale);
92
+ if (mode === "search-params") {
93
+ if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
94
+ rewriteUrl(req, res, `${`/${locale}${originalPath}`}${searchParams ?? ""}`, locale);
95
+ return next();
96
+ }
97
+ const search$1 = appendLocaleSearchIfNeeded(searchParams, locale);
98
+ return redirectUrl(res, search$1 ? `${originalPath}${search$1}` : `${originalPath}${searchParams ?? ""}`);
99
+ }
100
+ const internalPath = `/${locale}${originalPath}`;
101
+ const search = appendLocaleSearchIfNeeded(searchParams, locale);
102
+ rewriteUrl(req, res, search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`, locale);
103
+ return next();
104
+ };
105
+ /**
106
+ * The main prefix logic:
107
+ * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite
108
+ * - If there is a pathLocale, handle storage mismatch or default locale special cases
109
+ */
110
+ const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale }) => {
111
+ if (!pathLocale) {
112
+ handleMissingPathLocale({
113
+ req,
114
+ res,
115
+ next,
116
+ originalPath,
117
+ searchParams,
118
+ storageLocale
119
+ });
120
+ return;
121
+ }
122
+ handleExistingPathLocale({
123
+ req,
124
+ res,
125
+ next,
126
+ originalPath,
127
+ searchParams,
128
+ pathLocale
129
+ });
130
+ };
131
+ /**
132
+ * Handles requests where the locale is missing from the URL pathname.
133
+ * We detect a locale from storage / headers / default, then either redirect or rewrite.
134
+ */
135
+ const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale }) => {
136
+ let locale = storageLocale ?? localeDetector(req.headers, supportedLocales, defaultLocale);
137
+ if (!supportedLocales.includes(locale)) locale = defaultLocale;
138
+ const search = appendLocaleSearchIfNeeded(searchParams, locale);
139
+ const newPath = constructPath(locale, originalPath, search);
140
+ if (prefixDefault || locale !== defaultLocale) return redirectUrl(res, newPath);
141
+ rewriteUrl(req, res, newPath, locale);
142
+ return next();
143
+ };
144
+ /**
145
+ * Handles requests where the locale prefix is present in the pathname.
146
+ */
147
+ const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
148
+ handleDefaultLocaleRedirect({
149
+ req,
150
+ res,
151
+ next,
152
+ originalPath,
153
+ searchParams,
154
+ pathLocale
155
+ });
156
+ };
157
+ /**
158
+ * If the path locale is the default locale but we don't want to prefix the default, remove it.
159
+ */
160
+ const handleDefaultLocaleRedirect = ({ req, res, next, originalPath, searchParams, pathLocale }) => {
161
+ if (!prefixDefault && pathLocale === defaultLocale) {
162
+ let newPath = originalPath.replace(`/${defaultLocale}`, "") || "/";
163
+ if (searchParams) newPath += searchParams;
164
+ rewriteUrl(req, res, newPath, pathLocale);
165
+ return next();
166
+ }
167
+ rewriteUrl(req, res, searchParams ? `${originalPath}${searchParams}` : originalPath, pathLocale);
168
+ return next();
169
+ };
22
170
  return {
23
171
  name: "vite-intlayer-middleware-plugin",
24
172
  configureServer: (server) => {
@@ -54,154 +202,6 @@ const intlayerProxy = () => {
54
202
  };
55
203
  };
56
204
  /**
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
205
  * @deprecated Rename to intlayerProxy instead
206
206
  *
207
207
  * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
@@ -1 +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 /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/__') ||\n /**\n * ./myFile.js\n */\n req.url\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\n const cookieHeader = req.headers.cookie ?? '';\n const cookies = cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n return cookies[name] ?? null;\n },\n });\n return locale;\n};\n\n/**\n * Appends locale to search params when routing mode is 'search-params'.\n */\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => res.setHeader(name, value),\n });\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\nconst constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? (currentPath.slice(`/${locale}`.length) ?? '/')\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n if (mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix}${search}`\n : pathWithoutPrefix;\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n\n let newPath = `${normalizedBasePath}${basePathTrailingSlash ? '' : ''}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${originalPath}`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${originalPath}`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n}) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, originalPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n let newPath = originalPath.replace(`/${defaultLocale}`, '') || '/';\n // In prefix modes, don't add locale to search params\n // Just preserve the original search params if they exist\n if (searchParams) {\n newPath += searchParams;\n }\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n // Preserve original search params without adding locale\n const newPath = searchParams\n ? `${originalPath}${searchParams}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin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,iBAQI;AAEJ,KAAI,CAAC,iBAAiB,eAAe,eAAe;EAElD,IAAI,UAAU,aAAa,QAAQ,IAAI,iBAAiB,GAAG,IAAI;AAG/D,MAAI,aACF,YAAW;AAEb,aAAW,KAAK,KAAK,SAAS,WAAW;AACzC,SAAO,MAAM;;AAQf,YAAW,KAAK,KAHA,eACZ,GAAG,eAAe,iBAClB,cAC0B,WAAW;AACzC,QAAO,MAAM;;;;;;;;;;;;;;AAef,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
1
+ {"version":3,"file":"intlayerProxyPlugin.mjs","names":["search"],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} 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/**\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 = (\n configOptions?: GetConfigurationOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const { basePath = '', mode = DefaultValues.Routing.ROUTING_MODE } = routing;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => {\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 */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n 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 */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string\n ) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n 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 */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? (currentPath.slice(`/${locale}`.length) ?? '/')\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // 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 */\n const 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 */\n const 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 */\n const 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 */\n const 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 */\n const 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 return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/__') ||\n /**\n * ./myFile.js\n */\n req.url\n ?.split('?')[0]\n .match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // 3. Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n });\n });\n },\n };\n};\n\n/**\n * @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":";;;;;;;;;;;;;;;AAyBA,MAAa,iBACX,kBACW;CAGX,MAAM,EAAE,sBAAsB,YAFP,iBAAiB,cAAc;CAGtD,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;CAErD,MAAM,EAAE,WAAW,IAAI,OAAO,cAAc,QAAQ,iBAAiB;CAGrE,MAAM,WAAW,SAAS,eAAe,SAAS;CAClD,MAAM,gBAAgB,SAAS;;;;CAU/B,MAAM,oBAAoB,QAA6C;AAerE,SAde,qBAAqB,EAClC,YAAY,SAAiB;AAU3B,WATqB,IAAI,QAAQ,UAAU,IACd,MAAM,IAAI,CAAC,QACrC,KAAK,WAAW;IACf,MAAM,CAAC,KAAK,OAAO,OAAO,MAAM,CAAC,MAAM,IAAI;AAC3C,QAAI,OAAO;AACX,WAAO;MAET,EAAE,CACH,CACc,SAAS;KAE3B,CAAC;;;;;CAOJ,MAAM,8BACJ,QACA,WACuB;AACvB,MAAI,SAAS,gBAAiB,QAAO;EAErC,MAAM,SAAS,IAAI,gBAAgB,UAAU,GAAG;AAChD,SAAO,IAAI,UAAU,OAAO;AAC5B,SAAO,IAAI,OAAO,UAAU;;;;;CAM9B,MAAM,iBAAiB,aAAyC;EAI9D,MAAM,eADW,S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W;AAEb,cAAW,KAAK,KAAK,SAAS,WAAW;AACzC,UAAO,MAAM;;AAQf,aAAW,KAAK,KAHA,eACZ,GAAG,eAAe,iBAClB,cAC0B,WAAW;AACzC,SAAO,MAAM;;AAGf,QAAO;EACL,MAAM;EACN,kBAAkB,WAAW;AAC3B,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;AAEzC,QACE,IAAI,KAAK,WAAW,gBAAgB,IAOpC,IAAI,KAAK,WAAW,KAAK,IAMzB,IAAI,KAAK,WAAW,MAAM,IAI1B,IAAI,KACA,MAAM,IAAI,CAAC,GACZ,MAAM,aAAa,CAEtB,QAAO,MAAM;IAIf,MAAM,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;;;;;;;;;;;;;;AAeH,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
@@ -1,3 +1,4 @@
1
+ import { GetConfigurationOptions } from "@intlayer/config";
1
2
  import { Plugin } from "vite";
2
3
 
3
4
  //#region src/intlayerProxyPlugin.d.ts
@@ -11,7 +12,7 @@ import { Plugin } from "vite";
11
12
  * plugins: [ intlayerProxyPlugin() ],
12
13
  * });
13
14
  */
14
- declare const intlayerProxy: () => Plugin;
15
+ declare const intlayerProxy: (configOptions?: GetConfigurationOptions) => Plugin;
15
16
  /**
16
17
  * @deprecated Rename to intlayerProxy instead
17
18
  *
@@ -24,7 +25,7 @@ declare const intlayerProxy: () => Plugin;
24
25
  * });
25
26
  * ```
26
27
  */
27
- declare const intlayerMiddleware: () => Plugin;
28
+ declare const intlayerMiddleware: (configOptions?: GetConfigurationOptions) => Plugin;
28
29
  /**
29
30
  * @deprecated Rename to intlayerProxy instead
30
31
  *
@@ -37,7 +38,7 @@ declare const intlayerMiddleware: () => Plugin;
37
38
  * });
38
39
  * ```
39
40
  */
40
- declare const intLayerMiddlewarePlugin: () => Plugin;
41
+ declare const intLayerMiddlewarePlugin: (configOptions?: GetConfigurationOptions) => Plugin;
41
42
  //#endregion
42
43
  export { intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy };
43
44
  //# sourceMappingURL=intlayerProxyPlugin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":[],"mappings":";;;;;;AAyCA;AAidA;AAcA;;;;;cA/da,qBAAoB;;;;;;;;;;;;;cAidpB,0BAjdoB;;;;;;;;;;;;;cA+dpB,gCA/doB"}
1
+ {"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":[],"mappings":";;;;;;;AAyBA;AAieA;AAcA;;;;;cA/ea,gCACK,4BACf;;;;;;;;;;;;;cA+dU,qCAheK,4BACf;;;;;;;;;;;;;cA6eU,2CA9eK,4BACf"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-intlayer",
3
- "version": "7.1.6",
3
+ "version": "7.1.8-canary.0",
4
4
  "private": false,
5
5
  "description": "A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration",
6
6
  "keywords": [
@@ -76,14 +76,14 @@
76
76
  },
77
77
  "dependencies": {
78
78
  "@babel/core": "7.28.4",
79
- "@intlayer/babel": "7.1.6",
80
- "@intlayer/chokidar": "7.1.6",
81
- "@intlayer/config": "7.1.6",
82
- "@intlayer/core": "7.1.6",
83
- "@intlayer/dictionaries-entry": "7.1.6",
84
- "@intlayer/types": "7.1.6",
79
+ "@intlayer/babel": "7.1.8-canary.0",
80
+ "@intlayer/chokidar": "7.1.8-canary.0",
81
+ "@intlayer/config": "7.1.8-canary.0",
82
+ "@intlayer/core": "7.1.8-canary.0",
83
+ "@intlayer/dictionaries-entry": "7.1.8-canary.0",
84
+ "@intlayer/types": "7.1.8-canary.0",
85
85
  "fast-glob": "3.3.3",
86
- "intlayer": "7.1.6"
86
+ "intlayer": "7.1.8-canary.0"
87
87
  },
88
88
  "devDependencies": {
89
89
  "@types/node": "24.10.1",
@@ -93,7 +93,7 @@
93
93
  "rimraf": "6.1.0",
94
94
  "tsdown": "0.16.5",
95
95
  "typescript": "5.9.3",
96
- "vitest": "4.0.8"
96
+ "vitest": "4.0.10"
97
97
  },
98
98
  "peerDependencies": {
99
99
  "@babel/core": ">=6.0.0",