{"version":3,"file":"createMiddlewareRouting.mjs","names":[],"sources":["../../src/middleware-dir/createMiddlewareRouting.ts"],"sourcesContent":["import { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport {\n  defaultLocaleCookieName,\n  defaultResetLocaleCookieName,\n} from '@generaltranslation/react-core/pure';\nimport { createUnsupportedLocalesWarning } from '../errors/middleware';\nimport {\n  defaultLocaleRoutingEnabledCookieName,\n  defaultReferrerLocaleCookieName,\n} from '../utils/cookies';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport { compilePathRegex } from '../utils/pathRegex';\nimport {\n  createPathMatcher,\n  createPathToSharedPathMap,\n  type PathConfig,\n  type PathMatcher,\n} from './createPathMatcher';\nimport { parseEnvConfig } from './resolveMiddlewareConfig';\nimport type {\n  MiddlewareI18nConfig,\n  MiddlewareRouting,\n  ResolvedMiddlewareConfig,\n  RouteOverrides,\n} from './types';\n\n/**\n * Pre-processes the locale, cookie, and path configuration once per\n * middleware instance so requests only do lookups.\n */\nexport function createMiddlewareRouting({\n  pathConfig: inputPathConfig,\n  routeOverrides: inputRouteOverrides,\n  localeRoutes,\n  prefixDefaultLocale,\n}: ResolvedMiddlewareConfig): MiddlewareRouting {\n  const pathRegex = compilePathRegex(\n    process.env._GENERALTRANSLATION_PATH_REGEX\n  );\n\n  // i18n config\n  const i18nConfig = parseEnvConfig<MiddlewareI18nConfig>(\n    '_GENERALTRANSLATION_I18N_CONFIG_PARAMS',\n    process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS\n  );\n\n  // gt instance\n  const gt = new GTRuntime({\n    customMapping: i18nConfig.customMapping,\n  });\n\n  // Configured spellings are the identity used by routes, cookies and caches.\n  const defaultLocale: string =\n    i18nConfig.defaultLocale || libraryDefaultLocale;\n  const locales = Array.from(\n    new Set([defaultLocale, ...(i18nConfig.locales || [])])\n  );\n  // Route entries repeat locale keys. Resolve each key once per factory instead\n  // of rebuilding the full locale-resolution index for every route/locale pair.\n  const resolvedConfigLocales = new Map<string, string>();\n  const determineLocaleWithCache = (locale: string) => {\n    const cached = resolvedConfigLocales.get(locale);\n    if (cached !== undefined) return cached;\n    const resolved = gt.determineLocale(locale, locales) ?? locale;\n    resolvedConfigLocales.set(locale, resolved);\n    return resolved;\n  };\n  const resolvePathConfigLocale =\n    process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === 'true'\n      ? determineLocaleWithCache\n      : (locale: string) => locale;\n\n  // cookies and header names\n  const headersAndCookies = i18nConfig.headersAndCookies || {};\n  const localeRoutingEnabledCookieName =\n    headersAndCookies?.localeRoutingEnabledCookieName ||\n    defaultLocaleRoutingEnabledCookieName;\n  const referrerLocaleCookieName =\n    headersAndCookies?.referrerLocaleCookieName ||\n    defaultReferrerLocaleCookieName;\n  const localeCookieName =\n    headersAndCookies?.localeCookieName || defaultLocaleCookieName;\n  const resetLocaleCookieName =\n    headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;\n  const localeHeaderName =\n    headersAndCookies?.localeHeaderName || defaultLocaleHeaderName;\n\n  if (!gt.isValidLocale(defaultLocale))\n    throw new Error(\n      `gt-next middleware: defaultLocale \"${defaultLocale}\" is not a valid locale.`\n    );\n\n  const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));\n  if (warningLocales.length)\n    console.warn(createUnsupportedLocalesWarning(warningLocales));\n\n  // --- localized routes --- //\n  // Resolve pathConfig keys to the configured locale spelling.\n  const pathConfig = Object.entries(inputPathConfig).reduce<PathConfig>(\n    (acc, [sharedPath, localizedPath]) => {\n      if (typeof localizedPath === 'string') {\n        acc[sharedPath] = localizedPath;\n      } else {\n        acc[sharedPath] = Object.entries(localizedPath).reduce<{\n          [key: string]: string;\n        }>((acc, [locale, localizedPath]) => {\n          acc[resolvePathConfigLocale(locale)] = localizedPath;\n          return acc;\n        }, {});\n      }\n      return acc;\n    },\n    {}\n  );\n\n  // String aliases apply to every locale, including the default locale.\n  // Expand a copy for lookup while retaining string target semantics in routing.\n  const matcherPathConfig = Object.fromEntries(\n    Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [\n      sharedPath,\n      typeof localizedPath === 'string'\n        ? Object.fromEntries(\n            locales.map((locale) => [\n              determineLocaleWithCache(locale),\n              localizedPath === '' ? '/' : localizedPath,\n            ])\n          )\n        : localizedPath,\n    ])\n  );\n\n  // Create the path mapping\n  const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(\n    matcherPathConfig,\n    prefixDefaultLocale,\n    defaultLocale\n  );\n\n  // --- route overrides --- //\n  // Resolve routeOverrides keys to the configured locale spelling.\n  const routeOverrides = Object.entries(\n    inputRouteOverrides\n  ).reduce<RouteOverrides>((acc, [locale, paths]) => {\n    acc[resolvePathConfigLocale(locale)] = paths;\n    return acc;\n  }, {});\n\n  // Create the route override path mapping\n  const routeOverridePathMaps = Object.entries(routeOverrides).reduce<\n    Record<string, PathMatcher>\n  >((acc, [locale, paths]) => {\n    const overridePathConfig = Object.fromEntries(\n      paths.map((path) => [path, path])\n    );\n    acc[locale] = createPathToSharedPathMap(\n      overridePathConfig,\n      true,\n      defaultLocale\n    ).pathToSharedPath;\n    return acc;\n  }, {});\n\n  // --- locale routes --- //\n  // Compile availability separately from aliases and overrides so it cannot\n  // change route precedence. An empty list deliberately matches nothing.\n  const localeRoutePathMaps = new Map(\n    Object.entries(localeRoutes).map(([locale, paths]) => {\n      // Match request resolution so equivalent spellings use the same map key.\n      const resolvedLocale = determineLocaleWithCache(locale);\n      return [\n        resolvedLocale,\n        createPathMatcher(paths.map((path) => [path, path])),\n      ];\n    })\n  );\n\n  return {\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  };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BA,SAAgB,w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