vite-intlayer 9.3.2 → 9.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.mjs +3 -1
- package/dist/esm/intlayerChunkPlugin.mjs +181 -0
- package/dist/esm/intlayerChunkPlugin.mjs.map +1 -0
- package/dist/esm/intlayerNitroHandler.mjs +17 -7
- package/dist/esm/intlayerNitroHandler.mjs.map +1 -1
- package/dist/esm/intlayerPlugin.mjs +4 -0
- package/dist/esm/intlayerPlugin.mjs.map +1 -1
- package/dist/esm/intlayerPreloadPlugin.mjs +88 -0
- package/dist/esm/intlayerPreloadPlugin.mjs.map +1 -0
- package/dist/esm/intlayerProxyHandler.mjs +449 -0
- package/dist/esm/intlayerProxyHandler.mjs.map +1 -0
- package/dist/esm/intlayerProxyPlugin.mjs +10 -406
- package/dist/esm/intlayerProxyPlugin.mjs.map +1 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/intlayerChunkPlugin.d.ts +88 -0
- package/dist/types/intlayerChunkPlugin.d.ts.map +1 -0
- package/dist/types/intlayerNitroHandler.d.ts +1 -1
- package/dist/types/intlayerNitroHandler.d.ts.map +1 -1
- package/dist/types/intlayerPlugin.d.ts.map +1 -1
- package/dist/types/intlayerPreloadPlugin.d.ts +34 -0
- package/dist/types/intlayerPreloadPlugin.d.ts.map +1 -0
- package/dist/types/intlayerProxyHandler.d.ts +50 -0
- package/dist/types/intlayerProxyHandler.d.ts.map +1 -0
- package/dist/types/intlayerProxyPlugin.d.ts +4 -11
- package/dist/types/intlayerProxyPlugin.d.ts.map +1 -1
- package/package.json +8 -8
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { createPrimaryInstanceGuard } from "./dedupePlugin.mjs";
|
|
2
|
+
import { createProxyHandler } from "./intlayerProxyHandler.mjs";
|
|
2
3
|
import { getAppLogger } from "@intlayer/config/logger";
|
|
3
4
|
import { getConfiguration } from "@intlayer/config/node";
|
|
4
|
-
import { formatProxyEnabledMessage,
|
|
5
|
-
import {
|
|
6
|
-
import { fileURLToPath, parse } from "node:url";
|
|
7
|
-
import { getCookie, getLocaleFromStorageServer, setLocaleInStorageServer } from "@intlayer/core/utils";
|
|
5
|
+
import { formatProxyEnabledMessage, isProxyStorageLocaleEnabled, resolveProxyMode } from "@intlayer/core/localization";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
8
7
|
|
|
9
8
|
//#region src/intlayerProxyPlugin.ts
|
|
10
9
|
const PROXY_PLUGIN_NAME = "vite-intlayer-middleware-plugin";
|
|
@@ -15,40 +14,10 @@ const PROXY_PLUGIN_NAME = "vite-intlayer-middleware-plugin";
|
|
|
15
14
|
*/
|
|
16
15
|
const NITRO_PREVIEW_PLUGIN_NAME = "nitro:preview";
|
|
17
16
|
/**
|
|
18
|
-
* Header Nitro's prerenderer sets on every request it issues to the server it
|
|
19
|
-
* is generating pages from. Its value is the route being generated.
|
|
20
|
-
*/
|
|
21
|
-
const NITRO_PRERENDER_HEADER = "x-nitro-prerender";
|
|
22
|
-
/**
|
|
23
|
-
* Environment flag TanStack Start sets on the build process while it prerenders
|
|
24
|
-
* pages through a Vite preview server. The preview server — and therefore this
|
|
25
|
-
* middleware — runs in that same process, so the flag is readable here.
|
|
26
|
-
*/
|
|
27
|
-
const TANSTACK_PRERENDER_ENV_VAR = "TSS_PRERENDERING";
|
|
28
|
-
/**
|
|
29
|
-
* Detects requests issued by a prerenderer rather than by a real visitor.
|
|
30
|
-
*
|
|
31
|
-
* Prerendered pages are written to disk and then served to every visitor, so
|
|
32
|
-
* their content must depend on the URL alone. Anything client-specific — a
|
|
33
|
-
* locale cookie, a persisted locale on the response — would either be baked
|
|
34
|
-
* into a static file or make the generated page depend on the machine running
|
|
35
|
-
* the build.
|
|
36
|
-
*
|
|
37
|
-
* @param req - The incoming request.
|
|
38
|
-
* @returns `true` when the request comes from a prerender pass.
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```ts
|
|
42
|
-
* isPrerenderRequest({ headers: { 'x-nitro-prerender': '/about' } }); // true
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
const isPrerenderRequest = (req) => Boolean(req.headers[NITRO_PRERENDER_HEADER]) || process.env[TANSTACK_PRERENDER_ENV_VAR] === "true";
|
|
46
|
-
/**
|
|
47
17
|
* Creates a standalone, framework-agnostic locale-routing middleware.
|
|
48
18
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* used in every environment:
|
|
19
|
+
* It loads the Intlayer configuration and hands it to the runtime handler in
|
|
20
|
+
* `intlayerProxyHandler`, so it can be used in every environment:
|
|
52
21
|
*
|
|
53
22
|
* - **Dev**: wired up automatically by `intlayerProxy` via `configureServer`
|
|
54
23
|
* - **Preview**: wired up automatically by `intlayerProxy` via `configurePreviewServer`
|
|
@@ -65,377 +34,12 @@ const isPrerenderRequest = (req) => Boolean(req.headers[NITRO_PRERENDER_HEADER])
|
|
|
65
34
|
*
|
|
66
35
|
* @param options - Plugin-specific options, such as path ignoring and Intlayer configuration overrides.
|
|
67
36
|
* @returns A Connect-compatible `(req, res, next) => void` middleware.
|
|
68
|
-
*
|
|
69
37
|
*/
|
|
70
|
-
const createIntlayerProxyHandler = (options) => {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const canUseStorageLocale = isProxyStorageLocaleEnabled(resolveProxyMode(enableProxy), isDevServer);
|
|
76
|
-
const redirectCounts = /* @__PURE__ */ new Map();
|
|
77
|
-
const MAX_REDIRECTS = 10;
|
|
78
|
-
const REDIRECT_TTL_MS = 2e3;
|
|
79
|
-
const noPrefix = !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "no-prefix") && mode === "no-prefix" || !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && mode === "search-params";
|
|
80
|
-
const prefixDefault = !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "prefix-all") && mode === "prefix-all";
|
|
81
|
-
const rewriteRules = process.env.INTLAYER_ROUTING_REWRITE_RULES !== "false" ? getRewriteRules(rewrite, "url") : void 0;
|
|
82
|
-
/**
|
|
83
|
-
* Extracts the hostname from a request's `Host` header, handling IPv6
|
|
84
|
-
* literals (`[::1]:5173` → `::1`) that a plain `split(':')` would mangle.
|
|
85
|
-
*/
|
|
86
|
-
const getRequestHostname = (req) => {
|
|
87
|
-
const host = req.headers.host ?? "";
|
|
88
|
-
const ipv6Match = host.match(/^\[([^\]]+)\]/);
|
|
89
|
-
if (ipv6Match) return ipv6Match[1];
|
|
90
|
-
return host.split(":")[0] ?? "";
|
|
91
|
-
};
|
|
92
|
-
/**
|
|
93
|
-
* Retrieves the locale from storage (cookies, localStorage, sessionStorage).
|
|
94
|
-
*
|
|
95
|
-
* Returns `undefined` when the stored locale is not allowed to drive locale
|
|
96
|
-
* resolution (auto mode on a dev/preview server, or a prerender pass, whose
|
|
97
|
-
* output must stay URL-driven), which makes every caller fall through to
|
|
98
|
-
* `Accept-Language` detection and then the default locale.
|
|
99
|
-
*/
|
|
100
|
-
const getStorageLocale = (req) => {
|
|
101
|
-
if (!canUseStorageLocale || isPrerenderRequest(req)) return void 0;
|
|
102
|
-
return getLocaleFromStorageServer({ getCookie: (name) => getCookie(name, req.headers.cookie) });
|
|
103
|
-
};
|
|
104
|
-
/**
|
|
105
|
-
* Appends locale to search params when routing mode is 'search-params'.
|
|
106
|
-
*/
|
|
107
|
-
const appendLocaleSearchIfNeeded = (search, locale) => {
|
|
108
|
-
if (process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params" || mode !== "search-params") return search;
|
|
109
|
-
const params = new URLSearchParams(search ?? "");
|
|
110
|
-
params.set("locale", locale);
|
|
111
|
-
return `?${params.toString()}`;
|
|
112
|
-
};
|
|
113
|
-
/**
|
|
114
|
-
* Checks whether a pathname starts with the given locale as a full path
|
|
115
|
-
* segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match
|
|
116
|
-
* unrelated paths like `/friends`, causing wrong prefix stripping and
|
|
117
|
-
* self-redirect loops.
|
|
118
|
-
*/
|
|
119
|
-
const hasLocaleSegmentPrefix = (pathname, locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);
|
|
120
|
-
/**
|
|
121
|
-
* Extracts the locale from the URL pathname if present as the first segment.
|
|
122
|
-
* e.g. if pathname is /en/some/page or /en, checks if "en" is in supportedLocales.
|
|
123
|
-
*/
|
|
124
|
-
const getPathLocale = (pathname) => {
|
|
125
|
-
const firstSegment = pathname.split("/").filter(Boolean)[0];
|
|
126
|
-
if (firstSegment && supportedLocales.includes(firstSegment)) return firstSegment;
|
|
127
|
-
};
|
|
128
|
-
/**
|
|
129
|
-
* Persists the resolved locale onto the outgoing response as a cookie (and
|
|
130
|
-
* header, per `routing.storage`). Only the cookie survives a client redirect,
|
|
131
|
-
* so this is what carries an explicitly-selected locale across a
|
|
132
|
-
* prefix-stripping redirect. Enabled cookie/header targets are resolved by
|
|
133
|
-
* {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.
|
|
134
|
-
*/
|
|
135
|
-
const persistLocaleOnResponse = (res, locale) => {
|
|
136
|
-
setLocaleInStorageServer(locale, {
|
|
137
|
-
setCookieStore: (name, value, attributes) => {
|
|
138
|
-
const parts = [`${name}=${encodeURIComponent(value)}`];
|
|
139
|
-
if (attributes.path) parts.push(`Path=${attributes.path}`);
|
|
140
|
-
if (attributes.domain) parts.push(`Domain=${attributes.domain}`);
|
|
141
|
-
if (typeof attributes.expires === "number") parts.push(`Expires=${new Date(attributes.expires).toUTCString()}`);
|
|
142
|
-
if (attributes.secure) parts.push("Secure");
|
|
143
|
-
if (attributes.httpOnly) parts.push("HttpOnly");
|
|
144
|
-
if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite}`);
|
|
145
|
-
const cookieString = parts.join("; ");
|
|
146
|
-
const existing = res.getHeader("Set-Cookie");
|
|
147
|
-
const cookies = Array.isArray(existing) ? existing.map(String) : existing !== void 0 ? [String(existing)] : [];
|
|
148
|
-
cookies.push(cookieString);
|
|
149
|
-
res.setHeader("Set-Cookie", cookies);
|
|
150
|
-
},
|
|
151
|
-
setHeader: (name, value) => {
|
|
152
|
-
res.setHeader(name, value);
|
|
153
|
-
}
|
|
154
|
-
});
|
|
155
|
-
};
|
|
156
|
-
/**
|
|
157
|
-
* Identifies the client issuing a request, so redirect-loop tracking is
|
|
158
|
-
* scoped per client. Without this, concurrent visitors hitting the same
|
|
159
|
-
* legitimate redirect (e.g. `/` → `/fr/`) would share one counter and trip
|
|
160
|
-
* the loop detector under normal production traffic.
|
|
161
|
-
*/
|
|
162
|
-
const getClientKey = (req) => {
|
|
163
|
-
const forwardedFor = req.headers["x-forwarded-for"];
|
|
164
|
-
return (Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor)?.split(",")[0]?.trim() || req.socket?.remoteAddress || "unknown";
|
|
165
|
-
};
|
|
166
|
-
/**
|
|
167
|
-
* Strips any origin from a redirect target, keeping only path, search and
|
|
168
|
-
* hash. Prevents open redirects: user-controlled paths like `//evil.com/x`
|
|
169
|
-
* would otherwise be echoed verbatim into the `Location` header and be
|
|
170
|
-
* interpreted by browsers as a protocol-relative cross-origin URL.
|
|
171
|
-
*/
|
|
172
|
-
const toSameOriginUrl = (url) => {
|
|
173
|
-
try {
|
|
174
|
-
const parsed = new URL(url, "http://intlayer-internal");
|
|
175
|
-
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
|
176
|
-
} catch {
|
|
177
|
-
return url;
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
/**
|
|
181
|
-
* Writes a redirect response with the given new URL.
|
|
182
|
-
*/
|
|
183
|
-
const redirectUrl = (req, res, newUrl, options) => {
|
|
184
|
-
const { reason, originalUrl, persistLocale, status = 302, allowCrossOrigin = false } = options ?? {};
|
|
185
|
-
const targetUrl = allowCrossOrigin ? newUrl : toSameOriginUrl(newUrl);
|
|
186
|
-
if (originalUrl) {
|
|
187
|
-
if (originalUrl === targetUrl) {
|
|
188
|
-
console.error("[REDIRECT LOOP DETECTED!]", {
|
|
189
|
-
originalUrl,
|
|
190
|
-
reason
|
|
191
|
-
});
|
|
192
|
-
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
193
|
-
return res.end(`Redirect loop detected: ${originalUrl} redirects to itself`);
|
|
194
|
-
}
|
|
195
|
-
const now = Date.now();
|
|
196
|
-
const trackingKey = `${getClientKey(req)}|${originalUrl} -> ${targetUrl}`;
|
|
197
|
-
const previousEntry = redirectCounts.get(trackingKey);
|
|
198
|
-
const count = previousEntry && now - previousEntry.lastSeen < REDIRECT_TTL_MS ? previousEntry.count + 1 : 1;
|
|
199
|
-
redirectCounts.set(trackingKey, {
|
|
200
|
-
count,
|
|
201
|
-
lastSeen: now
|
|
202
|
-
});
|
|
203
|
-
if (count > MAX_REDIRECTS) {
|
|
204
|
-
console.error("[REDIRECT LOOP DETECTED!]", {
|
|
205
|
-
originalUrl,
|
|
206
|
-
redirectCount: count,
|
|
207
|
-
lastRedirectTo: targetUrl,
|
|
208
|
-
reason
|
|
209
|
-
});
|
|
210
|
-
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
211
|
-
return res.end(`Redirect loop detected: ${count} redirects from ${originalUrl}`);
|
|
212
|
-
}
|
|
213
|
-
for (const [entryKey, entry] of redirectCounts) if (now - entry.lastSeen >= REDIRECT_TTL_MS) redirectCounts.delete(entryKey);
|
|
214
|
-
}
|
|
215
|
-
if (persistLocale && !isPrerenderRequest(req)) persistLocaleOnResponse(res, persistLocale);
|
|
216
|
-
res.writeHead(status, { Location: targetUrl });
|
|
217
|
-
return res.end();
|
|
218
|
-
};
|
|
219
|
-
/**
|
|
220
|
-
* "Rewrite" the request internally by adjusting req.url.
|
|
221
|
-
* Also sets the locale in the response/request headers via storage to mimic
|
|
222
|
-
* Next.js's behaviour of propagating the detected locale downstream.
|
|
223
|
-
*/
|
|
224
|
-
const rewriteUrl = (req, res, newUrl, locale) => {
|
|
225
|
-
if (req.url !== newUrl) req.url = newUrl;
|
|
226
|
-
if (locale) setLocaleInStorageServer(locale, { setHeader: (name, value) => {
|
|
227
|
-
res.setHeader(name, value);
|
|
228
|
-
req.headers[name] = value;
|
|
229
|
-
} });
|
|
230
|
-
};
|
|
231
|
-
/**
|
|
232
|
-
* Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.
|
|
233
|
-
* - basePath: (e.g. '/myapp')
|
|
234
|
-
* - locale: (e.g. 'en')
|
|
235
|
-
* - currentPath: (e.g. '/products/shoes')
|
|
236
|
-
* - search: (e.g. '?foo=bar')
|
|
237
|
-
*/
|
|
238
|
-
const constructPath = (locale, currentPath, search) => {
|
|
239
|
-
const pathWithoutPrefix = hasLocaleSegmentPrefix(currentPath, locale) ? currentPath.slice(`/${locale}`.length) : currentPath;
|
|
240
|
-
const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
|
|
241
|
-
const normalizedBasePath = cleanBasePath.endsWith("/") ? cleanBasePath.slice(0, -1) : cleanBasePath;
|
|
242
|
-
if (!(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "no-prefix") && mode === "no-prefix" || !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && mode === "search-params") return search ? `${pathWithoutPrefix || "/"}${search}` : pathWithoutPrefix || "/";
|
|
243
|
-
let newPath = `${normalizedBasePath}${hasLocaleSegmentPrefix(currentPath, locale) ? currentPath : `/${locale}${currentPath}`}`;
|
|
244
|
-
if (!prefixDefault && locale === defaultLocale) newPath = `${normalizedBasePath}${pathWithoutPrefix || "/"}`;
|
|
245
|
-
if (newPath.length > 1 && newPath.endsWith("/")) newPath = newPath.slice(0, -1);
|
|
246
|
-
if (search) newPath += search;
|
|
247
|
-
return newPath;
|
|
248
|
-
};
|
|
249
|
-
/**
|
|
250
|
-
* If `noPrefix` is true, we never prefix the locale in the URL.
|
|
251
|
-
* We simply rewrite the request to the same path, but with the best-chosen locale
|
|
252
|
-
* in a header or search params if desired.
|
|
253
|
-
*/
|
|
254
|
-
const handleNoPrefix = ({ req, res, next, originalPath, searchParams, storageLocale, originalUrl }) => {
|
|
255
|
-
const pathLocale = getPathLocale(originalPath);
|
|
256
|
-
let locale = storageLocale ?? defaultLocale;
|
|
257
|
-
if (!storageLocale) locale = localeDetector(req.headers, supportedLocales, defaultLocale);
|
|
258
|
-
if (!supportedLocales.includes(locale)) locale = defaultLocale;
|
|
259
|
-
if (pathLocale) {
|
|
260
|
-
const pathWithoutLocale = originalPath.slice(`/${pathLocale}`.length) || "/";
|
|
261
|
-
const canonicalPath = getCanonicalPath(pathWithoutLocale, pathLocale, rewriteRules);
|
|
262
|
-
const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);
|
|
263
|
-
const redirectPath = search ? `${canonicalPath}${search}` : `${canonicalPath}${searchParams ?? ""}`;
|
|
264
|
-
return redirectUrl(req, res, redirectPath, {
|
|
265
|
-
originalUrl,
|
|
266
|
-
persistLocale: pathLocale
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);
|
|
270
|
-
if (!(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && mode === "search-params") {
|
|
271
|
-
if (new URLSearchParams(searchParams ?? "").get("locale") === locale) {
|
|
272
|
-
const rewritePath = `${getInternalPath(canonicalPath, locale)}${searchParams ?? ""}`;
|
|
273
|
-
rewriteUrl(req, res, rewritePath, locale);
|
|
274
|
-
return next();
|
|
275
|
-
}
|
|
276
|
-
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
277
|
-
const redirectPath = search ? `${originalPath}${search}` : `${originalPath}${searchParams ?? ""}`;
|
|
278
|
-
return redirectUrl(req, res, redirectPath, { originalUrl });
|
|
279
|
-
}
|
|
280
|
-
const internalPath = getInternalPath(canonicalPath, locale);
|
|
281
|
-
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
282
|
-
const rewritePath = search ? `${internalPath}${search}` : `${internalPath}${searchParams ?? ""}`;
|
|
283
|
-
rewriteUrl(req, res, rewritePath, locale);
|
|
284
|
-
return next();
|
|
285
|
-
};
|
|
286
|
-
/**
|
|
287
|
-
* The main prefix logic.
|
|
288
|
-
*/
|
|
289
|
-
const handlePrefix = ({ req, res, next, originalPath, searchParams, pathLocale, storageLocale, originalUrl }) => {
|
|
290
|
-
if (!pathLocale) {
|
|
291
|
-
handleMissingPathLocale({
|
|
292
|
-
req,
|
|
293
|
-
res,
|
|
294
|
-
next,
|
|
295
|
-
originalPath,
|
|
296
|
-
searchParams,
|
|
297
|
-
storageLocale,
|
|
298
|
-
originalUrl
|
|
299
|
-
});
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
|
-
handleExistingPathLocale({
|
|
303
|
-
req,
|
|
304
|
-
res,
|
|
305
|
-
next,
|
|
306
|
-
originalPath,
|
|
307
|
-
searchParams,
|
|
308
|
-
pathLocale,
|
|
309
|
-
originalUrl
|
|
310
|
-
});
|
|
311
|
-
};
|
|
312
|
-
/**
|
|
313
|
-
* Handles requests where the locale is missing from the URL pathname.
|
|
314
|
-
* Detects a locale from storage / headers / default, then either redirects or rewrites.
|
|
315
|
-
*/
|
|
316
|
-
const handleMissingPathLocale = ({ req, res, next, originalPath, searchParams, storageLocale, originalUrl }) => {
|
|
317
|
-
let locale = storageLocale ?? localeDetector(req.headers, supportedLocales, defaultLocale);
|
|
318
|
-
if (!supportedLocales.includes(locale)) locale = defaultLocale;
|
|
319
|
-
const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);
|
|
320
|
-
const targetLocalizedPathResult = getLocalizedPath(canonicalPath, locale, rewriteRules);
|
|
321
|
-
const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
|
|
322
|
-
const search = appendLocaleSearchIfNeeded(searchParams, locale);
|
|
323
|
-
const newPath = constructPath(locale, targetLocalizedPath, search);
|
|
324
|
-
if (prefixDefault || locale !== defaultLocale) return redirectUrl(req, res, newPath, { originalUrl });
|
|
325
|
-
rewriteUrl(req, res, `${canonicalPath}${searchParams}`, locale);
|
|
326
|
-
return next();
|
|
327
|
-
};
|
|
328
|
-
/**
|
|
329
|
-
* Handles requests where the locale prefix is present in the pathname.
|
|
330
|
-
*/
|
|
331
|
-
const handleExistingPathLocale = ({ req, res, next, originalPath, searchParams, pathLocale, originalUrl }) => {
|
|
332
|
-
const rawPath = originalPath.slice(`/${pathLocale}`.length) || "/";
|
|
333
|
-
const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);
|
|
334
|
-
if (canonicalPath !== rawPath) {
|
|
335
|
-
const newPath = searchParams ? `${originalPath}${searchParams}` : originalPath;
|
|
336
|
-
rewriteUrl(req, res, newPath, pathLocale);
|
|
337
|
-
return next();
|
|
338
|
-
}
|
|
339
|
-
handleDefaultLocaleRedirect({
|
|
340
|
-
req,
|
|
341
|
-
res,
|
|
342
|
-
next,
|
|
343
|
-
searchParams,
|
|
344
|
-
pathLocale,
|
|
345
|
-
canonicalPath,
|
|
346
|
-
originalUrl
|
|
347
|
-
});
|
|
348
|
-
};
|
|
349
|
-
/**
|
|
350
|
-
* If the path locale is the default locale but we don't want to prefix the default, remove it.
|
|
351
|
-
*/
|
|
352
|
-
const handleDefaultLocaleRedirect = ({ req, res, next, searchParams, pathLocale, canonicalPath, originalUrl }) => {
|
|
353
|
-
if (!prefixDefault && pathLocale === defaultLocale) {
|
|
354
|
-
const targetLocalizedPathResult = getLocalizedPath(canonicalPath, pathLocale, rewriteRules);
|
|
355
|
-
const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
|
|
356
|
-
const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
|
|
357
|
-
const normalizedBasePath = cleanBasePath.endsWith("/") ? cleanBasePath.slice(0, -1) : cleanBasePath;
|
|
358
|
-
let finalPath = targetLocalizedPath;
|
|
359
|
-
if (finalPath.startsWith("/")) finalPath = finalPath.slice(1);
|
|
360
|
-
const fullPath = `${normalizedBasePath}/${finalPath}`.replace(/\/+/g, "/");
|
|
361
|
-
return redirectUrl(req, res, fullPath + (searchParams ?? ""), {
|
|
362
|
-
originalUrl,
|
|
363
|
-
persistLocale: pathLocale
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
const internalUrl = getInternalPath(canonicalPath, pathLocale);
|
|
367
|
-
const newPath = searchParams ? `${internalUrl}${searchParams}` : internalUrl;
|
|
368
|
-
rewriteUrl(req, res, newPath, pathLocale);
|
|
369
|
-
return next();
|
|
370
|
-
};
|
|
371
|
-
return (req, res, next) => {
|
|
372
|
-
const parsedUrl = parse(req.url ?? "/", true);
|
|
373
|
-
const originalPath = parsedUrl.pathname ?? "/";
|
|
374
|
-
const searchParams = parsedUrl.search ?? "";
|
|
375
|
-
const pathLocale = getPathLocale(originalPath);
|
|
376
|
-
if ((ignore?.(req) ?? false) || originalPath.startsWith("/node_modules") || originalPath.startsWith("/@") || originalPath.startsWith("/_")) return next();
|
|
377
|
-
if (originalPath.match(/\.[a-zA-Z0-9]+$/)) {
|
|
378
|
-
if (pathLocale) req.url = `${originalPath.slice(`/${pathLocale}`.length) || "/"}${searchParams}`;
|
|
379
|
-
return next();
|
|
380
|
-
}
|
|
381
|
-
const storageLocale = getStorageLocale(req);
|
|
382
|
-
const effectiveStorageLocale = pathLocale && supportedLocales.includes(pathLocale) ? pathLocale : storageLocale;
|
|
383
|
-
const originalUrl = req.url;
|
|
384
|
-
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && !noPrefix && pathLocale && domains) {
|
|
385
|
-
const localeDomain = domains[pathLocale];
|
|
386
|
-
if (localeDomain) {
|
|
387
|
-
const reqHost = getRequestHostname(req);
|
|
388
|
-
if (getDomainHostname(localeDomain) !== reqHost) {
|
|
389
|
-
const rawPath = originalPath.slice(`/${pathLocale}`.length) || "/";
|
|
390
|
-
const targetOrigin = getDomainOrigin(localeDomain);
|
|
391
|
-
redirectUrl(req, res, `${targetOrigin}${rawPath}${searchParams}`, {
|
|
392
|
-
reason: "domain-routing",
|
|
393
|
-
originalUrl,
|
|
394
|
-
status: 301,
|
|
395
|
-
allowCrossOrigin: true
|
|
396
|
-
});
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && !noPrefix && !pathLocale) {
|
|
402
|
-
const reqHost = getRequestHostname(req);
|
|
403
|
-
const domainLocale = getLocaleFromDomain(reqHost, domains);
|
|
404
|
-
if (domainLocale) {
|
|
405
|
-
const canonicalPath = getCanonicalPath(originalPath, domainLocale, rewriteRules);
|
|
406
|
-
if (!prefixDefault && domainLocale === defaultLocale) {
|
|
407
|
-
rewriteUrl(req, res, `${canonicalPath}${searchParams}`, domainLocale);
|
|
408
|
-
return next();
|
|
409
|
-
}
|
|
410
|
-
const internalPath = getInternalPath(canonicalPath, domainLocale);
|
|
411
|
-
rewriteUrl(req, res, searchParams ? `${internalPath}${searchParams}` : internalPath, domainLocale);
|
|
412
|
-
return next();
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
if (noPrefix) {
|
|
416
|
-
handleNoPrefix({
|
|
417
|
-
req,
|
|
418
|
-
res,
|
|
419
|
-
next,
|
|
420
|
-
originalPath,
|
|
421
|
-
searchParams,
|
|
422
|
-
storageLocale: effectiveStorageLocale,
|
|
423
|
-
originalUrl
|
|
424
|
-
});
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
handlePrefix({
|
|
428
|
-
req,
|
|
429
|
-
res,
|
|
430
|
-
next,
|
|
431
|
-
originalPath,
|
|
432
|
-
searchParams,
|
|
433
|
-
pathLocale,
|
|
434
|
-
storageLocale: effectiveStorageLocale,
|
|
435
|
-
originalUrl
|
|
436
|
-
});
|
|
437
|
-
};
|
|
438
|
-
};
|
|
38
|
+
const createIntlayerProxyHandler = (options) => createProxyHandler({
|
|
39
|
+
configuration: getConfiguration(options?.configOptions),
|
|
40
|
+
ignore: options?.ignore,
|
|
41
|
+
isDevServer: options?.isDevServer ?? false
|
|
42
|
+
});
|
|
439
43
|
/**
|
|
440
44
|
* Vite plugin that provides locale-based routing middleware for **all environments**:
|
|
441
45
|
* development, preview, and production SSR (Nitro / TanStack Start).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { fileURLToPath, parse } from 'node:url';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n formatProxyEnabledMessage,\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getInternalPath,\n getLocaleFromDomain,\n getLocalizedPath,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport {\n getCookie,\n getLocaleFromStorageServer,\n setLocaleInStorageServer,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\nimport { createPrimaryInstanceGuard } from './dedupePlugin';\n\nconst PROXY_PLUGIN_NAME = 'vite-intlayer-middleware-plugin';\n\n/**\n * Name of the Vite plugin `nitro/vite` registers in preview mode. It mounts the\n * built Nitro server — which already carries the Intlayer proxy as a Nitro\n * middleware — inside the Vite preview server.\n */\nconst NITRO_PREVIEW_PLUGIN_NAME = 'nitro:preview';\n\n/**\n * Header Nitro's prerenderer sets on every request it issues to the server it\n * is generating pages from. Its value is the route being generated.\n */\nconst NITRO_PRERENDER_HEADER = 'x-nitro-prerender';\n\n/**\n * Environment flag TanStack Start sets on the build process while it prerenders\n * pages through a Vite preview server. The preview server — and therefore this\n * middleware — runs in that same process, so the flag is readable here.\n */\nconst TANSTACK_PRERENDER_ENV_VAR = 'TSS_PRERENDERING';\n\n/**\n * Detects requests issued by a prerenderer rather than by a real visitor.\n *\n * Prerendered pages are written to disk and then served to every visitor, so\n * their content must depend on the URL alone. Anything client-specific — a\n * locale cookie, a persisted locale on the response — would either be baked\n * into a static file or make the generated page depend on the machine running\n * the build.\n *\n * @param req - The incoming request.\n * @returns `true` when the request comes from a prerender pass.\n *\n * @example\n * ```ts\n * isPrerenderRequest({ headers: { 'x-nitro-prerender': '/about' } }); // true\n * ```\n */\nconst isPrerenderRequest = (req: IncomingMessage): boolean =>\n Boolean(req.headers[NITRO_PRERENDER_HEADER]) ||\n process.env[TANSTACK_PRERENDER_ENV_VAR] === 'true';\n\nexport type IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxy({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n /**\n * Optional Intlayer configuration overrides forwarded to `getConfiguration`.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxy({ configOptions: { override: { ... } } }) ],\n * });\n * ```\n */\n configOptions?: GetConfigurationOptions;\n /**\n * Whether a development or preview server is serving the app.\n *\n * Set internally by the plugin from `configureServer` /\n * `configurePreviewServer`. It only matters in the proxy's auto mode, where\n * a dev server keeps locale routing URL-driven by ignoring the stored locale\n * as a redirect source.\n *\n * Defaults to `false` so that mounting `createIntlayerProxyHandler()`\n * manually — the documented production Nitro setup — keeps full behaviour.\n *\n * @default false\n */\n isDevServer?: boolean;\n};\n\n/**\n * A Node.js-compatible Connect middleware function.\n * Compatible with Vite dev/preview server, Node.js http, Express, and h3's\n * `fromNodeMiddleware` wrapper for Nitro/TanStack Start production use.\n */\ntype NodeMiddleware = (\n req: IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n next: () => void\n) => void;\n\n/**\n * Creates a standalone, framework-agnostic locale-routing middleware.\n *\n * This function contains all the locale detection, redirect, and rewrite logic.\n * It is intentionally separated from the Vite plugin so the same handler can be\n * used in every environment:\n *\n * - **Dev**: wired up automatically by `intlayerProxy` via `configureServer`\n * - **Preview**: wired up automatically by `intlayerProxy` via `configurePreviewServer`\n * - **Production (Nitro / TanStack Start)**: create `server/middleware/intlayerProxy.ts`:\n *\n * @example\n * ```ts\n * // server/middleware/intlayerProxy.ts\n * import { fromNodeMiddleware } from 'h3';\n * import { createIntlayerProxyHandler } from 'vite-intlayer';\n *\n * export default fromNodeMiddleware(createIntlayerProxyHandler());\n * ```\n *\n * @param options - Plugin-specific options, such as path ignoring and Intlayer configuration overrides.\n * @returns A Connect-compatible `(req, res, next) => void` middleware.\n *\n */\nexport const createIntlayerProxyHandler = (\n options?: IntlayerProxyPluginOptions\n): NodeMiddleware => {\n const { ignore, configOptions, isDevServer = false } = options ?? {};\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = routing;\n\n // In auto mode a dev/preview server ignores the stored locale when resolving\n // which locale a request maps to, so a lingering cookie cannot keep pulling\n // navigation to another locale while developing. Prefix redirects, locale\n // persistence and `Accept-Language` detection are unaffected.\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n resolveProxyMode(enableProxy),\n isDevServer\n );\n\n type RedirectCounter = { count: number; lastSeen: number };\n const redirectCounts = new Map<string, RedirectCounter>();\n const MAX_REDIRECTS = 10;\n const REDIRECT_TTL_MS = 2_000;\n\n // Derived flags from routing.mode\n const noPrefix =\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n mode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n mode === 'search-params');\n const prefixDefault =\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all'\n ) && mode === 'prefix-all';\n\n const rewriteRules =\n process.env.INTLAYER_ROUTING_REWRITE_RULES !== 'false'\n ? getRewriteRules(rewrite, 'url')\n : undefined;\n\n /**\n * Extracts the hostname from a request's `Host` header, handling IPv6\n * literals (`[::1]:5173` → `::1`) that a plain `split(':')` would mangle.\n */\n const getRequestHostname = (req: IncomingMessage): string => {\n const host = req.headers.host ?? '';\n const ipv6Match = host.match(/^\\[([^\\]]+)\\]/);\n if (ipv6Match) return ipv6Match[1]!;\n return host.split(':')[0] ?? '';\n };\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n *\n * Returns `undefined` when the stored locale is not allowed to drive locale\n * resolution (auto mode on a dev/preview server, or a prerender pass, whose\n * output must stay URL-driven), which makes every caller fall through to\n * `Accept-Language` detection and then the default locale.\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n if (!canUseStorageLocale || isPrerenderRequest(req)) return undefined;\n\n const locale = getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(name, req.headers.cookie),\n });\n return locale;\n };\n\n /**\n * Appends locale to search params when routing mode is 'search-params'.\n */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (\n (process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params') ||\n mode !== 'search-params'\n )\n return search;\n\n const params = new URLSearchParams(search ?? '');\n\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Checks whether a pathname starts with the given locale as a full path\n * segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match\n * unrelated paths like `/friends`, causing wrong prefix stripping and\n * self-redirect loops.\n */\n const hasLocaleSegmentPrefix = (pathname: string, locale: Locale): boolean =>\n pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);\n\n /**\n * Extracts the locale from the URL pathname if present as the first segment.\n * e.g. if pathname is /en/some/page or /en, checks if \"en\" is in supportedLocales.\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\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 * Persists the resolved locale onto the outgoing response as a cookie (and\n * header, per `routing.storage`). Only the cookie survives a client redirect,\n * so this is what carries an explicitly-selected locale across a\n * prefix-stripping redirect. Enabled cookie/header targets are resolved by\n * {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.\n */\n const persistLocaleOnResponse = (\n res: ServerResponse<IncomingMessage>,\n locale: Locale\n ) => {\n setLocaleInStorageServer(locale, {\n setCookieStore: (name, value, attributes) => {\n const parts: string[] = [`${name}=${encodeURIComponent(value)}`];\n if (attributes.path) parts.push(`Path=${attributes.path}`);\n if (attributes.domain) parts.push(`Domain=${attributes.domain}`);\n if (typeof attributes.expires === 'number')\n parts.push(`Expires=${new Date(attributes.expires).toUTCString()}`);\n if (attributes.secure) parts.push('Secure');\n if (attributes.httpOnly) parts.push('HttpOnly');\n if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite}`);\n\n const cookieString = parts.join('; ');\n const existing = res.getHeader('Set-Cookie');\n const cookies = Array.isArray(existing)\n ? existing.map(String)\n : existing !== undefined\n ? [String(existing)]\n : [];\n cookies.push(cookieString);\n res.setHeader('Set-Cookie', cookies);\n },\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n },\n });\n };\n\n /**\n * Identifies the client issuing a request, so redirect-loop tracking is\n * scoped per client. Without this, concurrent visitors hitting the same\n * legitimate redirect (e.g. `/` → `/fr/`) would share one counter and trip\n * the loop detector under normal production traffic.\n */\n const getClientKey = (req: IncomingMessage): string => {\n const forwardedFor = req.headers['x-forwarded-for'];\n const forwardedIp = (\n Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor\n )\n ?.split(',')[0]\n ?.trim();\n\n return forwardedIp || req.socket?.remoteAddress || 'unknown';\n };\n\n /**\n * Strips any origin from a redirect target, keeping only path, search and\n * hash. Prevents open redirects: user-controlled paths like `//evil.com/x`\n * would otherwise be echoed verbatim into the `Location` header and be\n * interpreted by browsers as a protocol-relative cross-origin URL.\n */\n const toSameOriginUrl = (url: string): string => {\n try {\n const parsed = new URL(url, 'http://intlayer-internal');\n return `${parsed.pathname}${parsed.search}${parsed.hash}`;\n } catch {\n return url;\n }\n };\n\n type RedirectOptions = {\n /** Human-readable reason logged when a redirect loop is detected. */\n reason?: string;\n /** The URL of the incoming request, used for redirect-loop tracking. */\n originalUrl?: string;\n /**\n * When provided, the locale is persisted (cookie/header, per config) on\n * the redirect response so the follow-up request resolves the same locale.\n */\n persistLocale?: Locale;\n /**\n * HTTP status for the redirect. Defaults to 302: locale redirects depend\n * on mutable state (cookie, Accept-Language) and must not be cached by\n * the browser as permanent. Domain-routing redirects pass 301 explicitly.\n */\n status?: number;\n /**\n * Allows a cross-origin `Location` target. Only the domain-routing\n * redirect sets this; all other targets are sanitized to same-origin.\n */\n allowCrossOrigin?: boolean;\n };\n\n /**\n * Writes a redirect response with the given new URL.\n */\n const redirectUrl = (\n req: IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n options?: RedirectOptions\n ) => {\n const {\n reason,\n originalUrl,\n persistLocale,\n status = 302,\n allowCrossOrigin = false,\n } = options ?? {};\n\n const targetUrl = allowCrossOrigin ? newUrl : toSameOriginUrl(newUrl);\n\n if (originalUrl) {\n if (originalUrl === targetUrl) {\n console.error('[REDIRECT LOOP DETECTED!]', { originalUrl, reason });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${originalUrl} redirects to itself`\n );\n }\n\n const now = Date.now();\n const trackingKey = `${getClientKey(req)}|${originalUrl} -> ${targetUrl}`;\n const previousEntry = redirectCounts.get(trackingKey);\n const count =\n previousEntry && now - previousEntry.lastSeen < REDIRECT_TTL_MS\n ? previousEntry.count + 1\n : 1;\n\n redirectCounts.set(trackingKey, { count, lastSeen: now });\n\n if (count > MAX_REDIRECTS) {\n console.error('[REDIRECT LOOP DETECTED!]', {\n originalUrl,\n redirectCount: count,\n lastRedirectTo: targetUrl,\n reason,\n });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${count} redirects from ${originalUrl}`\n );\n }\n\n for (const [entryKey, entry] of redirectCounts) {\n if (now - entry.lastSeen >= REDIRECT_TTL_MS)\n redirectCounts.delete(entryKey);\n }\n }\n\n // A prerendered response is stored as a static file and replayed to every\n // visitor, so persisting the locale on it would hand the locale of the\n // build machine to everyone hitting that page.\n if (persistLocale && !isPrerenderRequest(req)) {\n persistLocaleOnResponse(res, persistLocale);\n }\n\n res.writeHead(status, { Location: targetUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url.\n * Also sets the locale in the response/request headers via storage to mimic\n * Next.js's behaviour of propagating the detected locale downstream.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n if (req.url !== newUrl) {\n req.url = newUrl;\n }\n if (locale) {\n setLocaleInStorageServer(locale, {\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n req.headers[name] = value;\n },\n });\n }\n };\n\n /**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g. '/myapp')\n * - locale: (e.g. 'en')\n * - currentPath: (e.g. '/products/shoes')\n * - search: (e.g. '?foo=bar')\n */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix to avoid double-prefixing\n const pathWithoutPrefix = hasLocaleSegmentPrefix(currentPath, locale)\n ? currentPath.slice(`/${locale}`.length)\n : currentPath;\n\n // Ensure basePath always starts with '/' and has no trailing slash\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n mode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n mode === 'search-params')\n ) {\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 = hasLocaleSegmentPrefix(currentPath, locale)\n ? currentPath\n : `/${locale}${currentPath}`;\n\n let newPath = `${normalizedBasePath}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix || '/'}`;\n }\n\n // Never emit a trailing slash (`/fr/` for the root path): the framework's\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy, creating an infinite redirect loop.\n if (newPath.length > 1 && newPath.endsWith('/')) {\n newPath = newPath.slice(0, -1);\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n };\n\n /* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n /**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\n const handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n const pathLocale = getPathLocale(originalPath);\n\n // Determine the best locale: prefer cookie/storage, fall back to Accept-Language detection\n let locale = storageLocale ?? defaultLocale;\n\n // Use localeDetector if no storage locale is available\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 // Guard against a stale/unsupported locale coming from storage or detection\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${searchParams ?? ''}`;\n\n // Persist the explicitly-requested locale: stripping the prefix drops\n // the only locale signal from the URL, so without this the follow-up\n // request would fall back to cookie / Accept-Language detection and\n // could resolve a different locale.\n return redirectUrl(req, res, redirectPath, {\n originalUrl,\n persistLocale: pathLocale,\n });\n }\n\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // In search-params mode, we need to redirect to add the locale search param\n if (\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n mode === 'search-params'\n ) {\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 (existingLocale === locale) {\n // Rewrite internally — URL stays the same in the browser, but the framework\n // sees /[locale]/path so the [locale] route param is populated correctly.\n // getInternalPath collapses the root path to `/${locale}` — a trailing\n // slash (`/fr/`) would trigger the framework's trailing-slash\n // normalisation redirect and loop with this proxy.\n const internalPath = getInternalPath(canonicalPath, locale);\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match — redirect to add/update it (URL changes in browser)\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n return redirectUrl(req, res, redirectPath, { originalUrl });\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n // so the framework can match the [locale] route param without exposing it in the URL.\n // getInternalPath collapses the root path to `/${locale}` — a trailing slash\n // (`/fr/`) would trigger the framework's trailing-slash normalisation\n // redirect and loop with this proxy.\n const internalPath = getInternalPath(canonicalPath, locale);\n\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 the browser\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n };\n\n /**\n * The main prefix logic.\n */\n const handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n });\n return;\n }\n\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n });\n };\n\n /**\n * Handles requests where the locale is missing from the URL pathname.\n * Detects a locale from storage / headers / default, then either redirects or rewrites.\n */\n const handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // Choose the best locale: cookie/storage → Accept-Language detection → defaultLocale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // If still invalid, fall back to defaultLocale\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), this resolves to /about\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // Determine target localized path for redirection.\n // /about + 'fr' → /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct new path, preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, targetLocalizedPath, search);\n\n // If we always prefix default or if this is not the default locale,\n // do a redirect so the user sees the locale in the URL\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(req, res, newPath, { originalUrl });\n }\n\n // If we do NOT prefix the default locale, pass through the canonical path unchanged.\n // Rewriting to `/${locale}${canonicalPath}` (e.g. /en/) causes TanStack Start to issue a\n // trailing-slash normalisation redirect (/en/ → /en), which the proxy then strips back to /,\n // creating an infinite redirect loop.\n // Because {-$locale} is an optional segment, the framework matches the un-prefixed URL with\n // locale=undefined and falls back to defaultLocale via `params.locale ?? defaultLocale`.\n // searchParams MUST be preserved here — dropping them causes the framework (e.g. TanStack Start) to\n // see a URL with no search params, trigger a validateSearch normalisation redirect to the prefixed URL\n // (e.g. /en?page=1&...), which the middleware then strips back to /?..., creating an infinite loop.\n rewriteUrl(req, res, `${canonicalPath}${searchParams}`, 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 originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n originalUrl?: string;\n }) => {\n const rawPath = originalPath.slice(`/${pathLocale}`.length) || '/';\n\n // Identify the canonical path (internal path).\n // Ex: /a-propos (from URL) → /about (canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // When rewrite rules are configured and the URL is already a valid localized pretty URL\n // (e.g. /fr/essais which maps to canonical /fr/tests), do NOT redirect to canonical.\n //\n // Why: the SPA router (Solid, React Router, Vue Router…) is expected to define routes using\n // the localized paths (e.g. <Route path=\"/essais\">) so the browser URL must stay as-is.\n // A 301 redirect to canonical would:\n // 1. Change the browser URL to the canonical form (/fr/tests)\n // 2. Break subsequent client-side navigation because <A> links produced by getLocalizedUrl\n // point back to the localized URL (/fr/essais) which then has no matching route.\n //\n // We set the locale header and call next() so the server serves the page at the pretty URL.\n if (canonicalPath !== rawPath) {\n const newPath = searchParams\n ? `${originalPath}${searchParams}`\n : originalPath;\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n });\n };\n\n /**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\n const handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n searchParams: string;\n pathLocale: Locale;\n canonicalPath: string;\n originalUrl?: string;\n }) => {\n // If we don't prefix the default locale AND the path locale IS the default → strip the prefix\n if (!prefixDefault && pathLocale === defaultLocale) {\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const cleanBasePath = basePath.startsWith('/')\n ? basePath\n : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${normalizedBasePath}/${finalPath}`.replace(\n /\\/+/g,\n '/'\n );\n\n // Persist the explicitly-requested default locale. Stripping the prefix\n // (e.g. /es → /) drops the only locale signal from the URL, so without\n // this the follow-up request to the canonical path would fall back to\n // Accept-Language detection and could resolve a different locale.\n return redirectUrl(req, res, fullPath + (searchParams ?? ''), {\n originalUrl,\n persistLocale: pathLocale,\n });\n }\n\n // If we do prefix the default or pathLocale !== default, keep as-is\n // but rewrite to canonical internally.\n // Never emit a trailing slash (`/fr/` for the bare `/fr` URL): rewriting\n // `/fr` to `/fr/` makes the framework issue a trailing-slash normalisation\n // redirect back to `/fr`, which this proxy rewrites again — an infinite\n // redirect loop. `getInternalPath` collapses the root path to `/${locale}`.\n const internalUrl = getInternalPath(canonicalPath, pathLocale);\n const newPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n };\n\n return (req, res, next) => {\n // Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // Check if there's a locale prefix in the path FIRST\n const pathLocale = getPathLocale(originalPath);\n\n // Bypass special Vite/server endpoints and node_modules\n if (\n // Custom ignore function\n (ignore?.(req) ?? false) ||\n originalPath.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 originalPath.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n originalPath.startsWith('/_')\n ) {\n return next();\n }\n\n // Static file requests (e.g. /assets/video.mp4): bypass locale routing.\n // If the URL carries a locale prefix (e.g. /fr/assets/video.mp4),\n // rewrite the request internally to the unprefixed path (/assets/video.mp4)\n // so the file can be served correctly from the public directory.\n if (originalPath.match(/\\.[a-zA-Z0-9]+$/)) {\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n req.url = `${pathWithoutLocale}${searchParams}`;\n }\n return next();\n }\n\n // Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // CRITICAL FIX: If there's a valid pathLocale, it takes precedence over storage\n // This prevents race conditions when cookies are stale during locale switches\n const effectiveStorageLocale =\n pathLocale && supportedLocales.includes(pathLocale)\n ? pathLocale\n : storageLocale;\n\n // Store original URL for redirect tracking\n const originalUrl = req.url;\n\n // Domain routing: if the path locale is mapped to a different domain, redirect there.\n // e.g. intlayer.org/zh/about → https://intlayer.zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n !noPrefix &&\n pathLocale &&\n domains\n ) {\n const localeDomain = domains[pathLocale as keyof typeof domains];\n if (localeDomain) {\n const reqHost = getRequestHostname(req);\n const domainHost = getDomainHostname(localeDomain);\n if (domainHost !== reqHost) {\n const rawPath = originalPath.slice(`/${pathLocale}`.length) || '/';\n const targetOrigin = getDomainOrigin(localeDomain);\n // Domain mapping is stable config, so a cacheable 301 is intended\n // here — unlike locale-detection redirects, which use 302.\n redirectUrl(req, res, `${targetOrigin}${rawPath}${searchParams}`, {\n reason: 'domain-routing',\n originalUrl,\n status: 301,\n allowCrossOrigin: true,\n });\n return;\n }\n }\n }\n\n // Domain routing: if the current hostname is exclusively mapped to one locale,\n // treat it as that locale without a URL prefix.\n // e.g. intlayer.zh/about → internally rewrite to /zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n !noPrefix &&\n !pathLocale\n ) {\n const reqHost = getRequestHostname(req);\n const domainLocale = getLocaleFromDomain(reqHost, domains);\n if (domainLocale) {\n const canonicalPath = getCanonicalPath(\n originalPath,\n domainLocale,\n rewriteRules\n );\n\n // Default locale without forced prefixing: pass the canonical path\n // through unchanged, mirroring handleMissingPathLocale. Rewriting `/`\n // to `/en/` makes TanStack Start issue a trailing-slash normalisation\n // redirect (/en/ → /en), whose prefix the proxy then strips back to /,\n // creating an infinite redirect loop.\n if (!prefixDefault && domainLocale === defaultLocale) {\n rewriteUrl(\n req as Connect.IncomingMessage,\n res,\n `${canonicalPath}${searchParams}`,\n domainLocale\n );\n return next();\n }\n\n // Never emit a trailing slash (`/zh/`): the framework would redirect\n // it to `/zh`, which this proxy rewrites to `/zh/` again — a loop.\n const internalPath = getInternalPath(canonicalPath, domainLocale);\n\n rewriteUrl(\n req as Connect.IncomingMessage,\n res,\n searchParams ? `${internalPath}${searchParams}` : internalPath,\n domainLocale\n );\n return next();\n }\n }\n\n if (noPrefix) {\n handleNoPrefix({\n req: req as Connect.IncomingMessage,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n return;\n }\n\n handlePrefix({\n req: req as Connect.IncomingMessage,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n };\n};\n\n/**\n * Vite plugin that provides locale-based routing middleware for **all environments**:\n * development, preview, and production SSR (Nitro / TanStack Start).\n *\n * - **Dev** (`vite dev`): registered via `configureServer`.\n * - **Preview** (`vite preview`): registered via `configurePreviewServer`.\n * - **Production Nitro** (`vite build`): automatically injected via the `.nitro` module\n * property that `nitro/vite` reads and pushes into `nitroConfig.modules`. The module\n * registers `intlayerNitroHandler` as a Nitro server middleware — no extra user config\n * needed.\n *\n * If you need custom config options or an `ignore` predicate in production, bypass\n * auto-injection and create a server middleware file manually:\n *\n * ```ts\n * // server/middleware/intlayerProxy.ts\n * import { fromNodeMiddleware } from 'h3';\n * import { createIntlayerProxyHandler } from 'vite-intlayer';\n *\n * export default fromNodeMiddleware(\n * createIntlayerProxyHandler({\n * ignore: (req) => req.url?.startsWith('/api'),\n * configOptions: myConfig,\n * })\n * );\n * ```\n *\n * @param options - Plugin-specific options, like ignoring certain paths and Intlayer configuration overrides.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n *\n * @deprecated Since Intlayer v9, `intlayerProxy()` is bundled directly into the `intlayer()` plugin and enabled by default through the `routing.enableProxy` option (unset by default, which selects auto mode). Registering it separately as shown below is now optional.\n */\nexport const intlayerProxy = (options?: IntlayerProxyPluginOptions): Plugin => {\n // Dev and preview servers run the same handler; both are \"dev servers\" as far\n // as auto mode is concerned, so a single instance covers both hooks.\n const handler = createIntlayerProxyHandler({ ...options, isDevServer: true });\n const intlayerConfig = getConfiguration(options?.configOptions);\n const logger = getAppLogger(intlayerConfig);\n\n // Both hooks below serve a dev or preview server, hence the hard-coded true.\n const isStorageLocaleSuppressed = !isProxyStorageLocaleEnabled(\n resolveProxyMode(intlayerConfig.routing.enableProxy),\n true\n );\n\n /**\n * Logs that the proxy is serving requests, spelling out when auto mode has\n * suppressed the stored locale so the reported state matches the behaviour.\n */\n const logProxyEnabled = () =>\n logger(formatProxyEnabledMessage(isStorageLocaleSuppressed), {\n level: 'info',\n });\n\n // Ensures the proxy registers its middleware only once, even when it is\n // registered both via `intlayer()` (which now bundles it) and a manual\n // `intlayerProxy()` call.\n const guard = createPrimaryInstanceGuard(PROXY_PLUGIN_NAME);\n\n // Set during `configResolved`: `nitro/vite` serves the *built* Nitro server\n // from inside the preview server, and that build already carries the proxy as\n // a Nitro middleware (see `nitroModule` below).\n let isNitroServingPreview = false;\n\n /**\n * Nitro module injected automatically by `nitro/vite`.\n *\n * When a Vite plugin carries a `.nitro` property, `nitro/vite` pushes it into\n * `nitroConfig.modules` during the build phase. The module's `setup` hook adds\n * our locale-routing handler to Nitro's server pipeline, making locale detection\n * work in production SSR builds (TanStack Start, Nuxt, etc.) without any extra\n * user configuration.\n *\n * @see https://github.com/nitrojs/nitro (nitro/vite source, line ~402)\n */\n const nitroModule = {\n name: 'intlayer-proxy',\n setup(nitro: {\n options: {\n dev: boolean;\n handlers: {\n route: string;\n handler: string;\n middleware: boolean;\n }[];\n };\n }) {\n // In dev mode, locale routing is already handled by configureServer (Vite dev server).\n // The Nitro dev server uses h3 v2's Web Fetch API event model which is incompatible\n // with fromNodeMiddleware (h3 v1) and would cause double-execution anyway.\n // Only inject for production builds where Nitro is the actual HTTP server.\n if (nitro.options.dev) return;\n\n const handlerPath = fileURLToPath(\n new URL('./intlayerNitroHandler.mjs', import.meta.url)\n );\n\n // Skip if an identical handler was already registered by another instance\n // (e.g. both `intlayer()` and a manual `intlayerProxy()`).\n const alreadyRegistered = nitro.options.handlers.some(\n (existingHandler) => existingHandler.handler === handlerPath\n );\n if (alreadyRegistered) return;\n\n nitro.options.handlers.push({\n route: '/**',\n handler: handlerPath,\n middleware: true,\n });\n },\n };\n\n const plugin = {\n name: PROXY_PLUGIN_NAME,\n // Decide whether this is the primary instance before registering middleware.\n configResolved: (config: { plugins: readonly { name: string }[] }) => {\n guard.resolve(config);\n isNitroServingPreview = config.plugins.some(\n (registeredPlugin) =>\n registeredPlugin.name === NITRO_PREVIEW_PLUGIN_NAME\n );\n },\n // Injected into nitroConfig.modules by the `nitro/vite` plugin so the\n // locale-routing middleware is registered in the production Nitro server.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nitro: nitroModule as any,\n // Vite dev server\n configureServer: (server) => {\n if (!guard.isPrimary) return;\n logProxyEnabled();\n server.middlewares.use(handler);\n },\n // Vite preview server\n configurePreviewServer: (server) => {\n if (!guard.isPrimary) return;\n // With Nitro, the preview server forwards every request to the built\n // Nitro server, whose pipeline already starts with this proxy. Adding a\n // second layer here would run locale resolution twice on the same\n // request: the first pass rewrites `req.url` (and the locale request\n // header), the second pass reads that rewritten URL as if it came from\n // the browser and can redirect it back — the redirect ping-pong that\n // shows up as \"max redirects reached\" while prerendering.\n if (isNitroServingPreview) return;\n logProxyEnabled();\n server.middlewares.use(handler);\n },\n } as Plugin;\n\n // Register the plugin object so the dedupe guard can identify the primary\n // instance by reference during `configResolved`.\n guard.setPlugin(plugin);\n\n return plugin;\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":";;;;;;;;;AA+BA,MAAM,oBAAoB;;;;;;AAO1B,MAAM,4BAA4B;;;;;AAMlC,MAAM,yBAAyB;;;;;;AAO/B,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;AAmBnC,MAAM,sBAAsB,QAC1B,QAAQ,IAAI,QAAQ,uBAAuB,KAC3C,QAAQ,IAAI,gCAAgC;;;;;;;;;;;;;;;;;;;;;;;;;AA+E9C,MAAa,8BACX,YACmB;CACnB,MAAM,EAAE,QAAQ,eAAe,cAAc,UAAU,WAAW,CAAC;CAGnE,MAAM,EAAE,sBAAsB,YAFP,iBAAiB,aAEe;CACvD,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;CAErD,MAAM,EACJ,WAAW,IACX,OAAO,cACP,SACA,S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G,CACvD;IAOA,IAH0B,MAAM,QAAQ,SAAS,MAC9C,oBAAoB,gBAAgB,YAAY,WAE/B,GAAG;IAEvB,MAAM,QAAQ,SAAS,KAAK;KAC1B,OAAO;KACP,SAAS;KACT,YAAY;IACd,CAAC;GACH;EAgBiB;EAEjB,kBAAkB,WAAW;GAC3B,IAAI,CAAC,MAAM,WAAW;GACtB,gBAAgB;GAChB,OAAO,YAAY,IAAI,OAAO;EAChC;EAEA,yBAAyB,WAAW;GAClC,IAAI,CAAC,MAAM,WAAW;GAQtB,IAAI,uBAAuB;GAC3B,gBAAgB;GAChB,OAAO,YAAY,IAAI,OAAO;EAChC;CACF;CAIA,MAAM,UAAU,MAAM;CAEtB,OAAO;AACT;;;;;;;;;;;;;AAcA,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,MAAa,2BAA2B"}
|
|
1
|
+
{"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\nimport { fileURLToPath } from 'node:url';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n formatProxyEnabledMessage,\n isProxyStorageLocaleEnabled,\n resolveProxyMode,\n} from '@intlayer/core/localization';\n/* @ts-ignore - Vite types error */\nimport type { Plugin } from 'vite';\nimport { createPrimaryInstanceGuard } from './dedupePlugin';\nimport {\n createProxyHandler,\n type NodeMiddleware,\n} from './intlayerProxyHandler';\n\nconst PROXY_PLUGIN_NAME = 'vite-intlayer-middleware-plugin';\n\n/**\n * Name of the Vite plugin `nitro/vite` registers in preview mode. It mounts the\n * built Nitro server — which already carries the Intlayer proxy as a Nitro\n * middleware — inside the Vite preview server.\n */\nconst NITRO_PREVIEW_PLUGIN_NAME = 'nitro:preview';\n\nexport type IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxy({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n /**\n * Optional Intlayer configuration overrides forwarded to `getConfiguration`.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxy({ configOptions: { override: { ... } } }) ],\n * });\n * ```\n */\n configOptions?: GetConfigurationOptions;\n /**\n * Whether a development or preview server is serving the app.\n *\n * Set internally by the plugin from `configureServer` /\n * `configurePreviewServer`. It only matters in the proxy's auto mode, where\n * a dev server keeps locale routing URL-driven by ignoring the stored locale\n * as a redirect source.\n *\n * Defaults to `false` so that mounting `createIntlayerProxyHandler()`\n * manually — the documented production Nitro setup — keeps full behaviour.\n *\n * @default false\n */\n isDevServer?: boolean;\n};\n\n/**\n * Creates a standalone, framework-agnostic locale-routing middleware.\n *\n * It loads the Intlayer configuration and hands it to the runtime handler in\n * `intlayerProxyHandler`, so it can be used in every environment:\n *\n * - **Dev**: wired up automatically by `intlayerProxy` via `configureServer`\n * - **Preview**: wired up automatically by `intlayerProxy` via `configurePreviewServer`\n * - **Production (Nitro / TanStack Start)**: create `server/middleware/intlayerProxy.ts`:\n *\n * @example\n * ```ts\n * // server/middleware/intlayerProxy.ts\n * import { fromNodeMiddleware } from 'h3';\n * import { createIntlayerProxyHandler } from 'vite-intlayer';\n *\n * export default fromNodeMiddleware(createIntlayerProxyHandler());\n * ```\n *\n * @param options - Plugin-specific options, such as path ignoring and Intlayer configuration overrides.\n * @returns A Connect-compatible `(req, res, next) => void` middleware.\n */\nexport const createIntlayerProxyHandler = (\n options?: IntlayerProxyPluginOptions\n): NodeMiddleware =>\n createProxyHandler({\n configuration: getConfiguration(options?.configOptions),\n ignore: options?.ignore,\n isDevServer: options?.isDevServer ?? false,\n });\n\n/**\n * Vite plugin that provides locale-based routing middleware for **all environments**:\n * development, preview, and production SSR (Nitro / TanStack Start).\n *\n * - **Dev** (`vite dev`): registered via `configureServer`.\n * - **Preview** (`vite preview`): registered via `configurePreviewServer`.\n * - **Production Nitro** (`vite build`): automatically injected via the `.nitro` module\n * property that `nitro/vite` reads and pushes into `nitroConfig.modules`. The module\n * registers `intlayerNitroHandler` as a Nitro server middleware — no extra user config\n * needed.\n *\n * If you need custom config options or an `ignore` predicate in production, bypass\n * auto-injection and create a server middleware file manually:\n *\n * ```ts\n * // server/middleware/intlayerProxy.ts\n * import { fromNodeMiddleware } from 'h3';\n * import { createIntlayerProxyHandler } from 'vite-intlayer';\n *\n * export default fromNodeMiddleware(\n * createIntlayerProxyHandler({\n * ignore: (req) => req.url?.startsWith('/api'),\n * configOptions: myConfig,\n * })\n * );\n * ```\n *\n * @param options - Plugin-specific options, like ignoring certain paths and Intlayer configuration overrides.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n *\n * @deprecated Since Intlayer v9, `intlayerProxy()` is bundled directly into the `intlayer()` plugin and enabled by default through the `routing.enableProxy` option (unset by default, which selects auto mode). Registering it separately as shown below is now optional.\n */\nexport const intlayerProxy = (options?: IntlayerProxyPluginOptions): Plugin => {\n // Dev and preview servers run the same handler; both are \"dev servers\" as far\n // as auto mode is concerned, so a single instance covers both hooks.\n const handler = createIntlayerProxyHandler({ ...options, isDevServer: true });\n const intlayerConfig = getConfiguration(options?.configOptions);\n const logger = getAppLogger(intlayerConfig);\n\n // Both hooks below serve a dev or preview server, hence the hard-coded true.\n const isStorageLocaleSuppressed = !isProxyStorageLocaleEnabled(\n resolveProxyMode(intlayerConfig.routing.enableProxy),\n true\n );\n\n /**\n * Logs that the proxy is serving requests, spelling out when auto mode has\n * suppressed the stored locale so the reported state matches the behaviour.\n */\n const logProxyEnabled = () =>\n logger(formatProxyEnabledMessage(isStorageLocaleSuppressed), {\n level: 'info',\n });\n\n // Ensures the proxy registers its middleware only once, even when it is\n // registered both via `intlayer()` (which now bundles it) and a manual\n // `intlayerProxy()` call.\n const guard = createPrimaryInstanceGuard(PROXY_PLUGIN_NAME);\n\n // Set during `configResolved`: `nitro/vite` serves the *built* Nitro server\n // from inside the preview server, and that build already carries the proxy as\n // a Nitro middleware (see `nitroModule` below).\n let isNitroServingPreview = false;\n\n /**\n * Nitro module injected automatically by `nitro/vite`.\n *\n * When a Vite plugin carries a `.nitro` property, `nitro/vite` pushes it into\n * `nitroConfig.modules` during the build phase. The module's `setup` hook adds\n * our locale-routing handler to Nitro's server pipeline, making locale detection\n * work in production SSR builds (TanStack Start, Nuxt, etc.) without any extra\n * user configuration.\n *\n * @see https://github.com/nitrojs/nitro (nitro/vite source, line ~402)\n */\n const nitroModule = {\n name: 'intlayer-proxy',\n setup(nitro: {\n options: {\n dev: boolean;\n handlers: {\n route: string;\n handler: string;\n middleware: boolean;\n }[];\n };\n }) {\n // In dev mode, locale routing is already handled by configureServer (Vite dev server).\n // The Nitro dev server uses h3 v2's Web Fetch API event model which is incompatible\n // with fromNodeMiddleware (h3 v1) and would cause double-execution anyway.\n // Only inject for production builds where Nitro is the actual HTTP server.\n if (nitro.options.dev) return;\n\n const handlerPath = fileURLToPath(\n new URL('./intlayerNitroHandler.mjs', import.meta.url)\n );\n\n // Skip if an identical handler was already registered by another instance\n // (e.g. both `intlayer()` and a manual `intlayerProxy()`).\n const alreadyRegistered = nitro.options.handlers.some(\n (existingHandler) => existingHandler.handler === handlerPath\n );\n if (alreadyRegistered) return;\n\n nitro.options.handlers.push({\n route: '/**',\n handler: handlerPath,\n middleware: true,\n });\n },\n };\n\n const plugin = {\n name: PROXY_PLUGIN_NAME,\n // Decide whether this is the primary instance before registering middleware.\n configResolved: (config: { plugins: readonly { name: string }[] }) => {\n guard.resolve(config);\n isNitroServingPreview = config.plugins.some(\n (registeredPlugin) =>\n registeredPlugin.name === NITRO_PREVIEW_PLUGIN_NAME\n );\n },\n // Injected into nitroConfig.modules by the `nitro/vite` plugin so the\n // locale-routing middleware is registered in the production Nitro server.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nitro: nitroModule as any,\n // Vite dev server\n configureServer: (server) => {\n if (!guard.isPrimary) return;\n logProxyEnabled();\n server.middlewares.use(handler);\n },\n // Vite preview server\n configurePreviewServer: (server) => {\n if (!guard.isPrimary) return;\n // With Nitro, the preview server forwards every request to the built\n // Nitro server, whose pipeline already starts with this proxy. Adding a\n // second layer here would run locale resolution twice on the same\n // request: the first pass rewrites `req.url` (and the locale request\n // header), the second pass reads that rewritten URL as if it came from\n // the browser and can redirect it back — the redirect ping-pong that\n // shows up as \"max redirects reached\" while prerendering.\n if (isNitroServingPreview) return;\n logProxyEnabled();\n server.middlewares.use(handler);\n },\n } as Plugin;\n\n // Register the plugin object so the dedupe guard can identify the primary\n // instance by reference during `configResolved`.\n guard.setPlugin(plugin);\n\n return plugin;\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":";;;;;;;;AAoBA,MAAM,oBAAoB;;;;;;AAO1B,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;AAkElC,MAAa,8BACX,YAEA,mBAAmB;CACjB,eAAe,iBAAiB,SAAS,aAAa;CACtD,QAAQ,SAAS;CACjB,aAAa,SAAS,eAAe;AACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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import { IntlayerCompilerOptions, intlayerCompiler } from "./IntlayerCompilerPlugin.js";
|
|
2
|
+
import { ChunkingContext, DictionaryModule, ModuleGraphNode, createDictionaryModuleParser, intlayerChunk, resolveBoundaries, toBoundaryName } from "./intlayerChunkPlugin.js";
|
|
2
3
|
import { intlayerMinify } from "./intlayerMinifyPlugin.js";
|
|
3
4
|
import { intlayerOptimize } from "./intlayerOptimizePlugin.js";
|
|
4
5
|
import { IntlayerProxyPluginOptions, createIntlayerProxyHandler, intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy } from "./intlayerProxyPlugin.js";
|
|
5
6
|
import { IntlayerPluginOptions, intLayerPlugin, intlayer, intlayerPlugin } from "./intlayerPlugin.js";
|
|
7
|
+
import { intlayerPreload } from "./intlayerPreloadPlugin.js";
|
|
6
8
|
import { intlayerPrune } from "./intlayerPrunePlugin.js";
|
|
7
|
-
export { IntlayerCompilerOptions, IntlayerPluginOptions, IntlayerProxyPluginOptions, createIntlayerProxyHandler, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerCompiler, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerProxy, intlayerPrune };
|
|
9
|
+
export { ChunkingContext, DictionaryModule, IntlayerCompilerOptions, IntlayerPluginOptions, IntlayerProxyPluginOptions, ModuleGraphNode, createDictionaryModuleParser, createIntlayerProxyHandler, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerChunk, intlayerCompiler, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerPreload, intlayerProxy, intlayerPrune, resolveBoundaries, toBoundaryName };
|