next-intlayer 7.0.0-canary.2 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/client/useLocale.cjs +10 -2
- package/dist/cjs/client/useLocale.cjs.map +1 -1
- package/dist/cjs/proxy/intlayerProxy.cjs +62 -42
- package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
- package/dist/cjs/proxy/multipleProxies.cjs +4 -4
- package/dist/cjs/proxy/multipleProxies.cjs.map +1 -1
- package/dist/cjs/server/withIntlayer.cjs +3 -4
- package/dist/cjs/server/withIntlayer.cjs.map +1 -1
- package/dist/esm/client/useLocale.mjs +11 -3
- package/dist/esm/client/useLocale.mjs.map +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs +62 -43
- package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
- package/dist/esm/proxy/multipleProxies.mjs +4 -4
- package/dist/esm/proxy/multipleProxies.mjs.map +1 -1
- package/dist/esm/server/withIntlayer.mjs +4 -5
- package/dist/esm/server/withIntlayer.mjs.map +1 -1
- package/dist/types/client/useLocale.d.ts +4 -4
- package/dist/types/client/useLocale.d.ts.map +1 -1
- package/dist/types/generateStaticParams.d.ts +2 -2
- package/dist/types/generateStaticParams.d.ts.map +1 -1
- package/dist/types/proxy/intlayerProxy.d.ts.map +1 -1
- package/dist/types/server/withIntlayer.d.ts.map +1 -1
- package/package.json +21 -18
- package/dist/cjs/middleware/index.cjs +0 -7
- package/dist/cjs/middleware/intlayerMiddleware.cjs +0 -227
- package/dist/cjs/middleware/intlayerMiddleware.cjs.map +0 -1
- package/dist/cjs/middleware/localeDetector.cjs +0 -21
- package/dist/cjs/middleware/localeDetector.cjs.map +0 -1
- package/dist/cjs/middleware/multipleMiddlewares.cjs +0 -58
- package/dist/cjs/middleware/multipleMiddlewares.cjs.map +0 -1
- package/dist/cjs/proxy/multipleProxy.cjs +0 -60
- package/dist/cjs/proxy/multipleProxy.cjs.map +0 -1
- package/dist/esm/middleware/index.mjs +0 -5
- package/dist/esm/middleware/intlayerMiddleware.mjs +0 -223
- package/dist/esm/middleware/intlayerMiddleware.mjs.map +0 -1
- package/dist/esm/middleware/localeDetector.mjs +0 -19
- package/dist/esm/middleware/localeDetector.mjs.map +0 -1
- package/dist/esm/middleware/multipleMiddlewares.mjs +0 -56
- package/dist/esm/middleware/multipleMiddlewares.mjs.map +0 -1
- package/dist/esm/proxy/multipleProxy.mjs +0 -57
- package/dist/esm/proxy/multipleProxy.mjs.map +0 -1
- package/dist/types/middleware/index.d.ts +0 -4
- package/dist/types/middleware/intlayerMiddleware.d.ts +0 -31
- package/dist/types/middleware/intlayerMiddleware.d.ts.map +0 -1
- package/dist/types/middleware/localeDetector.d.ts +0 -14
- package/dist/types/middleware/localeDetector.d.ts.map +0 -1
- package/dist/types/middleware/multipleMiddlewares.d.ts +0 -33
- package/dist/types/middleware/multipleMiddlewares.d.ts.map +0 -1
- package/dist/types/proxy/multipleProxy.d.ts +0 -34
- package/dist/types/proxy/multipleProxy.d.ts.map +0 -1
|
@@ -1,227 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
const require_middleware_localeDetector = require('./localeDetector.cjs');
|
|
3
|
-
let __intlayer_config_built = require("@intlayer/config/built");
|
|
4
|
-
__intlayer_config_built = require_rolldown_runtime.__toESM(__intlayer_config_built);
|
|
5
|
-
let __intlayer_core = require("@intlayer/core");
|
|
6
|
-
__intlayer_core = require_rolldown_runtime.__toESM(__intlayer_core);
|
|
7
|
-
let next_server = require("next/server");
|
|
8
|
-
next_server = require_rolldown_runtime.__toESM(next_server);
|
|
9
|
-
|
|
10
|
-
//#region src/middleware/intlayerMiddleware.ts
|
|
11
|
-
const { internationalization, routing } = __intlayer_config_built.default ?? {};
|
|
12
|
-
const { locales, defaultLocale } = internationalization ?? {};
|
|
13
|
-
const { headerName, basePath, detectLocaleOnPrefetchNoPrefix, mode } = routing ?? {};
|
|
14
|
-
const noPrefix = mode === "no-prefix" || mode === "search-params";
|
|
15
|
-
const prefixDefault = mode === "prefix-all";
|
|
16
|
-
/**
|
|
17
|
-
* Detects if the request is a prefetch request from Next.js.
|
|
18
|
-
*
|
|
19
|
-
* Next.js prefetch requests can be identified by several headers:
|
|
20
|
-
* - purpose: 'prefetch' (standard prefetch header)
|
|
21
|
-
* - next-router-prefetch: '1' (Next.js router prefetch)
|
|
22
|
-
* - next-url: present (Next.js internal navigation)
|
|
23
|
-
*
|
|
24
|
-
* During prefetch, we should ignore cookie-based locale detection
|
|
25
|
-
* to prevent unwanted redirects when users are switching locales.
|
|
26
|
-
*
|
|
27
|
-
* @param request - The incoming Next.js request object.
|
|
28
|
-
* @returns - True if the request is a prefetch request, false otherwise.
|
|
29
|
-
*/
|
|
30
|
-
const isPrefetchRequest = (request) => {
|
|
31
|
-
const purpose = request.headers.get("purpose");
|
|
32
|
-
const nextRouterPrefetch = request.headers.get("next-router-prefetch");
|
|
33
|
-
const nextUrl = request.headers.get("next-url");
|
|
34
|
-
const xNextjsData = request.headers.get("x-nextjs-data");
|
|
35
|
-
return purpose === "prefetch" || nextRouterPrefetch === "1" || !!nextUrl || !!xNextjsData;
|
|
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
|
-
* Middleware that handles the internationalization layer
|
|
45
|
-
*
|
|
46
|
-
* Usage:
|
|
47
|
-
*
|
|
48
|
-
* ```ts
|
|
49
|
-
* // ./src/middleware.ts
|
|
50
|
-
*
|
|
51
|
-
* export { intlayerMiddleware as middleware } from '@intlayer/next/middleware';
|
|
52
|
-
*
|
|
53
|
-
* // applies this middleware only to files in the app directory
|
|
54
|
-
* export const config = {
|
|
55
|
-
* matcher: '/((?!api|static|.*\\..*|_next).*)',
|
|
56
|
-
* };
|
|
57
|
-
* ```
|
|
58
|
-
*
|
|
59
|
-
* Main middleware function for handling internationalization.
|
|
60
|
-
*
|
|
61
|
-
* @param request - The incoming Next.js request object.
|
|
62
|
-
* @param event - The Next.js fetch event (optional).
|
|
63
|
-
* @param response - The Next.js response object (optional).
|
|
64
|
-
* @returns - The response to be returned to the client.
|
|
65
|
-
*/
|
|
66
|
-
const intlayerMiddleware = (request, _event, _response) => {
|
|
67
|
-
const pathname = request.nextUrl.pathname;
|
|
68
|
-
const cookieLocale = getCookieLocale(request);
|
|
69
|
-
const basePathTrailingSlash = basePath.endsWith("/");
|
|
70
|
-
if (noPrefix) return handleNoPrefix(request, cookieLocale, pathname, basePathTrailingSlash);
|
|
71
|
-
return handlePrefix(request, cookieLocale, getPathLocale(pathname), pathname, basePathTrailingSlash);
|
|
72
|
-
};
|
|
73
|
-
/**
|
|
74
|
-
* Retrieves the locale from the request cookies if available and valid.
|
|
75
|
-
*
|
|
76
|
-
* @param request - The incoming Next.js request object.
|
|
77
|
-
* @returns - The locale found in the cookies, or undefined if not found or invalid.
|
|
78
|
-
*/
|
|
79
|
-
const getCookieLocale = (request) => (0, __intlayer_core.getLocaleFromStorage)({ getCookie: (name) => request.cookies.get(name)?.value ?? null });
|
|
80
|
-
/**
|
|
81
|
-
* Handles the case where URLs do not have locale prefixes.
|
|
82
|
-
*
|
|
83
|
-
* @param request - The incoming Next.js request object.
|
|
84
|
-
* @param cookieLocale - The locale from the cookie.
|
|
85
|
-
* @param pathname - The pathname from the request URL.
|
|
86
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
87
|
-
* @returns - The rewritten response with the locale applied.
|
|
88
|
-
*/
|
|
89
|
-
const handleNoPrefix = (request, cookieLocale, pathname, basePathTrailingSlash) => {
|
|
90
|
-
const locale = cookieLocale ?? defaultLocale;
|
|
91
|
-
return rewriteUrl(request, constructPath(locale, pathname, basePath, basePathTrailingSlash, appendLocaleSearchIfNeeded(request.nextUrl.search, locale)), locale);
|
|
92
|
-
};
|
|
93
|
-
/**
|
|
94
|
-
* Extracts the locale from the URL pathname if present.
|
|
95
|
-
*
|
|
96
|
-
* @param pathname - The pathname from the request URL.
|
|
97
|
-
* @returns - The locale found in the pathname, or undefined if not found.
|
|
98
|
-
*/
|
|
99
|
-
const getPathLocale = (pathname) => locales.find((locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`);
|
|
100
|
-
/**
|
|
101
|
-
* Handles the case where URLs have locale prefixes.
|
|
102
|
-
*
|
|
103
|
-
* @param request - The incoming Next.js request object.
|
|
104
|
-
* @param cookieLocale - The locale from the cookie.
|
|
105
|
-
* @param pathLocale - The locale extracted from the pathname.
|
|
106
|
-
* @param pathname - The pathname from the request URL.
|
|
107
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
108
|
-
* @returns - The response to be returned to the client.
|
|
109
|
-
*/
|
|
110
|
-
const handlePrefix = (request, cookieLocale, pathLocale, pathname, basePathTrailingSlash) => {
|
|
111
|
-
if (!pathLocale) {
|
|
112
|
-
if (isPrefetchRequest(request) && !detectLocaleOnPrefetchNoPrefix) return handleMissingPathLocale(request, defaultLocale, pathname, basePathTrailingSlash);
|
|
113
|
-
return handleMissingPathLocale(request, cookieLocale, pathname, basePathTrailingSlash);
|
|
114
|
-
}
|
|
115
|
-
return handleExistingPathLocale(request, cookieLocale, pathLocale, pathname, basePathTrailingSlash);
|
|
116
|
-
};
|
|
117
|
-
/**
|
|
118
|
-
* Handles requests where the locale is missing from the URL pathname.
|
|
119
|
-
*
|
|
120
|
-
* @param request - The incoming Next.js request object.
|
|
121
|
-
* @param cookieLocale - The locale from the cookie.
|
|
122
|
-
* @param pathname - The pathname from the request URL.
|
|
123
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
124
|
-
* @returns - The response to be returned to the client.
|
|
125
|
-
*/
|
|
126
|
-
const handleMissingPathLocale = (request, cookieLocale, pathname, basePathTrailingSlash) => {
|
|
127
|
-
let locale = cookieLocale ?? require_middleware_localeDetector.localeDetector?.(request) ?? defaultLocale;
|
|
128
|
-
if (!locales.includes(locale)) locale = defaultLocale;
|
|
129
|
-
const newPath = constructPath(locale, pathname, basePath, basePathTrailingSlash, appendLocaleSearchIfNeeded(request.nextUrl.search, locale));
|
|
130
|
-
return prefixDefault || locale !== defaultLocale ? redirectUrl(request, newPath) : rewriteUrl(request, newPath, locale);
|
|
131
|
-
};
|
|
132
|
-
/**
|
|
133
|
-
* Handles requests where the locale exists in the URL pathname.
|
|
134
|
-
*
|
|
135
|
-
* @param request - The incoming Next.js request object.
|
|
136
|
-
* @param cookieLocale - The locale from the cookie.
|
|
137
|
-
* @param pathLocale - The locale extracted from the pathname.
|
|
138
|
-
* @param pathname - The pathname from the request URL.
|
|
139
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
140
|
-
* @returns - The response to be returned to the client.
|
|
141
|
-
*/
|
|
142
|
-
const handleExistingPathLocale = (request, cookieLocale, pathLocale, pathname, basePathTrailingSlash) => {
|
|
143
|
-
if (cookieLocale && cookieLocale !== pathLocale) return redirectUrl(request, handleCookieLocaleMismatch(request, pathname, pathLocale, cookieLocale, basePath, basePathTrailingSlash));
|
|
144
|
-
return handleDefaultLocaleRedirect(request, pathLocale, pathname, basePathTrailingSlash);
|
|
145
|
-
};
|
|
146
|
-
/**
|
|
147
|
-
* Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.
|
|
148
|
-
*
|
|
149
|
-
* @param request - The incoming Next.js request object.
|
|
150
|
-
* @param pathname - The pathname from the request URL.
|
|
151
|
-
* @param pathLocale - The locale extracted from the pathname.
|
|
152
|
-
* @param cookieLocale - The locale from the cookie.
|
|
153
|
-
* @param basePath - The base path of the application.
|
|
154
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
155
|
-
* @returns - The new URL path with the correct locale.
|
|
156
|
-
*/
|
|
157
|
-
const handleCookieLocaleMismatch = (request, pathname, pathLocale, cookieLocale, basePath$1, basePathTrailingSlash) => {
|
|
158
|
-
return constructPath(cookieLocale, pathname.replace(`/${pathLocale}`, `/${cookieLocale}`), basePath$1, basePathTrailingSlash, appendLocaleSearchIfNeeded(request.nextUrl.search, cookieLocale));
|
|
159
|
-
};
|
|
160
|
-
/**
|
|
161
|
-
* Handles redirection when the default locale is used and prefixing is not required.
|
|
162
|
-
*
|
|
163
|
-
* @param request - The incoming Next.js request object.
|
|
164
|
-
* @param pathLocale - The locale extracted from the pathname.
|
|
165
|
-
* @param pathname - The pathname from the request URL.
|
|
166
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
167
|
-
* @returns - The rewritten response without the locale prefix.
|
|
168
|
-
*/
|
|
169
|
-
const handleDefaultLocaleRedirect = (request, pathLocale, pathname, basePathTrailingSlash) => {
|
|
170
|
-
if (!prefixDefault && pathLocale === defaultLocale) {
|
|
171
|
-
let pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) ?? "/";
|
|
172
|
-
if (basePathTrailingSlash) pathWithoutLocale = pathWithoutLocale.slice(1);
|
|
173
|
-
const searchWithLocale$1 = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
|
|
174
|
-
if (searchWithLocale$1) pathWithoutLocale += searchWithLocale$1;
|
|
175
|
-
else if (request.nextUrl.search) pathWithoutLocale += request.nextUrl.search;
|
|
176
|
-
return rewriteUrl(request, `${basePath}${pathWithoutLocale}`, pathLocale);
|
|
177
|
-
}
|
|
178
|
-
const searchWithLocale = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
|
|
179
|
-
return rewriteUrl(request, searchWithLocale ? `${pathname}${searchWithLocale}` : pathname, pathLocale);
|
|
180
|
-
};
|
|
181
|
-
/**
|
|
182
|
-
* Constructs a new path by combining the locale, path, basePath, and search parameters.
|
|
183
|
-
*
|
|
184
|
-
* @param locale - The locale to include in the path.
|
|
185
|
-
* @param path - The original path from the request.
|
|
186
|
-
* @param basePath - The base path of the application.
|
|
187
|
-
* @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
|
|
188
|
-
* @param [search] - The query string from the request URL (optional).
|
|
189
|
-
* @returns - The constructed new path.
|
|
190
|
-
*/
|
|
191
|
-
const constructPath = (locale, path, basePath$1, basePathTrailingSlash, search) => {
|
|
192
|
-
const pathWithLocalePrefix = mode === "search-params" ? path : `${locale}${path}`;
|
|
193
|
-
let newPath = `${basePath$1}${basePathTrailingSlash ? "" : "/"}${pathWithLocalePrefix}`;
|
|
194
|
-
if (search) newPath += search;
|
|
195
|
-
return newPath;
|
|
196
|
-
};
|
|
197
|
-
/**
|
|
198
|
-
* Rewrites the URL to the new path and sets the locale header.
|
|
199
|
-
*
|
|
200
|
-
* @param request - The incoming Next.js request object.
|
|
201
|
-
* @param newPath - The new path to rewrite to.
|
|
202
|
-
* @param locale - The locale to set in the response header.
|
|
203
|
-
* @returns - The rewritten response.
|
|
204
|
-
*/
|
|
205
|
-
const rewriteUrl = (request, newPath, locale) => {
|
|
206
|
-
const search = request.nextUrl.search;
|
|
207
|
-
const pathWithSearch = search && !newPath.includes("?") ? `${newPath}${search}` : newPath;
|
|
208
|
-
const response = next_server.NextResponse.rewrite(new URL(pathWithSearch, request.url));
|
|
209
|
-
response.headers.set(headerName, locale);
|
|
210
|
-
return response;
|
|
211
|
-
};
|
|
212
|
-
/**
|
|
213
|
-
* Redirects the request to the new path.
|
|
214
|
-
*
|
|
215
|
-
* @param request - The incoming Next.js request object.
|
|
216
|
-
* @param newPath - The new path to redirect to.
|
|
217
|
-
* @returns - The redirect response.
|
|
218
|
-
*/
|
|
219
|
-
const redirectUrl = (request, newPath) => {
|
|
220
|
-
const search = request.nextUrl.search;
|
|
221
|
-
const pathWithSearch = search && !newPath.includes("?") ? `${newPath}${search}` : newPath;
|
|
222
|
-
return next_server.NextResponse.redirect(new URL(pathWithSearch, request.url));
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
//#endregion
|
|
226
|
-
exports.intlayerMiddleware = intlayerMiddleware;
|
|
227
|
-
//# sourceMappingURL=intlayerMiddleware.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerMiddleware.cjs","names":["configuration","localeDetector","basePath","searchWithLocale","NextResponse"],"sources":["../../../src/middleware/intlayerMiddleware.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { getLocaleFromStorage } from '@intlayer/core';\nimport type { Locale } from '@intlayer/types';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { headerName, basePath, detectLocaleOnPrefetchNoPrefix, mode } =\n routing ?? {};\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst noPrefix = mode === 'no-prefix' || mode === 'search-params';\nconst prefixDefault = mode === 'prefix-all';\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests can be identified by several headers:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js router prefetch)\n * - next-url: present (Next.js internal navigation)\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n const nextUrl = request.headers.get('next-url');\n const xNextjsData = request.headers.get('x-nextjs-data');\n\n return (\n purpose === 'prefetch' ||\n nextRouterPrefetch === '1' ||\n !!nextUrl ||\n !!xNextjsData\n );\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\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\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Middleware that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/middleware.ts\n *\n * export { intlayerMiddleware as middleware } from '@intlayer/next/middleware';\n *\n * // applies this middleware only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main middleware function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerMiddleware = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const cookieLocale = getCookieLocale(request);\n const basePathTrailingSlash = basePath.endsWith('/');\n\n if (\n noPrefix // If the application is configured not to use locale prefixes in URLs\n ) {\n return handleNoPrefix(\n request,\n cookieLocale,\n pathname,\n basePathTrailingSlash\n );\n }\n\n const pathLocale = getPathLocale(pathname);\n\n return handlePrefix(\n request,\n cookieLocale,\n pathLocale,\n pathname,\n basePathTrailingSlash\n );\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getCookieLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param cookieLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The rewritten response with the locale applied.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n cookieLocale: Locale | undefined,\n pathname: string,\n basePathTrailingSlash: boolean\n): NextResponse => {\n const locale = cookieLocale ?? defaultLocale;\n\n const newPath = constructPath(\n locale,\n pathname,\n basePath,\n basePathTrailingSlash,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n return rewriteUrl(request, newPath, locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n locales.find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param cookieLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n cookieLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string,\n basePathTrailingSlash: boolean\n): NextResponse => {\n if (\n !pathLocale // If the URL does not contain a locale prefix\n ) {\n const isPrefetch = isPrefetchRequest(request);\n\n if (isPrefetch && !detectLocaleOnPrefetchNoPrefix) {\n return handleMissingPathLocale(\n request,\n defaultLocale,\n pathname,\n basePathTrailingSlash\n );\n }\n\n return handleMissingPathLocale(\n request,\n cookieLocale,\n pathname,\n basePathTrailingSlash\n );\n }\n\n // If the URL contains a locale prefix\n return handleExistingPathLocale(\n request,\n cookieLocale,\n pathLocale,\n pathname,\n basePathTrailingSlash\n );\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param cookieLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n cookieLocale: Locale | undefined,\n pathname: string,\n basePathTrailingSlash: boolean\n): NextResponse => {\n let locale = (cookieLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n if (!locales.includes(locale)) {\n locale = defaultLocale;\n }\n\n const newPath = constructPath(\n locale,\n pathname,\n basePath,\n basePathTrailingSlash,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(request, newPath, locale);\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param cookieLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n cookieLocale: Locale | undefined,\n pathLocale: Locale,\n pathname: string,\n basePathTrailingSlash: boolean\n): NextResponse => {\n if (\n // If the cookie locale is set and differs from the locale in the URL\n cookieLocale &&\n cookieLocale !== pathLocale\n ) {\n const newPath = handleCookieLocaleMismatch(\n request,\n pathname,\n pathLocale,\n cookieLocale,\n basePath,\n basePathTrailingSlash\n );\n return redirectUrl(request, newPath);\n }\n\n // If the cookie locale matches the path locale, or cookie locale is not set, or serverSetCookie is 'always'\n return handleDefaultLocaleRedirect(\n request,\n pathLocale,\n pathname,\n basePathTrailingSlash\n );\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param cookieLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The new URL path with the correct locale.\n */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n pathname: string,\n pathLocale: Locale,\n cookieLocale: Locale,\n basePath: string,\n basePathTrailingSlash: boolean\n): string => {\n // Replace the pathLocale in the pathname with the cookieLocale\n const newPath = pathname.replace(`/${pathLocale}`, `/${cookieLocale}`);\n\n return constructPath(\n cookieLocale,\n newPath,\n basePath,\n basePathTrailingSlash,\n appendLocaleSearchIfNeeded(request.nextUrl.search, cookieLocale)\n );\n};\n\n/**\n * Handles redirection when the default locale is used and prefixing is not required.\n *\n * @param request - The incoming Next.js request object.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The rewritten response without the locale prefix.\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string,\n basePathTrailingSlash: boolean\n): NextResponse => {\n if (\n // If default locale should not be prefixed and the pathLocale is the defaultLocale\n !prefixDefault &&\n pathLocale === defaultLocale\n ) {\n let pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) ?? '/';\n\n if (basePathTrailingSlash) {\n pathWithoutLocale = pathWithoutLocale.slice(1);\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n if (searchWithLocale) {\n pathWithoutLocale += searchWithLocale;\n } else if (request.nextUrl.search) {\n pathWithoutLocale += request.nextUrl.search;\n }\n\n return rewriteUrl(request, `${basePath}${pathWithoutLocale}`, pathLocale);\n }\n\n // If prefixing default locale is required or pathLocale is not the defaultLocale\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n const newPath = searchWithLocale\n ? `${pathname}${searchWithLocale}`\n : pathname;\n return rewriteUrl(request, newPath, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n basePathTrailingSlash: boolean,\n search?: string\n): string => {\n // In 'search-params' mode, we do not prefix the path with the locale\n const pathWithLocalePrefix =\n mode === 'search-params' ? path : `${locale}${path}`;\n\n let newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n if (search) {\n newPath += search;\n }\n return newPath;\n};\n\n/**\n * Rewrites the URL to the new path and sets the locale header.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to rewrite to.\n * @param locale - The locale to set in the response header.\n * @returns - The rewritten response.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n // Ensure we preserve the original search params if they were present and not explicitly included in newPath\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const response = NextResponse.rewrite(new URL(pathWithSearch, request.url));\n response.headers.set(headerName, locale);\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @returns - The redirect response.\n */\nconst redirectUrl = (request: NextRequest, newPath: string): NextResponse => {\n // Ensure we preserve the original search params if they were present and not explicitly included in newPath\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"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"}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let __intlayer_core = require("@intlayer/core");
|
|
3
|
-
__intlayer_core = require_rolldown_runtime.__toESM(__intlayer_core);
|
|
4
|
-
|
|
5
|
-
//#region src/middleware/localeDetector.ts
|
|
6
|
-
/**
|
|
7
|
-
* Detects the locale from the request headers
|
|
8
|
-
*
|
|
9
|
-
* Headers are provided by the browser and can be used to determine the user's preferred language
|
|
10
|
-
*/
|
|
11
|
-
const localeDetector = (request) => {
|
|
12
|
-
const negotiatorHeaders = {};
|
|
13
|
-
request.headers.forEach((value, key) => {
|
|
14
|
-
negotiatorHeaders[key] = value;
|
|
15
|
-
});
|
|
16
|
-
return (0, __intlayer_core.localeDetector)(negotiatorHeaders);
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
//#endregion
|
|
20
|
-
exports.localeDetector = localeDetector;
|
|
21
|
-
//# sourceMappingURL=localeDetector.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"localeDetector.cjs","names":["negotiatorHeaders: Record<string, string>"],"sources":["../../../src/middleware/localeDetector.ts"],"sourcesContent":["import { localeDetector as localeDetectorCore } from '@intlayer/core';\nimport type { LocalesValues } from '@intlayer/types';\nimport type { NextRequest } from 'next/server.js';\n\n/**\n * Detects the locale from the request headers\n *\n * Headers are provided by the browser and can be used to determine the user's preferred language\n */\nexport const localeDetector = (request: NextRequest): LocalesValues => {\n const negotiatorHeaders: Record<string, string> = {};\n\n request.headers.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const locale = localeDetectorCore(negotiatorHeaders);\n\n return locale;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB,YAAwC;CACrE,MAAMA,oBAA4C,EAAE;AAEpD,SAAQ,QAAQ,SAAS,OAAO,QAAQ;AACtC,oBAAkB,OAAO;GACzB;AAIF,4CAFkC,kBAAkB"}
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let next_server = require("next/server");
|
|
3
|
-
next_server = require_rolldown_runtime.__toESM(next_server);
|
|
4
|
-
|
|
5
|
-
//#region src/middleware/multipleMiddlewares.ts
|
|
6
|
-
/**
|
|
7
|
-
* Utility to combine multiple Next.js middlewares into one.
|
|
8
|
-
*
|
|
9
|
-
* It executes middlewares in order, merges headers, and correctly handles
|
|
10
|
-
* redirects and rewrites.
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* import { multipleMiddlewares, intlayerMiddleware } from "next-intlayer/middleware";
|
|
14
|
-
* import { NextResponse } from "next/server";
|
|
15
|
-
*
|
|
16
|
-
* const authMiddleware = (req: NextRequest) => {
|
|
17
|
-
* if (!req.cookies.get("token")) {
|
|
18
|
-
* return NextResponse.redirect(new URL("/login", req.url));
|
|
19
|
-
* }
|
|
20
|
-
* return NextResponse.next();
|
|
21
|
-
* };
|
|
22
|
-
*
|
|
23
|
-
* export default multipleMiddlewares([
|
|
24
|
-
* intlayerMiddleware,
|
|
25
|
-
* authMiddleware,
|
|
26
|
-
* ]);
|
|
27
|
-
*
|
|
28
|
-
* @param middlewares - An array of middleware functions to execute in order.
|
|
29
|
-
* @returns A single middleware function that runs all provided middlewares.
|
|
30
|
-
*/
|
|
31
|
-
const multipleMiddlewares = (middlewares) => async (req, event, response) => {
|
|
32
|
-
const middlewareHeader = [];
|
|
33
|
-
for (const middleware of middlewares) {
|
|
34
|
-
const result = await middleware(req, event, response);
|
|
35
|
-
if (!result.ok) return result;
|
|
36
|
-
middlewareHeader.push(result.headers);
|
|
37
|
-
}
|
|
38
|
-
const mergedHeaders = new Headers();
|
|
39
|
-
const transmittedHeaders = new Headers();
|
|
40
|
-
middlewareHeader.forEach((header) => {
|
|
41
|
-
for (const [key, value] of header.entries()) {
|
|
42
|
-
mergedHeaders.append(key, value);
|
|
43
|
-
if (key.startsWith("x-middleware-request-")) {
|
|
44
|
-
const fixedKey = key.replace("x-middleware-request-", "");
|
|
45
|
-
transmittedHeaders.append(fixedKey, value);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
const redirect = mergedHeaders.get("x-middleware-request-redirect");
|
|
50
|
-
if (redirect) return next_server.NextResponse.redirect(new URL(redirect, req.url), { status: 307 });
|
|
51
|
-
const rewrite = mergedHeaders.get("x-middleware-rewrite");
|
|
52
|
-
if (rewrite) return next_server.NextResponse.rewrite(new URL(rewrite, req.url), { request: { headers: transmittedHeaders } });
|
|
53
|
-
return next_server.NextResponse.next({ request: { headers: transmittedHeaders } });
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
//#endregion
|
|
57
|
-
exports.multipleMiddlewares = multipleMiddlewares;
|
|
58
|
-
//# sourceMappingURL=multipleMiddlewares.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"multipleMiddlewares.cjs","names":["NextResponse"],"sources":["../../../src/middleware/multipleMiddlewares.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js middlewares into one.\n *\n * It executes middlewares in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleMiddlewares, intlayerMiddleware } from \"next-intlayer/middleware\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleMiddlewares([\n * intlayerMiddleware,\n * authMiddleware,\n * ]);\n *\n * @param middlewares - An array of middleware functions to execute in order.\n * @returns A single middleware function that runs all provided middlewares.\n */\nexport const multipleMiddlewares =\n (\n middlewares: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store middleware headers\n const middlewareHeader = [];\n\n // Loop through middleware functions\n for (const middleware of middlewares) {\n // Execute middleware function and await the result\n const result = await middleware(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push middleware headers to the array\n middlewareHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the middlewares\n const transmittedHeaders = new Headers();\n\n // Merge headers\n middlewareHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the middlewares\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the middleware headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next middleware\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,uBAET,gBAMF,OAAO,KAAkB,OAAwB,aAA4B;CAE3E,MAAM,mBAAmB,EAAE;AAG3B,MAAK,MAAM,cAAc,aAAa;EAEpC,MAAM,SAAS,MAAM,WAAW,KAAK,OAAO,SAAS;AAGrD,MAAI,CAAC,OAAO,GACV,QAAO;AAIT,mBAAiB,KAAK,OAAO,QAAQ;;CAIvC,MAAM,gBAAgB,IAAI,SAAS;CAGnC,MAAM,qBAAqB,IAAI,SAAS;AAGxC,kBAAiB,SAAS,WAAW;AACnC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,SAAS,EAAE;AAC3C,iBAAc,OAAO,KAAK,MAAM;AAGhC,OAAI,IAAI,WAAW,wBAAwB,EAAE;IAE3C,MAAM,WAAW,IAAI,QAAQ,yBAAyB,GAAG;AAGzD,uBAAmB,OAAO,UAAU,MAAM;;;GAG9C;CAGF,MAAM,WAAW,cAAc,IAAI,gCAAgC;AAGnE,KAAI,SAEF,QAAOA,yBAAa,SAAS,IAAI,IAAI,UAAU,IAAI,IAAI,EAAE,EACvD,QAAQ,KACT,CAAC;CAIJ,MAAM,UAAU,cAAc,IAAI,uBAAuB;AACzD,KAAI,QAEF,QAAOA,yBAAa,QAAQ,IAAI,IAAI,SAAS,IAAI,IAAI,EAAE,EACrD,SAAS,EACP,SAAS,oBACV,EACF,CAAC;AAIJ,QAAOA,yBAAa,KAAK,EACvB,SAAS,EACP,SAAS,oBACV,EACF,CAAC"}
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let next_server = require("next/server");
|
|
3
|
-
next_server = require_rolldown_runtime.__toESM(next_server);
|
|
4
|
-
|
|
5
|
-
//#region src/proxy/multipleProxy.ts
|
|
6
|
-
/**
|
|
7
|
-
* Utility to combine multiple Next.js middlewares into one.
|
|
8
|
-
*
|
|
9
|
-
* It executes middlewares in order, merges headers, and correctly handles
|
|
10
|
-
* redirects and rewrites.
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* import { multipleProxy, intlayerMiddleware } from "next-intlayer/middleware";
|
|
14
|
-
* import { NextResponse } from "next/server";
|
|
15
|
-
*
|
|
16
|
-
* const authMiddleware = (req: NextRequest) => {
|
|
17
|
-
* if (!req.cookies.get("token")) {
|
|
18
|
-
* return NextResponse.redirect(new URL("/login", req.url));
|
|
19
|
-
* }
|
|
20
|
-
* return NextResponse.next();
|
|
21
|
-
* };
|
|
22
|
-
*
|
|
23
|
-
* export default multipleProxy([
|
|
24
|
-
* intlayerMiddleware,
|
|
25
|
-
* authMiddleware,
|
|
26
|
-
* ]);
|
|
27
|
-
*
|
|
28
|
-
* @param middlewares - An array of middleware functions to execute in order.
|
|
29
|
-
* @returns A single middleware function that runs all provided middlewares.
|
|
30
|
-
*/
|
|
31
|
-
const multipleProxy = (middlewares) => async (req, event, response) => {
|
|
32
|
-
const middlewareHeader = [];
|
|
33
|
-
for (const middleware of middlewares) {
|
|
34
|
-
const result = await middleware(req, event, response);
|
|
35
|
-
if (!result.ok) return result;
|
|
36
|
-
middlewareHeader.push(result.headers);
|
|
37
|
-
}
|
|
38
|
-
const mergedHeaders = new Headers();
|
|
39
|
-
const transmittedHeaders = new Headers();
|
|
40
|
-
middlewareHeader.forEach((header) => {
|
|
41
|
-
for (const [key, value] of header.entries()) {
|
|
42
|
-
mergedHeaders.append(key, value);
|
|
43
|
-
if (key.startsWith("x-middleware-request-")) {
|
|
44
|
-
const fixedKey = key.replace("x-middleware-request-", "");
|
|
45
|
-
transmittedHeaders.append(fixedKey, value);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
const redirect = mergedHeaders.get("x-middleware-request-redirect");
|
|
50
|
-
if (redirect) return next_server.NextResponse.redirect(new URL(redirect, req.url), { status: 307 });
|
|
51
|
-
const rewrite = mergedHeaders.get("x-middleware-rewrite");
|
|
52
|
-
if (rewrite) return next_server.NextResponse.rewrite(new URL(rewrite, req.url), { request: { headers: transmittedHeaders } });
|
|
53
|
-
return next_server.NextResponse.next({ request: { headers: transmittedHeaders } });
|
|
54
|
-
};
|
|
55
|
-
const multipleMiddlewares = multipleProxy;
|
|
56
|
-
|
|
57
|
-
//#endregion
|
|
58
|
-
exports.multipleMiddlewares = multipleMiddlewares;
|
|
59
|
-
exports.multipleProxy = multipleProxy;
|
|
60
|
-
//# sourceMappingURL=multipleProxy.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"multipleProxy.cjs","names":["middlewareHeader: Headers[]","NextResponse"],"sources":["../../../src/proxy/multipleProxy.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js middlewares into one.\n *\n * It executes middlewares in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxy, intlayerMiddleware } from \"next-intlayer/middleware\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxy([\n * intlayerMiddleware,\n * authMiddleware,\n * ]);\n *\n * @param middlewares - An array of middleware functions to execute in order.\n * @returns A single middleware function that runs all provided middlewares.\n */\nexport const multipleProxy =\n (\n middlewares: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store middleware headers\n const middlewareHeader: Headers[] = [];\n\n // Loop through middleware functions\n for (const middleware of middlewares) {\n // Execute middleware function and await the result\n const result = await middleware(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push middleware headers to the array\n middlewareHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the middlewares\n const transmittedHeaders = new Headers();\n\n // Merge headers\n middlewareHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the middlewares\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the middleware headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next middleware\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n\nexport const multipleMiddlewares = multipleProxy;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,iBAET,gBAMF,OAAO,KAAkB,OAAwB,aAA4B;CAE3E,MAAMA,mBAA8B,EAAE;AAGtC,MAAK,MAAM,cAAc,aAAa;EAEpC,MAAM,SAAS,MAAM,WAAW,KAAK,OAAO,SAAS;AAGrD,MAAI,CAAC,OAAO,GACV,QAAO;AAIT,mBAAiB,KAAK,OAAO,QAAQ;;CAIvC,MAAM,gBAAgB,IAAI,SAAS;CAGnC,MAAM,qBAAqB,IAAI,SAAS;AAGxC,kBAAiB,SAAS,WAAW;AACnC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,SAAS,EAAE;AAC3C,iBAAc,OAAO,KAAK,MAAM;AAGhC,OAAI,IAAI,WAAW,wBAAwB,EAAE;IAE3C,MAAM,WAAW,IAAI,QAAQ,yBAAyB,GAAG;AAGzD,uBAAmB,OAAO,UAAU,MAAM;;;GAG9C;CAGF,MAAM,WAAW,cAAc,IAAI,gCAAgC;AAGnE,KAAI,SAEF,QAAOC,yBAAa,SAAS,IAAI,IAAI,UAAU,IAAI,IAAI,EAAE,EACvD,QAAQ,KACT,CAAC;CAIJ,MAAM,UAAU,cAAc,IAAI,uBAAuB;AACzD,KAAI,QAEF,QAAOA,yBAAa,QAAQ,IAAI,IAAI,SAAS,IAAI,IAAI,EAAE,EACrD,SAAS,EACP,SAAS,oBACV,EACF,CAAC;AAIJ,QAAOA,yBAAa,KAAK,EACvB,SAAS,EACP,SAAS,oBACV,EACF,CAAC;;AAGN,MAAa,sBAAsB"}
|