next-intlayer 8.6.3 → 8.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/cjs/client/useLocale.cjs.map +1 -1
  2. package/dist/cjs/generateStaticParams.cjs +1 -2
  3. package/dist/cjs/generateStaticParams.cjs.map +1 -1
  4. package/dist/cjs/proxy/intlayerProxy.cjs +2 -4
  5. package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
  6. package/dist/cjs/server/getLocale.cjs +1 -2
  7. package/dist/cjs/server/getLocale.cjs.map +1 -1
  8. package/dist/cjs/server/withIntlayer.cjs +15 -13
  9. package/dist/cjs/server/withIntlayer.cjs.map +1 -1
  10. package/dist/esm/client/useLocale.mjs.map +1 -1
  11. package/dist/esm/generateStaticParams.mjs +2 -2
  12. package/dist/esm/generateStaticParams.mjs.map +1 -1
  13. package/dist/esm/proxy/intlayerProxy.mjs +1 -2
  14. package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
  15. package/dist/esm/server/getLocale.mjs +2 -2
  16. package/dist/esm/server/getLocale.mjs.map +1 -1
  17. package/dist/esm/server/withIntlayer.mjs +16 -14
  18. package/dist/esm/server/withIntlayer.mjs.map +1 -1
  19. package/dist/types/client/useLocale.d.ts +6 -7
  20. package/dist/types/client/useLocale.d.ts.map +1 -1
  21. package/dist/types/generateStaticParams.d.ts.map +1 -1
  22. package/dist/types/index.d.ts +1 -1
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/intlayer/dist/types/index.d.ts +1 -2
  25. package/dist/types/proxy/intlayerProxy.d.ts.map +1 -1
  26. package/dist/types/server/useDictionary.d.ts +1 -1
  27. package/dist/types/server/useDictionaryAsync.d.ts +1 -1
  28. package/dist/types/server/useDictionaryDynamic.d.ts +1 -1
  29. package/dist/types/server/useIntlayer.d.ts +1 -1
  30. package/dist/types/server/withIntlayer.d.ts +1 -2
  31. package/dist/types/server/withIntlayer.d.ts.map +1 -1
  32. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"useLocale.cjs","names":[],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport { usePathname, useRouter } from 'next/navigation.js';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\n\ntype UseLocaleProps = {\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: DeclaredLocales; path: string }) => void);\n};\n\nconst usePathWithoutLocale = () => {\n const pathname = usePathname(); // updates on client navigations\n const [fullPath, setFullPath] = useState(pathname);\n\n useEffect(() => {\n // Runs only on client; avoids suspense.\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setFullPath(search ? `${pathname}${search}` : pathname);\n }, [pathname]);\n\n // Your own helper\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\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 = ({ onChange = 'replace' }: UseLocaleProps = {}) => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathWithoutLocale();\n\n const redirectionFunction = useCallback(\n (locale: DeclaredLocales) => {\n if (!onChange) return;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n },\n [replace, push, pathWithoutLocale, onChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n };\n};\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,6BAA6B;CACjC,MAAM,gDAAwB;CAC9B,MAAM,CAAC,UAAU,mCAAwB,SAAS;AAElD,4BAAgB;EAEd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,cAAY,SAAS,GAAG,WAAW,WAAW,SAAS;IACtD,CAAC,SAAS,CAAC;AAGd,uFAA0C,SAAS,EAAE,CAAC,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BlE,MAAa,aAAa,EAAE,WAAW,cAA8B,EAAE,KAAK;CAC1E,MAAM,EAAE,SAAS,4CAAoB;CACrC,MAAM,oBAAoB,sBAAsB;AA2BhD,QAAO;EACL,iCALqC,EACrC,wCArBC,WAA4B;AAC3B,OAAI,CAAC,SAAU;GAEf,MAAM,kEAAiC,mBAAmB,OAAO;AAEjE,OAAI,OAAO,aAAa,YAAY;AAClC,aAAS;KAAE;KAAQ,MAAM;KAAgB,CAAC;AAC1C;;AAGF,OAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,OAAI,aAAa,OACf,MAAK,eAAe;KAGxB;GAAC;GAAS;GAAM;GAAmB;GAAS,CAC7C,EAIA,CAAC;EAIA;EACD"}
1
+ {"version":3,"file":"useLocale.cjs","names":[],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { usePathname, useRouter } from 'next/navigation.js';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\n\ntype UseLocaleProps = {\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nconst usePathWithoutLocale = () => {\n const pathname = usePathname(); // updates on client navigations\n const [fullPath, setFullPath] = useState(pathname);\n\n useEffect(() => {\n // Runs only on client; avoids suspense.\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setFullPath(search ? `${pathname}${search}` : pathname);\n }, [pathname]);\n\n // Your own helper\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\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 = ({ onChange = 'replace' }: UseLocaleProps = {}) => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathWithoutLocale();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n },\n [replace, push, pathWithoutLocale, onChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n };\n};\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,6BAA6B;CACjC,MAAM,gDAAwB;CAC9B,MAAM,CAAC,UAAU,mCAAwB,SAAS;AAElD,4BAAgB;EAEd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,cAAY,SAAS,GAAG,WAAW,WAAW,SAAS;IACtD,CAAC,SAAS,CAAC;AAGd,uFAA0C,SAAS,EAAE,CAAC,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BlE,MAAa,aAAa,EAAE,WAAW,cAA8B,EAAE,KAAK;CAC1E,MAAM,EAAE,SAAS,4CAAoB;CACrC,MAAM,oBAAoB,sBAAsB;AA2BhD,QAAO;EACL,iCALqC,EACrC,wCArBC,WAA0B;AACzB,OAAI,CAAC,SAAU;GAEf,MAAM,kEAAiC,mBAAmB,OAAO;AAEjE,OAAI,OAAO,aAAa,YAAY;AAClC,aAAS;KAAE;KAAQ,MAAM;KAAgB,CAAC;AAC1C;;AAGF,OAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,OAAI,aAAa,OACf,MAAK,eAAe;KAGxB;GAAC;GAAS;GAAM;GAAmB;GAAS,CAC7C,EAIA,CAAC;EAIA;EACD"}
@@ -1,10 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
3
  let _intlayer_config_built = require("@intlayer/config/built");
4
- _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
5
4
 
6
5
  //#region src/generateStaticParams.ts
7
- const { locales } = _intlayer_config_built.default.internationalization;
6
+ const { locales } = _intlayer_config_built.internationalization;
8
7
  /**
9
8
  * Generates static parameters for Next.js's dynamic routes based on the configured locales.
10
9
  *
@@ -1 +1 @@
1
- {"version":3,"file":"generateStaticParams.cjs","names":["configuration"],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\n\nconst { locales } = configuration.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,+BAAc;;;;;;;;;;;;;;;;;;;AAoBlC,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,QAAQ,EAAE"}
1
+ {"version":3,"file":"generateStaticParams.cjs","names":["internationalization"],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n\nconst { locales } = internationalization;\n\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":";;;;;AAGA,MAAM,EAAE,YAAYA;;;;;;;;;;;;;;;;;;;AAqBpB,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,QAAQ,EAAE"}
@@ -3,7 +3,6 @@ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
3
  const require_proxy_localeDetector = require('./localeDetector.cjs');
4
4
  let _intlayer_core_localization = require("@intlayer/core/localization");
5
5
  let _intlayer_config_built = require("@intlayer/config/built");
6
- _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
7
6
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
8
7
  let _intlayer_core_utils = require("@intlayer/core/utils");
9
8
  let next_server = require("next/server");
@@ -28,9 +27,8 @@ const TREE_SHAKE_PREFIX_MODES = process.env["INTLAYER_ROUTING_MODE"] && process.
28
27
  * (INTLAYER_ROUTING_REWRITE_RULES === 'false').
29
28
  */
30
29
  const TREE_SHAKE_REWRITE = process.env["INTLAYER_ROUTING_REWRITE_RULES"] === "false";
31
- const { internationalization, routing } = _intlayer_config_built.default ?? {};
32
- const { locales, defaultLocale } = internationalization ?? {};
33
- const { basePath, mode, rewrite } = routing ?? {};
30
+ const { locales, defaultLocale } = _intlayer_config_built.internationalization ?? {};
31
+ const { basePath, mode, rewrite } = _intlayer_config_built.routing ?? {};
34
32
  const effectiveMode = mode ?? _intlayer_config_defaultValues.ROUTING_MODE;
35
33
  const noPrefix = !TREE_SHAKE_NO_PREFIX && effectiveMode === "no-prefix" || !TREE_SHAKE_SEARCH_PARAMS && effectiveMode === "search-params";
36
34
  const prefixDefault = !TREE_SHAKE_PREFIX_MODES && effectiveMode === "prefix-all";
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.cjs","names":["configuration","ROUTING_MODE","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\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\n/**\n * True when the build-time routing mode is known and is NOT 'no-prefix'.\n * Use to guard no-prefix-specific code paths so bundlers can eliminate them.\n */\nconst TREE_SHAKE_NO_PREFIX =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\n/**\n * True when rewrite rules are explicitly disabled at build time\n * (INTLAYER_ROUTING_REWRITE_RULES === 'false').\n */\nconst TREE_SHAKE_REWRITE =\n process.env['INTLAYER_ROUTING_REWRITE_RULES'] === 'false';\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 { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params');\nconst prefixDefault =\n !TREE_SHAKE_PREFIX_MODES && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = !TREE_SHAKE_REWRITE\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 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 (TREE_SHAKE_SEARCH_PARAMS || effectiveMode !== 'search-params')\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 */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n 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 (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params')\n ) {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n 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 return NextResponse.redir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B,eAC3C,CAAC,4BAA4B,kBAAkB,gBAEhD,QAAO,GAAG,oBAAoB,SAAS,IAAI,WAAW;CAIxD,MAAM,uBAAuB,KAAK,WAAW,IAAI,SAAS,GACtD,OACA,GAAG,SAAS,KAAK,WAAW,IAAI,GAAG,KAAK,MAAM;AAQlD,QALgB,GAAG,WADW,SAAS,SAAS,IAAI,GACE,KAAK,MAAM,uBAGvC,QAAQ,QAAQ,IAAI;;;;;;;AAUhD,MAAM,cACJ,SACA,SACA,WACiB;CACjB,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,iBACJ,UAAU,CAAC,QAAQ,SAAS,IAAI,GAAG,GAAG,UAAU,WAAW;CAE7D,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/BC,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;AAE7D,QAAOA,yBAAa,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI,CAAC"}
1
+ {"version":3,"file":"intlayerProxy.cjs","names":["internationalization","routing","ROUTING_MODE","localeDetector","NextResponse"],"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\n/**\n * True when the build-time routing mode is known and is NOT 'no-prefix'.\n * Use to guard no-prefix-specific code paths so bundlers can eliminate them.\n */\nconst TREE_SHAKE_NO_PREFIX =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\n/**\n * True when rewrite rules are explicitly disabled at build time\n * (INTLAYER_ROUTING_REWRITE_RULES === 'false').\n */\nconst TREE_SHAKE_REWRITE =\n process.env['INTLAYER_ROUTING_REWRITE_RULES'] === 'false';\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 } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params');\nconst prefixDefault =\n !TREE_SHAKE_PREFIX_MODES && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = !TREE_SHAKE_REWRITE\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 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 (TREE_SHAKE_SEARCH_PARAMS || effectiveMode !== 'search-params')\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 */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n 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 (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params')\n ) {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n 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 return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAM,uBACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;AAK3C,MAAM,2BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAAM,0BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBACzC,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAAM,qBACJ,QAAQ,IAAI,sCAAsC;AAkDpD,MAAM,EAAE,SAAS,kBAAkBA,+CAAwB,EAAE;AAC7D,MAAM,EAAE,UAAU,MAAM,YAAYC,kCAAW,EAAE;AAKjD,MAAM,gBAAgB,QAAQC;AAC9B,MAAM,WACH,CAAC,wBAAwB,kBAAkB,eAC3C,CAAC,4BAA4B,kBAAkB;AAClD,MAAM,gBACJ,CAAC,2BAA2B,kBAAkB;AAEhD,MAAM,iBAAiB,CAAC;AAExB,MAAM,eAAe,CAAC,sEACF,SAAS,MAAM,GAC/B;;;;;;;;;;;;;;;AAgB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F,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;AAE7D,QAAOA,yBAAa,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI,CAAC"}
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
3
  let _intlayer_core_localization = require("@intlayer/core/localization");
4
4
  let _intlayer_config_built = require("@intlayer/config/built");
5
- _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
6
5
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
7
6
  let _intlayer_core_utils = require("@intlayer/core/utils");
8
7
  let next_headers_js = require("next/headers.js");
@@ -27,7 +26,7 @@ let next_headers_js = require("next/headers.js");
27
26
  * ```
28
27
  */
29
28
  const getLocale = async () => {
30
- const defaultLocale = _intlayer_config_built.default?.internationalization?.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE;
29
+ const defaultLocale = _intlayer_config_built.internationalization?.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE;
31
30
  const headersList = await (0, next_headers_js.headers)();
32
31
  const cookiesList = await (0, next_headers_js.cookies)();
33
32
  const storedLocale = (0, _intlayer_core_utils.getLocaleFromStorageServer)({
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.cjs","names":["configuration","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBACJA,gCAAe,sBAAsB,iBAAiBC;CAGxD,MAAM,cAAc,oCAAe;CACnC,MAAM,cAAc,oCAAe;CAEnC,MAAM,oEAA0C;EAC9C,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qEAAoC,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}
1
+ {"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBAAgBA,6CAAsB,iBAAiBC;CAG7D,MAAM,cAAc,oCAAe;CACnC,MAAM,cAAc,oCAAe;CAEnC,MAAM,oEAA0C;EAC9C,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qEAAoC,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}
@@ -138,7 +138,7 @@ const getCommandsEvent = () => {
138
138
  * export default withIntlayerSync(nextConfig)
139
139
  * ```
140
140
  */
141
- const withIntlayerSync = (nextConfig = {}, configOptions, unusedNodeTypesFromAsync) => {
141
+ const withIntlayerSync = (nextConfig = {}, configOptions) => {
142
142
  if (typeof nextConfig !== "object") nextConfig = {};
143
143
  const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(configOptions);
144
144
  (0, _intlayer_chokidar_cli.logConfigDetails)(configOptions);
@@ -168,15 +168,20 @@ const withIntlayerSync = (nextConfig = {}, configOptions, unusedNodeTypesFromAsy
168
168
  "@intlayer/chokidar",
169
169
  "@intlayer/webpack"
170
170
  ];
171
- let unusedNodeTypes = unusedNodeTypesFromAsync;
172
- if (isBuildCommand && !unusedNodeTypes) unusedNodeTypes = (0, _intlayer_config_utils.getUnusedNodeTypes)((0, _intlayer_dictionaries_entry.getDictionaries)(intlayerConfig));
173
- if (unusedNodeTypes && unusedNodeTypes.length > 0) appLogger(["Filtering out plugins:", unusedNodeTypes.map((key) => (0, _intlayer_config_logger.colorize)(key, _intlayer_config_colors.BLUE)).join(", ")], { isVerbose: true });
174
- const nodeTypeEnvVars = unusedNodeTypes ? (0, _intlayer_config_envVars.formatNodeTypeToEnvVar)(unusedNodeTypes, false) : {};
175
- const getNewConfig = () => {
176
- let config = { env: {
177
- ...nodeTypeEnvVars,
171
+ let env = {};
172
+ if (isBuildCommand) {
173
+ const dictionaries = (0, _intlayer_dictionaries_entry.getDictionaries)(intlayerConfig);
174
+ if (Object.keys(dictionaries).length === 0) appLogger("No dictionaries found. Please check your configuration.", { isVerbose: true });
175
+ const unusedNodeTypes = (0, _intlayer_config_utils.getUnusedNodeTypes)(dictionaries);
176
+ if (unusedNodeTypes && unusedNodeTypes.length > 0) appLogger(["Filtering out plugins:", unusedNodeTypes.map((key) => (0, _intlayer_config_logger.colorize)(key, _intlayer_config_colors.BLUE)).join(", ")], { isVerbose: true });
177
+ env = {
178
+ ...env,
179
+ ...(0, _intlayer_config_envVars.formatNodeTypeToEnvVar)(unusedNodeTypes),
178
180
  ...(0, _intlayer_config_envVars.getConfigEnvVars)(intlayerConfig)
179
- } };
181
+ };
182
+ }
183
+ const getNewConfig = () => {
184
+ let config = { env };
180
185
  if (isGteNext15) config = {
181
186
  ...config,
182
187
  serverExternalPackages
@@ -263,10 +268,7 @@ const withIntlayer = async (nextConfig = {}, configOptions) => {
263
268
  cacheTimeoutMs: isBuildCommand ? 1e3 * 30 : 1e3 * 60 * 60,
264
269
  env: isBuildCommand ? "prod" : "dev"
265
270
  });
266
- const nextConfigResolved = await nextConfig;
267
- let unusedNodeTypes;
268
- if (isBuildCommand) unusedNodeTypes = await (0, _intlayer_config_utils.getUnusedNodeTypesAsync)((0, _intlayer_dictionaries_entry.getDictionaries)(intlayerConfig));
269
- return withIntlayerSync(nextConfigResolved, configOptions, unusedNodeTypes);
271
+ return withIntlayerSync(await nextConfig, configOptions);
270
272
  };
271
273
 
272
274
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n getUnusedNodeTypes,\n getUnusedNodeTypesAsync,\n normalizePath,\n type PluginNodeType,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n 'Build optimization enabled',\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions,\n unusedNodeTypesFromAsync?: PluginNodeType[]\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n let unusedNodeTypes = unusedNodeTypesFromAsync;\n\n if (isBuildCommand && !unusedNodeTypes) {\n const dictionaries = getDictionaries(intlayerConfig) as Record<\n string,\n Dictionary\n >;\n unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n }\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out plugins:',\n unusedNodeTypes.map((key) => colorize(key, ANSIColors.BLUE)).join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n const nodeTypeEnvVars = unusedNodeTypes\n ? formatNodeTypeToEnvVar(unusedNodeTypes, false)\n : {};\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env: {\n ...nodeTypeEnvVars,\n ...getConfigEnvVars(intlayerConfig),\n },\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env['INTLAYER_IS_DEV_COMMAND'] = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n let unusedNodeTypes: PluginNodeType[] | undefined;\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n }\n\n return withIntlayerSync(nextConfigResolved, configOptions, unusedNodeTypes);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAAu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AAsB,OACtB,cACA,YACD;AAUD,sCAPE,cAAc,EACd,YACD,EAGuC,WAAW;;;;;;;;;;;;;;;;;AAoBrD,MAAa,eAAe,OAC1B,aAA6B,EAAE,EAC/B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,kBAAkB;AAE3E,SAAQ,IAAI,6BAA6B,eAAe,SAAS;CAEjE,MAAM,6DAAkC,cAAc;CAEtD,MAAM,EAAE,SAAS,eAAe;AAKhC,KAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,QAEjE,qDAAsB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;EAChC,CAAC;CAGJ,MAAM,qBAAqB,MAAM;CAEjC,IAAI;AAEJ,KAAI,eAEF,mBAAkB,4GADmB,eAAe,CACS;AAG/D,QAAO,iBAAiB,oBAAoB,eAAe,gBAAgB"}
1
+ {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n getUnusedNodeTypes,\n getUnusedNodeTypesAsync,\n normalizePath,\n type PluginNodeType,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n 'Build optimization enabled',\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out plugins:',\n unusedNodeTypes\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env['INTLAYER_IS_DEV_COMMAND'] = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;AAElC,KAAI;AAIF,iBAFE,eAAe,OAAO,0DAA8B,EAC1B,oBAAoB,CAC9B;SACZ;AAIR,QAAO;EACL,yDAA6B,aAAa,KAAK,SAAS;EACxD,yDAA6B,aAAa,KAAK,SAAS;EACxD,yDAA6B,aAAa,KAAK,SAAS;EACxD,+DAAmC,aAAa,KAAK,SAAS;EAC/D;;AAIH,MAAM,2BAA2B,mBAAmC;AAClE,KAAI;AAGF,GADE,eAAe,OAAO,0DAA8B,EACtC,QAAQ,gBAAgB;AACxC,SAAO;UACA,IAAI;AACX,SAAO;;;AAKX,MAAM,oCAAoC,mBAAmC;AAC3E,KAAI;AAGF,GADE,eAAe,OAAO,0DAA8B,EACtC,QAAQ,kBAAkB;AAC1C,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,KAAK;EAChB,KAAK,iBAAiB,SAAS;EAChC,CAAC;AAKJ,QAAO,iBAFoB,MAAM,YAEW,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"useLocale.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport { usePathname, useRouter } from 'next/navigation.js';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\n\ntype UseLocaleProps = {\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: DeclaredLocales; path: string }) => void);\n};\n\nconst usePathWithoutLocale = () => {\n const pathname = usePathname(); // updates on client navigations\n const [fullPath, setFullPath] = useState(pathname);\n\n useEffect(() => {\n // Runs only on client; avoids suspense.\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setFullPath(search ? `${pathname}${search}` : pathname);\n }, [pathname]);\n\n // Your own helper\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\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 = ({ onChange = 'replace' }: UseLocaleProps = {}) => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathWithoutLocale();\n\n const redirectionFunction = useCallback(\n (locale: DeclaredLocales) => {\n if (!onChange) return;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n },\n [replace, push, pathWithoutLocale, onChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n };\n};\n"],"mappings":";;;;;;;;AAmBA,MAAM,6BAA6B;CACjC,MAAM,WAAW,aAAa;CAC9B,MAAM,CAAC,UAAU,eAAe,SAAS,SAAS;AAElD,iBAAgB;EAEd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,cAAY,SAAS,GAAG,WAAW,WAAW,SAAS;IACtD,CAAC,SAAS,CAAC;AAGd,QAAO,cAAc,qBAAqB,SAAS,EAAE,CAAC,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BlE,MAAa,aAAa,EAAE,WAAW,cAA8B,EAAE,KAAK;CAC1E,MAAM,EAAE,SAAS,SAAS,WAAW;CACrC,MAAM,oBAAoB,sBAAsB;AA2BhD,QAAO;EACL,GALsBA,YAAe,EACrC,gBAtB0B,aACzB,WAA4B;AAC3B,OAAI,CAAC,SAAU;GAEf,MAAM,iBAAiB,gBAAgB,mBAAmB,OAAO;AAEjE,OAAI,OAAO,aAAa,YAAY;AAClC,aAAS;KAAE;KAAQ,MAAM;KAAgB,CAAC;AAC1C;;AAGF,OAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,OAAI,aAAa,OACf,MAAK,eAAe;KAGxB;GAAC;GAAS;GAAM;GAAmB;GAAS,CAC7C,EAIA,CAAC;EAIA;EACD"}
1
+ {"version":3,"file":"useLocale.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { usePathname, useRouter } from 'next/navigation.js';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\n\ntype UseLocaleProps = {\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nconst usePathWithoutLocale = () => {\n const pathname = usePathname(); // updates on client navigations\n const [fullPath, setFullPath] = useState(pathname);\n\n useEffect(() => {\n // Runs only on client; avoids suspense.\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setFullPath(search ? `${pathname}${search}` : pathname);\n }, [pathname]);\n\n // Your own helper\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\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 = ({ onChange = 'replace' }: UseLocaleProps = {}) => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathWithoutLocale();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n },\n [replace, push, pathWithoutLocale, onChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n };\n};\n"],"mappings":";;;;;;;;AAmBA,MAAM,6BAA6B;CACjC,MAAM,WAAW,aAAa;CAC9B,MAAM,CAAC,UAAU,eAAe,SAAS,SAAS;AAElD,iBAAgB;EAEd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,cAAY,SAAS,GAAG,WAAW,WAAW,SAAS;IACtD,CAAC,SAAS,CAAC;AAGd,QAAO,cAAc,qBAAqB,SAAS,EAAE,CAAC,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BlE,MAAa,aAAa,EAAE,WAAW,cAA8B,EAAE,KAAK;CAC1E,MAAM,EAAE,SAAS,SAAS,WAAW;CACrC,MAAM,oBAAoB,sBAAsB;AA2BhD,QAAO;EACL,GALsBA,YAAe,EACrC,gBAtB0B,aACzB,WAA0B;AACzB,OAAI,CAAC,SAAU;GAEf,MAAM,iBAAiB,gBAAgB,mBAAmB,OAAO;AAEjE,OAAI,OAAO,aAAa,YAAY;AAClC,aAAS;KAAE;KAAQ,MAAM;KAAgB,CAAC;AAC1C;;AAGF,OAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,OAAI,aAAa,OACf,MAAK,eAAe;KAGxB;GAAC;GAAS;GAAM;GAAmB;GAAS,CAC7C,EAIA,CAAC;EAIA;EACD"}
@@ -1,7 +1,7 @@
1
- import configuration from "@intlayer/config/built";
1
+ import { internationalization } from "@intlayer/config/built";
2
2
 
3
3
  //#region src/generateStaticParams.ts
4
- const { locales } = configuration.internationalization;
4
+ const { locales } = internationalization;
5
5
  /**
6
6
  * Generates static parameters for Next.js's dynamic routes based on the configured locales.
7
7
  *
@@ -1 +1 @@
1
- {"version":3,"file":"generateStaticParams.mjs","names":[],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\n\nconst { locales } = configuration.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,YAAY,cAAc;;;;;;;;;;;;;;;;;;;AAoBlC,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,QAAQ,EAAE"}
1
+ {"version":3,"file":"generateStaticParams.mjs","names":[],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n\nconst { locales } = internationalization;\n\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":";;;AAGA,MAAM,EAAE,YAAY;;;;;;;;;;;;;;;;;;;AAqBpB,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,QAAQ,EAAE"}
@@ -1,6 +1,6 @@
1
1
  import { localeDetector as localeDetector$1 } from "./localeDetector.mjs";
2
2
  import { getCanonicalPath, getLocalizedPath, getRewriteRules } from "@intlayer/core/localization";
3
- import configuration from "@intlayer/config/built";
3
+ import { internationalization, routing } from "@intlayer/config/built";
4
4
  import { ROUTING_MODE } from "@intlayer/config/defaultValues";
5
5
  import { getLocaleFromStorageServer, setLocaleInStorageServer } from "@intlayer/core/utils";
6
6
  import { NextResponse } from "next/server";
@@ -25,7 +25,6 @@ const TREE_SHAKE_PREFIX_MODES = process.env["INTLAYER_ROUTING_MODE"] && process.
25
25
  * (INTLAYER_ROUTING_REWRITE_RULES === 'false').
26
26
  */
27
27
  const TREE_SHAKE_REWRITE = process.env["INTLAYER_ROUTING_REWRITE_RULES"] === "false";
28
- const { internationalization, routing } = configuration ?? {};
29
28
  const { locales, defaultLocale } = internationalization ?? {};
30
29
  const { basePath, mode, rewrite } = routing ?? {};
31
30
  const effectiveMode = mode ?? ROUTING_MODE;
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration 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\n/**\n * True when the build-time routing mode is known and is NOT 'no-prefix'.\n * Use to guard no-prefix-specific code paths so bundlers can eliminate them.\n */\nconst TREE_SHAKE_NO_PREFIX =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\n/**\n * True when rewrite rules are explicitly disabled at build time\n * (INTLAYER_ROUTING_REWRITE_RULES === 'false').\n */\nconst TREE_SHAKE_REWRITE =\n process.env['INTLAYER_ROUTING_REWRITE_RULES'] === 'false';\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 { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params');\nconst prefixDefault =\n !TREE_SHAKE_PREFIX_MODES && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = !TREE_SHAKE_REWRITE\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 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 (TREE_SHAKE_SEARCH_PARAMS || effectiveMode !== 'search-params')\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 */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n 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 (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params')\n ) {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n 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 return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,uBACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;AAK3C,MAAM,2BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAAM,0BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBACzC,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAA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AS,SAAS,IAAI,GACE,KAAK,MAAM,uBAGvC,QAAQ,QAAQ,IAAI;;;;;;;AAUhD,MAAM,cACJ,SACA,SACA,WACiB;CACjB,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,iBACJ,UAAU,CAAC,QAAQ,SAAS,IAAI,GAAG,GAAG,UAAU,WAAW;CAE7D,MAAM,iBAAiB,IAAI,QAAQ,QAAQ,QAAQ;AACnD,0BAAyB,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/B,aAAa,KAAK,EAChB,SAAS,EACP,SAAS,gBACV,EACF,CAAC,GACF,aAAa,QAAQ,WAAW,EAC9B,SAAS,EACP,SAAS,gBACV,EACF,CAAC;AAER,0BAAyB,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;AAE7D,QAAO,aAAa,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI,CAAC"}
1
+ {"version":3,"file":"intlayerProxy.mjs","names":["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\n/**\n * True when the build-time routing mode is known and is NOT 'no-prefix'.\n * Use to guard no-prefix-specific code paths so bundlers can eliminate them.\n */\nconst TREE_SHAKE_NO_PREFIX =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\n/**\n * True when rewrite rules are explicitly disabled at build time\n * (INTLAYER_ROUTING_REWRITE_RULES === 'false').\n */\nconst TREE_SHAKE_REWRITE =\n process.env['INTLAYER_ROUTING_REWRITE_RULES'] === 'false';\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 } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params');\nconst prefixDefault =\n !TREE_SHAKE_PREFIX_MODES && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = !TREE_SHAKE_REWRITE\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 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 (TREE_SHAKE_SEARCH_PARAMS || effectiveMode !== 'search-params')\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 */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n 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 (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!TREE_SHAKE_NO_PREFIX && effectiveMode === 'no-prefix') ||\n (!TREE_SHAKE_SEARCH_PARAMS && effectiveMode === 'search-params')\n ) {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n 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 return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,uBACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;AAK3C,MAAM,2BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAAM,0BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBACzC,QAAQ,IAAI,6BAA6B;;;;;AAM3C,MAAM,qBACJ,QAAQ,IAAI,sCAAsC;AAkDpD,MAAM,EAAE,SAAS,kBAAkB,wBAAwB,EAAE;AAC7D,MAAM,EAAE,UAAU,MAAM,YAAY,WAAW,EAAE;AAKjD,MAAM,gBAAgB,QAAQ;AAC9B,MAAM,WACH,CAAC,wBAAwB,kBAAkB,eAC3C,CAAC,4BAA4B,kBAAkB;AAClD,MAAM,gBACJ,CAAC,2BAA2B,kBAAkB;AAEhD,MAAM,iBAAiB,CAAC;AAExB,MAAM,eAAe,CAAC,qBAClB,gBAAgB,SAAS,MAAM,GAC/B;;;;;;;;;;;;;;;AAgBJ,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,gBAAgB;AAExD,QACE,YAAY,cACZ,uBAAu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;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;AAE7D,QAAO,aAAa,SAAS,IAAI,IAAI,gBAAgB,QAAQ,IAAI,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { localeDetector } from "@intlayer/core/localization";
2
- import configuration from "@intlayer/config/built";
2
+ import { internationalization } from "@intlayer/config/built";
3
3
  import { DEFAULT_LOCALE } from "@intlayer/config/defaultValues";
4
4
  import { getLocaleFromStorageServer } from "@intlayer/core/utils";
5
5
  import { cookies, headers } from "next/headers.js";
@@ -24,7 +24,7 @@ import { cookies, headers } from "next/headers.js";
24
24
  * ```
25
25
  */
26
26
  const getLocale = async () => {
27
- const defaultLocale = configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;
27
+ const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;
28
28
  const headersList = await headers();
29
29
  const cookiesList = await cookies();
30
30
  const storedLocale = getLocaleFromStorageServer({
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.mjs","names":[],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBACJ,eAAe,sBAAsB,iBAAiB;CAGxD,MAAM,cAAc,MAAM,SAAS;CACnC,MAAM,cAAc,MAAM,SAAS;CAEnC,MAAM,eAAe,2BAA2B;EAC9C,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qBAAqB,eAAe,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}
1
+ {"version":3,"file":"getLocale.mjs","names":[],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBAAgB,sBAAsB,iBAAiB;CAG7D,MAAM,cAAc,MAAM,SAAS;CACnC,MAAM,cAAc,MAAM,SAAS;CAEnC,MAAM,eAAe,2BAA2B;EAC9C,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qBAAqB,eAAe,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}
@@ -7,7 +7,7 @@ import * as ANSIColors from "@intlayer/config/colors";
7
7
  import { formatNodeTypeToEnvVar, getConfigEnvVars } from "@intlayer/config/envVars";
8
8
  import { colorize, getAppLogger } from "@intlayer/config/logger";
9
9
  import { getConfiguration } from "@intlayer/config/node";
10
- import { compareVersions, getAlias, getProjectRequire, getUnusedNodeTypes, getUnusedNodeTypesAsync, normalizePath } from "@intlayer/config/utils";
10
+ import { compareVersions, getAlias, getProjectRequire, getUnusedNodeTypes, normalizePath } from "@intlayer/config/utils";
11
11
  import { getDictionaries } from "@intlayer/dictionaries-entry";
12
12
  import { IntlayerPlugin } from "@intlayer/webpack";
13
13
  import { defu } from "defu";
@@ -134,7 +134,7 @@ const getCommandsEvent = () => {
134
134
  * export default withIntlayerSync(nextConfig)
135
135
  * ```
136
136
  */
137
- const withIntlayerSync = (nextConfig = {}, configOptions, unusedNodeTypesFromAsync) => {
137
+ const withIntlayerSync = (nextConfig = {}, configOptions) => {
138
138
  if (typeof nextConfig !== "object") nextConfig = {};
139
139
  const intlayerConfig = getConfiguration(configOptions);
140
140
  logConfigDetails(configOptions);
@@ -164,15 +164,20 @@ const withIntlayerSync = (nextConfig = {}, configOptions, unusedNodeTypesFromAsy
164
164
  "@intlayer/chokidar",
165
165
  "@intlayer/webpack"
166
166
  ];
167
- let unusedNodeTypes = unusedNodeTypesFromAsync;
168
- if (isBuildCommand && !unusedNodeTypes) unusedNodeTypes = getUnusedNodeTypes(getDictionaries(intlayerConfig));
169
- if (unusedNodeTypes && unusedNodeTypes.length > 0) appLogger(["Filtering out plugins:", unusedNodeTypes.map((key) => colorize(key, ANSIColors.BLUE)).join(", ")], { isVerbose: true });
170
- const nodeTypeEnvVars = unusedNodeTypes ? formatNodeTypeToEnvVar(unusedNodeTypes, false) : {};
171
- const getNewConfig = () => {
172
- let config = { env: {
173
- ...nodeTypeEnvVars,
167
+ let env = {};
168
+ if (isBuildCommand) {
169
+ const dictionaries = getDictionaries(intlayerConfig);
170
+ if (Object.keys(dictionaries).length === 0) appLogger("No dictionaries found. Please check your configuration.", { isVerbose: true });
171
+ const unusedNodeTypes = getUnusedNodeTypes(dictionaries);
172
+ if (unusedNodeTypes && unusedNodeTypes.length > 0) appLogger(["Filtering out plugins:", unusedNodeTypes.map((key) => colorize(key, ANSIColors.BLUE)).join(", ")], { isVerbose: true });
173
+ env = {
174
+ ...env,
175
+ ...formatNodeTypeToEnvVar(unusedNodeTypes),
174
176
  ...getConfigEnvVars(intlayerConfig)
175
- } };
177
+ };
178
+ }
179
+ const getNewConfig = () => {
180
+ let config = { env };
176
181
  if (isGteNext15) config = {
177
182
  ...config,
178
183
  serverExternalPackages
@@ -259,10 +264,7 @@ const withIntlayer = async (nextConfig = {}, configOptions) => {
259
264
  cacheTimeoutMs: isBuildCommand ? 1e3 * 30 : 1e3 * 60 * 60,
260
265
  env: isBuildCommand ? "prod" : "dev"
261
266
  });
262
- const nextConfigResolved = await nextConfig;
263
- let unusedNodeTypes;
264
- if (isBuildCommand) unusedNodeTypes = await getUnusedNodeTypesAsync(getDictionaries(intlayerConfig));
265
- return withIntlayerSync(nextConfigResolved, configOptions, unusedNodeTypes);
267
+ return withIntlayerSync(await nextConfig, configOptions);
266
268
  };
267
269
 
268
270
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.mjs","names":[],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n getUnusedNodeTypes,\n getUnusedNodeTypesAsync,\n normalizePath,\n type PluginNodeType,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n 'Build optimization enabled',\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions,\n unusedNodeTypesFromAsync?: PluginNodeType[]\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n let unusedNodeTypes = unusedNodeTypesFromAsync;\n\n if (isBuildCommand && !unusedNodeTypes) {\n const dictionaries = getDictionaries(intlayerConfig) as Record<\n string,\n Dictionary\n >;\n unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n }\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out plugins:',\n unusedNodeTypes.map((key) => colorize(key, ANSIColors.BLUE)).join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n const nodeTypeEnvVars = unusedNodeTypes\n ? formatNodeTypeToEnvVar(unusedNodeTypes, false)\n : {};\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env: {\n ...nodeTypeEnvVars,\n ...getConfigEnvVars(intlayerConfig),\n },\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env['INTLAYER_IS_DEV_COMMAND'] = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n let unusedNodeTypes: PluginNodeType[] | undefined;\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n }\n\n return withIntlayerSync(nextConfigResolved, configOptions, unusedNodeTypes);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAc,gBAAgB;AAElC,KAAI;AAIF,iBAFE,eAAe,OAAO,WAAW,mBAAmB,EAC1B,oBAAoB,CAC9B;SACZ;AAIR,QAAO;EACL,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,mBAAmB,gBAAgB,aAAa,KAA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MAAa,eAAe,OAC1B,aAA6B,EAAE,EAC/B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,kBAAkB;AAE3E,SAAQ,IAAI,6BAA6B,eAAe,SAAS;CAEjE,MAAM,iBAAiB,iBAAiB,cAAc;CAEtD,MAAM,EAAE,SAAS,eAAe;AAKhC,KAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,QAEjE,OAAM,gBAAgB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;EAChC,CAAC;CAGJ,MAAM,qBAAqB,MAAM;CAEjC,IAAI;AAEJ,KAAI,eAEF,mBAAkB,MAAM,wBADH,gBAAgB,eAAe,CACS;AAG/D,QAAO,iBAAiB,oBAAoB,eAAe,gBAAgB"}
1
+ {"version":3,"file":"withIntlayer.mjs","names":[],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n getUnusedNodeTypes,\n getUnusedNodeTypesAsync,\n normalizePath,\n type PluginNodeType,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n 'Build optimization enabled',\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out plugins:',\n unusedNodeTypes\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env['INTLAYER_IS_DEV_COMMAND'] = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAc,gBAAgB;AAElC,KAAI;AAIF,iBAFE,eAAe,OAAO,WAAW,mBAAmB,EAC1B,oBAAoB,CAC9B;SACZ;AAIR,QAAO;EACL,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,aAAa,gBAAgB,aAAa,KAAK,SAAS;EACxD,mBAAmB,gBAAgB,aAAa,KAAK,SAAS;EAC/D;;AAIH,MAAM,2BAA2B,mBAAmC;AAClE,KAAI;AAGF,GADE,eAAe,OAAO,WAAW,mBAAmB,EACtC,QAAQ,gBAAgB;AACxC,SAAO;UACA,IAAI;AACX,SAAO;;;AAKX,MAAM,oCAAoC,mBAAmC;AAC3E,KAAI;AAGF,GADE,eAAe,OAAO,WAAW,mBAAmB,EACtC,QAAQ,kBAAkB;AAC1C,SAAO;UACA,IAAI;AACX,SAAO;;;AAIX,MAAM,qBACJ,YACA,gBACA,uBACW;CA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SAAS,QAEjE,OAAM,gBAAgB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;EAChC,CAAC;AAKJ,QAAO,iBAFoB,MAAM,YAEW,cAAc"}
@@ -1,10 +1,9 @@
1
- import { LocalesValues as LocalesValues$1 } from "../intlayer/dist/types/index.js";
2
- import { DeclaredLocales } from "@intlayer/types/module_augmentation";
1
+ import { LocalesValues } from "@intlayer/types/module_augmentation";
3
2
 
4
3
  //#region src/client/useLocale.d.ts
5
4
  type UseLocaleProps = {
6
5
  onChange?: 'replace' | 'push' | 'none' | ((params: {
7
- locale: DeclaredLocales;
6
+ locale: LocalesValues;
8
7
  path: string;
9
8
  }) => void);
10
9
  };
@@ -36,10 +35,10 @@ declare const useLocale: ({
36
35
  onChange
37
36
  }?: UseLocaleProps) => {
38
37
  pathWithoutLocale: string;
39
- locale: LocalesValues$1;
40
- defaultLocale: LocalesValues$1;
41
- availableLocales: LocalesValues$1[];
42
- setLocale: (locale: LocalesValues$1) => void;
38
+ locale: LocalesValues;
39
+ defaultLocale: LocalesValues;
40
+ availableLocales: LocalesValues[];
41
+ setLocale: (locale: LocalesValues) => void;
43
42
  };
44
43
  //#endregion
45
44
  export { useLocale };
@@ -1 +1 @@
1
- {"version":3,"file":"useLocale.d.ts","names":[],"sources":["../../../src/client/useLocale.ts"],"mappings":";;;;KAWK,cAAA;EACH,QAAA,mCAIM,MAAA;IAAU,MAAA,EAAQ,eAAA;IAAiB,IAAA;EAAA;AAAA;;;;;;;;;AAyC3C;;;;;;;;;;;;;;;;cAAa,SAAA;EAAa;AAAA,IAA0B,cAAA;;UAAmB,eAAA"}
1
+ {"version":3,"file":"useLocale.d.ts","names":[],"sources":["../../../src/client/useLocale.ts"],"mappings":";;;KAWK,cAAA;EACH,QAAA,mCAIM,MAAA;IAAU,MAAA,EAAQ,aAAA;IAAe,IAAA;EAAA;AAAA;;;;;;;;AAyCzC;;;;;;;;;;;;;;;;;cAAa,SAAA;EAAa;AAAA,IAA0B,cAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateStaticParams.d.ts","names":[],"sources":["../../src/generateStaticParams.ts"],"mappings":";;;;;;AAsBA;;;;;;;;;;;;;;;cAAa,oBAAA;UAAkE,MAAA;AAAA"}
1
+ {"version":3,"file":"generateStaticParams.d.ts","names":[],"sources":["../../src/generateStaticParams.ts"],"mappings":";;;;;;AAwBA;;;;;;;;;;;;;;;cAAa,oBAAA;UAAkE,MAAA;AAAA"}
@@ -463,7 +463,7 @@ declare const useMarkdownRenderer: ({
463
463
  forceInline,
464
464
  preserveFrontmatter,
465
465
  tagfilter
466
- }?: index_d_exports.RenderMarkdownProps) => (content: string) => string | number | bigint | boolean | Iterable<_$react.ReactNode> | _$react.JSX.Element | Promise<_$react.ReactNode>;
466
+ }?: index_d_exports.RenderMarkdownProps) => (content: string) => string | number | bigint | boolean | Iterable<_$react.ReactNode> | Promise<_$react.ReactNode> | _$react.JSX.Element;
467
467
  /**
468
468
  * @deprecated import from next-intlayer/markdown instead
469
469
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;;;;;;;cAiDa,gBAAA,UAAgB,EAAA,CAAA,eAAA,CAAA,uBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gDAFtB,eAAA,CAAA,uBAAA,EAAA,UAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAEoB,OAAA,CAAA,EAAA,CAAA,OAAA,CAAA,cAAA,CAAA,WAAA,OAAA,OAAA,CAAA,SAAA,GAAA,OAAA,CAAA,OAAA,CAAA,SAAA;AAAA;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CAAA,SAAA,IAAA,OAAA,CAAA,GAAA,CAAA,OAAA;;;;cAInB,gBAAA,EAAgB,OAAA,CAAA,EAAA,CAAA,eAAA,CAAA,qBAAA;;;;KAIjB,mBAAA,GAAsB,eAAA,CAAA,mBAAA;;;;KAItB,qBAAA,GAAwB,eAAA,CAAA,qBAAA"}
@@ -1,4 +1,3 @@
1
1
  import { Locale as Locale$1 } from "@intlayer/types/allLocales";
2
2
  import { Dictionary } from "@intlayer/types/dictionary";
3
- import { LocalesValues as LocalesValues$1 } from "@intlayer/types/module_augmentation";
4
- export { type Locale$1 as Locale, type LocalesValues$1 as LocalesValues };
3
+ export { type Locale$1 as Locale };
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.d.ts","names":[],"sources":["../../../src/proxy/intlayerProxy.ts"],"mappings":";;;;;AAyKA;;;;;;;;;;;;;;;;;;;;;cAAa,aAAA,GACX,OAAA,EAAS,WAAA,EACT,MAAA,GAAS,cAAA,EACT,SAAA,GAAY,YAAA,KACX,YAAA"}
1
+ {"version":3,"file":"intlayerProxy.d.ts","names":[],"sources":["../../../src/proxy/intlayerProxy.ts"],"mappings":";;;;;AAwKA;;;;;;;;;;;;;;;;;;;;;cAAa,aAAA,GACX,OAAA,EAAS,WAAA,EACT,MAAA,GAAS,cAAA,EACT,SAAA,GAAY,YAAA,KACX,YAAA"}
@@ -1,5 +1,5 @@
1
- import { Dictionary } from "@intlayer/types/dictionary";
2
1
  import { DeclaredLocales } from "@intlayer/types/module_augmentation";
2
+ import { Dictionary } from "@intlayer/types/dictionary";
3
3
  import { useDictionary as useDictionary$1 } from "react-intlayer/server";
4
4
 
5
5
  //#region src/server/useDictionary.d.ts
@@ -1,5 +1,5 @@
1
- import { Dictionary } from "@intlayer/types/dictionary";
2
1
  import { DeclaredLocales, StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
2
+ import { Dictionary } from "@intlayer/types/dictionary";
3
3
  import { useDictionaryAsync as useDictionaryAsync$1 } from "react-intlayer/server";
4
4
 
5
5
  //#region src/server/useDictionaryAsync.d.ts
@@ -1,5 +1,5 @@
1
- import { Dictionary } from "@intlayer/types/dictionary";
2
1
  import { DeclaredLocales, StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
2
+ import { Dictionary } from "@intlayer/types/dictionary";
3
3
  import { useDictionaryDynamic as useDictionaryDynamic$1 } from "react-intlayer/server";
4
4
 
5
5
  //#region src/server/useDictionaryDynamic.d.ts
@@ -1,5 +1,5 @@
1
- import { Locale } from "@intlayer/types/allLocales";
2
1
  import { DeclaredLocales, DictionaryKeys } from "@intlayer/types/module_augmentation";
2
+ import { Locale } from "@intlayer/types/allLocales";
3
3
  import { useIntlayer as useIntlayer$1 } from "react-intlayer/server";
4
4
 
5
5
  //#region src/server/useIntlayer.d.ts
@@ -1,6 +1,5 @@
1
1
  import { NextConfig } from "next";
2
2
  import { GetConfigurationOptions } from "@intlayer/config/node";
3
- import { PluginNodeType } from "@intlayer/config/utils";
4
3
 
5
4
  //#region src/server/withIntlayer.d.ts
6
5
  type WithIntlayerOptions = GetConfigurationOptions & {
@@ -17,7 +16,7 @@ type WithIntlayerOptions = GetConfigurationOptions & {
17
16
  * export default withIntlayerSync(nextConfig)
18
17
  * ```
19
18
  */
20
- declare const withIntlayerSync: <T extends Partial<NextConfig>>(nextConfig?: T, configOptions?: WithIntlayerOptions, unusedNodeTypesFromAsync?: PluginNodeType[]) => NextConfig & T;
19
+ declare const withIntlayerSync: <T extends Partial<NextConfig>>(nextConfig?: T, configOptions?: WithIntlayerOptions) => NextConfig & T;
21
20
  /**
22
21
  * A Next.js plugin that adds the intlayer configuration to the webpack configuration
23
22
  * and sets the environment variables
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.d.ts","names":[],"sources":["../../../src/server/withIntlayer.ts"],"mappings":";;;;;KAyRK,mBAAA,GAAsB,uBAAA;EACzB,eAAA;AAAA;;;;;AAcF;;;;;;;cAAa,gBAAA,aAA8B,OAAA,CAAQ,UAAA,GACjD,UAAA,GAAY,CAAA,EACZ,aAAA,GAAgB,mBAAA,EAChB,wBAAA,GAA2B,cAAA,OAC1B,UAAA,GAAa,CAAA;;;;;;;;;;;;;;;;cA2OH,YAAA,aAAgC,OAAA,CAAQ,UAAA,GACnD,UAAA,GAAY,CAAA,GAAI,OAAA,CAAQ,CAAA,GACxB,aAAA,GAAgB,mBAAA,KACf,OAAA,CAAQ,UAAA,GAAa,CAAA"}
1
+ {"version":3,"file":"withIntlayer.d.ts","names":[],"sources":["../../../src/server/withIntlayer.ts"],"mappings":";;;;KAyRK,mBAAA,GAAsB,uBAAA;EACzB,eAAA;AAAA;;;;;AAcF;;;;;;;cAAa,gBAAA,aAA8B,OAAA,CAAQ,UAAA,GACjD,UAAA,GAAY,CAAA,EACZ,aAAA,GAAgB,mBAAA,KACf,UAAA,GAAa,CAAA;;;;;;;;;;;;;;;AAoPhB;cAAa,YAAA,aAAgC,OAAA,CAAQ,UAAA,GACnD,UAAA,GAAY,CAAA,GAAI,OAAA,CAAQ,CAAA,GACxB,aAAA,GAAgB,mBAAA,KACf,OAAA,CAAQ,UAAA,GAAa,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-intlayer",
3
- "version": "8.6.3",
3
+ "version": "8.6.5",
4
4
  "private": false,
5
5
  "description": "Simplify internationalization i18n in Next.js with context providers, hooks, locale detection, and multilingual content integration.",
6
6
  "keywords": [
@@ -129,15 +129,15 @@
129
129
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
130
130
  },
131
131
  "dependencies": {
132
- "@intlayer/chokidar": "8.6.3",
133
- "@intlayer/config": "8.6.3",
134
- "@intlayer/core": "8.6.3",
135
- "@intlayer/dictionaries-entry": "8.6.3",
136
- "@intlayer/types": "8.6.3",
137
- "@intlayer/webpack": "8.6.3",
132
+ "@intlayer/chokidar": "8.6.5",
133
+ "@intlayer/config": "8.6.5",
134
+ "@intlayer/core": "8.6.5",
135
+ "@intlayer/dictionaries-entry": "8.6.5",
136
+ "@intlayer/types": "8.6.5",
137
+ "@intlayer/webpack": "8.6.5",
138
138
  "defu": "6.1.4",
139
139
  "node-loader": "2.1.0",
140
- "react-intlayer": "8.6.3"
140
+ "react-intlayer": "8.6.5"
141
141
  },
142
142
  "devDependencies": {
143
143
  "@types/node": "25.5.0",