next-intlayer 8.4.4 → 8.4.6

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.
Files changed (72) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -1
  2. package/dist/cjs/client/IntlayerClientProvider.cjs +36 -1
  3. package/dist/cjs/client/IntlayerClientProvider.cjs.map +1 -1
  4. package/dist/cjs/client/format/index.cjs +9 -1
  5. package/dist/cjs/client/index.cjs +16 -1
  6. package/dist/cjs/client/useLocale.cjs +71 -1
  7. package/dist/cjs/client/useLocale.cjs.map +1 -1
  8. package/dist/cjs/client/useLocalePageRouter.cjs +45 -1
  9. package/dist/cjs/client/useLocalePageRouter.cjs.map +1 -1
  10. package/dist/cjs/client/useRewriteURL.cjs +12 -1
  11. package/dist/cjs/generateStaticParams.cjs +29 -1
  12. package/dist/cjs/generateStaticParams.cjs.map +1 -1
  13. package/dist/cjs/index.cjs +132 -1
  14. package/dist/cjs/proxy/index.cjs +8 -1
  15. package/dist/cjs/proxy/intlayerProxy.cjs +249 -1
  16. package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
  17. package/dist/cjs/proxy/localeDetector.cjs +20 -1
  18. package/dist/cjs/proxy/localeDetector.cjs.map +1 -1
  19. package/dist/cjs/proxy/middleware.cjs +37 -1
  20. package/dist/cjs/proxy/middleware.cjs.map +1 -1
  21. package/dist/cjs/proxy/multipleProxies.cjs +57 -1
  22. package/dist/cjs/proxy/multipleProxies.cjs.map +1 -1
  23. package/dist/cjs/server/format/index.cjs +9 -1
  24. package/dist/cjs/server/getLocale.cjs +48 -1
  25. package/dist/cjs/server/getLocale.cjs.map +1 -1
  26. package/dist/cjs/server/index.cjs +75 -1
  27. package/dist/cjs/server/useDictionary.cjs +17 -1
  28. package/dist/cjs/server/useDictionary.cjs.map +1 -1
  29. package/dist/cjs/server/useDictionaryAsync.cjs +17 -1
  30. package/dist/cjs/server/useDictionaryAsync.cjs.map +1 -1
  31. package/dist/cjs/server/useDictionaryDynamic.cjs +17 -1
  32. package/dist/cjs/server/useDictionaryDynamic.cjs.map +1 -1
  33. package/dist/cjs/server/useIntlayer.cjs +29 -1
  34. package/dist/cjs/server/useIntlayer.cjs.map +1 -1
  35. package/dist/cjs/server/withIntlayer.cjs +258 -1
  36. package/dist/cjs/server/withIntlayer.cjs.map +1 -1
  37. package/dist/esm/client/IntlayerClientProvider.mjs +34 -1
  38. package/dist/esm/client/IntlayerClientProvider.mjs.map +1 -1
  39. package/dist/esm/client/format/index.mjs +1 -1
  40. package/dist/esm/client/index.mjs +6 -1
  41. package/dist/esm/client/useLocale.mjs +69 -1
  42. package/dist/esm/client/useLocale.mjs.map +1 -1
  43. package/dist/esm/client/useLocalePageRouter.mjs +43 -1
  44. package/dist/esm/client/useLocalePageRouter.mjs.map +1 -1
  45. package/dist/esm/client/useRewriteURL.mjs +5 -1
  46. package/dist/esm/generateStaticParams.mjs +26 -1
  47. package/dist/esm/generateStaticParams.mjs.map +1 -1
  48. package/dist/esm/index.mjs +8 -1
  49. package/dist/esm/proxy/index.mjs +5 -1
  50. package/dist/esm/proxy/intlayerProxy.mjs +246 -1
  51. package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
  52. package/dist/esm/proxy/localeDetector.mjs +18 -1
  53. package/dist/esm/proxy/localeDetector.mjs.map +1 -1
  54. package/dist/esm/proxy/middleware.mjs +35 -1
  55. package/dist/esm/proxy/middleware.mjs.map +1 -1
  56. package/dist/esm/proxy/multipleProxies.mjs +55 -1
  57. package/dist/esm/proxy/multipleProxies.mjs.map +1 -1
  58. package/dist/esm/server/format/index.mjs +1 -1
  59. package/dist/esm/server/getLocale.mjs +45 -1
  60. package/dist/esm/server/getLocale.mjs.map +1 -1
  61. package/dist/esm/server/index.mjs +5 -1
  62. package/dist/esm/server/useDictionary.mjs +15 -1
  63. package/dist/esm/server/useDictionary.mjs.map +1 -1
  64. package/dist/esm/server/useDictionaryAsync.mjs +15 -1
  65. package/dist/esm/server/useDictionaryAsync.mjs.map +1 -1
  66. package/dist/esm/server/useDictionaryDynamic.mjs +15 -1
  67. package/dist/esm/server/useDictionaryDynamic.mjs.map +1 -1
  68. package/dist/esm/server/useIntlayer.mjs +25 -1
  69. package/dist/esm/server/useIntlayer.mjs.map +1 -1
  70. package/dist/esm/server/withIntlayer.mjs +253 -1
  71. package/dist/esm/server/withIntlayer.mjs.map +1 -1
  72. package/package.json +8 -8
