{"version":3,"file":"createNextMiddleware.mjs","names":[],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { applyTrailingSlash } from './pathname';\nimport { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport {\n  normalizePathname,\n  getSharedPath,\n  replaceDynamicSegments,\n  getLocalizedPath,\n  getLocaleFromRequest,\n  getResponse,\n  ResponseConfig,\n} from './utils';\nimport { pathnameMatchesRegex } from '../utils/pathRegex';\nimport { createMiddlewareRouting } from './createMiddlewareRouting';\nimport { resolveMiddlewareConfig } from './resolveMiddlewareConfig';\nimport type { MiddlewareConfig } from './types';\nimport { createLinkRoutingConfigMismatchWarning } from '../errors/middleware';\n\nexport type { RouteOverrides, LocaleRoutes } from './types';\n\nconst NEXT_JS_SOURCE_MAP_PATH = '/__nextjs_source-map';\n\n// Options gt-next/link reads from withGTConfig() to avoid redirects.\nconst LINK_ROUTING_OPTIONS = [\n  'prefixDefaultLocale',\n  'enableSmartRouting',\n] as const;\n\n/**\n * Middleware factory to create a Next.js middleware for i18n routing and locale detection.\n *\n * This middleware sets a cookie based on the locale derived from several sources\n * such as the request pathname, referer, or 'Accept-Language' header.\n * If locale routing is enabled, it redirects to the localized pathname and\n * updates the locale cookie.\n *\n * Options omitted here fall back to the same options passed to `withGTConfig()`.\n *\n * @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.\n * @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about\n * @param {boolean} [config.enableSmartRouting=true] - Keep automatic locale negotiation. Disable to treat returning visitors' unprefixed URLs as default-locale routes.\n * @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps\n * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing\n * @param {RouteOverrides} [config.routeOverrides] - Locale-relative paths to rewrite from /{locale}/{path} to /{locale}/{locale}/{path}\n * @param {LocaleRoutes} [config.localeRoutes] - Shared paths available per locale; other paths fall back to the default locale\n * @returns {function} - A middleware function that processes the request and response.\n */\nexport function createNextMiddleware(options: MiddlewareConfig = {}) {\n  const config = resolveMiddlewareConfig(options);\n  if (process.env.NODE_ENV === 'development') {\n    const linkConfig = resolveMiddlewareConfig();\n    const mismatches = LINK_ROUTING_OPTIONS.filter(\n      (option) => config[option] !== linkConfig[option]\n    );\n    if (mismatches.length)\n      console.warn(createLinkRoutingConfigMismatchWarning(mismatches));\n  }\n  const {\n    localeRouting,\n    prefixDefaultLocale,\n    enableSmartRouting,\n    ignoreSourceMaps,\n  } = config;\n  const {\n    pathRegex,\n    gt,\n    defaultLocale,\n    locales,\n    localeRoutingEnabledCookieName,\n    referrerLocaleCookieName,\n    localeCookieName,\n    resetLocaleCookieName,\n    localeHeaderName,\n    pathConfig,\n    pathToSharedPath,\n    defaultLocalePaths,\n    routeOverridePathMaps,\n    localeRoutePathMaps,\n  } = createMiddlewareRouting(config);\n\n  /**\n   * Processes the incoming request to determine the user's locale and sets a locale cookie.\n   * Optionally redirects the user based on the locale if locale-based routing is enabled.\n   *\n   * - Checks if the request URL contains a locale.\n   * - Falls back to the referer URL for locale if needed.\n   * - If no locale is found in the URL or referer, it checks the 'Accept-Language' header.\n   * - Sets a cookie with the detected or default locale.\n   * - Redirects to the correct locale route if locale routing is enabled.\n   *\n   * @param {NextRequest} req - The incoming request object, containing URL and headers.\n   * @returns {NextResponse} - The Next.js response, either continuing the request or redirecting to the localized URL.\n   */\n  function middleware(req: NextRequest) {\n    if (!pathnameMatchesRegex(req.nextUrl.pathname, pathRegex)) {\n      return NextResponse.next();\n    }\n\n    // Ignore source maps\n    if (\n      ignoreSourceMaps &&\n      req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)\n    ) {\n      return NextResponse.next();\n    }\n\n    // ---------- LOCALE DETECTION ---------- //\n\n    const {\n      userLocale: requestedLocale,\n      pathnameLocale: pathnameRoutingLocale,\n      unstandardizedPathnameLocale,\n      clearResetCookie,\n    } = getLocaleFromRequest(\n      req,\n      defaultLocale,\n      locales,\n      localeRouting,\n      prefixDefaultLocale,\n      defaultLocalePaths,\n      referrerLocaleCookieName,\n      localeCookieName,\n      resetLocaleCookieName,\n      gt,\n      enableSmartRouting\n    );\n\n    let userLocale = requestedLocale;\n    const pathnameLocale = pathnameRoutingLocale;\n    const headerList = new Headers(req.headers);\n\n    const responseConfig: Omit<ResponseConfig, 'type'> = {\n      originalUrl: req.nextUrl,\n      headerList,\n      userLocale,\n      clearResetCookie,\n      localeRouting,\n      localeRoutingEnabledCookieName,\n      resetLocaleCookieName,\n      localeHeaderName,\n    };\n\n    const getRewriteResponse = (responsePath: string) =>\n      getResponse({ responsePath, type: 'rewrite', ...responseConfig });\n\n    const getRedirectResponse = (responsePath: string) => {\n      const response = getResponse({\n        responsePath,\n        type: 'redirect',\n        ...responseConfig,\n      });\n      if (\n        !enableSmartRouting &&\n        !prefixDefaultLocale &&\n        pathnameLocale === defaultLocale &&\n        userLocale === defaultLocale &&\n        req.headers.get('sec-fetch-dest') === 'document' &&\n        !req.cookies.has(localeCookieName)\n      ) {\n        // Preserve explicit /en intent across a first document redirect.\n        // Background fetches and returning visits must not change the cookie.\n        response.cookies.set(localeCookieName, defaultLocale);\n      }\n      return response;\n    };\n\n    const getNextResponse = () =>\n      getResponse({ type: 'next', ...responseConfig });\n\n    if (localeRouting) {\n      // ---------- GET PATHS ---------- //\n\n      // get pathname\n      const { pathname } = req.nextUrl;\n\n      // standardize pathname (ie, /tg/welcome -> /fil/welcome), (/blog -> /blog)\n      const standardizedPathname =\n        pathnameLocale && pathnameLocale !== unstandardizedPathnameLocale\n          ? pathname.replace(\n              new RegExp(`^/${unstandardizedPathnameLocale}`),\n              `/${pathnameLocale}`\n            )\n          : pathname;\n\n      // Get the shared path for the unprefixed pathname\n      const sharedPathMatch = getSharedPath(\n        standardizedPathname,\n        pathToSharedPath,\n        pathnameLocale\n      );\n      const sharedPath = sharedPathMatch?.sharedPath;\n\n      // Return early for a locale route that does not exist\n      const localeRoutePathMap = localeRoutePathMaps.get(userLocale);\n      if (userLocale !== defaultLocale && localeRoutePathMap) {\n        // Resolve the shared page path without a locale prefix (e.g. /blog/hello).\n        // Strip the URL's locale, which may differ from the newly selected locale.\n        const sharedPagePath = sharedPathMatch\n          ? replaceDynamicSegments(\n              sharedPathMatch.matchedPathname,\n              sharedPath || '/',\n              sharedPathMatch.pathTemplate\n            )\n          : (pathnameLocale\n              ? standardizedPathname.slice(pathnameLocale.length + 1)\n              : standardizedPathname) || '/';\n\n        // If the path does not exist, redirect to the default locale path\n        if (\n          getSharedPath(sharedPagePath, localeRoutePathMap, undefined) ===\n          undefined\n        ) {\n          // Get the path to redirect to\n          const defaultPath =\n            sharedPath !== undefined\n              ? getLocalizedPath(sharedPath, defaultLocale, pathConfig)\n              : undefined;\n          const fallbackPath =\n            defaultPath !== undefined && sharedPathMatch\n              ? replaceDynamicSegments(\n                  sharedPathMatch.matchedPathname,\n                  defaultPath,\n                  sharedPathMatch.pathTemplate\n                )\n              : `/${defaultLocale}${sharedPagePath === '/' ? '' : sharedPagePath}`;\n          const publicFallbackPath = applyTrailingSlash(\n            standardizedPathname,\n            prefixDefaultLocale\n              ? fallbackPath\n              : fallbackPath.slice(defaultLocale.length + 1) || '/'\n          );\n\n          // The default locale is terminal, even if the preference/reset cookie\n          // still requests an unavailable locale on the redirected request.\n          userLocale = defaultLocale;\n          responseConfig.userLocale = defaultLocale;\n          const fallbackUrl = new URL(req.nextUrl);\n          fallbackUrl.pathname = publicFallbackPath;\n          if (fallbackUrl.pathname !== pathname) {\n            return getRedirectResponse(publicFallbackPath);\n          }\n          // Already at the fallback URL: use normal default-locale routing below,\n          // including its alias/override rewrite, instead of redirecting to itself.\n        }\n      }\n\n      // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n      const sharedPathWithParameters =\n        sharedPathMatch !== undefined\n          ? applyTrailingSlash(\n              standardizedPathname,\n              replaceDynamicSegments(\n                sharedPathMatch.matchedPathname,\n                `/${userLocale}${sharedPath}`,\n                sharedPathMatch.pathTemplate\n              )\n            )\n          : undefined;\n\n      // Localized path (/en/blog, /fr/fr-about, /fr/dashboard/[id]/custom)\n      const localizedPath =\n        sharedPath !== undefined\n          ? getLocalizedPath(sharedPath, userLocale, pathConfig)\n          : undefined;\n\n      // Combine localized path with dynamic parameters (/en/blog, /fr/fr-about, /fr/dashboard/1/fr-custom)\n      const localizedPathWithParameters =\n        localizedPath !== undefined && sharedPathMatch !== undefined\n          ? applyTrailingSlash(\n              standardizedPathname,\n              replaceDynamicSegments(\n                sharedPathMatch.matchedPathname,\n                localizedPath,\n                sharedPathMatch.pathTemplate\n              )\n            )\n          : undefined;\n\n      const pagePath =\n        (sharedPathWithParameters?.slice(userLocale.length + 1) ??\n          (pathnameLocale\n            ? standardizedPathname.slice(pathnameLocale.length + 1)\n            : standardizedPathname)) ||\n        '/';\n      const routeOverridePathMap = routeOverridePathMaps[userLocale];\n      const routeOverrideMatch = routeOverridePathMap\n        ? getSharedPath(pagePath, routeOverridePathMap, undefined)\n        : undefined;\n      const routeOverridePath =\n        routeOverrideMatch !== undefined\n          ? applyTrailingSlash(\n              standardizedPathname,\n              `/${userLocale}/${userLocale}${pagePath === '/' ? '' : pagePath}`\n            )\n          : undefined;\n\n      // ---------- ROUTING LOGIC ---------- //\n\n      // ----- CASE: no localized path exists ----- //\n\n      if (localizedPathWithParameters === undefined) {\n        // --- CASE: remove defaultLocale prefix --- //\n\n        if (!prefixDefaultLocale && userLocale === defaultLocale) {\n          if (pathnameLocale) {\n            // REDIRECT CASE: explicit default locale or setLocale (/en/customers -> /customers)\n            if (clearResetCookie || !enableSmartRouting) {\n              return getRedirectResponse(\n                pathname.slice(\n                  (unstandardizedPathnameLocale as string).length + 1\n                ) || '/'\n              );\n            }\n          } else {\n            // REWRITE CASE: no pathnameLocale (/customers -> /en/customers)\n            return getRewriteResponse(\n              routeOverridePath || `/${userLocale}${pathname}`\n            );\n          }\n        }\n\n        // --- CASE: defaultLocale prefix --- //\n        // REDIRECT CASE: no pathnameLocale (ie, /customers -> /fr/customers)\n        else if (!pathnameLocale) {\n          return getRedirectResponse(`/${userLocale}${pathname}`);\n        }\n\n        // REDIRECT CASE: wrong pathnameLocale (ie, /fr/customers -> /en/customers) (this usually happens after a locale switch)\n        if (pathnameLocale && userLocale !== unstandardizedPathnameLocale) {\n          return getRedirectResponse(\n            pathname.replace(\n              new RegExp(`^/${unstandardizedPathnameLocale}`),\n              `/${userLocale}`\n            )\n          );\n        }\n\n        // BASE CASE: has pathnameLocale and it's correct\n        if (routeOverridePath) {\n          return getRewriteResponse(routeOverridePath);\n        }\n        return getNextResponse();\n      }\n\n      // ----- CASE: localized path exists ----- //\n\n      if (!prefixDefaultLocale && userLocale === defaultLocale) {\n        // --- CASE: remove defaultLocale prefix --- //\n\n        if (pathnameLocale) {\n          // REDIRECT CASE: explicit default locale or setLocale (/en/blog -> /blog)\n          if (clearResetCookie || !enableSmartRouting) {\n            return getRedirectResponse(\n              localizedPathWithParameters.slice(userLocale.length + 1) || '/'\n            );\n          }\n        } else {\n          const localizedPublicPath =\n            localizedPathWithParameters.slice(userLocale.length + 1) || '/';\n\n          // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n          if (\n            !pathnameLocale &&\n            normalizePathname(localizedPublicPath) !==\n              normalizePathname(pathname)\n          ) {\n            return getRedirectResponse(localizedPublicPath);\n          }\n\n          // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n          return getRewriteResponse(\n            routeOverridePath || (sharedPathWithParameters as string)\n          );\n        }\n      }\n\n      // --- CASE: add defaultLocale prefix --- //\n\n      // REDIRECT CASE: incorrect pathnameLocale\n      if (\n        normalizePathname(pathname) !==\n        normalizePathname(localizedPathWithParameters)\n      ) {\n        return getRedirectResponse(localizedPathWithParameters);\n      }\n\n      if (routeOverridePath) {\n        return getRewriteResponse(routeOverridePath);\n      }\n\n      // REWRITE CASE: displaying correct localized path, which is the same as the shared path (/fil/blog => /fil/blog) (/fr/fr-dashboard/1/fr-custom => /fr/dashboard/1/custom)\n      // Next.js route identity preserves Unicode spelling, even when lookup\n      // considers the public alias and shared path canonically equivalent.\n      const rewriteUrl = new URL(\n        sharedPathWithParameters as string,\n        req.nextUrl\n      );\n      if (\n        req.nextUrl.pathname !== rewriteUrl.pathname // no rewrite needed if it's already the shared path\n      ) {\n        // convert to shared path with dynamic parameters\n        return getRewriteResponse(sharedPathWithParameters as string);\n      }\n    }\n\n    // BASE CASE\n    return getNextResponse();\n  }\n\n  return middleware;\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,0BAA0B;AAGhC,MAAM,uBAAuB,CAC3B,uBACA,qBACD;;;;;;;;;;;;;;;;;;;;AAqBD,SAAgB,qBAAqB,UAA4B,EAAE,EAAE;CACnE,MAAM,SAAS,wBAAwB,QAAQ;AAC/C,KAAI,QAAQ,IAAI,aAAa,eAAe;EAC1C,MAAM,aAAa,yBAAyB;EAC5C,MAAM,aAAa,qBAAqB,QACrC,WAAW,OAAO,YAAY,WAAW,QAC3C;AACD,MAAI,WAAW,OACb,SAAQ,KAAK,uCAAuC,WAAW,CAAC;;CAEpE,MAAM,EACJ,eACA,qBACA,oBACA,qBACE;CACJ,MAAM,EACJ,WACA,IACA,eACA,SACA,gCACA,0BACA,kBACA,uBACA,kBACA,YACA,kBACA,oBACA,uBACA,wBACE,wBAAwB,OAAO;;;;;;;;;;;;;;CAenC,SAAS,WAAW,KAAkB;AACpC,MAAI,CAAC,qBAAqB,IAAI,QAAQ,UAAU,UAAU,CACxD,QAAO,aAAa,MAAM;AAI5B,MACE,oBACA,IAAI,QAAQ,SAAS,WAAW,wBAAwB,CAExD,QAAO,aAAa,MAAM;EAK5B,MAAM,EACJ,YAAY,iBACZ,gBAAgB,uBAChB,8BACA,qBACE,qBACF,KACA,eACA,SACA,eACA,qBACA,oBACA,0BACA,kBACA,uBACA,IACA,mBACD;EAED,IAAI,aAAa;EACjB,MAAM,iBAAiB;EACvB,MAAM,aAAa,IAAI,QAAQ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