next-intlayer 9.0.0-canary.9 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/client/IntlayerClientProvider.cjs +0 -1
- package/dist/cjs/client/IntlayerClientProvider.cjs.map +1 -1
- package/dist/cjs/client/index.cjs +0 -1
- package/dist/cjs/client/useLocale.cjs +2 -2
- package/dist/cjs/client/useLocale.cjs.map +1 -1
- package/dist/cjs/client/useLocalePageRouter.cjs +2 -2
- package/dist/cjs/client/useLocalePageRouter.cjs.map +1 -1
- package/dist/cjs/client/usePathname.cjs +2 -2
- package/dist/cjs/client/usePathname.cjs.map +1 -1
- package/dist/cjs/client/useRewriteURL.cjs +0 -1
- package/dist/cjs/generateStaticParams.cjs +0 -1
- package/dist/cjs/generateStaticParams.cjs.map +1 -1
- package/dist/cjs/index.cjs +0 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/proxy/intlayerProxy.cjs +86 -50
- package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
- package/dist/cjs/proxy/localeDetector.cjs +0 -1
- package/dist/cjs/proxy/localeDetector.cjs.map +1 -1
- package/dist/cjs/proxy/multipleProxies.cjs +0 -1
- package/dist/cjs/proxy/multipleProxies.cjs.map +1 -1
- package/dist/cjs/server/getLocale.cjs +0 -1
- package/dist/cjs/server/getLocale.cjs.map +1 -1
- package/dist/cjs/server/index.cjs +0 -1
- package/dist/cjs/server/useDictionary.cjs +0 -1
- package/dist/cjs/server/useDictionary.cjs.map +1 -1
- package/dist/cjs/server/useDictionaryAsync.cjs +0 -1
- package/dist/cjs/server/useDictionaryAsync.cjs.map +1 -1
- package/dist/cjs/server/useDictionaryDynamic.cjs +0 -1
- package/dist/cjs/server/useDictionaryDynamic.cjs.map +1 -1
- package/dist/cjs/server/useIntlayer.cjs.map +1 -1
- package/dist/cjs/server/withIntlayer.cjs +46 -14
- package/dist/cjs/server/withIntlayer.cjs.map +1 -1
- package/dist/esm/client/IntlayerClientProvider.mjs.map +1 -1
- package/dist/esm/client/useLocale.mjs +2 -1
- package/dist/esm/client/useLocale.mjs.map +1 -1
- package/dist/esm/client/useLocalePageRouter.mjs +2 -1
- package/dist/esm/client/useLocalePageRouter.mjs.map +1 -1
- package/dist/esm/client/usePathname.mjs +2 -1
- package/dist/esm/client/usePathname.mjs.map +1 -1
- package/dist/esm/generateStaticParams.mjs.map +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs +87 -50
- package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
- package/dist/esm/proxy/localeDetector.mjs.map +1 -1
- package/dist/esm/proxy/multipleProxies.mjs.map +1 -1
- package/dist/esm/server/getLocale.mjs.map +1 -1
- package/dist/esm/server/useDictionary.mjs.map +1 -1
- package/dist/esm/server/useDictionaryAsync.mjs.map +1 -1
- package/dist/esm/server/useDictionaryDynamic.mjs.map +1 -1
- package/dist/esm/server/useIntlayer.mjs.map +1 -1
- package/dist/esm/server/withIntlayer.mjs +42 -10
- package/dist/esm/server/withIntlayer.mjs.map +1 -1
- package/dist/types/client/IntlayerClientProvider.d.ts +0 -1
- package/dist/types/client/IntlayerClientProvider.d.ts.map +1 -1
- package/dist/types/client/useLocale.d.ts +1 -6
- package/dist/types/client/useLocale.d.ts.map +1 -1
- package/dist/types/client/useLocalePageRouter.d.ts +1 -5
- package/dist/types/client/useLocalePageRouter.d.ts.map +1 -1
- package/dist/types/client/usePathname.d.ts.map +1 -1
- package/dist/types/generateStaticParams.d.ts.map +1 -1
- package/dist/types/index.d.ts +13 -440
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/markdown/index.d.ts +0 -3
- package/dist/types/proxy/intlayerProxy.d.ts +0 -1
- package/dist/types/proxy/intlayerProxy.d.ts.map +1 -1
- package/dist/types/proxy/localeDetector.d.ts +0 -1
- package/dist/types/proxy/localeDetector.d.ts.map +1 -1
- package/dist/types/proxy/middleware.d.ts +4 -4
- package/dist/types/proxy/middleware.d.ts.map +1 -1
- package/dist/types/proxy/multipleProxies.d.ts +0 -1
- package/dist/types/proxy/multipleProxies.d.ts.map +1 -1
- package/dist/types/server/getLocale.d.ts +0 -1
- package/dist/types/server/getLocale.d.ts.map +1 -1
- package/dist/types/server/useDictionary.d.ts +0 -1
- package/dist/types/server/useDictionary.d.ts.map +1 -1
- package/dist/types/server/useDictionaryAsync.d.ts +0 -1
- package/dist/types/server/useDictionaryAsync.d.ts.map +1 -1
- package/dist/types/server/useDictionaryDynamic.d.ts +0 -1
- package/dist/types/server/useDictionaryDynamic.d.ts.map +1 -1
- package/dist/types/server/useIntlayer.d.ts +0 -1
- package/dist/types/server/useIntlayer.d.ts.map +1 -1
- package/dist/types/server/withIntlayer.d.ts +1 -8
- package/dist/types/server/withIntlayer.d.ts.map +1 -1
- package/dist/types/types/NextPage.d.ts +0 -1
- package/dist/types/types/NextPage.d.ts.map +1 -1
- package/dist/types/types/index.d.ts +1 -1
- package/package.json +12 -12
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
5
4
|
let react_intlayer = require("react-intlayer");
|
|
6
5
|
let react_jsx_runtime = require("react/jsx-runtime");
|
|
7
6
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlayerClientProvider.cjs","names":["IntlayerProvider"],"sources":["../../../src/client/IntlayerClientProvider.tsx"],"sourcesContent":["'use client';\n\nimport type { FC } from 'react';\n\nimport { IntlayerProvider, type IntlayerProviderProps } from 'react-intlayer';\n\nexport type IntlayerClientProviderProps = IntlayerProviderProps;\n\n/**\n * Provider for client-side components in Next.js.\n *\n * This component wraps the `IntlayerProvider` from `react-intlayer` and is intended\n * to be used within Next.js App Router client components.\n *\n * @param props - The provider props.\n * @returns The provider component.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { IntlayerClientProvider } from 'next-intlayer';\n *\n * export default function ClientLayout({ children, locale }) {\n * return (\n * <IntlayerClientProvider locale={locale}>\n * {children}\n * </IntlayerClientProvider>\n * );\n * }\n * ```\n */\nexport const IntlayerClientProvider: FC<IntlayerProviderProps> = (props) => (\n <IntlayerProvider {...props} />\n);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"IntlayerClientProvider.cjs","names":["IntlayerProvider"],"sources":["../../../src/client/IntlayerClientProvider.tsx"],"sourcesContent":["'use client';\n\nimport type { FC } from 'react';\n\nimport { IntlayerProvider, type IntlayerProviderProps } from 'react-intlayer';\n\nexport type IntlayerClientProviderProps = IntlayerProviderProps;\n\n/**\n * Provider for client-side components in Next.js.\n *\n * This component wraps the `IntlayerProvider` from `react-intlayer` and is intended\n * to be used within Next.js App Router client components.\n *\n * @param props - The provider props.\n * @returns The provider component.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { IntlayerClientProvider } from 'next-intlayer';\n *\n * export default function ClientLayout({ children, locale }) {\n * return (\n * <IntlayerClientProvider locale={locale}>\n * {children}\n * </IntlayerClientProvider>\n * );\n * }\n * ```\n */\nexport const IntlayerClientProvider: FC<IntlayerProviderProps> = (props) => (\n <IntlayerProvider {...props} />\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,0BAAqD,UAChE,2CAACA,iCAAD,EAAkB,GAAI,MAAQ"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_client_IntlayerClientProvider = require('./IntlayerClientProvider.cjs');
|
|
4
3
|
const require_client_usePathname = require('./usePathname.cjs');
|
|
5
4
|
const require_client_useLocale = require('./useLocale.cjs');
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
5
4
|
const require_client_usePathname = require('./usePathname.cjs');
|
|
6
5
|
let react_intlayer = require("react-intlayer");
|
|
7
6
|
let _intlayer_core_localization = require("@intlayer/core/localization");
|
|
@@ -41,7 +40,8 @@ const useLocale = ({ onChange = "replace", onLocaleChange, isCookieEnabled } = {
|
|
|
41
40
|
...(0, react_intlayer.useLocale)({
|
|
42
41
|
onLocaleChange: (0, react.useCallback)((locale) => {
|
|
43
42
|
if (!onChange) return;
|
|
44
|
-
const
|
|
43
|
+
const currentDomain = process.env.INTLAYER_ROUTING_DOMAINS !== "false" && typeof window !== "undefined" ? window.location.hostname : void 0;
|
|
44
|
+
const pathWithLocale = (0, _intlayer_core_localization.getLocalizedUrl)(pathWithoutLocale, locale, { currentDomain });
|
|
45
45
|
if (typeof onChange === "function") {
|
|
46
46
|
onChange({
|
|
47
47
|
locale,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocale.cjs","names":["usePathname"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useLocale.cjs","names":["usePathname"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa,EACxB,WAAW,WACX,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,SAAS,2CAAmB;CACpC,MAAM,oBAAoBA,uCAAY;CAuDtC,OAAO;EACL,iCANqC;GACrC,wCAhDC,WAA0B;IACzB,IAAI,CAAC,UAAU;IAEf,MAAM,gBACJ,QAAQ,IAAI,6BAA6B,WACzC,OAAO,WAAW,cACd,OAAO,SAAS,WAChB;IAEN,MAAM,kEAAiC,mBAAmB,QAAQ,EAChE,cACF,CAAC;IAED,IAAI,OAAO,aAAa,YAAY;KAClC,SAAS;MAAE;MAAQ,MAAM;KAAe,CAAC;KACzC;IACF;IAIA,IACE,QAAQ,IAAI,6BAA6B,wDACtB,cAAc,GACjC;KACA,IAAI;MACF,MAAM,SAAS,IAAI,IAAI,cAAc;MACrC,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACrD,OAAO,SAAS,OAAO;KAE3B,QAAQ,CAER;KACA;IACF;IAEA,IAAI,aAAa,WACf,QAAQ,cAAc;IAExB,IAAI,aAAa,QACf,KAAK,cAAc;IAGrB,iBAAiB,MAAyB;GAC5C,GACA;IAAC;IAAS;IAAM;IAAmB;IAAU;GAAc,CAIzB;GAClC;EACF,CAGmB;EACjB;CACF;AACF"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
5
4
|
let react_intlayer = require("react-intlayer");
|
|
6
5
|
let _intlayer_core_localization = require("@intlayer/core/localization");
|
|
7
6
|
let react = require("react");
|
|
@@ -35,7 +34,8 @@ const useLocalePageRouter = ({ onLocaleChange, isCookieEnabled } = {}) => {
|
|
|
35
34
|
return {
|
|
36
35
|
...(0, react_intlayer.useLocale)({
|
|
37
36
|
onLocaleChange: (0, react.useCallback)((locale) => {
|
|
38
|
-
|
|
37
|
+
const pathWithLocale = (0, _intlayer_core_localization.getLocalizedUrl)(pathWithoutLocale, locale);
|
|
38
|
+
push(pathWithLocale);
|
|
39
39
|
onLocaleChange?.(locale);
|
|
40
40
|
return reload();
|
|
41
41
|
}, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocalePageRouter.cjs","names":[],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useLocalePageRouter.cjs","names":[],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,uBAAuB,EAClC,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,MAAM,UAAU,yCAAqB;CAC7C,MAAM,mGACuB,QAAQ,GACnC,CAAC,QAAQ,CACX;CAoBA,OAAO;EACL,iCANqC;GACrC,wCAbC,WAA0B;IACzB,MAAM,kEAAiC,mBAAmB,MAAM;IAEhE,KAAK,cAAc;IAEnB,iBAAiB,MAAgB;IAEjC,OAAO,OAAO;GAChB,GACA;IAAC;IAAmB;IAAgB;GAAM,CAIR;GAClC;EACF,CAGmB;EACjB;CACF;AACF"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
5
4
|
let _intlayer_core_localization = require("@intlayer/core/localization");
|
|
6
5
|
let next_navigation_js = require("next/navigation.js");
|
|
7
6
|
let react = require("react");
|
|
@@ -31,7 +30,8 @@ const usePathname = () => {
|
|
|
31
30
|
const nextPathname = (0, next_navigation_js.usePathname)();
|
|
32
31
|
const [searchParams, setSearchParams] = (0, react.useState)("");
|
|
33
32
|
(0, react.useEffect)(() => {
|
|
34
|
-
|
|
33
|
+
const search = typeof window !== "undefined" ? window.location.search : "";
|
|
34
|
+
setSearchParams(search);
|
|
35
35
|
}, [nextPathname]);
|
|
36
36
|
const fullPath = searchParams ? `${nextPathname}${searchParams}` : nextPathname;
|
|
37
37
|
return (0, react.useMemo)(() => (0, _intlayer_core_localization.getPathWithoutLocale)(fullPath), [fullPath]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePathname.cjs","names":[],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["'use client';\n\nimport { getPathWithoutLocale } from '@intlayer/core/localization';\nimport { usePathname as useNextPathname } from 'next/navigation.js';\nimport { useEffect, useMemo, useState } from 'react';\n\n/**\n * Next.js hook that returns the current pathname with the locale segment removed.\n *\n * Wraps Next.js `usePathname()` so it re-renders on client navigations and\n * appends any search parameters before stripping the locale prefix.\n *\n * @returns The current pathname without the locale prefix.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { usePathname } from 'next-intlayer';\n *\n * const NavItem = ({ href }: { href: string }) => {\n * const pathname = usePathname();\n * return <a className={pathname === href ? 'active' : ''}>{href}</a>;\n * };\n * ```\n */\nexport const usePathname = (): string => {\n const nextPathname = useNextPathname();\n const [searchParams, setSearchParams] = useState<string>('');\n\n useEffect(() => {\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setSearchParams(search);\n }, [nextPathname]);\n\n const fullPath = searchParams\n ? `${nextPathname}${searchParams}`\n : nextPathname;\n\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"usePathname.cjs","names":[],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["'use client';\n\nimport { getPathWithoutLocale } from '@intlayer/core/localization';\nimport { usePathname as useNextPathname } from 'next/navigation.js';\nimport { useEffect, useMemo, useState } from 'react';\n\n/**\n * Next.js hook that returns the current pathname with the locale segment removed.\n *\n * Wraps Next.js `usePathname()` so it re-renders on client navigations and\n * appends any search parameters before stripping the locale prefix.\n *\n * @returns The current pathname without the locale prefix.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { usePathname } from 'next-intlayer';\n *\n * const NavItem = ({ href }: { href: string }) => {\n * const pathname = usePathname();\n * return <a className={pathname === href ? 'active' : ''}>{href}</a>;\n * };\n * ```\n */\nexport const usePathname = (): string => {\n const nextPathname = useNextPathname();\n const [searchParams, setSearchParams] = useState<string>('');\n\n useEffect(() => {\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setSearchParams(search);\n }, [nextPathname]);\n\n const fullPath = searchParams\n ? `${nextPathname}${searchParams}`\n : nextPathname;\n\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,oBAA4B;CACvC,MAAM,mDAA+B;CACrC,MAAM,CAAC,cAAc,uCAAoC,EAAE;CAE3D,2BAAgB;EACd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;EACxE,gBAAgB,MAAM;CACxB,GAAG,CAAC,YAAY,CAAC;CAEjB,MAAM,WAAW,eACb,GAAG,eAAe,iBAClB;CAEJ,sFAA0C,QAAQ,GAAG,CAAC,QAAQ,CAAC;AACjE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateStaticParams.cjs","names":["internationalization"],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\nconst { locales } = internationalization;\n\n/**\n * Generates static parameters for Next.js's dynamic routes based on the configured locales.\n *\n * This function is typically used in Next.js App Router for `generateStaticParams`\n * to ensure all supported locales are pre-rendered at build time.\n *\n * @returns An array of objects containing the `locale` parameter for each configured locale.\n *\n * @example\n * ```tsx\n * // app/[locale]/layout.tsx\n * export { generateStaticParams } from 'next-intlayer';\n *\n * export default async function RootLayout({ children, params }) {\n * // ...\n * }\n * ```\n */\nexport const generateStaticParams = () => locales.map((locale) => ({ locale }));\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"generateStaticParams.cjs","names":["internationalization"],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\nconst { locales } = internationalization;\n\n/**\n * Generates static parameters for Next.js's dynamic routes based on the configured locales.\n *\n * This function is typically used in Next.js App Router for `generateStaticParams`\n * to ensure all supported locales are pre-rendered at build time.\n *\n * @returns An array of objects containing the `locale` parameter for each configured locale.\n *\n * @example\n * ```tsx\n * // app/[locale]/layout.tsx\n * export { generateStaticParams } from 'next-intlayer';\n *\n * export default async function RootLayout({ children, params }) {\n * // ...\n * }\n * ```\n */\nexport const generateStaticParams = () => locales.map((locale) => ({ locale }));\n"],"mappings":";;;;AAEA,MAAM,EAAE,YAAYA;;;;;;;;;;;;;;;;;;;AAoBpB,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,OAAO,EAAE"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_client_IntlayerClientProvider = require('./client/IntlayerClientProvider.cjs');
|
|
4
3
|
const require_client_usePathname = require('./client/usePathname.cjs');
|
|
5
4
|
const require_client_useLocale = require('./client/useLocale.cjs');
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["_MarkdownProvider","_useMarkdownContext","_renderMarkdown","_useMarkdownRenderer","_MarkdownRenderer"],"sources":["../../src/index.ts"],"sourcesContent":["export {\n getDictionary,\n getIntlayer,\n IntlayerClientContext,\n type IntlayerNode,\n localeCookie,\n localeInStorage,\n setLocaleCookie,\n setLocaleInStorage,\n t,\n useDictionary,\n useDictionaryAsync,\n useDictionaryDynamic,\n useI18n,\n useIntl,\n useIntlayer,\n useLoadDynamic,\n useLocaleCookie,\n useLocaleStorage,\n} from 'react-intlayer';\nexport * from './client/index';\nexport { generateStaticParams } from './generateStaticParams';\nexport type {\n LocalParams,\n LocalPromiseParams,\n Next14LayoutIntlayer,\n Next14PageIntlayer,\n Next15LayoutIntlayer,\n Next15PageIntlayer,\n NextLayoutIntlayer,\n NextPageIntlayer,\n} from './types/index';\n\nimport type {\n MarkdownProviderOptions as _MarkdownProviderOptions,\n MarkdownRendererProps as _MarkdownRendererProps,\n RenderMarkdownProps as _RenderMarkdownProps,\n} from './markdown';\nimport {\n MarkdownProvider as _MarkdownProvider,\n MarkdownRenderer as _MarkdownRenderer,\n renderMarkdown as _renderMarkdown,\n useMarkdownContext as _useMarkdownContext,\n useMarkdownRenderer as _useMarkdownRenderer,\n} from './markdown';\n\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const MarkdownProvider = _MarkdownProvider;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const useMarkdownContext = _useMarkdownContext;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type MarkdownProviderOptions = _MarkdownProviderOptions;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const renderMarkdown = _renderMarkdown;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const useMarkdownRenderer = _useMarkdownRenderer;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const MarkdownRenderer = _MarkdownRenderer;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type RenderMarkdownProps = _RenderMarkdownProps;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type MarkdownRendererProps = _MarkdownRendererProps;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["_MarkdownProvider","_useMarkdownContext","_renderMarkdown","_useMarkdownRenderer","_MarkdownRenderer"],"sources":["../../src/index.ts"],"sourcesContent":["export {\n getDictionary,\n getIntlayer,\n IntlayerClientContext,\n type IntlayerNode,\n localeCookie,\n localeInStorage,\n setLocaleCookie,\n setLocaleInStorage,\n t,\n useDictionary,\n useDictionaryAsync,\n useDictionaryDynamic,\n useI18n,\n useIntl,\n useIntlayer,\n useLoadDynamic,\n useLocaleCookie,\n useLocaleStorage,\n} from 'react-intlayer';\nexport * from './client/index';\nexport { generateStaticParams } from './generateStaticParams';\nexport type {\n LocalParams,\n LocalPromiseParams,\n Next14LayoutIntlayer,\n Next14PageIntlayer,\n Next15LayoutIntlayer,\n Next15PageIntlayer,\n NextLayoutIntlayer,\n NextPageIntlayer,\n} from './types/index';\n\nimport type {\n MarkdownProviderOptions as _MarkdownProviderOptions,\n MarkdownRendererProps as _MarkdownRendererProps,\n RenderMarkdownProps as _RenderMarkdownProps,\n} from './markdown';\nimport {\n MarkdownProvider as _MarkdownProvider,\n MarkdownRenderer as _MarkdownRenderer,\n renderMarkdown as _renderMarkdown,\n useMarkdownContext as _useMarkdownContext,\n useMarkdownRenderer as _useMarkdownRenderer,\n} from './markdown';\n\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const MarkdownProvider = _MarkdownProvider;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const useMarkdownContext = _useMarkdownContext;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type MarkdownProviderOptions = _MarkdownProviderOptions;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const renderMarkdown = _renderMarkdown;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const useMarkdownRenderer = _useMarkdownRenderer;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport const MarkdownRenderer = _MarkdownRenderer;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type RenderMarkdownProps = _RenderMarkdownProps;\n/**\n * @deprecated import from next-intlayer/markdown instead\n */\nexport type MarkdownRendererProps = _MarkdownRendererProps;\n"],"mappings":";;;;;;;;;;;;;AAiDA,MAAa,2DAAmBA;;;;AAIhC,MAAa,6DAAqBC;;;;AAQlC,MAAa,yDAAiBC;;;;AAI9B,MAAa,8DAAsBC;;;;AAInC,MAAa,2DAAmBC"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
2
|
const require_proxy_localeDetector = require('./localeDetector.cjs');
|
|
4
3
|
let _intlayer_core_localization = require("@intlayer/core/localization");
|
|
5
4
|
let _intlayer_core_utils = require("@intlayer/core/utils");
|
|
@@ -17,36 +16,17 @@ const prefixDefault = !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYE
|
|
|
17
16
|
const internalPrefix = !noPrefix;
|
|
18
17
|
const rewriteRules = process.env.INTLAYER_ROUTING_REWRITE_RULES !== "false" ? (0, _intlayer_core_localization.getRewriteRules)(rewrite, "url") : void 0;
|
|
19
18
|
/**
|
|
20
|
-
* Strips the protocol from a domain string and returns only the hostname.
|
|
21
|
-
* e.g. 'https://intlayer.zh' → 'intlayer.zh', 'intlayer.zh' → 'intlayer.zh'
|
|
22
|
-
*/
|
|
23
|
-
const normalizeDomainHostname = (domain) => {
|
|
24
|
-
try {
|
|
25
|
-
return /^https?:\/\//.test(domain) ? new URL(domain).hostname : domain;
|
|
26
|
-
} catch {
|
|
27
|
-
return domain;
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* Returns the locale exclusively mapped to a given hostname via `routing.domains`,
|
|
32
|
-
* or undefined if zero or more than one locale share that hostname.
|
|
33
|
-
*
|
|
34
|
-
* Example: with domains = { zh: 'intlayer.zh', fr: 'intlayer.org' }
|
|
35
|
-
* getLocaleFromDomain('intlayer.zh') → 'zh'
|
|
36
|
-
* getLocaleFromDomain('intlayer.org') → undefined (multiple locales share it)
|
|
37
|
-
*/
|
|
38
|
-
const getLocaleFromDomain = (hostname) => {
|
|
39
|
-
if (!domains) return void 0;
|
|
40
|
-
const matching = Object.entries(domains).filter(([, domain]) => normalizeDomainHostname(domain) === hostname);
|
|
41
|
-
return matching.length === 1 ? matching[0]?.[0] : void 0;
|
|
42
|
-
};
|
|
43
|
-
/**
|
|
44
19
|
* Detects if the request is a prefetch request from Next.js.
|
|
45
20
|
*
|
|
46
|
-
* Next.js prefetch requests
|
|
21
|
+
* Next.js prefetch requests are identified by:
|
|
47
22
|
* - purpose: 'prefetch' (standard prefetch header)
|
|
48
|
-
* - next-router-prefetch: '1' (Next.js router prefetch)
|
|
49
|
-
*
|
|
23
|
+
* - next-router-prefetch: '1' (Next.js app-router prefetch)
|
|
24
|
+
*
|
|
25
|
+
* Note: `next-url` and `x-nextjs-data` are intentionally NOT used here.
|
|
26
|
+
* Both are also sent on real client-side navigations (RSC navigation
|
|
27
|
+
* requests and pages-router data requests respectively), so treating them
|
|
28
|
+
* as prefetch would force such navigations to the default locale instead
|
|
29
|
+
* of the user's stored locale.
|
|
50
30
|
*
|
|
51
31
|
* During prefetch, we should ignore cookie-based locale detection
|
|
52
32
|
* to prevent unwanted redirects when users are switching locales.
|
|
@@ -57,9 +37,7 @@ const getLocaleFromDomain = (hostname) => {
|
|
|
57
37
|
const isPrefetchRequest = (request) => {
|
|
58
38
|
const purpose = request.headers.get("purpose");
|
|
59
39
|
const nextRouterPrefetch = request.headers.get("next-router-prefetch");
|
|
60
|
-
|
|
61
|
-
const xNextjsData = request.headers.get("x-nextjs-data");
|
|
62
|
-
return purpose === "prefetch" || nextRouterPrefetch === "1" || !!nextUrl || !!xNextjsData;
|
|
40
|
+
return purpose === "prefetch" || nextRouterPrefetch === "1";
|
|
63
41
|
};
|
|
64
42
|
const appendLocaleSearchIfNeeded = (search, locale) => {
|
|
65
43
|
if (process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params" || effectiveMode !== "search-params") return search;
|
|
@@ -100,16 +78,19 @@ const intlayerProxy = (request, _event, _response) => {
|
|
|
100
78
|
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && pathLocale && domains) {
|
|
101
79
|
const localeDomain = domains[pathLocale];
|
|
102
80
|
if (localeDomain) {
|
|
103
|
-
if (
|
|
81
|
+
if ((0, _intlayer_core_localization.getDomainHostname)(localeDomain) !== request.nextUrl.hostname) {
|
|
104
82
|
const rawPath = pathname.slice(`/${pathLocale}`.length) || "/";
|
|
105
|
-
const targetOrigin =
|
|
83
|
+
const targetOrigin = (0, _intlayer_core_localization.getDomainOrigin)(localeDomain);
|
|
106
84
|
return next_server.NextResponse.redirect(new URL(`${rawPath}${request.nextUrl.search}`, targetOrigin));
|
|
107
85
|
}
|
|
108
86
|
}
|
|
109
87
|
}
|
|
110
88
|
if (process.env.INTLAYER_ROUTING_DOMAINS !== "false" && !pathLocale) {
|
|
111
|
-
const domainLocale = getLocaleFromDomain(request.nextUrl.hostname);
|
|
112
|
-
if (domainLocale)
|
|
89
|
+
const domainLocale = (0, _intlayer_core_localization.getLocaleFromDomain)(request.nextUrl.hostname, domains);
|
|
90
|
+
if (domainLocale) {
|
|
91
|
+
const internalPath = (0, _intlayer_core_localization.getInternalPath)((0, _intlayer_core_localization.getCanonicalPath)(pathname, domainLocale, rewriteRules), domainLocale);
|
|
92
|
+
return rewriteUrl(request, internalPath + (request.nextUrl.search ?? ""), domainLocale);
|
|
93
|
+
}
|
|
113
94
|
}
|
|
114
95
|
return handlePrefix(request, localLocale, pathLocale, pathname);
|
|
115
96
|
};
|
|
@@ -131,7 +112,8 @@ const handleNoPrefix = (request, localLocale, pathname) => {
|
|
|
131
112
|
if (pathLocale) {
|
|
132
113
|
const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname.slice(`/${pathLocale}`.length) || "/", pathLocale, rewriteRules);
|
|
133
114
|
const search = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
|
|
134
|
-
|
|
115
|
+
const redirectPath = search ? `${canonicalPath}${search}` : `${canonicalPath}${request.nextUrl.search ?? ""}`;
|
|
116
|
+
return redirectUrl(request, redirectPath, pathLocale);
|
|
135
117
|
}
|
|
136
118
|
if (!(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && effectiveMode === "search-params") {
|
|
137
119
|
const existingLocale = new URLSearchParams(request.nextUrl.search).get("locale");
|
|
@@ -139,24 +121,40 @@ const handleNoPrefix = (request, localLocale, pathname) => {
|
|
|
139
121
|
let locale = localLocale ?? (isExistingValid ? existingLocale : void 0) ?? require_proxy_localeDetector.localeDetector?.(request) ?? defaultLocale;
|
|
140
122
|
if (!locales?.includes(locale)) locale = defaultLocale;
|
|
141
123
|
const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname, locale, rewriteRules);
|
|
142
|
-
if (existingLocale === locale)
|
|
124
|
+
if (existingLocale === locale) {
|
|
125
|
+
const rewritePath = `${internalPrefix ? (0, _intlayer_core_localization.getInternalPath)(canonicalPath, locale) : canonicalPath}${request.nextUrl.search ?? ""}`;
|
|
126
|
+
return rewriteUrl(request, rewritePath, locale);
|
|
127
|
+
}
|
|
143
128
|
const search = appendLocaleSearchIfNeeded(request.nextUrl.search, locale);
|
|
144
|
-
|
|
129
|
+
const redirectPath = search ? `${pathname}${search}` : `${pathname}${request.nextUrl.search ?? ""}`;
|
|
130
|
+
return redirectUrl(request, redirectPath);
|
|
145
131
|
}
|
|
146
132
|
let locale = localLocale ?? require_proxy_localeDetector.localeDetector?.(request) ?? defaultLocale;
|
|
147
133
|
if (!locales?.includes(locale)) locale = defaultLocale;
|
|
148
134
|
const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(pathname, locale, rewriteRules);
|
|
149
|
-
const internalPath = internalPrefix ?
|
|
135
|
+
const internalPath = internalPrefix ? (0, _intlayer_core_localization.getInternalPath)(canonicalPath, locale) : canonicalPath;
|
|
150
136
|
const search = appendLocaleSearchIfNeeded(request.nextUrl.search, locale);
|
|
151
|
-
|
|
137
|
+
const rewritePath = search ? `${internalPath}${search}` : `${internalPath}${request.nextUrl.search ?? ""}`;
|
|
138
|
+
return rewriteUrl(request, rewritePath, locale);
|
|
152
139
|
};
|
|
153
140
|
/**
|
|
141
|
+
* Checks whether a pathname starts with the given locale as a full path
|
|
142
|
+
* segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match
|
|
143
|
+
* unrelated paths like `/friends`, causing wrong prefix stripping and
|
|
144
|
+
* self-redirect loops.
|
|
145
|
+
*
|
|
146
|
+
* @param pathname - The pathname to test.
|
|
147
|
+
* @param locale - The locale to look for as the first path segment.
|
|
148
|
+
* @returns - True if the first path segment is exactly the locale.
|
|
149
|
+
*/
|
|
150
|
+
const hasLocaleSegmentPrefix = (pathname, locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);
|
|
151
|
+
/**
|
|
154
152
|
* Extracts the locale from the URL pathname if present.
|
|
155
153
|
*
|
|
156
154
|
* @param pathname - The pathname from the request URL.
|
|
157
155
|
* @returns - The locale found in the pathname, or undefined if not found.
|
|
158
156
|
*/
|
|
159
|
-
const getPathLocale = (pathname) => locales?.find((locale) =>
|
|
157
|
+
const getPathLocale = (pathname) => locales?.find((locale) => hasLocaleSegmentPrefix(pathname, locale));
|
|
160
158
|
/**
|
|
161
159
|
* Handles the case where URLs have locale prefixes.
|
|
162
160
|
*
|
|
@@ -190,7 +188,7 @@ const handleMissingPathLocale = (request, localLocale, pathname) => {
|
|
|
190
188
|
const targetLocalizedPathResult = (0, _intlayer_core_localization.getLocalizedPath)(canonicalPath, locale, rewriteRules);
|
|
191
189
|
const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
|
|
192
190
|
const newPath = constructPath(locale, targetLocalizedPath, basePath, appendLocaleSearchIfNeeded(request.nextUrl.search, locale));
|
|
193
|
-
return prefixDefault || locale !== defaultLocale ? redirectUrl(request, newPath) : rewriteUrl(request, internalPrefix ?
|
|
191
|
+
return prefixDefault || locale !== defaultLocale ? redirectUrl(request, newPath) : rewriteUrl(request, internalPrefix ? (0, _intlayer_core_localization.getInternalPath)(canonicalPath, locale) : canonicalPath, locale);
|
|
194
192
|
};
|
|
195
193
|
/**
|
|
196
194
|
* Handles requests where the locale exists in the URL pathname.
|
|
@@ -206,8 +204,11 @@ const handleExistingPathLocale = (request, pathLocale, pathname) => {
|
|
|
206
204
|
const canonicalPath = (0, _intlayer_core_localization.getCanonicalPath)(rawPath, pathLocale, rewriteRules);
|
|
207
205
|
const targetLocalizedPathResult = (0, _intlayer_core_localization.getLocalizedPath)(canonicalPath, pathLocale, rewriteRules);
|
|
208
206
|
const targetLocalizedPath = typeof targetLocalizedPathResult === "string" ? targetLocalizedPathResult : targetLocalizedPathResult.path;
|
|
209
|
-
if ((typeof targetLocalizedPathResult === "string" ? false : targetLocalizedPathResult.isRewritten) && targetLocalizedPath !== rawPath)
|
|
210
|
-
|
|
207
|
+
if ((typeof targetLocalizedPathResult === "string" ? false : targetLocalizedPathResult.isRewritten) && targetLocalizedPath !== rawPath) {
|
|
208
|
+
const newPath = constructPath(pathLocale, targetLocalizedPath, basePath, appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale));
|
|
209
|
+
return redirectUrl(request, newPath);
|
|
210
|
+
}
|
|
211
|
+
const internalUrl = internalPrefix ? (0, _intlayer_core_localization.getInternalPath)(canonicalPath, pathLocale) : canonicalPath;
|
|
211
212
|
if (!prefixDefault && pathLocale === defaultLocale) return handleDefaultLocaleRedirect(request, pathLocale, canonicalPath);
|
|
212
213
|
const search = request.nextUrl.search;
|
|
213
214
|
return rewriteUrl(request, internalUrl + (search ?? ""), pathLocale);
|
|
@@ -232,7 +233,9 @@ const handleDefaultLocaleRedirect = (request, pathLocale, canonicalPath) => {
|
|
|
232
233
|
const basePathTrailingSlash = basePathValue.endsWith("/");
|
|
233
234
|
let finalPath = targetLocalizedPath;
|
|
234
235
|
if (finalPath.startsWith("/")) finalPath = finalPath.slice(1);
|
|
235
|
-
|
|
236
|
+
const fullPath = `${basePathValue}${basePathTrailingSlash ? "" : "/"}${finalPath}`;
|
|
237
|
+
const searchWithLocale = appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale);
|
|
238
|
+
return redirectUrl(request, fullPath + (searchWithLocale ?? request.nextUrl.search ?? ""), pathLocale);
|
|
236
239
|
};
|
|
237
240
|
/**
|
|
238
241
|
* Constructs a new path by combining the locale, path, basePath, and search parameters.
|
|
@@ -244,11 +247,12 @@ const handleDefaultLocaleRedirect = (request, pathLocale, canonicalPath) => {
|
|
|
244
247
|
* @returns - The constructed new path.
|
|
245
248
|
*/
|
|
246
249
|
const constructPath = (locale, path, basePath, search) => {
|
|
247
|
-
const pathWithoutPrefix = path
|
|
250
|
+
const pathWithoutPrefix = hasLocaleSegmentPrefix(path, locale) ? path.slice(`/${locale}`.length) || "/" : path;
|
|
248
251
|
if (!(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "no-prefix") && effectiveMode === "no-prefix" || !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && effectiveMode === "search-params") return `${pathWithoutPrefix}${search ?? ""}`;
|
|
249
|
-
const pathWithLocalePrefix = path
|
|
252
|
+
const pathWithLocalePrefix = hasLocaleSegmentPrefix(path, locale) ? path : `${locale}${path.startsWith("/") ? "" : "/"}${path}`;
|
|
250
253
|
const basePathValue = basePath || "";
|
|
251
|
-
|
|
254
|
+
const cleanPath = `${basePathValue}${basePathValue.endsWith("/") ? "" : "/"}${pathWithLocalePrefix}`.replace(/\/+/g, "/");
|
|
255
|
+
return cleanPath !== "/" && cleanPath.endsWith("/") ? cleanPath.slice(0, -1) : cleanPath;
|
|
252
256
|
};
|
|
253
257
|
/**
|
|
254
258
|
* This handles the internal path Next.js sees.
|
|
@@ -276,14 +280,46 @@ const rewriteUrl = (request, newPath, locale) => {
|
|
|
276
280
|
*
|
|
277
281
|
* @param request - The incoming Next.js request object.
|
|
278
282
|
* @param newPath - The new path to redirect to.
|
|
283
|
+
* @param persistLocale - When provided, the locale is written to storage
|
|
284
|
+
* (cookie/header, per config) on the redirect response so the follow-up
|
|
285
|
+
* request resolves the same locale instead of re-running detection.
|
|
279
286
|
* @returns - The redirect response.
|
|
280
287
|
*/
|
|
281
|
-
const redirectUrl = (request, newPath) => {
|
|
288
|
+
const redirectUrl = (request, newPath, persistLocale) => {
|
|
282
289
|
const search = request.nextUrl.search;
|
|
283
290
|
const pathWithSearch = search && !newPath.includes("?") ? `${newPath}${search}` : newPath;
|
|
284
291
|
const target = new URL(pathWithSearch, request.url);
|
|
285
292
|
const safeTarget = target.origin === request.nextUrl.origin ? target : new URL(`${target.pathname}${target.search}${target.hash}`, request.url);
|
|
286
|
-
|
|
293
|
+
const response = next_server.NextResponse.redirect(safeTarget);
|
|
294
|
+
if (persistLocale) persistLocaleOnResponse(response, persistLocale);
|
|
295
|
+
return response;
|
|
296
|
+
};
|
|
297
|
+
/**
|
|
298
|
+
* Writes the resolved locale to the outgoing response's storage (cookie and/or
|
|
299
|
+
* header, according to `routing.storage`). Only the cookie survives a client
|
|
300
|
+
* redirect, so this is what carries an explicitly-selected locale across a
|
|
301
|
+
* prefix-stripping redirect. Enabled cookie/header targets are resolved by
|
|
302
|
+
* {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.
|
|
303
|
+
*
|
|
304
|
+
* @param response - The outgoing Next.js response to attach storage to.
|
|
305
|
+
* @param locale - The locale to persist.
|
|
306
|
+
*/
|
|
307
|
+
const persistLocaleOnResponse = (response, locale) => {
|
|
308
|
+
(0, _intlayer_core_utils.setLocaleInStorageServer)(locale, {
|
|
309
|
+
setCookieStore: (name, value, attributes) => {
|
|
310
|
+
response.cookies.set(name, value, {
|
|
311
|
+
path: attributes.path,
|
|
312
|
+
domain: attributes.domain,
|
|
313
|
+
expires: typeof attributes.expires === "number" ? new Date(attributes.expires) : attributes.expires,
|
|
314
|
+
secure: attributes.secure,
|
|
315
|
+
sameSite: attributes.sameSite,
|
|
316
|
+
httpOnly: attributes.httpOnly
|
|
317
|
+
});
|
|
318
|
+
},
|
|
319
|
+
setHeader: (name, value) => {
|
|
320
|
+
response.headers.set(name, value);
|
|
321
|
+
}
|
|
322
|
+
});
|
|
287
323
|
};
|
|
288
324
|
|
|
289
325
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxy.cjs","names":["internationalization","routing","ROUTING_MODE","NextResponse","localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport {\n getLocaleFromStorageServer,\n setLocaleInStorageServer,\n} 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 { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite, domains, enableProxy } = routing ?? {};\n\n// Whether the locale-routing proxy is enabled (default: true). When disabled,\n// `intlayerProxy` becomes a pass-through so apps can handle routing themselves.\n// The env var is injected at build time so bundlers can tree-shake this branch.\nconst isProxyEnabled =\n process.env.INTLAYER_ROUTING_ENABLE_PROXY !== 'false' &&\n (enableProxy ?? true);\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 (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params');\nconst prefixDefault =\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all'\n ) && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules =\n process.env.INTLAYER_ROUTING_REWRITE_RULES !== 'false'\n ? getRewriteRules(rewrite, 'url')\n : undefined;\n\n/**\n * Strips the protocol from a domain string and returns only the hostname.\n * e.g. 'https://intlayer.zh' → 'intlayer.zh', 'intlayer.zh' → 'intlayer.zh'\n */\nconst normalizeDomainHostname = (domain: string): string => {\n try {\n return /^https?:\\/\\//.test(domain) ? new URL(domain).hostname : domain;\n } catch {\n return domain;\n }\n};\n\n/**\n * Returns the locale exclusively mapped to a given hostname via `routing.domains`,\n * or undefined if zero or more than one locale share that hostname.\n *\n * Example: with domains = { zh: 'intlayer.zh', fr: 'intlayer.org' }\n * getLocaleFromDomain('intlayer.zh') → 'zh'\n * getLocaleFromDomain('intlayer.org') → undefined (multiple locales share it)\n */\nconst getLocaleFromDomain = (hostname: string): Locale | undefined => {\n if (!domains) return undefined;\n\n const matching = Object.entries(domains).filter(\n ([, domain]) => normalizeDomainHostname(domain!) === hostname\n );\n\n return matching.length === 1 ? (matching[0]?.[0] as Locale) : undefined;\n};\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 (\n (process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params') ||\n effectiveMode !== 'search-params'\n )\n 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 *\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n // When the proxy is disabled, pass the request through untouched.\n if (!isProxyEnabled) {\n return NextResponse.next();\n }\n\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\n // Domain routing: if the path locale is mapped to a different domain, redirect there.\n // e.g. intlayer.org/zh/about → https://intlayer.zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n pathLocale &&\n domains\n ) {\n const localeDomain = domains[pathLocale];\n\n if (localeDomain) {\n const domainHost = normalizeDomainHostname(localeDomain);\n\n if (domainHost !== request.nextUrl.hostname) {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n const targetOrigin = /^https?:\\/\\//.test(localeDomain)\n ? localeDomain\n : `https://${localeDomain}`;\n\n return NextResponse.redirect(\n new URL(`${rawPath}${request.nextUrl.search}`, targetOrigin)\n );\n }\n }\n }\n\n // Domain routing: if the current hostname is exclusively mapped to one locale,\n // treat it as that locale's domain — no URL prefix needed.\n // e.g. intlayer.zh/about → internally rewrite to /zh/about\n if (process.env.INTLAYER_ROUTING_DOMAINS !== 'false' && !pathLocale) {\n const domainLocale = getLocaleFromDomain(request.nextUrl.hostname);\n\n if (domainLocale) {\n const canonicalPath = getCanonicalPath(\n pathname,\n domainLocale,\n rewriteRules\n );\n const internalPath = `/${domainLocale}${canonicalPath}`;\n\n return rewriteUrl(\n request,\n internalPath + (request.nextUrl.search ?? ''),\n domainLocale\n );\n }\n }\n\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 getLocaleFromStorageServer({\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 (\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params'\n ) {\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 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[] | undefined)?.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?.includes(locale as 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 // Fix: pass `canonicalPath` (the path *without* the locale prefix, e.g. /pricing)\n // instead of `pathname` (the full path including prefix, e.g. /en/pricing).\n // Previously this caused an infinite redirect loop in prefix-no-default mode\n // because handleDefaultLocaleRedirect built the redirect target from its third\n // argument, which reproduced the same URL on every response.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, canonicalPath);\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 // Always called with !prefixDefault && pathLocale === defaultLocale (pre-validated by caller).\n // Redirect to strip the default-locale prefix from the URL.\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 const basePathValue = (basePath as string) || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePathValue}${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/**\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 (\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params')\n ) {\n // `search` is either undefined or already has a leading '?' (from\n // appendLocaleSearchIfNeeded / request.nextUrl.search), so append as-is.\n return `${pathWithoutPrefix}${search ?? ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathValue = basePath || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n const newPath = `${basePathValue}${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\n // Next.js strips `basePath` from `request.nextUrl.pathname` before the\n // middleware runs, so every path computed from it (e.g. `/en/about`) lacks\n // the basePath prefix. When we pass that as an absolute path to `new URL`,\n // it replaces the entire path after the origin, silently discarding the\n // basePath (e.g. `new URL('/en/', 'http://host/weather/')` →\n // `http://host/en/`). Prepending the configured basePath restores the\n // correct mount-point so rewrites resolve under the app root.\n const basePathValue = (basePath as string) || '';\n const pathWithBase =\n basePathValue && !newPath.startsWith(basePathValue)\n ? `${basePathValue}${newPath}`\n : newPath;\n\n const pathWithSearch =\n search && !pathWithBase.includes('?')\n ? `${pathWithBase}${search}`\n : pathWithBase;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorageServer(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 setLocaleInStorageServer(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 const target = new URL(pathWithSearch, request.url);\n\n // Prevent open redirect: if the resolved origin differs from the request\n // origin, strip it back to a same-origin URL using only the path/search/hash.\n const safeTarget =\n target.origin === request.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n request.url\n );\n\n return NextResponse.redirect(safeTarget);\n};\n"],"mappings":";;;;;;;;;;AAuDA,MAAM,EAAE,SAAS,kBAAkBA,+CAAwB,EAAE;AAC7D,MAAM,EAAE,UAAU,MAAM,SAAS,SAAS,gBAAgBC,kCAAW,EAAE;AAKvE,MAAM,iBACJ,QAAQ,IAAI,kCAAkC,YAC7C,eAAe;AAKlB,MAAM,gBAAgB,QAAQC;AAC9B,MAAM,WACH,EACC,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,gBAEtC,kBAAkB,eACnB,EACC,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,oBAEtC,kBAAkB;AACtB,MAAM,gBACJ,EACE,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,iBACnC,kBAAkB;AAEzB,MAAM,iBAAiB,CAAC;AAExB,MAAM,eACJ,QAAQ,IAAI,mCAAmC,2DAC3B,SAAS,MAAM,GAC/B;;;;;AAMN,MAAM,2BAA2B,WAA2B;AAC1D,KAAI;AACF,SAAO,eAAe,KAAK,OAAO,GAAG,IAAI,IAAI,OAAO,CAAC,WAAW;SAC1D;AACN,SAAO;;;;;;;;;;;AAYX,MAAM,uBAAuB,aAAyC;AACpE,KAAI,CAAC,QAAS,QAAO;CAErB,MAAM,WAAW,OAAO,QAAQ,QAAQ,CAAC,QACtC,GAAG,YAAY,wBAAwB,OAAQ,KAAK,SACtD;AAED,QAAO,SAAS,WAAW,IAAK,SAAS,KAAK,KAAgB;;;;;;;;;;;;;;;;AAiBhE,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,gBAAg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/B,MAAM,gBAAiB,YAAuB;CAC9C,MAAM,eACJ,iBAAiB,CAAC,QAAQ,WAAW,cAAc,GAC/C,GAAG,gBAAgB,YACnB;CAEN,MAAM,iBACJ,UAAU,CAAC,aAAa,SAAS,IAAI,GACjC,GAAG,eAAe,WAClB;CAEN,MAAM,iBAAiB,IAAI,QAAQ,QAAQ,QAAQ;AACnD,oDAAyB,QAAQ,EAC/B,YAAY,MAAc,UAAkB;AAC1C,iBAAe,IAAI,MAAM,MAAM;IAElC,CAAC;CAEF,MAAM,YAAY,IAAI,IAAI,gBAAgB,QAAQ,IAAI;CAItD,MAAM,WACJ,UAAU,SAAS,QAAQ,QAAQ,OAC/BD,yBAAa,KAAK,EAChB,SAAS,EACP,SAAS,gBACV,EACF,CAAC,GACFA,yBAAa,QAAQ,WAAW,EAC9B,SAAS,EACP,SAAS,gBACV,EACF,CAAC;AAER,oDAAyB,QAAQ,EAC/B,YAAY,MAAc,UAAkB;AAC1C,WAAS,QAAQ,IAAI,MAAM,MAAM;IAEpC,CAAC;AACF,QAAO;;;;;;;;;AAUT,MAAM,eAAe,SAAsB,YAAkC;CAC3E,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,iBACJ,UAAU,CAAC,QAAQ,SAAS,IAAI,GAAG,GAAG,UAAU,WAAW;CAE7D,MAAM,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI;CAInD,MAAM,aACJ,OAAO,WAAW,QAAQ,QAAQ,SAC9B,SACA,IAAI,IACF,GAAG,OAAO,WAAW,OAAO,SAAS,OAAO,QAC5C,QAAQ,IACT;AAEP,QAAOA,yBAAa,SAAS,WAAW"}
|
|
1
|
+
{"version":3,"file":"intlayerProxy.cjs","names":["internationalization","routing","ROUTING_MODE","NextResponse","localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getInternalPath,\n getLocaleFromDomain,\n getLocalizedPath,\n getRewriteRules,\n type LocaleDomainMap,\n} from '@intlayer/core/localization';\nimport {\n getLocaleFromStorageServer,\n setLocaleInStorageServer,\n} 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 { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite, domains, enableProxy } = routing ?? {};\n\n// Whether the locale-routing proxy is enabled (default: true). When disabled,\n// `intlayerProxy` becomes a pass-through so apps can handle routing themselves.\n// The env var is injected at build time so bundlers can tree-shake this branch.\nconst isProxyEnabled =\n process.env.INTLAYER_ROUTING_ENABLE_PROXY !== 'false' &&\n (enableProxy ?? true);\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 (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params');\nconst prefixDefault =\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all'\n ) && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules =\n process.env.INTLAYER_ROUTING_REWRITE_RULES !== 'false'\n ? getRewriteRules(rewrite, 'url')\n : undefined;\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests are identified by:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js app-router prefetch)\n *\n * Note: `next-url` and `x-nextjs-data` are intentionally NOT used here.\n * Both are also sent on real client-side navigations (RSC navigation\n * requests and pages-router data requests respectively), so treating them\n * as prefetch would force such navigations to the default locale instead\n * of the user's stored locale.\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\n return purpose === 'prefetch' || nextRouterPrefetch === '1';\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 (\n (process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params') ||\n effectiveMode !== 'search-params'\n )\n 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 *\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n // When the proxy is disabled, pass the request through untouched.\n if (!isProxyEnabled) {\n return NextResponse.next();\n }\n\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\n // Domain routing: if the path locale is mapped to a different domain, redirect there.\n // e.g. intlayer.org/zh/about → https://intlayer.zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n pathLocale &&\n domains\n ) {\n const localeDomain = domains[pathLocale];\n\n if (localeDomain) {\n const domainHost = getDomainHostname(localeDomain);\n\n if (domainHost !== request.nextUrl.hostname) {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n const targetOrigin = getDomainOrigin(localeDomain);\n\n return NextResponse.redirect(\n new URL(`${rawPath}${request.nextUrl.search}`, targetOrigin)\n );\n }\n }\n }\n\n // Domain routing: if the current hostname is exclusively mapped to one locale,\n // treat it as that locale's domain — no URL prefix needed.\n // e.g. intlayer.zh/about → internally rewrite to /zh/about\n if (process.env.INTLAYER_ROUTING_DOMAINS !== 'false' && !pathLocale) {\n const domainLocale = getLocaleFromDomain(\n request.nextUrl.hostname,\n domains as LocaleDomainMap\n );\n\n if (domainLocale) {\n const canonicalPath = getCanonicalPath(\n pathname,\n domainLocale,\n rewriteRules\n );\n\n // Never emit a trailing slash (`/zh/`): Next.js trailing-slash\n // normalisation would redirect it back and forth with this proxy.\n const internalPath = getInternalPath(canonicalPath, domainLocale);\n\n return rewriteUrl(\n request,\n internalPath + (request.nextUrl.search ?? ''),\n domainLocale\n );\n }\n }\n\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 getLocaleFromStorageServer({\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 // Persist the explicitly-requested locale: stripping the prefix drops the\n // only locale signal from the URL, so without this the follow-up request\n // would fall back to cookie / Accept-Language detection and could resolve\n // a different locale.\n return redirectUrl(request, redirectPath, pathLocale);\n }\n\n if (\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params'\n ) {\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 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 ? getInternalPath(canonicalPath, locale as Locale)\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 ? getInternalPath(canonicalPath, locale as Locale)\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 * Checks whether a pathname starts with the given locale as a full path\n * segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match\n * unrelated paths like `/friends`, causing wrong prefix stripping and\n * self-redirect loops.\n *\n * @param pathname - The pathname to test.\n * @param locale - The locale to look for as the first path segment.\n * @returns - True if the first path segment is exactly the locale.\n */\nconst hasLocaleSegmentPrefix = (pathname: string, locale: Locale): boolean =>\n pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);\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[] | undefined)?.find((locale) =>\n hasLocaleSegmentPrefix(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?.includes(locale as 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 // Never emit a trailing slash (`/en/` for canonicalPath `/`): Next.js\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy. `getInternalPath` collapses the root path to `/${locale}`.\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? getInternalPath(canonicalPath, locale) : 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 // Never emit a trailing slash (`/fr/` for the bare `/fr` URL): rewriting\n // `/fr` to `/fr/` makes Next.js issue a trailing-slash normalisation\n // redirect back to `/fr`, which this proxy rewrites again — an infinite\n // redirect loop. `getInternalPath` collapses the root path to `/${locale}`.\n const internalUrl = internalPrefix\n ? getInternalPath(canonicalPath, pathLocale)\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n // Fix: pass `canonicalPath` (the path *without* the locale prefix, e.g. /pricing)\n // instead of `pathname` (the full path including prefix, e.g. /en/pricing).\n // Previously this caused an infinite redirect loop in prefix-no-default mode\n // because handleDefaultLocaleRedirect built the redirect target from its third\n // argument, which reproduced the same URL on every response.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, canonicalPath);\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 // Always called with !prefixDefault && pathLocale === defaultLocale (pre-validated by caller).\n // Redirect to strip the default-locale prefix from the URL.\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 const basePathValue = (basePath as string) || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // Persist the explicitly-requested default locale. Stripping the prefix\n // (e.g. /es → /) drops the only locale signal from the URL, so without this\n // the follow-up request to the canonical path would fall back to\n // Accept-Language detection and could resolve a different locale (e.g. /en).\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? ''),\n pathLocale\n );\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 = hasLocaleSegmentPrefix(path, locale)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params')\n ) {\n // `search` is either undefined or already has a leading '?' (from\n // appendLocaleSearchIfNeeded / request.nextUrl.search), so append as-is.\n return `${pathWithoutPrefix}${search ?? ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = hasLocaleSegmentPrefix(path, locale)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathValue = basePath || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n const newPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n // Never emit a trailing slash (`/fr/` for the root path): the framework's\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy, creating an infinite redirect loop.\n return cleanPath !== '/' && cleanPath.endsWith('/')\n ? cleanPath.slice(0, -1)\n : 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\n // Next.js strips `basePath` from `request.nextUrl.pathname` before the\n // middleware runs, so every path computed from it (e.g. `/en/about`) lacks\n // the basePath prefix. When we pass that as an absolute path to `new URL`,\n // it replaces the entire path after the origin, silently discarding the\n // basePath (e.g. `new URL('/en/', 'http://host/weather/')` →\n // `http://host/en/`). Prepending the configured basePath restores the\n // correct mount-point so rewrites resolve under the app root.\n const basePathValue = (basePath as string) || '';\n const pathWithBase =\n basePathValue && !newPath.startsWith(basePathValue)\n ? `${basePathValue}${newPath}`\n : newPath;\n\n const pathWithSearch =\n search && !pathWithBase.includes('?')\n ? `${pathWithBase}${search}`\n : pathWithBase;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorageServer(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 setLocaleInStorageServer(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 * @param persistLocale - When provided, the locale is written to storage\n * (cookie/header, per config) on the redirect response so the follow-up\n * request resolves the same locale instead of re-running detection.\n * @returns - The redirect response.\n */\nconst redirectUrl = (\n request: NextRequest,\n newPath: string,\n persistLocale?: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const target = new URL(pathWithSearch, request.url);\n\n // Prevent open redirect: if the resolved origin differs from the request\n // origin, strip it back to a same-origin URL using only the path/search/hash.\n const safeTarget =\n target.origin === request.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n request.url\n );\n\n const response = NextResponse.redirect(safeTarget);\n\n if (persistLocale) {\n persistLocaleOnResponse(response, persistLocale);\n }\n\n return response;\n};\n\n/**\n * Writes the resolved locale to the outgoing response's storage (cookie and/or\n * header, according to `routing.storage`). Only the cookie survives a client\n * redirect, so this is what carries an explicitly-selected locale across a\n * prefix-stripping redirect. Enabled cookie/header targets are resolved by\n * {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.\n *\n * @param response - The outgoing Next.js response to attach storage to.\n * @param locale - The locale to persist.\n */\nconst persistLocaleOnResponse = (\n response: NextResponse,\n locale: Locale\n): void => {\n setLocaleInStorageServer(locale, {\n setCookieStore: (name, value, attributes) => {\n response.cookies.set(name, value, {\n path: attributes.path,\n domain: attributes.domain,\n expires:\n typeof attributes.expires === 'number'\n ? new Date(attributes.expires)\n : attributes.expires,\n secure: attributes.secure,\n sameSite: attributes.sameSite,\n httpOnly: attributes.httpOnly,\n });\n },\n setHeader: (name, value) => {\n response.headers.set(name, value);\n },\n });\n};\n"],"mappings":";;;;;;;;;AA4DA,MAAM,EAAE,SAAS,kBAAkBA,+CAAwB,CAAC;AAC5D,MAAM,EAAE,UAAU,MAAM,SAAS,SAAS,gBAAgBC,kCAAW,CAAC;AAKtE,MAAM,iBACJ,QAAQ,IAAI,kCAAkC,YAC7C,eAAe;AAKlB,MAAM,gBAAgB,QAAQC;AAC9B,MAAM,WACH,EACC,QAA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yBAAa,KAAK,EAChB,SAAS,EACP,SAAS,eACX,EACF,CAAC,IACDA,yBAAa,QAAQ,WAAW,EAC9B,SAAS,EACP,SAAS,eACX,EACF,CAAC;CAEP,mDAAyB,QAAQ,EAC/B,YAAY,MAAc,UAAkB;EAC1C,SAAS,QAAQ,IAAI,MAAM,KAAK;CAClC,EACF,CAAC;CACD,OAAO;AACT;;;;;;;;;;;AAYA,MAAM,eACJ,SACA,SACA,kBACiB;CACjB,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,iBACJ,UAAU,CAAC,QAAQ,SAAS,GAAG,IAAI,GAAG,UAAU,WAAW;CAE7D,MAAM,SAAS,IAAI,IAAI,gBAAgB,QAAQ,GAAG;CAIlD,MAAM,aACJ,OAAO,WAAW,QAAQ,QAAQ,SAC9B,SACA,IAAI,IACF,GAAG,OAAO,WAAW,OAAO,SAAS,OAAO,QAC5C,QAAQ,GACV;CAEN,MAAM,WAAWA,yBAAa,SAAS,UAAU;CAEjD,IAAI,eACF,wBAAwB,UAAU,aAAa;CAGjD,OAAO;AACT;;;;;;;;;;;AAYA,MAAM,2BACJ,UACA,WACS;CACT,mDAAyB,QAAQ;EAC/B,iBAAiB,MAAM,OAAO,eAAe;GAC3C,SAAS,QAAQ,IAAI,MAAM,OAAO;IAChC,MAAM,WAAW;IACjB,QAAQ,WAAW;IACnB,SACE,OAAO,WAAW,YAAY,WAC1B,IAAI,KAAK,WAAW,OAAO,IAC3B,WAAW;IACjB,QAAQ,WAAW;IACnB,UAAU,WAAW;IACrB,UAAU,WAAW;GACvB,CAAC;EACH;EACA,YAAY,MAAM,UAAU;GAC1B,SAAS,QAAQ,IAAI,MAAM,KAAK;EAClC;CACF,CAAC;AACH"}
|
|
@@ -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":"
|
|
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,CAAC;CAEnD,QAAQ,QAAQ,SAAS,OAAO,QAAQ;EACtC,kBAAkB,OAAO;CAC3B,CAAC;CAID,uDAFkC,iBAEtB;AACd"}
|