@@ -1,2 +1,250 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./localeDetector.cjs`);let n=require(`@intlayer/core/localization`),r=require(`@intlayer/config/built`);r=e.__toESM(r);let i=require(`@intlayer/config/defaultValues`),a=require(`@intlayer/core/utils`),o=require(`next/server`);const{internationalization:s,routing:c}=r.default??{},{locales:l,defaultLocale:u}=s??{},{basePath:d,mode:f,rewrite:p}=c??{},m=f??i.ROUTING_MODE,h=m===`no-prefix`||m===`search-params`,g=m===`prefix-all`,_=!h,v=(0,n.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,a.getLocaleFromStorage)({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),C=(e,r,i)=>{let a=w(i);if(a){let t=(0,n.getCanonicalPath)(i.slice(`/${a}`.length)||`/`,a,v),r=b(e.nextUrl.search,a);return j(e,r?`${t}${r}`:`${t}${e.nextUrl.search??``}`)}if(m===`search-params`){let a=new URLSearchParams(e.nextUrl.search).get(`locale`),o=l?.includes(a),s=r??(o?a:void 0)??r??t.localeDetector?.(e)??u;l?.includes(s)||(s=u);let c=(0,n.getCanonicalPath)(i,s,v);if(a===s)return A(e,`${_?`/${s}${c}`:c}${e.nextUrl.search??``}`,s);let d=b(e.nextUrl.search,s);return j(e,d?`${i}${d}`:`${i}${e.nextUrl.search??``}`)}let o=r??t.localeDetector?.(e)??u;l?.includes(o)||(o=u);let s=(0,n.getCanonicalPath)(i,o,v),c=_?`/${o}${s}`:s,d=b(e.nextUrl.search,o);return A(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,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,r,i)=>{let a=r??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,n.getCanonicalPath)(i,a,v),s=(0,n.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=k(a,c,d,b(e.nextUrl.search,a));return g||a!==u?j(e,f):A(e,_?`/${a}${o}`:o,a)},D=(e,t,r)=>{let i=r.slice(`/${t}`.length)||`/`,a=(0,n.getCanonicalPath)(i,t,v),o=(0,n.getLocalizedPath)(a,t,v),s=typeof o==`string`?o:o.path;if(typeof o!=`string`&&o.isRewritten&&s!==i)return j(e,k(t,s,d,b(e.nextUrl.search,t)));let c=_?`/${t}${a}`:a;if(!g&&t===u)return O(e,t,r);let l=e.nextUrl.search;return A(e,c+(l??``),t)},O=(e,t,r)=>{if(!g&&t===u){let i=(0,n.getLocalizedPath)(r,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),j(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${r}`:r;return A(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},k=(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,`/`)},A=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t,s=new Headers(e.headers);(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{s.set(e,t)}});let c=new URL(i,e.url),l=c.href===e.nextUrl.href?o.NextResponse.next({request:{headers:s}}):o.NextResponse.rewrite(c,{request:{headers:s}});return(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},j=(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;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ const require_proxy_localeDetector = require('./localeDetector.cjs');
4
+ let _intlayer_core_localization = require("@intlayer/core/localization");
5
+ let _intlayer_config_built = require("@intlayer/config/built");
6
+ _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
7
+ let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
8
+ let _intlayer_core_utils = require("@intlayer/core/utils");
9
+ let next_server = require("next/server");
10
+
11
+ //#region src/proxy/intlayerProxy.ts
12
+ const { internationalization, routing } = _intlayer_config_built.default ?? {};
13
+ const { locales, defaultLocale } = internationalization ?? {};
14
+ const { basePath, mode, rewrite } = routing ?? {};
15
+ const effectiveMode = mode ?? _intlayer_config_defaultValues.ROUTING_MODE;
16
+ const noPrefix = effectiveMode === "no-prefix" || effectiveMode === "search-params";
17
+ const prefixDefault = effectiveMode === "prefix-all";
18
+ const internalPrefix = !noPrefix;
19
+ const rewriteRules = (0, _intlayer_core_localization.getRewriteRules)(rewrite, "url");
20
+ /**
21
+ * Detects if the request is a prefetch request from Next.js.
22
+ *
23
+ * Next.js prefetch requests can be identified by several headers:
24
+ * - purpose: 'prefetch' (standard prefetch header)
25
+ * - next-router-prefetch: '1' (Next.js router prefetch)
26
+ * - next-url: present (Next.js internal navigation)
27
+ *
28
+ * During prefetch, we should ignore cookie-based locale detection
29
+ * to prevent unwanted redirects when users are switching locales.
30
+ *
31
+ * @param request - The incoming Next.js request object.
32
+ * @returns - True if the request is a prefetch request, false otherwise.
33
+ */
34
+ const isPrefetchRequest = (request) => {
35
+ const purpose = request.headers.get("purpose");
36
+ const nextRouterPrefetch = request.headers.get("next-router-prefetch");
37
+ const nextUrl = request.headers.get("next-url");
38
+ const xNextjsData = request.headers.get("x-nextjs-data");
39
+ return purpose === "prefetch" || nextRouterPrefetch === "1" || !!nextUrl || !!xNextjsData;
40
+ };
41
+ const appendLocaleSearchIfNeeded = (search, locale) => {
42
+ if (effectiveMode !== "search-params") return search;
43
+ const params = new URLSearchParams(search ?? "");
44
+ params.set("locale", locale);
45
+ return `?${params.toString()}`;
46
+ };
47
+ /**
48
+ * Proxy that handles the internationalization layer
49
+ *
50
+ * Usage:
51
+ *
52
+ * ```ts
53
+ * // ./src/proxy.ts
54
+ *
55
+ * export { intlayerProxy as proxy } from '@intlayer/next/proxy';
56
+ *
57
+ * // applies this proxy only to files in the app directory
58
+ * export const config = {
59
+ * matcher: '/((?!api|static|.*\\..*|_next).*)',
60
+ * };
61
+ * ```
62
+ *
63
+ * Main proxy function for handling internationalization.
64
+ *
65
+ * @param request - The incoming Next.js request object.
66
+ * @param event - The Next.js fetch event (optional).
67
+ * @param response - The Next.js response object (optional).
68
+ * @returns - The response to be returned to the client.
69
+ */
70
+ const intlayerProxy = (request, _event, _response) => {
71
+ const pathname = request.nextUrl.pathname;
72
+ const localLocale = getLocalLocale(request);
73
+ if (noPrefix) return handleNoPrefix(request, localLocale, pathname);
74
+ return handlePrefix(request, localLocale, getPathLocale(pathname), pathname);
75
+ };
76
+ /**
77
+ * Retrieves the locale from the request cookies if available and valid.
78
+ *
79
+ * @param request - The incoming Next.js request object.
80
+ * @returns - The locale found in the cookies, or undefined if not found or invalid.
81
+ */
82
+ const getLocalLocale = (request) => (0, _intlayer_core_utils.getLocaleFromStorage)({
83
+ getCookie: (name) => request.cookies.get(name)?.value ?? null,
84
+ getHeader: (name) => request.headers.get(name) ?? null
85
+ });
86
+ /**
87
+ * Handles the case where URLs do not have locale prefixes.
88
+ */
89
+ const handleNoPrefix = (request, localLocale, pathname) => {
90
+ const pathLocale = getPathLocale(pathname);
91
+ if (pathLocale) {
92
+ const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname.slice(`/${pathLocale}`.length) || "/", pathLocale, rewriteRules);
93
+ const search = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
94
+ return redirectUrl(request, search ? `${canonicalPath}${search}` : `${canonicalPath}${request.nextUrl.search ?? ""}`);
95
+ }
96
+ if (effectiveMode === "search-params") {
97
+ const existingLocale = new URLSearchParams(request.nextUrl.search).get("locale");
98
+ const isExistingValid = locales?.includes(existingLocale);
99
+ let locale = localLocale ?? (isExistingValid ? existingLocale : void 0) ?? localLocale ?? require_proxy_localeDetector.localeDetector?.(request) ?? defaultLocale;
100
+ if (!locales?.includes(locale)) locale = defaultLocale;
101
+ const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname, locale, rewriteRules);
102
+ if (existingLocale === locale) return rewriteUrl(request, `${internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath}${request.nextUrl.search ?? ""}`, locale);
103
+ const search = appendLocaleSearchIfNeeded(request.nextUrl.search, locale);
104
+ return redirectUrl(request, search ? `${pathname}${search}` : `${pathname}${request.nextUrl.search ?? ""}`);
105
+ }
106
+ let locale = localLocale ?? require_proxy_localeDetector.localeDetector?.(request) ?? defaultLocale;
107
+ if (!locales?.includes(locale)) locale = defaultLocale;
108
+ const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname, locale, rewriteRules);
109
+ const internalPath = internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath;
110
+ const search = appendLocaleSearchIfNeeded(request.nextUrl.search, locale);
111
+ return rewriteUrl(request, search ? `${internalPath}${search}` : `${internalPath}${request.nextUrl.search ?? ""}`, locale);
112
+ };
113
+ /**
114
+ * Extracts the locale from the URL pathname if present.
115
+ *
116
+ * @param pathname - The pathname from the request URL.
117
+ * @returns - The locale found in the pathname, or undefined if not found.
118
+ */
119
+ const getPathLocale = (pathname) => locales.find((locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`);
120
+ /**
121
+ * Handles the case where URLs have locale prefixes.
122
+ *
123
+ * @param request - The incoming Next.js request object.
124
+ * @param localLocale - The locale from the cookie.
125
+ * @param pathLocale - The locale extracted from the pathname.
126
+ * @param pathname - The pathname from the request URL.
127
+ * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
128
+ * @returns - The response to be returned to the client.
129
+ */
130
+ const handlePrefix = (request, localLocale, pathLocale, pathname) => {
131
+ if (!pathLocale) {
132
+ if (isPrefetchRequest(request) && true) return handleMissingPathLocale(request, defaultLocale, pathname);
133
+ return handleMissingPathLocale(request, localLocale, pathname);
134
+ }
135
+ return handleExistingPathLocale(request, pathLocale, pathname);
136
+ };
137
+ /**
138
+ * Handles requests where the locale is missing from the URL pathname.
139
+ *
140
+ * @param request - The incoming Next.js request object.
141
+ * @param localLocale - The locale from the cookie.
142
+ * @param pathname - The pathname from the request URL.
143
+ * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.
144
+ * @returns - The response to be returned to the client.
145
+ */
146
+ const handleMissingPathLocale = (request, localLocale, pathname) => {
147
+ let locale = localLocale ?? require_proxy_localeDetector.localeDetector?.(request) ?? defaultLocale;
148
+ if (!locales.includes(locale)) locale = defaultLocale;
149
+ const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname, locale, rewriteRules);
150
+ const targetLocalizedPathResult = (0, _intlayer_core_localization.getLocalizedPath)(canonicalPath, locale, rewriteRules);
151
+ const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
152
+ const newPath = constructPath(locale, targetLocalizedPath, basePath, appendLocaleSearchIfNeeded(request.nextUrl.search, locale));
153
+ return prefixDefault || locale !== defaultLocale ? redirectUrl(request, newPath) : rewriteUrl(request, internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath, locale);
154
+ };
155
+ /**
156
+ * Handles requests where the locale exists in the URL pathname.
157
+ *
158
+ * @param request - The incoming Next.js request object.
159
+ * @param localLocale - The locale from the cookie.
160
+ * @param pathLocale - The locale extracted from the pathname.
161
+ * @param pathname - The pathname from the request URL.
162
+ * @returns - The response to be returned to the client.
163
+ */
164
+ const handleExistingPathLocale = (request, pathLocale, pathname) => {
165
+ const rawPath = pathname.slice(`/${pathLocale}`.length) || "/";
166
+ const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(rawPath, pathLocale, rewriteRules);
167
+ const targetLocalizedPathResult = (0, _intlayer_core_localization.getLocalizedPath)(canonicalPath, pathLocale, rewriteRules);
168
+ const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
169
+ if ((typeof targetLocalizedPathResult === "string" ? false : targetLocalizedPathResult.isRewritten) && targetLocalizedPath !== rawPath) return redirectUrl(request, constructPath(pathLocale, targetLocalizedPath, basePath, appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)));
170
+ const internalUrl = internalPrefix ? `/${pathLocale}${canonicalPath}` : canonicalPath;
171
+ if (!prefixDefault && pathLocale === defaultLocale) return handleDefaultLocaleRedirect(request, pathLocale, pathname);
172
+ const search = request.nextUrl.search;
173
+ return rewriteUrl(request, internalUrl + (search ?? ""), pathLocale);
174
+ };
175
+ /**
176
+ * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.
177
+ *
178
+ * @param request - The incoming Next.js request object.
179
+ * @param pathname - The pathname from the request URL.
180
+ * @param pathLocale - The locale extracted from the pathname.
181
+ * @param localLocale - The locale from the cookie.
182
+ * @param basePath - The base path of the application.
183
+ * @returns - The new URL path with the correct locale.
184
+ */
185
+ /**
186
+ * The key fix for 404s without [locale] folders
187
+ */
188
+ const handleDefaultLocaleRedirect = (request, pathLocale, canonicalPath) => {
189
+ if (!prefixDefault && pathLocale === defaultLocale) {
190
+ const targetLocalizedPathResult = (0, _intlayer_core_localization.getLocalizedPath)(canonicalPath, pathLocale, rewriteRules);
191
+ const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
192
+ const basePathTrailingSlash = basePath.endsWith("/");
193
+ let finalPath = targetLocalizedPath;
194
+ if (finalPath.startsWith("/")) finalPath = finalPath.slice(1);
195
+ return redirectUrl(request, `${basePath}${basePathTrailingSlash ? "" : "/"}${finalPath}` + (appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale) ?? request.nextUrl.search ?? ""));
196
+ }
197
+ const searchWithLocale = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
198
+ const internalPath = internalPrefix ? `/${pathLocale}${canonicalPath}` : canonicalPath;
199
+ return rewriteUrl(request, searchWithLocale ? `${internalPath}${searchWithLocale}` : `${internalPath}${request.nextUrl.search ?? ""}`, pathLocale);
200
+ };
201
+ /**
202
+ * Constructs a new path by combining the locale, path, basePath, and search parameters.
203
+ *
204
+ * @param locale - The locale to include in the path.
205
+ * @param path - The original path from the request.
206
+ * @param basePath - The base path of the application.
207
+ * @param [search] - The query string from the request URL (optional).
208
+ * @returns - The constructed new path.
209
+ */
210
+ const constructPath = (locale, path, basePath, search) => {
211
+ const pathWithoutPrefix = path.startsWith(`/${locale}`) ? path.slice(`/${locale}`.length) || "/" : path;
212
+ if (effectiveMode === "no-prefix" || effectiveMode === "search-params") return `${pathWithoutPrefix}${search ? `?${search}` : ""}`;
213
+ const pathWithLocalePrefix = path.startsWith(`/${locale}`) ? path : `${locale}${path.startsWith("/") ? "" : "/"}${path}`;
214
+ return `${basePath}${basePath.endsWith("/") ? "" : "/"}${pathWithLocalePrefix}`.replace(/\/+/g, "/");
215
+ };
216
+ /**
217
+ * This handles the internal path Next.js sees.
218
+ * To support optional [locale] folders, we need to decide if we
219
+ * keep the locale prefix or strip it.
220
+ */
221
+ const rewriteUrl = (request, newPath, locale) => {
222
+ const search = request.nextUrl.search;
223
+ const pathWithSearch = search && !newPath.includes("?") ? `${newPath}${search}` : newPath;
224
+ const requestHeaders = new Headers(request.headers);
225
+ (0, _intlayer_core_utils.setLocaleInStorage)(locale, { setHeader: (name, value) => {
226
+ requestHeaders.set(name, value);
227
+ } });
228
+ const targetUrl = new URL(pathWithSearch, request.url);
229
+ const response = targetUrl.href === request.nextUrl.href ? next_server.NextResponse.next({ request: { headers: requestHeaders } }) : next_server.NextResponse.rewrite(targetUrl, { request: { headers: requestHeaders } });
230
+ (0, _intlayer_core_utils.setLocaleInStorage)(locale, { setHeader: (name, value) => {
231
+ response.headers.set(name, value);
232
+ } });
233
+ return response;
234
+ };
235
+ /**
236
+ * Redirects the request to the new path.
237
+ *
238
+ * @param request - The incoming Next.js request object.
239
+ * @param newPath - The new path to redirect to.
240
+ * @returns - The redirect response.
241
+ */
242
+ const redirectUrl = (request, newPath) => {
243
+ const search = request.nextUrl.search;
244
+ const pathWithSearch = search && !newPath.includes("?") ? `${newPath}${search}` : newPath;
245
+ return next_server.NextResponse.redirect(new URL(pathWithSearch, request.url));
246
+ };
247
+
248
+ //#endregion
249
+ exports.intlayerProxy = intlayerProxy;
2
250
  //# sourceMappingURL=intlayerProxy.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.cjs","names":["configuration","ROUTING_MODE","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\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/allLocales';\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 ?? 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\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n 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 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, 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 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 // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\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 */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\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 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":"qWA+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,aACxB,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,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OACE,IAAY,YACZ,IAAuB,KACvB,CAAC,CAAC,GACF,CAAC,CAAC,GAKA,GAC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W,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,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
+ {"version":3,"file":"intlayerProxy.cjs","names":["configuration","ROUTING_MODE","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\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/allLocales';\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 ?? 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\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n 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 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, 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 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 // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\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 */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\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 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":";;;;;;;;;;;AA+CA,MAAM,EAAE,sBAAsB,YAAYA,kCAAiB,EAAE;AAC7D,MAAM,EAAE,SAAS,kBAAkB,wBAAwB,EAAE;AAC7D,MAAM,EAAE,UAAU,MAAM,YAAY,WAAW,EAAE;AAKjD,MAAM,gBAAgB,QAAQC;AAC9B,MAAM,WACJ,kBAAkB,eAAe,kBAAkB;AACrD,MAAM,gBAAgB,kBAAkB;AAExC,MAAM,iBAAiB,CAAC;AAExB,MAAM,gEAA+B,SAAS,MAAM;;;;;;;;;;;;;;;AAgBpD,MAAM,qBAAqB,YAAkC;CAC3D,MAAM,UAAU,QAAQ,QAAQ,IAAI,UAAU;CAC9C,MAAM,qBAAqB,QAAQ,QAAQ,IAAI,uBAAuB;CACtE,MAAM,UAAU,QAAQ,QAAQ,IAAI,WAAW;CAC/C,MAAM,cAAc,QAAQ,QAAQ,IAAI,gBAA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AC/B,MAAM,iBACJ,UAAU,CAAC,QAAQ,SAAS,IAAI,GAAG,GAAG,UAAU,WAAW;AAE7D,QAAOA,yBAAa,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI,CAAC"}
@@ -1,2 +1,21 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/core/localization`);const t=t=>{let n={};return t.headers.forEach((e,t)=>{n[t]=e}),(0,e.localeDetector)(n)};exports.localeDetector=t;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let _intlayer_core_localization = require("@intlayer/core/localization");
4
+
5
+ //#region src/proxy/localeDetector.ts
6
+ /**
7
+ * Detects the locale from the request headers
8
+ *
9
+ * Headers are provided by the browser and can be used to determine the user's preferred language
10
+ */
11
+ const localeDetector = (request) => {
12
+ const negotiatorHeaders = {};
13
+ request.headers.forEach((value, key) => {
14
+ negotiatorHeaders[key] = value;
15
+ });
16
+ return (0, _intlayer_core_localization.localeDetector)(negotiatorHeaders);
17
+ };
18
+
19
+ //#endregion
20
+ exports.localeDetector = localeDetector;
2
21
  //# sourceMappingURL=localeDetector.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"localeDetector.cjs","names":[],"sources":["../../../src/proxy/localeDetector.ts"],"sourcesContent":["import { localeDetector as localeDetectorCore } from '@intlayer/core/localization';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { NextRequest } from 'next/server.js';\n\n/**\n * Detects the locale from the request headers\n *\n * Headers are provided by the browser and can be used to determine the user's preferred language\n */\nexport const localeDetector = (request: NextRequest): LocalesValues => {\n const negotiatorHeaders: Record<string, string> = {};\n\n request.headers.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const locale = localeDetectorCore(negotiatorHeaders);\n\n return locale;\n};\n"],"mappings":"6JASA,MAAa,EAAkB,GAAwC,CACrE,IAAM,EAA4C,EAAE,CAQpD,OANA,EAAQ,QAAQ,SAAS,EAAO,IAAQ,CACtC,EAAkB,GAAO,GACzB,EAIF,EAAA,EAAA,gBAFkC,EAAkB"}
1
+ {"version":3,"file":"localeDetector.cjs","names":[],"sources":["../../../src/proxy/localeDetector.ts"],"sourcesContent":["import { localeDetector as localeDetectorCore } from '@intlayer/core/localization';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { NextRequest } from 'next/server.js';\n\n/**\n * Detects the locale from the request headers\n *\n * Headers are provided by the browser and can be used to determine the user's preferred language\n */\nexport const localeDetector = (request: NextRequest): LocalesValues => {\n const negotiatorHeaders: Record<string, string> = {};\n\n request.headers.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const locale = localeDetectorCore(negotiatorHeaders);\n\n return locale;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB,YAAwC;CACrE,MAAM,oBAA4C,EAAE;AAEpD,SAAQ,QAAQ,SAAS,OAAO,QAAQ;AACtC,oBAAkB,OAAO;GACzB;AAIF,wDAFkC,kBAAkB"}
@@ -1,2 +1,38 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./intlayerProxy.cjs`),t=require(`./multipleProxies.cjs`),n=e.intlayerProxy,r=t.multipleProxies;exports.intlayerMiddleware=n,exports.multipleMiddlewares=r;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_proxy_intlayerProxy = require('./intlayerProxy.cjs');
3
+ const require_proxy_multipleProxies = require('./multipleProxies.cjs');
4
+
5
+ //#region src/proxy/middleware.ts
6
+ /**
7
+ * Reexport for nextjs <=15
8
+ */
9
+ /**
10
+ * Middleware that handles the internationalization layer
11
+ *
12
+ * Usage:
13
+ *
14
+ * ```ts
15
+ * // ./src/middleware.ts
16
+ *
17
+ * export { intlayerMiddleware as middleware } from '@intlayer/next/middleware';
18
+ *
19
+ * // applies this middleware only to files in the app directory
20
+ * export const config = {
21
+ * matcher: '/((?!api|static|.*\\..*|_next).*)',
22
+ * };
23
+ * ```
24
+ *
25
+ * Main middleware function for handling internationalization.
26
+ *
27
+ * @param request - The incoming Next.js request object.
28
+ * @param event - The Next.js fetch event (optional).
29
+ * @param response - The Next.js response object (optional).
30
+ * @returns - The response to be returned to the client.
31
+ */
32
+ const intlayerMiddleware = require_proxy_intlayerProxy.intlayerProxy;
33
+ const multipleMiddlewares = require_proxy_multipleProxies.multipleProxies;
34
+
35
+ //#endregion
36
+ exports.intlayerMiddleware = intlayerMiddleware;
37
+ exports.multipleMiddlewares = multipleMiddlewares;
2
38
  //# sourceMappingURL=middleware.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["intlayerProxy","multipleProxies"],"sources":["../../../src/proxy/middleware.ts"],"sourcesContent":["import { intlayerProxy } from './intlayerProxy';\nimport { multipleProxies } from './multipleProxies';\n\n/**\n * Reexport for nextjs <=15\n */\n\n/**\n * Middleware that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/middleware.ts\n *\n * export { intlayerMiddleware as middleware } from '@intlayer/next/middleware';\n *\n * // applies this middleware only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main middleware function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerMiddleware = intlayerProxy;\n\nexport const multipleMiddlewares = multipleProxies;\n"],"mappings":"6IA8Ba,EAAqBA,EAAAA,cAErB,EAAsBC,EAAAA"}
1
+ {"version":3,"file":"middleware.cjs","names":["intlayerProxy","multipleProxies"],"sources":["../../../src/proxy/middleware.ts"],"sourcesContent":["import { intlayerProxy } from './intlayerProxy';\nimport { multipleProxies } from './multipleProxies';\n\n/**\n * Reexport for nextjs <=15\n */\n\n/**\n * Middleware that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/middleware.ts\n *\n * export { intlayerMiddleware as middleware } from '@intlayer/next/middleware';\n *\n * // applies this middleware only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main middleware function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerMiddleware = intlayerProxy;\n\nexport const multipleMiddlewares = multipleProxies;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,qBAAqBA;AAElC,MAAa,sBAAsBC"}
@@ -1,2 +1,58 @@
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;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let next_server = require("next/server");
4
+
5
+ //#region src/proxy/multipleProxies.ts
6
+ /**
7
+ * Utility to combine multiple Next.js proxies into one.
8
+ *
9
+ * It executes proxies in order, merges headers, and correctly handles
10
+ * redirects and rewrites.
11
+ *
12
+ * @example
13
+ * import { multipleProxies, intlayerProxy } from "next-intlayer/proxy";
14
+ * import { NextResponse } from "next/server";
15
+ *
16
+ * const authMiddleware = (req: NextRequest) => {
17
+ * if (!req.cookies.get("token")) {
18
+ * return NextResponse.redirect(new URL("/login", req.url));
19
+ * }
20
+ * return NextResponse.next();
21
+ * };
22
+ *
23
+ * export default multipleProxies([
24
+ * intlayerProxy,
25
+ * authMiddleware,
26
+ * ]);
27
+ *
28
+ * @param proxies - An array of proxy functions to execute in order.
29
+ * @returns A single proxy function that runs all provided proxies.
30
+ */
31
+ const multipleProxies = (proxies) => async (req, event, response) => {
32
+ const proxyHeader = [];
33
+ for (const proxy of proxies) {
34
+ const result = await proxy(req, event, response);
35
+ if (!result.ok) return result;
36
+ proxyHeader.push(result.headers);
37
+ }
38
+ const mergedHeaders = new Headers();
39
+ const transmittedHeaders = new Headers(req.headers);
40
+ proxyHeader.forEach((header) => {
41
+ for (const [key, value] of header.entries()) {
42
+ mergedHeaders.append(key, value);
43
+ if (key.startsWith("x-middleware-request-")) {
44
+ const fixedKey = key.replace("x-middleware-request-", "");
45
+ transmittedHeaders.append(fixedKey, value);
46
+ }
47
+ }
48
+ });
49
+ const redirect = mergedHeaders.get("x-middleware-request-redirect");
50
+ if (redirect) return next_server.NextResponse.redirect(new URL(redirect, req.url), { status: 307 });
51
+ const rewrite = mergedHeaders.get("x-middleware-rewrite");
52
+ if (rewrite) return next_server.NextResponse.rewrite(new URL(rewrite, req.url), { request: { headers: transmittedHeaders } });
53
+ return next_server.NextResponse.next({ request: { headers: transmittedHeaders } });
54
+ };
55
+
56
+ //#endregion
57
+ exports.multipleProxies = multipleProxies;
2
58
  //# 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(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
+ {"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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,mBAET,YAMF,OAAO,KAAkB,OAAwB,aAA4B;CAE3E,MAAM,cAAyB,EAAE;AAGjC,MAAK,MAAM,SAAS,SAAS;EAE3B,MAAM,SAAS,MAAM,MAAM,KAAK,OAAO,SAAS;AAGhD,MAAI,CAAC,OAAO,GACV,QAAO;AAIT,cAAY,KAAK,OAAO,QAAQ;;CAIlC,MAAM,gBAAgB,IAAI,SAAS;CAGnC,MAAM,qBAAqB,IAAI,QAAQ,IAAI,QAAQ;AAGnD,aAAY,SAAS,WAAW;AAC9B,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,SAAS,EAAE;AAC3C,iBAAc,OAAO,KAAK,MAAM;AAGhC,OAAI,IAAI,WAAW,wBAAwB,EAAE;IAE3C,MAAM,WAAW,IAAI,QAAQ,yBAAyB,GAAG;AAGzD,uBAAmB,OAAO,UAAU,MAAM;;;GAG9C;CAGF,MAAM,WAAW,cAAc,IAAI,gCAAgC;AAGnE,KAAI,SAEF,QAAOA,yBAAa,SAAS,IAAI,IAAI,UAAU,IAAI,IAAI,EAAE,EACvD,QAAQ,KACT,CAAC;CAIJ,MAAM,UAAU,cAAc,IAAI,uBAAuB;AACzD,KAAI,QAEF,QAAOA,yBAAa,QAAQ,IAAI,IAAI,SAAS,IAAI,IAAI,EAAE,EACrD,SAAS,EACP,SAAS,oBACV,EACF,CAAC;AAIJ,QAAOA,yBAAa,KAAK,EACvB,SAAS,EACP,SAAS,oBACV,EACF,CAAC"}
@@ -1 +1,9 @@
1
- var e=require(`react-intlayer/server/format`);Object.keys(e).forEach(function(t){t!==`default`&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}})});
1
+
2
+
3
+ var react_intlayer_server_format = require("react-intlayer/server/format");
4
+ Object.keys(react_intlayer_server_format).forEach(function (k) {
5
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
+ enumerable: true,
7
+ get: function () { return react_intlayer_server_format[k]; }
8
+ });
9
+ });
@@ -1,2 +1,49 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/core/localization`),n=require(`@intlayer/config/built`);n=e.__toESM(n);let r=require(`@intlayer/config/defaultValues`),i=require(`@intlayer/core/utils`),a=require(`next/headers.js`);const o=async()=>{let e=n.default?.internationalization?.defaultLocale??r.DEFAULT_LOCALE,o=await(0,a.headers)(),s=await(0,a.cookies)(),c=(0,i.getLocaleFromStorage)({getCookie:e=>s.get(e)?.value??null,getHeader:e=>o.get(e)??null});if(c)return c;let l={};return o.forEach((e,t)=>{l[t]=e}),(0,t.localeDetector)(l)||e};exports.getLocale=o;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let _intlayer_core_localization = require("@intlayer/core/localization");
4
+ let _intlayer_config_built = require("@intlayer/config/built");
5
+ _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
6
+ let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
7
+ let _intlayer_core_utils = require("@intlayer/core/utils");
8
+ let next_headers_js = require("next/headers.js");
9
+
10
+ //#region src/server/getLocale.ts
11
+ /**
12
+ * Helper function to extract the current locale from Next.js headers and cookies.
13
+ *
14
+ * This function is designed to be used in Server Components, Server Actions, or Route Handlers
15
+ * to determine the locale preferred by the user or stored in their preferences.
16
+ *
17
+ * @returns A promise that resolves to the detected `Locale`.
18
+ *
19
+ * @example
20
+ * ```tsx
21
+ * import { getLocale } from 'next-intlayer/server';
22
+ *
23
+ * export default async function MyServerComponent() {
24
+ * const locale = await getLocale();
25
+ * // ...
26
+ * }
27
+ * ```
28
+ */
29
+ const getLocale = async () => {
30
+ const defaultLocale = _intlayer_config_built.default?.internationalization?.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE;
31
+ const headersList = await (0, next_headers_js.headers)();
32
+ const cookiesList = await (0, next_headers_js.cookies)();
33
+ const storedLocale = (0, _intlayer_core_utils.getLocaleFromStorage)({
34
+ getCookie: (name) => cookiesList.get(name)?.value ?? null,
35
+ getHeader: (name) => headersList.get(name) ?? null
36
+ });
37
+ if (storedLocale) return storedLocale;
38
+ const negotiatorHeaders = {};
39
+ headersList.forEach((value, key) => {
40
+ negotiatorHeaders[key] = value;
41
+ });
42
+ const userFallbackLocale = (0, _intlayer_core_localization.localeDetector)(negotiatorHeaders);
43
+ if (userFallbackLocale) return userFallbackLocale;
44
+ return defaultLocale;
45
+ };
46
+
47
+ //#endregion
48
+ exports.getLocale = getLocale;
2
49
  //# sourceMappingURL=getLocale.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.cjs","names":["configuration","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"uUA0BA,MAAa,EAAY,SAA6B,CACpD,IAAM,EACJA,EAAAA,SAAe,sBAAsB,eAAiBC,EAAAA,eAGlD,EAAc,MAAA,EAAA,EAAA,UAAe,CAC7B,EAAc,MAAA,EAAA,EAAA,UAAe,CAE7B,GAAA,EAAA,EAAA,sBAAoC,CACxC,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAE,OAAS,KAC7D,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAI,KACvD,CAAC,CAEF,GAAI,EAAc,OAAO,EAGzB,IAAM,EAA4C,EAAE,CASpD,OARA,EAAY,SAAS,EAAO,IAAQ,CAClC,EAAkB,GAAO,GACzB,EAEI,EAAA,EAAA,gBAAoC,EAAkB,EAIrD"}
1
+ {"version":3,"file":"getLocale.cjs","names":["configuration","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBACJA,gCAAe,sBAAsB,iBAAiBC;CAGxD,MAAM,cAAc,oCAAe;CACnC,MAAM,cAAc,oCAAe;CAEnC,MAAM,8DAAoC;EACxC,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qEAAoC,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}