next-intlayer 8.1.7 → 8.1.8
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/proxy/intlayerProxy.cjs +1 -1
- package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
- package/dist/cjs/proxy/multipleProxies.cjs +1 -1
- package/dist/cjs/proxy/multipleProxies.cjs.map +1 -1
- package/dist/cjs/server/withIntlayer.cjs +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
- package/dist/esm/proxy/multipleProxies.mjs +1 -1
- package/dist/esm/proxy/multipleProxies.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./localeDetector.cjs`);let n=require(`@intlayer/config/built`);n=e.__toESM(n);let r=require(`@intlayer/core/localization`),i=require(`@intlayer/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./localeDetector.cjs`);let n=require(`@intlayer/config/built`);n=e.__toESM(n);let r=require(`@intlayer/core/localization`),i=require(`@intlayer/core/utils`),a=require(`@intlayer/config/client`),o=require(`next/server`);const{internationalization:s,routing:c}=n.default??{},{locales:l,defaultLocale:u}=s??{},{basePath:d,mode:f,rewrite:p}=c??{},m=f??a.DefaultValues.Routing.ROUTING_MODE,h=m===`no-prefix`||m===`search-params`,g=m===`prefix-all`,_=!h,v=(0,r.getRewriteRules)(p,`url`),y=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},b=(e,t)=>{if(m!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},x=(e,t,n)=>{let r=e.nextUrl.pathname,i=S(e);return h?C(e,i,r):T(e,i,w(r),r)},S=e=>(0,i.getLocaleFromStorage)({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),C=(e,n,i)=>{let a=w(i);if(a){let t=(0,r.getCanonicalPath)(i.slice(`/${a}`.length)||`/`,a,v),n=b(e.nextUrl.search,a);return M(e,n?`${t}${n}`:`${t}${e.nextUrl.search??``}`)}if(m===`search-params`){let a=new URLSearchParams(e.nextUrl.search).get(`locale`),o=l?.includes(a),s=n??(o?a:void 0)??t.localeDetector?.(e)??u;l?.includes(s)||(s=u);let c=(0,r.getCanonicalPath)(i,s,v);if(a===s)return j(e,`${_?`/${s}${c}`:c}${e.nextUrl.search??``}`,s);let d=b(e.nextUrl.search,s);return M(e,d?`${i}${d}`:`${i}${e.nextUrl.search??``}`)}let o=n??t.localeDetector?.(e)??u;l?.includes(o)||(o=u);let s=(0,r.getCanonicalPath)(i,o,v),c=_?`/${o}${s}`:s,d=b(e.nextUrl.search,o);return j(e,d?`${c}${d}`:`${c}${e.nextUrl.search??``}`,o)},w=e=>l.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),T=(e,t,n,r)=>n?D(e,t,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,n,i)=>{let a=n??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,r.getCanonicalPath)(i,a,v),s=(0,r.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=A(a,c,d,b(e.nextUrl.search,a));return g||a!==u?M(e,f):j(e,_?`/${a}${o}`:o,a)},D=(e,t,n,i)=>{let a=i.slice(`/${n}`.length)||`/`,o=(0,r.getCanonicalPath)(a,n,v);if(t&&t!==n)return M(e,O(e,o,t,d));let s=(0,r.getLocalizedPath)(o,n,v),c=typeof s==`string`?s:s.path;if(typeof s!=`string`&&s.isRewritten&&c!==a)return M(e,A(n,c,d,b(e.nextUrl.search,n)));let l=_?`/${n}${o}`:o;if(!g&&n===u)return k(e,n,i);let f=e.nextUrl.search;return j(e,l+(f??``),n)},O=(e,t,n,i)=>{let a=(0,r.getLocalizedPath)(t,n,v);return A(n,typeof a==`string`?a:a.path,i,b(e.nextUrl.search,n))},k=(e,t,n)=>{if(!g&&t===u){let i=(0,r.getLocalizedPath)(n,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),M(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${n}`:n;return j(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},A=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(m===`no-prefix`||m===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},j=(e,t,n)=>{let r=e.nextUrl.search,a=r&&!t.includes(`?`)?`${t}${r}`:t;console.log(`[intlayerProxy] Rewriting to ${a} with locale ${n}`);let s=new Headers(e.headers);(0,i.setLocaleInStorage)(n,{setHeader:(e,t)=>{s.set(e,t)}});let c=new URL(a,e.url),l=c.href===e.nextUrl.href?o.NextResponse.next({request:{headers:s}}):o.NextResponse.rewrite(c,{request:{headers:s}});return(0,i.setLocaleInStorage)(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},M=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return o.NextResponse.redirect(new URL(r,e.url))};exports.intlayerProxy=x;
|
|
2
2
|
//# sourceMappingURL=intlayerProxy.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxy.cjs","names":["configuration","DefaultValues","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\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 (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy 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 intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\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 getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n const locale = localLocale ?? defaultLocale;\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // Resolve the internal canonical path\n // If user visits /a-propos (no prefix), and we detect 'fr', we resolve to /about\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as 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 as Locale[]).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 localLocale - 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 localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, localLocale, pathLocale, pathname);\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 localLocale - 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 localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, 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 const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\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 localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\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 localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\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 basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, 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 [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 search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const response = NextResponse.rewrite(new URL(pathWithSearch, request.url), {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\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 const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"8VA+CA,KAAM,CAAE,uBAAsB,WAAYA,EAAAA,SAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQC,EAAAA,cAAc,QAAQ,aAC9C,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,GAAA,EAAA,EAAA,iBAA+B,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,C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AAK,MAAM,IAAI,IAAS,OAAO,EAAI,IACnC,EAEJ,GAAI,IAAkB,aAAe,IAAkB,gBACrD,MAAO,GAAG,IAAoB,EAAS,IAAI,IAAW,KAIxD,IAAM,EAAuB,EAAK,WAAW,IAAI,IAAS,CACtD,EACA,GAAG,IAAS,EAAK,WAAW,IAAI,CAAG,GAAK,MAAM,IAQlD,MALgB,GAAG,IADW,EAAS,SAAS,IAAI,CACE,GAAK,MAAM,IAGvC,QAAQ,OAAQ,IAAI,EAU1C,GACJ,EACA,EACA,IACiB,CACjB,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAEvD,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,EACnD,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAWC,EAAAA,aAAa,QAAQ,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAE,CAC1E,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOF,OALA,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAC7D,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
|
|
1
|
+
{"version":3,"file":"intlayerProxy.cjs","names":["configuration","DefaultValues","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\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 (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy 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 intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\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 getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as 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 as Locale[]).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 localLocale - 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 localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, localLocale, pathLocale, pathname);\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 localLocale - 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 localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, 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 const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\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 localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\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 localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\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 basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, 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 [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 search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n console.log(\n `[intlayerProxy] Rewriting to ${pathWithSearch} with locale ${locale}`\n );\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\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 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":"8VA+CA,KAAM,CAAE,uBAAsB,WAAYA,EAAAA,SAAiB,EAA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C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/BC,EAAAA,aAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACFA,EAAAA,aAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`next/server`);const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers;a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.NextResponse.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.NextResponse.rewrite(new URL(l,n.url),{request:{headers:s}}):e.NextResponse.next({request:{headers:s}})};exports.multipleProxies=t;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`next/server`);const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers(n.headers);a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.NextResponse.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.NextResponse.rewrite(new URL(l,n.url),{request:{headers:s}}):e.NextResponse.next({request:{headers:s}})};exports.multipleProxies=t;
|
|
2
2
|
//# sourceMappingURL=multipleProxies.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\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 multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\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 proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(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 proxy headers to the array\n proxyHeader.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 proxies\n const transmittedHeaders = new Headers();\n\n // Merge headers\n proxyHeader.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 proxies\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 proxy 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 proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"6IA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,
|
|
1
|
+
{"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\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 multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\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 proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(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 proxy headers to the array\n proxyHeader.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 proxies\n const transmittedHeaders = new Headers(req.headers);\n\n // Merge headers\n proxyHeader.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 proxies\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 proxy 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 proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"6IA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAAQ,EAAI,QAAQ,CAGnD,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEKA,EAAAA,aAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIGA,EAAAA,aAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`node:path`),n=require(`@intlayer/chokidar/build`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/config/client`),a=require(`@intlayer/config/logger`),o=require(`@intlayer/config/node`),s=require(`@intlayer/config/utils`),c=require(`@intlayer/dictionaries-entry`),l=require(`@intlayer/webpack`),u=require(`defu`),d=require(`next/package.json`);d=e.__toESM(d);const f=(0,s.compareVersions)(d.default.version,`≥`,`13.0.0`),p=(0,s.compareVersions)(d.default.version,`≥`,`15.0.0`),m=(0,s.compareVersions)(d.default.version,`≥`,`16.0.0`),h=(0,s.compareVersions)(d.default.version,`≥`,`15.3.0`),g=m?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),_=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/swc`),!0}catch{return!1}},v=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/babel`),!0}catch{return!1}},y=(e,n,r)=>{let i=(n.build?.require??(0,s.getProjectRequire)())?.resolve(e);return r?(0,s.normalizePath)(`./${(0,t.relative)(process.cwd(),i)}`):i},b=(e,n,o,s)=>{let{optimize:l}=e.build,u=e.build.importMode??e.dictionary?.importMode,{dictionariesDir:d,unmergedDictionariesDir:p,dynamicDictionariesDir:m,fetchDictionariesDir:h,mainDir:g}=e.system,{baseDir:b}=e.content,x=(0,a.getAppLogger)(e);if(l===!1||l===void 0&&!n||!f)return{};let S=_(e);if((0,r.runOnce)((0,t.join)(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[(0,a.colorize)(`Recommended: Install`,a.ANSIColors.GREY),(0,a.colorize)(`@intlayer/swc`,a.ANSIColors.GREY_LIGHT),(0,a.colorize)(`package to enable build optimization. See documentation: `,a.ANSIColors.GREY),(0,a.colorize)(`https://intlayer.org/docs/en/bundle_optimization`,a.ANSIColors.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),(0,r.runOnce)((0,t.join)(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(v(e)){let t=e.compiler?.enabled??!0;t===`build-only`&&(t=!s),x(t?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!S)return{};let C=(0,t.join)(g,`dictionaries.mjs`),w=(0,t.join)(g,`dynamic_dictionaries.mjs`),T=(0,t.join)(g,`unmerged_dictionaries.mjs`),E=(0,t.join)(g,`fetch_dictionaries.mjs`),D=[...(0,r.getComponentTransformPatternSync)(e),C,T],O=(0,c.getDictionaries)(e),k={};return Object.values(O).forEach(e=>{k[e.key]=e.importMode??u??i.DefaultValues.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[y(`@intlayer/swc`,e,o),{dictionariesDir:d,dictionariesEntryPath:C,unmergedDictionariesEntryPath:T,unmergedDictionariesDir:p,dynamicDictionariesDir:m,dynamicDictionariesEntryPath:w,fetchDictionariesDir:h,fetchDictionariesEntryPath:E,importMode:u,filesList:D,replaceDictionaryEntry:!0,dictionaryModeMap:k}]]}}},x=()=>{let e=process.env.npm_lifecycle_event,t=process.env.npm_lifecycle_script??``;return{isDevCommand:e===`dev`||process.argv.some(e=>e===`dev`)||/(^|\s)(next\s+)?dev(\s|$)/.test(t),isBuildCommand:e===`build`||process.argv.some(e=>e===`build`)||/(^|\s)(next\s+)?build(\s|$)/.test(t),isStartCommand:e===`start`||process.argv.some(e=>e===`start`)||/(^|\s)(next\s+)?start(\s|$)/.test(t)}},S=(e={},n)=>{typeof e!=`object`&&(e={});let r=(0,o.getConfiguration)(n),i=(0,a.getAppLogger)(r),c=n?.enableTurbopack??g;c&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:d,isDevCommand:m}=x(),_={resolveAlias:(0,s.getAlias)({configuration:r,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},v=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],y=()=>{let n={};return p&&(n={...n,serverExternalPackages:v}),f&&!p&&(n={...n,experimental:{...n?.experimental??{},serverComponentsExternalPackages:v}}),n=c?p&&h?{...n,turbopack:_}:{...n,experimental:{...n?.experimental??{},turbo:_}}:{...n,webpack:(n,i)=>{let{isServer:a,nextRuntime:o}=i;return typeof e.webpack==`function`&&(n=e.webpack(n,i)),n.externals===!1&&(n.externals=[]),n.externals.push({esbuild:`esbuild`,module:`module`,fs:`fs`,chokidar:`chokidar`,fsevents:`fsevents`}),n.module.rules.push({test:/\.node$/,loader:`node-loader`}),n.resolve.alias={...n.resolve.alias,...(0,s.getAlias)({configuration:r,formatter:e=>(0,t.resolve)(e)})},m&&a&&o===`nodejs`&&n.plugins.push(new l.IntlayerPlugin(r)),n}},n},S=b(r,d,c??!1,m);return(0,u.defu)((0,u.defu)(y(),S),e)},C=async(e={},t)=>{let{isBuildCommand:r,isDevCommand:i,isStartCommand:a}=x();process.env.INTLAYER_IS_DEV_COMMAND=i?`true`:`false`;let s=(0,o.getConfiguration)(t),{mode:c}=s.build;return!a&&(i||r||c===`auto`)&&await(0,n.prepareIntlayer)(s,{clean:r,cacheTimeoutMs:r?1e3*30:1e3*60*60}),S(await e,t)};exports.withIntlayer=C,exports.withIntlayerSync=S;
|
|
2
2
|
//# sourceMappingURL=withIntlayer.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{localeDetector as e}from"./localeDetector.mjs";import t from"@intlayer/config/built";import{getCanonicalPath as n,getLocalizedPath as r,getRewriteRules as i}from"@intlayer/core/localization";import{DefaultValues as a}from"@intlayer/config/client";import{getLocaleFromStorage as o,setLocaleInStorage as s}from"@intlayer/core/utils";import{NextResponse as c}from"next/server";const{internationalization:l,routing:u}=t??{},{locales:d,defaultLocale:f}=l??{},{basePath:p,mode:m,rewrite:h}=u??{},g=m??a.Routing.ROUTING_MODE,_=g===`no-prefix`||g===`search-params`,v=g===`prefix-all`,y=!_,b=i(h,`url`),x=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},S=(e,t)=>{if(g!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},C=(e,t,n)=>{let r=e.nextUrl.pathname,i=w(e);return _?T(e,i,r):D(e,i,E(r),r)},w=e=>o({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),T=(
|
|
1
|
+
import{localeDetector as e}from"./localeDetector.mjs";import t from"@intlayer/config/built";import{getCanonicalPath as n,getLocalizedPath as r,getRewriteRules as i}from"@intlayer/core/localization";import{DefaultValues as a}from"@intlayer/config/client";import{getLocaleFromStorage as o,setLocaleInStorage as s}from"@intlayer/core/utils";import{NextResponse as c}from"next/server";const{internationalization:l,routing:u}=t??{},{locales:d,defaultLocale:f}=l??{},{basePath:p,mode:m,rewrite:h}=u??{},g=m??a.Routing.ROUTING_MODE,_=g===`no-prefix`||g===`search-params`,v=g===`prefix-all`,y=!_,b=i(h,`url`),x=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},S=(e,t)=>{if(g!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},C=(e,t,n)=>{let r=e.nextUrl.pathname,i=w(e);return _?T(e,i,r):D(e,i,E(r),r)},w=e=>o({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),T=(t,r,i)=>{let a=E(i);if(a){let e=n(i.slice(`/${a}`.length)||`/`,a,b),r=S(t.nextUrl.search,a);return P(t,r?`${e}${r}`:`${e}${t.nextUrl.search??``}`)}if(g===`search-params`){let a=new URLSearchParams(t.nextUrl.search).get(`locale`),o=d?.includes(a),s=r??(o?a:void 0)??e?.(t)??f;d?.includes(s)||(s=f);let c=n(i,s,b);if(a===s)return N(t,`${y?`/${s}${c}`:c}${t.nextUrl.search??``}`,s);let l=S(t.nextUrl.search,s);return P(t,l?`${i}${l}`:`${i}${t.nextUrl.search??``}`)}let o=r??e?.(t)??f;d?.includes(o)||(o=f);let s=n(i,o,b),c=y?`/${o}${s}`:s,l=S(t.nextUrl.search,o);return N(t,l?`${c}${l}`:`${c}${t.nextUrl.search??``}`,o)},E=e=>d.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),D=(e,t,n,r)=>n?k(e,t,n,r):x(e)?O(e,f,r):O(e,t,r),O=(t,i,a)=>{let o=i??e?.(t)??f;d.includes(o)||(o=f);let s=n(a,o,b),c=r(s,o,b),l=typeof c==`string`?c:c.path,u=M(o,l,p,S(t.nextUrl.search,o));return v||o!==f?P(t,u):N(t,y?`/${o}${s}`:s,o)},k=(e,t,i,a)=>{let o=a.slice(`/${i}`.length)||`/`,s=n(o,i,b);if(t&&t!==i)return P(e,A(e,s,t,p));let c=r(s,i,b),l=typeof c==`string`?c:c.path;if(typeof c!=`string`&&c.isRewritten&&l!==o)return P(e,M(i,l,p,S(e.nextUrl.search,i)));let u=y?`/${i}${s}`:s;if(!v&&i===f)return j(e,i,a);let d=e.nextUrl.search;return N(e,u+(d??``),i)},A=(e,t,n,i)=>{let a=r(t,n,b);return M(n,typeof a==`string`?a:a.path,i,S(e.nextUrl.search,n))},j=(e,t,n)=>{if(!v&&t===f){let i=r(n,t,b),a=typeof i==`string`?i:i.path,o=p.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),P(e,`${p}${o?``:`/`}${s}`+(S(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=S(e.nextUrl.search,t),a=y?`/${t}${n}`:n;return N(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},M=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(g===`no-prefix`||g===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},N=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t;console.log(`[intlayerProxy] Rewriting to ${i} with locale ${n}`);let a=new Headers(e.headers);s(n,{setHeader:(e,t)=>{a.set(e,t)}});let o=new URL(i,e.url),l=o.href===e.nextUrl.href?c.next({request:{headers:a}}):c.rewrite(o,{request:{headers:a}});return s(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},P=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return c.redirect(new URL(r,e.url))};export{C as intlayerProxy};
|
|
2
2
|
//# sourceMappingURL=intlayerProxy.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\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 (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy 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 intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\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 getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n const locale = localLocale ?? defaultLocale;\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // Resolve the internal canonical path\n // If user visits /a-propos (no prefix), and we detect 'fr', we resolve to /about\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as 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 as Locale[]).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 localLocale - 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 localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, localLocale, pathLocale, pathname);\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 localLocale - 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 localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, 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 const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\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 localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\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 localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\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 basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, 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 [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 search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const response = NextResponse.rewrite(new URL(pathWithSearch, request.url), {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\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 const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"6XA+CA,KAAM,CAAE,uBAAsB,WAAY,GAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQ,EAAc,QAAQ,aAC9C,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,EAAe,EAAgB,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OACE,IAAY,YACZ,IAAuB,KACvB,CAAC,CAAC,GACF,CAAC,CAAC,GAKA,GACJ,EACA,IACuB,CACvB,GAAI,IAAkB,gBAAiB,OAAO,EAC9C,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAEhD,OADA,EAAO,IAAI,SAAU,EAAO,CACrB,IAAI,EAAO,UAAU,IA0BjB,GACX,EACA,EACA,IACiB,CACjB,IAAM,EAAW,EAAQ,QAAQ,SAC3B,EAAc,EAAe,EAAQ,CAO3C,OALI,EACK,EAAe,EAAS,EAAa,EAAS,CAIhD,EAAa,EAAS,EADV,EAAc,EAAS,CACY,EAAS,EAS3D,EAAkB,GACtB,EAAqB,CACnB,UAAY,GAAiB,EAAQ,QAAQ,IAAI,EAAK,EAAE,OAAS,KACjE,UAAY,GAAiB,EAAQ,QAAQ,IAAI,EAAK,EAAI,KAC3D,CAAC,CAKE,GACJ,EACA,EACA,IACiB,CACjB,I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K,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAC7D,OAAO,EAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
|
|
1
|
+
{"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\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 (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy 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 intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\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 getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as 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 as Locale[]).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 localLocale - 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 localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, localLocale, pathLocale, pathname);\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 localLocale - 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 localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, 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 const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\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 localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\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 localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\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 basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, 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 [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 search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n console.log(\n `[intlayerProxy] Rewriting to ${pathWithSearch} with locale ${locale}`\n );\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\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 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":"6XA+CA,KAAM,CAAE,uBAAsB,WAAY,GAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQ,EAAc,QAAQ,aAC9C,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,EAAe,EAAgB,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OACE,IAAY,YACZ,IAAuB,KACvB,CAAC,CAAC,GACF,CAAC,CAAC,GAKA,GACJ,EACA,IACuB,CACvB,GAAI,IAAkB,gBAAiB,OAAO,EAC9C,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAEhD,OADA,EAAO,IAAI,SAAU,EAAO,CACrB,IAAI,EAAO,UAAU,IA0BjB,GACX,EACA,EACA,IACiB,CACjB,IAAM,EAAW,EAAQ,QAAQ,SAE3B,EAAc,EAAe,EAAQ,CAO3C,OALI,EACK,EAAe,EAAS,EAAa,EAAS,CAIhD,EAAa,EAAS,EADV,EAAc,EAAS,CACY,EAAS,EAS3D,EAAkB,GACtB,EAAqB,CACnB,UA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AAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,QAAQ,IACN,gCAAgC,EAAe,eAAe,IAC/D,CAED,IAAM,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,CACnD,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/B,EAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACF,EAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAO,EAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{NextResponse as e}from"next/server";const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers;a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.rewrite(new URL(l,n.url),{request:{headers:s}}):e.next({request:{headers:s}})};export{t as multipleProxies};
|
|
1
|
+
import{NextResponse as e}from"next/server";const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers(n.headers);a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.rewrite(new URL(l,n.url),{request:{headers:s}}):e.next({request:{headers:s}})};export{t as multipleProxies};
|
|
2
2
|
//# sourceMappingURL=multipleProxies.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipleProxies.mjs","names":[],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\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 multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\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 proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(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 proxy headers to the array\n proxyHeader.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 proxies\n const transmittedHeaders = new Headers();\n\n // Merge headers\n proxyHeader.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 proxies\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 proxy 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 proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"2CA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,
|
|
1
|
+
{"version":3,"file":"multipleProxies.mjs","names":[],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\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 multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\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 proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(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 proxy headers to the array\n proxyHeader.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 proxies\n const transmittedHeaders = new Headers(req.headers);\n\n // Merge headers\n proxyHeader.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 proxies\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 proxy 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 proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"2CA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAAQ,EAAI,QAAQ,CAGnD,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAO,EAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEK,EAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIG,EAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-intlayer",
|
|
3
|
-
"version": "8.1.
|
|
3
|
+
"version": "8.1.8",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Simplify internationalization i18n in Next.js with context providers, hooks, locale detection, and multilingual content integration.",
|
|
6
6
|
"keywords": [
|
|
@@ -124,15 +124,15 @@
|
|
|
124
124
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
125
125
|
},
|
|
126
126
|
"dependencies": {
|
|
127
|
-
"@intlayer/chokidar": "8.1.
|
|
128
|
-
"@intlayer/config": "8.1.
|
|
129
|
-
"@intlayer/core": "8.1.
|
|
130
|
-
"@intlayer/dictionaries-entry": "8.1.
|
|
131
|
-
"@intlayer/types": "8.1.
|
|
132
|
-
"@intlayer/webpack": "8.1.
|
|
127
|
+
"@intlayer/chokidar": "8.1.8",
|
|
128
|
+
"@intlayer/config": "8.1.8",
|
|
129
|
+
"@intlayer/core": "8.1.8",
|
|
130
|
+
"@intlayer/dictionaries-entry": "8.1.8",
|
|
131
|
+
"@intlayer/types": "8.1.8",
|
|
132
|
+
"@intlayer/webpack": "8.1.8",
|
|
133
133
|
"defu": "6.1.4",
|
|
134
134
|
"node-loader": "2.1.0",
|
|
135
|
-
"react-intlayer": "8.1.
|
|
135
|
+
"react-intlayer": "8.1.8"
|
|
136
136
|
},
|
|
137
137
|
"devDependencies": {
|
|
138
138
|
"@types/node": "25.3.0",
|