{"version":3,"sources":["../src/server-plugins.ts","../src/navigation-errors.ts","../src/redirect-query.ts","../src/server/request.ts","../src/server/request-bridge.ts","../src/base-path.ts","../src/i18n/routing.ts","../src/routing/specificity.ts","../src/plugins/route-pattern.ts","../src/plugins/redirects.ts","../src/plugins/headers.ts","../src/plugins/rewrites.ts","../src/plugins/env.ts","../src/plugins/compression.ts","../src/plugins/logger.ts"],"sourcesContent":["// Server-side plugins export\nexport {\n  createRedirectsPlugin,\n  createHeadersPlugin,\n  createRewritesPlugin,\n  createEnvPlugin,\n  createCompressionPlugin,\n  createLoggerPlugin,\n} from \"./plugins\";\n\nexport type {\n  FarmPlugin,\n  FarmPluginContext,\n  FarmPluginLifecycle,\n  FarmRequestPluginContext,\n  FarmRequestStore,\n} from \"./plugin\";\nexport type { RedirectConfig, HeaderConfig, RewriteConfig } from \"./config\";\n","export type FarmRedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nexport interface FarmRedirectSignal {\n  url: string;\n  status: FarmRedirectStatus;\n}\n\nconst REDIRECT_ERROR_CODE = \"FARM_REDIRECT\";\nconst NOT_FOUND_ERROR_CODE = \"FARM_NOT_FOUND\";\nconst REDIRECT_ERROR_SYMBOL = Symbol.for(\"farm.navigation.redirect\");\nconst NOT_FOUND_ERROR_SYMBOL = Symbol.for(\"farm.navigation.notFound\");\n\ntype FarmNavigationError = Error & {\n  digest: string;\n  [REDIRECT_ERROR_SYMBOL]?: FarmRedirectSignal;\n  [NOT_FOUND_ERROR_SYMBOL]?: true;\n};\n\nexport function redirect(url: string, status: FarmRedirectStatus = 307): never {\n  throw createRedirectError(url, status);\n}\n\nexport function permanentRedirect(url: string): never {\n  redirect(url, 308);\n}\n\nexport function notFound(): never {\n  const error = new Error(NOT_FOUND_ERROR_CODE) as FarmNavigationError;\n  error.digest = NOT_FOUND_ERROR_CODE;\n  error[NOT_FOUND_ERROR_SYMBOL] = true;\n  throw error;\n}\n\nexport function isFarmRedirectError(error: unknown): boolean {\n  return Boolean(getFarmRedirectError(error));\n}\n\nexport function getFarmRedirectError(error: unknown): FarmRedirectSignal | null {\n  if (!error || typeof error !== \"object\") return null;\n  const candidate = error as Partial<FarmNavigationError>;\n  if (candidate[REDIRECT_ERROR_SYMBOL]) {\n    return candidate[REDIRECT_ERROR_SYMBOL] as FarmRedirectSignal;\n  }\n\n  if (\n    typeof candidate.digest === \"string\" &&\n    candidate.digest.startsWith(`${REDIRECT_ERROR_CODE};`)\n  ) {\n    const [, status, ...urlParts] = candidate.digest.split(\";\");\n    const parsedStatus = Number(status);\n    if (isFarmRedirectStatus(parsedStatus)) {\n      return {\n        status: parsedStatus,\n        url: urlParts.join(\";\"),\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function isFarmNotFoundError(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const candidate = error as Partial<FarmNavigationError>;\n  return Boolean(candidate[NOT_FOUND_ERROR_SYMBOL] || candidate.digest === NOT_FOUND_ERROR_CODE);\n}\n\nfunction createRedirectError(url: string, status: FarmRedirectStatus): FarmNavigationError {\n  const error = new Error(`${REDIRECT_ERROR_CODE};${status};${url}`) as FarmNavigationError;\n  error.digest = `${REDIRECT_ERROR_CODE};${status};${url}`;\n  error[REDIRECT_ERROR_SYMBOL] = { url, status };\n  return error;\n}\n\nexport function isFarmRedirectStatus(status: unknown): status is FarmRedirectStatus {\n  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n","/** Preserve an incoming query when a redirect destination does not declare one. */\nexport function appendFarmRedirectQuery(destination: string, search: string): string {\n  if (!search || search === \"?\") return destination;\n\n  const hashIndex = destination.indexOf(\"#\");\n  const pathAndQuery = hashIndex === -1 ? destination : destination.slice(0, hashIndex);\n  if (pathAndQuery.includes(\"?\")) return destination;\n\n  if (hashIndex === -1) return `${destination}${search}`;\n  return `${pathAndQuery}${search}${destination.slice(hashIndex)}`;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { Readable } from \"node:stream\";\nimport type { FarmRequest } from \"../types\";\nimport { _setCurrentRequestResolver } from \"./request-bridge\";\n\nconst REQUEST_STORAGE_KEY = Symbol.for(\"@farm.js/core/request-storage\");\n\nfunction getRequestStore(): AsyncLocalStorage<Request> {\n  const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n  const existing = runtime[REQUEST_STORAGE_KEY];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<Request>;\n  }\n\n  const storage = new AsyncLocalStorage<Request>();\n  runtime[REQUEST_STORAGE_KEY] = storage;\n  return storage;\n}\n\nconst requestStore = getRequestStore();\n\n_setCurrentRequestResolver(() => requestStore.getStore());\n\nexport interface FarmRequestURLOptions {\n  origin?: string | URL;\n  trustProxy?: boolean;\n}\n\nexport function resolveFarmRequestURL(req: FarmRequest, options: FarmRequestURLOptions = {}): URL {\n  if (options.origin) {\n    return new URL(req.url || \"/\", options.origin);\n  }\n\n  const forwardedHost = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-host\"])\n    : undefined;\n  const fallbackHost = firstForwardedHeaderValue(req.headers.host) || \"localhost\";\n  const forwardedProto = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-proto\"])\n    : undefined;\n  const normalizedProto = forwardedProto?.toLowerCase();\n  const proto =\n    normalizedProto === \"https\" || normalizedProto === \"http\"\n      ? normalizedProto\n      : isEncryptedFarmRequest(req)\n        ? \"https\"\n        : \"http\";\n  return new URL(req.url || \"/\", resolveRequestOrigin(proto, forwardedHost, fallbackHost));\n}\n\nexport function createWebRequestFromFarmRequest(\n  req: FarmRequest,\n  options: FarmRequestURLOptions = {},\n): Request {\n  const fullUrl = resolveFarmRequestURL(req, options).toString();\n\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  const method = (req.method || \"GET\").toUpperCase();\n  const init: RequestInit & { duplex?: \"half\" } = {\n    method: req.method,\n    headers,\n  };\n\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    init.body = Readable.toWeb(req) as ReadableStream<Uint8Array>;\n    init.duplex = \"half\";\n  }\n\n  return new Request(fullUrl, init);\n}\n\nfunction isEncryptedFarmRequest(req: FarmRequest): boolean {\n  return Boolean((req.socket as { encrypted?: boolean } | undefined)?.encrypted);\n}\n\nfunction firstForwardedHeaderValue(value: string | string[] | undefined): string | undefined {\n  const first = Array.isArray(value) ? value[0] : value;\n  const token = first?.split(\",\", 1)[0]?.trim();\n  return token || undefined;\n}\n\nfunction resolveRequestOrigin(proto: \"http\" | \"https\", host: string | undefined, fallback: string) {\n  for (const candidate of [host, fallback, \"localhost\"]) {\n    if (!candidate) continue;\n    if (/[\\s/?#@\\\\]/u.test(candidate)) continue;\n    try {\n      const url = new URL(`${proto}://${candidate}`);\n      if (url.username || url.password || url.pathname !== \"/\" || url.search || url.hash) continue;\n      return url.origin;\n    } catch {\n      // Try the next host instead of turning an untrusted proxy header into a 500.\n    }\n  }\n  return `${proto}://localhost`;\n}\n\nexport async function _runWithCurrentRequest<T>(\n  request: Request,\n  fn: () => Promise<T> | T,\n): Promise<T> {\n  return requestStore.run(request, fn);\n}\n\nexport function getCurrentRequest(): Request {\n  const request = requestStore.getStore();\n  if (!request) {\n    throw new Error(\n      \"No current request is available. getCurrentRequest() can only be used during server rendering.\",\n    );\n  }\n\n  return request;\n}\n\n// Some runtimes (StackBlitz WebContainers among them) lose AsyncLocalStorage\n// context across async boundaries mid-render. Callers whose feature can\n// degrade gracefully should use this instead of getCurrentRequest() so a\n// missing store never turns into a 500.\nexport function getCurrentRequestOrNull(): Request | null {\n  return requestStore.getStore() ?? null;\n}\n","type CurrentRequestResolver = () => Request | undefined;\n\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\n\ntype GlobalWithCurrentRequestResolver = typeof globalThis & {\n  [CURRENT_REQUEST_RESOLVER_KEY]?: CurrentRequestResolver;\n};\n\nfunction getGlobalState(): GlobalWithCurrentRequestResolver {\n  return globalThis as GlobalWithCurrentRequestResolver;\n}\n\nexport function _setCurrentRequestResolver(resolver: CurrentRequestResolver | undefined): void {\n  getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;\n}\n\nexport function _resolveCurrentRequest(): Request | undefined {\n  return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n","const FARM_BASE_PATH = Symbol.for(\"farm.basePath\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide base path for framework link rendering. */\nexport function setFarmBasePath(basePath: string | undefined): void {\n  getFarmGlobalState()[FARM_BASE_PATH] = normalizeFarmBasePath(basePath);\n}\n\n/** @internal Read the app-wide base path used by framework links. */\nexport function getFarmBasePath(): string {\n  return (getFarmGlobalState()[FARM_BASE_PATH] as string | undefined) ?? \"\";\n}\n\nexport function applyFarmBasePath(href: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath || !href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const canonicalHref = canonicalizeAppRelativeHref(href);\n  if (\n    canonicalHref === normalizedBasePath ||\n    canonicalHref.startsWith(`${normalizedBasePath}/`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}?`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}#`)\n  ) {\n    return canonicalHref;\n  }\n  return `${normalizedBasePath}${canonicalHref}`;\n}\n\nfunction canonicalizeAppRelativeHref(href: string): string {\n  const origin = \"http://farm.local\";\n  const resolved = new URL(href, origin);\n  if (resolved.origin !== origin) {\n    throw new Error(\"Farm app-relative href cannot change the URL origin.\");\n  }\n  return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nexport function stripFarmBasePath(pathname: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath) return pathname || \"/\";\n  if (pathname === normalizedBasePath) return \"/\";\n  if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || \"/\";\n  return pathname.slice(normalizedBasePath.length) || \"/\";\n}\n\nexport function normalizeFarmBasePath(basePath: string | undefined): string {\n  if (!basePath || basePath === \"/\") return \"\";\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(basePath)) {\n    throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = basePath.trim();\n  if (!pathname || pathname === \"/\") return \"\";\n  if (pathname.includes(\"?\") || pathname.includes(\"#\")) {\n    throw new Error(\"Farm basePath cannot contain a query string or hash.\");\n  }\n  if (pathname.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(pathname)) {\n    throw new Error('Farm basePath must be a pathname such as \"/docs\", not a URL.');\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal in URL pathnames and cannot be dot segments.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return `/${pathname}`.replace(/\\/{2,}/g, \"/\").replace(/\\/+$/, \"\");\n}\n\n/** Normalize a configured application base path while preserving `/` for root. */\nexport function normalizeFarmConfigBasePath(basePath: string | undefined): string {\n  return normalizeFarmBasePath(basePath) || \"/\";\n}\n","import { applyFarmBasePath, stripFarmBasePath } from \"../base-path\";\nimport type { FarmI18nDirection, FarmI18nRouting, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocalePathConfig {\n  locales: readonly string[];\n  defaultLocale: string;\n  routing: FarmI18nRouting;\n  basePath?: string;\n}\n\nexport interface FarmLocalePathMatch {\n  locale?: string;\n  pathname: string;\n  explicit: boolean;\n}\n\nconst RTL_LANGUAGES = new Set([\n  \"ar\",\n  \"arc\",\n  \"ckb\",\n  \"dv\",\n  \"fa\",\n  \"he\",\n  \"ku\",\n  \"nqo\",\n  \"ps\",\n  \"sd\",\n  \"syr\",\n  \"ug\",\n  \"ur\",\n  \"yi\",\n]);\n\nexport function resolveFarmLocalePath(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): FarmLocalePathMatch {\n  const normalized = normalizePathname(stripFarmBasePath(pathname, config.basePath));\n  if (config.routing === \"none\") {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const segments = normalized.split(\"/\").filter(Boolean);\n  const firstSegment = segments[0];\n  const locale = config.locales.find(\n    (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase(),\n  );\n  if (!locale) {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const remaining = segments.slice(1);\n  return {\n    locale,\n    pathname: remaining.length > 0 ? `/${remaining.join(\"/\")}` : \"/\",\n    explicit: true,\n  };\n}\n\nexport function stripFarmLocaleFromPathname(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): string {\n  return resolveFarmLocalePath(pathname, config).pathname;\n}\n\nexport function localizeFarmPathname(\n  pathname: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  const internalPathname = resolveFarmLocalePath(pathname, config).pathname;\n  let localizedPathname = internalPathname;\n  if (config.routing === \"none\") {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  if (config.routing === \"prefix-except-default\" && locale === config.defaultLocale) {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  localizedPathname = internalPathname === \"/\" ? `/${locale}` : `/${locale}${internalPathname}`;\n  return applyFarmBasePath(localizedPathname, config.basePath);\n}\n\nexport function localizeFarmHref(\n  href: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  if (!href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const url = new URL(href, \"http://farm.local\");\n  url.pathname = localizeFarmPathname(url.pathname, locale, config);\n  return `${url.pathname}${url.search}${url.hash}`;\n}\n\nexport function getFarmLocaleDirection(\n  locale: string,\n  direction: ResolvedFarmI18nConfig[\"direction\"] | undefined,\n): FarmI18nDirection {\n  const configured = direction?.[locale];\n  if (configured) return configured;\n  const language = locale.split(\"-\")[0]?.toLowerCase() || locale.toLowerCase();\n  return RTL_LANGUAGES.has(language) ? \"rtl\" : \"ltr\";\n}\n\nfunction normalizePathname(pathname: string): string {\n  const withLeadingSlash = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n  if (withLeadingSlash === \"/\") return \"/\";\n  return withLeadingSlash.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n}\n","export type RouteSegmentSpecificity = \"static\" | \"dynamic\" | \"catch-all\" | \"optional-catch-all\";\n\nexport class AmbiguousRouteError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"AmbiguousRouteError\";\n  }\n}\n\nexport class NonTerminalCatchAllRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"NonTerminalCatchAllRouteError\";\n  }\n}\n\nexport class DuplicateRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DuplicateRouteParameterError\";\n  }\n}\n\nexport class ReservedRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"ReservedRouteParameterError\";\n  }\n}\n\nexport class BrowserUnstableRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"BrowserUnstableRouteError\";\n  }\n}\n\nconst SEGMENT_RANK: Record<RouteSegmentSpecificity, number> = {\n  static: 4,\n  dynamic: 3,\n  \"catch-all\": 1,\n  \"optional-catch-all\": 0,\n};\n\n// Ending a route is more specific than consuming the same path through a\n// catch-all, while a following static or dynamic segment remains more specific.\nconst ROUTE_END_RANK = 2;\n\n/** Sort route patterns from the most specific segment sequence to the least specific. */\nexport function compareRouteSpecificity(\n  left: readonly RouteSegmentSpecificity[],\n  right: readonly RouteSegmentSpecificity[],\n): number {\n  const length = Math.max(left.length, right.length);\n\n  for (let index = 0; index < length; index++) {\n    const leftRank = index < left.length ? SEGMENT_RANK[left[index]!] : ROUTE_END_RANK;\n    const rightRank = index < right.length ? SEGMENT_RANK[right[index]!] : ROUTE_END_RANK;\n    if (leftRank !== rightRank) return rightRank - leftRank;\n  }\n\n  return 0;\n}\n\nexport type RoutePatternSyntax = \"page\" | \"router\" | \"api\";\n\nconst ROUTER_PARAMETER_NAME = \"[A-Za-z0-9_$-]+\";\nconst PAGE_PARAMETER_PATTERN = /^(?:\\[\\[\\.\\.\\.(.+)\\]\\]|\\[\\.\\.\\.(.+)\\]|\\[(.+)\\])$/;\nconst ROUTER_PARAMETER_PATTERN =\n  /^(?:\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]|\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]|\\[([A-Za-z0-9_$-]+)\\]|:([A-Za-z0-9_$-]+)|\\*([A-Za-z0-9_$-]+)\\??)$/;\nconst RESERVED_PARAMETER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertBrowserStableRoutePath(pattern: string): void {\n  if (pattern.includes(\"\\\\\") || hasControlCharacter(pattern)) {\n    throw new BrowserUnstableRouteError(\n      `Route path \"${pattern}\" cannot contain backslashes or control characters.`,\n    );\n  }\n\n  for (const segment of pattern.split(\"/\").filter(Boolean)) {\n    if (\n      (segment.startsWith(\"(\") && segment.endsWith(\")\")) ||\n      (segment.startsWith(\"[\") && segment.endsWith(\"]\"))\n    ) {\n      continue;\n    }\n\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes stay literal in browser pathnames.\n    }\n    if (\n      decoded === \".\" ||\n      decoded === \"..\" ||\n      decoded.includes(\"/\") ||\n      decoded.includes(\"\\\\\") ||\n      hasControlCharacter(decoded)\n    ) {\n      throw new BrowserUnstableRouteError(\n        `Route path \"${pattern}\" contains browser-unstable segment \"${segment}\".`,\n      );\n    }\n  }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n  return Array.from(value).some((character) => {\n    const code = character.charCodeAt(0);\n    return code <= 31 || (code >= 127 && code <= 159);\n  });\n}\n\nexport function assertUniqueRouteParameters(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): void {\n  const parameterPattern = syntax === \"router\" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;\n  const names = new Set<string>();\n\n  for (const segment of splitRoutePattern(pattern, syntax)) {\n    const match = parameterPattern.exec(segment);\n    const name = match?.slice(1).find(Boolean);\n    if (!name) continue;\n    if (RESERVED_PARAMETER_NAMES.has(name)) {\n      throw new ReservedRouteParameterError(\n        `Route parameter \"${name}\" in route \"${pattern}\" is reserved. Use a different parameter name.`,\n      );\n    }\n    if (names.has(name)) {\n      throw new DuplicateRouteParameterError(\n        `Duplicate route parameter \"${name}\" in route \"${pattern}\". Each dynamic segment must use a unique name.`,\n      );\n    }\n    names.add(name);\n  }\n}\n\nfunction splitRoutePattern(pattern: string, syntax: RoutePatternSyntax): string[] {\n  return pattern\n    .replace(/\\\\/g, \"/\")\n    .split(\"/\")\n    .filter(Boolean)\n    .filter((segment) =>\n      syntax === \"api\" ? true : !(segment.startsWith(\"(\") && segment.endsWith(\")\")),\n    );\n}\n\nexport function assertTerminalCatchAll(pattern: string, syntax: RoutePatternSyntax = \"page\"): void {\n  const segments = splitRoutePattern(pattern, syntax);\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const catchAllPattern = new RegExp(\n    syntax === \"router\"\n      ? `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]|\\\\*${parameterName}\\\\??)$`\n      : `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\])$`,\n  );\n  const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));\n  if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {\n    throw new NonTerminalCatchAllRouteError(\n      `Catch-all segment \"${segments[catchAllIndex]}\" must be the final segment in route \"${pattern}\".`,\n    );\n  }\n}\n\n/** Return the URL-matching shape of a route without its parameter names. */\nexport function getRoutePatternShape(pattern: string, syntax: RoutePatternSyntax = \"page\"): string {\n  assertTerminalCatchAll(pattern, syntax);\n  const segments = splitRoutePattern(pattern, syntax).map((segment) => {\n    const specificity = getPatternSegmentSpecificity(segment, syntax);\n    if (specificity !== \"static\") return specificity;\n\n    try {\n      return `static:${decodeURIComponent(segment)}`;\n    } catch {\n      return `static:${segment}`;\n    }\n  });\n\n  return segments.length === 0 ? \"/\" : JSON.stringify(segments);\n}\n\n/** Return the specificity of every URL-consuming segment in a route pattern. */\nexport function getRoutePatternSpecificity(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): RouteSegmentSpecificity[] {\n  assertTerminalCatchAll(pattern, syntax);\n  return splitRoutePattern(pattern, syntax).map((segment) =>\n    getPatternSegmentSpecificity(segment, syntax),\n  );\n}\n\nfunction getPatternSegmentSpecificity(\n  segment: string,\n  syntax: RoutePatternSyntax,\n): RouteSegmentSpecificity {\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const supportsColonAndStar = syntax === \"router\";\n  if (\n    new RegExp(`^\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}\\\\?$`).test(segment))\n  ) {\n    return \"optional-catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}$`).test(segment))\n  ) {\n    return \"catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment))\n  ) {\n    return \"dynamic\";\n  }\n\n  return \"static\";\n}\n","import { localizeFarmHref, resolveFarmLocalePath } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { assertBrowserStableRoutePath } from \"../routing/specificity\";\n\ntype ConfigRoutePatternToken =\n  | { kind: \"param\"; name: string; captureIndex: number; catchAll: boolean }\n  | { kind: \"wildcard\"; captureIndex: number };\n\nexport interface CompiledConfigRoutePattern {\n  regex: RegExp;\n  tokens: ConfigRoutePatternToken[];\n}\n\nexport function validateConfigRouteSource(source: string, field = \"Config route source\"): string {\n  if (typeof source !== \"string\" || source.length === 0) {\n    throw new TypeError(`${field} must be a non-empty pathname pattern.`);\n  }\n  if (source.trim() !== source) {\n    throw new Error(`${field} cannot contain leading or trailing whitespace.`);\n  }\n  if (!source.startsWith(\"/\")) {\n    throw new Error(`${field} must start with \"/\".`);\n  }\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw new Error(`${field} must be a pathname without a query string or hash.`);\n  }\n  if (\n    source.includes(\"\\\\\") ||\n    Array.from(source).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new Error(`${field} cannot contain backslashes or control characters.`);\n  }\n  assertBrowserStableRoutePath(source);\n  return source;\n}\n\nexport function resolveConfigRoutePathname(\n  pathname: string,\n  i18n?: ResolvedFarmI18nConfig,\n): { pathname: string; locale?: string } {\n  if (!i18n?.enabled) return { pathname: normalizeConfigRoutePathname(pathname) };\n  const match = resolveFarmLocalePath(pathname, i18n);\n  return { pathname: normalizeConfigRoutePathname(match.pathname), locale: match.locale };\n}\n\n/**\n * Drop a trailing slash before matching, mirroring `normalizeRuntimePath` in\n * the generated production matcher. Without this a request for `/old/` misses\n * a `/old` rule in dev while matching it in a built app.\n */\nfunction normalizeConfigRoutePathname(pathname: string): string {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\/+$/, \"\") || \"/\" : pathname;\n}\n\nexport function localizeConfigRouteDestination(\n  destination: string,\n  locale: string | undefined,\n  i18n?: ResolvedFarmI18nConfig,\n): string {\n  return locale && i18n?.enabled ? localizeFarmHref(destination, locale, i18n) : destination;\n}\n\n/**\n * Append a catch-all capture, absorbing the separator that precedes it.\n *\n * The production matcher works on split segments and lets a non-terminal\n * catch-all consume zero of them (`minConsume = 0`), so `/x/*` + `/y` matches\n * `/x/y` and `/files/:path*` matches `/files`. Emitting a bare `(.*)` after a\n * literal `/` instead demands at least that separator, so the same rule was\n * inert in dev. Folding the slash into the optional group is how path-to-regexp\n * expresses the same thing, and it keeps one capture group so capture indexes\n * are unchanged (a non-participating group reads back as \"\").\n */\nfunction appendCatchAll(pattern: string): string {\n  return pattern.endsWith(\"/\") ? `${pattern.slice(0, -1)}(?:/(.*))?` : `${pattern}(.*)`;\n}\n\nfunction escapeRegexCharacter(character: string): string {\n  return /[\\\\^$.*+?()[\\]{}|]/.test(character) ? `\\\\${character}` : character;\n}\n\nexport function compileConfigRoutePattern(source: string): CompiledConfigRoutePattern {\n  validateConfigRouteSource(source);\n  const tokens: ConfigRoutePatternToken[] = [];\n  let pattern = \"\";\n  let captureIndex = 1;\n\n  for (let index = 0; index < source.length; ) {\n    const rest = source.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      tokens.push({\n        kind: \"param\",\n        name: parameter[1],\n        captureIndex,\n        catchAll: parameter[2] === \"*\",\n      });\n      pattern = parameter[2] ? appendCatchAll(pattern) : `${pattern}([^/]+)`;\n      captureIndex += 1;\n      index += parameter[0].length;\n      continue;\n    }\n\n    if (source[index] === \"*\") {\n      tokens.push({ kind: \"wildcard\", captureIndex });\n      pattern = appendCatchAll(pattern);\n      captureIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    pattern += escapeRegexCharacter(source[index]);\n    index += 1;\n  }\n\n  return { regex: new RegExp(`^${pattern}$`), tokens };\n}\n\nexport function interpolateConfigRouteDestination(\n  destination: string,\n  match: RegExpMatchArray,\n  tokens: readonly ConfigRoutePatternToken[],\n): string {\n  const namedCaptures = new Map<string, string>();\n  const wildcardCaptures: string[] = [];\n  const captures = new Map<number, string>();\n\n  for (const token of tokens) {\n    const value = normalizeConfigRouteCapture(\n      match[token.captureIndex] || \"\",\n      token.kind === \"wildcard\" || token.catchAll,\n    );\n    captures.set(token.captureIndex, value);\n    if (token.kind === \"param\") {\n      namedCaptures.set(token.name, value);\n    } else {\n      wildcardCaptures.push(value);\n    }\n  }\n\n  let result = \"\";\n  let wildcardIndex = 0;\n  for (let index = 0; index < destination.length; ) {\n    const rest = destination.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      const value = namedCaptures.get(parameter[1]);\n      result += value === undefined ? parameter[0] : value;\n      index += parameter[0].length;\n      continue;\n    }\n\n    const capture = rest.match(/^\\$(\\d+)/);\n    if (capture) {\n      result += captures.get(Number(capture[1])) ?? \"\";\n      index += capture[0].length;\n      continue;\n    }\n\n    if (destination[index] === \"*\") {\n      result += wildcardCaptures[wildcardIndex] || \"\";\n      wildcardIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    result += destination[index];\n    index += 1;\n  }\n\n  return result;\n}\n\nfunction normalizeConfigRouteCapture(value: string, catchAll: boolean): string {\n  const segments = catchAll ? value.split(\"/\").filter(Boolean) : [value];\n  return segments\n    .map((segment) => encodeConfigRouteSegment(decodeConfigRouteSegment(segment)))\n    .join(\"/\");\n}\n\nfunction decodeConfigRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction encodeConfigRouteSegment(segment: string): string {\n  return encodeURIComponent(segment).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { RedirectConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { isFarmRedirectStatus } from \"../navigation-errors\";\nimport { appendFarmRedirectQuery } from \"../redirect-query\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport {\n  compileConfigRoutePattern,\n  interpolateConfigRouteDestination,\n  localizeConfigRouteDestination,\n  resolveConfigRoutePathname,\n} from \"./route-pattern\";\n\nexport function createRedirectsPlugin(\n  redirects: RedirectConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  for (const redirect of redirects) {\n    if (redirect.statusCode !== undefined && !isFarmRedirectStatus(redirect.statusCode)) {\n      throw new RangeError(\n        `Redirect \"${redirect.source}\" statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n  }\n  const compiledRedirects = redirects.map((redirect) => ({\n    redirect,\n    pattern: compileConfigRoutePattern(redirect.source),\n  }));\n\n  return {\n    name: \"farm:redirects\",\n    enforce: \"pre\",\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const routePath = resolveConfigRoutePathname(url.pathname, i18n);\n      const pathname = routePath.pathname;\n\n      for (const { redirect, pattern } of compiledRedirects) {\n        const match = pathname.match(pattern.regex);\n        if (match) {\n          const localizedDestination = localizeConfigRouteDestination(\n            interpolateConfigRouteDestination(redirect.destination, match, pattern.tokens),\n            routePath.locale,\n            i18n,\n          );\n          const destination = appendFarmRedirectQuery(localizedDestination, url.search);\n\n          const statusCode = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n\n          res.writeHead(statusCode, {\n            Location: destination,\n          });\n          res.end();\n          return;\n        }\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { HeaderConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport { compileConfigRoutePattern, resolveConfigRoutePathname } from \"./route-pattern\";\n\nconst FARM_CONFIG_HEADERS_FINALIZER = Symbol.for(\"farm.configHeadersFinalizer\");\n\nfunction appendConfiguredLinkHeader(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Link\");\n  if (current === undefined) {\n    res.setHeader(\"Link\", value);\n    return;\n  }\n\n  const currentValue = Array.isArray(current) ? current.join(\", \") : String(current);\n  if (currentValue !== value && !currentValue.endsWith(`, ${value}`)) {\n    res.setHeader(\"Link\", `${currentValue}, ${value}`);\n  }\n}\n\nfunction appendConfiguredSetCookieHeader(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Set-Cookie\");\n  if (current === undefined) {\n    res.setHeader(\"Set-Cookie\", value);\n    return;\n  }\n\n  const values = (Array.isArray(current) ? current : [current]).map(String);\n  if (!values.includes(value)) {\n    res.setHeader(\"Set-Cookie\", [...values, value]);\n  }\n}\n\nfunction applyResponseHeaders(\n  res: FarmResponse,\n  matchedHeaders: readonly HeaderConfig[\"headers\"][],\n): void {\n  for (const headers of matchedHeaders) {\n    for (const header of headers) {\n      const key = header.key.toLowerCase();\n      if (key === \"link\") {\n        appendConfiguredLinkHeader(res, header.value);\n      } else if (key === \"set-cookie\") {\n        appendConfiguredSetCookieHeader(res, header.value);\n      } else {\n        res.setHeader(header.key, header.value);\n      }\n    }\n  }\n}\n\nfunction applyWriteHeadHeaders(res: FarmResponse, headers: unknown): void {\n  if (Array.isArray(headers)) {\n    let setCookieWritten = false;\n    for (let index = 0; index + 1 < headers.length; index += 2) {\n      const key = String(headers[index]);\n      const value = headers[index + 1] as string | number | readonly string[];\n      if (key.toLowerCase() === \"set-cookie\" && setCookieWritten) {\n        const current = res.getHeader(\"Set-Cookie\");\n        const values = (Array.isArray(current) ? current : [current]).filter(\n          (entry) => entry !== undefined,\n        );\n        res.setHeader(\"Set-Cookie\", [...values, ...(Array.isArray(value) ? value : [value])]);\n      } else {\n        res.setHeader(key, value);\n        if (key.toLowerCase() === \"set-cookie\") setCookieWritten = true;\n      }\n    }\n    return;\n  }\n\n  if (!headers || typeof headers !== \"object\") return;\n  for (const [key, value] of Object.entries(headers)) {\n    if (value !== undefined) res.setHeader(key, value);\n  }\n}\n\nexport function createHeadersPlugin(\n  headers: HeaderConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  const compiledHeaders = headers.map((config) => ({\n    config,\n    pattern: compileConfigRoutePattern(config.source),\n  }));\n\n  return {\n    name: \"farm:headers\",\n    enforce: \"pre\",\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const pathname = resolveConfigRoutePathname(url.pathname, i18n).pathname;\n      const matchedHeaders = compiledHeaders\n        .filter(({ pattern }) => pattern.regex.test(pathname))\n        .map(({ config }) => config.headers);\n\n      applyResponseHeaders(res, matchedHeaders);\n\n      const responseWithFinalizer = res as FarmResponse & {\n        [FARM_CONFIG_HEADERS_FINALIZER]?: boolean;\n      };\n      if (matchedHeaders.length === 0 || responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER]) {\n        return;\n      }\n\n      responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER] = true;\n      const writeHead = res.writeHead;\n      res.writeHead = ((statusCode: number, ...args: unknown[]) => {\n        const statusMessage = typeof args[0] === \"string\" ? (args.shift() as string) : undefined;\n        applyWriteHeadHeaders(res, args[0]);\n        applyResponseHeaders(res, matchedHeaders);\n        return statusMessage === undefined\n          ? (writeHead as any).call(res, statusCode)\n          : (writeHead as any).call(res, statusCode, statusMessage);\n      }) as FarmResponse[\"writeHead\"];\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { RewriteConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport {\n  compileConfigRoutePattern,\n  interpolateConfigRouteDestination,\n  localizeConfigRouteDestination,\n  resolveConfigRoutePathname,\n} from \"./route-pattern\";\n\nexport const FARM_CONFIG_REWRITES_PLUGIN_NAME = \"farm:rewrites\";\n\nexport function createRewritesPlugin(\n  rewrites: RewriteConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  const compiledRewrites = rewrites.map((rewrite) => ({\n    rewrite,\n    pattern: compileConfigRoutePattern(rewrite.source),\n  }));\n\n  return {\n    name: FARM_CONFIG_REWRITES_PLUGIN_NAME,\n    enforce: \"pre\",\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const routePath = resolveConfigRoutePathname(url.pathname, i18n);\n      const pathname = routePath.pathname;\n\n      for (const { rewrite, pattern } of compiledRewrites) {\n        const match = pathname.match(pattern.regex);\n        if (match) {\n          const newPath = localizeConfigRouteDestination(\n            interpolateConfigRouteDestination(rewrite.destination, match, pattern.tokens),\n            routePath.locale,\n            i18n,\n          );\n          const destinationUrl = new URL(newPath, url);\n          if (!destinationUrl.search && url.search) {\n            destinationUrl.search = url.search;\n          }\n          req.url =\n            destinationUrl.origin === url.origin\n              ? destinationUrl.pathname + destinationUrl.search\n              : destinationUrl.href;\n          break;\n        }\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\n\nexport function createEnvPlugin(\n  env: Record<string, string>,\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n  } = {},\n): FarmPlugin {\n  return {\n    name: \"farm:env\",\n\n    configResolved(config, context) {\n      for (const [key, value] of Object.entries(env)) {\n        process.env[key] = value;\n      }\n    },\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport { pipeline, Readable } from \"node:stream\";\nimport { constants, createBrotliCompress, createGzip } from \"node:zlib\";\n\ntype SupportedEncoding = \"br\" | \"gzip\";\n\nconst Q_VALUE = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/;\n\nfunction parseEncodingQuality(header: string): Map<string, number> {\n  const qualities = new Map<string, number>();\n\n  for (const item of header.split(\",\")) {\n    const [rawEncoding, ...parameters] = item.trim().split(\";\");\n    const encoding = rawEncoding?.trim().toLowerCase();\n    if (!encoding) continue;\n\n    let quality = 1;\n    for (const parameter of parameters) {\n      const [rawName, rawValue] = parameter.split(\"=\", 2);\n      if (rawName?.trim().toLowerCase() !== \"q\") continue;\n      const value = rawValue?.trim() ?? \"\";\n      quality = Q_VALUE.test(value) ? Number(value) : 0;\n    }\n\n    qualities.set(encoding, Math.max(qualities.get(encoding) ?? 0, quality));\n  }\n\n  return qualities;\n}\n\nfunction selectEncoding(header: string): SupportedEncoding | undefined {\n  if (!header.trim()) return undefined;\n\n  const qualities = parseEncodingQuality(header);\n  const wildcard = qualities.get(\"*\") ?? 0;\n  const quality = (encoding: SupportedEncoding) => qualities.get(encoding) ?? wildcard;\n  const brotli = quality(\"br\");\n  const gzip = quality(\"gzip\");\n\n  if (brotli <= 0 && gzip <= 0) return undefined;\n  return brotli >= gzip ? \"br\" : \"gzip\";\n}\n\nfunction isCompressionEligible(request: Request, response: Response): boolean {\n  if (\n    (request.method !== \"HEAD\" && !response.body) ||\n    response.status === 204 ||\n    response.status === 205 ||\n    response.status === 304 ||\n    response.headers.has(\"content-encoding\") ||\n    response.headers.has(\"content-range\") ||\n    response.headers.get(\"cache-control\")?.toLowerCase().includes(\"no-transform\")\n  ) {\n    return false;\n  }\n\n  const mediaType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n  return mediaType !== \"text/event-stream\";\n}\n\nfunction appendVary(headers: Headers, value: string): void {\n  const current = headers.get(\"vary\");\n  const values = current\n    ? current\n        .split(\",\")\n        .map((item) => item.trim())\n        .filter(Boolean)\n    : [];\n  if (values.includes(\"*\")) return;\n  if (!values.some((item) => item.toLowerCase() === value.toLowerCase())) {\n    values.push(value);\n  }\n  headers.set(\"vary\", values.join(\", \"));\n}\n\nfunction compressResponse(response: Response, encoding: SupportedEncoding): Response {\n  // Both compressors must flush per chunk. Without an explicit flush mode brotli\n  // buffers until its 4 MB window fills or the source ends, so a streaming SSR,\n  // RSC, or NDJSON response delivers nothing to the client until it completes -\n  // and `selectEncoding` prefers brotli on every tie, so that is the default\n  // path for an ordinary browser.\n  const compressor =\n    encoding === \"br\"\n      ? createBrotliCompress({ flush: constants.BROTLI_OPERATION_FLUSH })\n      : createGzip({ flush: constants.Z_SYNC_FLUSH });\n  const input = Readable.fromWeb(response.body as any);\n  const output = pipeline(input, compressor, () => {\n    // pipeline forwards source failures to the compressed body and destroys\n    // the source when the response consumer cancels it. The web stream owns\n    // observing the resulting destination error.\n  });\n  const headers = new Headers(response.headers);\n\n  headers.set(\"content-encoding\", encoding);\n  headers.delete(\"content-length\");\n  appendVary(headers, \"Accept-Encoding\");\n\n  const etag = headers.get(\"etag\");\n  if (etag && !etag.startsWith(\"W/\")) {\n    headers.set(\"etag\", `W/${etag}`);\n  }\n\n  return new Response(Readable.toWeb(output) as ReadableStream<Uint8Array>, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nfunction varyIdentityResponse(response: Response): Response {\n  const headers = new Headers(response.headers);\n  appendVary(headers, \"Accept-Encoding\");\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function createCompressionPlugin({\n  beforeRequest: overrideBeforeRequest,\n  afterResponse: overrideAfterResponse,\n}: {\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n} = {}): FarmPlugin {\n  return {\n    name: \"farm:compression\",\n    enforce: \"post\",\n\n    runtime: {\n      after({ request, response, isProd }) {\n        if (!isProd || !isCompressionEligible(request, response)) return;\n\n        if (request.method === \"HEAD\") return varyIdentityResponse(response);\n\n        const encoding = selectEncoding(request.headers.get(\"accept-encoding\") ?? \"\");\n        if (!encoding) return varyIdentityResponse(response);\n        return compressResponse(response, encoding);\n      },\n    },\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmResponse } from \"../types\";\nimport type { FarmRequest } from \"../types\";\n\nexport function createLoggerPlugin({\n  beforeRequest,\n  afterResponse,\n}: {\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n} = {}): FarmPlugin {\n  const plugin: FarmPlugin = {\n    name: \"farm:logger\",\n    enforce: \"post\",\n  };\n\n  if (beforeRequest) {\n    plugin.beforeRequest = async (req, res, context) => {\n      await beforeRequest(req, res, context);\n    };\n  }\n  if (afterResponse) {\n    plugin.afterResponse = async (req, res, context) => {\n      await afterResponse(req, res, context);\n    };\n  }\n\n  return plugin;\n}\n"],"mappings":";;;;;;;;;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