{"version":3,"sources":["../src/ssg.ts","../src/routing/route-manager.ts","../src/utils/client-component.ts","../src/island.ts","../src/navigation/render-plan.ts","../src/static-metadata-image.ts","../src/routing/route-slots.ts","../src/server/renderer.ts","../src/server/dev-styles.ts","../src/server/full-document.ts","../src/not-found.ts","../src/font-vite.ts","../src/components/not-found-styles.ts","../src/server/error-diagnostics.ts","../src/app.ts","../src/default-styles.ts","../src/plugin.ts","../src/client-plugin-build.ts","../src/client-cache-persistence-build.ts","../src/type-artifacts.ts","../src/routing/generate-route-types.ts","../src/image-types.ts","../src/content-types.ts","../src/i18n/type-generator.ts","../src/vite.ts","../src/dev-static.ts","../src/server-query-boundary.ts","../src/client-boundary-env.ts","../src/image-vite.ts","../src/server/vite-config.ts","../src/theme/vite.ts","../src/integration-provider-build.ts","../src/navigation/page-data-error.ts","../src/openapi/dev-status.ts"],"sourcesContent":["/**\n * Farm.js SSG (Static Site Generation) Module\n *\n * Handles collection and pre-rendering of SSG pages at build time.\n *\n * SSR is the default - pages render on each request\n * SSG is opt-in via `export const ssg = true`, Next-compatible route\n * config exports, or a top-of-file rendering directive.\n *\n * @example\n * ```tsx\n * // SSG Page\n * export const ssg = true;\n * export default function AboutPage() {\n *   return <h1>About</h1>;\n * }\n *\n * // SSG with ISR\n * export const ssg = true;\n * export const revalidate = 60;\n * export default async function ProductsPage() {\n *   const products = await fetchProducts();\n *   return <ProductList products={products} />;\n * }\n *\n * // Dynamic SSG\n * export const ssg = true;\n * export async function getStaticPaths() {\n *   const posts = await fetchPosts();\n *   return posts.map(post => ({ slug: post.slug }));\n * }\n * export default async function BlogPost({ params }) {\n *   return <article>{params.slug}</article>;\n * }\n *\n * // Next-compatible route config\n * export const dynamic = \"force-static\";\n * export const revalidate = 60;\n *\n * // PPR/static-shell route\n * export const experimental_ppr = true;\n * export const revalidate = 60;\n *\n * // Directive config\n * \"use ssg; 60\";\n * export default function DocsPage() {\n *   return <h1>Docs</h1>;\n * }\n * ```\n */\n\nimport { readFile } from \"fs/promises\";\nimport type {\n  RouteModule,\n  SSGPage,\n  SSGCollectionResult,\n  StaticPathParams,\n  StaticPathPrimitive,\n} from \"./types\";\n\ninterface RouteEntry {\n  path: string;\n  filePath: string;\n  isDynamic: boolean;\n  pattern: string;\n}\n\nexport type RouteRenderingDynamic = NonNullable<RouteModule[\"dynamic\"]>;\n\nexport interface RouteRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive?: string;\n}\n\nexport interface RouteRenderingOptions {\n  /**\n   * Whether `experimental.ppr` is enabled in the app config. Route-level PPR\n   * opt-ins (`ppr`, `experimental_ppr`, `\"use ppr\"`) are inert without it.\n   */\n  experimentalPPR?: boolean;\n}\n\nexport interface StaticRouteCandidateAnalysis {\n  candidate: boolean;\n  blockers: string[];\n}\n\ninterface DirectiveRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive: string;\n}\n\nconst OPTIONAL_CATCH_ALL_SEGMENT = /^\\[\\[\\.\\.\\.([^\\]]+)\\]\\]$/;\nconst REQUIRED_CATCH_ALL_SEGMENT = /^\\[\\.\\.\\.([^\\]]+)\\]$/;\nconst REQUIRED_DYNAMIC_SEGMENT = /^\\[([^\\]]+)\\]$/;\n\nconst REQUEST_API_LABELS = new Map<string, string>([\n  [\"cookies\", \"request cookies\"],\n  [\"headers\", \"request headers\"],\n  [\"getCurrentRequest\", \"the current Request\"],\n  [\"useSearchParams\", \"URL search parameters\"],\n  [\"auth\", \"request authentication\"],\n  [\"getServerSession\", \"request authentication\"],\n  [\"getSession\", \"request authentication\"],\n  [\"currentUser\", \"request authentication\"],\n]);\n\nconst ROUTE_PROP_LABELS = new Map<string, string>([\n  [\"searchParams\", \"URL search parameters\"],\n  [\"middleware\", \"middleware request data\"],\n  [\"middlewareData\", \"middleware request data\"],\n  [\"context\", \"request context\"],\n]);\n\n/**\n * Resolve route rendering from Farm exports, Next-compatible exports, and\n * top-of-file directives such as `\"use ssg\";` or `\"use ssg; 60\";`.\n */\nfunction resolveConfiguredRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const pprEnabled = options?.experimentalPPR === true;\n  const directiveConfig = parseRouteRenderingDirective(source);\n  let ssg = directiveConfig?.ssg ?? false;\n  let requestedPPR = directiveConfig?.ppr ?? false;\n  let revalidate = directiveConfig?.revalidate;\n  const moduleDynamic = normalizeDynamicMode(mod?.dynamic);\n  const dynamic = moduleDynamic ?? directiveConfig?.dynamic;\n  const hasExplicitSsg = typeof mod?.ssg === \"boolean\";\n  const hasExplicitPPR =\n    typeof mod?.ppr === \"boolean\" || typeof mod?.experimental_ppr === \"boolean\";\n\n  if (hasExplicitSsg) {\n    ssg = mod!.ssg === true;\n  }\n\n  if (hasExplicitPPR) {\n    requestedPPR = mod?.ppr === true || mod?.experimental_ppr === true;\n  }\n\n  if (typeof mod?.revalidate === \"number\") {\n    if (mod.revalidate > 0) {\n      revalidate = mod.revalidate;\n      // A PPR opt-in keeps the route dynamic even while experimental.ppr is\n      // off: the page expects Suspense holes, so falling back to ISR would\n      // bake request-time content into a shared static artifact.\n      if (!hasExplicitSsg && !requestedPPR) {\n        ssg = true;\n      }\n    } else {\n      revalidate = undefined;\n      if (!hasExplicitSsg) {\n        ssg = false;\n      }\n    }\n  } else if (mod?.revalidate === false) {\n    revalidate = undefined;\n  }\n\n  if (moduleDynamic === \"force-static\" || moduleDynamic === \"error\") {\n    ssg = true;\n    requestedPPR = false;\n  } else if (moduleDynamic === \"force-dynamic\") {\n    ssg = false;\n    requestedPPR = false;\n    revalidate = undefined;\n  }\n\n  const ppr = pprEnabled && !ssg && requestedPPR;\n\n  return {\n    ssg,\n    ppr,\n    revalidate: ssg || ppr ? revalidate : undefined,\n    dynamic,\n    directive: directiveConfig?.directive,\n  };\n}\n\n/**\n * Resolve the effective rendering mode. Direct request reads make an explicitly\n * static route dynamic so request-specific HTML cannot enter a shared artifact.\n */\nexport function resolveRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const rendering = resolveConfiguredRouteRenderingConfig(mod, source, options);\n  if (!rendering.ssg || !source) {\n    return rendering;\n  }\n\n  const requestBlockers = findRequestBoundSourceBlockers(source);\n  if (requestBlockers.length === 0) {\n    return rendering;\n  }\n\n  return {\n    ...rendering,\n    ssg: false,\n    revalidate: undefined,\n  };\n}\n\nexport async function resolveRouteRenderingConfigFromFile(\n  mod: RouteModule | null | undefined,\n  filePath: string,\n  options?: RouteRenderingOptions,\n): Promise<RouteRenderingConfig> {\n  const source = await readFile(filePath, \"utf8\").catch(() => undefined);\n  return resolveRouteRenderingConfig(mod, source, options);\n}\n\n/**\n * Conservatively identify a route that may be safe to pre-render.\n *\n * This intentionally produces a suggestion rather than changing rendering:\n * request-bound work can live in a transitive import, which source inspection\n * of the route module cannot prove safe. Explicit route config always wins.\n */\nexport function analyzeStaticRouteCandidate(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n  options: { isDynamic?: boolean } = {},\n): StaticRouteCandidateAnalysis {\n  const blockers: string[] = [];\n\n  if (!source) {\n    blockers.push(\"route source is unavailable\");\n  }\n\n  if (options.isDynamic) {\n    blockers.push(\"the route has dynamic path segments\");\n  }\n\n  if (hasExplicitRenderingConfig(mod, source)) {\n    blockers.push(\"the route already has explicit rendering config\");\n  }\n\n  if (source) {\n    blockers.push(...findRequestBoundSourceBlockers(source));\n  }\n\n  return {\n    candidate: blockers.length === 0,\n    blockers,\n  };\n}\n\nfunction findRequestBoundSourceBlockers(source: string): string[] {\n  const blockers = new Set<string>();\n  const code = stripCommentsAndLiteralContents(source);\n\n  const sourceWithoutComments = stripComments(source);\n  for (const binding of readRequestApiImportBindings(sourceWithoutComments)) {\n    if (new RegExp(`\\\\b${escapeRegExp(binding.local)}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`).test(code)) {\n      blockers.add(`the route reads ${binding.label}`);\n    }\n  }\n\n  for (const namespace of readNamespaceImportBindings(sourceWithoutComments)) {\n    for (const [name, label] of REQUEST_API_LABELS) {\n      if (\n        new RegExp(\n          `\\\\b${escapeRegExp(namespace)}\\\\s*(?:\\\\?\\\\.\\\\s*|\\\\.\\\\s*)${name}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`,\n        ).test(code)\n      ) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n  }\n\n  const params = readDefaultRouteParameters(code);\n  if (params) {\n    for (const [name, label] of ROUTE_PROP_LABELS) {\n      if (new RegExp(`\\\\b${name}\\\\b`).test(params)) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n\n    const propsName = params.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?::|,|$)/)?.[1];\n    if (propsName) {\n      for (const [name, label] of ROUTE_PROP_LABELS) {\n        if (new RegExp(`\\\\b${escapeRegExp(propsName)}\\\\s*\\\\.\\\\s*${name}\\\\b`).test(code)) {\n          blockers.add(`the route reads ${label}`);\n        }\n        if (\n          new RegExp(`\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}\\\\s*=\\\\s*${escapeRegExp(propsName)}\\\\b`).test(\n            code,\n          )\n        ) {\n          blockers.add(`the route reads ${label}`);\n        }\n      }\n    }\n  }\n\n  return [...blockers];\n}\n\nfunction readRequestApiImportBindings(source: string): Array<{ local: string; label: string }> {\n  const bindings: Array<{ local: string; label: string }> = [];\n  for (const clause of readStaticImportClauses(source)) {\n    const namedGroup = clause.match(/\\{([\\s\\S]*?)\\}/)?.[1];\n    for (const rawSpecifier of (namedGroup ?? \"\").split(\",\")) {\n      const specifier = rawSpecifier.trim().replace(/^type\\s+/, \"\");\n      const imported = specifier.match(/^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/);\n      if (!imported?.[1]) continue;\n      const label = REQUEST_API_LABELS.get(imported[1]);\n      if (label) bindings.push({ local: imported[2] ?? imported[1], label });\n    }\n\n    const local = clause.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?:,|$)/)?.[1];\n    if (local) {\n      const label = REQUEST_API_LABELS.get(local);\n      if (label) bindings.push({ local, label });\n    }\n  }\n\n  return bindings;\n}\n\nfunction readNamespaceImportBindings(source: string): string[] {\n  return readStaticImportClauses(source)\n    .map((clause) => clause.match(/\\*\\s*as\\s*([A-Za-z_$][\\w$]*)/)?.[1])\n    .filter((binding): binding is string => Boolean(binding));\n}\n\nfunction readStaticImportClauses(source: string): string[] {\n  return [...source.matchAll(/\\bimport\\s+(?!\\()([\\s\\S]*?)\\s+from\\s*[\"'][^\"']+[\"']/g)]\n    .map((match) => match[1])\n    .filter((clause): clause is string => Boolean(clause));\n}\n\nfunction readDefaultRouteParameters(code: string): string | undefined {\n  const inlineParams =\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?function\\b[^(]*\\(([^)]*)\\)/)?.[1] ??\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?\\(([^)]*)\\)\\s*=>/)?.[1];\n  if (inlineParams !== undefined) return inlineParams;\n\n  const binding =\n    code.match(/\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\s*;?/)?.[1] ??\n    code.match(/\\bexport\\s*\\{\\s*([A-Za-z_$][\\w$]*)\\s+as\\s+default\\s*\\}/)?.[1];\n  if (!binding) return undefined;\n  const escapedBinding = escapeRegExp(binding);\n\n  return (\n    code.match(new RegExp(`\\\\bfunction\\\\s+${escapedBinding}\\\\s*\\\\(([^)]*)\\\\)`))?.[1] ??\n    code.match(\n      new RegExp(\n        `\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*(?:async\\\\s+)?\\\\(([^)]*)\\\\)\\\\s*=>`,\n      ),\n    )?.[1] ??\n    code.match(\n      new RegExp(`\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*function\\\\s*\\\\(([^)]*)\\\\)`),\n    )?.[1]\n  );\n}\n\nfunction stripCommentsAndLiteralContents(source: string): string {\n  return sanitizeSource(source, true);\n}\n\nfunction stripComments(source: string): string {\n  return sanitizeSource(source, false);\n}\n\nfunction sanitizeSource(source: string, maskLiterals: boolean): string {\n  const output = [...source];\n  const mask = (index: number) => {\n    if (output[index] !== \"\\n\" && output[index] !== \"\\r\") output[index] = \" \";\n  };\n\n  const scanQuoted = (start: number, quote: \"'\" | '\"'): number => {\n    let index = start;\n    if (maskLiterals) mask(index);\n    index += 1;\n    while (index < source.length) {\n      if (source[index] === \"\\\\\") {\n        if (maskLiterals) mask(index);\n        if (index + 1 < source.length && maskLiterals) mask(index + 1);\n        index += 2;\n        continue;\n      }\n      const character = source[index];\n      if (maskLiterals) mask(index);\n      index += 1;\n      if (character === quote) break;\n    }\n    return index;\n  };\n\n  const scanCode = (start: number, stopAtTemplateBrace: boolean): number => {\n    let index = start;\n    let braceDepth = 0;\n    while (index < source.length) {\n      const character = source[index];\n      const next = source[index + 1];\n      if (character === \"/\" && next === \"/\") {\n        while (index < source.length && source[index] !== \"\\n\" && source[index] !== \"\\r\") {\n          mask(index++);\n        }\n        continue;\n      }\n      if (character === \"/\" && next === \"*\") {\n        mask(index++);\n        mask(index++);\n        while (index < source.length) {\n          const closesComment = source[index] === \"*\" && source[index + 1] === \"/\";\n          mask(index++);\n          if (closesComment) {\n            mask(index++);\n            break;\n          }\n        }\n        continue;\n      }\n      if (character === \"'\" || character === '\"') {\n        index = scanQuoted(index, character);\n        continue;\n      }\n      if (character === \"`\") {\n        if (maskLiterals) mask(index);\n        index += 1;\n        while (index < source.length) {\n          if (source[index] === \"\\\\\") {\n            if (maskLiterals) mask(index);\n            if (index + 1 < source.length && maskLiterals) mask(index + 1);\n            index += 2;\n          } else if (source[index] === \"`\") {\n            if (maskLiterals) mask(index);\n            index += 1;\n            break;\n          } else if (source[index] === \"$\" && source[index + 1] === \"{\") {\n            if (maskLiterals) {\n              mask(index);\n              mask(index + 1);\n            }\n            index = scanCode(index + 2, true);\n          } else {\n            if (maskLiterals) mask(index);\n            index += 1;\n          }\n        }\n        continue;\n      }\n      if (character === \"{\") {\n        braceDepth += 1;\n      } else if (character === \"}\") {\n        if (stopAtTemplateBrace && braceDepth === 0) {\n          if (maskLiterals) mask(index);\n          return index + 1;\n        }\n        braceDepth = Math.max(0, braceDepth - 1);\n      }\n      index += 1;\n    }\n    return index;\n  };\n\n  scanCode(0, false);\n  return output.join(\"\");\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction hasExplicitRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n): boolean {\n  return (\n    typeof mod?.ssg === \"boolean\" ||\n    typeof mod?.ppr === \"boolean\" ||\n    typeof mod?.experimental_ppr === \"boolean\" ||\n    typeof mod?.revalidate !== \"undefined\" ||\n    typeof mod?.dynamic !== \"undefined\" ||\n    typeof parseRouteRenderingDirective(source) !== \"undefined\"\n  );\n}\n\nexport function parseRouteRenderingDirective(\n  source: string | undefined,\n): DirectiveRenderingConfig | undefined {\n  if (!source) {\n    return undefined;\n  }\n\n  for (const directive of readDirectivePrologue(source)) {\n    const config = parseKnownRenderingDirective(directive);\n    if (config) {\n      return config;\n    }\n  }\n\n  return undefined;\n}\n\nfunction parseKnownRenderingDirective(directive: string): DirectiveRenderingConfig | undefined {\n  const normalized = directive.trim().toLowerCase();\n  const match = normalized.match(\n    /^use\\s+(ssg|static|isr|ssr|dynamic|ppr)(?:\\s*[;:]\\s*(\\d+))?\\s*;?$/,\n  );\n\n  if (!match?.[1]) {\n    return undefined;\n  }\n\n  const mode = match[1];\n  const revalidate = match[2] ? Number(match[2]) : undefined;\n\n  if (mode === \"ssr\" || mode === \"dynamic\") {\n    return {\n      ssg: false,\n      ppr: false,\n      dynamic: \"force-dynamic\",\n      directive,\n    };\n  }\n\n  if (mode === \"ppr\") {\n    return {\n      ssg: false,\n      ppr: true,\n      revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n      directive,\n    };\n  }\n\n  return {\n    ssg: true,\n    ppr: false,\n    dynamic: \"force-static\",\n    revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n    directive,\n  };\n}\n\nfunction normalizeDynamicMode(value: unknown): RouteRenderingDynamic | undefined {\n  switch (value) {\n    case \"auto\":\n    case \"force-static\":\n    case \"force-dynamic\":\n    case \"error\":\n      return value;\n    default:\n      return undefined;\n  }\n}\n\nfunction readDirectivePrologue(source: string): string[] {\n  const directives: string[] = [];\n  let index = skipTrivia(source, 0);\n\n  while (index < source.length) {\n    const parsed = readStringStatement(source, index);\n    if (!parsed) {\n      break;\n    }\n\n    directives.push(parsed.value);\n    index = skipTrivia(source, parsed.end);\n  }\n\n  return directives;\n}\n\nfunction skipTrivia(source: string, start: number): number {\n  let index = start;\n\n  while (index < source.length) {\n    const char = source[index];\n\n    if (char && /\\s/.test(char)) {\n      index += 1;\n      continue;\n    }\n\n    if (source.startsWith(\"//\", index)) {\n      const nextLine = source.indexOf(\"\\n\", index + 2);\n      index = nextLine === -1 ? source.length : nextLine + 1;\n      continue;\n    }\n\n    if (source.startsWith(\"/*\", index)) {\n      const end = source.indexOf(\"*/\", index + 2);\n      index = end === -1 ? source.length : end + 2;\n      continue;\n    }\n\n    break;\n  }\n\n  return index;\n}\n\nfunction readStringStatement(\n  source: string,\n  start: number,\n): { value: string; end: number } | undefined {\n  const quote = source[start];\n  if (quote !== '\"' && quote !== \"'\") {\n    return undefined;\n  }\n\n  let value = \"\";\n  let index = start + 1;\n\n  while (index < source.length) {\n    const char = source[index];\n    if (char === \"\\\\\") {\n      value += source.slice(index, index + 2);\n      index += 2;\n      continue;\n    }\n\n    if (char === quote) {\n      index += 1;\n      const semicolonIndex = skipHorizontalWhitespace(source, index);\n      const end = source[semicolonIndex] === \";\" ? semicolonIndex + 1 : index;\n      return { value, end };\n    }\n\n    value += char ?? \"\";\n    index += 1;\n  }\n\n  return undefined;\n}\n\nfunction skipHorizontalWhitespace(source: string, start: number): number {\n  let index = start;\n  while (source[index] === \" \" || source[index] === \"\\t\" || source[index] === \"\\r\") {\n    index += 1;\n  }\n  return index;\n}\n\n/**\n * Collect SSG pages from route modules\n *\n * Scans all routes and categorizes them into:\n * - SSG pages: Pre-rendered at build time\n * - SSR routes: Rendered on each request\n *\n * @param routes - Array of route entries\n * @param loadModule - Function to load a route module\n * @returns SSG pages and SSR routes\n */\nexport async function collectSSGPages(\n  routes: RouteEntry[],\n  loadModule: (filePath: string) => Promise<RouteModule>,\n  options: { suggestStaticRendering?: boolean } = {},\n): Promise<SSGCollectionResult> {\n  const ssgPages: SSGPage[] = [];\n  const ssrRoutes: string[] = [];\n  const staticCandidateRoutes: string[] = [];\n\n  for (const route of routes) {\n    try {\n      const mod = await loadModule(route.filePath);\n\n      if (!mod) {\n        ssrRoutes.push(route.path);\n        continue;\n      }\n\n      const source = await readFile(route.filePath, \"utf8\").catch(() => undefined);\n      const configuredRendering = resolveConfiguredRouteRenderingConfig(mod, source);\n      const rendering = resolveRouteRenderingConfig(mod, source);\n\n      if (configuredRendering.ssg && !rendering.ssg && source) {\n        const blockers = findRequestBoundSourceBlockers(source);\n        console.warn(\n          `[Farm.js] Static rendering disabled for \"${route.path}\" because ${blockers.join(\n            \" and \",\n          )}. Farm will render this route on each request instead.`,\n        );\n      }\n\n      // Check if page is marked for SSG\n      if (rendering.ssg) {\n        if (route.isDynamic) {\n          // Dynamic SSG route requires getStaticPaths\n          const getStaticPaths = mod.getStaticPaths || mod.generateStaticParams;\n\n          if (!getStaticPaths) {\n            throw new Error(\n              `Dynamic SSG route \"${route.path}\" requires getStaticPaths export. ` +\n                `Add: export function getStaticPaths() { return [{ paramName: 'value' }]; }`,\n            );\n          }\n\n          // Get all paths to pre-render\n          const paths = await getStaticPaths();\n\n          // Materialize every path before adding any of them. If one entry is\n          // invalid, the outer error handler can safely fall the whole route\n          // back to SSR without leaving a partial SSG manifest behind.\n          const materializedPages = paths.map((params) => ({\n            urlPath: materializeSSGRoutePath(route.path, params),\n            filePath: route.filePath,\n            params: normalizeStaticPathParams(params),\n            revalidate: rendering.revalidate,\n          }));\n\n          ssgPages.push(...materializedPages);\n        } else {\n          // Static SSG page\n          ssgPages.push({\n            urlPath: route.path,\n            filePath: route.filePath,\n            params: {},\n            revalidate: rendering.revalidate,\n          });\n        }\n      } else {\n        // SSR route (default)\n        ssrRoutes.push(route.path);\n\n        if (\n          options.suggestStaticRendering !== false &&\n          analyzeStaticRouteCandidate(mod, source, { isDynamic: route.isDynamic }).candidate\n        ) {\n          staticCandidateRoutes.push(route.path);\n        }\n      }\n    } catch (error) {\n      console.error(`Error processing route ${route.path}:`, error);\n      // Fall back to SSR for problematic routes\n      ssrRoutes.push(route.path);\n    }\n  }\n\n  if (staticCandidateRoutes.length > 0) {\n    const visibleRoutes = staticCandidateRoutes.slice(0, 10);\n    const remainingCount = staticCandidateRoutes.length - visibleRoutes.length;\n    const remainingSuffix = remainingCount > 0 ? `\\n  …and ${remainingCount} more` : \"\";\n\n    console.warn(\n      `[Farm.js] ${staticCandidateRoutes.length} route${\n        staticCandidateRoutes.length === 1 ? \" appears\" : \"s appear\"\n      } eligible for static rendering:\\n  ${visibleRoutes.join(\"\\n  \")}${remainingSuffix}\\n` +\n        `Add \\`export const dynamic = \"force-static\";\\` after verifying that imported code ` +\n        `does not read cookies, headers, authentication, or other request data.`,\n    );\n  }\n\n  return { ssg: ssgPages, ssr: ssrRoutes };\n}\n\nfunction materializeSSGRoutePath(routePattern: string, params: StaticPathParams): string {\n  const outputSegments: string[] = [];\n\n  for (const segment of routePattern.split(\"/\")) {\n    if (!segment) {\n      continue;\n    }\n\n    const optionalCatchAll = segment.match(OPTIONAL_CATCH_ALL_SEGMENT);\n    if (optionalCatchAll) {\n      const parameterName = optionalCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: true,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredCatchAll = segment.match(REQUIRED_CATCH_ALL_SEGMENT);\n    if (requiredCatchAll) {\n      const parameterName = requiredCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: false,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredDynamic = segment.match(REQUIRED_DYNAMIC_SEGMENT);\n    if (requiredDynamic) {\n      const parameterName = requiredDynamic[1]!;\n      const value = params[parameterName];\n      if (isStaticPathArray(value)) {\n        throw new Error(\n          `Cannot materialize SSG route \"${routePattern}\": parameter \"${parameterName}\" ` +\n            \"must be a scalar value; arrays are only supported for catch-all segments.\",\n        );\n      }\n      if (isMissingPathValue(value)) {\n        throw missingRequiredParameterError(routePattern, parameterName);\n      }\n      outputSegments.push(encodePathSegment(value));\n      continue;\n    }\n\n    outputSegments.push(segment);\n  }\n\n  return outputSegments.length > 0 ? `/${outputSegments.join(\"/\")}` : \"/\";\n}\n\nfunction readCatchAllSegments(\n  value: StaticPathParams[string] | undefined,\n  options: {\n    optional: boolean;\n    parameterName: string;\n    routePattern: string;\n  },\n): StaticPathPrimitive[] {\n  if (isMissingPathValue(value) || (isStaticPathArray(value) && value.length === 0)) {\n    if (options.optional) {\n      return [];\n    }\n    throw missingRequiredParameterError(options.routePattern, options.parameterName);\n  }\n\n  const segments = isStaticPathArray(value) ? [...value] : [value as StaticPathPrimitive];\n  if (segments.some(isMissingPathValue)) {\n    throw new Error(\n      `Cannot materialize SSG route \"${options.routePattern}\": catch-all parameter ` +\n        `\"${options.parameterName}\" contains an empty path segment.`,\n    );\n  }\n\n  return segments;\n}\n\nfunction normalizeStaticPathParams(params: StaticPathParams): Record<string, string> {\n  return Object.fromEntries(\n    Object.entries(params).map(([key, value]) => [\n      key,\n      isStaticPathArray(value) ? value.map(String).join(\"/\") : String(value),\n    ]),\n  );\n}\n\nfunction isMissingPathValue(value: unknown): value is \"\" | null | undefined {\n  return value === \"\" || value === null || typeof value === \"undefined\";\n}\n\nfunction isStaticPathArray(\n  value: StaticPathParams[string] | undefined,\n): value is readonly StaticPathPrimitive[] {\n  return Array.isArray(value);\n}\n\nfunction missingRequiredParameterError(routePattern: string, parameterName: string): Error {\n  return new Error(\n    `Cannot materialize SSG route \"${routePattern}\": required parameter ` +\n      `\"${parameterName}\" is missing or empty.`,\n  );\n}\n\nfunction encodePathSegment(value: StaticPathPrimitive): string {\n  const encoded = encodeURIComponent(String(value)).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n\n  // Dot-only URL segments are normalized as navigation by URL parsers and\n  // filesystem joins. Pre-rendering them could therefore escape the intended\n  // route directory or overwrite a parent artifact. They cannot faithfully be\n  // represented as a static URL segment, so keep the route server-rendered.\n  if (encoded === \".\" || encoded === \"..\") {\n    throw new Error(\n      `Cannot materialize SSG path segment \"${encoded}\": dot-only segments are unsafe to prerender.`,\n    );\n  }\n\n  return encoded;\n}\n\n/**\n * Check if a route module is SSG\n */\nexport function isSSGModule(mod: RouteModule | null | undefined): boolean {\n  return resolveRouteRenderingConfig(mod).ssg;\n}\n\n/**\n * Check if a route module has ISR (Incremental Static Regeneration)\n */\nexport function hasISR(mod: RouteModule | null | undefined): boolean {\n  const rendering = resolveRouteRenderingConfig(mod);\n  return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n}\n\n/**\n * Get revalidation interval for a module\n */\nexport function getRevalidateInterval(mod: RouteModule | null | undefined): number | undefined {\n  return resolveRouteRenderingConfig(mod).revalidate;\n}\n\n/**\n * Check if a route module has PPR/static-shell caching enabled.\n */\nexport function hasPPR(\n  mod: RouteModule | null | undefined,\n  options?: RouteRenderingOptions,\n): boolean {\n  return resolveRouteRenderingConfig(mod, undefined, options).ppr;\n}\n\n/**\n * Generate SSG manifest for production builds\n */\nexport function generateSSGManifest(pages: SSGPage[]): string {\n  return JSON.stringify(\n    pages.map((page) => ({\n      urlPath: page.urlPath,\n      params: page.params,\n      revalidate: page.revalidate,\n    })),\n    null,\n    2,\n  );\n}\n\n/**\n * Check if a URL path matches an SSG page\n */\nexport function matchSSGPage(urlPath: string, ssgPages: SSGPage[]): SSGPage | undefined {\n  const normalizedPath = urlPath === \"/\" ? \"/\" : urlPath.replace(/\\/$/, \"\");\n  return ssgPages.find((page) => page.urlPath === normalizedPath);\n}\n","import type {\n  FarmConfig,\n  ParsedRoute,\n  RouteModule,\n  LayoutModule,\n  SSGCollectionResult,\n} from \"../types\";\nimport {\n  parseRoutePath,\n  matchRoute,\n  matchRoutePrefix,\n  resolveAppPath,\n  globFiles,\n  logger,\n  toRootRelativeUrlPath,\n  toViteModuleId,\n} from \"../utils\";\nimport { collectSSGPages, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport type {\n  ProgrammaticPageRoute,\n  ProgrammaticLayoutRoute,\n  ProgrammaticRedirectRoute,\n  ProgrammaticRouteSearchClientOptions,\n} from \"../routes\";\nimport {\n  createProgrammaticRouteModuleId,\n  getProgrammaticRouteSearchClientOptions,\n  parseProgrammaticRoutePath,\n} from \"../routes-shared\";\nimport { loadProgrammaticRouteManifests } from \"../routes.server\";\nimport {\n  createFarmMarkdownRouteModuleFromFile,\n  isFarmMarkdownPageFile,\n  loadFarmMdxComponents,\n  resolveMdxConfig,\n} from \"../app-markdown\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  resolveFarmIsolatedClientHydrationMode,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport { getIntegrationProviders } from \"../integrations\";\nimport type { MetadataImageKind } from \"../metadata\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport type { FarmServerRendererRuntime } from \"../renderer\";\nimport { createFarmRouteRenderPlan, type FarmRouteRenderPlan } from \"../navigation/render-plan\";\nimport { getFarmSourceRoots, type FarmSourceRoot } from \"../layers\";\nimport {\n  inspectStaticMetadataImage,\n  isStaticMetadataImageFile,\n  type StaticMetadataImageInfo,\n} from \"../static-metadata-image\";\nimport {\n  getFarmRouteRuntimeConfig,\n  mergeFarmRouteRuntimeConfigs,\n  normalizeFarmRouteRuntimeConfig,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport {\n  localizeFarmHref,\n  localizeFarmPathname,\n  resolveFarmLocalePath,\n  stripFarmLocaleFromPathname,\n} from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { appendFarmRedirectQuery } from \"../redirect-query\";\nimport { createRouteSlotContainerId, parseRouteSlotFile } from \"./route-slots\";\nimport { getFarmRendererComponentExtensions } from \"../renderer\";\nimport type { ApplicationMetadataRouteKind } from \"../metadata-route\";\nimport {\n  AmbiguousRouteError,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternShape,\n  type RouteSegmentSpecificity,\n} from \"./specificity\";\n\ninterface RouteEntry {\n  route: ParsedRoute;\n  modulePath: string;\n  markdownSourcePath?: string;\n  pattern: string;\n  source?: \"file\" | \"programmatic\";\n  sourceRoot: string;\n}\n\nexport interface RouteSlotEntry extends RouteEntry {\n  name: string;\n  ownerPattern: string;\n  interception: boolean;\n  fallback: boolean;\n  containerId: string;\n}\n\nexport interface MatchedRouteSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n  route: RouteSlotEntry;\n  params: Record<string, string>;\n}\n\nexport interface FarmClientRouteManifest {\n  routes: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n    renderPlan: FarmRouteRenderPlan;\n    suppressedAsyncHydration?: true;\n    search?: ProgrammaticRouteSearchClientOptions;\n    segments: Array<{\n      segment: string;\n      isDynamic: boolean;\n      isCatchAll?: boolean;\n      isOptional?: boolean;\n    }>;\n  }>;\n  layouts: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n  }>;\n  slots: Array<{\n    name: string;\n    ownerPattern: string;\n    pattern: string;\n    modulePath: string;\n    containerId: string;\n    interception: boolean;\n    fallback: boolean;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    segments: RouteEntry[\"route\"][\"segments\"];\n  }>;\n}\n\nexport function shouldSuggestStaticRenderingForI18n(\n  i18n: Pick<ResolvedFarmI18nConfig, \"routing\" | \"detection\"> | undefined,\n): boolean {\n  return (\n    !i18n ||\n    i18n.routing === \"prefix-always\" ||\n    (i18n.routing === \"prefix-except-default\" && i18n.detection.every((signal) => signal === \"url\"))\n  );\n}\n\ninterface MetadataImageEntry extends RouteEntry {\n  kind: MetadataImageKind;\n  fileName: \"opengraph-image\" | \"twitter-image\";\n  sourceType: \"module\" | \"static\";\n  staticInfo?: StaticMetadataImageInfo;\n}\n\nexport interface ApplicationMetadataRouteEntry extends RouteEntry {\n  kind: ApplicationMetadataRouteKind;\n  fileName: \"sitemap\" | \"robots\" | \"manifest\";\n  outputName: \"sitemap.xml\" | \"robots.txt\" | \"manifest.webmanifest\";\n}\n\ninterface RedirectEntry {\n  route: ParsedRoute;\n  pattern: string;\n  definition: ProgrammaticRedirectRoute;\n}\n\nfunction getRouteSpecificity(entry: RouteEntry): RouteSegmentSpecificity[] {\n  return entry.route.segments.map((segment) => {\n    if (!segment.isDynamic) return \"static\";\n    if (!segment.isCatchAll) return \"dynamic\";\n    return segment.isOptional ? \"optional-catch-all\" : \"catch-all\";\n  });\n}\n\nfunction compareRouteEntries(left: RouteEntry, right: RouteEntry): number {\n  return compareRouteSpecificity(getRouteSpecificity(left), getRouteSpecificity(right));\n}\n\n/**\n * Manages route discovery and matching for the Farm.js application\n */\nexport class RouteManager {\n  private config: Required<FarmConfig>;\n  private routes: Map<string, RouteEntry> = new Map();\n  private pageRouteShapes: Map<string, RouteEntry> = new Map();\n  private layouts: Map<string, RouteEntry> = new Map();\n  private routeSlots: Map<string, RouteSlotEntry> = new Map();\n  private loadings: Map<string, RouteEntry> = new Map();\n  private errors: Map<string, RouteEntry> = new Map();\n  private metadataImages: Map<string, MetadataImageEntry> = new Map();\n  private metadataRoutes: Map<string, ApplicationMetadataRouteEntry> = new Map();\n  private redirects: Map<string, RedirectEntry> = new Map();\n  private programmaticPages: Map<string, ProgrammaticPageRoute> = new Map();\n  private programmaticLayouts: Map<string, ProgrammaticLayoutRoute> = new Map();\n  private rendererRuntime?: FarmServerRendererRuntime;\n  private viteServer?: ViteDevServer;\n  private clientManifestCache?: {\n    projectRoot: string;\n    manifest: FarmClientRouteManifest;\n    isolatedClientBoundaryModules: ReadonlySet<string>;\n  };\n\n  constructor(config: Required<FarmConfig>, viteServer?: ViteDevServer) {\n    this.config = config;\n    this.viteServer = viteServer;\n  }\n\n  setRendererRuntime(rendererRuntime: FarmServerRendererRuntime): void {\n    this.rendererRuntime = rendererRuntime;\n  }\n\n  /**\n   * Discover all routes in the app directory\n   */\n  async discoverRoutes(): Promise<void> {\n    this.invalidateClientManifest();\n    this.routes.clear();\n    this.pageRouteShapes.clear();\n    this.layouts.clear();\n    this.routeSlots.clear();\n    this.loadings.clear();\n    this.errors.clear();\n    this.metadataImages.clear();\n    this.metadataRoutes.clear();\n    this.redirects.clear();\n    this.programmaticPages.clear();\n    this.programmaticLayouts.clear();\n\n    for (const source of getFarmSourceRoots(this.config)) {\n      await this.discoverFileRoutes(source);\n      await this.discoverProgrammaticRoutes(source);\n    }\n\n    for (const slot of this.routeSlots.values()) {\n      if (slot.interception && !this.pageRouteShapes.has(getRoutePatternShape(slot.pattern))) {\n        throw new AmbiguousRouteError(\n          `Intercepting route slot \"${slot.name}\" targets \"${slot.pattern}\", but no canonical page exists for that URL`,\n        );\n      }\n    }\n\n    this.routes = new Map(\n      Array.from(this.routes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n    this.metadataRoutes = new Map(\n      Array.from(this.metadataRoutes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n\n    // Silent discovery - only log if verbose mode enabled\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\n        `Discovered ${this.routes.size} pages, ${this.layouts.size} layouts, and ${this.metadataRoutes.size} metadata routes`,\n      );\n    }\n\n    if (process.env.FARM_VERBOSE) {\n      this.logRoutes();\n    }\n  }\n\n  /**\n   * Find matching route for a given URL path\n   */\n  matchRoute(\n    pathname: string,\n    options: {\n      interceptFrom?: string;\n    } = {},\n  ): {\n    route: RouteEntry | null;\n    params: Record<string, string>;\n    layouts: RouteEntry[];\n    slots: MatchedRouteSlot[];\n  } {\n    // Remove trailing slash except for root\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    // Find matching page route\n    let matchedRoute: RouteEntry | null = null;\n    let params: Record<string, string> = {};\n\n    for (const routeEntry of this.routes.values()) {\n      const match = matchRoute(normalizedPath, routeEntry.route.segments);\n      if (match.matches) {\n        matchedRoute = routeEntry;\n        params = match.params;\n        break;\n      }\n    }\n\n    // Find all matching layouts (from root to specific)\n    const layouts = this.findMatchingLayouts(normalizedPath);\n    const slots = this.findMatchingRouteSlots(normalizedPath, options.interceptFrom);\n\n    return {\n      route: matchedRoute,\n      params,\n      layouts,\n      slots,\n    };\n  }\n\n  /**\n   * Get all registered routes\n   */\n  getRoutes(): Map<string, RouteEntry> {\n    return new Map(this.routes);\n  }\n\n  /**\n   * Get all registered layouts\n   */\n  getLayouts(): Map<string, RouteEntry> {\n    return new Map(this.layouts);\n  }\n\n  getRouteSlots(): Map<string, RouteSlotEntry> {\n    return new Map(this.routeSlots);\n  }\n\n  /** Resolve route rules, inherited layouts, and the page export in precedence order. */\n  async resolveRouteRuntimeConfig(pattern: string): Promise<ResolvedFarmRouteRuntimeConfig> {\n    const routeEntry = this.routes.get(pattern);\n    if (!routeEntry) {\n      throw new Error(`Cannot resolve runtime configuration for unknown route \"${pattern}\"`);\n    }\n\n    const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, this.config.routeRules);\n    const layouts = this.findMatchingLayouts(pattern);\n    const layoutConfigs = [];\n\n    for (const layout of layouts) {\n      const layoutModule = await this.loadLayoutModule(layout.modulePath);\n      layoutConfigs.push(\n        normalizeFarmRouteRuntimeConfig(\n          getFarmRouteRuntimeConfig(layoutModule),\n          `Layout \"${layout.pattern}\"`,\n        ),\n      );\n    }\n\n    const routeModule = await this.loadRouteModule(routeEntry.modulePath);\n    const routeConfig = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(routeModule),\n      `Route \"${pattern}\"`,\n    );\n\n    return resolveFarmRouteRuntimeConfig(\n      mergeFarmRouteRuntimeConfigs(inherited, ...layoutConfigs, routeConfig),\n      `Route \"${pattern}\"`,\n    );\n  }\n\n  /**\n   * Get all route-level loading boundaries.\n   */\n  getLoadings(): Map<string, RouteEntry> {\n    return new Map(this.loadings);\n  }\n\n  /**\n   * Get all route-level error boundaries.\n   */\n  getErrors(): Map<string, RouteEntry> {\n    return new Map(this.errors);\n  }\n\n  getMetadataImages(): Map<string, MetadataImageEntry> {\n    return new Map(this.metadataImages);\n  }\n\n  getMetadataRoutes(): Map<string, ApplicationMetadataRouteEntry> {\n    return new Map(this.metadataRoutes);\n  }\n\n  getRedirects(): ProgrammaticRedirectRoute[] {\n    return Array.from(this.redirects.values()).map((entry) => entry.definition);\n  }\n\n  matchRedirect(\n    pathname: string,\n    search = \"\",\n  ): {\n    redirect: ProgrammaticRedirectRoute;\n    destination: string;\n    statusCode: number;\n    params: Record<string, string>;\n  } | null {\n    const i18n = this.getI18nConfig();\n    const localeMatch = i18n ? resolveFarmLocalePath(pathname, i18n) : undefined;\n    const routePathname = localeMatch?.pathname || pathname;\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n\n    for (const redirectEntry of this.redirects.values()) {\n      const match = matchRoute(normalizedPath, redirectEntry.route.segments);\n      if (!match.matches) continue;\n\n      const statusCode =\n        redirectEntry.definition.statusCode || (redirectEntry.definition.permanent ? 308 : 307);\n\n      return {\n        redirect: redirectEntry.definition,\n        destination: appendFarmRedirectQuery(\n          this.localizeRedirectDestination(\n            interpolateRedirectDestination(redirectEntry.definition.destination, match.params),\n            localeMatch?.locale,\n          ),\n          search,\n        ),\n        statusCode,\n        params: match.params,\n      };\n    }\n\n    return null;\n  }\n\n  /**\n   * Return the nearest matching loading boundary for a pathname.\n   */\n  getMatchingLoading(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.loadings);\n  }\n\n  /**\n   * Return the nearest matching error boundary for a pathname.\n   */\n  getMatchingError(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.errors);\n  }\n\n  matchMetadataImage(pathname: string): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n    pagePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getMetadataImageSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const pagePath = normalizedPath.slice(0, -suffix.fileName.length - 1) || \"/\";\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== suffix.kind) continue;\n\n      const match = matchRoute(pagePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      return {\n        image: imageEntry,\n        params: match.params,\n        pagePath,\n      };\n    }\n\n    return null;\n  }\n\n  matchMetadataRoute(pathname: string): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getApplicationMetadataRouteSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const routePath = normalizedPath.slice(0, -suffix.outputName.length - 1) || \"/\";\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== suffix.kind) continue;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      return { metadata, params: match.params, routePath };\n    }\n\n    return null;\n  }\n\n  getMatchingMetadataRoute(\n    pathname: string,\n    kind: ApplicationMetadataRouteKind,\n  ): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      metadata: ApplicationMetadataRouteEntry;\n      params: Record<string, string>;\n      routePath: string;\n    } | null = null;\n\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== kind || metadata.route.segments.length > pathSegments.length) continue;\n      const routePath =\n        metadata.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, metadata.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      if (!bestMatch || metadata.route.segments.length > bestMatch.metadata.route.segments.length) {\n        bestMatch = { metadata, params: match.params, routePath };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataRoutePath(\n    metadata: ApplicationMetadataRouteEntry,\n    params: Record<string, string> = {},\n  ): string {\n    const routePath = routeSegmentsToPath(metadata.route.segments, params);\n    return routePath === \"/\" ? `/${metadata.outputName}` : `${routePath}/${metadata.outputName}`;\n  }\n\n  getMatchingMetadataImage(\n    pathname: string,\n    kind: MetadataImageKind,\n  ): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      image: MetadataImageEntry;\n      params: Record<string, string>;\n    } | null = null;\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== kind) continue;\n      if (imageEntry.route.segments.length > pathSegments.length) continue;\n\n      const candidatePath =\n        imageEntry.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, imageEntry.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(candidatePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      if (!bestMatch || imageEntry.route.segments.length > bestMatch.image.route.segments.length) {\n        bestMatch = {\n          image: imageEntry,\n          params: match.params,\n        };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataImagePath(image: MetadataImageEntry, params: Record<string, string> = {}): string {\n    const pagePath = routeSegmentsToPath(image.route.segments, params);\n    const imagePath = pagePath === \"/\" ? `/${image.fileName}` : `${pagePath}/${image.fileName}`;\n    return image.staticInfo ? `${imagePath}?v=${image.staticInfo.hash}` : imagePath;\n  }\n\n  /**\n   * Generate the compiled route decisions consumed by SPA navigation.\n   * Requests still fetch route data, but never inspect component source.\n   */\n  generateClientManifest(projectRoot: string = this.config.root): FarmClientRouteManifest {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    if (this.clientManifestCache?.projectRoot === normalizedProjectRoot) {\n      return this.clientManifestCache.manifest;\n    }\n\n    const toUrlPath = (absolutePath: string) => {\n      const rootRelative = toRootRelativeUrlPath(absolutePath, normalizedProjectRoot);\n      if (rootRelative !== undefined) return rootRelative;\n      if (path.isAbsolute(absolutePath)) {\n        const normalized = absolutePath.replace(/\\\\/g, \"/\");\n        return normalized.startsWith(\"/\") ? `/@fs${normalized}` : `/@fs/${normalized}`;\n      }\n      return absolutePath;\n    };\n\n    const integrationProviders = getIntegrationProviders(this.config.integrations).filter(\n      (provider) => provider.component || provider.type === \"clerk\",\n    );\n    const unsupportedIntegrationProvider = integrationProviders.find(\n      (provider) => provider.supportsIsolatedHydration !== true,\n    );\n    if (\n      this.config.experimental?.isolatedClientHydration === \"enabled\" &&\n      this.config.experimental?.serverComponents !== true &&\n      unsupportedIntegrationProvider\n    ) {\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide because integration provider \"${unsupportedIntegrationProvider.name}\" does not declare supportsIsolatedHydration: true.`,\n      );\n    }\n    const isolatedMode = resolveFarmIsolatedClientHydrationMode(\n      this.config.experimental?.isolatedClientHydration,\n      {\n        serverComponents: this.config.experimental?.serverComponents === true,\n        hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n      },\n    );\n    const layoutEntries = Array.from(this.layouts.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    const routeEntries = Array.from(this.routes.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    enforceFarmIsolatedHydrationRouteBudget(\n      layoutEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      routeEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      (layoutPattern, routePattern) =>\n        layoutPattern === \"/\" ||\n        routePattern === layoutPattern ||\n        routePattern.startsWith(`${layoutPattern.replace(/\\/$/, \"\")}/`),\n    );\n\n    for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.costGuardExceeded) continue;\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide for ${entry.modulePath}: ${metadata.fallbackReason}.`,\n      );\n    }\n    if (isolatedMode === \"analyze\") {\n      for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n        if (!metadata.isolatedHydrationEligible) continue;\n        logger.info(\n          `[Farm.js] isolated hydration analysis: ${entry.modulePath} can keep ${metadata.isolatedBoundaries.length} client ${metadata.isolatedBoundaries.length === 1 ? \"boundary\" : \"boundaries\"} while excluding its server owner from the browser graph.`,\n        );\n      }\n    }\n\n    const routes = routeEntries.map(({ entry, metadata }) => {\n      const programmaticPage = this.programmaticPages.get(entry.modulePath);\n      const layoutShouldHydrate = layoutEntries.some(\n        ({ entry: layout, metadata: layoutMetadata }) =>\n          layoutMetadata.shouldHydrate &&\n          (layout.pattern === \"/\" ||\n            entry.pattern === layout.pattern ||\n            entry.pattern.startsWith(`${layout.pattern.replace(/\\/$/, \"\")}/`)),\n      );\n      return {\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        islandStrategy: metadata.islandStrategy,\n        ...(metadata.hasIsolatedClientBoundaries\n          ? {\n              hasIsolatedClientBoundaries: true as const,\n              isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n                ...boundary,\n                modulePath: toUrlPath(boundary.modulePath),\n              })),\n            }\n          : {}),\n        renderPlan: createFarmRouteRenderPlan({\n          pageShouldHydrate: metadata.shouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: metadata.islandStrategy,\n        }),\n        suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n        search: getProgrammaticRouteSearchClientOptions(programmaticPage?.search),\n        segments: entry.route.segments.map((seg) => ({\n          segment: seg.segment,\n          isDynamic: seg.isDynamic,\n          isCatchAll: seg.isCatchAll,\n          isOptional: seg.isOptional,\n        })),\n      };\n    });\n\n    const layouts = layoutEntries.map(({ entry, metadata }) => ({\n      pattern: entry.pattern,\n      modulePath: toUrlPath(entry.modulePath),\n      shouldHydrate: metadata.shouldHydrate,\n      isClientComponent: metadata.isClientComponent,\n      islandStrategy: metadata.islandStrategy,\n      ...(metadata.hasIsolatedClientBoundaries\n        ? {\n            hasIsolatedClientBoundaries: true as const,\n            isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n              ...boundary,\n              modulePath: toUrlPath(boundary.modulePath),\n            })),\n          }\n        : {}),\n    }));\n\n    const slots = Array.from(this.routeSlots.values()).map((entry) => {\n      const metadata = getClientModuleMetadata(entry.modulePath, normalizedProjectRoot);\n      return {\n        name: entry.name,\n        ownerPattern: entry.ownerPattern,\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        containerId: entry.containerId,\n        interception: entry.interception,\n        fallback: entry.fallback,\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        segments: entry.route.segments,\n      };\n    });\n\n    const isolatedClientBoundaryModules = new Set<string>();\n    for (const { metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.hasIsolatedClientBoundaries) continue;\n      for (const boundary of metadata.isolatedBoundaries) {\n        isolatedClientBoundaryModules.add(path.resolve(boundary.modulePath));\n      }\n    }\n\n    const manifest = { routes, layouts, slots };\n    this.clientManifestCache = {\n      projectRoot: normalizedProjectRoot,\n      manifest,\n      isolatedClientBoundaryModules,\n    };\n    return manifest;\n  }\n\n  /** @internal Client modules selected by the compiled hydration ownership plan. */\n  getIsolatedClientBoundaryModules(projectRoot: string = this.config.root): ReadonlySet<string> {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    this.generateClientManifest(normalizedProjectRoot);\n    return this.clientManifestCache?.isolatedClientBoundaryModules ?? new Set();\n  }\n\n  /**\n   * Invalidate build-time route metadata after a page or layout changes in dev.\n   * Navigation requests reuse the cached manifest and never inspect source files.\n   */\n  invalidateClientManifest(): void {\n    this.clientManifestCache = undefined;\n  }\n\n  /**\n   * Load a route module dynamically\n   */\n  async loadRouteModule(modulePath: string): Promise<RouteModule> {\n    try {\n      const programmaticPage = this.programmaticPages.get(modulePath);\n      if (programmaticPage) {\n        const { createRouteModuleFromProgrammaticPage } = await import(\"../routes\");\n        return createRouteModuleFromProgrammaticPage(programmaticPage, this.rendererRuntime);\n      }\n\n      if (isFarmMarkdownPageFile(modulePath)) {\n        const mdxConfig = resolveMdxConfig(this.config.mdx);\n        const components = await loadFarmMdxComponents(mdxConfig, {\n          root: this.config.root,\n          loadModule: this.viteServer\n            ? (componentModulePath) => this.viteServer!.ssrLoadModule(componentModulePath)\n            : undefined,\n        });\n        return await createFarmMarkdownRouteModuleFromFile(modulePath, {\n          components,\n          config: mdxConfig,\n        });\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as RouteModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as RouteModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load route module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Load a layout module dynamically\n   */\n  async loadLayoutModule(modulePath: string): Promise<LayoutModule> {\n    try {\n      const programmaticLayout = this.programmaticLayouts.get(modulePath);\n      if (programmaticLayout) {\n        const { createLayoutModuleFromProgrammaticLayout } = await import(\"../routes\");\n        return createLayoutModuleFromProgrammaticLayout(programmaticLayout) as LayoutModule;\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as LayoutModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as LayoutModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load layout module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Create a route pattern from parsed route\n   */\n  private createRoutePattern(route: ParsedRoute): string {\n    if (route.segments.length === 0) return \"/\";\n\n    return (\n      \"/\" +\n      route.segments\n        .map((segment) => {\n          if (!segment.isDynamic) return segment.segment;\n\n          if (segment.isCatchAll) {\n            return segment.isOptional ? `[[...${segment.segment}]]` : `[...${segment.segment}]`;\n          }\n\n          return `[${segment.segment}]`;\n        })\n        .join(\"/\")\n    );\n  }\n\n  private registerPageRoute(entry: RouteEntry): void {\n    assertUniqueRouteParameters(entry.pattern);\n    const shape = getRoutePatternShape(entry.pattern);\n    const existing = this.pageRouteShapes.get(shape);\n\n    if (existing && existing.pattern !== entry.pattern) {\n      if (existing.sourceRoot === entry.sourceRoot) {\n        throw new Error(\n          `Ambiguous page routes \"${existing.pattern}\" and \"${entry.pattern}\" match the same URLs. Found ${existing.modulePath} and ${entry.modulePath}. Keep only one route for this URL shape.`,\n        );\n      }\n      this.routes.delete(existing.pattern);\n    }\n\n    this.routes.set(entry.pattern, entry);\n    this.pageRouteShapes.set(shape, entry);\n  }\n\n  private async discoverFileRoutes(source: FarmSourceRoot): Promise<void> {\n    const appDir = resolveAppPath(source.root, source.srcDir, \"app\");\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer).map(\n      (extension) => extension.slice(1),\n    );\n    const componentGlob = componentExtensions.join(\",\");\n    const pageFiles = await safeGlobFiles(`**/page.{${componentGlob},md,mdx}`, appDir);\n    const slotDefaultFiles = await safeGlobFiles(`**/@*/**/default.{${componentGlob}}`, appDir);\n    const layoutFiles = await safeGlobFiles(`**/layout.{${componentGlob}}`, appDir);\n    const loadingFiles = await safeGlobFiles(`**/loading.{${componentGlob}}`, appDir);\n    const errorFiles = await safeGlobFiles(`**/error.{${componentGlob}}`, appDir);\n    const metadataImageFiles = await safeGlobFiles(\n      `**/{opengraph-image,twitter-image}.{${componentGlob},png,jpg,jpeg,gif,webp}`,\n      appDir,\n    );\n    const metadataRouteFiles = await safeGlobFiles(\"**/{sitemap,robots,manifest}.{ts,js}\", appDir);\n\n    const canonicalPageGroups = new Map<\n      string,\n      {\n        route: ParsedRoute;\n        files: string[];\n      }\n    >();\n    for (const file of pageFiles.filter((candidate) => parseRouteSlotFile(candidate) === null)) {\n      const route = parseRoutePath(file);\n      const pattern = this.createRoutePattern(route);\n      const group = canonicalPageGroups.get(pattern);\n      if (group) {\n        group.files.push(file);\n      } else {\n        canonicalPageGroups.set(pattern, {\n          route,\n          files: [file],\n        });\n      }\n    }\n\n    for (const [pattern, group] of canonicalPageGroups) {\n      const componentFiles = group.files.filter((file) => !isFarmMarkdownPageFile(file));\n      const markdownFiles = group.files.filter(isFarmMarkdownPageFile);\n      if (componentFiles.length > 1) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found ${componentFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n      if (markdownFiles.length > 1) {\n        throw new Error(\n          `Duplicate markdown representation for page route \"${pattern}\". Found ${markdownFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n\n      const componentFile = componentFiles[0];\n      const markdownFile = markdownFiles[0];\n      const primaryFile = componentFile || markdownFile;\n      if (!primaryFile) continue;\n\n      const modulePath = path.join(appDir, primaryFile);\n      const existing = this.routes.get(pattern);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n      this.registerPageRoute({\n        route: group.route,\n        modulePath,\n        ...(markdownFile\n          ? {\n              markdownSourcePath: path.join(appDir, markdownFile),\n            }\n          : {}),\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const [kind, files, target] of [\n      [\"layout\", layoutFiles, this.layouts],\n      [\"loading\", loadingFiles, this.loadings],\n      [\"error\", errorFiles, this.errors],\n    ] as const) {\n      for (const file of files) {\n        const route = parseRoutePath(file);\n        const modulePath = path.join(appDir, file);\n        const pattern = this.createRoutePattern(route);\n        const existing = target.get(pattern);\n        if (existing?.sourceRoot === source.root) {\n          throw new Error(\n            `Duplicate ${kind} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n          );\n        }\n        target.set(pattern, {\n          route,\n          modulePath,\n          pattern,\n          source: \"file\",\n          sourceRoot: source.root,\n        });\n      }\n    }\n\n    for (const file of [...pageFiles, ...slotDefaultFiles]) {\n      const slot = parseRouteSlotFile(file);\n      if (!slot) continue;\n\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(slot.route);\n      const ownerPattern = this.createRoutePattern(slot.ownerRoute);\n      const key = `${ownerPattern}:${slot.name}:${slot.interception ? \"intercept\" : \"slot\"}:${\n        slot.fallback ? \"default\" : pattern\n      }`;\n      const existing = this.routeSlots.get(key);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate route slot \"${slot.name}\" for \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n\n      this.routeSlots.set(key, {\n        route: slot.route,\n        modulePath,\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n        name: slot.name,\n        ownerPattern,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        containerId: createRouteSlotContainerId(slot.name, ownerPattern),\n      });\n    }\n\n    for (const file of metadataImageFiles) {\n      const fileBase = path.basename(file, path.extname(file));\n      const kind: MetadataImageKind = fileBase === \"twitter-image\" ? \"twitter\" : \"opengraph\";\n      const fileName = kind === \"twitter\" ? \"twitter-image\" : \"opengraph-image\";\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${kind}:${pattern}`;\n      const existing = this.metadataImages.get(key);\n      const sourceType = isStaticMetadataImageFile(file) ? \"static\" : \"module\";\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one static image or module per route segment.`,\n        );\n      }\n\n      const staticInfo =\n        sourceType === \"static\" ? await inspectStaticMetadataImage(modulePath) : undefined;\n\n      this.metadataImages.set(key, {\n        route,\n        modulePath,\n        pattern,\n        kind,\n        fileName,\n        sourceType,\n        staticInfo,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const file of metadataRouteFiles) {\n      const descriptor = getApplicationMetadataRouteDescriptor(\n        path.basename(file, path.extname(file)),\n      );\n      if (!descriptor) continue;\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${descriptor.kind}:${pattern}`;\n      const existing = this.metadataRoutes.get(key);\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${descriptor.fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one .ts or .js metadata route per segment.`,\n        );\n      }\n\n      this.metadataRoutes.set(key, {\n        route,\n        modulePath,\n        pattern,\n        ...descriptor,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n  }\n\n  private async discoverProgrammaticRoutes(source: FarmSourceRoot): Promise<void> {\n    const manifests = await loadProgrammaticRouteManifests({\n      root: source.root,\n      srcDir: source.srcDir,\n      loadModule: (filePath) => this.loadProgrammaticRoutesModule(filePath),\n    });\n\n    for (const { filePath, manifest } of manifests) {\n      for (const definition of manifest.routes) {\n        if (definition.kind === \"page\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"page\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.routes.get(pattern);\n\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"page\", definition.path);\n          this.programmaticPages.set(modulePath, definition);\n          this.registerPageRoute({\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"layout\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"layout\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.layouts.get(pattern);\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate layout route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"layout\", definition.path);\n          this.programmaticLayouts.set(modulePath, definition);\n          this.layouts.set(pattern, {\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"redirect\") {\n          const route = parseProgrammaticRoutePath(definition.source, \"page\");\n          const pattern = this.createRoutePattern(route);\n          this.redirects.set(pattern, {\n            route,\n            pattern,\n            definition,\n          });\n        }\n      }\n    }\n  }\n\n  private async loadProgrammaticRoutesModule(filePath: string): Promise<Record<string, any>> {\n    if (this.viteServer) {\n      const viteRoot = this.viteServer.config?.root || this.config.root || process.cwd();\n      return await this.viteServer.ssrLoadModule(toViteModuleId(filePath, viteRoot));\n    }\n\n    const fileUrl = `file://${filePath}`;\n    return await import(/* @vite-ignore */ fileUrl);\n  }\n\n  /**\n   * Find all layouts that should wrap a given path\n   */\n  private findMatchingLayouts(pathname: string): RouteEntry[] {\n    const matchingLayouts: RouteEntry[] = [];\n\n    const sortedLayouts = Array.from(this.layouts.values()).sort((a, b) => {\n      return a.route.segments.length - b.route.segments.length;\n    });\n\n    for (const layoutEntry of sortedLayouts) {\n      if (matchRoutePrefix(pathname, layoutEntry.route.segments)) {\n        matchingLayouts.push(layoutEntry);\n      }\n    }\n\n    return matchingLayouts;\n  }\n\n  private findMatchingRouteSlots(pathname: string, interceptFrom?: string): MatchedRouteSlot[] {\n    const groups = new Map<string, RouteSlotEntry[]>();\n    for (const entry of this.routeSlots.values()) {\n      if (!this.matchesRoutePrefix(pathname, entry.ownerPattern)) continue;\n      const key = `${entry.ownerPattern}:${entry.name}`;\n      const entries = groups.get(key) ?? [];\n      entries.push(entry);\n      groups.set(key, entries);\n    }\n\n    const normalizedFrom = interceptFrom\n      ? this.toRoutePathname(new URL(interceptFrom, \"http://farm.local\").pathname)\n      : undefined;\n    const matches: MatchedRouteSlot[] = [];\n\n    for (const entries of groups.values()) {\n      const candidates = entries\n        .filter((entry) => !entry.fallback)\n        .filter(\n          (entry) =>\n            !entry.interception ||\n            (normalizedFrom !== undefined &&\n              this.matchesRoutePrefix(normalizedFrom, entry.ownerPattern)),\n        )\n        .map((entry) => ({\n          entry,\n          match: matchRoute(pathname, entry.route.segments),\n        }))\n        .filter((candidate) => candidate.match.matches)\n        .sort((left, right) => {\n          if (left.entry.interception !== right.entry.interception) {\n            return left.entry.interception ? -1 : 1;\n          }\n          return compareRouteEntries(left.entry, right.entry);\n        });\n\n      const selected = candidates[0];\n      if (selected) {\n        matches.push({\n          name: selected.entry.name,\n          ownerPattern: selected.entry.ownerPattern,\n          containerId: selected.entry.containerId,\n          interception: selected.entry.interception,\n          fallback: false,\n          route: selected.entry,\n          params: selected.match.params,\n        });\n        continue;\n      }\n\n      const fallback = entries.find((entry) => entry.fallback);\n      if (fallback) {\n        matches.push({\n          name: fallback.name,\n          ownerPattern: fallback.ownerPattern,\n          containerId: fallback.containerId,\n          interception: false,\n          fallback: true,\n          route: fallback,\n          params: {},\n        });\n      }\n    }\n\n    return matches.sort((left, right) => {\n      const ownerDifference = left.route.route.segments.length - right.route.route.segments.length;\n      return ownerDifference || left.name.localeCompare(right.name);\n    });\n  }\n\n  private matchesRoutePrefix(pathname: string, pattern: string): boolean {\n    if (pattern === \"/\") return true;\n    const patternSegments = parseRoutePath(`${pattern}/page.tsx`).segments;\n    return matchRoutePrefix(pathname, patternSegments);\n  }\n\n  private findNearestBoundary(\n    pathname: string,\n    boundaries: Map<string, RouteEntry>,\n  ): RouteEntry | null {\n    const normalizedPath = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n    let bestMatch: RouteEntry | null = null;\n\n    for (const boundaryEntry of boundaries.values()) {\n      if (!matchRoutePrefix(normalizedPath, boundaryEntry.route.segments)) continue;\n\n      if (!bestMatch || boundaryEntry.route.segments.length > bestMatch.route.segments.length) {\n        bestMatch = boundaryEntry;\n      }\n    }\n\n    return bestMatch;\n  }\n\n  /**\n   * Log discovered routes for debugging\n   */\n  private logRoutes(): void {\n    if (this.routes.size > 0) {\n      logger.info(\"Registered routes:\");\n      for (const [pattern, entry] of this.routes) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n\n    if (this.layouts.size > 0) {\n      logger.info(\"Registered layouts:\");\n      for (const [pattern, entry] of this.layouts) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n  }\n\n  /**\n   * Collect SSG pages for static generation\n   *\n   * Returns all pages marked with `export const ssg = true` along with\n   * their pre-computed paths (for dynamic routes using getStaticPaths)\n   */\n  async collectSSGPages(): Promise<SSGCollectionResult> {\n    const routes = Array.from(this.routes.values()).map((entry) => ({\n      path: entry.pattern,\n      filePath: entry.modulePath,\n      isDynamic: entry.route.segments.some((seg) => seg.isDynamic),\n      pattern: entry.pattern,\n    }));\n\n    const i18n = this.getI18nConfig();\n    const result = await collectSSGPages(routes, (filePath) => this.loadRouteModule(filePath), {\n      suggestStaticRendering: shouldSuggestStaticRenderingForI18n(i18n),\n    });\n    if (!i18n) {\n      return result;\n    }\n\n    // A single static URL cannot safely vary by cookie or Accept-Language.\n    // Keep locale-without-prefix pages dynamic so caches never pin one language.\n    if (i18n.routing === \"none\") {\n      return {\n        ssg: [],\n        ssr: Array.from(new Set([...result.ssr, ...result.ssg.map((page) => page.urlPath)])),\n      };\n    }\n\n    return {\n      ssg: result.ssg.flatMap((page) =>\n        i18n.locales.map((locale) => ({\n          ...page,\n          urlPath: localizeFarmPathname(page.urlPath, locale, i18n),\n        })),\n      ),\n      ssr: result.ssr.flatMap((routePath) =>\n        i18n.locales.map((locale) => localizeFarmPathname(routePath, locale, i18n)),\n      ),\n    };\n  }\n\n  private toRoutePathname(pathname: string): string {\n    const i18n = this.getI18nConfig();\n    return i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n  }\n\n  private localizeRedirectDestination(destination: string, locale?: string): string {\n    if (!locale || !destination.startsWith(\"/\") || destination.startsWith(\"//\")) {\n      return destination;\n    }\n    const i18n = this.getI18nConfig();\n    return i18n ? localizeFarmHref(destination, locale, i18n) : destination;\n  }\n\n  private getI18nConfig(): ResolvedFarmI18nConfig | undefined {\n    const i18n = this.config.i18n;\n    return i18n && typeof i18n === \"object\" && \"enabled\" in i18n && i18n.enabled ? i18n : undefined;\n  }\n\n  /**\n   * Check if a route is SSG\n   */\n  async isRouteSSG(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Check if a route has ISR (Incremental Static Regeneration)\n   */\n  async hasRouteISR(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Get revalidation interval for a route\n   */\n  async getRouteRevalidateInterval(modulePath: string): Promise<number | undefined> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.revalidate;\n    } catch {\n      return undefined;\n    }\n  }\n}\n\nexport function interpolateRedirectDestination(\n  destination: string,\n  params: Record<string, string>,\n): string {\n  let result = destination;\n\n  for (const [key, value] of Object.entries(params)) {\n    // Longest token first: [[...key]] contains [...key], which contains [key].\n    result = replaceAll(result, `[[...${key}]]`, value);\n    result = replaceAll(result, `[...${key}]`, value);\n    result = replaceAll(result, `[${key}]`, value);\n    result = replaceAll(result, `:${key}*`, value);\n    result = replaceAll(result, `:${key}`, value);\n  }\n\n  return result;\n}\n\nfunction getMetadataImageSuffix(pathname: string): {\n  kind: MetadataImageKind;\n  fileName: MetadataImageEntry[\"fileName\"];\n} | null {\n  if (pathname === \"/opengraph-image\" || pathname.endsWith(\"/opengraph-image\")) {\n    return { kind: \"opengraph\", fileName: \"opengraph-image\" };\n  }\n\n  if (pathname === \"/twitter-image\" || pathname.endsWith(\"/twitter-image\")) {\n    return { kind: \"twitter\", fileName: \"twitter-image\" };\n  }\n\n  return null;\n}\n\nfunction getApplicationMetadataRouteDescriptor(fileName: string): {\n  kind: ApplicationMetadataRouteKind;\n  fileName: ApplicationMetadataRouteEntry[\"fileName\"];\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  if (fileName === \"sitemap\") {\n    return { kind: \"sitemap\", fileName: \"sitemap\", outputName: \"sitemap.xml\" };\n  }\n  if (fileName === \"robots\") {\n    return { kind: \"robots\", fileName: \"robots\", outputName: \"robots.txt\" };\n  }\n  if (fileName === \"manifest\") {\n    return { kind: \"manifest\", fileName: \"manifest\", outputName: \"manifest.webmanifest\" };\n  }\n  return null;\n}\n\nfunction getApplicationMetadataRouteSuffix(pathname: string): {\n  kind: ApplicationMetadataRouteKind;\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  for (const fileName of [\"sitemap\", \"robots\", \"manifest\"] as const) {\n    const descriptor = getApplicationMetadataRouteDescriptor(fileName)!;\n    if (\n      pathname === `/${descriptor.outputName}` ||\n      pathname.endsWith(`/${descriptor.outputName}`)\n    ) {\n      return { kind: descriptor.kind, outputName: descriptor.outputName };\n    }\n  }\n  return null;\n}\n\nfunction routeSegmentsToPath(\n  segments: ParsedRoute[\"segments\"],\n  params: Record<string, string>,\n): string {\n  if (segments.length === 0) return \"/\";\n\n  const parts: string[] = [];\n  for (const segment of segments) {\n    if (!segment.isDynamic) {\n      parts.push(segment.segment);\n      continue;\n    }\n\n    const value = params[segment.segment];\n    if (!value && segment.isOptional) continue;\n    if (!value) {\n      parts.push(`[${segment.segment}]`);\n      continue;\n    }\n\n    parts.push(...value.split(\"/\").map((part) => encodeURIComponent(part)));\n  }\n\n  return `/${parts.join(\"/\")}`;\n}\n\nfunction replaceAll(input: string, search: string, replacement: string): string {\n  return input.split(search).join(replacement);\n}\n\nasync function safeGlobFiles(pattern: string, cwd: string): Promise<string[]> {\n  try {\n    return await globFiles(pattern, cwd);\n  } catch {\n    return [];\n  }\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { isFarmIslandStrategy, type FarmIslandStrategy } from \"../island\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\n\nfunction readIfExists(filePath: string): string | null {\n  try {\n    if (!filePath || !fs.existsSync(filePath)) {\n      return null;\n    }\n    return fs.readFileSync(filePath, \"utf-8\");\n  } catch {\n    return null;\n  }\n}\n\nexport function resolveModuleSourcePath(modulePath: string, root?: string): string | null {\n  const candidates = new Set<string>();\n  const withoutQuery = modulePath.split(\"?\")[0];\n\n  if (modulePath) {\n    candidates.add(modulePath);\n    candidates.add(withoutQuery);\n\n    if (modulePath.startsWith(\"file://\")) {\n      try {\n        candidates.add(fileURLToPath(modulePath));\n      } catch {\n        // ignore invalid file urls\n      }\n    }\n\n    if (modulePath.startsWith(\"/@fs/\")) {\n      // Vite emits /@fs/C:/... on Windows, where the leading slash is not part of the path.\n      const fsPath = withoutQuery.slice(\"/@fs/\".length);\n      candidates.add(path.normalize(/^[A-Za-z]:/.test(fsPath) ? fsPath : `/${fsPath}`));\n    }\n  }\n\n  if (root && modulePath) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(root, normalized));\n    candidates.add(path.resolve(root, normalized));\n  }\n\n  if (withoutQuery?.startsWith(\"/src/\")) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(process.cwd(), normalized));\n    candidates.add(path.resolve(process.cwd(), normalized));\n  }\n\n  for (const candidate of candidates) {\n    if (fs.existsSync(candidate)) {\n      return candidate;\n    }\n  }\n\n  return null;\n}\n\nexport interface ClientModuleMetadata {\n  isClientComponent: boolean;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  /**\n   * Set when the module would hydrate (client imports or an explicit hydrate\n   * export) but its default export is an async server component, which React\n   * cannot run in a client root. Hydration is suppressed so the\n   * server-rendered HTML stays intact instead of crashing to a blank page.\n   */\n  suppressedAsyncHydration?: true;\n}\n\nexport interface IsolatedClientBoundaryReference {\n  /** Absolute source path. Converted to a Vite URL only at the manifest edge. */\n  modulePath: string;\n  islandStrategy: FarmIslandStrategy;\n}\n\nexport interface ClientModuleHydrationPlan extends ClientModuleMetadata {\n  mode: FarmIsolatedClientHydrationMode;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  isolatedHydrationEligible: boolean;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\n/** @internal Largest measured statically bounded independent-root plan. */\nexport const FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES = 4;\n\nfunction isolatedHydrationBoundaryLimit(): number {\n  const benchmarkRoot = process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_ROOT;\n  const benchmarkLimit = Number(process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_LIMIT);\n  const resolvedBenchmarkRoot = benchmarkRoot ? path.resolve(benchmarkRoot) : null;\n  const isBenchmarkFixture =\n    process.env.FARM_INTERNAL_BENCHMARK === \"isolated-hydration\" &&\n    resolvedBenchmarkRoot !== null &&\n    (process.cwd() === resolvedBenchmarkRoot ||\n      process.cwd().startsWith(`${resolvedBenchmarkRoot}${path.sep}`));\n  return isBenchmarkFixture &&\n    Number.isSafeInteger(benchmarkLimit) &&\n    benchmarkLimit > FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES\n    ? benchmarkLimit\n    : FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES;\n}\n\ninterface ParsedClientModuleMetadata {\n  isClientComponent: boolean;\n  hasHydrateExport: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n}\n\nconst RESOLVABLE_SOURCE_EXTENSIONS = [\n  \".svelte\",\n  \".vue\",\n  \".tsx\",\n  \".ts\",\n  \".jsx\",\n  \".js\",\n  \".mts\",\n  \".mjs\",\n  \".cts\",\n  \".cjs\",\n] as const;\n\nexport function resolveFarmIsolatedClientHydrationMode(\n  mode: FarmIsolatedClientHydrationMode | undefined,\n  options: {\n    serverComponents?: boolean;\n    hasUnsupportedIntegrationProvider?: boolean;\n  } = {},\n): FarmIsolatedClientHydrationMode {\n  if (options.serverComponents) return \"off\";\n  if (mode === \"enabled\" && options.hasUnsupportedIntegrationProvider) return \"off\";\n  return mode ?? \"off\";\n}\n\nexport function hasUseClientDirective(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n\n  // Fast path: directive at the very start of the file.\n  const normalized = content.trimStart();\n  if (normalized.startsWith(\"'use client'\") || normalized.startsWith('\"use client\"')) {\n    return true;\n  }\n  if (!normalized.includes(\"use client\")) {\n    return false;\n  }\n\n  // Directive-prologue semantics allow comments and other directives (e.g.\n  // \"use strict\") before \"use client\". Scan the leading string-literal\n  // statements with the comment-aware tokenizer.\n  for (const token of tokenizeModuleSource(content)) {\n    if (token.kind === \"string\") {\n      if (token.value === \"use client\") {\n        return true;\n      }\n      continue;\n    }\n    if (token.kind === \"punctuation\" && token.value === \";\") {\n      continue;\n    }\n    return false;\n  }\n  return false;\n}\n\nexport function hasHydrateExport(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n  if (/\\bexport\\s+const\\s+hydrate\\s*=\\s*true\\b/.test(content)) {\n    return true;\n  }\n  // Export lists may carry several specifiers and as-renames; the module\n  // opts in when any specifier's *exported* name is hydrate.\n  for (const match of content.matchAll(/\\bexport\\s*\\{([^}]*)\\}/g)) {\n    for (const specifier of match[1].split(\",\")) {\n      const parts = specifier.trim().split(/\\s+as\\s+/);\n      const exportedName = (parts[1] ?? parts[0])?.trim();\n      if (exportedName === \"hydrate\") {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\ninterface ModuleSourceToken {\n  kind: \"identifier\" | \"string\" | \"punctuation\";\n  value: string;\n  line: number;\n}\n\nconst REGEXP_PREFIX_PUNCTUATION = new Set([\n  \"(\",\n  \"[\",\n  \"{\",\n  \",\",\n  \";\",\n  \":\",\n  \"=\",\n  \"!\",\n  \"?\",\n  \"&\",\n  \"|\",\n  \"+\",\n  \"-\",\n  \"*\",\n  \"%\",\n  \"^\",\n  \"~\",\n  \">\",\n]);\nconst REGEXP_PREFIX_KEYWORDS = new Set([\n  \"await\",\n  \"case\",\n  \"delete\",\n  \"do\",\n  \"else\",\n  \"in\",\n  \"instanceof\",\n  \"new\",\n  \"of\",\n  \"return\",\n  \"throw\",\n  \"typeof\",\n  \"void\",\n  \"yield\",\n]);\n\nfunction canStartRegularExpression(previous: ModuleSourceToken | undefined): boolean {\n  if (!previous) return true;\n  return previous.kind === \"identifier\"\n    ? REGEXP_PREFIX_KEYWORDS.has(previous.value)\n    : REGEXP_PREFIX_PUNCTUATION.has(previous.value);\n}\n\nfunction skipRegularExpression(content: string, startIndex: number): number | null {\n  let index = startIndex + 1;\n  let inCharacterClass = false;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (character === \"\\n\" || character === \"\\r\") return null;\n    if (character === \"\\\\\") {\n      index += 2;\n      continue;\n    }\n    if (character === \"[\") {\n      inCharacterClass = true;\n      index++;\n      continue;\n    }\n    if (character === \"]\" && inCharacterClass) {\n      inCharacterClass = false;\n      index++;\n      continue;\n    }\n    if (character === \"/\" && !inCharacterClass) {\n      index++;\n      while (index < content.length && /[A-Za-z]/.test(content[index])) index++;\n      return index;\n    }\n    index++;\n  }\n\n  return null;\n}\n\nfunction tokenizeModuleSource(content: string): ModuleSourceToken[] {\n  const tokens: ModuleSourceToken[] = [];\n  let index = 0;\n  let line = 1;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (/\\s/.test(character)) {\n      if (character === \"\\n\") line++;\n      index++;\n      continue;\n    }\n\n    if (character === \"/\" && content[index + 1] === \"/\") {\n      index += 2;\n      while (index < content.length && content[index] !== \"\\n\") index++;\n      continue;\n    }\n    if (character === \"/\" && content[index + 1] === \"*\") {\n      index += 2;\n      while (index < content.length) {\n        if (content[index] === \"\\n\") line++;\n        if (content[index] === \"*\" && content[index + 1] === \"/\") {\n          index += 2;\n          break;\n        }\n        index++;\n      }\n      continue;\n    }\n\n    if (character === \"/\" && canStartRegularExpression(tokens[tokens.length - 1])) {\n      const endIndex = skipRegularExpression(content, index);\n      if (endIndex !== null) {\n        index = endIndex;\n        continue;\n      }\n    }\n\n    if (character === '\"' || character === \"'\") {\n      const quote = character;\n      const tokenLine = line;\n      let value = \"\";\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          value += next;\n          if (index + 1 < content.length) value += content[index + 1];\n          index += 2;\n          continue;\n        }\n        if (next === quote) {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        value += next;\n        index++;\n      }\n      tokens.push({ kind: \"string\", value, line: tokenLine });\n      continue;\n    }\n\n    if (character === \"`\") {\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          index += 2;\n          continue;\n        }\n        if (next === \"`\") {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        index++;\n      }\n      continue;\n    }\n\n    if (/[A-Za-z_$]/.test(character)) {\n      const start = index++;\n      while (index < content.length && /[\\w$]/.test(content[index])) index++;\n      tokens.push({ kind: \"identifier\", value: content.slice(start, index), line });\n      continue;\n    }\n\n    tokens.push({ kind: \"punctuation\", value: character, line });\n    index++;\n  }\n\n  return tokens;\n}\n\nfunction isIslandExportStart(tokens: ModuleSourceToken[], index: number): boolean {\n  const token = tokens[index];\n  const previous = tokens[index - 1];\n  const startsStatement =\n    !previous ||\n    previous.value === \";\" ||\n    previous.value === \"{\" ||\n    previous.value === \"}\" ||\n    token.line > previous.line;\n  return (\n    startsStatement &&\n    token.value === \"export\" &&\n    tokens[index + 1]?.value === \"const\" &&\n    tokens[index + 2]?.value === \"island\"\n  );\n}\n\nexport function getIslandStrategyExport(content: string | null): FarmIslandStrategy | null {\n  if (!content) return null;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (!isIslandExportStart(tokens, index)) continue;\n\n    let valueIndex = index + 3;\n    if (tokens[valueIndex]?.value === \":\") {\n      while (valueIndex < tokens.length && tokens[valueIndex].value !== \"=\") valueIndex++;\n    }\n    if (tokens[valueIndex]?.value !== \"=\") break;\n    valueIndex++;\n\n    const literal = tokens[valueIndex];\n    if (!literal || literal.kind !== \"string\" || !isFarmIslandStrategy(literal.value)) break;\n\n    let trailingIndex = valueIndex + 1;\n    if (tokens[trailingIndex]?.value === \"as\" && tokens[trailingIndex + 1]?.value === \"const\") {\n      trailingIndex += 2;\n    }\n    const trailing = tokens[trailingIndex];\n    if (trailing && trailing.value !== \";\" && trailing.line === literal.line) break;\n    return literal.value;\n  }\n\n  if (tokens.some((_token, index) => isIslandExportStart(tokens, index))) {\n    throw new Error(\n      'Farm island configuration must be a static \"load\", \"interaction\", \"visible\", or \"idle\" string literal.',\n    );\n  }\n\n  return null;\n}\n\nexport function stripUseClientDirective(content: string): string {\n  // Comments (and other directives) may precede \"use client\"; keep them and\n  // remove only the directive itself.\n  return content.replace(\n    /^((?:\\s|\\/\\/[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/|(?:\"[^\"\\n]*\"|'[^'\\n]*')\\s*;?)*)([\"'])use client\\2\\s*;?\\s*/,\n    \"$1\",\n  );\n}\n\n/**\n * Best-effort static detection of an async default export, e.g.\n * `export default async function Page() {}`. Covers direct async\n * function/arrow default exports and `export default X` where `X` is a local\n * `async function X` or `X = async ...` declaration. Wrapped exports such as\n * `export default withAuth(Page)` cannot be resolved statically; the client\n * runtime guards against those at hydration time.\n */\nexport function hasAsyncDefaultExport(content: string | null): boolean {\n  if (!content) return false;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    const token = tokens[index];\n    if (token.kind !== \"identifier\" || token.value !== \"export\") continue;\n    if (tokens[index - 1]?.value === \".\") continue;\n    if (tokens[index + 1]?.value !== \"default\") continue;\n\n    const exported = tokens[index + 2];\n    if (exported.kind === \"identifier\" && exported.value === \"async\") {\n      return true;\n    }\n    if (\n      exported.kind === \"identifier\" &&\n      ![\"function\", \"class\"].includes(exported.value) &&\n      tokens[index + 3]?.value !== \"(\" &&\n      isAsyncLocalDeclaration(tokens, exported.value)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isAsyncLocalDeclaration(tokens: ModuleSourceToken[], name: string): boolean {\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (\n      tokens[index].value === \"async\" &&\n      tokens[index + 1]?.value === \"function\" &&\n      tokens[index + 2]?.value === name\n    ) {\n      return true;\n    }\n    if (\n      tokens[index].value === name &&\n      tokens[index + 1]?.value === \"=\" &&\n      tokens[index + 2]?.value === \"async\"\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction parseClientModuleMetadata(\n  content: string | null,\n  inspectIslandExport: boolean,\n): ParsedClientModuleMetadata {\n  if (!content) {\n    return {\n      isClientComponent: false,\n      hasHydrateExport: false,\n      islandStrategy: null,\n    };\n  }\n\n  const isClientComponent = hasUseClientDirective(content);\n  const hasHydrate = hasHydrateExport(content);\n  return {\n    isClientComponent,\n    hasHydrateExport: hasHydrate,\n    islandStrategy:\n      inspectIslandExport || isClientComponent || hasHydrate\n        ? getIslandStrategyExport(content)\n        : null,\n  };\n}\n\nexport function getClientModuleMetadata(modulePath: string, root?: string): ClientModuleMetadata {\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  return inspectClientModuleMetadata(resolvedPath, root, new Set(), true);\n}\n\n/**\n * Resolve hydration ownership without changing the legacy metadata contract.\n * The old metadata remains the conservative fallback; only an enabled and\n * completely supported graph moves ownership to leaf client modules.\n */\nexport function getClientModuleHydrationPlan(\n  modulePath: string,\n  root: string | undefined,\n  mode: FarmIsolatedClientHydrationMode = \"off\",\n): ClientModuleHydrationPlan {\n  const metadata = getClientModuleMetadata(modulePath, root);\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  const content = readIfExists(resolvedPath ?? \"\");\n  const parsed = parseClientModuleMetadata(content, true);\n  const emptyPlan = (\n    fallbackReason?: string,\n    costGuardExceeded = false,\n    estimatedIsolatedRootCount = 0,\n  ): ClientModuleHydrationPlan => ({\n    ...metadata,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount,\n    isolatedHydrationEligible: false,\n    hasIsolatedClientBoundaries: false,\n    isolatedBoundaries: [],\n    ...(costGuardExceeded ? { costGuardExceeded: true as const } : {}),\n    ...(fallbackReason ? { fallbackReason } : {}),\n  });\n\n  if (mode === \"off\") return emptyPlan();\n  if (!resolvedPath) return emptyPlan(\"the owner source could not be resolved\");\n  if (parsed.isClientComponent) {\n    return emptyPlan(\"the owner is already a client component\");\n  }\n  if (parsed.hasHydrateExport) {\n    return emptyPlan(\"the owner explicitly exports `hydrate = true`\");\n  }\n\n  const inspection = collectIsolatedClientBoundaries(resolvedPath, root);\n  if (inspection.boundaries.length === 0) {\n    return emptyPlan(inspection.fallbackReason);\n  }\n  if (inspection.fallbackReason) {\n    return emptyPlan(\n      inspection.fallbackReason,\n      inspection.costGuardExceeded,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  if (inspection.estimatedBoundaryCount > boundaryLimit) {\n    return emptyPlan(\n      `the client graph can create ${inspection.estimatedBoundaryCount} isolated roots, above the measured limit of ${boundaryLimit}`,\n      true,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n\n  const enabled = mode === \"enabled\";\n  return {\n    ...metadata,\n    shouldHydrate: enabled ? false : metadata.shouldHydrate,\n    islandStrategy: enabled ? null : metadata.islandStrategy,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,\n    isolatedHydrationEligible: true,\n    hasIsolatedClientBoundaries: enabled,\n    isolatedBoundaries: inspection.boundaries,\n  };\n}\n\ninterface FarmIsolatedHydrationRoutePlan {\n  mode: FarmIsolatedClientHydrationMode;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\ninterface FarmIsolatedHydrationRouteOwner {\n  pattern: string;\n  depth: number;\n  metadata: FarmIsolatedHydrationRoutePlan;\n}\n\nfunction restoreRouteWideHydration(\n  metadata: FarmIsolatedHydrationRoutePlan,\n  fallbackReason?: string,\n): void {\n  metadata.shouldHydrate = metadata.legacyShouldHydrate;\n  metadata.islandStrategy = metadata.legacyIslandStrategy;\n  metadata.hasIsolatedClientBoundaries = false;\n  metadata.isolatedBoundaries = [];\n  if (fallbackReason) {\n    metadata.costGuardExceeded = true;\n    metadata.fallbackReason = fallbackReason;\n  }\n}\n\n/** @internal Applies the measured root budget to each complete layout and page chain. */\nexport function enforceFarmIsolatedHydrationRouteBudget(\n  layouts: FarmIsolatedHydrationRouteOwner[],\n  routes: FarmIsolatedHydrationRouteOwner[],\n  layoutAppliesToRoute: (layoutPattern: string, routePattern: string) => boolean,\n): void {\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  const sortedLayouts = [...layouts].sort((left, right) => left.depth - right.depth);\n\n  for (const route of routes) {\n    if (route.metadata.mode !== \"enabled\") continue;\n    const applicableLayouts = sortedLayouts.filter((layout) =>\n      layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (applicableLayouts.some((layout) => layout.metadata.shouldHydrate)) continue;\n\n    const layoutRootCount = applicableLayouts.reduce(\n      (count, layout) =>\n        count +\n        (layout.metadata.hasIsolatedClientBoundaries\n          ? layout.metadata.estimatedIsolatedRootCount\n          : 0),\n      0,\n    );\n    const routeRootCount = route.metadata.hasIsolatedClientBoundaries\n      ? route.metadata.estimatedIsolatedRootCount\n      : 0;\n    const totalRootCount = layoutRootCount + routeRootCount;\n    if (totalRootCount <= boundaryLimit) continue;\n\n    let accumulatedLayoutRoots = 0;\n    const overflowingLayout = applicableLayouts.find((layout) => {\n      if (layout.metadata.hasIsolatedClientBoundaries) {\n        accumulatedLayoutRoots += layout.metadata.estimatedIsolatedRootCount;\n      }\n      return accumulatedLayoutRoots > boundaryLimit;\n    });\n    const fallbackReason = `the matched route ${route.pattern} can create ${totalRootCount} isolated roots, above the measured limit of ${boundaryLimit}`;\n\n    if (overflowingLayout) {\n      restoreRouteWideHydration(overflowingLayout.metadata, fallbackReason);\n    } else if (route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata, fallbackReason);\n    }\n  }\n\n  for (const layout of sortedLayouts) {\n    const hasRouteWideAncestor = sortedLayouts.some(\n      (ancestor) =>\n        ancestor !== layout &&\n        ancestor.depth < layout.depth &&\n        ancestor.metadata.shouldHydrate &&\n        layoutAppliesToRoute(ancestor.pattern, layout.pattern),\n    );\n    if (hasRouteWideAncestor && layout.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(layout.metadata);\n    }\n  }\n\n  for (const route of routes) {\n    const hasRouteWideLayout = sortedLayouts.some(\n      (layout) =>\n        layout.metadata.shouldHydrate && layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (hasRouteWideLayout && route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata);\n    }\n  }\n}\n\n/**\n * The first compiler pass intentionally accepts only statically named React\n * component exports. A rejected module retains route-wide hydration.\n */\nexport function isIsolatableClientBoundarySource(content: string | null): boolean {\n  if (!content || !hasUseClientDirective(content)) return false;\n  if (/\\bexport\\s*\\{/.test(content) || /\\bexport\\s*\\*/.test(content)) return false;\n  return (\n    /\\bexport\\s+default\\s+(?!(?:type|interface)\\b)/.test(content) ||\n    /\\bexport\\s+(?:async\\s+)?function\\s+[A-Z][$\\w]*/.test(content) ||\n    /\\bexport\\s+(?:const|let|var|class)\\s+[A-Z][$\\w]*/.test(content)\n  );\n}\n\nfunction getStaticImportBindings(content: string | null): Map<string, string[]> {\n  const bindings = new Map<string, string[]>();\n  if (!content) return bindings;\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length; index++) {\n    if (tokens[index].value !== \"import\" || tokens[index - 1]?.value === \".\") continue;\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.kind === \"string\") {\n      continue;\n    }\n\n    let fromIndex = -1;\n    for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n      if (tokens[cursor].value === \";\") break;\n      if (tokens[cursor].value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n        fromIndex = cursor;\n        break;\n      }\n    }\n    if (fromIndex === -1) continue;\n    const specifier = tokens[fromIndex + 1].value;\n    const clause = tokens.slice(index + 1, fromIndex);\n    const localNames: string[] = [];\n\n    if (clause[0]?.kind === \"identifier\" && clause[0].value !== \"type\") {\n      localNames.push(clause[0].value);\n    }\n    const namespaceAs = clause.findIndex(\n      (token, clauseIndex) => token.value === \"*\" && clause[clauseIndex + 1]?.value === \"as\",\n    );\n    if (namespaceAs !== -1 && clause[namespaceAs + 2]?.kind === \"identifier\") {\n      localNames.push(clause[namespaceAs + 2].value);\n    }\n\n    const openingBrace = clause.findIndex((token) => token.value === \"{\");\n    const closingBrace = clause.findIndex(\n      (token, clauseIndex) => clauseIndex > openingBrace && token.value === \"}\",\n    );\n    if (openingBrace !== -1 && closingBrace !== -1) {\n      let entryStart = openingBrace + 1;\n      for (let cursor = entryStart; cursor <= closingBrace; cursor++) {\n        if (cursor !== closingBrace && clause[cursor]?.value !== \",\") continue;\n        const entry = clause.slice(entryStart, cursor).filter((token) => token.value !== \"type\");\n        const asIndex = entry.findIndex((token) => token.value === \"as\");\n        const local = asIndex === -1 ? entry[0] : entry[asIndex + 1];\n        if (local?.kind === \"identifier\") localNames.push(local.value);\n        entryStart = cursor + 1;\n      }\n    }\n\n    bindings.set(\n      specifier,\n      Array.from(new Set([...(bindings.get(specifier) ?? []), ...localNames])),\n    );\n  }\n\n  return bindings;\n}\n\n/**\n * Elements whose content model the HTML parser enforces. A boundary marker\n * emitted inside one of these is relocated or ignored before any script runs:\n * in a table the marker and its row are foster-parented out of the table, in a\n * select the options stop being direct children and the control renders empty,\n * and inside svg the marker is created in the SVG namespace as an unknown\n * element whose children never render. RFC 0001 requires these to take the\n * route-wide fallback.\n */\nconst PARSER_SENSITIVE_JSX_CONTAINERS = new Set([\n  \"table\",\n  \"thead\",\n  \"tbody\",\n  \"tfoot\",\n  \"tr\",\n  \"select\",\n  \"optgroup\",\n  \"svg\",\n]);\n\n/**\n * Names a parser-sensitive element that encloses a use of one of the bindings,\n * or undefined when every use is in ordinary flow content.\n *\n * Ambiguity resolves toward reporting a container: the caller turns a hit into\n * the complete route-wide fallback, which is always correct, while a miss would\n * leave the silent DOM corruption in place.\n */\nfunction findParserSensitiveJsxContainer(\n  content: string | null,\n  localBindings: string[],\n): string | undefined {\n  if (!content || localBindings.length === 0) return undefined;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const openDepth = new Map<string, number>();\n\n  const isSelfClosing = (openingIndex: number): boolean => {\n    for (let index = openingIndex; index < tokens.length; index++) {\n      if (tokens[index].value === \">\") return tokens[index - 1]?.value === \"/\";\n    }\n    return false;\n  };\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\") continue;\n\n    if (tokens[index + 1].value === \"/\") {\n      const closing = tokens[index + 2]?.value;\n      if (closing && openDepth.has(closing)) {\n        openDepth.set(closing, Math.max(0, (openDepth.get(closing) ?? 0) - 1));\n      }\n      continue;\n    }\n\n    const tag = tokens[index + 1].value;\n    if (names.has(tag)) {\n      for (const [container, depth] of openDepth) {\n        if (depth > 0) return container;\n      }\n      continue;\n    }\n    if (PARSER_SENSITIVE_JSX_CONTAINERS.has(tag) && !isSelfClosing(index)) {\n      openDepth.set(tag, (openDepth.get(tag) ?? 0) + 1);\n    }\n  }\n\n  return undefined;\n}\n\nfunction countStaticJsxUses(content: string | null, localBindings: string[]): number {\n  if (!content || localBindings.length === 0) return 0;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  let count = 0;\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value === \"<\" && names.has(tokens[index + 1].value)) count++;\n  }\n  return count;\n}\n\nfunction findMatchingToken(\n  tokens: ModuleSourceToken[],\n  openingIndex: number,\n  opening: string,\n  closing: string,\n): number {\n  let depth = 0;\n  for (let index = openingIndex; index < tokens.length; index++) {\n    if (tokens[index].value === opening) depth++;\n    if (tokens[index].value !== closing) continue;\n    depth--;\n    if (depth === 0) return index;\n  }\n  return tokens.length - 1;\n}\n\nfunction containsClientJsx(\n  tokens: ModuleSourceToken[],\n  start: number,\n  end: number,\n  clientBindings: Set<string>,\n): boolean {\n  for (let index = start; index < end; index++) {\n    if (tokens[index].value === \"<\" && clientBindings.has(tokens[index + 1]?.value)) return true;\n  }\n  return false;\n}\n\nfunction findStatementEnd(tokens: ModuleSourceToken[], start: number): number {\n  let parentheses = 0;\n  let brackets = 0;\n  let braces = 0;\n  const statementStarters = new Set([\n    \"class\",\n    \"const\",\n    \"export\",\n    \"function\",\n    \"import\",\n    \"let\",\n    \"var\",\n  ]);\n  for (let index = start; index < tokens.length; index++) {\n    const value = tokens[index].value;\n    if (\n      index > start &&\n      parentheses === 0 &&\n      brackets === 0 &&\n      braces === 0 &&\n      tokens[index].line > tokens[index - 1].line &&\n      statementStarters.has(value)\n    ) {\n      return index;\n    }\n    if (value === \";\" && parentheses === 0 && brackets === 0 && braces === 0) return index;\n    if (value === \"(\") parentheses++;\n    if (value === \")\") parentheses--;\n    if (value === \"[\") brackets++;\n    if (value === \"]\") brackets--;\n    if (value === \"{\") braces++;\n    if (value === \"}\") braces--;\n  }\n  return tokens.length;\n}\n\nfunction getClientRenderingHelpers(\n  tokens: ModuleSourceToken[],\n  clientBindings: Set<string>,\n): Set<string> {\n  const helperBodies = new Map<string, [start: number, end: number]>();\n  for (let index = 0; index < tokens.length; index++) {\n    let helperName: string | undefined;\n    let bodyStart = -1;\n    let bodyEnd = -1;\n\n    if (tokens[index].value === \"function\" && tokens[index + 1]?.kind === \"identifier\") {\n      helperName = tokens[index + 1].value;\n      const parametersStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > index + 1 && token.value === \"(\",\n      );\n      const parametersEnd =\n        parametersStart === -1 ? index + 1 : findMatchingToken(tokens, parametersStart, \"(\", \")\");\n      bodyStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > parametersEnd && token.value === \"{\",\n      );\n      if (bodyStart !== -1) bodyEnd = findMatchingToken(tokens, bodyStart, \"{\", \"}\");\n    } else if (\n      (tokens[index].value === \"const\" ||\n        tokens[index].value === \"let\" ||\n        tokens[index].value === \"var\") &&\n      tokens[index + 1]?.kind === \"identifier\"\n    ) {\n      helperName = tokens[index + 1].value;\n      let assignmentIndex = -1;\n      let arrowIndex = -1;\n      for (let cursor = index + 2; cursor < tokens.length; cursor++) {\n        if (tokens[cursor].value === \";\") break;\n        if (assignmentIndex === -1 && tokens[cursor].value === \"=\") assignmentIndex = cursor;\n        if (tokens[cursor].value === \"=\" && tokens[cursor + 1]?.value === \">\") {\n          arrowIndex = cursor;\n          break;\n        }\n      }\n      if (arrowIndex !== -1) {\n        bodyStart = arrowIndex + 2;\n        bodyEnd =\n          tokens[bodyStart]?.value === \"{\"\n            ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n            : findStatementEnd(tokens, bodyStart);\n      } else if (assignmentIndex !== -1) {\n        bodyStart = assignmentIndex + 1;\n        bodyEnd = findStatementEnd(tokens, bodyStart);\n      }\n    }\n\n    if (helperName && bodyStart !== -1 && bodyEnd !== -1) {\n      helperBodies.set(helperName, [bodyStart, bodyEnd]);\n    }\n  }\n\n  const helpers = new Set<string>();\n  let addedHelper = true;\n  while (addedHelper) {\n    addedHelper = false;\n    for (const [helperName, [bodyStart, bodyEnd]] of helperBodies) {\n      if (helpers.has(helperName)) continue;\n      const rendersClientBoundary =\n        containsClientJsx(tokens, bodyStart, bodyEnd, clientBindings) ||\n        tokens.slice(bodyStart, bodyEnd).some((token) => helpers.has(token.value));\n      if (!rendersClientBoundary) continue;\n      helpers.add(helperName);\n      addedHelper = true;\n    }\n  }\n  return helpers;\n}\n\n/**\n * True when a boundary is handed a React element, as JSX children or as an\n * element-valued prop.\n *\n * Boundary props cross to the browser as JSON, and an element cannot be\n * serialized. Without this check the SSR wrapper drops the marker for that\n * boundary and the component renders as ordinary server markup that nothing\n * ever hydrates, leaving an interactive-looking widget permanently dead with\n * no browser-visible diagnostic. String and number children serialize fine and\n * are deliberately not flagged.\n */\nfunction passesElementValuedProps(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\" || !names.has(tokens[index + 1].value)) continue;\n    const name = tokens[index + 1].value;\n\n    // Walk the opening tag, watching for an element inside an attribute\n    // expression such as icon={<Icon />}.\n    let cursor = index + 2;\n    let braceDepth = 0;\n    let selfClosing = false;\n    for (; cursor < tokens.length; cursor++) {\n      const value = tokens[cursor].value;\n      if (value === \"{\") braceDepth++;\n      else if (value === \"}\") braceDepth--;\n      else if (value === \"<\" && braceDepth > 0) return true;\n      else if (value === \">\" && braceDepth === 0) {\n        selfClosing = tokens[cursor - 1]?.value === \"/\";\n        break;\n      }\n    }\n    if (selfClosing || cursor >= tokens.length) continue;\n\n    // The first tag after the opening one decides it: the boundary's own\n    // closing tag means no element children, anything else is an element child.\n    for (let child = cursor + 1; child < tokens.length; child++) {\n      if (tokens[child].value !== \"<\") continue;\n      const closesBoundary = tokens[child + 1]?.value === \"/\" && tokens[child + 2]?.value === name;\n      if (!closesBoundary) return true;\n      break;\n    }\n  }\n\n  return false;\n}\n\nfunction hasDynamicJsxCardinality(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const clientBindings = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const renderingHelpers = getClientRenderingHelpers(tokens, clientBindings);\n  const containsDynamicRenderer = (start: number, end: number) =>\n    containsClientJsx(tokens, start, end, clientBindings) ||\n    tokens.slice(start, end).some((token) => renderingHelpers.has(token.value));\n\n  for (let index = 0; index < tokens.length; index++) {\n    let callStart = -1;\n    if (\n      tokens[index].value === \".\" &&\n      (tokens[index + 1]?.value === \"map\" || tokens[index + 1]?.value === \"flatMap\") &&\n      tokens[index + 2]?.value === \"(\"\n    ) {\n      callStart = index + 2;\n    } else if (\n      tokens[index].value === \"Array\" &&\n      tokens[index + 1]?.value === \".\" &&\n      tokens[index + 2]?.value === \"from\" &&\n      tokens[index + 3]?.value === \"(\"\n    ) {\n      callStart = index + 3;\n    }\n    if (callStart !== -1) {\n      const callEnd = findMatchingToken(tokens, callStart, \"(\", \")\");\n      if (containsDynamicRenderer(callStart + 1, callEnd)) return true;\n      index = callEnd;\n      continue;\n    }\n\n    if (\n      (tokens[index].value === \"for\" || tokens[index].value === \"while\") &&\n      tokens[index + 1]?.value === \"(\"\n    ) {\n      const conditionEnd = findMatchingToken(tokens, index + 1, \"(\", \")\");\n      const bodyStart = conditionEnd + 1;\n      const bodyEnd =\n        tokens[bodyStart]?.value === \"{\"\n          ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n          : tokens.findIndex((token, tokenIndex) => tokenIndex > bodyStart && token.value === \";\");\n      if (containsDynamicRenderer(bodyStart, bodyEnd === -1 ? tokens.length : bodyEnd)) return true;\n    }\n  }\n\n  return false;\n}\n\nfunction collectIsolatedClientBoundaries(\n  ownerPath: string,\n  root: string | undefined,\n): {\n  boundaries: IsolatedClientBoundaryReference[];\n  estimatedBoundaryCount: number;\n  costGuardExceeded?: boolean;\n  fallbackReason?: string;\n} {\n  const boundaries = new Map<string, IsolatedClientBoundaryReference>();\n  const estimates = new Map<string, number>();\n  const visiting = new Set<string>();\n  let fallbackReason: string | undefined;\n  let costGuardExceeded = false;\n  const projectRoot = root ? path.resolve(root) : undefined;\n\n  const visit = (moduleSourcePath: string): number => {\n    if (fallbackReason) return 0;\n    const cached = estimates.get(moduleSourcePath);\n    if (cached !== undefined) return cached;\n    if (visiting.has(moduleSourcePath)) return 0;\n    visiting.add(moduleSourcePath);\n    const content = readIfExists(moduleSourcePath);\n    const parsed = parseClientModuleMetadata(content, false);\n\n    if (parsed.isClientComponent) {\n      if (projectRoot && !path.resolve(moduleSourcePath).startsWith(`${projectRoot}${path.sep}`)) {\n        fallbackReason = `client boundary ${moduleSourcePath} is outside the application root`;\n        return 0;\n      }\n      if (!isIsolatableClientBoundarySource(content)) {\n        fallbackReason = `client boundary ${moduleSourcePath} uses an unsupported export shape`;\n        return 0;\n      }\n      boundaries.set(moduleSourcePath, {\n        modulePath: moduleSourcePath,\n        islandStrategy: parsed.islandStrategy ?? \"load\",\n      });\n      estimates.set(moduleSourcePath, 1);\n      visiting.delete(moduleSourcePath);\n      return 1;\n    }\n\n    if (parsed.hasHydrateExport) {\n      fallbackReason = `imported module ${moduleSourcePath} explicitly exports hydrate = true`;\n      return 0;\n    }\n\n    const importedBindings = getStaticImportBindings(content);\n    let estimatedBoundaryCount = 0;\n    for (const specifier of new Set(getImportSpecifiers(content))) {\n      const importedPath = resolveImportedModuleSourcePath(moduleSourcePath, specifier, root);\n      if (!importedPath) continue;\n      if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n        const packageMetadata = inspectPackageClientBoundary(importedPath, root, new Set());\n        if (packageMetadata.shouldHydrate) {\n          fallbackReason = `package client boundary ${specifier} cannot yet be isolated`;\n          return 0;\n        }\n        continue;\n      }\n      const importedBoundaryCount = visit(importedPath);\n      if (fallbackReason || importedBoundaryCount === 0) continue;\n      const localBindings = importedBindings.get(specifier) ?? [];\n      const staticUses = countStaticJsxUses(content, localBindings);\n      if (staticUses > 0) {\n        const container = findParserSensitiveJsxContainer(content, localBindings);\n        if (container) {\n          fallbackReason = `the client boundary imported from ${specifier} renders inside <${container}>, where the HTML parser relocates its hydration marker`;\n          return 0;\n        }\n        if (passesElementValuedProps(content, localBindings)) {\n          fallbackReason = `the client boundary imported from ${specifier} receives React elements, which cannot cross the boundary as serialized props`;\n          return 0;\n        }\n      }\n      if (staticUses > 0 && hasDynamicJsxCardinality(content, localBindings)) {\n        fallbackReason = `the client boundary count imported from ${specifier} is data-dependent`;\n        costGuardExceeded = true;\n        return 0;\n      }\n      estimatedBoundaryCount += importedBoundaryCount * Math.max(1, staticUses);\n    }\n\n    estimates.set(moduleSourcePath, estimatedBoundaryCount);\n    visiting.delete(moduleSourcePath);\n    return estimatedBoundaryCount;\n  };\n\n  const estimatedBoundaryCount = visit(ownerPath);\n  return {\n    boundaries: Array.from(boundaries.values()),\n    estimatedBoundaryCount,\n    costGuardExceeded,\n    fallbackReason,\n  };\n}\n\nexport function isClientComponentModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).isClientComponent;\n}\n\nexport function shouldHydrateModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).shouldHydrate;\n}\n\nfunction inspectClientModuleMetadata(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n  inspectIslandExport: boolean,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, inspectIslandExport);\n  if (parsed.isClientComponent) {\n    return {\n      isClientComponent: true,\n      shouldHydrate: true,\n      islandStrategy: parsed.islandStrategy ?? \"load\",\n    };\n  }\n\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n  for (const specifier of getImportSpecifiers(content)) {\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata =\n      !specifier.startsWith(\".\") && !specifier.startsWith(\"/\")\n        ? inspectPackageClientBoundary(importedPath, root, visited)\n        : inspectClientModuleMetadata(importedPath, root, visited, false);\n    if (importedMetadata.isClientComponent || importedMetadata.shouldHydrate) {\n      importsClientBoundary = true;\n      if (importedIslandStrategy === null) {\n        importedIslandStrategy = importedMetadata.islandStrategy;\n      } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n        // One route-level React root cannot honor multiple schedules safely.\n        // Fall back to eager hydration when its imported boundaries disagree.\n        importedIslandStrategy = \"load\";\n      }\n    }\n  }\n\n  const shouldHydrate = parsed.hasHydrateExport || importsClientBoundary;\n\n  // React cannot run an async component in a client root: hydrating the route\n  // module would throw, blank the server-rendered HTML, and re-run the page's\n  // data fetching in a loop. Keep async server pages server-only even when\n  // they import client components.\n  if (shouldHydrate && hasAsyncDefaultExport(content)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n      suppressedAsyncHydration: true,\n    };\n  }\n\n  return {\n    isClientComponent: false,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction inspectPackageClientBoundary(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, false);\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n\n  // Package entry points commonly re-export their React implementation from a\n  // relative file. Follow only files inside that package entry graph: scanning\n  // bare dependencies here would incorrectly turn server package APIs into\n  // client boundaries because of unrelated transitive imports.\n  for (const specifier of getImportSpecifiers(content)) {\n    if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) continue;\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata = inspectPackageClientBoundary(importedPath, root, visited);\n    if (!importedMetadata.shouldHydrate) continue;\n    importsClientBoundary = true;\n    if (importedIslandStrategy === null) {\n      importedIslandStrategy = importedMetadata.islandStrategy;\n    } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n      importedIslandStrategy = \"load\";\n    }\n  }\n\n  const shouldHydrate =\n    parsed.isClientComponent || parsed.hasHydrateExport || importsClientBoundary;\n  return {\n    isClientComponent: parsed.isClientComponent,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction getImportSpecifiers(content: string | null): string[] {\n  if (!content) return [];\n\n  const tokens = tokenizeModuleSource(content);\n  const matches = new Set<string>();\n  let braceDepth = 0;\n\n  for (let index = 0; index < tokens.length; index++) {\n    const keyword = tokens[index];\n    if (keyword.value === \"{\") {\n      braceDepth++;\n      continue;\n    }\n    if (keyword.value === \"}\") {\n      braceDepth = Math.max(0, braceDepth - 1);\n      continue;\n    }\n    if (braceDepth !== 0) continue;\n    if (keyword.kind !== \"identifier\" || ![\"import\", \"export\"].includes(keyword.value)) {\n      continue;\n    }\n\n    const previous = tokens[index - 1];\n    if (previous?.value === \".\") continue;\n\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.value === \".\") {\n      continue;\n    }\n\n    let specifier: string | undefined;\n    if (keyword.value === \"import\" && first.kind === \"string\") {\n      specifier = first.value;\n    } else {\n      if (keyword.value === \"export\" && first.value !== \"{\" && first.value !== \"*\") {\n        continue;\n      }\n\n      let fromIndex = -1;\n      for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n        const token = tokens[cursor];\n        if (token.value === \";\") break;\n        if (token.value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n          fromIndex = cursor;\n          break;\n        }\n      }\n      if (fromIndex === -1 || isTypeOnlyNamedClause(tokens, index + 1, fromIndex)) {\n        continue;\n      }\n      specifier = tokens[fromIndex + 1].value;\n    }\n\n    if (!specifier || specifier.startsWith(\"node:\") || specifier.includes(\"?\")) {\n      continue;\n    }\n    matches.add(specifier);\n  }\n\n  return Array.from(matches);\n}\n\nfunction isTypeOnlyNamedClause(\n  tokens: ModuleSourceToken[],\n  startIndex: number,\n  endIndex: number,\n): boolean {\n  if (tokens[startIndex]?.value !== \"{\") return false;\n\n  const closingBraceIndex = tokens.findIndex(\n    (token, index) => index > startIndex && index < endIndex && token.value === \"}\",\n  );\n  if (closingBraceIndex === -1) return false;\n\n  let entryStartsAt = startIndex + 1;\n  for (let index = entryStartsAt; index <= closingBraceIndex; index++) {\n    if (index !== closingBraceIndex && tokens[index]?.value !== \",\") continue;\n    const entry = tokens.slice(entryStartsAt, index);\n    if (entry.length > 0 && entry[0].value !== \"type\") return false;\n    entryStartsAt = index + 1;\n  }\n  return true;\n}\n\nfunction resolveImportedModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n    return resolvePackageModuleSourcePath(importerPath, specifier, root);\n  }\n\n  const candidates = new Set<string>();\n  const basePath = specifier.startsWith(\".\")\n    ? path.resolve(path.dirname(importerPath), specifier)\n    : root\n      ? path.resolve(root, specifier.replace(/^\\/+/, \"\"))\n      : path.resolve(specifier);\n\n  candidates.add(basePath);\n  return resolveSourceCandidate(candidates);\n}\n\nfunction resolvePackageModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  const packageParts = specifier.split(\"/\");\n  const packageName = specifier.startsWith(\"@\")\n    ? packageParts.slice(0, 2).join(\"/\")\n    : packageParts[0];\n  const packageSubpath = packageParts.slice(packageName.startsWith(\"@\") ? 2 : 1).join(\"/\");\n  const packageDirectory = findPackageDirectory(importerPath, packageName, root);\n  if (!packageDirectory) return null;\n\n  const packageJsonPath = path.join(packageDirectory, \"package.json\");\n  const packageJson = readPackageJson(packageJsonPath);\n  const exportKey = packageSubpath ? `./${packageSubpath}` : \".\";\n  const exportTarget = resolvePackageExport(packageJson?.exports, exportKey);\n  const candidates = new Set<string>();\n\n  if (exportTarget?.startsWith(\"./\")) {\n    candidates.add(path.resolve(packageDirectory, exportTarget));\n  }\n  if (packageSubpath) {\n    candidates.add(path.join(packageDirectory, packageSubpath));\n  } else {\n    for (const entry of [packageJson?.browser, packageJson?.module, packageJson?.main]) {\n      if (typeof entry === \"string\") candidates.add(path.resolve(packageDirectory, entry));\n    }\n    candidates.add(path.join(packageDirectory, \"index\"));\n  }\n\n  return resolveSourceCandidate(candidates);\n}\n\nfunction findPackageDirectory(\n  importerPath: string,\n  packageName: string,\n  root?: string,\n): string | null {\n  const searchRoots = new Set<string>();\n  let current = path.dirname(importerPath);\n  while (true) {\n    searchRoots.add(current);\n    const parent = path.dirname(current);\n    if (parent === current) break;\n    current = parent;\n  }\n  if (root) {\n    current = path.resolve(root);\n    while (true) {\n      searchRoots.add(current);\n      const parent = path.dirname(current);\n      if (parent === current) break;\n      current = parent;\n    }\n  }\n\n  for (const searchRoot of searchRoots) {\n    const packageDirectory = path.join(searchRoot, \"node_modules\", packageName);\n    if (fs.existsSync(path.join(packageDirectory, \"package.json\"))) {\n      return packageDirectory;\n    }\n  }\n  return null;\n}\n\nfunction readPackageJson(packageJsonPath: string): Record<string, any> | null {\n  try {\n    return JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n  } catch {\n    return null;\n  }\n}\n\nfunction resolvePackageExport(exportsField: unknown, exportKey: string): string | null {\n  if (typeof exportsField === \"string\") {\n    return exportKey === \".\" ? exportsField : null;\n  }\n  if (Array.isArray(exportsField)) {\n    for (const candidate of exportsField) {\n      const resolved = resolvePackageExport(candidate, exportKey);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!exportsField || typeof exportsField !== \"object\") return null;\n\n  const entries = Object.entries(exportsField as Record<string, unknown>);\n  const subpathExports = entries.some(([key]) => key.startsWith(\".\"));\n  if (subpathExports) {\n    const exact = (exportsField as Record<string, unknown>)[exportKey];\n    if (exact !== undefined) return resolveConditionalExportTarget(exact);\n\n    for (const [key, value] of entries) {\n      const wildcardIndex = key.indexOf(\"*\");\n      if (wildcardIndex === -1) continue;\n      const prefix = key.slice(0, wildcardIndex);\n      const suffix = key.slice(wildcardIndex + 1);\n      if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) continue;\n      const wildcard = exportKey.slice(prefix.length, exportKey.length - suffix.length);\n      const target = resolveConditionalExportTarget(value);\n      return target?.replace(\"*\", wildcard) ?? null;\n    }\n    return null;\n  }\n\n  return exportKey === \".\" ? resolveConditionalExportTarget(exportsField) : null;\n}\n\nfunction resolveConditionalExportTarget(value: unknown): string | null {\n  if (typeof value === \"string\") return value;\n  if (Array.isArray(value)) {\n    for (const candidate of value) {\n      const resolved = resolveConditionalExportTarget(candidate);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!value || typeof value !== \"object\") return null;\n\n  const conditions = value as Record<string, unknown>;\n  // This metadata controls browser hydration, so prefer client-facing exports\n  // regardless of declaration order while retaining Node-only package support.\n  for (const condition of [\"browser\", \"import\", \"module\", \"node\", \"default\", \"require\"]) {\n    if (conditions[condition] === undefined) continue;\n    const resolved = resolveConditionalExportTarget(conditions[condition]);\n    if (resolved) return resolved;\n  }\n  return null;\n}\n\nfunction resolveSourceCandidate(candidates: Iterable<string>): string | null {\n  for (const candidate of candidates) {\n    const paths = [candidate];\n    for (const extension of RESOLVABLE_SOURCE_EXTENSIONS) {\n      paths.push(`${candidate}${extension}`, path.join(candidate, `index${extension}`));\n    }\n    for (const sourcePath of paths) {\n      try {\n        if (fs.statSync(sourcePath).isFile()) return sourcePath;\n      } catch {\n        // Continue to the next candidate.\n      }\n    }\n  }\n  return null;\n}\n","/**\n * Controls when Farm loads and hydrates a server-rendered client boundary.\n *\n * `load` is the compatibility-first default. The deferred strategies keep the\n * server-rendered HTML visible while postponing the boundary's JavaScript.\n */\nexport type FarmIslandStrategy = \"load\" | \"interaction\" | \"visible\" | \"idle\";\n\nexport const FARM_ISLAND_STRATEGIES = [\"load\", \"interaction\", \"visible\", \"idle\"] as const;\n\nexport function isFarmIslandStrategy(value: unknown): value is FarmIslandStrategy {\n  return FARM_ISLAND_STRATEGIES.includes(value as FarmIslandStrategy);\n}\n","import type { FarmIslandStrategy } from \"../island\";\nimport type { RouteRenderingConfig } from \"../ssg\";\n\n/**\n * A build-time rendering decision consumed by the browser router.\n *\n * The browser never inspects module source to choose a rendering path. It\n * executes this compact plan and only evaluates request-specific cache keys at\n * runtime.\n */\nexport interface FarmRouteRenderPlan {\n  version: 1;\n  output: \"html\";\n  navigation: \"html-fragment\";\n  hydration: \"none\" | \"route-island\" | \"layout-island\" | \"route-and-layout-islands\";\n  islandStrategy: FarmIslandStrategy | null;\n  cache: {\n    mode: \"static\" | \"revalidate\" | \"dynamic\";\n    revalidate?: number;\n  };\n}\n\nexport interface FarmRouteRenderPlanInput {\n  pageShouldHydrate?: boolean;\n  layoutShouldHydrate?: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n  rendering?: Pick<RouteRenderingConfig, \"ssg\" | \"ppr\" | \"revalidate\">;\n}\n\n/** Create a deterministic route plan during manifest generation. */\nexport function createFarmRouteRenderPlan(\n  input: FarmRouteRenderPlanInput = {},\n): FarmRouteRenderPlan {\n  const pageShouldHydrate = input.pageShouldHydrate === true;\n  const layoutShouldHydrate = input.layoutShouldHydrate === true;\n  const hydration = pageShouldHydrate\n    ? layoutShouldHydrate\n      ? \"route-and-layout-islands\"\n      : \"route-island\"\n    : layoutShouldHydrate\n      ? \"layout-island\"\n      : \"none\";\n\n  const rendering = input.rendering;\n  const cache = rendering?.ssg\n    ? typeof rendering.revalidate === \"number\" && rendering.revalidate > 0\n      ? { mode: \"revalidate\" as const, revalidate: rendering.revalidate }\n      : { mode: \"static\" as const }\n    : { mode: \"dynamic\" as const };\n\n  return {\n    version: 1,\n    output: \"html\",\n    navigation: \"html-fragment\",\n    hydration,\n    islandStrategy: hydration === \"none\" ? null : (input.islandStrategy ?? \"load\"),\n    cache,\n  };\n}\n\n/**\n * Cache policy for a fragment response. Explicit static rendering is safe to\n * share; dynamic output remains private even when the browser caches it.\n */\nexport function getFarmFragmentCacheControl(plan: FarmRouteRenderPlan): string {\n  if (plan.cache.mode === \"static\") {\n    return \"public, max-age=0, s-maxage=31536000, immutable\";\n  }\n  if (plan.cache.mode === \"revalidate\") {\n    const seconds = Math.max(1, plan.cache.revalidate ?? 1);\n    return `public, max-age=0, s-maxage=${seconds}, stale-while-revalidate=${seconds}`;\n  }\n  return \"private, max-age=0\";\n}\n\nexport function parseFarmLayoutChainHeader(value: string | null): string[] {\n  if (!value || value.length > 8_192) return [];\n  try {\n    const parsed = JSON.parse(value);\n    if (!Array.isArray(parsed) || parsed.length > 64) return [];\n    return parsed.filter(\n      (pattern): pattern is string =>\n        typeof pattern === \"string\" && pattern.startsWith(\"/\") && pattern.length <= 512,\n    );\n  } catch {\n    return [];\n  }\n}\n\nexport function getSharedLayoutPrefixLength(current: string[], next: string[]): number {\n  let index = 0;\n  while (index < current.length && index < next.length && current[index] === next[index]) {\n    index++;\n  }\n  return index;\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\n\nexport const STATIC_METADATA_IMAGE_EXTENSIONS = [\"png\", \"jpg\", \"jpeg\", \"gif\", \"webp\"] as const;\n\nexport type StaticMetadataImageExtension = (typeof STATIC_METADATA_IMAGE_EXTENSIONS)[number];\n\nexport interface StaticMetadataImageInfo {\n  extension: StaticMetadataImageExtension;\n  contentType: string;\n  width: number;\n  height: number;\n  alt?: string;\n  hash: string;\n  byteLength: number;\n}\n\nconst CONTENT_TYPES: Record<StaticMetadataImageExtension, string> = {\n  png: \"image/png\",\n  jpg: \"image/jpeg\",\n  jpeg: \"image/jpeg\",\n  gif: \"image/gif\",\n  webp: \"image/webp\",\n};\n\nexport function isStaticMetadataImageFile(filePath: string): boolean {\n  return getStaticMetadataImageExtension(filePath) !== null;\n}\n\nexport async function inspectStaticMetadataImage(\n  filePath: string,\n): Promise<StaticMetadataImageInfo> {\n  const extension = getStaticMetadataImageExtension(filePath);\n  if (!extension) {\n    throw new Error(`Unsupported static metadata image: ${filePath}`);\n  }\n\n  const bytes = await readFile(filePath);\n  let dimensions: ReturnType<typeof imageSize>;\n\n  try {\n    dimensions = imageSize(bytes);\n  } catch (error) {\n    const reason = error instanceof Error ? error.message : String(error);\n    throw new Error(`Could not read metadata image ${filePath}: ${reason}`);\n  }\n\n  if (!dimensions.width || !dimensions.height) {\n    throw new Error(`Could not determine metadata image dimensions for ${filePath}`);\n  }\n\n  const alt = await readAltText(filePath);\n\n  return {\n    extension,\n    contentType: CONTENT_TYPES[extension],\n    width: dimensions.width,\n    height: dimensions.height,\n    alt,\n    hash: createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 16),\n    byteLength: bytes.byteLength,\n  };\n}\n\nexport function getStaticMetadataImageAltPath(filePath: string): string {\n  return path.join(\n    path.dirname(filePath),\n    `${path.basename(filePath, path.extname(filePath))}.alt.txt`,\n  );\n}\n\nfunction getStaticMetadataImageExtension(filePath: string): StaticMetadataImageExtension | null {\n  const extension = path.extname(filePath).slice(1).toLowerCase();\n  return STATIC_METADATA_IMAGE_EXTENSIONS.includes(extension as StaticMetadataImageExtension)\n    ? (extension as StaticMetadataImageExtension)\n    : null;\n}\n\nasync function readAltText(filePath: string): Promise<string | undefined> {\n  try {\n    const value = (await readFile(getStaticMetadataImageAltPath(filePath), \"utf8\")).trim();\n    return value || undefined;\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return undefined;\n    }\n    throw error;\n  }\n}\n","import type { ParsedRoute } from \"../types\";\nimport { parseRoutePath } from \"../utils\";\n\nexport type RouteSlotConvention = {\n  name: string;\n  ownerRoute: ParsedRoute;\n  route: ParsedRoute;\n  interception: boolean;\n  fallback: boolean;\n};\n\nconst SLOT_SEGMENT = /^@([A-Za-z][A-Za-z0-9_-]*)$/;\n\n/**\n * Parse a page nested below an `@slot` directory without adding the slot name\n * or interception marker to its public URL.\n */\nexport function parseRouteSlotFile(filePath: string): RouteSlotConvention | null {\n  const normalized = filePath.replace(/\\\\/g, \"/\");\n  const parts = normalized.split(\"/\").filter(Boolean);\n  const fileName = parts.at(-1) ?? \"\";\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte)$/, \"\");\n  if (baseName !== \"page\" && baseName !== \"default\") return null;\n\n  const slotIndex = parts.findIndex((part) => SLOT_SEGMENT.test(part));\n  if (slotIndex < 0) return null;\n  if (parts.slice(slotIndex + 1, -1).some((part) => SLOT_SEGMENT.test(part))) {\n    throw new Error(`Nested route slots are not supported in \"${filePath}\"`);\n  }\n\n  const slotMatch = parts[slotIndex]!.match(SLOT_SEGMENT);\n  const name = slotMatch?.[1];\n  if (!name) return null;\n\n  const ownerParts = parts.slice(0, slotIndex);\n  const contentParts = parts.slice(slotIndex + 1, -1);\n  const marker = parseInterceptionMarker(contentParts[0]);\n  let targetBase = ownerParts;\n  let targetParts = contentParts;\n\n  if (marker) {\n    targetBase =\n      marker.root === true ? [] : ownerParts.slice(0, Math.max(0, ownerParts.length - marker.up));\n    targetParts = [...(marker.remainder ? [marker.remainder] : []), ...contentParts.slice(1)];\n  }\n\n  const ownerFile = [...ownerParts, \"layout.tsx\"].join(\"/\");\n  const routeFile = [\n    ...(baseName === \"default\" ? ownerParts : targetBase),\n    ...(baseName === \"default\" ? [] : targetParts),\n    \"page.tsx\",\n  ].join(\"/\");\n\n  return {\n    name,\n    ownerRoute: parseRoutePath(ownerFile || \"layout.tsx\"),\n    route: parseRoutePath(routeFile || \"page.tsx\"),\n    interception: marker !== null,\n    fallback: baseName === \"default\",\n  };\n}\n\nexport function createRouteSlotContainerId(name: string, ownerPattern: string): string {\n  const owner =\n    ownerPattern === \"/\"\n      ? \"root\"\n      : ownerPattern\n          .replace(/^\\//, \"\")\n          .replace(/[^A-Za-z0-9_-]+/g, \"-\")\n          .replace(/^-+|-+$/g, \"\");\n  return `__farm_slot_${name}_${owner || \"root\"}__`;\n}\n\nfunction parseInterceptionMarker(\n  segment: string | undefined,\n): { up: number; root?: boolean; remainder: string } | null {\n  if (!segment) return null;\n  if (segment.startsWith(\"(...)\")) {\n    return {\n      up: 0,\n      root: true,\n      remainder: segment.slice(5),\n    };\n  }\n  if (segment.startsWith(\"(.)\")) {\n    return {\n      up: 0,\n      remainder: segment.slice(3),\n    };\n  }\n\n  let remainder = segment;\n  let up = 0;\n  while (remainder.startsWith(\"(..)\")) {\n    up += 1;\n    remainder = remainder.slice(4);\n  }\n  return up > 0 ? { up, remainder } : null;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport type {\n  FarmConfig,\n  FarmRequest,\n  FarmResponse,\n  LoadingProps,\n  PageProps,\n  RouteModule,\n  SSGPage,\n} from \"../types\";\nimport type { MatchedRouteSlot, RouteManager } from \"../routing/route-manager\";\nimport { logger, toViteModuleId } from \"../utils\";\nimport { collectDevStylesheetUrls } from \"./dev-styles\";\nimport {\n  composeFarmFullDocument,\n  extractFarmFullDocument,\n  opensFarmFullDocument,\n  removeFarmDocumentTitles,\n} from \"./full-document\";\nimport { getClientModuleMetadata } from \"../utils/client-component\";\nimport { Writable } from \"stream\";\nimport {\n  _clearCurrentMiddlewareContext,\n  _clearCurrentMiddlewareData,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n} from \"../middleware/server\";\nimport { getRequestContextSnapshot } from \"../request-context\";\nimport { matchSSGPage, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  farmRequestWantsMarkdown,\n} from \"../app-markdown\";\nimport {\n  getIntegrationProviders,\n  getRegisteredIntegrationAPIManifest,\n  isFarmIntegrationProviderComponentReference,\n} from \"../integrations\";\nimport {\n  _runWithCurrentRequest,\n  createWebRequestFromFarmRequest,\n  resolveFarmRequestURL,\n} from \"./request\";\nimport { createFarmCacheKey, getFarmDataCache, normalizeRevalidatePath } from \"../cache\";\nimport { resolveFarmNotFoundComponentPath } from \"../not-found\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { emitFarmEvent } from \"../observability\";\nimport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n} from \"../navigation-errors\";\nimport {\n  addMetadataImageReference,\n  mergeMetadata,\n  renderMetadataHead,\n  type FarmMetadataImageReference,\n  type MetadataImageKind,\n} from \"../metadata\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"../route-context\";\nimport { searchParamsToObject } from \"../search-params\";\nimport { prepareDeferredData, snapshotDeferredData, type DeferredRecord } from \"../deferred\";\nimport { createFarmDeploymentCookie, FARM_DEPLOYMENT_ID_HEADER } from \"../deployment\";\nimport type { StaticMetadataImageInfo } from \"../static-metadata-image\";\nimport {\n  _runWithFarmI18nRequest,\n  getFarmI18nClientSnapshot,\n  type FarmI18nClientSnapshot,\n  type FarmI18nRuntime,\n} from \"../i18n/server\";\nimport { createFarmLocaleCookie, getFarmLocaleVaryHeaders } from \"../i18n/resolver\";\nimport { localizeFarmHref, localizeFarmPathname } from \"../i18n/routing\";\nimport { sendWebResponse } from \"./response\";\nimport { matchesFarmIfNoneMatch } from \"../server-http\";\nimport { renderFarmFontDevHead } from \"../font-vite\";\nimport { createFarmMetadataImageResponse } from \"../metadata-image\";\nimport { createFarmMetadataRouteResponse } from \"../metadata-route\";\nimport {\n  resolveFarmTrailingSlashRedirect,\n  setFarmTrailingSlashPreference,\n} from \"../trailing-slash\";\nimport { applyFarmBasePath, setFarmBasePath } from \"../base-path\";\nimport { DEFAULT_NOT_FOUND_STYLES } from \"../components/not-found-styles\";\nimport {\n  createDefaultErrorMarkup,\n  getDefaultErrorStatusText,\n  resolveDefaultErrorStatus,\n} from \"../components/error-page\";\nimport { createFarmThemeDocumentParts } from \"../theme/server-runtime\";\nimport { getTheme as getFarmTheme } from \"../theme/server\";\nimport { FARM_VERSION } from \"../version\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  getFarmRendererCapabilities,\n  getFarmRendererComponentExtensions,\n  isReactRenderer,\n  readFarmRendererWebStream,\n  resolveFarmRendererModule,\n  type FarmServerRendererRuntime,\n} from \"../renderer\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createDefaultErrorDiagnostics } from \"./error-diagnostics\";\n\nlet cachedClerkProvider: { ClerkProvider: any } | null = null;\n\nconst importRuntimeModule = new Function(\"specifier\", \"return import(specifier);\") as (\n  specifier: string,\n) => Promise<any>;\n\ninterface CachedSSGPage {\n  html: string;\n  document: boolean;\n}\n\ninterface CachedPPRShell {\n  html: string;\n}\n\nexport function shouldServePrerenderedPage(\n  nodeEnv: string | undefined,\n  method: string | undefined,\n): boolean {\n  if (nodeEnv !== \"production\") return false;\n  const normalizedMethod = (method || \"GET\").toUpperCase();\n  return normalizedMethod === \"GET\" || normalizedMethod === \"HEAD\";\n}\n\nfunction formatSSGManifestError(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\nfunction parseSSGManifest(content: string, manifestPath: string): SSGPage[] {\n  let manifest: unknown;\n\n  try {\n    manifest = JSON.parse(content);\n  } catch (error) {\n    throw new Error(\n      `Failed to parse SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n    );\n  }\n\n  if (!Array.isArray(manifest)) {\n    throw new Error(`Invalid SSG manifest at ${manifestPath}: expected an array of pages.`);\n  }\n\n  for (const [index, page] of manifest.entries()) {\n    if (!page || typeof page !== \"object\" || Array.isArray(page)) {\n      throw new Error(`Invalid SSG manifest at ${manifestPath}: page ${index} must be an object.`);\n    }\n\n    const entry = page as Record<string, unknown>;\n    if (typeof entry.urlPath !== \"string\") {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have a string urlPath.`,\n      );\n    }\n    if (\n      !entry.params ||\n      typeof entry.params !== \"object\" ||\n      Array.isArray(entry.params) ||\n      Object.values(entry.params).some((value) => typeof value !== \"string\")\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have string params.`,\n      );\n    }\n    if (\n      entry.revalidate !== undefined &&\n      (typeof entry.revalidate !== \"number\" ||\n        !Number.isFinite(entry.revalidate) ||\n        entry.revalidate <= 0)\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} revalidate must be a positive number.`,\n      );\n    }\n  }\n\n  return manifest as SSGPage[];\n}\n\ninterface PPRShellCacheOptions {\n  pathname: string;\n  search: string;\n  /**\n   * Locale the shell was rendered in, resolved once when these options are built.\n   * The shell carries `lang`, `dir`, the message catalog and the alternate links, so\n   * it cannot be shared across locales. It is captured rather than read at write\n   * time because the shell is stored from a streaming `onComplete` callback, which\n   * can run outside the request context that resolved the locale.\n   */\n  locale: string;\n  revalidate?: number;\n}\n\nexport interface FarmNavigationFragmentLayout {\n  pattern: string;\n  module: { default?: any };\n}\n\nexport interface FarmNavigationFragmentSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  module: { default?: any };\n  props: Record<string, unknown>;\n}\n\nexport interface FarmNavigationFragmentInput {\n  PageComponent: any;\n  LoadingComponent?: any;\n  pageProps: Record<string, unknown>;\n  params: Record<string, string>;\n  layouts: FarmNavigationFragmentLayout[];\n  /** First destination layout that changed compared with the active shell. */\n  layoutStartIndex?: number;\n  slots?: FarmNavigationFragmentSlot[];\n  pageShouldHydrate: boolean;\n  layoutShouldHydrate: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n}\n\nconst warnedSuppressedAsyncHydrationModules = new Set<string>();\n\nfunction warnSuppressedAsyncHydrationOnce(modulePath: string): void {\n  if (warnedSuppressedAsyncHydrationModules.has(modulePath)) return;\n  warnedSuppressedAsyncHydrationModules.add(modulePath);\n  logger.warn(\n    `${modulePath} is an async server component that imports client components. ` +\n      `React cannot hydrate async components in the browser, so this route stays ` +\n      `server-rendered and its client imports are not interactive. Move the ` +\n      `interactive UI into a \"use client\" child rendered by a synchronous page, ` +\n      `or enable experimental server components support.`,\n  );\n}\n\n// Routes whose layout was observed to render a full `<html>` document. The\n// streaming path can't rewrite a document after its shell is flushed, so once a\n// route is seen to be full-document it is served through the buffered path\n// (which composes the document correctly) on every subsequent request.\nconst fullDocumentRoutes = new Set<string>();\n\nlet warnedFullDocumentLayout = false;\n\nfunction warnFarmFullDocumentLayout(): void {\n  if (warnedFullDocumentLayout) return;\n  warnedFullDocumentLayout = true;\n  logger.warn(\n    `A root layout returned a full <html> document. Farm.js owns the document ` +\n      `shell, so a layout should return a fragment (its children) — like the docs ` +\n      `example — and let the framework provide <html>/<head>/<body>. The document ` +\n      `has been composed into the response, but returning a fragment avoids the ` +\n      `ambiguity and keeps dev and production identical.`,\n  );\n}\n\nfunction hasRequestHeader(req: FarmRequest, name: string): boolean {\n  const value = req.headers[name.toLowerCase()];\n  return Array.isArray(value) ? value.length > 0 : Boolean(value);\n}\n\n/**\n * The request pathname (without query/hash) used as the default canonical URL.\n * Prefers the resolved route path recorded on the request, falling back to the\n * raw request URL.\n */\nfunction getFarmMetadataPathname(req: FarmRequest): string | undefined {\n  const raw = (req as any).__FARM_ROUTE__ || req.url;\n  if (typeof raw !== \"string\" || raw.length === 0) return undefined;\n  const boundary = raw.search(/[?#]/);\n  return boundary === -1 ? raw : raw.slice(0, boundary);\n}\n\nfunction serializeInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction appendResponseHeader(res: FarmResponse, name: string, value: string): void {\n  const current = res.getHeader(name);\n  if (current === undefined) {\n    res.setHeader(name, value);\n  } else if (Array.isArray(current)) {\n    res.setHeader(name, [...current.map(String), value]);\n  } else {\n    res.setHeader(name, [String(current), value]);\n  }\n}\n\nfunction appendResponseVary(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Vary\");\n  const values = new Set(\n    (Array.isArray(current) ? current.join(\",\") : String(current || \"\"))\n      .split(\",\")\n      .map((entry) => entry.trim())\n      .filter(Boolean),\n  );\n  values.add(value);\n  res.setHeader(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction renderI18nAlternateLinks(requestPath: string, snapshot: FarmI18nClientSnapshot): string {\n  if (snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const links = snapshot.locales.map((locale) => {\n    const href = localizeFarmPathname(url.pathname, locale, snapshot);\n    return `<link rel=\"alternate\" hreflang=\"${escapeHtmlAttribute(locale)}\" href=\"${escapeHtmlAttribute(href)}\">`;\n  });\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeHtmlAttribute(\n      localizeFarmPathname(url.pathname, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return links.join(\"\");\n}\n\nfunction createPPRRefreshScript(): string {\n  return `<script>(function(){if(window.__FARM_PPR_REFRESHING__)return;window.__FARM_PPR_REFRESHING__=true;function replaceRoot(html){var doc=new DOMParser().parseFromString(html,\"text/html\");var next=doc.getElementById(\"root\");var current=document.getElementById(\"root\");if(!next||!current)return;current.innerHTML=next.innerHTML;}fetch(window.location.href,{credentials:\"same-origin\",headers:{\"x-farm-ppr-refresh\":\"1\"}}).then(function(response){return response.ok?response.text():null;}).then(function(html){if(html)replaceRoot(html);}).catch(function(){});})();</script>`;\n}\n\nfunction createPreHydrationClickQueueScript(): string {\n  return `<script>(function(){if(window.__FARM_PREHYDRATION_CLICK_QUEUE__)return;var queue=[];window.__FARM_PREHYDRATION_CLICK_QUEUE__=queue;window.__FARM_HYDRATED__=false;document.documentElement.dataset.farmHydrated=\"false\";function isModified(event){return !!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}function closestQueuedTarget(target){while(target&&target!==document.documentElement){if(target.matches&&target.matches('button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]'))return target;target=target.parentElement}return null}document.addEventListener(\"click\",function(event){if(window.__FARM_HYDRATED__)return;if(event.defaultPrevented||event.button!==0||isModified(event))return;var target=closestQueuedTarget(event.target);if(!target||target.closest&&target.closest(\"a[href]\")||target.closest&&target.closest('[data-farm-island-hydrated=\"true\"]'))return;if(queue.some(function(item){return item.target===target}))return;queue.push({target:target,createdAt:Date.now()});document.dispatchEvent(new CustomEvent(\"farm:island-interaction\",{detail:{target:target}}));event.preventDefault();event.stopImmediatePropagation()},true);})();</script>`;\n}\n\nfunction createDocumentFooter(options: {\n  suspenseRevealFallback: string;\n  refreshPPR?: boolean;\n  deferredHydrationScript?: string;\n}): string {\n  return `</div>\n  ${options.suspenseRevealFallback}\n  ${options.refreshPPR ? createPPRRefreshScript() : \"\"}\n  ${options.deferredHydrationScript || \"\"}\n  <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n}\n\nfunction createDeferredHydrationScript(records: readonly DeferredRecord[]): string {\n  if (records.length === 0) return \"\";\n  return `<script>window.__FARM_DEFERRED_DATA__=${serializeInlineValue(\n    snapshotDeferredData(records),\n  )};</script>`;\n}\n\nfunction toMiddlewareMap(input: unknown): Map<string, any> {\n  if (input instanceof Map) {\n    return new Map(input as Map<string, any>);\n  }\n  if (input && typeof input === \"object\") {\n    return new Map(Object.entries(input as Record<string, any>));\n  }\n  return new Map<string, any>();\n}\n\nfunction isWebResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    value instanceof Response &&\n    typeof value.arrayBuffer === \"function\"\n  );\n}\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModule,\n  input: {\n    props: PageProps;\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<\n  PageProps & {\n    search: unknown;\n    data?: unknown;\n    __farmCanonicalPath?: string;\n    __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n    __farmRoutePropsResolved?: true;\n  }\n> {\n  const resolveRouteProps = (routeModule as any).__farmResolveRouteProps;\n  if (typeof resolveRouteProps === \"function\") {\n    // Resolve the top-level route state before starting the HTTP stream. It can\n    // still return explicit defer() values for nested Suspense boundaries, but\n    // redirects, notFound(), and failures must retain their real HTTP status.\n    return await resolveRouteProps(input.props);\n  }\n\n  if ((routeModule as any).__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = (routeModule as any).__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params: params as Record<string, string>,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction createRouteStateProps(input: {\n  params: Record<string, string>;\n  searchParamsObject: Record<string, string | string[] | undefined>;\n  path: string;\n  middlewareMap: Map<string, any>;\n  pluginExposedContext: Map<string, any>;\n}): LoadingProps {\n  return {\n    params: input.params,\n    search: input.searchParamsObject,\n    searchParams: Promise.resolve(input.searchParamsObject),\n    path: input.path,\n    middleware: input.middlewareMap.size > 0 ? { data: input.middlewareMap } : undefined,\n    context: input.pluginExposedContext.size > 0 ? { data: input.pluginExposedContext } : undefined,\n  };\n}\n\nexport class ServerRenderer {\n  private config: Required<FarmConfig>;\n  private routeManager: RouteManager;\n  private ssgManifest: SSGPage[] = [];\n  private dataCache = getFarmDataCache();\n  private i18nRuntime?: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n  private rendererRuntime!: FarmServerRendererRuntime;\n\n  constructor(\n    config: Required<FarmConfig>,\n    routeManager: RouteManager,\n    i18nRuntime?: FarmI18nRuntime,\n    viteServer?: ViteDevServer,\n  ) {\n    this.config = config;\n    this.routeManager = routeManager;\n    this.i18nRuntime = i18nRuntime;\n    this.viteServer = viteServer;\n    this.loadSSGManifest();\n  }\n\n  async initialize(): Promise<void> {\n    if (this.rendererRuntime) return;\n\n    if (this.config.notFound?.component?.trim()) {\n      resolveFarmNotFoundComponentPath(this.config, getFarmAppDirectories(this.config));\n    }\n\n    const loaded = isReactRenderer(this.config.renderer)\n      ? await import(\"../renderer/react/server\")\n      : this.viteServer\n        ? await this.viteServer.ssrLoadModule(this.config.renderer.server)\n        : await import(\n            pathToFileURL(\n              resolveFarmRendererModule(\n                this.config.root || process.cwd(),\n                this.config.renderer.server,\n              ),\n            ).href\n          );\n    const runtime = loaded as Partial<FarmServerRendererRuntime>;\n    const required = [\"createElement\", \"isValidElement\", \"renderToString\"] as const;\n    for (const key of required) {\n      if (typeof runtime[key] !== \"function\") {\n        throw new Error(\n          `Renderer \\`${this.config.renderer.name}\\` server module must export ${key}().`,\n        );\n      }\n    }\n\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    if (capabilities.streaming.node && typeof runtime.renderToPipeableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Node streaming but its server module does not export renderToPipeableStream().`,\n      );\n    }\n    if (capabilities.streaming.web && typeof runtime.renderToReadableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Web streaming but its server module does not export renderToReadableStream().`,\n      );\n    }\n\n    this.rendererRuntime = runtime as FarmServerRendererRuntime;\n    this.routeManager.setRendererRuntime?.(this.rendererRuntime);\n  }\n\n  private createPageBoundary(\n    pageElement: unknown,\n    options: {\n      pageShouldHydrate: boolean;\n      layoutShouldHydrate: boolean;\n      islandStrategy?: FarmIslandStrategy | null;\n    },\n  ): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        id: \"__farm_page__\",\n        \"data-farm-segment\": \"page\",\n        \"data-farm-client\": options.pageShouldHydrate ? \"true\" : \"false\",\n        ...(options.layoutShouldHydrate ? { \"data-farm-layout-client\": \"true\" } : {}),\n        \"data-farm-island\": \"page\",\n        \"data-farm-island-strategy\": options.islandStrategy || \"load\",\n      },\n      pageElement,\n    );\n  }\n\n  /// Stylesheets the app imported through JS (fontsource packages, component\n  /// CSS) that the document must link alongside globals.css — see #658.\n  private collectDevStyleHrefs(): string[] {\n    const graph = this.viteServer?.moduleGraph;\n    if (!graph) return [];\n    return collectDevStylesheetUrls(graph.idToModuleMap.values());\n  }\n\n  private collectDevStyleLinks(): string[] {\n    return this.collectDevStyleHrefs().map(\n      (href) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(href)}\">`,\n    );\n  }\n\n  private createLayoutBoundary(pattern: string, layoutElement: unknown): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        \"data-farm-layout-boundary\": \"true\",\n        \"data-farm-layout-pattern\": pattern,\n        style: { display: \"contents\" },\n      },\n      layoutElement,\n    );\n  }\n\n  private wrapClientGraph(element: unknown): unknown {\n    const getIsolatedClientBoundaryModules = this.routeManager.getIsolatedClientBoundaryModules;\n    if (\n      !this.rendererRuntime.wrapClientGraph ||\n      typeof getIsolatedClientBoundaryModules !== \"function\" ||\n      getIsolatedClientBoundaryModules.call(this.routeManager, this.config.root).size === 0\n    ) {\n      return element;\n    }\n    return this.rendererRuntime.wrapClientGraph(element);\n  }\n\n  private async renderElementToCompleteHTML(element: unknown): Promise<string> {\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    const renderToPipeableStream = capabilities.streaming.node\n      ? this.rendererRuntime.renderToPipeableStream\n      : undefined;\n\n    if (renderToPipeableStream) {\n      return await new Promise<string>((resolve, reject) => {\n        const chunks: Buffer[] = [];\n        let started = false;\n        const writable = new Writable({\n          write(chunk, _encoding, callback) {\n            chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n            callback();\n          },\n        });\n        writable.once(\"finish\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n        writable.once(\"error\", reject);\n\n        const stream = renderToPipeableStream(element, {\n          onShellReady() {\n            started = true;\n            stream.pipe(writable);\n          },\n          onShellError(error) {\n            reject(error);\n          },\n          onError(error) {\n            if (!started) reject(error);\n          },\n        });\n      });\n    }\n\n    if (capabilities.streaming.web && this.rendererRuntime.renderToReadableStream) {\n      const stream = await this.rendererRuntime.renderToReadableStream(element);\n      return await readFarmRendererWebStream(stream);\n    }\n\n    return await this.rendererRuntime.renderToString(element);\n  }\n\n  /**\n   * Buffered render carrying document-head markup for renderers that emit it\n   * during render (e.g. <svelte:head>). Other renderers return an empty head.\n   */\n  private async renderElementToDocumentParts(\n    element: unknown,\n  ): Promise<{ html: string; head: string }> {\n    if (this.rendererRuntime.renderToStringWithHead) {\n      const rendered = await this.rendererRuntime.renderToStringWithHead(element);\n      return { html: rendered.html, head: rendered.head || \"\" };\n    }\n    return { html: await this.rendererRuntime.renderToString(element), head: \"\" };\n  }\n\n  /**\n   * Render the route tree used by client navigation without producing a second\n   * document response. Layout markers let the browser preserve the longest\n   * common shell and replace only the first changed boundary.\n   */\n  async renderNavigationFragment(input: FarmNavigationFragmentInput): Promise<string> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    let element = this.rendererRuntime.createElement(input.PageComponent, input.pageProps);\n    if (input.LoadingComponent) {\n      element = this.rendererRuntime.createElement(\n        this.rendererRuntime.Suspense,\n        {\n          fallback: this.rendererRuntime.createElement(input.LoadingComponent, {\n            params: input.params,\n            path: (input.pageProps as any).path,\n          }),\n        },\n        element,\n      );\n    }\n    if (input.pageShouldHydrate && !input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n    element = this.createPageBoundary(element, {\n      pageShouldHydrate: input.pageShouldHydrate,\n      layoutShouldHydrate: input.layoutShouldHydrate,\n      islandStrategy: input.islandStrategy,\n    });\n\n    const layoutStartIndex = Math.max(\n      0,\n      Math.min(input.layoutStartIndex ?? 0, input.layouts.length),\n    );\n    for (let index = input.layouts.length - 1; index >= layoutStartIndex; index--) {\n      const layout = input.layouts[index]!;\n      const LayoutComponent = layout.module.default;\n      if (!LayoutComponent) continue;\n      const slotProps: Record<string, unknown> = {};\n      for (const slot of input.slots || []) {\n        if (slot.ownerPattern !== layout.pattern || !slot.module.default) continue;\n        let slotElement = this.rendererRuntime.createElement(slot.module.default, slot.props);\n        slotElement = this.wrapClientGraph(slotElement);\n        slotProps[slot.name] = this.rendererRuntime.createElement(\n          \"div\",\n          {\n            id: slot.containerId,\n            \"data-farm-route-slot\": slot.name,\n            \"data-farm-slot-owner\": slot.ownerPattern,\n          },\n          slotElement,\n        );\n      }\n      element = this.rendererRuntime.createElement(LayoutComponent, {\n        children: element,\n        params: input.params,\n        ...slotProps,\n      });\n      element = this.createLayoutBoundary(layout.pattern, element);\n    }\n\n    if (input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n\n    return this.renderElementToCompleteHTML(await this.wrapWithIntegrationProviders(element));\n  }\n\n  async runWithRequestContext<T>(request: Request, fn: () => T | Promise<T>): Promise<T> {\n    return _runWithCurrentRequest(request, () =>\n      this.i18nRuntime?.config.enabled\n        ? _runWithFarmI18nRequest(this.i18nRuntime, request, fn, {\n            redirect: false,\n          })\n        : fn(),\n    );\n  }\n\n  async resolveRouteContext(input: {\n    request: Request;\n    rawRequest?: FarmRequest;\n    params: Record<string, string>;\n    search: Record<string, string | string[] | undefined>;\n    path: string;\n  }): Promise<unknown> {\n    return resolveFarmRouteContext(this.config, input);\n  }\n\n  /**\n   * Load SSG manifest from build output\n   */\n  private loadSSGManifest(): void {\n    const manifestPath = path.join(this.config.root, this.config.outDir, \"__ssg_manifest.json\");\n    let content: string;\n\n    try {\n      content = fs.readFileSync(manifestPath, \"utf-8\");\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n        return;\n      }\n\n      throw new Error(\n        `Failed to read SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n      );\n    }\n\n    this.ssgManifest = parseSSGManifest(content, manifestPath);\n    logger.info(`Loaded SSG manifest: ${this.ssgManifest.length} pages`);\n  }\n\n  /**\n   * Check if a path should be served from SSG cache\n   */\n  private async shouldServeSSG(pathname: string): Promise<SSGPage | null> {\n    const ssgPage = matchSSGPage(pathname, this.ssgManifest);\n    if (!ssgPage) return null;\n\n    const cached = await this.getCachedSSGPage(pathname);\n    if (cached && (await this.dataCache.isStaleAsync(cached))) {\n      // Stale - needs revalidation (serve stale, regenerate in background)\n      this.regenerateSSGPage(ssgPage);\n    }\n\n    return ssgPage;\n  }\n\n  private getSSGCacheKey(urlPath: string): string {\n    return createFarmCacheKey([\"ssg\", normalizeRevalidatePath(urlPath)]);\n  }\n\n  private getPPRCacheKey(pathname: string, search = \"\", locale = \"\"): string {\n    return createFarmCacheKey([\"ppr\", locale, normalizeRevalidatePath(pathname), search]);\n  }\n\n  private getCachedSSGPage(urlPath: string) {\n    return this.dataCache.getEntryAsync<CachedSSGPage>(this.getSSGCacheKey(urlPath), {\n      allowStale: true,\n    });\n  }\n\n  private async cacheSSGPage(\n    page: SSGPage,\n    html: string,\n    options: { document: boolean; createdAt?: number },\n  ): Promise<void> {\n    await this.dataCache.setAsync(\n      this.getSSGCacheKey(page.urlPath),\n      { html, document: options.document },\n      {\n        createdAt: options.createdAt,\n        paths: [page.urlPath],\n        tags: [\"ssg\"],\n        revalidate: page.revalidate ?? false,\n      },\n    );\n  }\n\n  private getCachedPPRShell(pathname: string, search: string, locale = \"\") {\n    return this.dataCache.getEntryAsync<CachedPPRShell>(\n      this.getPPRCacheKey(pathname, search, locale),\n    );\n  }\n\n  private async cachePPRShell(options: PPRShellCacheOptions, html: string): Promise<void> {\n    const key = this.getPPRCacheKey(options.pathname, options.search, options.locale);\n    await this.dataCache.setAsync(\n      key,\n      { html },\n      {\n        paths: [options.pathname],\n        tags: [\"ppr\"],\n        revalidate: options.revalidate ?? false,\n      },\n    );\n    emitFarmEvent({\n      type: \"ppr.shell.cached\",\n      route: options.pathname,\n      key,\n      revalidate: options.revalidate,\n    });\n  }\n\n  private getPPRShellBypassReason(\n    req: FarmRequest,\n    middlewareMap: Map<string, any>,\n    middlewareContext: Map<string, any>,\n    pluginExposedContext: Map<string, any>,\n  ): string | undefined {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      return \"method\";\n    }\n\n    if (req.headers.cookie) {\n      return \"cookie\";\n    }\n\n    if (req.headers.authorization) {\n      return \"authorization\";\n    }\n\n    if (hasRequestHeader(req, \"x-farm-ppr-refresh\")) {\n      return \"refresh\";\n    }\n\n    if (middlewareMap.size > 0) {\n      return \"middleware-data\";\n    }\n\n    if (middlewareContext.size > 0) {\n      return \"middleware-context\";\n    }\n\n    if (pluginExposedContext.size > 0) {\n      return \"plugin-context\";\n    }\n\n    return undefined;\n  }\n\n  private getPPRHeaders(status: \"hit\" | \"miss\" | \"bypass\", revalidate?: number) {\n    const headers: Record<string, string> = {\n      \"X-Farm-PPR\": status,\n    };\n\n    if (status === \"bypass\") {\n      headers[\"Cache-Control\"] = \"private, no-store\";\n      return headers;\n    }\n\n    if (typeof revalidate === \"number\" && revalidate > 0) {\n      headers[\"Cache-Control\"] = `s-maxage=${revalidate}, stale-while-revalidate`;\n    }\n\n    return headers;\n  }\n\n  private serveCachedPPRShell(res: FarmResponse, shell: CachedPPRShell, revalidate?: number): void {\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(this.getPPRHeaders(\"hit\", revalidate))) {\n      res.setHeader(key, value);\n    }\n    res.write(shell.html);\n    res.end();\n  }\n\n  /**\n   * Regenerate an SSG page in the background (ISR)\n   */\n  private async regenerateSSGPage(page: SSGPage): Promise<void> {\n    try {\n      // This runs in the background - don't await\n      setImmediate(async () => {\n        try {\n          const mod = await this.routeManager.loadRouteModule(page.filePath);\n          if (!mod?.default) return;\n\n          const { route, layouts } = this.routeManager.matchRoute(page.urlPath);\n          const layoutModules = await Promise.all(\n            layouts.map((l) => this.routeManager.loadLayoutModule(l.modulePath)),\n          );\n          const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n\n          const PageComponent = mod.default;\n          const pageProps = {\n            params: page.params,\n            searchParams: Promise.resolve({}),\n            path: page.urlPath,\n          };\n\n          let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n          const pageMetadata = routeManifest.routes.find(\n            (entry) => entry.pattern === route?.pattern,\n          ) ?? {\n            shouldHydrate: false,\n            islandStrategy: null,\n          };\n          const layoutMetadata = layouts.map(\n            (layout) =>\n              routeManifest.layouts.find((entry) => entry.pattern === layout.pattern) ?? {\n                shouldHydrate: false,\n                islandStrategy: null,\n              },\n          );\n          const layoutShouldHydrate = layoutMetadata.some((metadata) => metadata.shouldHydrate);\n          pageElement = this.createPageBoundary(pageElement, {\n            pageShouldHydrate: pageMetadata.shouldHydrate,\n            layoutShouldHydrate,\n            islandStrategy: pageMetadata.islandStrategy,\n          });\n\n          for (let i = layoutModules.length - 1; i >= 0; i--) {\n            const layoutModule = layoutModules[i];\n            const LayoutComponent = layoutModule.default;\n            pageElement = this.rendererRuntime.createElement(LayoutComponent, {\n              children: pageElement,\n              params: page.params,\n            });\n            pageElement = this.createLayoutBoundary(layouts[i]!.pattern, pageElement);\n          }\n\n          const html = await this.rendererRuntime.renderToString(\n            await this.wrapWithIntegrationProviders(pageElement),\n          );\n\n          // Resolve metadata so the regenerated document keeps its title and\n          // meta/OG tags instead of falling back to the framework default\n          // (\"Farm.js App\"). Without this, a static route served from the ISR\n          // cache loses its metadata after the first revalidation (issue #1018).\n          const mergedMetadata = await this.resolveRouteMetadata({\n            layoutModules,\n            routeModule: mod,\n            pageProps: pageProps as unknown as PageProps,\n            pathname: page.urlPath,\n          });\n          const { title, tags, hasFavicon } = renderMetadataHead(mergedMetadata);\n          const metadataHead = `${\n            hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">\\n  '\n          }<title>${title}</title>${tags}`;\n          const fullDocument = this.createFullHTML(\n            html,\n            pageMetadata.shouldHydrate === true,\n            page.urlPath,\n            metadataHead,\n          );\n\n          await this.cacheSSGPage(page, fullDocument, { document: true });\n\n          logger.info(`ISR: Regenerated ${page.urlPath}`);\n        } catch (error) {\n          logger.error(`ISR regeneration failed for ${page.urlPath}: ${error}`);\n        }\n      });\n    } catch (error) {\n      logger.error(`ISR trigger failed: ${error}`);\n    }\n  }\n\n  /**\n   * Serve a pre-rendered SSG page\n   */\n  private async serveSSGPage(req: FarmRequest, res: FarmResponse, page: SSGPage): Promise<boolean> {\n    // Check cache first (for ISR)\n    const cached = await this.getCachedSSGPage(page.urlPath);\n    if (cached) {\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      res.setHeader(\"X-Farm-SSG\", \"cached\");\n      if (page.revalidate) {\n        res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n      }\n      res.write(\n        cached.value.document\n          ? cached.value.html\n          : this.createFullHTML(cached.value.html, false, page.urlPath),\n      );\n      res.end();\n      return true;\n    }\n\n    // Try to read from file system (production)\n    try {\n      const htmlPath =\n        page.urlPath === \"/\"\n          ? path.join(this.config.root, this.config.outDir, \"client\", \"index.html\")\n          : path.join(this.config.root, this.config.outDir, \"client\", page.urlPath + \".html\");\n\n      if (fs.existsSync(htmlPath)) {\n        const stat = fs.statSync(htmlPath);\n        const html = fs.readFileSync(htmlPath, \"utf-8\");\n        await this.cacheSSGPage(page, html, {\n          document: true,\n          createdAt: stat.mtimeMs,\n        });\n        const fileCacheEntry = await this.getCachedSSGPage(page.urlPath);\n        if (fileCacheEntry && (await this.dataCache.isStaleAsync(fileCacheEntry))) {\n          this.regenerateSSGPage(page);\n        }\n\n        res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n        res.setHeader(\"X-Farm-SSG\", \"file\");\n        if (page.revalidate) {\n          res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n        }\n        res.write(html);\n        res.end();\n        return true;\n      }\n    } catch (error) {\n      logger.error(`Failed to serve SSG page ${page.urlPath}: ${error}`);\n    }\n\n    return false;\n  }\n\n  async renderPage(req: FarmRequest, res: FarmResponse): Promise<void> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    const request = createWebRequestFromFarmRequest(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const runtime = this.i18nRuntime;\n\n    if (runtime?.config.enabled) {\n      const resolution = runtime.resolveRequest(request);\n      const varyHeaders = getFarmLocaleVaryHeaders(runtime.config, resolution);\n      for (const header of varyHeaders) appendResponseVary(res, header);\n      if (resolution.persist) {\n        appendResponseHeader(\n          res,\n          \"Set-Cookie\",\n          createFarmLocaleCookie(resolution.locale, runtime.config),\n        );\n      }\n      if (resolution.redirect && (request.method === \"GET\" || request.method === \"HEAD\")) {\n        res.statusCode = 307;\n        res.setHeader(\"Location\", resolution.redirect);\n        if (varyHeaders.length > 0) res.setHeader(\"Cache-Control\", \"private, no-store\");\n        res.end();\n        return;\n      }\n    }\n\n    return this.runWithRequestContext(request, () => this.renderPageInContext(req, res));\n  }\n\n  private async renderPageInContext(req: FarmRequest, res: FarmResponse): Promise<void> {\n    const renderStartTime = Date.now();\n    let pathname = \"/\";\n    let params: Record<string, string> = {};\n    let layouts: Array<{ modulePath: string; pattern: string }> = [];\n    let routeSlots: MatchedRouteSlot[] = [];\n    let searchParamsObject: Record<string, string | string[] | undefined> = {};\n    let middlewareMap = new Map<string, any>();\n    let middlewareContext = new Map<string, any>();\n    let pluginExposedContext = new Map<string, any>();\n    let errorBoundaryEntry: { modulePath: string } | null = null;\n    let pprRefreshRoute: string | null = null;\n\n    const completeRender = (status = res.statusCode || 200, route = pathname) => {\n      emitFarmEvent({\n        type: \"render.complete\",\n        route,\n        pathname,\n        status,\n        durationMs: Date.now() - renderStartTime,\n      });\n    };\n\n    try {\n      const url = resolveFarmRequestURL(req, { trustProxy: this.config.server?.trustProxy });\n      pathname = url.pathname;\n      emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n      searchParamsObject = searchParamsToObject(url.searchParams);\n\n      const metadataRouteMatch = this.routeManager.matchMetadataRoute(pathname);\n      if (metadataRouteMatch) {\n        await this.renderMetadataRoute(req, res, metadataRouteMatch);\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      const metadataImageMatch = this.routeManager.matchMetadataImage(pathname);\n      if (metadataImageMatch) {\n        await this.renderMetadataImage(req, res, {\n          pathname,\n          searchParamsObject,\n          ...metadataImageMatch,\n        });\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      this.applyDeploymentHeaders(req, res);\n\n      const match = this.routeManager.matchRoute(pathname);\n      if (match.route) {\n        const redirectLocation = resolveFarmTrailingSlashRedirect(url, this.config.trailingSlash);\n        if (redirectLocation) {\n          res.statusCode = 308;\n          res.setHeader(\"Location\", redirectLocation);\n          res.end();\n          completeRender(308, match.route.pattern);\n          return;\n        }\n      }\n\n      // Pre-rendered HTML only represents retrieval requests. Other methods must\n      // continue through the live route so their request semantics are preserved.\n      if (shouldServePrerenderedPage(process.env.NODE_ENV, req.method)) {\n        const ssgPage = await this.shouldServeSSG(pathname);\n        if (ssgPage) {\n          const served = await this.serveSSGPage(req, res, ssgPage);\n          if (served) {\n            completeRender(res.statusCode || 200, ssgPage.urlPath);\n            return;\n          }\n        }\n      }\n\n      // Match route\n      const route = match.route;\n      params = match.params;\n      layouts = match.layouts;\n      routeSlots = match.slots ?? [];\n\n      if (!route) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        await this.render404(req, res);\n        completeRender(404);\n        return;\n      }\n\n      emitFarmEvent({\n        type: \"route.matched\",\n        pathname,\n        route: route.pattern,\n        params,\n      });\n\n      const loadingBoundaryEntry = this.routeManager.getMatchingLoading(pathname);\n      errorBoundaryEntry = this.routeManager.getMatchingError(pathname);\n\n      middlewareMap = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_DATA__);\n      middlewareContext = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_CONTEXT__);\n      pluginExposedContext = getRequestContextSnapshot(req as object, {\n        exposedOnly: true,\n      });\n      const currentRequest = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const routeContext = await this.resolveRouteContext({\n        request: currentRequest,\n        rawRequest: req,\n        params,\n        search: searchParamsObject,\n        path: pathname,\n      });\n\n      // Load route module\n      const routeModule = await this.routeManager.loadRouteModule(route.modulePath);\n\n      if (!routeModule.default) {\n        throw new Error(`Route module ${route.modulePath} does not export a default component`);\n      }\n\n      // Create page props with searchParams as plain object and middleware data\n      const rawPageProps: PageProps = withFarmRouteContext(\n        {\n          params,\n          searchParams: Promise.resolve(searchParamsObject),\n          path: pathname,\n          middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n          context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n        } as PageProps & { search: unknown },\n        routeContext,\n      );\n      const programmaticRouteComponents = (routeModule as any).__farmRouteComponents as\n        | {\n            error?: any;\n            notFound?: any;\n          }\n        | undefined;\n      let PageComponent = routeModule.default;\n      let pageProps: PageProps & {\n        search: unknown;\n        data?: unknown;\n        error?: unknown;\n        __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n        __farmRoutePropsResolved?: true;\n      };\n\n      try {\n        pageProps = await parseRouteModuleProps(routeModule, {\n          props: rawPageProps,\n          search: searchParamsObject,\n          routePath: route.pattern,\n        });\n      } catch (error) {\n        if (isFarmRedirectError(error)) throw error;\n\n        const routeStateProps = {\n          ...rawPageProps,\n          search: searchParamsObject,\n          searchParams: Promise.resolve(searchParamsObject),\n          error,\n        };\n\n        if (isFarmNotFoundError(error) && programmaticRouteComponents?.notFound) {\n          res.statusCode = 404;\n          PageComponent = programmaticRouteComponents.notFound;\n          pageProps = routeStateProps;\n        } else if (programmaticRouteComponents?.error) {\n          res.statusCode = 500;\n          PageComponent = programmaticRouteComponents.error;\n          pageProps = routeStateProps;\n        } else {\n          throw error;\n        }\n      }\n\n      const renderingConfig = await resolveRouteRenderingConfigFromFile(\n        routeModule,\n        route.modulePath,\n        { experimentalPPR: this.config.experimental?.ppr === true },\n      );\n      const pprBypassReason = renderingConfig.ppr\n        ? this.getPPRShellBypassReason(req, middlewareMap, middlewareContext, pluginExposedContext)\n        : undefined;\n      const canCachePPRShell = renderingConfig.ppr && !pprBypassReason;\n      const pprShellOptions: PPRShellCacheOptions | undefined = canCachePPRShell\n        ? {\n            pathname,\n            search: url.search,\n            locale: getFarmI18nClientSnapshot()?.locale ?? \"\",\n            revalidate: renderingConfig.revalidate,\n          }\n        : undefined;\n\n      if (renderingConfig.ppr && pprBypassReason) {\n        emitFarmEvent({\n          type: \"ppr.shell.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n        emitFarmEvent({\n          type: \"cache.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n\n        if (pprBypassReason === \"refresh\") {\n          pprRefreshRoute = pathname;\n          emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n        }\n      }\n\n      if (pprShellOptions) {\n        // Same locale for the lookup and the later store, so the two cannot diverge.\n        const pprCacheKey = this.getPPRCacheKey(pathname, url.search, pprShellOptions.locale);\n        const cachedPPRShell = await this.getCachedPPRShell(\n          pathname,\n          url.search,\n          pprShellOptions.locale,\n        );\n        if (cachedPPRShell) {\n          emitFarmEvent({\n            type: \"ppr.shell.hit\",\n            route: pathname,\n            key: pprCacheKey,\n          });\n          this.serveCachedPPRShell(res, cachedPPRShell.value, renderingConfig.revalidate);\n          completeRender(res.statusCode || 200, pathname);\n          return;\n        }\n        emitFarmEvent({\n          type: \"ppr.shell.miss\",\n          route: pathname,\n          key: pprCacheKey,\n        });\n      }\n\n      let LoadingFallbackComponent: any = null;\n      if (loadingBoundaryEntry) {\n        const loadingModule = await this.routeManager.loadRouteModule(\n          loadingBoundaryEntry.modulePath,\n        );\n        if (loadingModule.default) {\n          LoadingFallbackComponent = loadingModule.default;\n        }\n      }\n\n      let ErrorFallbackComponent: any = null;\n      if (errorBoundaryEntry) {\n        const errorModule = await this.routeManager.loadRouteModule(errorBoundaryEntry.modulePath);\n        if (errorModule.default) {\n          ErrorFallbackComponent = errorModule.default;\n        }\n      }\n\n      // Hydration decisions are compiled into a manifest and reused on requests.\n      // Development HMR invalidates this cache when a route module changes.\n      const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n      const routeManifestEntry = routeManifest.routes.find(\n        (entry) => entry.pattern === route.pattern,\n      );\n      const moduleMetadata =\n        routeManifestEntry || getClientModuleMetadata(route.modulePath, this.config.root);\n      const isClientComponent = moduleMetadata.isClientComponent;\n      const renderedRouteSlots = await Promise.all(\n        routeSlots.map(async (slot) => {\n          const slotModule = await this.routeManager.loadRouteModule(slot.route.modulePath);\n          if (!slotModule.default) {\n            throw new Error(\n              `Route slot \"${slot.name}\" module ${slot.route.modulePath} does not export a default component`,\n            );\n          }\n\n          const slotContext = await this.resolveRouteContext({\n            request: currentRequest,\n            rawRequest: req,\n            params: slot.params,\n            search: searchParamsObject,\n            path: pathname,\n          });\n          const rawSlotProps = withFarmRouteContext(\n            {\n              params: slot.params,\n              searchParams: Promise.resolve(searchParamsObject),\n              path: pathname,\n              middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n              context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n            } as PageProps & { search: unknown },\n            slotContext,\n          );\n          const slotProps = await parseRouteModuleProps(slotModule, {\n            props: rawSlotProps,\n            search: searchParamsObject,\n            routePath: slot.route.pattern,\n          });\n          const metadata = routeManifest.slots.find(\n            (entry) =>\n              entry.name === slot.name &&\n              entry.ownerPattern === slot.ownerPattern &&\n              entry.pattern === slot.route.pattern,\n          ) ?? {\n            isClientComponent: false,\n            shouldHydrate: false,\n          };\n\n          return {\n            ...slot,\n            module: slotModule,\n            props: slotProps,\n            isClientComponent: metadata.isClientComponent,\n            shouldHydrate: metadata.shouldHydrate,\n          };\n        }),\n      );\n      const shouldHydrate = moduleMetadata.shouldHydrate;\n      if (moduleMetadata.suppressedAsyncHydration) {\n        warnSuppressedAsyncHydrationOnce(route.modulePath);\n      }\n      const layoutHydrationMetadata = layouts.map((layout) => {\n        const manifestEntry = routeManifest.layouts.find(\n          (entry) => entry.pattern === layout.pattern,\n        ) as\n          | {\n              isClientComponent?: boolean;\n              shouldHydrate?: boolean;\n              islandStrategy?: \"load\" | \"interaction\" | \"visible\" | \"idle\" | null;\n              hasIsolatedClientBoundaries?: boolean;\n            }\n          | undefined;\n        if (typeof manifestEntry?.shouldHydrate === \"boolean\") {\n          return {\n            isClientComponent: manifestEntry.isClientComponent === true,\n            shouldHydrate: manifestEntry.shouldHydrate,\n            islandStrategy: manifestEntry.islandStrategy ?? null,\n            ...(manifestEntry.hasIsolatedClientBoundaries === true\n              ? { hasIsolatedClientBoundaries: true }\n              : {}),\n          };\n        }\n        return {\n          isClientComponent: false,\n          shouldHydrate: false,\n          islandStrategy: null,\n        };\n      });\n      const shouldHydrateLayout = layoutHydrationMetadata.some(\n        (metadata) => metadata.shouldHydrate,\n      );\n      const clientLayouts = layouts.map((layout, index) => ({\n        pattern: layout.pattern,\n        modulePath: toViteModuleId(layout.modulePath, this.config.root),\n        shouldHydrate: layoutHydrationMetadata[index]?.shouldHydrate === true,\n        islandStrategy: layoutHydrationMetadata[index]?.islandStrategy ?? null,\n        ...(layoutHydrationMetadata[index]?.hasIsolatedClientBoundaries === true\n          ? { hasIsolatedClientBoundaries: true }\n          : {}),\n      }));\n      const hydrationStrategies = [\n        ...(shouldHydrate && moduleMetadata.islandStrategy ? [moduleMetadata.islandStrategy] : []),\n        ...layoutHydrationMetadata.flatMap((metadata) =>\n          metadata.shouldHydrate && metadata.islandStrategy ? [metadata.islandStrategy] : [],\n        ),\n      ];\n      const hydrationIslandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] ?? \"load\")\n        : \"load\";\n      const hasHydratableRouteSlots = renderedRouteSlots.some(\n        (slot) => slot.isClientComponent || slot.shouldHydrate,\n      );\n      const hasIsolatedClientBoundaries =\n        routeManifestEntry?.hasIsolatedClientBoundaries === true ||\n        layoutHydrationMetadata.some((metadata) => metadata.hasIsolatedClientBoundaries === true);\n\n      (req as any).__FARM_PAGE_PATH__ = route.modulePath;\n      (req as any).__FARM_ROUTE__ = pathname;\n      (req as any).__FARM_IS_CLIENT_COMPONENT__ = isClientComponent;\n      (req as any).__FARM_PAGE_SHOULD_HYDRATE__ = shouldHydrate;\n      (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ = shouldHydrateLayout;\n      (req as any).__FARM_LAYOUTS__ = clientLayouts;\n      if (hasIsolatedClientBoundaries) {\n        (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\n      }\n      (req as any).__FARM_SHOULD_HYDRATE__ =\n        shouldHydrate || shouldHydrateLayout || hasIsolatedClientBoundaries;\n      (req as any).__FARM_ISLAND_STRATEGY__ = hydrationIslandStrategy;\n      (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ = hasHydratableRouteSlots;\n      (req as any).__FARM_LOADING_MODULE_PATH__ = loadingBoundaryEntry?.modulePath\n        ? toViteModuleId(loadingBoundaryEntry.modulePath, this.config.root)\n        : null;\n      (req as any).__FARM_ROUTE_SLOTS__ = renderedRouteSlots.map((slot) => ({\n        name: slot.name,\n        ownerPattern: slot.ownerPattern,\n        containerId: slot.containerId,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        modulePath: slot.route.modulePath,\n        isClientComponent: slot.isClientComponent,\n        shouldHydrate: slot.shouldHydrate,\n        props: {\n          params: slot.props.params,\n          search: (slot.props as any).search,\n          searchParams: (slot.props as any).search,\n          ...(\"data\" in slot.props ? { data: (slot.props as any).data } : {}),\n          ...((slot.props as any).__farmCanonicalPath\n            ? { __farmCanonicalPath: (slot.props as any).__farmCanonicalPath }\n            : {}),\n          ...((slot.props as any).__farmRoutePropsResolved\n            ? { __farmRoutePropsResolved: true }\n            : {}),\n          path: pathname,\n        },\n      }));\n      // Store pageProps for client-side hydration (serializable version - no Promises)\n      (req as any).__FARM_PROPS__ = {\n        params: pageProps.params,\n        search: (pageProps as any).search,\n        searchParams: (pageProps as any).search,\n        ...(\"data\" in pageProps ? { data: (pageProps as any).data } : {}),\n        ...((pageProps as any).__farmCanonicalPath\n          ? { __farmCanonicalPath: (pageProps as any).__farmCanonicalPath }\n          : {}),\n        ...((pageProps as any).__farmRoutePropsResolved ? { __farmRoutePropsResolved: true } : {}),\n        path: pathname,\n        middleware:\n          middlewareMap.size > 0\n            ? {\n                data: Object.fromEntries(middlewareMap),\n              }\n            : undefined,\n        context:\n          pluginExposedContext.size > 0\n            ? {\n                data: Object.fromEntries(pluginExposedContext),\n              }\n            : undefined,\n      };\n\n      // Load layout modules\n      const layoutModules = await Promise.all(\n        layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n\n      const mergedMetadata = await this.resolveRouteMetadata({\n        layoutModules,\n        routeModule,\n        pageProps,\n        pathname,\n      });\n\n      // Store metadata on request for renderWithSSR\n      (req as any).__FARM_METADATA__ = mergedMetadata;\n\n      // Get middleware data for AsyncLocalStorage\n      const middlewareDataForContext = middlewareMap;\n\n      await _runWithMiddlewareData(middlewareDataForContext, async () => {\n        await _runWithMiddlewareContext(middlewareContext, async () => {\n          await _runWithCurrentRequest(currentRequest, async () => {\n            let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n\n            if (LoadingFallbackComponent) {\n              const loadingFallback = this.rendererRuntime.createElement(LoadingFallbackComponent, {\n                ...createRouteStateProps({\n                  params,\n                  searchParamsObject,\n                  path: pathname,\n                  middlewareMap,\n                  pluginExposedContext,\n                }),\n              });\n\n              pageElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.Suspense,\n                { fallback: loadingFallback },\n                pageElement,\n              );\n            }\n\n            // A route-wide page owns every compiled client component beneath\n            // its React root. Keep shared leaf modules as ordinary components\n            // here even when an isolated layout also imports the same module.\n            if ((isClientComponent || shouldHydrate) && !shouldHydrateLayout) {\n              pageElement = this.wrapClientGraph(pageElement);\n            }\n\n            // Every route gets a stable HTML boundary. Server-only pages keep\n            // native markup with no React root; interactive pages hydrate this\n            // exact boundary.\n            pageElement = this.createPageBoundary(pageElement, {\n              pageShouldHydrate: isClientComponent || shouldHydrate,\n              layoutShouldHydrate: shouldHydrateLayout,\n              islandStrategy: hydrationIslandStrategy,\n            });\n\n            let wrappedElement: any = pageElement;\n            for (let i = layoutModules.length - 1; i >= 0; i--) {\n              const layoutModule = layoutModules[i];\n              const layoutEntry = layouts[i];\n              const LayoutComponent = layoutModule.default;\n              const slotProps: Record<string, any> = {};\n              for (const slot of renderedRouteSlots) {\n                if (slot.ownerPattern !== layoutEntry.pattern) continue;\n\n                let slotElement = this.rendererRuntime.createElement(\n                  slot.module.default,\n                  slot.props,\n                );\n                slotElement = this.wrapClientGraph(slotElement);\n                slotElement = this.rendererRuntime.createElement(\n                  \"div\",\n                  {\n                    id: slot.containerId,\n                    \"data-farm-route-slot\": slot.name,\n                    \"data-farm-slot-owner\": slot.ownerPattern,\n                  },\n                  slotElement,\n                );\n                slotProps[slot.name] = slotElement;\n              }\n              wrappedElement = this.rendererRuntime.createElement(LayoutComponent, {\n                children: wrappedElement,\n                params,\n                ...slotProps,\n              });\n              wrappedElement = this.createLayoutBoundary(layoutEntry.pattern, wrappedElement);\n            }\n\n            if (shouldHydrateLayout) {\n              wrappedElement = this.wrapClientGraph(wrappedElement);\n            }\n\n            if (ErrorFallbackComponent && this.rendererRuntime.ErrorBoundary) {\n              wrappedElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.ErrorBoundary,\n                {\n                  Fallback: ErrorFallbackComponent,\n                  fallbackProps: {\n                    ...createRouteStateProps({\n                      params,\n                      searchParamsObject,\n                      path: pathname,\n                      middlewareMap,\n                      pluginExposedContext,\n                    }),\n                  },\n                },\n                wrappedElement,\n              );\n            }\n\n            const integratedElement = await this.wrapWithIntegrationProviders(wrappedElement);\n            const pprHeaders = renderingConfig.ppr\n              ? this.getPPRHeaders(pprShellOptions ? \"miss\" : \"bypass\", renderingConfig.revalidate)\n              : undefined;\n\n            // Render with middleware data available\n            await this.renderWithSSR(\n              integratedElement,\n              req,\n              res,\n              () => {\n                _clearCurrentMiddlewareData();\n                _clearCurrentMiddlewareContext();\n              },\n              {\n                responseHeaders: pprHeaders,\n                routeManifest,\n                captureStaticShell: Boolean(pprShellOptions),\n                observabilityRoute: pathname,\n                onSuspenseHoleDetected: pprShellOptions\n                  ? () =>\n                      emitFarmEvent({\n                        type: \"ppr.suspense.holeDetected\",\n                        route: pathname,\n                      })\n                  : undefined,\n                onComplete:\n                  pprShellOptions && req.method !== \"HEAD\"\n                    ? (html) => this.cachePPRShell(pprShellOptions, html)\n                    : undefined,\n              },\n            );\n            if (pprRefreshRoute) {\n              emitFarmEvent({\n                type: \"ppr.refresh.complete\",\n                route: pprRefreshRoute,\n                durationMs: Date.now() - renderStartTime,\n              });\n            }\n            completeRender(res.statusCode || 200, pathname);\n          });\n        });\n      });\n    } catch (caughtError) {\n      let error = caughtError;\n\n      if (isWebResponse(error)) {\n        if (!res.headersSent && !(res as any).writableEnded) {\n          await sendWebResponse(res, error);\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(error.status, pathname);\n        return;\n      }\n\n      if (isFarmRedirectError(error)) {\n        const redirect = getFarmRedirectError(error)!;\n        const snapshot = getFarmI18nClientSnapshot();\n        const redirectUrl =\n          snapshot && redirect.url.startsWith(\"/\") && !redirect.url.startsWith(\"//\")\n            ? localizeFarmHref(redirect.url, snapshot.locale, snapshot)\n            : redirect.url;\n        emitFarmEvent({\n          type: \"route.redirect\",\n          from: pathname,\n          to: redirectUrl,\n          status: redirect.status,\n        });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          res.statusCode = redirect.status;\n          res.setHeader(\"Location\", redirectUrl);\n          res.end();\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(redirect.status, pathname);\n        return;\n      }\n\n      if (isFarmNotFoundError(error)) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          try {\n            await this.render404(req, res);\n            completeRender(404, pathname);\n            return;\n          } catch (notFoundRenderError) {\n            error = notFoundRenderError;\n          }\n        } else {\n          if (!(res as any).writableEnded) {\n            res.end();\n          }\n          completeRender(404, pathname);\n          return;\n        }\n      }\n\n      emitFarmEvent({ type: \"render.error\", route: pathname, error });\n      const errorStatus = resolveDefaultErrorStatus(error);\n      if (pprRefreshRoute) {\n        emitFarmEvent({\n          type: \"ppr.refresh.error\",\n          route: pprRefreshRoute,\n          error,\n        });\n      }\n      logger.error(`Error rendering page: ${error}`);\n\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return;\n      }\n\n      if (errorBoundaryEntry) {\n        const rendered = await this.renderRouteErrorBoundary(req, res, {\n          pathname,\n          params,\n          layouts,\n          searchParamsObject,\n          middlewareMap,\n          middlewareContext,\n          pluginExposedContext,\n          error,\n          statusCode: errorStatus,\n          errorModulePath: errorBoundaryEntry.modulePath,\n        });\n\n        if (rendered) {\n          return;\n        }\n      }\n\n      await this.renderError(req, res, error, errorStatus);\n    }\n  }\n\n  private async wrapWithIntegrationProviders(element: any): Promise<any> {\n    const providers = getIntegrationProviders(this.config.integrations);\n    let wrapped = element;\n\n    for (let i = providers.length - 1; i >= 0; i--) {\n      const provider = providers[i];\n      if (provider.component || provider.type === \"clerk\") {\n        if (!isReactRenderer(this.config.renderer)) {\n          throw new Error(\n            `Integration provider \\`${provider.type}\\` currently requires the React renderer.`,\n          );\n        }\n        let ProviderComponent;\n        if (isFarmIntegrationProviderComponentReference(provider.component)) {\n          const providerModuleId = provider.component.module.startsWith(\".\")\n            ? toViteModuleId(\n                path.resolve(this.config.root, provider.component.module),\n                this.config.root,\n              )\n            : provider.component.module;\n          const providerModule = this.viteServer\n            ? await this.viteServer.ssrLoadModule(providerModuleId)\n            : await importRuntimeModule(\n                provider.component.module.startsWith(\".\")\n                  ? pathToFileURL(path.resolve(this.config.root, provider.component.module)).href\n                  : provider.component.module,\n              );\n          ProviderComponent = providerModule[provider.component.export || \"default\"];\n        } else if (typeof provider.component === \"function\") {\n          ProviderComponent = provider.component;\n        } else if (provider.type === \"clerk\") {\n          if (!cachedClerkProvider) {\n            cachedClerkProvider = await importRuntimeModule(\"@clerk/react\");\n          }\n          ProviderComponent = cachedClerkProvider!.ClerkProvider;\n        } else {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` has an invalid component reference.`,\n          );\n        }\n        if (!ProviderComponent) {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` did not export its configured component.`,\n          );\n        }\n\n        wrapped = this.rendererRuntime.createElement(\n          ProviderComponent,\n          provider.props || {},\n          wrapped,\n        );\n      }\n    }\n\n    return wrapped;\n  }\n\n  private async resolveRouteMetadata(options: {\n    layoutModules: Array<Record<string, any>>;\n    routeModule: RouteModule;\n    pageProps: PageProps;\n    pathname: string;\n  }): Promise<Record<string, any>> {\n    let metadata: Record<string, any> = {};\n\n    for (const layoutModule of options.layoutModules) {\n      metadata = mergeMetadata(metadata, layoutModule.metadata);\n      if (typeof layoutModule.generateMetadata === \"function\") {\n        metadata = mergeMetadata(\n          metadata,\n          await layoutModule.generateMetadata({\n            params: options.pageProps.params,\n          }),\n        );\n      }\n    }\n\n    metadata = mergeMetadata(metadata, (options.routeModule as any).metadata);\n    if (typeof (options.routeModule as any).generateMetadata === \"function\") {\n      metadata = mergeMetadata(\n        metadata,\n        await (options.routeModule as any).generateMetadata(options.pageProps),\n      );\n    }\n\n    if (!metadata.manifest) {\n      const manifestMatch = this.routeManager.getMatchingMetadataRoute(\n        options.pathname,\n        \"manifest\",\n      );\n      if (manifestMatch) {\n        const rawHref = this.routeManager.resolveMetadataRoutePath(\n          manifestMatch.metadata,\n          manifestMatch.params,\n        );\n        const snapshot = getFarmI18nClientSnapshot();\n        const localizedHref = snapshot\n          ? localizeFarmHref(rawHref, snapshot.locale, snapshot)\n          : rawHref;\n        metadata.manifest = applyFarmBasePath(localizedHref, this.config.basePath);\n      }\n    }\n\n    for (const kind of [\"opengraph\", \"twitter\"] as const) {\n      const reference = await this.resolveMetadataImageReference(kind, options.pathname);\n      if (reference) {\n        metadata = addMetadataImageReference(metadata, reference);\n      }\n    }\n\n    return metadata;\n  }\n\n  private async resolveMetadataImageReference(\n    kind: MetadataImageKind,\n    pathname: string,\n  ): Promise<FarmMetadataImageReference | null> {\n    const match = this.routeManager.getMatchingMetadataImage(pathname, kind);\n    if (!match) return null;\n\n    const rawHref = this.routeManager.resolveMetadataImagePath(match.image, match.params);\n    const snapshot = getFarmI18nClientSnapshot();\n    const localizedHref = snapshot ? localizeFarmHref(rawHref, snapshot.locale, snapshot) : rawHref;\n    const href = applyFarmBasePath(localizedHref, this.config.basePath);\n    const reference: FarmMetadataImageReference = {\n      kind,\n      href,\n    };\n\n    if (match.image.sourceType === \"static\" && match.image.staticInfo) {\n      return {\n        ...reference,\n        width: match.image.staticInfo.width,\n        height: match.image.staticInfo.height,\n        alt: match.image.staticInfo.alt,\n        contentType: match.image.staticInfo.contentType,\n      };\n    }\n\n    try {\n      const imageModule = await this.routeManager.loadRouteModule(match.image.modulePath);\n      const size = (imageModule as any).size;\n      if (size && typeof size === \"object\") {\n        reference.width = typeof size.width === \"number\" ? size.width : undefined;\n        reference.height = typeof size.height === \"number\" ? size.height : undefined;\n      }\n      if (typeof (imageModule as any).alt === \"string\") {\n        reference.alt = (imageModule as any).alt;\n      }\n      if (typeof (imageModule as any).contentType === \"string\") {\n        reference.contentType = (imageModule as any).contentType;\n      }\n    } catch (error) {\n      logger.warn(`Failed to read ${kind} image metadata for ${pathname}: ${error}`);\n    }\n\n    return reference;\n  }\n\n  private async renderMetadataRoute(\n    req: FarmRequest,\n    res: FarmResponse,\n    match: NonNullable<ReturnType<RouteManager[\"matchMetadataRoute\"]>>,\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    try {\n      const routeModule = await this.routeManager.loadRouteModule(match.metadata.modulePath);\n      if (routeModule.default === undefined) {\n        throw new Error(\n          `Metadata route module ${match.metadata.modulePath} does not export a default value or handler`,\n        );\n      }\n\n      const request = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const url = new URL(request.url);\n      const value =\n        typeof routeModule.default === \"function\"\n          ? await (routeModule.default as any)({\n              request,\n              params: match.params,\n              searchParams: url.searchParams,\n              path: match.routePath,\n            })\n          : routeModule.default;\n      const response = createFarmMetadataRouteResponse(match.metadata.kind, value, routeModule, {\n        method,\n      });\n      await sendWebResponse(res as any, response);\n    } catch (error) {\n      logger.error(`Metadata route render failed for ${match.metadata.modulePath}: ${error}`);\n      await sendWebResponse(\n        res as any,\n        new Response(\"Internal Server Error\", {\n          status: 500,\n          headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n        }),\n      );\n    }\n  }\n\n  private async renderMetadataImage(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      pagePath: string;\n      params: Record<string, string>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      image: {\n        modulePath: string;\n        kind: MetadataImageKind;\n        sourceType?: \"module\" | \"static\";\n        staticInfo?: StaticMetadataImageInfo;\n      };\n    },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    if (options.image.sourceType === \"static\") {\n      if (!options.image.staticInfo) {\n        throw new Error(`Static metadata image ${options.image.modulePath} is missing file info`);\n      }\n      await this.writeStaticMetadataImageResponse(req, res, {\n        modulePath: options.image.modulePath,\n        staticInfo: options.image.staticInfo,\n      });\n      return;\n    }\n\n    const imageModule = await this.routeManager.loadRouteModule(options.image.modulePath);\n    if (!imageModule.default) {\n      throw new Error(\n        `Metadata image module ${options.image.modulePath} does not export a default component or handler`,\n      );\n    }\n\n    const imageProps: PageProps = {\n      params: options.params,\n      searchParams: Promise.resolve(options.searchParamsObject),\n      path: options.pagePath,\n    };\n    const handlerResult =\n      typeof imageModule.default === \"function\"\n        ? await (imageModule.default as any)(imageProps)\n        : imageModule.default;\n\n    await this.writeMetadataImageResponse(req, res, handlerResult, imageModule);\n  }\n\n  private async writeMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    value: unknown,\n    imageModule: RouteModule,\n  ): Promise<void> {\n    const ifNoneMatch = req.headers[\"if-none-match\"];\n    const response = await createFarmMetadataImageResponse(value, imageModule, {\n      method: req.method,\n      ifNoneMatch: Array.isArray(ifNoneMatch) ? ifNoneMatch[0] : ifNoneMatch,\n    });\n    await sendWebResponse(res as any, response);\n  }\n\n  private async writeStaticMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    image: { modulePath: string; staticInfo: StaticMetadataImageInfo },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    const etag = `\"${image.staticInfo.hash}\"`;\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const isVersioned = requestUrl.searchParams.get(\"v\") === image.staticInfo.hash;\n\n    res.setHeader(\"Content-Type\", image.staticInfo.contentType);\n    res.setHeader(\"Content-Length\", image.staticInfo.byteLength);\n    res.setHeader(\"ETag\", etag);\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.setHeader(\n      \"Cache-Control\",\n      isVersioned ? \"public, max-age=31536000, immutable\" : \"public, max-age=0, must-revalidate\",\n    );\n\n    if (matchesFarmIfNoneMatch(req.headers[\"if-none-match\"], etag)) {\n      res.statusCode = 304;\n      res.end();\n      return;\n    }\n\n    res.statusCode = res.statusCode || 200;\n    if (method === \"HEAD\") {\n      res.end();\n      return;\n    }\n\n    res.write(await fs.promises.readFile(image.modulePath));\n    res.end();\n  }\n\n  private async renderRouteErrorBoundary(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      params: Record<string, string>;\n      layouts: Array<{ modulePath: string }>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      middlewareMap: Map<string, any>;\n      middlewareContext: Map<string, any>;\n      pluginExposedContext: Map<string, any>;\n      error: unknown;\n      statusCode: number;\n      errorModulePath: string;\n    },\n  ): Promise<boolean> {\n    try {\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return true;\n      }\n\n      const errorModule = await this.routeManager.loadRouteModule(options.errorModulePath);\n      if (!errorModule.default) {\n        return false;\n      }\n\n      const ErrorComponent = errorModule.default;\n      const errorElement = this.rendererRuntime.createElement(ErrorComponent, {\n        ...createRouteStateProps({\n          params: options.params,\n          searchParamsObject: options.searchParamsObject,\n          path: options.pathname,\n          middlewareMap: options.middlewareMap,\n          pluginExposedContext: options.pluginExposedContext,\n        }),\n        error: options.error,\n        reset: () => {},\n      });\n\n      let wrapped: any = errorElement;\n      const layoutModules = await Promise.all(\n        options.layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n      for (let i = layoutModules.length - 1; i >= 0; i--) {\n        const LayoutComponent = layoutModules[i].default;\n        wrapped = this.rendererRuntime.createElement(LayoutComponent, {\n          children: wrapped,\n          params: options.params,\n        });\n      }\n\n      wrapped = await this.wrapWithIntegrationProviders(wrapped);\n\n      const html = await _runWithMiddlewareData(options.middlewareMap, () =>\n        _runWithMiddlewareContext(options.middlewareContext, () =>\n          this.rendererRuntime.renderToString(wrapped),\n        ),\n      );\n      res.statusCode = options.statusCode;\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      // A PPR shell failure leaves the \"miss\" caching headers (s-maxage,\n      // stale-while-revalidate, X-Farm-PPR) on res. Error responses must not be\n      // cached by shared/CDN caches, so clear them here, matching renderError.\n      res.setHeader(\"Cache-Control\", \"private, no-store\");\n      res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n      if (typeof res.removeHeader === \"function\") {\n        res.removeHeader(\"X-Farm-PPR\");\n      }\n      res.write(this.createFullHTML(html, false, options.pathname));\n      res.end();\n      return true;\n    } catch (renderError) {\n      logger.warn(`Failed to render route-level error boundary: ${renderError}`);\n      return false;\n    }\n  }\n\n  private async renderBufferedSSR(\n    element: unknown,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const startedAt = Date.now();\n    const route = options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    emitFarmEvent({ type: \"render.stream.start\", route });\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n      res.setHeader(key, value);\n    }\n\n    try {\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      const routeSlots = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlots,\n      });\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n      const deploymentId = this.getDeploymentId();\n      const bootstrapScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify((req as any).__FARM_IS_CLIENT_COMPONENT__ === true)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify((req as any).__FARM_LOADING_MODULE_PATH__ || null)};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const deferredScript = createDeferredHydrationScript(deferredProps.records);\n      const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n      const { html: content, head: rendererHead } =\n        await this.renderElementToDocumentParts(element);\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n        hasExplicitTitle,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      // A renderer-emitted <title> (e.g. <svelte:head>) must take effect: the\n      // first <title> in a document wins, so the fallback framework title is\n      // suppressed when the renderer supplies one. Explicit metadata titles\n      // still come first and win.\n      const documentTitleTag =\n        !hasExplicitTitle && /<title[\\s>]/i.test(rendererHead) ? \"\" : `<title>${title}</title>`;\n      const rendererHasTitle = /<title[\\s>]/i.test(rendererHead);\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const alternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // A layout that returns its own full `<html>` document is composed as the\n      // document (Farm assets merged in) rather than nested inside the shell,\n      // matching the production build and avoiding invalid nested documents.\n      const fullDocument = extractFarmFullDocument(content);\n      let html: string;\n      if (fullDocument) {\n        warnFarmFullDocumentLayout();\n        const shouldReplaceLayoutTitle = hasExplicitTitle || rendererHasTitle;\n        const documentHtml = shouldReplaceLayoutTitle\n          ? removeFarmDocumentTitles(fullDocument)\n          : fullDocument;\n        const effectiveRendererHead = hasExplicitTitle\n          ? removeFarmDocumentTitles(rendererHead)\n          : rendererHead;\n        html = composeFarmFullDocument(documentHtml, {\n          htmlAttributes: `${\n            i18nSnapshot\n              ? ` lang=\"${escapeHtmlAttribute(i18nSnapshot.locale)}\" dir=\"${escapeHtmlAttribute(i18nSnapshot.direction)}\"`\n              : \"\"\n          }${themeDocument.attributes}`,\n          replaceHtmlAttributes: [\n            ...(i18nSnapshot ? [\"lang\", \"dir\"] : []),\n            ...(themeDocument.attributes ? [\"data-theme\"] : []),\n          ],\n          headAssets: [\n            themeDocument.head,\n            `<meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">`,\n            hasExplicitTitle ? documentTitleTag : \"\",\n            metaTags,\n            alternateTags,\n            effectiveRendererHead,\n            renderFarmFontDevHead(this.config.root || process.cwd()),\n            `<link rel=\"stylesheet\" href=\"/src/app/globals.css\">`,\n            ...this.collectDevStyleLinks(),\n            `<script type=\"module\" src=\"/@vite/client\"></script>`,\n            rendererHydrationScript,\n            bootstrapScript,\n          ]\n            .filter(Boolean)\n            .join(\"\\n  \"),\n          bodyFooter: [deferredScript, `<script type=\"module\" src=\"/@farm/client.js\"></script>`]\n            .filter(Boolean)\n            .join(\"\\n  \"),\n        });\n      } else {\n        html = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n          i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n        }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n  ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  ${documentTitleTag}${metaTags}${alternateTags}${rendererHead ? `\\n  ${rendererHead}` : \"\"}\n  ${renderFarmFontDevHead(this.config.root || process.cwd())}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\">${this.collectDevStyleLinks()\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${rendererHydrationScript}\n  ${bootstrapScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">${content}</div>\n  ${deferredScript}\n  <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n      }\n\n      emitFarmEvent({\n        type: \"render.stream.shellReady\",\n        route,\n        durationMs: Date.now() - startedAt,\n      });\n      if ((req.method || \"GET\").toUpperCase() !== \"HEAD\") res.write(html);\n      res.end();\n      await options.onComplete?.(html);\n      emitFarmEvent({\n        type: \"render.stream.complete\",\n        route,\n        durationMs: Date.now() - startedAt,\n      });\n    } catch (error) {\n      emitFarmEvent({ type: \"render.error\", route, error });\n      throw error;\n    } finally {\n      clearMiddlewareData?.();\n    }\n  }\n\n  private async renderWithSSR(\n    element: any,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const renderToPipeableStream = this.rendererRuntime.renderToPipeableStream;\n    const fullDocumentRouteKey =\n      options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    // A full-document layout can't be composed once the stream's shell is\n    // flushed, so a route previously seen to render one is served through the\n    // buffered path, which produces a valid single document.\n    if (!renderToPipeableStream || fullDocumentRoutes.has(fullDocumentRouteKey)) {\n      return this.renderBufferedSSR(element, req, res, clearMiddlewareData, options);\n    }\n\n    return new Promise((resolve, reject) => {\n      const streamStartTime = Date.now();\n      const observabilityRoute =\n        options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n      const deploymentId = this.getDeploymentId();\n      emitFarmEvent({ type: \"render.stream.start\", route: observabilityRoute });\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n        res.setHeader(key, value);\n      }\n      const htmlParts: string[] = [];\n      // Splitting a static shell out of the stream requires knowing where the\n      // first dynamic boundary is, and only the renderer that emitted the\n      // markers can say. Without that, every chunk would look static and a\n      // per-request response would be cached as a shared shell, so skip the\n      // shell entirely rather than guess.\n      const findStaticShellBoundary = this.rendererRuntime.findStaticShellBoundary;\n      const staticShellParts: string[] | undefined =\n        options.captureStaticShell && findStaticShellBoundary ? [] : undefined;\n      let staticShellClosed = false;\n      let suspenseHoleEmitted = false;\n      let didError = false;\n\n      // Get the page path for client-side hydration\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const isClientComponent = (req as any).__FARM_IS_CLIENT_COMPONENT__ === true;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n\n      // Generate manifest for client-side SPA navigation (TanStack Start pattern)\n      // This manifest is inlined in HTML - no separate file or API endpoint\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n\n      // Convert to object format for client\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      // Convert routes array to object keyed by pattern\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      // Convert layouts array to object\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      // Inject page props, component info, and MANIFEST for client-side SPA\n      // __FARM_MANIFEST__ contains the full route manifest (TanStack Start pattern)\n      const routeSlotPayload = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlotPayload,\n      });\n      const propsScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify(isClientComponent)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify(\n        (req as any).__FARM_LOADING_MODULE_PATH__ || null,\n      )};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const hydrationClickQueueScript =\n        isClientComponent ||\n        (req as any).__FARM_SHOULD_HYDRATE__ === true ||\n        (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ === true\n          ? createPreHydrationClickQueueScript()\n          : \"\";\n\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const i18nAlternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // React 19: ensure root is a single DOM node so streaming starts early (avoids Fragment delay)\n      const streamRoot = this.rendererRuntime.createElement(\n        \"div\",\n        { style: { display: \"contents\" } },\n        element,\n      );\n      const devStyleLinks = this.collectDevStyleLinks();\n      const { pipe } = renderToPipeableStream(streamRoot, {\n        onShellReady() {\n          const shellReadyMs = Date.now() - streamStartTime;\n          emitFarmEvent({\n            type: \"render.stream.shellReady\",\n            route: observabilityRoute,\n            durationMs: shellReadyMs,\n          });\n          if (process.env.FARM_VERBOSE) {\n            console.log(`[FARM STREAM] onShellReady at ${shellReadyMs}ms`);\n          }\n          const shell = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n            i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n          }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n  ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  <title>${title}</title>${metaTags}${i18nAlternateTags}\n  ${fontHead}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />${devStyleLinks\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${propsScript}\n  ${hydrationClickQueueScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">`;\n          htmlParts.push(shell);\n          staticShellParts?.push(shell);\n\n          let firstChunk = true;\n          let checkedFullDocument = false;\n          const writableStream = new Writable({\n            write(chunk, encoding, callback) {\n              if (firstChunk && process.env.FARM_VERBOSE) {\n                console.log(`[FARM STREAM] first pipe chunk at ${Date.now() - streamStartTime}ms`);\n                firstChunk = false;\n              }\n              const chunkText = Buffer.isBuffer(chunk) ? chunk.toString() : String(chunk);\n              // The shell was already flushed, so this response still nests the\n              // document; record the route so later requests take the buffered\n              // path (which composes it correctly) and warn the developer once.\n              if (!checkedFullDocument) {\n                checkedFullDocument = true;\n                if (opensFarmFullDocument(chunkText)) {\n                  fullDocumentRoutes.add(fullDocumentRouteKey);\n                  warnFarmFullDocumentLayout();\n                }\n              }\n              htmlParts.push(chunkText);\n\n              if (staticShellParts && findStaticShellBoundary && !staticShellClosed) {\n                const dynamicIndex = findStaticShellBoundary(chunkText);\n                if (dynamicIndex >= 0) {\n                  if (dynamicIndex > 0) {\n                    staticShellParts.push(chunkText.slice(0, dynamicIndex));\n                  }\n                  staticShellClosed = true;\n                  if (!suspenseHoleEmitted) {\n                    suspenseHoleEmitted = true;\n                    options.onSuspenseHoleDetected?.();\n                  }\n                } else {\n                  staticShellParts.push(chunkText);\n                }\n              }\n\n              res.write(chunk, encoding, () => {\n                if (typeof (res as any).flush === \"function\") (res as any).flush();\n                callback();\n              });\n            },\n            final(callback) {\n              const suspenseRevealFallback = `<script>(function(){function moveFragment(srcId,placeholderId){var src=document.getElementById(srcId),ph=document.getElementById(placeholderId);if(!src||!ph||!ph.parentNode)return false;while(src.firstChild)ph.parentNode.insertBefore(src.firstChild,ph);ph.parentNode.removeChild(ph);if(src.parentNode)src.parentNode.removeChild(src);return true}function revealBoundary(boundaryId,sectionId){var boundary=document.getElementById(boundaryId),section=document.getElementById(sectionId);if(!boundary||!section||!boundary.parentNode)return false;var start=boundary.previousSibling;if(!start||start.nodeType!==8)return false;var parent=boundary.parentNode;var node=boundary;var depth=0;while(node){if(node.nodeType===8){var data=node.data;if(data===\"/$\"||data===\"/&\"){if(depth===0)break;depth--;}else if(data===\"$\"||data===\"$?\"||data===\"$~\"||data===\"$!\"||data===\"&\"){depth++;}}var next=node.nextSibling;parent.removeChild(node);node=next;}while(section.firstChild)parent.insertBefore(section.firstChild,node);if(section.parentNode)section.parentNode.removeChild(section);start.data=\"$\";return true}var tries=0;var timer=setInterval(function(){var changed=false;document.querySelectorAll('div[id^=\"S:\"]').forEach(function(section){var suffix=section.id.slice(2);changed=moveFragment('S:'+suffix,'P:'+suffix)||changed;});document.querySelectorAll('template[id^=\"B:\"]').forEach(function(boundary){var suffix=boundary.id.slice(2);changed=revealBoundary('B:'+suffix,'S:'+suffix)||changed;});tries++;if(tries>80||(!document.querySelector('template[id^=\"B:\"]')&&!document.querySelector('template[id^=\"P:\"]'))){clearInterval(timer);}},50);})();</script>`;\n              const footer = createDocumentFooter({\n                suspenseRevealFallback,\n                deferredHydrationScript: createDeferredHydrationScript(deferredProps.records),\n              });\n              htmlParts.push(footer);\n              res.write(footer);\n              res.end();\n              callback();\n              if (clearMiddlewareData) {\n                clearMiddlewareData();\n              }\n              if (!didError && options.onComplete) {\n                if (staticShellParts) {\n                  staticShellParts.push(\n                    createDocumentFooter({\n                      suspenseRevealFallback,\n                      refreshPPR: staticShellClosed,\n                    }),\n                  );\n                }\n\n                const cachedHtml = staticShellParts\n                  ? staticShellParts.join(\"\")\n                  : htmlParts.join(\"\");\n                Promise.resolve(options.onComplete(cachedHtml)).catch((error) => {\n                  logger.warn(`Failed to cache PPR shell: ${error}`);\n                });\n              }\n              emitFarmEvent({\n                type: \"render.stream.complete\",\n                route: observabilityRoute,\n                durationMs: Date.now() - streamStartTime,\n              });\n              resolve();\n            },\n          });\n\n          // Queue the shell immediately, then start piping the Suspense stream.\n          // Waiting for the write callback can delay the fallback until the whole\n          // response is ready under some dev-server wrappers.\n          res.write(shell);\n          if (typeof (res as any).flush === \"function\") {\n            (res as any).flush();\n          }\n          pipe(writableStream);\n        },\n        onShellError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR shell error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n\n          if (clearMiddlewareData) {\n            clearMiddlewareData();\n          }\n\n          reject(error);\n        },\n        onError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR streaming error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n        },\n      });\n    });\n  }\n\n  private async render404(req: FarmRequest, res: FarmResponse): Promise<void> {\n    res.statusCode = 404;\n\n    const pathname = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    }).pathname;\n\n    // Agents that navigate in Markdown (a `.md` URL or `Accept: text/markdown`)\n    // get a Markdown error body instead of the HTML not-found shell.\n    const acceptHeader = req.headers.accept;\n    const accept = Array.isArray(acceptHeader) ? acceptHeader.join(\",\") : acceptHeader;\n    if (farmRequestWantsMarkdown(pathname, accept)) {\n      res.setHeader(\"Content-Type\", FARM_MARKDOWN_CONTENT_TYPE);\n      res.setHeader(\"X-Farm-Markdown-Error\", \"404\");\n      res.setHeader(\"Cache-Control\", \"no-store\");\n      res.end(createFarmMarkdownErrorBody(404, pathname, this.config.basePath || \"/\"));\n      return;\n    }\n\n    try {\n      // Look for custom not-found page\n      const appDir = path.join(this.config.root, this.config.srcDir, \"app\");\n      const notFoundExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n      const notFoundPath = resolveFarmNotFoundComponentPath(\n        this.config,\n        getFarmAppDirectories(this.config),\n      );\n\n      if (notFoundPath) {\n        // Use routeManager to load the module (uses Vite's ssrLoadModule in dev)\n        const notFoundModule = await this.routeManager.loadRouteModule(notFoundPath);\n        const NotFoundComponent = notFoundModule.default;\n\n        if (NotFoundComponent) {\n          // Look for root layout\n          let LayoutComponent: any = null;\n          for (const ext of notFoundExtensions) {\n            const layoutPath = path.join(appDir, `layout${ext}`);\n            if (fs.existsSync(layoutPath)) {\n              const layoutModule = await this.routeManager.loadLayoutModule(layoutPath);\n              LayoutComponent = layoutModule.default;\n              break;\n            }\n          }\n\n          // Render the 404 page\n          let element: any = this.rendererRuntime.createElement(NotFoundComponent, { pathname });\n\n          // Wrap with layout if available\n          if (LayoutComponent) {\n            element = this.rendererRuntime.createElement(LayoutComponent, {\n              children: element,\n            });\n          }\n\n          element = await this.wrapWithIntegrationProviders(element);\n\n          // Render to string\n          const content = await this.rendererRuntime.renderToString(element);\n\n          const html = this.createFullHTML(content, false, pathname);\n          res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n          res.write(html);\n          res.end();\n          return;\n        }\n      }\n    } catch (error) {\n      throw new Error(`Failed to render custom 404 page: ${error}`);\n    }\n\n    // Render the shared adaptive fallback when the app does not provide its own page.\n    const homeHref = escapeHtmlAttribute(applyFarmBasePath(\"/\", this.config.basePath));\n    const defaultContent = `<style>${DEFAULT_NOT_FOUND_STYLES}</style><main class=\"farm-default-not-found\" aria-labelledby=\"farm-default-not-found-title\" aria-describedby=\"farm-default-not-found-description\"><div class=\"farm-default-not-found__content\"><h1 id=\"farm-default-not-found-title\" class=\"farm-default-not-found__code\">404</h1><p id=\"farm-default-not-found-description\" class=\"farm-default-not-found__description\">Not found</p><a class=\"farm-default-not-found__home\" href=\"${homeHref}\">GO HOME</a></div></main>`;\n\n    const html = this.createFullHTML(defaultContent, false, pathname);\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.write(html);\n    res.end();\n  }\n\n  private async renderError(\n    req: FarmRequest,\n    res: FarmResponse,\n    error: unknown,\n    statusCode = 500,\n  ): Promise<void> {\n    if (res.headersSent || (res as any).writableEnded) {\n      if (!(res as any).writableEnded) {\n        res.end();\n      }\n      return;\n    }\n\n    res.statusCode = statusCode;\n    const isDev = process.env.NODE_ENV === \"development\";\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const diagnostics = isDev\n      ? createDefaultErrorDiagnostics(error, this.config.root || process.cwd())\n      : undefined;\n    const statusText = getDefaultErrorStatusText(statusCode);\n    const content = createDefaultErrorMarkup({\n      statusCode,\n      statusText,\n      requestPath: requestUrl.pathname,\n      method: req.method || \"GET\",\n      message: diagnostics?.message,\n      errorName: diagnostics?.name,\n      stack: diagnostics?.stack,\n      sourceFrame: diagnostics?.sourceFrame,\n      development: isDev,\n      farmVersion: FARM_VERSION,\n      nodeVersion: process.version,\n      mode: isDev ? \"development\" : \"production\",\n    });\n\n    const html = this.createFullHTML(\n      content,\n      false,\n      requestUrl.pathname,\n      `${statusCode} - ${statusText}`,\n    );\n\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.setHeader(\"Cache-Control\", \"private, no-store\");\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.write(html);\n    res.end();\n  }\n\n  private createFullHTML(\n    content: string,\n    isClientComponent = false,\n    requestPath = \"/\",\n    metadataHead?: string,\n  ): string {\n    const i18nSnapshot = getFarmI18nClientSnapshot();\n    const clientScript = isClientComponent\n      ? `  <script type=\"module\" src=\"/@farm/client.js\"></script>`\n      : \"\";\n    const integrationManifestScript = `<script>\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(this.getDeploymentId())};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${i18nSnapshot ? `window.__FARM_I18N__ = ${serializeInlineValue(i18nSnapshot)};` : \"\"}\n</script>`;\n    const alternateLinks = i18nSnapshot ? renderI18nAlternateLinks(requestPath, i18nSnapshot) : \"\";\n    const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n    const themeDocument = createFarmThemeDocumentParts(\n      this.config.theme,\n      this.config.basePath,\n      getFarmTheme(),\n    );\n    const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n\n    // A layout that returns its own full `<html>` document must not be nested\n    // inside this shell (that yields invalid nested `<html>`/`<head>`/`<body>`).\n    // Compose Farm's managed assets into the layout's document instead, matching\n    // the production build's `hasFullDocument` path.\n    const fullDocument = extractFarmFullDocument(content);\n    if (fullDocument) {\n      warnFarmFullDocumentLayout();\n      return composeFarmFullDocument(\n        metadataHead ? removeFarmDocumentTitles(fullDocument) : fullDocument,\n        {\n          htmlAttributes: `${\n            i18nSnapshot\n              ? ` lang=\"${escapeHtmlAttribute(i18nSnapshot.locale)}\" dir=\"${escapeHtmlAttribute(i18nSnapshot.direction)}\"`\n              : \"\"\n          }${themeDocument.attributes}`,\n          replaceHtmlAttributes: [\n            ...(i18nSnapshot ? [\"lang\", \"dir\"] : []),\n            ...(themeDocument.attributes ? [\"data-theme\"] : []),\n          ],\n          headAssets: [\n            themeDocument.head,\n            `<meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(this.getDeploymentId())}\">`,\n            metadataHead,\n            alternateLinks,\n            fontHead,\n            `<link rel=\"stylesheet\" href=\"/src/app/globals.css\" />`,\n            ...this.collectDevStyleLinks(),\n            `<script type=\"module\" src=\"/@vite/client\"></script>`,\n            rendererHydrationScript,\n            integrationManifestScript,\n          ]\n            .filter(Boolean)\n            .join(\"\\n  \"),\n          bodyFooter: clientScript.trim(),\n        },\n      );\n    }\n\n    return `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n      i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n    }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(this.getDeploymentId())}\">\n  ${metadataHead ?? '<link rel=\"icon\" href=\"data:,\">\\n  <title>Farm.js App</title>'}${alternateLinks}\n  ${fontHead}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />${this.collectDevStyleLinks()\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${rendererHydrationScript}\n  ${integrationManifestScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">${content}</div>\n${clientScript}\n</body>\n</html>`;\n  }\n\n  private applyDeploymentHeaders(req: FarmRequest, res: FarmResponse): void {\n    const deploymentId = this.getDeploymentId();\n    res.setHeader(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n    if ((req.method || \"GET\").toUpperCase() !== \"GET\") return;\n\n    const forwardedProto = req.headers[\"x-forwarded-proto\"];\n    const isSecure =\n      (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n        ?.split(\",\")[0]\n        ?.trim() === \"https\" || Boolean((req.socket as any)?.encrypted);\n    const cookie = createFarmDeploymentCookie(deploymentId, this.config.basePath || \"/\", isSecure);\n    const existing = res.getHeader(\"Set-Cookie\");\n\n    if (Array.isArray(existing)) {\n      res.setHeader(\"Set-Cookie\", [...existing, cookie]);\n    } else if (existing) {\n      res.setHeader(\"Set-Cookie\", [String(existing), cookie]);\n    } else {\n      res.setHeader(\"Set-Cookie\", cookie);\n    }\n  }\n\n  private getDeploymentId(): string {\n    return this.config.deploymentId || \"development\";\n  }\n}\n","// Stylesheets the dev document must link beyond globals.css.\n//\n// The dev shell links `/src/app/globals.css` and nothing else, so CSS that\n// enters through a JS import — `import \"@fontsource-variable/geist\"` in a\n// layout, a component stylesheet, vendor CSS — never reaches the page: no\n// error, just silently missing rules (farming-labs/farm.js#658). Vite's module\n// graph knows every stylesheet the app touched; collecting it closes the gap.\n\n/** The slice of Vite's ModuleNode this module reads, kept minimal for tests. */\nexport interface DevStyleModule {\n  url?: string | null;\n  id?: string | null;\n  file?: string | null;\n}\n\nconst STYLE_EXTENSIONS = /\\.(css|scss|sass|less|styl|stylus)(?:$|\\?)/;\n\n/** The stylesheet link the shell already emits; its own `@import`s resolve\n * inside that response, so neither it nor its query variants repeat here. */\nconst ALREADY_LINKED = \"/src/app/globals.css\";\n\n/**\n * Stylesheet URLs from the module graph that the document should link,\n * deduped and sorted for a deterministic head. CSS modules (`.module.css`)\n * are excluded: their classes are hashed through the JS pipeline and a plain\n * link would apply nothing useful.\n */\nexport function collectDevStylesheetUrls(modules: Iterable<DevStyleModule>): string[] {\n  const seen = new Set<string>();\n  for (const mod of modules) {\n    const id = mod.id ?? mod.file ?? \"\";\n    if (!STYLE_EXTENSIONS.test(id)) continue;\n    if (id.includes(\".module.\")) continue;\n    const url = mod.url;\n    if (!url || !url.startsWith(\"/\")) continue;\n    const bare = url.split(\"?\")[0]!;\n    if (bare === ALREADY_LINKED) continue;\n    seen.add(bare);\n  }\n  return [...seen].sort();\n}\n","// Handling for a root layout that returns a full `<html>…</html>` document.\n//\n// Farm owns the document shell — a layout is expected to return a fragment (its\n// children), like the docs example does. When a layout instead returns a whole\n// document, the dev renderer must compose that document as the response rather\n// than nesting it inside the generated shell, which would emit invalid nested\n// `<html>`/`<head>`/`<body>`. This mirrors the production (Nitro) build's\n// `hasFullDocument` path so dev and prod agree.\n\n/** Peel Farm's leading `display:contents` wrapper divs (the stream root and any\n * layout-boundary divs) so the layout's own markup is exposed for inspection. */\nfunction stripContentsWrappers(markup: string): string {\n  let out = markup.replace(/^\\s+/, \"\");\n  const opener = /^<div\\b[^>]*style=\"display\\s*:\\s*contents\"[^>]*>/i;\n  let match: RegExpExecArray | null;\n  while ((match = opener.exec(out))) {\n    out = out.slice(match[0].length).replace(/^\\s+/, \"\");\n  }\n  return out;\n}\n\n/**\n * When `markup` (a rendered layout tree, possibly wrapped in Farm's\n * `display:contents` boundary divs) is a full HTML document, return just that\n * `<html>…</html>` document (leading `<!DOCTYPE>` preserved when present);\n * otherwise return `null`.\n */\nexport function extractFarmFullDocument(markup: string): string | null {\n  const inner = stripContentsWrappers(markup);\n  if (!/^<!doctype/i.test(inner) && !/^<html[\\s>]/i.test(inner)) return null;\n  const start = markup.search(/<!doctype|<html[\\s>]/i);\n  const closeIndex = markup.toLowerCase().lastIndexOf(\"</html>\");\n  if (start < 0 || closeIndex < 0) return null;\n  return markup.slice(start, closeIndex + \"</html>\".length);\n}\n\n/** True when a rendered layout tree is (or wraps) a full HTML document. */\nexport function isFarmFullDocument(markup: string): boolean {\n  return extractFarmFullDocument(markup) !== null;\n}\n\n/**\n * True when `markup` *begins* a full HTML document once Farm's wrappers are\n * peeled — usable on a streamed prefix, before the closing `</html>` has been\n * flushed.\n */\nexport function opensFarmFullDocument(markup: string): boolean {\n  const inner = stripContentsWrappers(markup);\n  return /^<!doctype/i.test(inner) || /^<html[\\s>]/i.test(inner);\n}\n\n/** Remove document title elements before inserting a higher-priority title. */\nexport function removeFarmDocumentTitles(markup: string): string {\n  return markup.replace(/<title\\b[^>]*>[\\s\\S]*?<\\/title>\\s*/gi, \"\");\n}\n\nexport interface FarmFullDocumentAssets {\n  /** Farm-managed `<head>` markup (styles, client/runtime scripts, metadata). */\n  headAssets: string;\n  /** Markup injected just before `</body>` (client bootstrap / entry scripts). */\n  bodyFooter: string;\n  /** Extra `<html>` attributes to merge (theme, direction). */\n  htmlAttributes?: string;\n  /** Existing attributes Farm owns and must replace before merging. */\n  replaceHtmlAttributes?: readonly string[];\n}\n\n/**\n * Compose a layout's own full document with Farm's managed head + body assets,\n * instead of nesting it inside the shell. String replacements use function\n * replacers so any `$`-sequences (`$&`, `$'`, `$$`) in the injected markup or\n * the document are inserted literally rather than expanded.\n */\nexport function composeFarmFullDocument(\n  documentHtml: string,\n  assets: FarmFullDocumentAssets,\n): string {\n  let html = documentHtml;\n\n  if (assets.htmlAttributes) {\n    html = html.replace(/<html\\b([^>]*)>/i, (_match, attrs: string) => {\n      let nextAttributes = attrs;\n      for (const name of assets.replaceHtmlAttributes ?? []) {\n        const escapedName = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n        nextAttributes = nextAttributes.replace(\n          new RegExp(\"\\\\s+\" + escapedName + \"=(?:\\\"[^\\\"]*\\\"|'[^']*'|[^\\\\s>]+)\", \"gi\"),\n          \"\",\n        );\n      }\n      return `<html${nextAttributes}${assets.htmlAttributes}>`;\n    });\n  }\n\n  // Ensure a hydration root exists so the client can mount, matching the shell.\n  if (!/\\sid=[\"']root[\"']/i.test(html)) {\n    html = html\n      .replace(/<body\\b([^>]*)>/i, '<body$1><div id=\"root\">')\n      .replace(/<\\/body>/i, \"</div></body>\");\n  }\n\n  if (assets.headAssets) {\n    html = html.replace(/<\\/head>/i, () => `  ${assets.headAssets}\\n</head>`);\n  }\n  if (assets.bodyFooter) {\n    html = html.replace(/<\\/body>/i, () => `  ${assets.bodyFooter}\\n</body>`);\n  }\n\n  return /^\\s*<!doctype/i.test(html) ? html : `<!DOCTYPE html>\\n${html}`;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getFarmRendererComponentExtensions, type FarmRenderer } from \"./renderer\";\n\ninterface FarmNotFoundPathConfig {\n  root: string;\n  renderer: FarmRenderer;\n  notFound?: {\n    component?: string;\n  };\n}\n\nexport function resolveFarmNotFoundComponentPath(\n  config: FarmNotFoundPathConfig,\n  appDirs: readonly string[],\n): string | null {\n  const extensions = getFarmRendererComponentExtensions(config.renderer);\n  const configuredPath = config.notFound?.component?.trim();\n\n  if (configuredPath) {\n    const componentPath = path.isAbsolute(configuredPath)\n      ? path.normalize(configuredPath)\n      : path.resolve(config.root, configuredPath);\n    if (!extensions.some((extension) => componentPath.endsWith(extension))) {\n      throw new Error(\n        `notFound.component must use one of the configured renderer extensions: ${extensions.join(\", \")}`,\n      );\n    }\n    if (!fs.existsSync(componentPath) || !fs.statSync(componentPath).isFile()) {\n      throw new Error(`notFound.component was not found: ${componentPath}`);\n    }\n    return componentPath;\n  }\n\n  let discoveredPath: string | null = null;\n  for (const appDir of appDirs) {\n    for (const extension of extensions) {\n      const candidate = path.join(appDir, `not-found${extension}`);\n      if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n        discoveredPath = candidate;\n        break;\n      }\n    }\n  }\n  return discoveredPath;\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Plugin, ResolvedConfig, Rollup, ViteDevServer } from \"vite\";\nimport type { FarmFontDisplay, FarmFontSource, RemoteFontSource } from \"./font\";\n\nconst FONT_IMPORTS = new Set([\"@farm.js/core\", \"@farm.js/core/font\"]);\nconst FONT_FUNCTIONS = new Set<FontLoaderKind>([\"localFont\", \"remoteFont\"]);\nconst FONT_CSS_PREFIX = \"\\0farm:font-css:\";\nconst FONT_RUNTIME_ID = \"\\0farm:font-runtime\";\nconst PUBLIC_FONT_RUNTIME_ID = \"virtual:farm-font-runtime\";\nconst PRELOAD_HEADER_MARKER = \"__FARM_FONT_PRELOAD_HEADER__\";\nconst FONT_SECTION_START = \"/* farm-fonts:start */\";\nconst FONT_SECTION_END = \"/* farm-fonts:end */\";\nconst MODULE_EXTENSION_RE = /\\.[cm]?[jt]sx?$/;\nconst FONT_EXTENSION_RE = /\\.(woff2?|ttf|otf)$/i;\nconst MAX_REMOTE_FONT_BYTES = 20 * 1024 * 1024;\nconst FONT_REGISTRIES_KEY = Symbol.for(\"farm.fontRegistries\");\nconst FONT_REMOTE_BYTES_KEY = Symbol.for(\"farm.fontRemoteBytes\");\n\ntype FontLoaderKind = \"localFont\" | \"remoteFont\";\ntype OutputAsset = Rollup.OutputAsset;\ntype OutputBundle = Rollup.OutputBundle;\n\ninterface AstNode {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n}\n\ninterface FontResource {\n  bytes?: Buffer;\n  extension: string;\n  format: string;\n  hash: string;\n  outputFileName?: string;\n  publicPath?: string;\n  publicUrl: string;\n}\n\ninterface NormalizedFontSource {\n  source: string;\n  weight: string;\n  style: string;\n  unicodeRange?: string;\n  resource: FontResource;\n}\n\ninterface FontDefinition {\n  id: string;\n  family: string;\n  className: string;\n  variableClassName: string;\n  variable?: string;\n  fallback: string[];\n  display: FarmFontDisplay;\n  preload: boolean;\n  preloadResources: Array<{ href: string; type: string }>;\n  weight?: number | string;\n  style?: string;\n  sources: NormalizedFontSource[];\n}\n\ninterface FontCall {\n  kind: FontLoaderKind;\n  binding?: string;\n  node: AstNode;\n  ancestors: readonly AstNode[];\n}\n\ninterface Replacement {\n  start: number;\n  end: number;\n  code: string;\n}\n\nexport interface TransformFarmFontCallsOptions {\n  code: string;\n  id: string;\n  root: string;\n  production: boolean;\n  parse: (code: string) => AstNode;\n  register: (\n    moduleId: string,\n    calls: Array<{ kind: FontLoaderKind; options: Record<string, unknown> }>,\n  ) => Promise<FontDefinition[]>;\n}\n\nexport interface TransformFarmFontCallsResult {\n  code: string;\n  fonts: FontDefinition[];\n}\n\nconst registries = getGlobalMap<string, FarmFontRegistry>(FONT_REGISTRIES_KEY);\nconst remoteBytes = getGlobalMap<string, Promise<Buffer>>(FONT_REMOTE_BYTES_KEY);\n\nexport function farmFontImportsPlugin(\n  options: { root?: string; basePath?: string; publicDir?: string | false } = {},\n): Plugin {\n  let root = normalizeRoot(options.root || process.cwd());\n  let production = process.env.NODE_ENV === \"production\";\n  let registry = getOrCreateRegistry(root, options.basePath, options.publicDir);\n\n  const updateRoot = (nextRoot: string, basePath?: string, publicDir?: string | false) => {\n    const normalized = normalizeRoot(nextRoot);\n    root = normalized;\n    registry = getOrCreateRegistry(root, basePath, publicDir);\n  };\n\n  return {\n    name: \"farm:font-imports\",\n    enforce: \"post\",\n\n    configResolved(config: ResolvedConfig) {\n      production = config.command === \"build\";\n      updateRoot(\n        config.root,\n        options.basePath || config.base,\n        options.publicDir === undefined ? config.publicDir : options.publicDir,\n      );\n      registry.production = production;\n    },\n\n    configureServer(server: ViteDevServer) {\n      updateRoot(\n        server.config.root,\n        options.basePath || server.config.base,\n        options.publicDir === undefined ? server.config.publicDir : options.publicDir,\n      );\n      registry.production = false;\n      server.middlewares.use(async (req, res, next) => {\n        const pathname = new URL(req.url || \"/\", \"http://farm.local\").pathname;\n\n        if (pathname === \"/@farm/fonts.css\") {\n          res.statusCode = 200;\n          res.setHeader(\"Content-Type\", \"text/css; charset=utf-8\");\n          res.setHeader(\"Cache-Control\", \"no-store\");\n          res.end(registry.renderCss(false));\n          return;\n        }\n\n        const resource = registry.getDevResource(pathname);\n        if (!resource?.bytes) {\n          next();\n          return;\n        }\n\n        res.statusCode = 200;\n        res.setHeader(\"Content-Type\", fontContentType(resource.extension));\n        res.setHeader(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n        res.end(resource.bytes);\n      });\n    },\n\n    resolveId(id) {\n      if (id === PUBLIC_FONT_RUNTIME_ID || id === FONT_RUNTIME_ID) return FONT_RUNTIME_ID;\n      if (id.startsWith(\"virtual:farm-font-css/\")) {\n        return `${FONT_CSS_PREFIX}${id.slice(\"virtual:farm-font-css/\".length)}`;\n      }\n      if (id.startsWith(FONT_CSS_PREFIX)) return id;\n      return null;\n    },\n\n    load(id) {\n      if (id === FONT_RUNTIME_ID) {\n        return `export const farmFontPreloadHeader = decodeURIComponent(${JSON.stringify(PRELOAD_HEADER_MARKER)});`;\n      }\n      if (!id.startsWith(FONT_CSS_PREFIX)) return null;\n      return registry.renderFontCss(\n        id.slice(FONT_CSS_PREFIX.length).replace(/\\.css$/, \"\"),\n        production,\n      );\n    },\n\n    async transform(code, id) {\n      const result = await transformFarmFontCalls({\n        code,\n        id,\n        root,\n        production,\n        parse: (source) => this.parse(source) as unknown as AstNode,\n        register: (moduleId, calls) => registry.register(moduleId, calls, production),\n      });\n\n      if (!result) registry.clearModule(id.split(\"?\", 1)[0]);\n\n      return result ? { code: result.code, map: null } : null;\n    },\n\n    async generateBundle(_options, bundle) {\n      registry.emitAssets(this, bundle);\n    },\n  };\n}\n\nexport async function transformFarmFontCalls(\n  options: TransformFarmFontCallsOptions,\n): Promise<TransformFarmFontCallsResult | null> {\n  const cleanId = options.id.split(\"?\", 1)[0];\n  if (\n    !MODULE_EXTENSION_RE.test(cleanId) ||\n    /\\.d\\.[cm]?ts$/.test(cleanId) ||\n    !containsFontFunction(options.code)\n  ) {\n    return null;\n  }\n\n  const ast = options.parse(options.code);\n  const bindings = findFontBindings(ast);\n  if (bindings.named.size === 0 && bindings.namespaces.size === 0) return null;\n\n  const calls = findFontCalls(ast, bindings);\n  if (calls.length === 0) return null;\n  validateFontBindingReferences(ast, calls, cleanId);\n\n  const registeredCalls = calls.map((call) => ({\n    kind: call.kind,\n    options: readFontOptions(options.code, cleanId, call),\n  }));\n  const fonts = await options.register(cleanId, registeredCalls);\n  const replacements: Replacement[] = calls.map((call, index) => ({\n    start: call.node.start,\n    end: call.node.end,\n    code: serializeFontResult(fonts[index]),\n  }));\n  replacements.push(\n    ...createFontImportReplacements(\n      options.code,\n      ast,\n      new Set(calls.map((call) => call.binding).filter((value): value is string => Boolean(value))),\n    ),\n  );\n  const imports = options.production\n    ? \"\"\n    : Array.from(new Set(fonts.map((font) => font.id)))\n        .map((id) => `import ${JSON.stringify(`virtual:farm-font-css/${id}.css`)};`)\n        .join(\"\\n\");\n\n  return {\n    code: `${applyReplacements(options.code, replacements)}\\n${imports}\\n`,\n    fonts,\n  };\n}\n\nexport function renderFarmFontDevHead(root: string): string {\n  const registry = registries.get(normalizeRoot(root));\n  if (!registry || registry.production || registry.size === 0) return \"\";\n  return `${registry.renderPreloadTags(false)}\\n  <link rel=\"stylesheet\" href=\"/@farm/fonts.css\">`;\n}\n\nclass FarmFontRegistry {\n  root: string;\n  basePath: string;\n  publicDir: string | false;\n  production = false;\n  private modules = new Map<string, FontDefinition[]>();\n  private definitions = new Map<string, FontDefinition>();\n  private resources = new Map<string, FontResource>();\n\n  constructor(root: string, basePath = \"/\", publicDir?: string | false) {\n    this.root = root;\n    this.basePath = normalizeBasePath(basePath);\n    this.publicDir = normalizePublicDir(root, publicDir);\n  }\n\n  get size(): number {\n    return this.getDefinitions().length;\n  }\n\n  async register(\n    moduleId: string,\n    calls: Array<{ kind: FontLoaderKind; options: Record<string, unknown> }>,\n    production: boolean,\n  ): Promise<FontDefinition[]> {\n    const definitions: FontDefinition[] = [];\n    for (const call of calls) {\n      definitions.push(await this.createDefinition(moduleId, call.kind, call.options, production));\n    }\n    this.modules.set(moduleId, definitions);\n    for (const definition of definitions) this.definitions.set(definition.id, definition);\n    return definitions;\n  }\n\n  clearModule(moduleId: string): void {\n    this.modules.delete(moduleId);\n  }\n\n  renderFontCss(id: string, production: boolean): string {\n    const definition = this.definitions.get(id);\n    return definition ? renderFontDefinitionCss(definition, production, this.basePath) : \"\";\n  }\n\n  renderCss(production: boolean): string {\n    const css = this.getDefinitions()\n      .map((definition) => renderFontDefinitionCss(definition, production, this.basePath))\n      .join(\"\\n\\n\");\n    return css ? `${FONT_SECTION_START}\\n${css}\\n${FONT_SECTION_END}\\n` : \"\";\n  }\n\n  renderPreloadHeader(production: boolean): string {\n    return this.getPreloadResources(production)\n      .map(\n        ({ url, resource }) =>\n          `<${url}>; rel=preload; as=font; type=${fontContentType(resource.extension)}; crossorigin`,\n      )\n      .join(\", \");\n  }\n\n  renderPreloadTags(production: boolean): string {\n    return this.getPreloadResources(production)\n      .map(\n        ({ url, resource }) =>\n          `<link rel=\"preload\" href=\"${escapeHtmlAttribute(url)}\" as=\"font\" type=\"${fontContentType(resource.extension)}\" crossorigin>`,\n      )\n      .join(\"\\n  \");\n  }\n\n  getDevResource(pathname: string): FontResource | undefined {\n    for (const resource of this.getActiveResources()) {\n      if (resource.bytes && resourceUrl(resource, false, this.basePath) === pathname) {\n        return resource;\n      }\n    }\n    return undefined;\n  }\n\n  emitAssets(context: { emitFile: (file: any) => string }, bundle: OutputBundle): void {\n    for (const resource of this.getActiveResources()) {\n      if (!resource.bytes || !resource.outputFileName) continue;\n      if (bundle[resource.outputFileName]) continue;\n      context.emitFile({\n        type: \"asset\",\n        fileName: resource.outputFileName,\n        source: resource.bytes,\n      });\n    }\n\n    const css = this.renderCss(true);\n    if (css) {\n      const cssAssets = Object.values(bundle).filter(\n        (entry): entry is OutputAsset => entry.type === \"asset\" && entry.fileName.endsWith(\".css\"),\n      );\n      const clientCss =\n        cssAssets.find(\n          (entry): entry is OutputAsset =>\n            entry.type === \"asset\" && entry.fileName === \"farm-client.css\",\n        ) ?? (cssAssets.length === 1 ? cssAssets[0] : undefined);\n      if (clientCss) {\n        clientCss.source = replaceFontSection(assetSourceToString(clientCss.source), css);\n      } else if (!bundle[\"farm-fonts.css\"]) {\n        context.emitFile({\n          type: \"asset\",\n          fileName: \"farm-fonts.css\",\n          source: css,\n        });\n      }\n    }\n\n    const preloadHeader = encodeURIComponent(this.renderPreloadHeader(true));\n    for (const entry of Object.values(bundle)) {\n      if (entry.type === \"chunk\" && entry.code.includes(PRELOAD_HEADER_MARKER)) {\n        entry.code = entry.code.split(PRELOAD_HEADER_MARKER).join(preloadHeader);\n      }\n    }\n  }\n\n  private getDefinitions(): FontDefinition[] {\n    const active = new Map<string, FontDefinition>();\n    for (const definitions of this.modules.values()) {\n      for (const definition of definitions) active.set(definition.id, definition);\n    }\n    return Array.from(active.values()).sort((left, right) => left.id.localeCompare(right.id));\n  }\n\n  private getActiveResources(): FontResource[] {\n    const active = new Set<FontResource>();\n    for (const definition of this.getDefinitions()) {\n      for (const source of definition.sources) active.add(source.resource);\n    }\n    return Array.from(active);\n  }\n\n  private getPreloadResources(production: boolean) {\n    const seen = new Set<string>();\n    const resources: Array<{ url: string; resource: FontResource }> = [];\n    for (const definition of this.getDefinitions()) {\n      if (!definition.preload) continue;\n      for (const source of definition.sources) {\n        const url = resourceUrl(source.resource, production, this.basePath);\n        if (seen.has(url)) continue;\n        seen.add(url);\n        resources.push({ url, resource: source.resource });\n      }\n    }\n    return resources;\n  }\n\n  private async createDefinition(\n    moduleId: string,\n    kind: FontLoaderKind,\n    raw: Record<string, unknown>,\n    production: boolean,\n  ): Promise<FontDefinition> {\n    validateOptionKeys(moduleId, kind, raw);\n    const family = requireString(raw.family, moduleId, `${kind}() family`);\n    const display = (raw.display ?? \"swap\") as FarmFontDisplay;\n    if (![\"auto\", \"block\", \"swap\", \"fallback\", \"optional\"].includes(display)) {\n      throw fontError(moduleId, `invalid font-display value ${JSON.stringify(display)}`);\n    }\n    const variable = optionalString(raw.variable, moduleId, `${kind}() variable`);\n    if (variable && !/^--[A-Za-z_][\\w-]*$/.test(variable)) {\n      throw fontError(moduleId, `font variable must be a CSS custom property such as --font-sans`);\n    }\n    const fallback = readStringArray(raw.fallback, moduleId, `${kind}() fallback`);\n    const defaultWeight = optionalWeight(raw.weight, moduleId);\n    const defaultStyle = optionalCssDescriptor(raw.style, moduleId, \"style\") || \"normal\";\n    const sources = readSources(raw.src, moduleId, kind, defaultWeight, defaultStyle);\n    const strategy = kind === \"remoteFont\" ? (raw.strategy ?? \"self-host\") : \"self-host\";\n    if (strategy !== \"self-host\" && strategy !== \"external\") {\n      throw fontError(moduleId, `remoteFont() strategy must be \"self-host\" or \"external\"`);\n    }\n    const integrity = optionalString(raw.integrity, moduleId, `${kind}() integrity`);\n\n    const normalizedSources: NormalizedFontSource[] = [];\n    for (const source of sources) {\n      const resource = await this.resolveResource({\n        kind,\n        moduleId,\n        source: source.path,\n        strategy,\n        integrity: source.integrity ?? integrity,\n        production,\n      });\n      normalizedSources.push({\n        source: source.path,\n        weight: String(source.weight ?? defaultWeight ?? \"400\"),\n        style: source.style || defaultStyle,\n        unicodeRange: source.unicodeRange,\n        resource,\n      });\n    }\n\n    const identity = JSON.stringify({\n      family,\n      display,\n      variable,\n      fallback,\n      preload: raw.preload !== false,\n      sources: normalizedSources.map((source) => ({\n        hash: source.resource.hash,\n        url: source.resource.publicUrl,\n        weight: source.weight,\n        style: source.style,\n        unicodeRange: source.unicodeRange,\n      })),\n    });\n    const id = createHash(\"sha256\").update(identity).digest(\"hex\").slice(0, 10);\n\n    return {\n      id,\n      family,\n      className: `farm-font-${id}`,\n      variableClassName: variable ? `farm-font-variable-${id}` : \"\",\n      variable,\n      fallback,\n      display,\n      preload: raw.preload !== false,\n      preloadResources:\n        raw.preload === false\n          ? []\n          : normalizedSources.map(({ resource }) => ({\n              href: resourceUrl(resource, production, this.basePath),\n              type: fontContentType(resource.extension),\n            })),\n      weight: defaultWeight,\n      style: raw.style === undefined ? undefined : defaultStyle,\n      sources: normalizedSources,\n    };\n  }\n\n  private async resolveResource(input: {\n    kind: FontLoaderKind;\n    moduleId: string;\n    source: string;\n    strategy: unknown;\n    integrity?: string;\n    production: boolean;\n  }): Promise<FontResource> {\n    if (input.kind === \"remoteFont\") {\n      let url: URL;\n      try {\n        url = new URL(input.source);\n      } catch {\n        throw fontError(input.moduleId, `remoteFont() source must be an absolute HTTPS URL`);\n      }\n      if (url.protocol !== \"https:\") {\n        throw fontError(input.moduleId, `remoteFont() only accepts HTTPS URLs`);\n      }\n      const extension = extensionFromPath(url.pathname);\n      if (input.strategy === \"external\") {\n        const hash = createHash(\"sha256\").update(url.href).digest(\"hex\").slice(0, 12);\n        const resource = {\n          extension,\n          format: fontFormat(extension),\n          hash,\n          publicUrl: url.href,\n        };\n        this.resources.set(`external:${url.href}`, resource);\n        return resource;\n      }\n\n      const bytes = await fetchRemoteFont(url, input.integrity);\n      return this.createSelfHostedResource(bytes, extension, path.basename(url.pathname));\n    }\n\n    if (input.source.startsWith(\"/\")) {\n      return this.createPublicResource(input.moduleId, input.source);\n    }\n\n    const resolvedPath = resolveLocalFontPath(input.source, input.moduleId, this.root);\n    if (!FONT_EXTENSION_RE.test(resolvedPath)) {\n      throw fontError(\n        input.moduleId,\n        `unsupported local font file ${JSON.stringify(input.source)}`,\n      );\n    }\n    let bytes: Buffer;\n    try {\n      bytes = await readFile(resolvedPath);\n    } catch (error) {\n      throw fontError(\n        input.moduleId,\n        `could not read ${JSON.stringify(input.source)}: ${(error as Error).message}`,\n      );\n    }\n    return this.createSelfHostedResource(\n      bytes,\n      path.extname(resolvedPath),\n      path.basename(resolvedPath),\n    );\n  }\n\n  private async createPublicResource(moduleId: string, source: string): Promise<FontResource> {\n    if (!this.publicDir) {\n      throw fontError(\n        moduleId,\n        `cannot resolve ${JSON.stringify(source)} because publicDir is disabled`,\n      );\n    }\n    const publicPath = normalizePublicFontPath(source, moduleId);\n    const resolvedPath = path.resolve(this.publicDir, `.${publicPath}`);\n    if (!isPathInside(this.publicDir, resolvedPath)) {\n      throw fontError(moduleId, `public font path must stay inside publicDir`);\n    }\n    if (!FONT_EXTENSION_RE.test(resolvedPath)) {\n      throw fontError(moduleId, `unsupported public font file ${JSON.stringify(source)}`);\n    }\n\n    let bytes: Buffer;\n    try {\n      bytes = await readFile(resolvedPath);\n    } catch (error) {\n      throw fontError(\n        moduleId,\n        `could not read ${JSON.stringify(source)} from publicDir: ${(error as Error).message}`,\n      );\n    }\n\n    const extension = path.extname(resolvedPath).toLowerCase();\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 12);\n    const resource: FontResource = {\n      extension,\n      format: fontFormat(extension),\n      hash,\n      publicPath,\n      publicUrl: \"\",\n    };\n    this.resources.set(`public:${publicPath}`, resource);\n    return resource;\n  }\n\n  private createSelfHostedResource(\n    bytes: Buffer,\n    extension: string,\n    fileName: string,\n  ): FontResource {\n    const normalizedExtension = extension.toLowerCase();\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 12);\n    const baseName = sanitizeFileName(path.basename(fileName, extension)) || \"font\";\n    const outputFileName = `assets/fonts/${baseName}-h${hash}${normalizedExtension}`;\n    const key = `${hash}${normalizedExtension}`;\n    const existing = this.resources.get(key);\n    if (existing) return existing;\n\n    const resource: FontResource = {\n      bytes,\n      extension: normalizedExtension,\n      format: fontFormat(normalizedExtension),\n      hash,\n      outputFileName,\n      publicUrl: \"\",\n    };\n    this.resources.set(key, resource);\n    return resource;\n  }\n}\n\nfunction findFontBindings(ast: AstNode) {\n  const named = new Map<string, FontLoaderKind>();\n  const namespaces = new Set<string>();\n  const body = Array.isArray(ast.body) ? ast.body : [];\n\n  for (const statement of body) {\n    if (!isAstNode(statement) || statement.type !== \"ImportDeclaration\") continue;\n    const source = isAstNode(statement.source) ? statement.source.value : undefined;\n    if (typeof source !== \"string\" || !FONT_IMPORTS.has(source)) continue;\n\n    const specifiers = Array.isArray(statement.specifiers) ? statement.specifiers : [];\n    for (const specifier of specifiers) {\n      if (!isAstNode(specifier) || !isAstNode(specifier.local)) continue;\n      const localName = specifier.local.name;\n      if (typeof localName !== \"string\") continue;\n      if (specifier.type === \"ImportNamespaceSpecifier\") {\n        namespaces.add(localName);\n        continue;\n      }\n      if (specifier.type !== \"ImportSpecifier\" || !isAstNode(specifier.imported)) continue;\n      const importedName = specifier.imported.name ?? specifier.imported.value;\n      if (isFontLoaderKind(importedName)) named.set(localName, importedName);\n    }\n  }\n  return { named, namespaces };\n}\n\nfunction findFontCalls(ast: AstNode, bindings: ReturnType<typeof findFontBindings>): FontCall[] {\n  const calls: FontCall[] = [];\n  walkAst(ast, (node, ancestors) => {\n    if (node.type !== \"CallExpression\" || !isAstNode(node.callee)) return;\n    let kind: FontLoaderKind | undefined;\n    if (node.callee.type === \"Identifier\" && typeof node.callee.name === \"string\") {\n      kind = bindings.named.get(node.callee.name);\n      if (kind) calls.push({ kind, binding: node.callee.name, node, ancestors });\n    } else if (\n      node.callee.type === \"MemberExpression\" &&\n      node.callee.computed !== true &&\n      isAstNode(node.callee.object) &&\n      isAstNode(node.callee.property) &&\n      node.callee.object.type === \"Identifier\" &&\n      node.callee.property.type === \"Identifier\" &&\n      typeof node.callee.object.name === \"string\" &&\n      typeof node.callee.property.name === \"string\" &&\n      bindings.namespaces.has(node.callee.object.name) &&\n      isFontLoaderKind(node.callee.property.name)\n    ) {\n      kind = node.callee.property.name;\n    }\n    if (kind && node.callee.type !== \"Identifier\") calls.push({ kind, node, ancestors });\n  });\n  return calls;\n}\n\nfunction validateFontBindingReferences(ast: AstNode, calls: FontCall[], id: string): void {\n  const calledBindings = new Set(\n    calls.map((call) => call.binding).filter((binding): binding is string => Boolean(binding)),\n  );\n  const transformedCallees = new Set(\n    calls.flatMap((call) => {\n      const callee = call.node.callee;\n      return call.binding && isAstNode(callee) ? [`${callee.start}:${callee.end}`] : [];\n    }),\n  );\n\n  walkAst(ast, (node, ancestors) => {\n    if (\n      node.type !== \"Identifier\" ||\n      typeof node.name !== \"string\" ||\n      !calledBindings.has(node.name)\n    ) {\n      return;\n    }\n    const parent = ancestors.at(-1);\n    if (!parent || isNonReferenceIdentifier(node, parent)) return;\n    if (transformedCallees.has(`${node.start}:${node.end}`)) return;\n    throw fontError(\n      id,\n      `${node.name} can only be referenced by statically compiled font declarations`,\n    );\n  });\n}\n\nfunction isNonReferenceIdentifier(node: AstNode, parent: AstNode): boolean {\n  if (parent.type === \"ImportSpecifier\") return true;\n  if (\n    (parent.type === \"MemberExpression\" || parent.type === \"OptionalMemberExpression\") &&\n    parent.property === node &&\n    parent.computed !== true\n  ) {\n    return true;\n  }\n  if (\n    (parent.type === \"Property\" || parent.type === \"PropertyDefinition\") &&\n    parent.key === node &&\n    parent.computed !== true &&\n    parent.shorthand !== true\n  ) {\n    return true;\n  }\n  return false;\n}\n\nfunction createFontImportReplacements(\n  code: string,\n  ast: AstNode,\n  calledBindings: ReadonlySet<string>,\n): Replacement[] {\n  if (calledBindings.size === 0) return [];\n  const replacements: Replacement[] = [];\n  const body = Array.isArray(ast.body) ? ast.body : [];\n\n  for (const statement of body) {\n    if (!isAstNode(statement) || statement.type !== \"ImportDeclaration\") continue;\n    const source = isAstNode(statement.source) ? statement.source.value : undefined;\n    if (typeof source !== \"string\" || !FONT_IMPORTS.has(source)) continue;\n    const specifiers = (Array.isArray(statement.specifiers) ? statement.specifiers : []).filter(\n      isAstNode,\n    );\n    const retained = specifiers.filter((specifier) => {\n      if (specifier.type !== \"ImportSpecifier\" || !isAstNode(specifier.local)) return true;\n      return typeof specifier.local.name !== \"string\" || !calledBindings.has(specifier.local.name);\n    });\n    if (retained.length === specifiers.length) continue;\n\n    replacements.push({\n      start: statement.start,\n      end: statement.end,\n      code: renderImportDeclaration(code, source, retained),\n    });\n  }\n\n  return replacements;\n}\n\nfunction renderImportDeclaration(code: string, source: string, specifiers: AstNode[]): string {\n  if (specifiers.length === 0) return \"\";\n  const defaultSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportDefaultSpecifier\",\n  );\n  const namespaceSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportNamespaceSpecifier\",\n  );\n  const namedSpecifiers = specifiers.filter((specifier) => specifier.type === \"ImportSpecifier\");\n  const parts: string[] = [];\n\n  if (defaultSpecifier && isAstNode(defaultSpecifier.local)) {\n    parts.push(code.slice(defaultSpecifier.local.start, defaultSpecifier.local.end));\n  }\n  if (namespaceSpecifier && isAstNode(namespaceSpecifier.local)) {\n    parts.push(`* as ${code.slice(namespaceSpecifier.local.start, namespaceSpecifier.local.end)}`);\n  }\n  if (namedSpecifiers.length > 0) {\n    parts.push(\n      `{ ${namedSpecifiers.map((specifier) => code.slice(specifier.start, specifier.end)).join(\", \")} }`,\n    );\n  }\n\n  return parts.length > 0 ? `import ${parts.join(\", \")} from ${JSON.stringify(source)};` : \"\";\n}\n\nfunction readFontOptions(code: string, id: string, call: FontCall): Record<string, unknown> {\n  if (!call.binding) {\n    throw fontError(id, `${call.kind}() must use a named import from @farm.js/core/font`);\n  }\n  const args = Array.isArray(call.node.arguments) ? call.node.arguments : [];\n  if (args.length !== 1 || !isAstNode(args[0]) || args[0].type !== \"ObjectExpression\") {\n    throw fontError(id, `${call.kind}() requires one inline options object`);\n  }\n  const parent = call.ancestors.at(-1);\n  if (!parent || parent.type !== \"VariableDeclarator\" || parent.init !== call.node) {\n    throw fontError(id, `${call.kind}() must initialize a module-scope variable`);\n  }\n  const declaration = call.ancestors.at(-2);\n  const statement = call.ancestors.at(-3);\n  const statementParent = call.ancestors.at(-4);\n  const isModuleScope =\n    declaration?.type === \"VariableDeclaration\" &&\n    (statement?.type === \"Program\" ||\n      (statement?.type === \"ExportNamedDeclaration\" && statementParent?.type === \"Program\"));\n  if (!isModuleScope || call.ancestors.some((ancestor) => isFunctionNode(ancestor))) {\n    throw fontError(id, `${call.kind}() must be declared directly at module scope`);\n  }\n  return evaluateStaticObject(code, id, args[0]);\n}\n\nfunction evaluateStaticObject(code: string, id: string, node: AstNode): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  const properties = Array.isArray(node.properties) ? node.properties : [];\n  for (const property of properties) {\n    if (!isAstNode(property) || property.type !== \"Property\" || property.computed === true) {\n      throw fontError(id, \"font options do not support spreads or computed properties\");\n    }\n    const key = readPropertyName(property.key);\n    if (!key || !isAstNode(property.value)) {\n      throw fontError(id, \"font options must use static property names and values\");\n    }\n    result[key] = evaluateStaticValue(code, id, property.value);\n  }\n  return result;\n}\n\nfunction evaluateStaticValue(code: string, id: string, node: AstNode): unknown {\n  if (node.type === \"Literal\") return node.value;\n  if (node.type === \"TemplateLiteral\") {\n    const expressions = Array.isArray(node.expressions) ? node.expressions : [];\n    const quasis = Array.isArray(node.quasis) ? node.quasis : [];\n    if (expressions.length === 0 && quasis.length === 1 && isAstNode(quasis[0])) {\n      const templateValue = quasis[0].value;\n      const value =\n        templateValue && typeof templateValue === \"object\"\n          ? (templateValue as { cooked?: unknown }).cooked\n          : undefined;\n      if (typeof value === \"string\") return value;\n    }\n  }\n  if (node.type === \"ArrayExpression\") {\n    const elements = Array.isArray(node.elements) ? node.elements : [];\n    return elements.map((element) => {\n      if (!isAstNode(element) || element.type === \"SpreadElement\") {\n        throw fontError(id, \"font option arrays must contain static values\");\n      }\n      return evaluateStaticValue(code, id, element);\n    });\n  }\n  if (node.type === \"ObjectExpression\") return evaluateStaticObject(code, id, node);\n  if (\n    node.type === \"UnaryExpression\" &&\n    (node.operator === \"+\" || node.operator === \"-\") &&\n    isAstNode(node.argument)\n  ) {\n    const value = evaluateStaticValue(code, id, node.argument);\n    if (typeof value === \"number\") return node.operator === \"-\" ? -value : value;\n  }\n  throw fontError(\n    id,\n    `font options must be statically analyzable near ${code.slice(node.start, node.end)}`,\n  );\n}\n\nfunction readSources(\n  value: unknown,\n  id: string,\n  kind: FontLoaderKind,\n  weight: number | string | undefined,\n  style: string,\n): Array<FarmFontSource & Pick<RemoteFontSource, \"integrity\">> {\n  if (typeof value === \"string\") return [{ path: value, weight, style }];\n  if (!Array.isArray(value) || value.length === 0) {\n    throw fontError(id, `${kind}() src must be a string or a non-empty source array`);\n  }\n  return value.map((entry, index) => {\n    if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n      throw fontError(id, `${kind}() src[${index}] must be an object`);\n    }\n    const source = entry as Record<string, unknown>;\n    const unknown = Object.keys(source).filter(\n      (key) =>\n        ![\n          \"path\",\n          \"weight\",\n          \"style\",\n          \"unicodeRange\",\n          ...(kind === \"remoteFont\" ? [\"integrity\"] : []),\n        ].includes(key),\n    );\n    if (unknown.length) throw fontError(id, `unknown src[${index}] option ${unknown[0]}`);\n    return {\n      path: requireString(source.path, id, `${kind}() src[${index}].path`),\n      weight: optionalWeight(source.weight, id) ?? weight,\n      style: optionalCssDescriptor(source.style, id, \"style\") || style,\n      unicodeRange: optionalUnicodeRange(source.unicodeRange, id),\n      integrity: optionalString(source.integrity, id, `${kind}() src[${index}].integrity`),\n    };\n  });\n}\n\nfunction validateOptionKeys(id: string, kind: FontLoaderKind, raw: Record<string, unknown>) {\n  const allowed = new Set([\n    \"src\",\n    \"family\",\n    \"weight\",\n    \"style\",\n    \"display\",\n    \"variable\",\n    \"fallback\",\n    \"preload\",\n    ...(kind === \"remoteFont\" ? [\"strategy\", \"integrity\"] : []),\n  ]);\n  const unknown = Object.keys(raw).find((key) => !allowed.has(key));\n  if (unknown) throw fontError(id, `unknown ${kind}() option ${JSON.stringify(unknown)}`);\n  if (typeof raw.preload !== \"undefined\" && typeof raw.preload !== \"boolean\") {\n    throw fontError(id, `${kind}() preload must be a boolean`);\n  }\n}\n\nfunction serializeFontResult(font: FontDefinition): string {\n  const stack = renderFamilyStack(font.family, font.fallback);\n  return JSON.stringify({\n    className: font.className,\n    variable: font.variableClassName,\n    style: {\n      fontFamily: stack,\n      ...(font.style ? { fontStyle: font.style } : {}),\n      ...(font.weight !== undefined && !String(font.weight).includes(\" \")\n        ? { fontWeight: font.weight }\n        : {}),\n    },\n    preloads: font.preloadResources,\n  });\n}\n\nfunction renderFontDefinitionCss(\n  font: FontDefinition,\n  production: boolean,\n  basePath: string,\n): string {\n  const faces = font.sources.map((source) => {\n    const descriptors = [\n      `  font-family: ${quoteCssString(font.family)};`,\n      `  src: url(${quoteCssString(resourceUrl(source.resource, production, basePath))}) format(${quoteCssString(source.resource.format)});`,\n      `  font-display: ${font.display};`,\n      `  font-weight: ${source.weight};`,\n      `  font-style: ${source.style};`,\n      ...(source.unicodeRange ? [`  unicode-range: ${source.unicodeRange};`] : []),\n    ];\n    return `@font-face {\\n${descriptors.join(\"\\n\")}\\n}`;\n  });\n  const stack = renderFamilyStack(font.family, font.fallback);\n  faces.push(`.${font.className} {\\n  font-family: ${stack};\\n}`);\n  if (font.variable && font.variableClassName) {\n    faces.push(`.${font.variableClassName} {\\n  ${font.variable}: ${stack};\\n}`);\n  }\n  return faces.join(\"\\n\\n\");\n}\n\nfunction resourceUrl(resource: FontResource, production: boolean, basePath: string): string {\n  // Production font URLs are root-relative: emitted assets land in the client\n  // output, which the server publishes at \"/\" regardless of basePath — the\n  // same convention as the hashed client JS/CSS hrefs. Only the dev server\n  // mounts under basePath (the Vite base), so only dev URLs carry the prefix.\n  if (resource.publicPath) {\n    return resource.publicPath;\n  }\n  if (!resource.bytes) return resource.publicUrl;\n  if (!production) {\n    return joinBasePath(basePath, `/@farm/font/${resource.hash}${resource.extension}`);\n  }\n  return `/${resource.outputFileName}`;\n}\n\nasync function fetchRemoteFont(url: URL, integrity?: string): Promise<Buffer> {\n  const key = `${url.href}\\0${integrity || \"\"}`;\n  let pending = remoteBytes.get(key);\n  if (!pending) {\n    pending = (async () => {\n      const response = await fetch(url, {\n        headers: { \"User-Agent\": \"Farm.js font compiler\" },\n        redirect: \"follow\",\n      });\n      if (!response.ok)\n        throw new Error(`request returned ${response.status} ${response.statusText}`);\n      const length = Number(response.headers.get(\"content-length\") || 0);\n      if (length > MAX_REMOTE_FONT_BYTES) throw new Error(\"font exceeds the 20 MB limit\");\n      const bytes = await readResponseBodyWithLimit(response, MAX_REMOTE_FONT_BYTES);\n      if (integrity) verifyIntegrity(bytes, integrity);\n      return bytes;\n    })().catch((error) => {\n      throw new Error(`[Farm fonts] Failed to download ${url.href}: ${(error as Error).message}`);\n    });\n    remoteBytes.set(key, pending);\n    const clearPending = () => {\n      if (remoteBytes.get(key) === pending) remoteBytes.delete(key);\n    };\n    void pending.then(clearPending, clearPending);\n  }\n  return pending;\n}\n\nasync function readResponseBodyWithLimit(response: Response, limit: number): Promise<Buffer> {\n  if (!response.body) return Buffer.alloc(0);\n  const reader = response.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n\n  while (true) {\n    const chunk = await reader.read();\n    if (chunk.done) break;\n    total += chunk.value.byteLength;\n    if (total > limit) {\n      await reader.cancel(\"font exceeds the configured byte limit\");\n      throw new Error(\"font exceeds the 20 MB limit\");\n    }\n    chunks.push(chunk.value);\n  }\n\n  return Buffer.concat(chunks, total);\n}\n\nfunction verifyIntegrity(bytes: Buffer, integrity: string): void {\n  const entries = integrity.trim().split(/\\s+/);\n  const supported = entries\n    .map((entry) => entry.match(/^(sha(?:256|384|512))-(.+)$/))\n    .filter((entry): entry is RegExpMatchArray => Boolean(entry));\n  if (supported.length === 0) throw new Error(\"integrity must use sha256, sha384, or sha512\");\n  const matches = supported.some((entry) => {\n    const actual = createHash(entry[1]).update(bytes).digest();\n    const expected = Buffer.from(entry[2], \"base64\");\n    return actual.length === expected.length && timingSafeEqual(actual, expected);\n  });\n  if (!matches) throw new Error(\"downloaded font did not match its integrity value\");\n}\n\nfunction resolveLocalFontPath(source: string, importer: string, root: string): string {\n  if (source.startsWith(\".\")) return path.resolve(path.dirname(importer), source);\n  if (path.isAbsolute(source)) {\n    return source;\n  }\n  try {\n    return createRequire(pathToFileURL(importer)).resolve(source);\n  } catch {\n    const segments = source.replace(/\\\\/g, \"/\").split(\"/\");\n    if (segments.includes(\"..\")) return path.resolve(root, source);\n\n    let current = path.dirname(importer);\n    const filesystemRoot = path.parse(current).root;\n    while (true) {\n      const candidate = path.join(current, \"node_modules\", ...segments);\n      if (existsSync(candidate)) return candidate;\n      if (current === filesystemRoot) break;\n      current = path.dirname(current);\n    }\n    return path.resolve(root, \"node_modules\", ...segments);\n  }\n}\n\nfunction replaceFontSection(css: string, section: string): string {\n  const start = css.indexOf(FONT_SECTION_START);\n  const end = css.indexOf(FONT_SECTION_END);\n  const withoutExisting =\n    start >= 0 && end >= start\n      ? `${css.slice(0, start)}${css.slice(end + FONT_SECTION_END.length)}`.trimEnd()\n      : css.trimEnd();\n  return `${withoutExisting}${withoutExisting ? \"\\n\\n\" : \"\"}${section}`;\n}\n\nexport function mergeFarmFontCss(clientCss: string, fontCss: string): string {\n  return replaceFontSection(clientCss, fontCss);\n}\n\nfunction getOrCreateRegistry(\n  root: string,\n  basePath = \"/\",\n  publicDir?: string | false,\n): FarmFontRegistry {\n  const normalized = normalizeRoot(root);\n  const existing = registries.get(normalized);\n  if (existing) {\n    existing.basePath = normalizeBasePath(basePath);\n    existing.publicDir = normalizePublicDir(normalized, publicDir);\n    return existing;\n  }\n  const registry = new FarmFontRegistry(normalized, basePath, publicDir);\n  registries.set(normalized, registry);\n  return registry;\n}\n\nfunction getGlobalMap<TKey, TValue>(key: symbol): Map<TKey, TValue> {\n  const runtime = globalThis as typeof globalThis & Record<symbol, unknown>;\n  const existing = runtime[key];\n  if (existing instanceof Map) return existing as Map<TKey, TValue>;\n  const created = new Map<TKey, TValue>();\n  runtime[key] = created;\n  return created;\n}\n\nfunction normalizeRoot(root: string): string {\n  return path.resolve(root).replace(/\\\\/g, \"/\");\n}\n\nfunction normalizePublicDir(root: string, publicDir?: string | false): string | false {\n  if (publicDir === false || publicDir === \"\") return false;\n  return path.resolve(root, publicDir || \"public\");\n}\n\nfunction normalizePublicFontPath(source: string, moduleId: string): string {\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw fontError(moduleId, `public font paths cannot contain a query string or fragment`);\n  }\n  return `/${source.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\")}`;\n}\n\nfunction isPathInside(parent: string, child: string): boolean {\n  const relative = path.relative(parent, child);\n  return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction normalizeBasePath(value: string): string {\n  if (!value || value === \"/\") return \"/\";\n  return `/${value.replace(/^\\/+|\\/+$/g, \"\")}/`;\n}\n\nfunction joinBasePath(basePath: string, value: string): string {\n  return basePath === \"/\" ? value : `${basePath.replace(/\\/$/, \"\")}${value}`;\n}\n\nfunction extensionFromPath(pathname: string): string {\n  const extension = path.extname(pathname).toLowerCase();\n  if (!FONT_EXTENSION_RE.test(extension)) {\n    throw new Error(`[Farm fonts] Remote font URL must end in .woff2, .woff, .ttf, or .otf`);\n  }\n  return extension;\n}\n\nfunction fontFormat(extension: string): string {\n  switch (extension.toLowerCase()) {\n    case \".woff2\":\n      return \"woff2\";\n    case \".woff\":\n      return \"woff\";\n    case \".ttf\":\n      return \"truetype\";\n    case \".otf\":\n      return \"opentype\";\n    default:\n      throw new Error(`[Farm fonts] Unsupported font extension ${extension}`);\n  }\n}\n\nfunction fontContentType(extension: string): string {\n  switch (extension.toLowerCase()) {\n    case \".woff2\":\n      return \"font/woff2\";\n    case \".woff\":\n      return \"font/woff\";\n    case \".ttf\":\n      return \"font/ttf\";\n    case \".otf\":\n      return \"font/otf\";\n    default:\n      return \"application/octet-stream\";\n  }\n}\n\nfunction renderFamilyStack(family: string, fallback: string[]): string {\n  return [quoteCssString(family), ...fallback.map(formatFallbackFamily)].join(\", \");\n}\n\nfunction formatFallbackFamily(value: string): string {\n  return /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|emoji|math|fangsong)$/.test(\n    value,\n  )\n    ? value\n    : quoteCssString(value);\n}\n\nfunction quoteCssString(value: string): string {\n  return JSON.stringify(value.replace(/[\\n\\r\\f]/g, \" \"));\n}\n\nfunction sanitizeFileName(value: string): string {\n  return value\n    .replace(/[^A-Za-z0-9_-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\")\n    .slice(0, 80);\n}\n\nfunction assetSourceToString(source: string | Uint8Array): string {\n  return typeof source === \"string\" ? source : Buffer.from(source).toString(\"utf8\");\n}\n\nfunction applyReplacements(code: string, replacements: Replacement[]): string {\n  let output = code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n  return output;\n}\n\nfunction walkAst(\n  node: AstNode,\n  visit: (node: AstNode, ancestors: readonly AstNode[]) => void,\n  ancestors: readonly AstNode[] = [],\n): void {\n  visit(node, ancestors);\n  const childAncestors = [...ancestors, node];\n  for (const [key, value] of Object.entries(node)) {\n    if ([\"start\", \"end\", \"loc\", \"range\"].includes(key)) continue;\n    if (isAstNode(value)) walkAst(value, visit, childAncestors);\n    else if (Array.isArray(value)) {\n      for (const item of value) if (isAstNode(item)) walkAst(item, visit, childAncestors);\n    }\n  }\n}\n\nfunction readPropertyName(value: unknown): string | undefined {\n  if (!isAstNode(value)) return undefined;\n  if (value.type === \"Identifier\" && typeof value.name === \"string\") return value.name;\n  if (value.type === \"Literal\" && typeof value.value === \"string\") return value.value;\n  return undefined;\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n  return (\n    Boolean(value) &&\n    typeof value === \"object\" &&\n    typeof (value as AstNode).type === \"string\" &&\n    typeof (value as AstNode).start === \"number\" &&\n    typeof (value as AstNode).end === \"number\"\n  );\n}\n\nfunction isFunctionNode(node: AstNode): boolean {\n  return (\n    node.type === \"FunctionDeclaration\" ||\n    node.type === \"FunctionExpression\" ||\n    node.type === \"ArrowFunctionExpression\"\n  );\n}\n\nfunction isFontLoaderKind(value: unknown): value is FontLoaderKind {\n  return typeof value === \"string\" && FONT_FUNCTIONS.has(value as FontLoaderKind);\n}\n\nfunction containsFontFunction(code: string): boolean {\n  return Array.from(FONT_FUNCTIONS).some((name) => code.includes(name));\n}\n\nfunction requireString(value: unknown, id: string, label: string): string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw fontError(id, `${label} must be a non-empty string`);\n  }\n  return value;\n}\n\nfunction optionalString(value: unknown, id: string, label: string): string | undefined {\n  if (value === undefined) return undefined;\n  return requireString(value, id, label);\n}\n\nfunction readStringArray(value: unknown, id: string, label: string): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value) || value.some((entry) => typeof entry !== \"string\")) {\n    throw fontError(id, `${label} must be an array of family names`);\n  }\n  return value as string[];\n}\n\nfunction optionalWeight(value: unknown, id: string): number | string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 1000) {\n    return value;\n  }\n  if (\n    typeof value === \"string\" &&\n    /^(?:[1-9]\\d{0,2}|1000)(?:\\s+(?:[1-9]\\d{0,2}|1000))?$/.test(value)\n  ) {\n    const bounds = value.split(/\\s+/).map(Number);\n    if (bounds.length === 2 && bounds[0] > bounds[1]) {\n      throw fontError(id, `font weight range must be ordered from lowest to highest`);\n    }\n    return value;\n  }\n  throw fontError(id, `font weight must be a number or range such as \"100 900\"`);\n}\n\nfunction optionalCssDescriptor(value: unknown, id: string, label: string): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\" || !/^[A-Za-z0-9 .-]+$/.test(value)) {\n    throw fontError(id, `font ${label} contains unsupported characters`);\n  }\n  return value;\n}\n\nfunction optionalUnicodeRange(value: unknown, id: string): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\" || !/^[Uu+0-9A-Fa-f?*, -]+$/.test(value)) {\n    throw fontError(id, `font unicodeRange contains unsupported characters`);\n  }\n  return value;\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n  return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\");\n}\n\nfunction fontError(id: string, message: string): Error {\n  return new Error(`[Farm fonts] ${message} in ${id.split(\"?\", 1)[0]}`);\n}\n","export const DEFAULT_NOT_FOUND_STYLES = `\nbody {\n  margin: 0;\n}\n\n.farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  place-items: center;\n  padding: 24px;\n  color: var(--farm-not-found-fg);\n  background: var(--farm-not-found-bg);\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  color-scheme: light;\n}\n\n.farm-default-not-found,\n.farm-default-not-found * {\n  box-sizing: border-box;\n}\n\n.farm-default-not-found__content {\n  width: min(100%, 280px);\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n}\n\n.farm-default-not-found__code {\n  margin: 0;\n  color: var(--farm-not-found-fg);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: clamp(88px, 20vw, 140px);\n  font-weight: 800;\n  line-height: 0.75;\n  letter-spacing: -0.1em;\n  transform: translateX(-3px);\n}\n\n@supports (-webkit-text-stroke: 1px currentColor) {\n  .farm-default-not-found__code {\n    color: var(--farm-not-found-bg);\n    -webkit-text-stroke: 2px var(--farm-not-found-fg);\n    text-shadow: 5px 5px 0 var(--farm-not-found-fg);\n  }\n}\n\n.farm-default-not-found__description {\n  width: 100%;\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin: 34px 0 30px;\n  color: var(--farm-not-found-muted);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 10px;\n  line-height: 1;\n  letter-spacing: 0.14em;\n  text-transform: uppercase;\n  white-space: nowrap;\n}\n\n.farm-default-not-found__description::before,\n.farm-default-not-found__description::after {\n  content: \"\";\n  height: 1px;\n  flex: 1 1 auto;\n  background: var(--farm-not-found-line);\n}\n\n.farm-default-not-found__home {\n  min-width: 132px;\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 20px;\n  border: 1px solid var(--farm-not-found-fg);\n  border-radius: 0;\n  color: var(--farm-not-found-button-fg);\n  background: var(--farm-not-found-fg);\n  font-size: 14px;\n  font-weight: 500;\n  line-height: 1;\n  text-decoration: none;\n  transition: opacity 150ms ease-out, transform 100ms ease-out;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-not-found__home:hover {\n    opacity: 0.78;\n  }\n}\n\n.farm-default-not-found__home:active {\n  transform: translateY(1px);\n}\n\n.farm-default-not-found__home:focus-visible {\n  outline: 2px solid var(--farm-not-found-fg);\n  outline-offset: 3px;\n}\n\n@media (prefers-color-scheme: dark) {\n  .farm-default-not-found {\n    --farm-not-found-bg: #0a0a0a;\n    --farm-not-found-fg: #ededed;\n    --farm-not-found-muted: #a1a1a1;\n    --farm-not-found-line: rgba(255, 255, 255, 0.2);\n    --farm-not-found-button-fg: #0a0a0a;\n    color-scheme: dark;\n  }\n}\n\n.dark .farm-default-not-found,\n[data-theme=\"dark\"] .farm-default-not-found,\n[data-color-scheme=\"dark\"] .farm-default-not-found {\n  --farm-not-found-bg: #0a0a0a;\n  --farm-not-found-fg: #ededed;\n  --farm-not-found-muted: #a1a1a1;\n  --farm-not-found-line: rgba(255, 255, 255, 0.2);\n  --farm-not-found-button-fg: #0a0a0a;\n  color-scheme: dark;\n}\n\n.light .farm-default-not-found,\n[data-theme=\"light\"] .farm-default-not-found,\n[data-color-scheme=\"light\"] .farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-not-found__home {\n    transition: none;\n  }\n\n  .farm-default-not-found__home:active {\n    transform: none;\n  }\n}\n`;\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DefaultErrorSourceFrame } from \"../components/error-page\";\n\nexport interface DefaultErrorDiagnostics {\n  name: string;\n  message: string;\n  stack?: string;\n  sourceFrame?: DefaultErrorSourceFrame;\n}\n\ninterface StackLocation {\n  absolutePath: string;\n  displayPath: string;\n  line: number;\n  column: number;\n}\n\nconst SECRET_VALUE_PATTERN =\n  /\\b(api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret[_-]?key|token|password|secret)\\s*[:=]\\s*([^\\s,;]+)/gi;\nconst BEARER_PATTERN = /\\b(Bearer\\s+)[A-Za-z0-9._~+/=-]+/gi;\n\nfunction redactErrorText(value: string): string {\n  return value\n    .replace(BEARER_PATTERN, \"$1[REDACTED]\")\n    .replace(SECRET_VALUE_PATTERN, \"$1=[REDACTED]\");\n}\n\nfunction isPathInsideRoot(root: string, filePath: string): boolean {\n  const relative = path.relative(root, filePath);\n  return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction normalizeStackPath(value: string): string | undefined {\n  const withoutQuery = value.replace(/[?#].*$/, \"\");\n  try {\n    return withoutQuery.startsWith(\"file://\") ? fileURLToPath(withoutQuery) : withoutQuery;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction findStackLocation(stack: string, root: string): StackLocation | undefined {\n  for (const stackLine of stack.split(\"\\n\")) {\n    const match = stackLine.match(\n      /(?:\\()?((?:file:\\/\\/\\/|\\/|[A-Za-z]:[\\\\/])[^\\n()]+):(\\d+):(\\d+)\\)?$/,\n    );\n    if (!match) continue;\n\n    const candidate = normalizeStackPath(match[1]);\n    if (!candidate || candidate.includes(`${path.sep}node_modules${path.sep}`)) continue;\n\n    const absolutePath = path.resolve(candidate);\n    if (!isPathInsideRoot(root, absolutePath) || !fs.existsSync(absolutePath)) continue;\n\n    const relativePath = path.relative(root, absolutePath).split(path.sep).join(\"/\");\n    return {\n      absolutePath,\n      displayPath: relativePath || path.basename(absolutePath),\n      line: Number(match[2]),\n      column: Number(match[3]),\n    };\n  }\n  return undefined;\n}\n\nfunction createSourceFrame(location: StackLocation): DefaultErrorSourceFrame | undefined {\n  try {\n    const sourceLines = fs.readFileSync(location.absolutePath, \"utf8\").split(/\\r?\\n/);\n    if (location.line < 1 || location.line > sourceLines.length) return undefined;\n\n    const start = Math.max(1, location.line - 2);\n    const end = Math.min(sourceLines.length, location.line + 2);\n    const lines = [];\n    for (let line = start; line <= end; line++) {\n      lines.push({\n        number: line,\n        content: sourceLines[line - 1],\n        highlight: line === location.line,\n      });\n    }\n\n    return {\n      file: location.displayPath,\n      line: location.line,\n      column: location.column,\n      lines,\n    };\n  } catch {\n    return undefined;\n  }\n}\n\nfunction sanitizeStack(stack: string, root: string): string {\n  const normalizedRoot = path.resolve(root);\n  return (\n    redactErrorText(stack)\n      .split(normalizedRoot)\n      .join(\"<project>\")\n      // Match displayPath, which reports project-relative paths with POSIX separators.\n      .replace(/<project>[^\\s)]*/g, (segment) => segment.split(\"\\\\\").join(\"/\"))\n      .split(\"\\n\")\n      .filter((line, index) => index === 0 || !line.includes(\"node:internal\"))\n      .slice(0, 14)\n      .join(\"\\n\")\n  );\n}\n\nexport function createDefaultErrorDiagnostics(\n  error: unknown,\n  root: string,\n): DefaultErrorDiagnostics {\n  const normalizedError =\n    error instanceof Error\n      ? error\n      : new Error(typeof error === \"string\" ? error : \"Unknown server rendering error\");\n  const rawStack = normalizedError.stack || `${normalizedError.name}: ${normalizedError.message}`;\n  const location = findStackLocation(rawStack, path.resolve(root));\n\n  return {\n    name: redactErrorText(normalizedError.name || \"Error\"),\n    message: redactErrorText(normalizedError.message || \"Unknown server rendering error\"),\n    stack: sanitizeStack(rawStack, root),\n    sourceFrame: location ? createSourceFrame(location) : undefined,\n  };\n}\n","import type { FarmConfig } from \"./types\";\nimport type { FarmDocsResolvedConfig } from \"./docs/types\";\nimport type { FarmMarkdownResolvedConfig } from \"./markdown\";\nimport { resolveMdxConfig, type FarmMdxResolvedConfig } from \"./app-markdown-config\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig, type FarmWorkflowsResolvedConfig } from \"./workflows\";\nimport { resolveCronConfig, type FarmCronResolvedConfig } from \"./cron\";\nimport { resolveAppPath, fileExists, logger } from \"./utils\";\nimport { initStorage } from \"./storage\";\nimport { configureFarmObservability } from \"./observability\";\nimport { normalizeRouteRules } from \"./route-rules\";\nimport { resolveServerActionsConfig } from \"./server-action-security\";\nimport { resolveFarmServerConfig } from \"./server-http\";\nimport { resolveFarmImageConfig, type ResolvedFarmImageConfig } from \"./image-config\";\nimport { getFarmAppDirectories, getFarmSourceRoots } from \"./layers\";\nimport { RouteManager } from \"./routing/route-manager\";\nimport { ServerRenderer } from \"./server/renderer\";\nimport { findProgrammaticRouteFiles } from \"./routes.server\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport {\n  createFarmI18nRuntime,\n  _setDefaultFarmI18nRuntime,\n  type FarmI18nRuntime,\n} from \"./i18n/server\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { configureFarmCache } from \"./cache\";\nimport { resolveFarmAuthConfig, type ResolvedFarmAuthConfig } from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmSecurityConfig, type ResolvedFarmSecurityConfig } from \"./security\";\nimport { resolveFarmThemeConfig } from \"./theme/config\";\nimport { _setDefaultFarmThemeConfig } from \"./theme/server\";\nimport type { ResolvedFarmThemeConfig } from \"./theme/types\";\nimport { getFarmRendererComponentExtensions, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { normalizeFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\ntype NormalizedFarmConfig = Omit<\n  Required<FarmConfig>,\n  \"api\" | \"devtools\" | \"devIndicators\" | \"images\" | \"i18n\" | \"performance\" | \"security\" | \"theme\"\n> & {\n  api: ResolvedFarmAPIConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n};\n\nconst defaultDocsConfig: FarmDocsResolvedConfig = {\n  enabled: false,\n  entry: \"/docs\",\n  config: { entry: \"docs\", docsPath: \"/docs\" },\n};\n\nfunction isResolvedDocsConfig(value: FarmConfig[\"docs\"]): value is FarmDocsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"entry\" in value &&\n    \"config\" in value\n  );\n}\n\nexport class FarmApp {\n  private config: NormalizedFarmConfig;\n  private routeManager: RouteManager;\n  private serverRenderer: ServerRenderer;\n  private i18nRuntime: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n\n  constructor(config: FarmConfig = {}, viteServer?: ViteDevServer) {\n    this.config = this.normalizeConfig(config);\n    configureFarmObservability(this.config.observability);\n    _setDefaultFarmThemeConfig(this.config.theme);\n    this.i18nRuntime = createFarmI18nRuntime(this.config.i18n);\n    _setDefaultFarmI18nRuntime(this.i18nRuntime);\n    this.viteServer = viteServer;\n    this.routeManager = new RouteManager(this.config, viteServer);\n    this.serverRenderer = new ServerRenderer(\n      this.config,\n      this.routeManager,\n      this.i18nRuntime,\n      this.viteServer,\n    );\n  }\n\n  async initialize(): Promise<void> {\n    // Silent initialization unless verbose mode\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\"Initializing Farm.js application...\");\n    }\n\n    await initStorage(this.config.storage);\n    await configureFarmCache(this.config.cache);\n    await this.i18nRuntime.initialize();\n    await this.serverRenderer.initialize();\n\n    // Verify app directory structure\n    await this.verifyAppStructure();\n\n    // Discover and register routes\n    await this.routeManager.discoverRoutes();\n\n    // Compile hydration and island decisions once during startup. Navigation\n    // requests only read this manifest; HMR invalidates it when route code changes.\n    this.routeManager.generateClientManifest(this.config.root);\n\n    if (process.env.FARM_VERBOSE) {\n      logger.success(\"Farm.js application initialized successfully!\");\n    }\n  }\n\n  getRouteManager(): RouteManager {\n    return this.routeManager;\n  }\n\n  getServerRenderer(): ServerRenderer {\n    return this.serverRenderer;\n  }\n\n  getI18nRuntime(): FarmI18nRuntime {\n    return this.i18nRuntime;\n  }\n\n  getConfig(): NormalizedFarmConfig {\n    return this.config;\n  }\n\n  private normalizeConfig(config: FarmConfig): NormalizedFarmConfig {\n    const root = config.root || process.cwd();\n    const basePath = normalizeFarmConfigBasePath(config.basePath);\n\n    return {\n      root,\n      srcDir: config.srcDir || \"src\",\n      extends: config.extends || [],\n      layers: [...(config.layers || [])],\n      outDir: config.outDir || \"dist\",\n      basePath,\n      trailingSlash: config.trailingSlash ?? false,\n      renderer: resolveFarmRenderer(config.renderer),\n      preset: config.preset ?? \"node-server\",\n      deploy: config.deploy || {},\n      storage: config.storage || {},\n      cache: config.cache || {},\n      auth: isResolvedAuthConfig(config.auth) ? config.auth : resolveFarmAuthConfig(config.auth),\n      integrations: config.integrations || {},\n      plugins: config.plugins || [],\n      migrations: config.migrations || { commands: [] },\n      cron: resolveCronConfig(config.cron),\n      workflows: resolveWorkflowsConfig(config.workflows),\n      api: normalizeFarmAppAPIConfig(config.api),\n      middleware: config.middleware || {},\n      routeRules: normalizeRouteRules(config.routeRules),\n      context: config.context || (() => undefined),\n      server: resolveFarmServerConfig(config.server),\n      serverActions: resolveServerActionsConfig(config.serverActions),\n      security: resolveFarmSecurityConfig(config.security),\n      images: resolveFarmImageConfig(config.images),\n      performance: resolveFarmPerformanceConfig(config.performance),\n      theme: resolveFarmThemeConfig(config.theme, basePath),\n      i18n: isResolvedI18nConfig(config.i18n)\n        ? config.i18n\n        : resolveFarmI18nConfig(config.i18n, {\n            root,\n            mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n            basePath,\n          }),\n      deploymentId: config.deploymentId || \"development\",\n      notFound: config.notFound || {},\n      serverRuntimeConfig: config.serverRuntimeConfig || {},\n      publicRuntimeConfig: config.publicRuntimeConfig || {},\n      docs: isResolvedDocsConfig(config.docs) ? config.docs : defaultDocsConfig,\n      md: resolveMarkdownConfig(config.md),\n      mdx: resolveMdxConfig(config.mdx),\n      observability: config.observability ?? false,\n      telemetry: config.telemetry !== false,\n      devtools: resolveFarmDevtoolsConfig(\n        config.devtools,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      devIndicators: resolveFarmDevIndicatorsConfig(\n        config.devIndicators,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      env: config.env || { server: {}, public: {} },\n      suppressLintOnLink: config.suppressLintOnLink ?? false,\n      experimental: {\n        serverComponents: config.experimental?.serverComponents ?? false,\n        serverActions: config.experimental?.serverActions ?? false,\n        isolatedClientHydration: config.experimental?.isolatedClientHydration ?? \"off\",\n        ppr: config.experimental?.ppr ?? false,\n        ...config.experimental,\n      },\n      agent: config.agent ?? {},\n      vite: config.vite || {},\n    };\n  }\n\n  private async verifyAppStructure(): Promise<void> {\n    const appDirs = getFarmAppDirectories(this.config);\n\n    const hasAppDirectory = (await Promise.all(appDirs.map((appDir) => fileExists(appDir)))).some(\n      Boolean,\n    );\n\n    if (!hasAppDirectory) {\n      const routeFiles = getFarmSourceRoots(this.config).flatMap((source) =>\n        findProgrammaticRouteFiles(source.root, source.srcDir),\n      );\n      if (routeFiles.length > 0) {\n        return;\n      }\n\n      const appDir = resolveAppPath(this.config.root, this.config.srcDir, \"app\");\n      throw new Error(\n        `App directory not found at ${appDir}. ` +\n          \"Please create a src/app directory or extend a Farm layer containing routes.\",\n      );\n    }\n\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n    const rootLayoutPaths = appDirs.flatMap((appDir) =>\n      componentExtensions.map((extension) => path.join(appDir, `layout${extension}`)),\n    );\n\n    const hasRootLayout = await Promise.all(rootLayoutPaths.map((p) => fileExists(p))).then(\n      (results) => results.some(Boolean),\n    );\n\n    if (!hasRootLayout) {\n      logger.warn(\n        `No root layout found. Consider creating src/app/layout${componentExtensions[0]} for consistent page structure.`,\n      );\n    }\n  }\n}\n\nfunction isResolvedI18nConfig(value: FarmConfig[\"i18n\"]): value is ResolvedFarmI18nConfig {\n  return Boolean(value && typeof value === \"object\" && \"enabled\" in value);\n}\n\nfunction isResolvedAuthConfig(value: FarmConfig[\"auth\"]): value is ResolvedFarmAuthConfig {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"emailAndPassword\" in value &&\n    \"database\" in value,\n  );\n}\n\nfunction normalizeFarmAppAPIConfig(config: FarmConfig[\"api\"]): ResolvedFarmAPIConfig {\n  if (typeof config?.baseURL === \"function\" || typeof config?.basePath === \"function\") {\n    throw new Error(\n      \"Farm API config resolver functions must be processed with resolveConfig() before creating a FarmApp.\",\n    );\n  }\n  return normalizeFarmAPIConfig(config as { baseURL?: string; basePath?: string } | undefined);\n}\n\nexport function createFarmApp(config?: FarmConfig, viteServer?: ViteDevServer): FarmApp {\n  return new FarmApp(config, viteServer);\n}\n","// Tailwind v4 syntax (used with @tailwindcss/vite – no PostCSS or tailwind.config)\nexport const defaultGlobalCSS = `@import \"tailwindcss\";\n`;\n","import type { PluginRoutes, PluginRoutesFactory } from \"./api/route\";\n// Plugin factories must emit declarations through public exports, never bundled\n// declaration chunk paths, even when they only import @farm.js/core/plugin.\nexport type { PluginRoutes, PluginRoutesFactory, RouteDefinition } from \"./api/route\";\nimport type { FarmConfig, FarmRequest, FarmResponse } from \"./types\";\nimport type { ViteDevServer } from \"vite\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport { getResolvedEnv, type ResolvedFarmEnv } from \"./env\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { getFarmPluginIntegrationContext } from \"./plugin-integration-context\";\n\ntype MaybePromise<T> = T | Promise<T>;\n/** @internal Marks a Node response whose intercepted end is awaiting response hooks. */\nexport const FARM_NODE_RESPONSE_END_PENDING = Symbol.for(\"farm.nodeResponseEndPending\");\ndeclare const FARM_PLUGIN_INTEGRATION_INSTANCE: unique symbol;\ndeclare const FARM_PLUGIN_INTEGRATION_BOUND: unique symbol;\n\nexport interface FarmPluginIntegrationContext<TInstance = unknown> {\n  /** Key used to register the integration in farm.config.ts. */\n  readonly key: string;\n  readonly category: string;\n  readonly type: string;\n  readonly instance: TInstance;\n  readonly serverRuntime: boolean;\n}\n\nexport class FarmRuntimeShutdownError extends Error {\n  readonly errors: readonly unknown[];\n\n  constructor(message: string, errors: readonly unknown[]) {\n    super(message);\n    this.name = \"FarmRuntimeShutdownError\";\n    this.errors = errors;\n  }\n}\n\nexport interface PluginRequestContext {\n  set: (\n    target: FarmRequest | Request,\n    key: string,\n    value: any,\n    options?: { exposeToPage?: boolean },\n  ) => void;\n  get: <T = any>(target: FarmRequest | Request, key: string) => T | undefined;\n  has: (target: FarmRequest | Request, key: string) => boolean;\n  delete: (target: FarmRequest | Request, key: string) => boolean;\n  clear: (target: FarmRequest | Request) => void;\n  getAll: (target: FarmRequest | Request, options?: { exposedOnly?: boolean }) => Map<string, any>;\n}\n\nexport interface FarmRequestStore {\n  set(key: string, value: unknown, options?: { exposeToPage?: boolean }): void;\n  get<T = unknown>(key: string): T | undefined;\n  has(key: string): boolean;\n  delete(key: string): boolean;\n  clear(): void;\n  snapshot(options?: { exposedOnly?: boolean }): Map<string, unknown>;\n}\n\nexport interface FarmPluginContext<TIntegrationInstance = unknown> {\n  config: FarmConfig;\n  viteServer?: ViteDevServer;\n  isDev: boolean;\n  isProd: boolean;\n  /** The owning integration when this plugin is contributed through `integration.plugins`. */\n  readonly integration?: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n  /** Register resource cleanup that must run when the application runtime closes. */\n  lifecycle: FarmPluginLifecycle;\n  /** @deprecated Use `ctx.req` inside request hooks. */\n  requestContext: PluginRequestContext;\n}\n\ntype FarmPluginHookContext<\n  TContext,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = TIntegrationBound extends true\n  ? Omit<TContext, \"integration\"> & {\n      /** The owning integration bound by `definePlugin.forIntegration<T>()`. */\n      readonly integration: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n    }\n  : TContext;\n\nexport interface FarmPluginLifecycle {\n  /**\n   * Register a database, storage, queue, or other resource disposer.\n   * Disposers run once in reverse registration order after plugin shutdown hooks.\n   */\n  onShutdown(dispose: () => void | Promise<void>): () => void;\n}\n\nexport interface FarmRequestPluginContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  /** Request-scoped values for the current hook invocation. */\n  readonly req: FarmRequestStore;\n}\n\nexport interface RouteDiscoveredPayload {\n  kind: \"page\" | \"layout\";\n  pattern: string;\n  modulePath: string;\n}\n\nexport interface RoutesGeneratedPayload {\n  routes: RouteDiscoveredPayload[];\n  pageCount: number;\n  layoutCount: number;\n}\n\nexport interface MiddlewareDiscoveredPayload {\n  path: string;\n  filePath: string;\n  handlerCount: number;\n}\n\nexport interface APIRouteDiscoveredPayload {\n  path: string;\n  filePath: string;\n  methods: string[];\n}\n\nexport interface RouteMatchPayload {\n  pathname: string;\n  method?: string;\n}\n\nexport interface RouteMatchResultPayload {\n  pathname: string;\n  matched: boolean;\n  routePattern: string | null;\n  params: Record<string, string>;\n  layoutPatterns: string[];\n}\n\nexport interface RenderLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePattern: string | null;\n  params: Record<string, string>;\n}\n\nexport interface APIHandlerLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePath?: string;\n}\n\nexport interface ErrorLifecyclePayload {\n  phase: string;\n  error: unknown;\n  meta?: Record<string, unknown>;\n}\n\nexport interface HMRUpdatePayload {\n  file: string;\n  modules: string[];\n}\n\nexport interface BundleLifecyclePayload {\n  root: string;\n  preset: string;\n  universal: boolean;\n  distDir: string;\n  outputDir?: string;\n}\n\nexport interface BundleResultPayload extends BundleLifecyclePayload {\n  success: boolean;\n}\n\nexport interface NitroBuildLifecyclePayload {\n  root: string;\n  preset: string;\n  distDir: string;\n  outputDir: string;\n}\n\nexport interface ShutdownPayload {\n  reason: string;\n}\n\nexport type FarmPluginRuntimeKind =\n  | \"request\"\n  | \"page\"\n  | \"api\"\n  | \"action\"\n  | \"integration\"\n  | \"docs\"\n  | \"asset\"\n  | (string & {});\n\nexport interface FarmPluginRouteRuntimePayload {\n  pathname: string;\n  pattern?: string | null;\n  params?: Record<string, string>;\n}\n\nexport interface FarmPluginSetupContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  env: ResolvedFarmEnv;\n}\n\nexport interface FarmPluginStateContext<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  state: TState;\n}\n\nexport interface FarmPluginRuntimeBaseEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginStateContext<TState, TIntegrationInstance> {\n  request: Request;\n  /** Request-scoped values shared by plugin hooks. */\n  req: FarmRequestStore;\n  kind: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  signal: AbortSignal;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginRuntimeContextEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeBeforeEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance> {\n  ctx: Readonly<TRequestContext>;\n}\n\nexport interface FarmPluginRuntimeAfterEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  response: Response;\n  durationMs: number;\n}\n\nexport interface FarmPluginRuntimeErrorEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  error: unknown;\n  durationMs: number;\n}\n\nexport type FarmPluginRuntimeStartEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginStateContext<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeCloseEvent<TState = unknown, TIntegrationInstance = unknown>\n  extends FarmPluginStateContext<TState, TIntegrationInstance>, ShutdownPayload {}\n\ntype FarmPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmRequestPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmRequestPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginSetupContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginSetupContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginStateContextFor<\n  TState,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginStateContext<TState, TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginRuntimeEventFor<\n  TEvent,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<TEvent, TIntegrationInstance, TIntegrationBound>;\n\nexport interface FarmPluginRuntimeHooks<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  start?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeStartEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  context?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeContextEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<TRequestContext>;\n  before?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Request | Response | void>;\n  after?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeAfterEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Response | void>;\n  error?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeErrorEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  close?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeCloseEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRuntimeRequestOptions {\n  kind?: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport type FarmPluginRuntimeRequestHandler = (request: Request) => MaybePromise<Response>;\n\nexport interface FarmPluginRuntimeSession {\n  request: Request;\n  response?: Response;\n  ctx: Readonly<Record<string, unknown>>;\n  startedAt: number;\n  options: FarmPluginRuntimeRequestOptions;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginDiscoveredRoute =\n  | RouteDiscoveredPayload\n  | ({ kind: \"middleware\" } & MiddlewareDiscoveredPayload)\n  | ({ kind: \"api\" } & APIRouteDiscoveredPayload);\n\nexport interface FarmPluginRouterHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  discovered?(\n    route: FarmPluginDiscoveredRoute,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  generated?(\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  before?(\n    route: RouteMatchPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  after?(\n    result: RouteMatchResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRenderHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  html?(\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<string | void>;\n}\n\nexport interface FarmPluginBuildHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  configure?(\n    buildConfig: any,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<any>;\n  after?(\n    result: BundleResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginDevHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  server?(\n    viteServer: ViteDevServer,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  update?(\n    update: HMRUpdatePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginClientConfig<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPlugin<TState, TPublic> {\n  /** Explicitly public, JSON-safe data embedded in the browser bundle. */\n  public?: TPublic;\n}\n\nexport interface FarmPlugin<\n  TState = any,\n  TRequestContext extends object = Record<string, unknown>,\n  TClientState = any,\n  TClientPublic = any,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n  TRoutes extends PluginRoutes = PluginRoutes,\n> {\n  name: string;\n  version?: string;\n  enforce?: \"pre\" | \"post\";\n  /** Declarative API routes, mounted through the normal dev and production API pipeline. */\n  routes?: PluginRoutesFactory<TRoutes>;\n\n  /** Transform Farm config before the development or production pipeline is created. */\n  configure?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<FarmConfig | void>;\n  /** Initialize private plugin state once for this plugin manager. */\n  setup?: (\n    context: FarmPluginSetupContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<TState>;\n\n  runtime?: FarmPluginRuntimeHooks<\n    TState,\n    TRequestContext,\n    TIntegrationInstance,\n    TIntegrationBound\n  >;\n  router?: FarmPluginRouterHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  render?: FarmPluginRenderHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  build?: FarmPluginBuildHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  dev?: FarmPluginDevHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  /** Optional browser lifecycle for this logical plugin. */\n  client?: FarmPluginClientConfig<TClientState, TClientPublic>;\n\n  /** @internal Carries the expected integration instance type without runtime data. */\n  readonly [FARM_PLUGIN_INTEGRATION_INSTANCE]?: (instance: TIntegrationInstance) => void;\n  /** @internal Prevents integration-bound plugins from being registered globally. */\n  readonly [FARM_PLUGIN_INTEGRATION_BOUND]?: TIntegrationBound;\n\n  /** @deprecated Use `setup` instead. */\n  init?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.start` instead. */\n  ready?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.server` instead. */\n  devServerCreated?: (\n    viteServer: ViteDevServer,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `configure` instead. */\n  config?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => FarmConfig | Promise<FarmConfig>;\n  configResolved?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  buildStart?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  buildEnd?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `router.discovered` instead. */\n  routeDiscovered?: (\n    route: RouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.generated` instead. */\n  routesGenerated?: (\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  middlewareDiscovered?: (\n    middleware: MiddlewareDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  apiRouteDiscovered?: (\n    route: APIRouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.before` instead. */\n  beforeRouteMatch?: (\n    route: RouteMatchPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.after` instead. */\n  afterRouteMatch?: (\n    result: RouteMatchResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.before` instead. */\n  beforeRender?: (\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.html` instead. */\n  afterRender?: (\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string> | void | Promise<void>;\n  /** @deprecated Use `runtime.before` instead. */\n  beforeApiHandler?: (\n    request: Request,\n    api: APIHandlerLifecyclePayload,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Request | Promise<Request> | void | Promise<void>;\n  /** @deprecated Use `runtime.after` instead. */\n  afterApiHandler?: (\n    response: Response,\n    api: APIHandlerLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Response | Promise<Response> | void | Promise<void>;\n  onError?: (\n    error: ErrorLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.update` instead. */\n  hmrUpdate?: (\n    update: HMRUpdatePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  beforeBundle?: (\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  afterBundle?: (\n    result: BundleResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.configure` instead. */\n  beforeNitroBuild?: (\n    nitroConfig: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n  afterNitroBuild?: (\n    payload: NitroBuildLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.close` instead. */\n  shutdown?: (\n    payload: ShutdownPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use the Web Request based `runtime.before` hook instead. */\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use the Web Response based `runtime.after` hook instead. */\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  // Transform hooks\n  /** @deprecated Use `render.html` instead. */\n  transformHTML?: (\n    html: string,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string>;\n  /** @deprecated Use `render.before` or `render.html` instead. */\n  transformPage?: (\n    component: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n}\n\nexport class PluginManager {\n  private plugins: FarmPlugin[] = [];\n  private hookPresence = new Map<keyof FarmPlugin, boolean>();\n  private runtimeHookPresence = new Map<\"context\" | \"before\" | \"after\" | \"error\", boolean>();\n  private context: FarmPluginContext;\n  private pluginStates = new Map<FarmPlugin, unknown>();\n  private setupComplete = false;\n  private initialized = false;\n  private runtimeReady = false;\n  private runtimeClosed = false;\n  private runtimeStartPromise?: Promise<void>;\n  private runtimeClosePromise?: Promise<void>;\n  private runtimeShutdownHooksRunning = false;\n  private runtimeDisposers: Array<() => void | Promise<void>> = [];\n  private runtimeRequestContexts = new WeakMap<Request, Readonly<Record<string, unknown>>>();\n  private failedRuntimeSessions = new WeakSet<FarmPluginRuntimeSession>();\n\n  constructor(context: Omit<FarmPluginContext, \"requestContext\" | \"lifecycle\">) {\n    this.context = {\n      ...context,\n      lifecycle: {\n        onShutdown: (dispose) => {\n          if (typeof dispose !== \"function\") {\n            throw new TypeError(\"Farm lifecycle.onShutdown requires a cleanup function\");\n          }\n          // Shutdown never waits for startup, because a plugin whose\n          // runtime.start() hangs still has to be able to stop. Setup can\n          // therefore finish after the runtime is already closed, and the only\n          // way not to leak what it just opened is to release it now. This is\n          // what the disposer would have done moments earlier.\n          if (this.runtimeClosed) {\n            void (async () => {\n              try {\n                await dispose();\n              } catch (error) {\n                console.error(\"Farm runtime cleanup registered after shutdown failed:\", error);\n              }\n            })();\n            return () => {};\n          }\n\n          this.runtimeDisposers.push(dispose);\n          let registered = true;\n          return () => {\n            if (!registered) return;\n            registered = false;\n            const index = this.runtimeDisposers.indexOf(dispose);\n            if (index >= 0) this.runtimeDisposers.splice(index, 1);\n          };\n        },\n      },\n      requestContext: {\n        set(target, key, value, options) {\n          setRequestContext(target as object, key, value, options);\n        },\n        get(target, key) {\n          return getRequestContext(target as object, key);\n        },\n        has(target, key) {\n          return hasRequestContext(target as object, key);\n        },\n        delete(target, key) {\n          return deleteRequestContext(target as object, key);\n        },\n        clear(target) {\n          clearRequestContext(target as object);\n        },\n        getAll(target, options) {\n          return getRequestContextSnapshot(target as object, options);\n        },\n      },\n    };\n  }\n\n  private createPluginHookContext(\n    plugin: FarmPlugin,\n    context: FarmPluginContext = this.context,\n  ): FarmPluginContext {\n    const integration = getFarmPluginIntegrationContext(plugin);\n    return integration ? { ...context, integration } : context;\n  }\n\n  private createRequestHookContext(\n    target: FarmRequest | Request,\n    plugin: FarmPlugin,\n  ): FarmRequestPluginContext {\n    const requestContext = this.context.requestContext;\n\n    return {\n      ...this.createPluginHookContext(plugin),\n      req: {\n        set(key, value, options) {\n          requestContext.set(target, key, value, options);\n        },\n        get(key) {\n          return requestContext.get(target, key);\n        },\n        has(key) {\n          return requestContext.has(target, key);\n        },\n        delete(key) {\n          return requestContext.delete(target, key);\n        },\n        clear() {\n          requestContext.clear(target);\n        },\n        snapshot(options) {\n          return requestContext.getAll(target, options);\n        },\n      },\n    };\n  }\n\n  private copyRequestStore(source: FarmRequest | Request, target: FarmRequest | Request): void {\n    const requestContext = this.context.requestContext;\n    const values = requestContext.getAll(source);\n    const exposed = requestContext.getAll(source, { exposedOnly: true });\n\n    for (const [key, value] of values) {\n      requestContext.set(target, key, value, {\n        exposeToPage: exposed.has(key),\n      });\n    }\n  }\n\n  private copyRuntimeRequestContext(source: Request, target: Request): void {\n    const runtimeContext = this.runtimeRequestContexts.get(source);\n    if (runtimeContext) {\n      this.runtimeRequestContexts.set(target, runtimeContext);\n    }\n  }\n\n  private createRuntimeBaseEvent(\n    plugin: FarmPlugin,\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): FarmPluginRuntimeBaseEvent {\n    return {\n      ...this.createStateHookContext(plugin),\n      request,\n      req: this.createRequestHookContext(request, plugin).req,\n      kind: options.kind ?? \"request\",\n      route: options.route,\n      signal: request.signal,\n      waitUntil,\n    };\n  }\n\n  private async createRuntimeRequestContext(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<Readonly<Record<string, unknown>>> {\n    const values: Record<string, unknown> = {};\n    const owners = new Map<string, string>();\n\n    for (const plugin of this.getSortedPlugins()) {\n      const createContext = plugin.runtime?.context;\n      if (!createContext) continue;\n\n      const result = await createContext(\n        this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n      );\n      if (result === undefined) continue;\n      if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n        throw new TypeError(`Farm plugin \"${plugin.name}\" runtime.context must return an object`);\n      }\n\n      for (const [key, value] of Object.entries(result)) {\n        const owner = owners.get(key);\n        if (owner) {\n          throw new Error(\n            `Farm plugin context key \"${key}\" from \"${plugin.name}\" conflicts with \"${owner}\"`,\n          );\n        }\n        owners.set(key, plugin.name);\n        values[key] = value;\n      }\n    }\n\n    const runtimeContext = Object.freeze(values);\n    this.runtimeRequestContexts.set(request, runtimeContext);\n    return runtimeContext;\n  }\n\n  private async runRuntimeErrorHooks(\n    request: Request,\n    error: unknown,\n    ctx: Readonly<Record<string, unknown>>,\n    durationMs: number,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<void> {\n    for (const plugin of this.getSortedPlugins()) {\n      const onError = plugin.runtime?.error;\n      if (!onError) continue;\n\n      try {\n        await onError({\n          ...this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n          ctx,\n          error,\n          durationMs,\n        });\n      } catch (hookError) {\n        console.error(`Farm plugin \"${plugin.name}\" runtime.error failed:`, hookError);\n      }\n    }\n\n    try {\n      await this.runHookParallel(\"onError\", {\n        phase: \"runtime\",\n        error,\n        meta: {\n          kind: options.kind ?? \"request\",\n          pathname: new URL(request.url).pathname,\n          durationMs,\n        },\n      });\n    } catch (hookError) {\n      console.error(\"Farm plugin onError hook failed:\", hookError);\n    }\n  }\n\n  private createStateHookContext(\n    plugin: FarmPlugin,\n    context: FarmPluginContext = this.context,\n  ): FarmPluginStateContext {\n    return {\n      ...this.createPluginHookContext(plugin, context),\n      state: this.pluginStates.get(plugin),\n    };\n  }\n\n  private getPluginHooks(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n  ): Array<(...args: any[]) => any> {\n    const hooks: Array<(...args: any[]) => any> = [];\n    const legacyHook = plugin[hookName];\n    if (typeof legacyHook === \"function\") {\n      hooks.push(legacyHook);\n    }\n\n    const withState = (context: FarmPluginContext) => this.createStateHookContext(plugin, context);\n\n    switch (hookName) {\n      case \"config\":\n        if (plugin.configure) {\n          hooks.push((config: FarmConfig, context: FarmPluginContext) =>\n            plugin.configure?.(config, context),\n          );\n        }\n        break;\n      case \"ready\":\n        if (plugin.runtime?.start) {\n          hooks.push((context: FarmPluginContext) => plugin.runtime?.start?.(withState(context)));\n        }\n        break;\n      case \"shutdown\":\n        if (plugin.runtime?.close) {\n          hooks.push((payload: ShutdownPayload, context: FarmPluginContext) =>\n            plugin.runtime?.close?.({\n              ...withState(context),\n              reason: payload.reason,\n            }),\n          );\n        }\n        break;\n      case \"routeDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: RouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"middlewareDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: MiddlewareDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"middleware\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"apiRouteDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: APIRouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"api\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"routesGenerated\":\n        if (plugin.router?.generated) {\n          hooks.push((routes: RoutesGeneratedPayload, context: FarmPluginContext) =>\n            plugin.router?.generated?.(routes, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRouteMatch\":\n        if (plugin.router?.before) {\n          hooks.push((route: RouteMatchPayload, context: FarmPluginContext) =>\n            plugin.router?.before?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"afterRouteMatch\":\n        if (plugin.router?.after) {\n          hooks.push((result: RouteMatchResultPayload, context: FarmPluginContext) =>\n            plugin.router?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRender\":\n        if (plugin.render?.before) {\n          hooks.push((render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.before?.(render, withState(context)),\n          );\n        }\n        break;\n      case \"afterRender\":\n        if (plugin.render?.html) {\n          hooks.push((html: string, render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.html?.(html, render, withState(context)),\n          );\n        }\n        break;\n      case \"beforeBundle\":\n        if (plugin.build?.before) {\n          hooks.push((bundle: BundleLifecyclePayload, context: FarmPluginContext) =>\n            plugin.build?.before?.(bundle, withState(context)),\n          );\n        }\n        break;\n      case \"beforeNitroBuild\":\n        if (plugin.build?.configure) {\n          hooks.push((buildConfig: any, context: FarmPluginContext) =>\n            plugin.build?.configure?.(buildConfig, withState(context)),\n          );\n        }\n        break;\n      case \"afterBundle\":\n        if (plugin.build?.after) {\n          hooks.push((result: BundleResultPayload, context: FarmPluginContext) =>\n            plugin.build?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"devServerCreated\":\n        if (plugin.dev?.server) {\n          hooks.push((server: ViteDevServer, context: FarmPluginContext) =>\n            plugin.dev?.server?.(server, withState(context)),\n          );\n        }\n        break;\n      case \"hmrUpdate\":\n        if (plugin.dev?.update) {\n          hooks.push((update: HMRUpdatePayload, context: FarmPluginContext) =>\n            plugin.dev?.update?.(update, withState(context)),\n          );\n        }\n        break;\n    }\n\n    return hooks;\n  }\n\n  private getHookContext(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n    args: any[],\n  ): FarmPluginContext {\n    if (\n      hookName === \"beforeRequest\" ||\n      hookName === \"afterResponse\" ||\n      hookName === \"beforeApiHandler\"\n    ) {\n      const target = args[0];\n      if (target && typeof target === \"object\") {\n        return this.createRequestHookContext(target, plugin);\n      }\n    }\n\n    return this.createPluginHookContext(plugin);\n  }\n\n  addPlugin(plugin: FarmPlugin) {\n    this.plugins.push(plugin);\n    this.hookPresence.clear();\n    this.runtimeHookPresence.clear();\n  }\n\n  addPlugins(plugins: FarmPlugin[]) {\n    for (const plugin of plugins) {\n      this.addPlugin(plugin);\n    }\n  }\n\n  getPlugins(): FarmPlugin[] {\n    return [...this.plugins];\n  }\n\n  getSortedPlugins(): FarmPlugin[] {\n    const pre = this.plugins.filter((p) => p.enforce === \"pre\");\n    const normal = this.plugins.filter((p) => !p.enforce);\n    const post = this.plugins.filter((p) => p.enforce === \"post\");\n    return [...pre, ...normal, ...post];\n  }\n\n  hasHook(hookName: keyof FarmPlugin): boolean {\n    const cached = this.hookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => this.getPluginHooks(plugin, hookName).length > 0);\n    this.hookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeHook(hookName: \"context\" | \"before\" | \"after\" | \"error\"): boolean {\n    const cached = this.runtimeHookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => typeof plugin.runtime?.[hookName] === \"function\");\n    this.runtimeHookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeRequestHooks(): boolean {\n    return (\n      this.hasRuntimeHook(\"context\") ||\n      this.hasRuntimeHook(\"before\") ||\n      this.hasRuntimeHook(\"after\") ||\n      this.hasRuntimeHook(\"error\")\n    );\n  }\n\n  copyRequestContext(source: FarmRequest | Request, target: FarmRequest | Request): void {\n    this.copyRequestStore(source, target);\n    if (source instanceof Request && target instanceof Request) {\n      this.copyRuntimeRequestContext(source, target);\n    }\n  }\n\n  async setupPlugins(): Promise<void> {\n    if (this.setupComplete) return;\n\n    for (const plugin of this.getSortedPlugins()) {\n      if (!plugin.setup) continue;\n      const state = await plugin.setup({\n        ...this.createPluginHookContext(plugin),\n        env: getResolvedEnv(),\n      });\n      this.pluginStates.set(plugin, state);\n    }\n\n    this.setupComplete = true;\n  }\n\n  async startRuntime(): Promise<void> {\n    if (this.runtimeReady) return;\n    if (this.runtimeStartPromise) return this.runtimeStartPromise;\n\n    this.runtimeStartPromise = (async () => {\n      if (!this.initialized) {\n        await this.runHookParallel(\"init\");\n      }\n      await this.setupPlugins();\n      if (!this.runtimeReady) {\n        await this.runHookParallel(\"ready\");\n      }\n    })();\n\n    try {\n      await this.runtimeStartPromise;\n    } catch (error) {\n      this.runtimeStartPromise = undefined;\n      throw error;\n    }\n  }\n\n  async closeRuntime(reason = \"runtime-closed\"): Promise<void> {\n    if (this.runtimeClosePromise) return this.runtimeClosePromise;\n    if (this.runtimeClosed) return;\n\n    this.runtimeClosePromise = (async () => {\n      const errors: unknown[] = [];\n      this.runtimeShutdownHooksRunning = true;\n      try {\n        await this.runHookParallel(\"shutdown\", { reason });\n      } catch (error) {\n        if (error instanceof FarmRuntimeShutdownError) errors.push(...error.errors);\n        else errors.push(error);\n      } finally {\n        this.runtimeShutdownHooksRunning = false;\n      }\n\n      // Shutdown deliberately does not wait for startup: a plugin whose\n      // runtime.start() never resolves still has to be able to stop. Setup can\n      // therefore finish while disposal is already running, so keep draining\n      // until nothing new is registered instead of splicing once and stranding\n      // whatever arrived late.\n      while (this.runtimeDisposers.length > 0) {\n        const batch = this.runtimeDisposers.splice(0).reverse();\n        for (const dispose of batch) {\n          try {\n            await dispose();\n          } catch (error) {\n            errors.push(error);\n          }\n        }\n      }\n\n      this.runtimeClosed = true;\n      if (errors.length > 0) {\n        throw new FarmRuntimeShutdownError(\"Farm runtime shutdown failed\", errors);\n      }\n    })();\n    return this.runtimeClosePromise;\n  }\n\n  async beginRuntimeRequest(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions = {},\n  ): Promise<FarmPluginRuntimeSession> {\n    await this.startRuntime();\n\n    const startedAt = Date.now();\n    const waitUntil = options.waitUntil\n      ? (promise: Promise<unknown>) => options.waitUntil?.(Promise.resolve(promise))\n      : (promise: Promise<unknown>) => {\n          void Promise.resolve(promise).catch(() => {});\n        };\n    let activeRequest = request;\n    let runtimeContext: Readonly<Record<string, unknown>> = Object.freeze({});\n\n    try {\n      runtimeContext = await this.createRuntimeRequestContext(activeRequest, options, waitUntil);\n\n      let response: Response | undefined;\n      for (const plugin of this.getSortedPlugins()) {\n        const before = plugin.runtime?.before;\n        if (!before) continue;\n\n        const result = await before({\n          ...this.createRuntimeBaseEvent(plugin, activeRequest, options, waitUntil),\n          ctx: runtimeContext,\n        });\n\n        if (result instanceof Request) {\n          this.copyRequestStore(activeRequest, result);\n          this.copyRuntimeRequestContext(activeRequest, result);\n          activeRequest = result;\n          continue;\n        }\n        if (result instanceof Response) {\n          response = result;\n          break;\n        }\n        if (result !== undefined) {\n          throw new TypeError(\n            `Farm plugin \"${plugin.name}\" runtime.before must return a Request, Response, or undefined`,\n          );\n        }\n      }\n\n      return {\n        request: activeRequest,\n        response,\n        ctx: runtimeContext,\n        startedAt,\n        options,\n        waitUntil,\n      };\n    } catch (error) {\n      await this.runRuntimeErrorHooks(\n        activeRequest,\n        error,\n        runtimeContext,\n        Date.now() - startedAt,\n        options,\n        waitUntil,\n      );\n      throw error;\n    }\n  }\n\n  async endRuntimeRequest(\n    session: FarmPluginRuntimeSession,\n    initialResponse: Response,\n  ): Promise<Response> {\n    let response = initialResponse;\n\n    try {\n      for (const plugin of this.getSortedPlugins()) {\n        const after = plugin.runtime?.after;\n        if (!after) continue;\n\n        const result = await after({\n          ...this.createRuntimeBaseEvent(\n            plugin,\n            session.request,\n            session.options,\n            session.waitUntil,\n          ),\n          ctx: session.ctx,\n          response,\n          durationMs: Date.now() - session.startedAt,\n        });\n        if (result !== undefined) {\n          if (!(result instanceof Response)) {\n            throw new TypeError(\n              `Farm plugin \"${plugin.name}\" runtime.after must return a Response or undefined`,\n            );\n          }\n          response = result;\n        }\n      }\n\n      return response;\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async failRuntimeRequest(session: FarmPluginRuntimeSession, error: unknown): Promise<void> {\n    if (this.failedRuntimeSessions.has(session)) return;\n    this.failedRuntimeSessions.add(session);\n    await this.runRuntimeErrorHooks(\n      session.request,\n      error,\n      session.ctx,\n      Date.now() - session.startedAt,\n      session.options,\n      session.waitUntil,\n    );\n  }\n\n  async runRuntimeRequest(\n    request: Request,\n    handler: FarmPluginRuntimeRequestHandler,\n    options: FarmPluginRuntimeRequestOptions = {},\n  ): Promise<Response> {\n    const session = await this.beginRuntimeRequest(request, options);\n    try {\n      const response = session.response ?? (await handler(session.request));\n      if (!(response instanceof Response)) {\n        throw new TypeError(\"Farm plugin runtime handlers must return a Response\");\n      }\n      return await this.endRuntimeRequest(session, response);\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async runHook<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<any> {\n    const plugins = this.getSortedPlugins();\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookContext = this.getHookContext(plugin, hookName, args);\n        const result = await (hook as any).apply(plugin, [...args, hookContext]);\n        if (result !== undefined) {\n          return result;\n        }\n      }\n    }\n  }\n\n  async runHookSerial<K extends keyof FarmPlugin>(\n    hookName: K,\n    initialValue: any,\n    ...args: any[]\n  ): Promise<any> {\n    const plugins = this.getSortedPlugins();\n    let value = initialValue;\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookArgs = [value, ...args];\n        const hookContext = this.getHookContext(plugin, hookName, hookArgs);\n        const result = await (hook as any).apply(plugin, [...hookArgs, hookContext]);\n        if (result !== undefined) {\n          if (\n            hookName === \"beforeApiHandler\" &&\n            result !== value &&\n            value &&\n            result &&\n            typeof value === \"object\" &&\n            typeof result === \"object\"\n          ) {\n            this.copyRequestStore(value as FarmRequest | Request, result as FarmRequest | Request);\n          }\n          value = result;\n        }\n      }\n    }\n\n    return value;\n  }\n\n  async runHookParallel<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<boolean> {\n    return this.runHookParallelFiltered(hookName, () => true, ...args);\n  }\n\n  /** @internal Runs hooks for only the plugins selected by the runtime adapter. */\n  async runHookParallelFiltered<K extends keyof FarmPlugin>(\n    hookName: K,\n    include: (plugin: FarmPlugin) => boolean,\n    ...args: any[]\n  ): Promise<boolean> {\n    if (hookName === \"shutdown\" && !this.runtimeShutdownHooksRunning) {\n      await this.closeRuntime(args[0]?.reason);\n      return false;\n    }\n\n    const plugins = this.getSortedPlugins().filter(include);\n\n    // Run selected hooks sequentially for deterministic execution and short-circuiting.\n    const sequentialHooks = new Set<keyof FarmPlugin>([\n      \"ready\",\n      \"shutdown\",\n      \"beforeRequest\",\n      \"afterResponse\",\n      \"beforeApiHandler\",\n      \"afterApiHandler\",\n      \"beforeRouteMatch\",\n      \"afterRouteMatch\",\n      \"beforeRender\",\n      \"afterRender\",\n    ]);\n\n    if (sequentialHooks.has(hookName)) {\n      const shutdownErrors: unknown[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          // Check if response is already sent (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && (res.writableEnded || res[FARM_NODE_RESPONSE_END_PENDING])) {\n              return true;\n            }\n          }\n\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          try {\n            await (hook as any).apply(plugin, [...args, hookContext]);\n          } catch (error) {\n            if (hookName !== \"shutdown\") throw error;\n            shutdownErrors.push(error);\n          }\n\n          // Check again after plugin execution (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && res.writableEnded) {\n              return true;\n            }\n          }\n        }\n      }\n      if (hookName === \"shutdown\" && shutdownErrors.length > 0) {\n        throw new FarmRuntimeShutdownError(\"Farm plugin shutdown hooks failed\", shutdownErrors);\n      }\n    } else {\n      // Run other hooks in parallel\n      const promises: Promise<any>[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          promises.push((hook as any).apply(plugin, [...args, hookContext]));\n        }\n      }\n      await Promise.all(promises);\n    }\n\n    if (hookName === \"init\") this.initialized = true;\n    if (hookName === \"ready\") this.runtimeReady = true;\n\n    return false;\n  }\n\n  updateContext(updates: Partial<FarmPluginContext>) {\n    this.context = {\n      ...this.context,\n      ...updates,\n      requestContext: this.context.requestContext,\n    };\n  }\n}\n\nexport function definePlugin<\n  TState = undefined,\n  TRequestContext extends object = Record<string, never>,\n  TClientState = unknown,\n  TClientPublic = undefined,\n  TIntegrationInstance = unknown,\n  const TRoutes extends PluginRoutes = PluginRoutes,\n>(\n  plugin: FarmPlugin<\n    TState,\n    TRequestContext,\n    TClientState,\n    TClientPublic,\n    TIntegrationInstance,\n    false,\n    TRoutes\n  >,\n): FarmPlugin<\n  TState,\n  TRequestContext,\n  TClientState,\n  TClientPublic,\n  TIntegrationInstance,\n  false,\n  TRoutes\n> {\n  return plugin;\n}\n\nexport namespace definePlugin {\n  /** Bind an integration instance type while preserving inference for plugin state and context. */\n  export function forIntegration<TIntegrationInstance>() {\n    return function defineBoundPlugin<\n      TState = undefined,\n      TRequestContext extends object = Record<string, never>,\n      TClientState = unknown,\n      TClientPublic = undefined,\n    >(\n      plugin: FarmPlugin<\n        TState,\n        TRequestContext,\n        TClientState,\n        TClientPublic,\n        TIntegrationInstance,\n        true\n      >,\n    ): FarmPlugin<\n      TState,\n      TRequestContext,\n      TClientState,\n      TClientPublic,\n      TIntegrationInstance,\n      true\n    > {\n      return plugin;\n    };\n  }\n}\nexport { farmPlugin } from \"./vite\";\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport type { FarmPlugin, FarmPluginClientConfig } from \"./plugin\";\n\nexport interface ResolvedFarmClientPlugin {\n  name: string;\n  version?: string;\n  enforce?: \"pre\" | \"post\";\n  definition: FarmClientPlugin;\n  publicData?: unknown;\n}\n\nexport interface FarmClientPluginEntryCode {\n  imports: string;\n  registrations: string;\n  plugins: ResolvedFarmClientPlugin[];\n}\n\nconst CLIENT_KEYS = [\n  \"public\",\n  \"setup\",\n  \"hydration\",\n  \"navigation\",\n  \"error\",\n  \"performance\",\n  \"close\",\n] as const;\nconst HYDRATION_KEYS = [\"before\", \"after\"] as const;\nconst NAVIGATION_KEYS = [\"before\", \"loaded\", \"resolved\", \"rendered\", \"error\"] as const;\nconst APP_CLIENT_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"mjs\"] as const;\n\n/** Resolve the optional application-owned browser lifecycle entry. */\nexport function resolveFarmAppClientEntry(\n  root = process.cwd(),\n  srcDir = \"src\",\n): string | undefined {\n  const sourceRoot = path.resolve(root, srcDir);\n  for (const extension of APP_CLIENT_EXTENSIONS) {\n    const candidate = path.join(sourceRoot, `client.${extension}`);\n    if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n  }\n  return undefined;\n}\n\nexport function resolveFarmClientPlugins(\n  plugins: readonly FarmPlugin[] | undefined,\n  _root?: string,\n): ResolvedFarmClientPlugin[] {\n  if (!plugins?.length) return [];\n\n  return plugins.flatMap((plugin) => {\n    if (!plugin.client) return [];\n    assertClientLifecycle(plugin.client, plugin.name);\n    assertPublicData(plugin.client.public, plugin.name);\n\n    return [\n      {\n        name: plugin.name,\n        version: plugin.version,\n        enforce: plugin.enforce,\n        definition: plugin.client,\n        publicData: plugin.client.public,\n      },\n    ];\n  });\n}\n\nexport function generateFarmClientPluginEntryCode(\n  plugins: readonly FarmPlugin[] | undefined,\n  root?: string,\n  srcDir = \"src\",\n  appPublicData?: unknown,\n): FarmClientPluginEntryCode {\n  const resolved = resolveFarmClientPlugins(plugins, root);\n  const appClientEntry = root ? resolveFarmAppClientEntry(root, srcDir) : undefined;\n  const imports = appClientEntry\n    ? `import farmAppClientDefinition from ${JSON.stringify(appClientEntry.replace(/\\\\/g, \"/\"))};`\n    : \"\";\n  const serializedPlugins = resolved.map(\n    (plugin) => `  {\n    name: ${JSON.stringify(plugin.name)},\n    version: ${serializeOptionalString(plugin.version)},\n    enforce: ${serializeOptionalString(plugin.enforce)},\n    definition: ${serializeClientLifecycle(plugin.definition, plugin.name)},\n    public: ${serializePublicData(plugin.publicData)},\n  }`,\n  );\n  if (appClientEntry) {\n    assertPublicData(appPublicData, \"farm:app-client\");\n    serializedPlugins.push(`  {\n    name: \"farm:app-client\",\n    enforce: \"post\",\n    definition: farmAppClientDefinition,\n    public: ${serializePublicData(appPublicData)},\n  }`);\n  }\n  const registrations = `[\n${serializedPlugins.join(\",\\n\")}\n]`;\n\n  return { imports, registrations, plugins: resolved };\n}\n\nfunction assertClientLifecycle(client: FarmPluginClientConfig, pluginName: string): void {\n  assertLifecycleObject(client, pluginName, \"client\", CLIENT_KEYS);\n  assertHook(client.setup, pluginName, \"client.setup\");\n  assertHook(client.error, pluginName, \"client.error\");\n  assertHook(client.performance, pluginName, \"client.performance\");\n  assertHook(client.close, pluginName, \"client.close\");\n\n  if (client.hydration !== undefined) {\n    assertLifecycleObject(client.hydration, pluginName, \"client.hydration\", HYDRATION_KEYS);\n    assertHook(client.hydration.before, pluginName, \"client.hydration.before\");\n    assertHook(client.hydration.after, pluginName, \"client.hydration.after\");\n  }\n\n  if (client.navigation !== undefined) {\n    assertLifecycleObject(client.navigation, pluginName, \"client.navigation\", NAVIGATION_KEYS);\n    for (const key of NAVIGATION_KEYS) {\n      assertHook(client.navigation[key], pluginName, `client.navigation.${key}`);\n    }\n  }\n}\n\nfunction assertLifecycleObject(\n  value: unknown,\n  pluginName: string,\n  location: string,\n  allowedKeys: readonly string[],\n): asserts value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be an object`);\n  }\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a plain object`);\n  }\n\n  for (const key of Reflect.ownKeys(value)) {\n    if (typeof key === \"symbol\") {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location} cannot contain symbol keys`);\n    }\n    if (!allowedKeys.includes(key)) {\n      throw new TypeError(`Client plugin \"${pluginName}\" has an unknown ${location}.${key} option`);\n    }\n    const descriptor = Object.getOwnPropertyDescriptor(value, key);\n    if (!descriptor?.enumerable) {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} must be enumerable`);\n    }\n    if (!(\"value\" in descriptor)) {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} cannot be an accessor`);\n    }\n  }\n}\n\nfunction assertHook(value: unknown, pluginName: string, location: string): void {\n  if (value === undefined) return;\n  if (typeof value !== \"function\") {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n  }\n  functionSource(value, pluginName, location);\n}\n\nfunction serializeClientLifecycle(definition: FarmClientPlugin, pluginName: string): string {\n  const fields: string[] = [];\n  pushHook(fields, \"setup\", definition.setup, pluginName, \"client.setup\", 2);\n  pushHookGroup(fields, \"hydration\", definition.hydration, HYDRATION_KEYS, pluginName, 2);\n  pushHookGroup(fields, \"navigation\", definition.navigation, NAVIGATION_KEYS, pluginName, 2);\n  pushHook(fields, \"error\", definition.error, pluginName, \"client.error\", 2);\n  pushHook(fields, \"performance\", definition.performance, pluginName, \"client.performance\", 2);\n  pushHook(fields, \"close\", definition.close, pluginName, \"client.close\", 2);\n\n  return fields.length ? `{\\n${fields.join(\",\\n\")}\\n  }` : \"{}\";\n}\n\nfunction pushHookGroup(\n  fields: string[],\n  groupName: \"hydration\" | \"navigation\",\n  group: Record<string, unknown> | undefined,\n  keys: readonly string[],\n  pluginName: string,\n  indent: number,\n): void {\n  if (!group) return;\n  const hooks: string[] = [];\n  for (const key of keys) {\n    pushHook(hooks, key, group[key], pluginName, `client.${groupName}.${key}`, indent + 2);\n  }\n  fields.push(\n    `${\" \".repeat(indent)}${JSON.stringify(groupName)}: {\\n${hooks.join(\",\\n\")}\\n${\" \".repeat(indent)}}`,\n  );\n}\n\nfunction pushHook(\n  fields: string[],\n  key: string,\n  hook: unknown,\n  pluginName: string,\n  location: string,\n  indent: number,\n): void {\n  if (hook === undefined) return;\n  fields.push(\n    `${\" \".repeat(indent)}${JSON.stringify(key)}: ${functionSource(hook, pluginName, location)}`,\n  );\n}\n\nfunction functionSource(value: unknown, pluginName: string, location: string): string {\n  if (typeof value !== \"function\") {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n  }\n\n  const source = Function.prototype.toString.call(value).trim();\n  if (!source || source.includes(\"[native code]\")) {\n    throw new TypeError(\n      `Client plugin \"${pluginName}\" ${location} must be authored inline and cannot be native or bound`,\n    );\n  }\n\n  if (/^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+|\\()/.test(source)) {\n    return `(${source})`;\n  }\n\n  const method = source.match(/^(async\\s+)?(\\*\\s*)?[$A-Z_a-z][$\\w]*\\s*(\\([\\s\\S]*)$/);\n  if (method) {\n    const asyncPrefix = method[1] ?? \"\";\n    const generator = method[2] ? \"*\" : \"\";\n    return `(${asyncPrefix}function${generator}${method[3]})`;\n  }\n\n  if (source.includes(\"=>\")) return `(${source})`;\n\n  throw new TypeError(\n    `Client plugin \"${pluginName}\" ${location} must use a function, method, or arrow function`,\n  );\n}\n\nfunction assertPublicData(value: unknown, pluginName: string): void {\n  if (value === undefined) return;\n  const seen = new WeakSet<object>();\n\n  const visit = (current: unknown, pathSegments: string[]): void => {\n    if (current === null || typeof current === \"string\" || typeof current === \"boolean\") {\n      return;\n    }\n    if (typeof current === \"number\") {\n      if (Number.isFinite(current)) return;\n      throwPublicDataError(pluginName, pathSegments, \"must be a finite number\");\n    }\n    if (typeof current !== \"object\") {\n      throwPublicDataError(pluginName, pathSegments, `cannot contain ${typeof current} values`);\n    }\n    if (seen.has(current)) {\n      throwPublicDataError(pluginName, pathSegments, \"cannot contain circular references\");\n    }\n    seen.add(current);\n\n    if (Array.isArray(current)) {\n      for (let index = 0; index < current.length; index += 1) {\n        if (!Object.prototype.hasOwnProperty.call(current, index)) {\n          throwPublicDataError(\n            pluginName,\n            [...pathSegments, String(index)],\n            \"cannot contain sparse array slots\",\n          );\n        }\n        visit(current[index], [...pathSegments, String(index)]);\n      }\n      for (const key of Reflect.ownKeys(current)) {\n        if (key === \"length\" || (typeof key === \"string\" && isArrayIndex(key))) continue;\n        throwPublicDataError(\n          pluginName,\n          pathSegments,\n          typeof key === \"symbol\"\n            ? \"cannot contain symbol keys\"\n            : `cannot contain non-index array property ${key}`,\n        );\n      }\n      seen.delete(current);\n      return;\n    }\n\n    const prototype = Object.getPrototypeOf(current);\n    if (prototype !== Object.prototype && prototype !== null) {\n      throwPublicDataError(pluginName, pathSegments, \"must contain only plain objects and arrays\");\n    }\n    for (const key of Reflect.ownKeys(current)) {\n      if (typeof key === \"symbol\") {\n        throwPublicDataError(pluginName, pathSegments, \"cannot contain symbol keys\");\n      }\n      const descriptor = Object.getOwnPropertyDescriptor(current, key);\n      if (!descriptor?.enumerable) {\n        throwPublicDataError(\n          pluginName,\n          [...pathSegments, key],\n          \"cannot contain non-enumerable properties\",\n        );\n      }\n      if (!(\"value\" in descriptor)) {\n        throwPublicDataError(\n          pluginName,\n          [...pathSegments, key],\n          \"cannot contain accessor properties\",\n        );\n      }\n      visit(descriptor.value, [...pathSegments, key]);\n    }\n    seen.delete(current);\n  };\n\n  visit(value, []);\n}\n\nfunction throwPublicDataError(pluginName: string, pathSegments: string[], message: string): never {\n  const location = pathSegments.length ? ` at client.public.${pathSegments.join(\".\")}` : \"\";\n  throw new TypeError(`Client plugin \"${pluginName}\"${location} ${message}`);\n}\n\nfunction serializePublicData(value: unknown): string {\n  if (value === undefined) return \"undefined\";\n  return `JSON.parse(${JSON.stringify(JSON.stringify(value))})`;\n}\n\nfunction serializeOptionalString(value: string | undefined): string {\n  return value === undefined ? \"undefined\" : JSON.stringify(value);\n}\n\nfunction isArrayIndex(key: string): boolean {\n  const value = Number(key);\n  return Number.isInteger(value) && value >= 0 && value < 4_294_967_295 && String(value) === key;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { FarmCacheUserConfig } from \"./cache\";\n\nconst ADAPTER_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"mjs\"] as const;\n\nexport interface ResolvedClientCacheAdapterEntry {\n  /** Absolute adapter module path with forward slashes, ready for codegen. */\n  importPath: string;\n  options: { version?: string; flushDelayMs?: number };\n}\n\nexport interface ClientCachePersistenceEntryCode {\n  imports: string;\n  init: string;\n}\n\n/**\n * Resolve `cache.client.adapter` from configuration to an absolute module\n * path for the generated client entries. Fails the build with an actionable\n * error when the option is set but the module cannot be found.\n */\nexport function resolveFarmClientCacheAdapterEntry(\n  root: string,\n  cache: FarmCacheUserConfig | undefined,\n): ResolvedClientCacheAdapterEntry | undefined {\n  const client = cache?.client;\n  const adapter = client?.adapter;\n  if (adapter === undefined) return undefined;\n\n  if (typeof adapter !== \"string\" || adapter.trim().length === 0) {\n    throw new Error(\n      'cache.client.adapter must be a module path string, for example \"./src/cache-adapter\".',\n    );\n  }\n\n  const resolved = path.resolve(root, adapter);\n  const found = resolveAdapterFile(resolved);\n  if (!found) {\n    throw new Error(\n      `cache.client.adapter was not found: ${adapter} (resolved to ${resolved}). ` +\n        \"Point it at a client module whose default export is created with defineClientCacheAdapter().\",\n    );\n  }\n\n  const options: ResolvedClientCacheAdapterEntry[\"options\"] = {};\n  if (client?.version !== undefined) options.version = client.version;\n  if (client?.flushDelayMs !== undefined) options.flushDelayMs = client.flushDelayMs;\n  return { importPath: found.replace(/\\\\/g, \"/\"), options };\n}\n\nfunction resolveAdapterFile(resolved: string): string | undefined {\n  if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) return resolved;\n  for (const extension of ADAPTER_EXTENSIONS) {\n    const candidate = `${resolved}.${extension}`;\n    if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n  }\n  return undefined;\n}\n\n/**\n * Code fragments for the generated client entries: an import of the user's\n * adapter module and an init call that runs before hydration starts. Empty\n * strings when persistence is not configured, so entries stay unchanged.\n */\nexport function generateClientCachePersistenceCode(\n  entry: ResolvedClientCacheAdapterEntry | undefined,\n): ClientCachePersistenceEntryCode {\n  if (!entry) return { imports: \"\", init: \"\" };\n\n  return {\n    imports: [\n      `import * as __farmClientCacheAdapterModule from ${JSON.stringify(entry.importPath)};`,\n      `import { initConfiguredClientCachePersistence as __farmInitClientCachePersistence } from \"@farm.js/core/client\";`,\n    ].join(\"\\n\"),\n    init: `__farmInitClientCachePersistence(__farmClientCacheAdapterModule, ${JSON.stringify(entry.options)});`,\n  };\n}\n","import { existsSync, mkdirSync, readFileSync, unlinkSync } from \"fs\";\nimport { dirname, isAbsolute, join, resolve } from \"path\";\nimport { APITypeGenerator, type APIRouteInfo } from \"./type-generator\";\nimport {\n  createRouteTypeDeclarations,\n  generateRouteTypes,\n  type GenerateRouteTypesOptions,\n} from \"./routing/generate-route-types\";\nimport { createEnvTypeDeclarations, generateEnvTypes } from \"./env-types\";\nimport { createFarmImageTypeDeclarations, generateFarmImageTypes } from \"./image-types\";\nimport { createContentTypeDeclarations } from \"./content-types\";\nimport { generateFarmI18nTypes, renderFarmI18nTypes } from \"./i18n/type-generator\";\nimport { readFarmI18nCatalogs } from \"./i18n/catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { getFarmAppDirectories, getFarmSourceRoots, type ResolvedFarmLayer } from \"./layers\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\nimport type { FarmPlugin } from \"./plugin\";\nimport { resolvePluginRoutes } from \"./api/route\";\n\nexport { generateFarmI18nTypes };\n\nexport interface GenerateFarmTypeArtifactsOptions {\n  root: string;\n  srcDir?: string;\n  configPath?: string;\n  plugins?: readonly FarmPlugin[];\n  extraRoutes?: string[];\n  layers?: readonly ResolvedFarmLayer[];\n  suppressLintOnLink?: boolean;\n  componentExtensions?: readonly string[];\n  routeTypesOutFile?: string;\n  apiTypesOutFile?: string;\n  envTypesOutFile?: string;\n  imageTypesOutFile?: string;\n  i18nTypesOutFile?: string;\n  i18nConfig?: ResolvedFarmI18nConfig;\n  routes?: boolean;\n  api?: boolean;\n  env?: boolean;\n  images?: boolean;\n  i18n?: boolean;\n  /** Compare generated content with disk without writing files. */\n  check?: boolean;\n}\n\nexport interface GenerateFarmTypeArtifactsResult {\n  typesPath?: string;\n  routeTypesPath?: string;\n  apiTypesPath?: string;\n  envTypesPath?: string;\n  imageTypesPath?: string;\n  i18nTypesPath?: string;\n  apiRoutes: APIRouteInfo[];\n  /** Generated files whose checked-in content is missing or stale. */\n  stalePaths: string[];\n}\n\nexport async function generateFarmTypeArtifacts(\n  options: GenerateFarmTypeArtifactsOptions,\n): Promise<GenerateFarmTypeArtifactsResult> {\n  const root = resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const shouldGenerateRoutes = options.routes !== false;\n  const shouldGenerateApi = options.api !== false;\n  const shouldGenerateEnv = options.env !== false;\n  const shouldGenerateImages = options.images !== false;\n  const shouldGenerateI18n = options.i18n !== false && options.i18nConfig?.enabled;\n  const sourceRoots = getFarmSourceRoots({ root, srcDir, layers: options.layers });\n  const appDirs = getFarmAppDirectories({ root, srcDir, layers: options.layers });\n\n  const result: GenerateFarmTypeArtifactsResult = {\n    apiRoutes: [],\n    stalePaths: [],\n  };\n  const unifiedTypesPath = join(root, srcDir, \"farm.d.ts\");\n  const shouldRefreshUnifiedTypes =\n    (shouldGenerateRoutes && !options.routeTypesOutFile) ||\n    (shouldGenerateEnv && !options.envTypesOutFile) ||\n    (shouldGenerateI18n && !options.i18nTypesOutFile);\n  const unifiedSections: string[] = [];\n\n  if (shouldRefreshUnifiedTypes && !options.routeTypesOutFile) {\n    const routeOptions: GenerateRouteTypesOptions = {\n      root,\n      srcDir,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    };\n    unifiedSections.push(await createRouteTypeDeclarations(routeOptions, unifiedTypesPath));\n    result.routeTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateRoutes) {\n    const routeOptions = {\n      root,\n      srcDir,\n      outFile: options.routeTypesOutFile,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    } satisfies GenerateRouteTypesOptions;\n    if (options.check) {\n      const routeTypesPath = resolveGeneratedPath(root, srcDir, options.routeTypesOutFile!);\n      const content = await createRouteTypeDeclarations(routeOptions, routeTypesPath);\n      checkGeneratedFile(routeTypesPath, content, result.stalePaths);\n      result.routeTypesPath = routeTypesPath;\n    } else {\n      result.routeTypesPath = await generateRouteTypes(routeOptions);\n    }\n  }\n\n  if (shouldGenerateApi) {\n    const generator = new APITypeGenerator(appDirs);\n    const apiRoutes = generator.scanAPIRoutes();\n    const apiTypesPath = options.apiTypesOutFile\n      ? resolve(root, options.apiTypesOutFile)\n      : join(root, srcDir, \"lib\", \"api.generated.ts\");\n    const pluginRoutes = resolvePluginRoutes(options.plugins);\n    const configFiles = [\n      ...(options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((file): file is string => Boolean(file)),\n      options.configPath\n        ? resolve(root, options.configPath)\n        : [\n            \"farm.config.ts\",\n            \"farm.config.mts\",\n            \"farm.config.js\",\n            \"farm.config.mjs\",\n            \"farm.config.cts\",\n            \"farm.config.cjs\",\n            \"config.ts\",\n            \"config.js\",\n          ]\n            .map((name) => join(root, name))\n            .find((file) => existsSync(file)),\n    ].filter((file): file is string => Boolean(file));\n    if (pluginRoutes.length && !configFiles.length) {\n      throw new Error(\n        \"Cannot generate plugin API types without a Farm config file. Pass configPath.\",\n      );\n    }\n    const content = generator.generateAPIRouter(apiRoutes, {\n      outFile: apiTypesPath,\n      pluginConfigs: pluginRoutes.length ? [...new Set(configFiles)] : [],\n      pluginRoutes,\n    });\n\n    writeOrCheckGeneratedFile(apiTypesPath, content, options.check, result.stalePaths);\n\n    result.apiTypesPath = apiTypesPath;\n    result.apiRoutes = apiRoutes;\n  }\n\n  if (shouldRefreshUnifiedTypes && !options.envTypesOutFile) {\n    unifiedSections.push(\n      createEnvTypeDeclarations(\n        {\n          root,\n          srcDir,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n    result.envTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateEnv) {\n    const envOptions = {\n      root,\n      srcDir,\n      outFile: options.envTypesOutFile,\n      configPath: options.configPath,\n      layerConfigPaths: (options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((configFile): configFile is string => Boolean(configFile)),\n    };\n    if (options.check) {\n      const envTypesPath = resolveGeneratedPath(root, srcDir, options.envTypesOutFile!);\n      checkGeneratedFile(\n        envTypesPath,\n        createEnvTypeDeclarations(envOptions, envTypesPath),\n        result.stalePaths,\n      );\n      result.envTypesPath = envTypesPath;\n    } else {\n      result.envTypesPath = await generateEnvTypes(envOptions);\n    }\n  }\n\n  // Static image modules are declared by @farm.js/core itself. Keep the\n  // explicit output option for callers that need a standalone declaration.\n  if (shouldGenerateImages && options.imageTypesOutFile) {\n    const imageTypesPath = resolveGeneratedPath(root, srcDir, options.imageTypesOutFile, false);\n    if (options.check) {\n      checkGeneratedFile(imageTypesPath, createFarmImageTypeDeclarations(), result.stalePaths);\n      result.imageTypesPath = imageTypesPath;\n    } else {\n      result.imageTypesPath = generateFarmImageTypes({\n        root,\n        srcDir,\n        outFile: options.imageTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes && options.i18nConfig?.enabled && !options.i18nTypesOutFile) {\n    const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n    unifiedSections.push(renderFarmI18nTypes(options.i18nConfig.locales, signatures));\n    result.i18nTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateI18n && options.i18nConfig) {\n    if (options.check) {\n      const i18nTypesPath = resolveGeneratedPath(root, srcDir, options.i18nTypesOutFile!, false);\n      const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n      checkGeneratedFile(\n        i18nTypesPath,\n        renderFarmI18nTypes(options.i18nConfig.locales, signatures),\n        result.stalePaths,\n      );\n      result.i18nTypesPath = i18nTypesPath;\n    } else {\n      result.i18nTypesPath = await generateFarmI18nTypes({\n        root,\n        srcDir,\n        config: options.i18nConfig,\n        outFile: options.i18nTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    unifiedSections.push(\n      createContentTypeDeclarations(\n        {\n          root,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    writeOrCheckGeneratedFile(\n      unifiedTypesPath,\n      `/**\n * Generated by Farm.js. Do not edit.\n * Contains project-specific route, environment, content, and internationalization types.\n */\n\nimport \"@farm.js/core/image\";\nimport \"@farm.js/core/css\";\n\n${unifiedSections.map(normalizeUnifiedTypeSection).join(\"\\n\\n\")}\n`,\n      options.check,\n      result.stalePaths,\n    );\n    result.typesPath = unifiedTypesPath;\n    if (options.check) {\n      collectLegacyTypeArtifacts(root, srcDir, result.stalePaths);\n    } else {\n      removeLegacyTypeArtifacts(root, srcDir);\n    }\n  }\n\n  return result;\n}\n\nfunction normalizeUnifiedTypeSection(section: string): string {\n  // The unified artifact already imports Farm's asset types, so it is a module.\n  // Individual generators add this marker for standalone declaration files, but\n  // formatters remove the now-redundant export and make `farm generate --check`\n  // report a false stale-file failure.\n  return section.trimEnd().replace(/\\n+export \\{\\};$/, \"\");\n}\n\nfunction resolveGeneratedPath(\n  root: string,\n  srcDir: string,\n  outFile: string,\n  relativeToSrc = true,\n): string {\n  if (isAbsolute(outFile)) return resolve(outFile);\n  return resolve(root, relativeToSrc ? join(srcDir, outFile) : outFile);\n}\n\nfunction writeOrCheckGeneratedFile(\n  filePath: string,\n  content: string,\n  check: boolean | undefined,\n  stalePaths: string[],\n): void {\n  if (check) {\n    checkGeneratedFile(filePath, content, stalePaths);\n    return;\n  }\n\n  mkdirSync(dirname(filePath), { recursive: true });\n  writeFileIfChanged(filePath, content);\n}\n\nfunction checkGeneratedFile(filePath: string, content: string, stalePaths: string[]): void {\n  if (!existsSync(filePath) || readFileSync(filePath, \"utf8\") !== content) {\n    stalePaths.push(filePath);\n  }\n}\n\nconst LEGACY_TYPE_ARTIFACTS = [\n  [\"farm-routes.d.ts\", \"Auto-generated route types\"],\n  [\"farm-env.d.ts\", \"Auto-generated env types\"],\n  [\"farm-images.d.ts\", \"Generated by Farm.js\"],\n  [\"farm-i18n.d.ts\", \"Generated by Farm.js\"],\n] as const;\n\nfunction removeLegacyTypeArtifacts(root: string, srcDir: string): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    const source = readFileSync(filePath, \"utf8\");\n    if (source.includes(marker)) {\n      unlinkSync(filePath);\n    }\n  }\n}\n\nfunction collectLegacyTypeArtifacts(root: string, srcDir: string, stalePaths: string[]): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    if (readFileSync(filePath, \"utf8\").includes(marker)) stalePaths.push(filePath);\n  }\n}\n","import * as path from \"path\";\nimport * as fs from \"fs\";\nimport { parseRoutePath } from \"../utils\";\nimport { parseRouteSlotFile } from \"./route-slots\";\nimport type { ParsedRoute } from \"../types\";\nimport { discoverProgrammaticRoutePaths } from \"../routes.server\";\nimport type { FarmSourceRoot } from \"../layers\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\nimport { resolveFarmComponentExtensions } from \"../renderer\";\n\nfunction routeSegmentsToTsTypeLiteral(segments: string[]): string {\n  if (segments.length === 0) return '\"/\"';\n  const hasDynamic = segments.some((s) => s.startsWith(\"[\"));\n  if (!hasDynamic) return JSON.stringify(\"/\" + segments.join(\"/\"));\n  const parts = segments.map((s) => {\n    if (s.startsWith(\"[[...\") || s.startsWith(\"[...\")) return \"${string}\";\n    if (s.startsWith(\"[\")) return \"${string}\";\n    return s;\n  });\n  return \"`/\" + parts.join(\"/\") + \"`\";\n}\n\nfunction routePatternToTsTypeLiterals(pattern: string): string[] {\n  if (pattern === \"/\") return ['\"/\"'];\n\n  let variants: string[][] = [[]];\n  for (const segment of pattern.slice(1).split(\"/\").filter(Boolean)) {\n    if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) {\n      variants = variants.flatMap((parts) => [parts, [...parts, segment]]);\n    } else {\n      variants = variants.map((parts) => [...parts, segment]);\n    }\n  }\n\n  return variants.map(routeSegmentsToTsTypeLiteral);\n}\n\nfunction routePatternToRouteLiteral(pattern: string): string {\n  return JSON.stringify(pattern);\n}\n\nfunction renderTypeUnion(values: readonly string[]): string {\n  return values.length <= 1 ? values[0] || \"never\" : `\\n  | ${values.join(\"\\n  | \")}`;\n}\n\nfunction renderTypeAlias(name: string, value: string): string {\n  return `export type ${name} =${value.startsWith(\"\\n\") ? \"\" : \" \"}${value};`;\n}\n\nfunction createRoutePattern(route: ParsedRoute): string {\n  if (route.segments.length === 0) return \"/\";\n  return (\n    \"/\" +\n    route.segments\n      .map((seg) => {\n        if (!seg.isDynamic) return seg.segment;\n        if (seg.isCatchAll) return seg.isOptional ? `[[...${seg.segment}]]` : `[...${seg.segment}]`;\n        return `[${seg.segment}]`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport interface GenerateRouteTypesOptions {\n  root: string;\n  srcDir?: string;\n  outFile?: string;\n  extraRoutes?: string[];\n  /** Ordered layer roots followed by the project root. */\n  sourceRoots?: readonly FarmSourceRoot[];\n  /** When true, do not augment LinkDefaultRoute so Link href accepts any string (no route-type errors). */\n  suppressLintOnLink?: boolean;\n  /** Additional renderer-owned component extensions, such as `.vue` or `.svelte`. */\n  componentExtensions?: readonly string[];\n}\n\nconst DEFAULT_OUT_FILE = \"farm-routes.d.ts\";\n\n/**\n * Scan application route modules, generate page and module route unions,\n * and write a .d.ts file for typed Link hrefs and route component props.\n */\nexport async function generateRouteTypes(options: GenerateRouteTypesOptions): Promise<string> {\n  const root = path.resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const outFile = options.outFile || DEFAULT_OUT_FILE;\n  const outPath = path.isAbsolute(outFile) ? outFile : path.join(root, srcDir, outFile);\n  const content = await createRouteTypeDeclarations(options, outPath);\n\n  fs.mkdirSync(path.dirname(outPath), { recursive: true });\n  writeFileIfChanged(outPath, content);\n\n  return outPath;\n}\n\nexport async function createRouteTypeDeclarations(\n  options: GenerateRouteTypesOptions,\n  outPath: string,\n): Promise<string> {\n  const { root, srcDir = \"src\", extraRoutes = [], suppressLintOnLink = false } = options;\n  const sourceRoots = options.sourceRoots ?? [{ name: \"project\", root, srcDir, layer: false }];\n  const componentExtensions = resolveFarmComponentExtensions(options.componentExtensions).map(\n    (extension) => extension.slice(1),\n  );\n\n  const patterns = new Set<string>();\n  const routeModulePatterns = new Set<string>();\n\n  const glob = await import(\"fast-glob\");\n  for (const source of sourceRoots) {\n    const appDir = path.join(source.root, source.srcDir, \"app\");\n    if (fs.existsSync(appDir)) {\n      const routeModuleFiles = await glob.default(\n        `**/{page,layout,loading,error}.{${componentExtensions.join(\",\")},md,mdx}`,\n        {\n          cwd: appDir,\n          absolute: false,\n        },\n      );\n\n      for (const file of routeModuleFiles) {\n        if (parseRouteSlotFile(file)) continue;\n        const route = parseRoutePath(file);\n        const pattern = createRoutePattern(route);\n        routeModulePatterns.add(pattern);\n        if (route.type === \"page\") {\n          patterns.add(pattern);\n        }\n      }\n    }\n\n    for (const route of await discoverProgrammaticRoutePaths(source.root, source.srcDir)) {\n      patterns.add(route);\n      routeModulePatterns.add(route);\n    }\n  }\n\n  for (const route of extraRoutes) {\n    if (route.startsWith(\"/\")) {\n      patterns.add(route);\n      routeModulePatterns.add(route);\n    }\n  }\n\n  const sortedPatterns = Array.from(patterns).sort();\n  const typeLiterals = Array.from(new Set(sortedPatterns.flatMap(routePatternToTsTypeLiterals)));\n  const patternLiterals = sortedPatterns.map(routePatternToRouteLiteral);\n  const routeModulePatternLiterals = Array.from(routeModulePatterns)\n    .sort()\n    .map(routePatternToRouteLiteral);\n\n  const routePathType = suppressLintOnLink ? \"string\" : renderTypeUnion(typeLiterals);\n  const routePatternType = suppressLintOnLink ? \"string\" : renderTypeUnion(patternLiterals);\n  const routeModulePatternType = renderTypeUnion(routeModulePatternLiterals);\n  const routeTypesImportPath = `./${path.basename(outPath).replace(/\\.d\\.ts$/, \"\")}`;\n  const linkAugmentationBlock = suppressLintOnLink\n    ? \"\"\n    : `\ndeclare module \"@farm.js/core/client\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n}\n\ndeclare module \"@farm.js/core\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n  // Ensure root import (\"@farm.js/core\") uses the same typed Link signature as client entry.\n  const Link: typeof import(\"@farm.js/core/client\").Link;\n}\n\n// Internal declaration path used by @farm.js/core root type re-exports.\ndeclare module \"@farm.js/core/dist/client.js\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n}\n`;\n\n  const routeModuleAugmentationBlock = `\ndeclare global {\n  namespace FarmJS {\n    interface RouteRegistry {\n      pattern: import(${JSON.stringify(routeTypesImportPath)}).RouteModulePattern;\n    }\n  }\n}\n`;\n\n  const content = `/**\n * Auto-generated route types from src/app.\n * Link href and route component props are typed automatically from generated declarations.\n * Regenerated on dev start and when routes change.\n * Set suppressLintOnLink: true in farm.config.ts to accept any string on Link href.\n */\n${renderTypeAlias(\"RoutePath\", routePathType)}\n${renderTypeAlias(\"RoutePattern\", routePatternType)}\n${renderTypeAlias(\"RouteModulePattern\", routeModulePatternType)}${linkAugmentationBlock}${routeModuleAugmentationBlock}\n`;\n\n  return content;\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport const FARM_STATIC_IMAGE_EXTENSIONS = [\"avif\", \"gif\", \"jpeg\", \"jpg\", \"png\", \"webp\"] as const;\n\nexport interface GenerateFarmImageTypesOptions {\n  root: string;\n  srcDir?: string;\n  outFile?: string;\n}\n\nexport function generateFarmImageTypes(options: GenerateFarmImageTypesOptions): string {\n  const outputPath = options.outFile\n    ? path.resolve(options.root, options.outFile)\n    : path.join(options.root, options.srcDir || \"src\", \"farm-images.d.ts\");\n  mkdirSync(path.dirname(outputPath), { recursive: true });\n  writeFileIfChanged(outputPath, createFarmImageTypeDeclarations());\n  return outputPath;\n}\n\nexport function createFarmImageTypeDeclarations(): string {\n  const modules = FARM_STATIC_IMAGE_EXTENSIONS.map(\n    (extension) => `declare module \"*.${extension}\" {\n  const image: import(\"@farm.js/core/image\").StaticImageData;\n  export const src: string;\n  export const width: number;\n  export const height: number;\n  export const blurDataURL: string | undefined;\n  export default image;\n}`,\n  );\n\n  return `// Generated by Farm.js. Do not edit.\n${modules.join(\"\\n\\n\")}\n\ndeclare module \"*?url\" {\n  const src: string;\n  export default src;\n}\n`;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport interface CreateContentTypeDeclarationsOptions {\n  root: string;\n  configPath?: string;\n  /** Lower-priority layer config files, ordered before the project config. */\n  layerConfigPaths?: readonly string[];\n}\n\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\n/** Infer content collection names and entry data from content() in Farm config. */\nexport function createContentTypeDeclarations(\n  options: CreateContentTypeDeclarationsOptions,\n  outPath: string,\n): string {\n  const root = path.resolve(options.root);\n  const projectConfig = findConfigPath(root, options.configPath);\n  const configPaths = [\n    ...(options.layerConfigPaths ?? []).filter((value) => fs.existsSync(value)),\n    ...(projectConfig ? [projectConfig] : []),\n  ];\n\n  if (configPaths.length === 0) return createEmptyContentTypes();\n\n  const imports = configPaths\n    .map(\n      (configPath, index) =>\n        `import type FarmContentConfig${index} from ${JSON.stringify(toTypeImportPath(outPath, configPath))};`,\n    )\n    .join(\"\\n\");\n  const registries = configPaths\n    .map(\n      (_configPath, index) =>\n        `type FarmContentRegistry${index} = ContentRegistryFromConfig<typeof FarmContentConfig${index}>;`,\n    )\n    .join(\"\\n\");\n  const registryUnion = configPaths\n    .map((_configPath, index) => `FarmContentRegistry${index}`)\n    .join(\" | \");\n\n  return `/**\n * Auto-generated content collection types from Farm layers and farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\n${imports}\n\ntype FarmContentPluginFromConfig<TConfig> = TConfig extends {\n  plugins?: readonly (infer TPlugin)[];\n}\n  ? Extract<TPlugin, { readonly __farmContentRegistry: Record<string, unknown> }>\n  : never;\ntype ContentRegistryFromConfig<TConfig> =\n  FarmContentPluginFromConfig<TConfig> extends {\n    readonly __farmContentRegistry: infer TRegistry;\n  }\n    ? TRegistry\n    : never;\ntype FarmContentUnionToIntersection<TValue> = (\n  TValue extends unknown ? (value: TValue) => void : never\n) extends (value: infer TIntersection) => void\n  ? TIntersection\n  : never;\n${registries}\n\ntype FarmResolvedContentRegistry = [${registryUnion}] extends [never]\n  ? {}\n  : FarmContentUnionToIntersection<${registryUnion}>;\n\ndeclare global {\n  namespace FarmJS {\n    interface ContentRegistry {\n      collections: FarmResolvedContentRegistry;\n    }\n  }\n}\n\nexport {};\n`;\n}\n\nfunction createEmptyContentTypes(): string {\n  return `/**\n * Auto-generated content collection types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\ndeclare global {\n  namespace FarmJS {\n    interface ContentRegistry {\n      collections: {};\n    }\n  }\n}\n\nexport {};\n`;\n}\n\nfunction findConfigPath(root: string, configPath?: string): string | null {\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    return fs.existsSync(resolvedPath) ? resolvedPath : null;\n  }\n  for (const filename of CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (fs.existsSync(resolvedPath)) return resolvedPath;\n  }\n  return null;\n}\n\nfunction toTypeImportPath(outPath: string, targetPath: string): string {\n  const relativePath = path\n    .relative(path.dirname(outPath), targetPath)\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/, \"\");\n  return relativePath.startsWith(\".\") ? relativePath : `./${relativePath}`;\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n  readFarmI18nCatalogs,\n  type FarmI18nArgumentKind,\n  type FarmI18nMessageSignature,\n} from \"./catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./types\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\n\nexport interface GenerateFarmI18nTypesOptions {\n  root: string;\n  srcDir?: string;\n  config: ResolvedFarmI18nConfig;\n  outFile?: string;\n}\n\nexport async function generateFarmI18nTypes(\n  options: GenerateFarmI18nTypesOptions,\n): Promise<string | undefined> {\n  if (!options.config.enabled) return undefined;\n\n  const { signatures } = await readFarmI18nCatalogs(options.config);\n  const outFile = options.outFile\n    ? resolve(options.root, options.outFile)\n    : join(resolve(options.root), options.srcDir || \"src\", \"farm-i18n.d.ts\");\n  const content = renderFarmI18nTypes(options.config.locales, signatures);\n\n  mkdirSync(dirname(outFile), { recursive: true });\n  writeFileIfChanged(outFile, content);\n  return outFile;\n}\n\nexport function renderFarmI18nTypes(\n  locales: readonly string[],\n  signatures: Record<string, FarmI18nMessageSignature>,\n): string {\n  const localeEntries = locales.map((locale) => `    ${JSON.stringify(locale)}: true;`);\n  const messageEntries = Object.entries(signatures)\n    .sort(([a], [b]) => a.localeCompare(b))\n    .map(([key, signature]) => `    ${JSON.stringify(key)}: ${renderSignature(signature)};`);\n\n  return `// Generated by Farm.js. Do not edit.\nimport \"@farm.js/core/i18n\";\n\ndeclare module \"@farm.js/core/i18n\" {\n  interface FarmI18nLocaleRegistry {\n${localeEntries.join(\"\\n\")}\n  }\n\n  interface FarmI18nMessageRegistry {\n${messageEntries.join(\"\\n\")}\n  }\n}\n\nexport {};\n`;\n}\n\nfunction renderSignature(signature: FarmI18nMessageSignature): string {\n  const entries = Object.entries(signature).sort(([a], [b]) => a.localeCompare(b));\n  if (entries.length === 0) return \"Record<never, never>\";\n  return `{ ${entries\n    .map(([name, kind]) => `${JSON.stringify(name)}: ${argumentType(kind)}`)\n    .join(\"; \")} }`;\n}\n\nfunction argumentType(kind: FarmI18nArgumentKind): string {\n  switch (kind) {\n    case \"number\":\n      return \"number\";\n    case \"date\":\n      return \"Date | number\";\n    case \"rich\":\n      return \"(chunks: unknown[]) => unknown\";\n    case \"select\":\n    case \"string\":\n      return \"string\";\n  }\n}\n","import type { ConfigEnv, Plugin, UserConfig, ViteDevServer, HmrContext, Connect } from \"vite\";\nimport type { FarmConfig, FarmRequest } from \"./types\";\nimport { FarmApp } from \"./app\";\nimport { logger, toPosixPath, toViteModuleId } from \"./utils\";\nimport { defaultGlobalCSS } from \"./default-styles\";\nimport {\n  FARM_NODE_RESPONSE_END_PENDING,\n  type FarmPlugin,\n  type FarmPluginRuntimeSession,\n  type PluginManager,\n} from \"./plugin\";\nimport { generateFarmClientPluginEntryCode } from \"./client-plugin-build\";\nimport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n  type ClientCachePersistenceEntryCode,\n} from \"./client-cache-persistence-build\";\n\nexport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n} from \"./client-cache-persistence-build\";\nexport type { ClientCachePersistenceEntryCode } from \"./client-cache-persistence-build\";\nimport { APIRouteManager } from \"./api/route-manager\";\nimport { DEFAULT_FARM_API_BASE_PATH } from \"./api/config\";\nimport { resolveFarmAPIServerBasePath } from \"./api/server-path\";\nimport { isFarmAPIPathname } from \"./api/runtime\";\nimport type { OpenAPIManager } from \"./openapi/manager\";\nimport { MiddlewareManager } from \"./middleware/manager\";\nimport { generateFarmTypeArtifacts, type GenerateFarmTypeArtifactsOptions } from \"./type-artifacts\";\nimport {\n  isProgrammaticRoutesFileName,\n  parseProgrammaticRouteModuleId,\n  scanProgrammaticPagePaths,\n} from \"./routes-shared\";\nimport type { FarmDocsAPIHandler } from \"./docs\";\nimport { createMarkdownMirrorResponse, resolveMarkdownMirrorTarget } from \"./markdown\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  createFarmMarkdownSourceResponse,\n  farmRequestWantsMarkdown,\n  isFarmMarkdownPageFile,\n  normalizeFarmMarkdownRoutePath,\n} from \"./app-markdown\";\nimport { applyWebResponseHeaders, sendWebResponse } from \"./server/response\";\nimport {\n  getClientModuleMetadata,\n  getIslandStrategyExport,\n  hasUseClientDirective,\n  isIsolatableClientBoundarySource,\n  resolveFarmIsolatedClientHydrationMode,\n  stripUseClientDirective,\n} from \"./utils/client-component\";\nimport {\n  dispatchIntegrationRequest,\n  getFarmIntegrationPluginOwner,\n  getIntegrationDocumentNavigationMatchers,\n  getIntegrationProviders,\n  matchIntegrationRoute,\n} from \"./integrations\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"./route-context\";\nimport {\n  FARM_DEVTOOLS_LAUNCH_PARAM,\n  FARM_DEVTOOLS_PATH,\n  resolveFarmDevtoolsConfig,\n} from \"./devtools-config\";\nimport { generateFarmDevIndicatorsClientRuntime } from \"./dev-indicators\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmUserConfig } from \"./config\";\nimport { getFarmAppDirectories, getFarmLayerAliases, getFarmSourceRoots } from \"./layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"./environment-vite\";\nimport { FARM_VERSION } from \"./version\";\nimport { createDeferredDataResponse } from \"./deferred\";\nimport { _withAfterNodeMiddleware } from \"./after\";\nimport { _runWithAPIRequestRuntime } from \"./api/server-context\";\nimport type { APIRequestRuntime } from \"./api/server-client-bridge\";\nimport { shouldBypassFarmRouterForDottedPath } from \"./dev-static\";\nimport { findClientServerFnViolation, formatServerFnBoundaryError } from \"./server-query-boundary\";\nimport {\n  analyzeClientBoundary,\n  formatClientBoundaryWarning,\n  shouldInspectClientBoundary,\n} from \"./client-boundary-env\";\nimport {\n  createFarmDeploymentMismatchResponse,\n  FARM_DEPLOYMENT_ID_HEADER,\n  getFarmDeploymentMismatch,\n} from \"./deployment\";\nimport { getPublicFarmImageConfig, resolveFarmImageConfig } from \"./image-config\";\nimport { farmImageImportsPlugin } from \"./image-vite\";\nimport { farmFontImportsPlugin } from \"./font-vite\";\nimport { resolveFarmLayoutFonts } from \"./font\";\nimport { createFarmImageHandler, type FarmImageHandler } from \"./image-server\";\nimport { isFarmI18nCatalogFile, resolveFarmI18nMessagePath } from \"./i18n/config\";\nimport { getFarmI18nClientSnapshot } from \"./i18n/server\";\nimport { localizeFarmPathname } from \"./i18n/routing\";\nimport type { FarmI18nClientSnapshot } from \"./i18n/types\";\nimport {\n  createFarmClientOptimizeDepsConfig,\n  createFarmClientOptimizeDepsEntries,\n  createFarmSourceAlias,\n} from \"./server/vite-config\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"./docs/fonts\";\nimport {\n  createFarmNodeRequestAbortSignal,\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"./server-http\";\nimport { createCliColors } from \"./cli-colors\";\nimport { createFarmThemeCssPlugin } from \"./theme/vite\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { emitFarmEvent, runWithFarmRequestSpan } from \"./observability\";\nimport {\n  getFarmRendererCapabilities,\n  isReactRenderer,\n  loadFarmRendererVitePlugins,\n  REACT_RENDERER,\n  resolveFarmRenderer,\n} from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { generateFarmIntegrationProviderClientCode } from \"./integration-provider-build\";\nimport type { FarmIslandStrategy } from \"./island\";\nimport { resolveRouteRenderingConfig } from \"./ssg\";\nimport {\n  createFarmRouteRenderPlan,\n  getSharedLayoutPrefixLength,\n  getFarmFragmentCacheControl,\n  parseFarmLayoutChainHeader,\n} from \"./navigation/render-plan\";\nimport { resolveFarmPageDataFailure } from \"./navigation/page-data-error\";\nimport { mergeMetadata } from \"./metadata\";\nimport { FARM_CONFIG_REWRITES_PLUGIN_NAME } from \"./plugins/rewrites\";\nimport { resolveFarmRequestURL } from \"./server/request\";\nimport { reportOpenAPIDevGenerationResult } from \"./openapi/dev-status\";\n\ninterface FarmVitePluginOptions extends FarmConfig {\n  openapi?: FarmUserConfig[\"openapi\"];\n  images?: FarmUserConfig[\"images\"];\n  publicDir?: FarmUserConfig[\"publicDir\"];\n  /** @internal Modules selected by the compiled isolated-hydration ownership plan. */\n  isolatedClientBoundaryModules?: ReadonlySet<string>;\n}\n\ntype TypeArtifactSelection = Pick<\n  GenerateFarmTypeArtifactsOptions,\n  \"routes\" | \"api\" | \"env\" | \"images\" | \"i18n\"\n>;\n\nconst ALL_TYPE_ARTIFACTS: TypeArtifactSelection = {\n  routes: true,\n  api: true,\n  env: true,\n  images: false,\n  i18n: true,\n};\n\nconst createEmptyTypeArtifactSelection = (): TypeArtifactSelection => ({\n  routes: false,\n  api: false,\n  env: false,\n  images: false,\n  i18n: false,\n});\n\nconst FARM_I18N_CLIENT_BRIDGE_ID = \"\\0farm-i18n-client-bridge\";\n\n// The @farm.js/devtools plugin serves this path itself; reaching the built-in\n// dashboard render means the app is still on the deprecated core UI.\nlet warnedDeprecatedDevtoolsDashboard = false;\nconst EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME = `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n\nfunction loadFarmDocsDevRuntime() {\n  return import(\"./docs\");\n}\n\nfunction loadFarmDocsSearchDevRuntime() {\n  return import(\"./docs/search-client\");\n}\n\nfunction loadFarmOpenAPIDevRuntime() {\n  return import(\"./openapi/manager\");\n}\n\nfunction loadFarmWorkflowsDevRuntime() {\n  return import(\"./workflows\");\n}\n\nfunction loadFarmDevtoolsSnapshotRuntime() {\n  return import(\"./devtools\");\n}\n\nfunction loadFarmDevtoolsUIRuntime() {\n  return import(\"./devtools-ui\");\n}\n\nfunction loadFarmDevtoolsClientRuntime() {\n  return import(\"./devtools-client\");\n}\n\nexport function farmI18nClientBridgePlugin(): Plugin {\n  return {\n    name: \"farm:i18n-client-bridge\",\n    enforce: \"pre\",\n    resolveId(id, _importer, options) {\n      if (id === \"@farm.js/core/i18n/server\" && !options?.ssr) {\n        return FARM_I18N_CLIENT_BRIDGE_ID;\n      }\n      return null;\n    },\n    load(id) {\n      if (id !== FARM_I18N_CLIENT_BRIDGE_ID) return null;\n      return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n    },\n  };\n}\n\nconst FARM_CONFIG_FILENAMES = new Set([\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n]);\n\nfunction serializeFarmInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeFarmHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction renderFarmI18nStaticHead(\n  requestPath: string,\n  snapshot: FarmI18nClientSnapshot | undefined,\n): string {\n  if (!snapshot) return \"\";\n  const runtime = `<script>window.__FARM_I18N__ = ${serializeFarmInlineValue(snapshot)};</script>`;\n  if (snapshot.routing === \"none\") return runtime;\n\n  const links = snapshot.locales.map(\n    (locale) =>\n      `<link rel=\"alternate\" hreflang=\"${escapeFarmHtmlAttribute(locale)}\" href=\"${escapeFarmHtmlAttribute(\n        localizeFarmPathname(requestPath, locale, snapshot),\n      )}\">`,\n  );\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeFarmHtmlAttribute(\n      localizeFarmPathname(requestPath, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return `${links.join(\"\")}${runtime}`;\n}\n\nfunction getPublicEnvDefine(config: FarmVitePluginOptions): Record<string, unknown> {\n  const publicEnv = (config as any).env?.public;\n  if (!isResolvedEnvScope(publicEnv)) {\n    return {};\n  }\n\n  return publicEnv;\n}\n\nfunction createRequestFromNodeRequest(\n  req: {\n    method?: string;\n    headers: Record<string, string | string[] | undefined>;\n  },\n  url: URL,\n  signal?: AbortSignal,\n): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (Array.isArray(value)) {\n      for (const item of value) headers.append(key, item);\n    } else if (value !== undefined) {\n      headers.set(key, value);\n    }\n  }\n\n  return new Request(url.toString(), {\n    method: req.method || \"GET\",\n    headers,\n    signal,\n  });\n}\n\nexport { createFarmNodeRequestAbortSignal } from \"./server-http\";\n\n/** Exported for tests: the request boundary all Farm dev middlewares share. */\nexport function withFarmRequestTracing(\n  handler: Parameters<typeof _withAfterNodeMiddleware>[0],\n  apiRuntime?: APIRequestRuntime,\n  resolveTraceUrl: (request: Connect.IncomingMessage) => URL = (request) =>\n    resolveFarmRequestURL(request as FarmRequest),\n): Connect.NextHandleFunction {\n  const middleware = _withAfterNodeMiddleware(handler);\n  return (req, res, next) => {\n    const traceUrl = resolveTraceUrl(req);\n    const traceRequest = createRequestFromNodeRequest(req, traceUrl);\n    const run = () =>\n      runWithFarmRequestSpan(traceRequest, () => middleware(req, res, next), {\n        getStatusCode: () => res.statusCode || 200,\n      });\n    const result = apiRuntime ? _runWithAPIRequestRuntime(apiRuntime, run) : run();\n    // connect ignores returned promises, so a rejection from the handler\n    // becomes an unhandled rejection and kills the dev server process. A\n    // throw from one request must cost that request a 500, not an outage.\n    return Promise.resolve(result).catch((error) => {\n      console.error(\n        `[FARM] Unhandled error while handling ${req.method || \"GET\"} ${req.url || \"/\"}:`,\n        error,\n      );\n      if (res.writableEnded) {\n        return;\n      }\n      if (res.headersSent) {\n        res.destroy?.(error instanceof Error ? error : new Error(String(error)));\n        return;\n      }\n      res.statusCode = 500;\n      res.setHeader(\"Content-Type\", \"application/json\");\n      res.end(JSON.stringify({ error: \"Internal server error\" }));\n    });\n  };\n}\n\nfunction toRequestBody(body: Buffer | undefined): ArrayBuffer | undefined {\n  if (!body) return undefined;\n  const copy = new Uint8Array(body.byteLength);\n  copy.set(body);\n  return copy.buffer;\n}\n\nfunction applyWebRequestToNodeRequest(\n  request: Request,\n  req: {\n    method?: string;\n    url?: string;\n    headers: Record<string, string | string[] | undefined>;\n  },\n): void {\n  const url = new URL(request.url);\n  req.method = request.method;\n  req.url = `${url.pathname}${url.search}`;\n\n  for (const key of Object.keys(req.headers)) {\n    delete req.headers[key];\n  }\n  request.headers.forEach((value, key) => {\n    req.headers[key] = value;\n  });\n}\n\nfunction createHeadersFromNodeResponse(res: {\n  getHeaders(): Record<string, string | number | string[] | undefined>;\n}): Headers {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(res.getHeaders())) {\n    if (Array.isArray(value)) {\n      for (const item of value) headers.append(key, item);\n    } else if (value !== undefined) {\n      headers.set(key, String(value));\n    }\n  }\n  return headers;\n}\n\nfunction applyWebResponseToNodeResponse(\n  response: Response,\n  res: {\n    statusCode: number;\n    headersSent: boolean;\n    getHeaderNames(): string[];\n    removeHeader(name: string): void;\n    setHeader(name: string, value: string): void;\n  },\n): void {\n  if (res.headersSent) return;\n\n  res.statusCode = response.status;\n  for (const name of res.getHeaderNames()) {\n    res.removeHeader(name);\n  }\n  applyWebResponseHeaders(res as any, response.headers);\n}\n\nfunction toNodeResponseBuffer(chunk: unknown, encoding?: unknown): Buffer | undefined {\n  if (chunk === undefined || chunk === null || typeof chunk === \"function\") return undefined;\n  if (Buffer.isBuffer(chunk)) return chunk;\n  if (chunk instanceof Uint8Array) return Buffer.from(chunk);\n  return Buffer.from(\n    String(chunk),\n    typeof encoding === \"string\" ? (encoding as BufferEncoding) : \"utf8\",\n  );\n}\n\nfunction applyNodeWriteHeadHeaders(res: any, headers: unknown): void {\n  if (Array.isArray(headers)) {\n    const grouped = new Map<string, { name: string; values: Array<string | number> }>();\n    for (let index = 0; index + 1 < headers.length; index += 2) {\n      const name = String(headers[index]);\n      const key = name.toLowerCase();\n      const entry = grouped.get(key) ?? { name, values: [] };\n      const value = headers[index + 1];\n      entry.values.push(...(Array.isArray(value) ? value : [value]).map(String));\n      grouped.set(key, entry);\n    }\n    for (const { name, values } of grouped.values()) {\n      res.setHeader(name, values.length === 1 ? values[0] : values);\n    }\n    return;\n  }\n\n  if (!headers || typeof headers !== \"object\") return;\n  for (const [name, value] of Object.entries(headers)) {\n    if (value !== undefined) res.setHeader(name, value);\n  }\n}\n\nfunction interceptFarmDevPageResponse(options: {\n  req: any;\n  res: any;\n  pm: PluginManager;\n  runtimeSession?: FarmPluginRuntimeSession;\n  hasRuntimeAfterHook: boolean;\n  hasAfterResponseHook: boolean;\n  hasHTMLTransformHook: boolean;\n  renderPayload: Record<string, unknown>;\n  method: string;\n  urlPath: string;\n  pathname: string;\n  startTime: number;\n  logResponse(method: string, path: string, status: number, durationMs: number, type: \"PAGE\"): void;\n  emitError(error: unknown): Promise<void>;\n}): { isEnded(): boolean } {\n  const {\n    req,\n    res,\n    pm,\n    runtimeSession,\n    hasRuntimeAfterHook,\n    hasAfterResponseHook,\n    hasHTMLTransformHook,\n    renderPayload,\n    method,\n    urlPath,\n    startTime,\n  } = options;\n  const originalWrite = res.write.bind(res);\n  const originalEnd = res.end.bind(res);\n  const originalWriteHead = res.writeHead.bind(res);\n  const originalFlushHeaders = res.flushHeaders?.bind(res);\n  let afterResponseCalled = false;\n  let interceptedEnd = false;\n  const htmlChunks: Buffer[] = [];\n  const responseChunks: Buffer[] = [];\n  let didStreamHtml = false;\n  const bufferPluginResponse = Boolean(\n    hasHTMLTransformHook || (runtimeSession && hasRuntimeAfterHook),\n  );\n  const shouldBufferCurrentResponse = () => {\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    return contentType.includes(\"text/html\")\n      ? bufferPluginResponse\n      : Boolean(runtimeSession && hasRuntimeAfterHook);\n  };\n\n  res.writeHead = ((statusCode: number, ...args: unknown[]) => {\n    const statusMessage = typeof args[0] === \"string\" ? args[0] : undefined;\n    const headers = statusMessage === undefined ? args[0] : args[1];\n    res.statusCode = statusCode;\n    if (statusMessage !== undefined) res.statusMessage = statusMessage;\n    applyNodeWriteHeadHeaders(res, headers);\n\n    if (shouldBufferCurrentResponse()) return res;\n    return statusMessage === undefined\n      ? originalWriteHead(statusCode)\n      : originalWriteHead(statusCode, statusMessage);\n  }) as any;\n\n  if (originalFlushHeaders) {\n    res.flushHeaders = (() =>\n      shouldBufferCurrentResponse() ? undefined : originalFlushHeaders()) as any;\n  }\n\n  res.write = ((chunk: unknown, ...args: unknown[]) => {\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    const isHtmlResponse = contentType.includes(\"text/html\");\n    const bufferChunk = toNodeResponseBuffer(chunk, args[0]);\n\n    if (isHtmlResponse && bufferChunk) {\n      htmlChunks.push(bufferChunk);\n      didStreamHtml = true;\n    } else if (runtimeSession && hasRuntimeAfterHook && bufferChunk) {\n      responseChunks.push(bufferChunk);\n    }\n\n    const shouldBufferResponse = isHtmlResponse\n      ? bufferPluginResponse\n      : Boolean(runtimeSession && hasRuntimeAfterHook);\n    if (shouldBufferResponse) {\n      const callback = args.find((arg) => typeof arg === \"function\") as (() => void) | undefined;\n      callback?.();\n      return true;\n    }\n\n    const writeResult = originalWrite(chunk, ...args);\n    if (isHtmlResponse && typeof res.flush === \"function\") res.flush();\n    return writeResult;\n  }) as any;\n\n  res.end = ((...args: unknown[]) => {\n    interceptedEnd = true;\n    res[FARM_NODE_RESPONSE_END_PENDING] = true;\n    if (afterResponseCalled) return res;\n\n    afterResponseCalled = true;\n    options.logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n    const originalEndArgs = [...args];\n    const callback =\n      typeof originalEndArgs[originalEndArgs.length - 1] === \"function\"\n        ? (originalEndArgs[originalEndArgs.length - 1] as () => void)\n        : undefined;\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    const isHtmlResponse = contentType.includes(\"text/html\");\n    const finalChunk = toNodeResponseBuffer(args[0], args[1]);\n    if (finalChunk) {\n      if (isHtmlResponse) htmlChunks.push(finalChunk);\n      else if (runtimeSession && hasRuntimeAfterHook) responseChunks.push(finalChunk);\n    }\n\n    Promise.resolve()\n      .then(async () => {\n        if (isHtmlResponse) {\n          const fullHtml = Buffer.concat(htmlChunks).toString(\"utf8\");\n          if (!didStreamHtml || bufferPluginResponse) {\n            let html = await pm.runHookSerial(\"transformHTML\", fullHtml);\n            html = await pm.runHookSerial(\"afterRender\", html, renderPayload);\n            originalEndArgs.length = 0;\n            originalEndArgs.push(html);\n            if (callback) originalEndArgs.push(callback);\n          } else {\n            await pm.runHookSerial(\"transformHTML\", fullHtml);\n            await pm.runHookSerial(\"afterRender\", fullHtml, renderPayload);\n          }\n        }\n\n        if (runtimeSession) {\n          pm.copyRequestContext(req, runtimeSession.request);\n          const status = res.statusCode || 200;\n          const canHaveBody =\n            method !== \"HEAD\" && status !== 204 && status !== 205 && status !== 304;\n          const firstArg = originalEndArgs[0];\n          const responseBody = canHaveBody\n            ? isHtmlResponse\n              ? didStreamHtml && !bufferPluginResponse\n                ? Buffer.concat(htmlChunks)\n                : toNodeResponseBuffer(firstArg, originalEndArgs[1])\n              : hasRuntimeAfterHook\n                ? Buffer.concat(responseChunks)\n                : toNodeResponseBuffer(firstArg, originalEndArgs[1])\n            : null;\n          const runtimeResponse = await pm.endRuntimeRequest(\n            runtimeSession,\n            new Response(responseBody ? toRequestBody(responseBody) : responseBody, {\n              status,\n              headers: createHeadersFromNodeResponse(res),\n            }),\n          );\n          applyWebResponseToNodeResponse(runtimeResponse, res);\n\n          const canReplaceOutput = isHtmlResponse\n            ? !didStreamHtml || bufferPluginResponse\n            : hasRuntimeAfterHook;\n          if (canReplaceOutput) {\n            const body = runtimeResponse.body\n              ? Buffer.from(await runtimeResponse.arrayBuffer())\n              : undefined;\n            originalEndArgs.length = 0;\n            if (body) originalEndArgs.push(body);\n            if (callback) originalEndArgs.push(callback);\n          }\n        }\n      })\n      .then(() =>\n        hasAfterResponseHook ? pm.runHookParallel(\"afterResponse\", req, res) : undefined,\n      )\n      .then(() => {\n        res.write = originalWrite;\n        res.end = originalEnd;\n        res.writeHead = originalWriteHead;\n        if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n        delete res[FARM_NODE_RESPONSE_END_PENDING];\n        originalEnd(...originalEndArgs);\n      })\n      .catch((error) => {\n        void options.emitError(error);\n        console.error(\"Error in afterResponse hook:\", error);\n        const shouldBufferResponse = isHtmlResponse\n          ? bufferPluginResponse\n          : Boolean(runtimeSession && hasRuntimeAfterHook);\n        if (shouldBufferResponse) {\n          const body = Buffer.concat(isHtmlResponse ? htmlChunks : responseChunks);\n          res.write = originalWrite;\n          res.end = originalEnd;\n          res.writeHead = originalWriteHead;\n          if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n          delete res[FARM_NODE_RESPONSE_END_PENDING];\n          originalEnd(body, callback);\n        } else {\n          res.write = originalWrite;\n          res.end = originalEnd;\n          res.writeHead = originalWriteHead;\n          if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n          delete res[FARM_NODE_RESPONSE_END_PENDING];\n          originalEnd(...originalEndArgs);\n        }\n      });\n\n    return res;\n  }) as any;\n\n  return {\n    isEnded: () => interceptedEnd || res.writableEnded,\n  };\n}\n\nfunction getFullEnvDefine(config: FarmVitePluginOptions): {\n  server: Record<string, unknown>;\n  public: Record<string, unknown>;\n} {\n  const env = (config as any).env;\n  if (!env || typeof env !== \"object\") {\n    return { server: {}, public: {} };\n  }\n\n  return {\n    server: isResolvedEnvScope(env.server) ? env.server : {},\n    public: isResolvedEnvScope(env.public) ? env.public : {},\n  };\n}\n\nfunction getEnvDefines(\n  config: FarmVitePluginOptions,\n  configEnv?: ConfigEnv,\n): Record<string, string> {\n  const defines: Record<string, string> = {\n    __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),\n    __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n    __FARM_IMAGE_CONFIG__: JSON.stringify(\n      getPublicFarmImageConfig(resolveFarmImageConfig(config.images)),\n    ),\n  };\n\n  if (configEnv?.isSsrBuild) {\n    defines.__FARM_ENV__ = JSON.stringify(getFullEnvDefine(config));\n  }\n\n  return defines;\n}\n\nfunction getFarmAPIBaseURLDefine(config: FarmVitePluginOptions): string {\n  const baseURL = config.api?.baseURL;\n  return typeof baseURL === \"string\" && baseURL ? baseURL : DEFAULT_FARM_API_BASE_PATH;\n}\n\nfunction isResolvedEnvScope(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    return false;\n  }\n\n  return !Object.values(value).some(\n    (entry) =>\n      typeof entry === \"function\" ||\n      (!!entry && typeof entry === \"object\" && typeof (entry as any).parse === \"function\"),\n  );\n}\n\nfunction isPotentialProgrammaticRouteSourceFile(\n  normalizedFile: string,\n  srcDirSlug: string,\n): boolean {\n  return (\n    normalizedFile.startsWith(`${srcDirSlug}/`) &&\n    /\\.(ts|tsx|js|jsx)$/.test(normalizedFile) &&\n    !normalizedFile.endsWith(\".d.ts\") &&\n    !normalizedFile.endsWith(\"/farm-routes.d.ts\") &&\n    !normalizedFile.endsWith(\"/farm-env.d.ts\") &&\n    !normalizedFile.endsWith(\"/lib/api.generated.ts\")\n  );\n}\n\nfunction fileContainsProgrammaticPageRoute(file: string): boolean {\n  if (!fs.existsSync(file)) {\n    return false;\n  }\n\n  try {\n    return scanProgrammaticPagePaths(fs.readFileSync(file, \"utf8\")).length > 0;\n  } catch {\n    return false;\n  }\n}\n\ninterface FarmModuleAstNode {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n}\n\nexport function rewriteEarlySsrRelativeImports(options: {\n  code: string;\n  id: string;\n  root: string;\n  parse: (code: string) => FarmModuleAstNode;\n}): string | null {\n  const cleanId = options.id.split(\"?\", 1)[0];\n  if (!path.isAbsolute(cleanId) || cleanId.replace(/\\\\/g, \"/\").includes(\"/node_modules/\")) {\n    return null;\n  }\n\n  const replacements: Array<{ start: number; end: number; code: string }> = [];\n  let ast: FarmModuleAstNode;\n  try {\n    ast = options.parse(options.code);\n  } catch {\n    return null;\n  }\n\n  walkModuleAst(ast, (node) => {\n    if (\n      node.type !== \"ImportDeclaration\" &&\n      node.type !== \"ExportNamedDeclaration\" &&\n      node.type !== \"ExportAllDeclaration\" &&\n      node.type !== \"ImportExpression\"\n    ) {\n      return;\n    }\n\n    const source = node.source;\n    if (!isFarmModuleAstNode(source) || typeof source.value !== \"string\") return;\n    if (!source.value.startsWith(\".\")) return;\n\n    const suffixIndex = source.value.search(/[?#]/);\n    const sourcePath = suffixIndex === -1 ? source.value : source.value.slice(0, suffixIndex);\n    const suffix = suffixIndex === -1 ? \"\" : source.value.slice(suffixIndex);\n    const resolvedPath = path.resolve(path.dirname(cleanId), sourcePath);\n\n    replacements.push({\n      start: source.start,\n      end: source.end,\n      code: JSON.stringify(`${toViteModuleId(resolvedPath, options.root)}${suffix}`),\n    });\n  });\n\n  if (replacements.length === 0) return null;\n\n  let output = options.code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n  return output;\n}\n\nexport function transformIsolatedClientBoundaryModule(options: {\n  code: string;\n  moduleReference: string;\n  islandStrategy: FarmIslandStrategy;\n  parse: (code: string) => FarmModuleAstNode;\n}): string | null {\n  let ast: FarmModuleAstNode;\n  try {\n    ast = options.parse(options.code);\n  } catch {\n    return null;\n  }\n\n  const body = Array.isArray((ast as any).body) ? ((ast as any).body as any[]) : [];\n  const replacements: Array<{ start: number; end: number; code: string }> = [];\n  const wrapperStatements: string[] = [];\n  const originalEntries: string[] = [];\n  let transformedExports = 0;\n\n  const addWrapper = (localName: string, exportName: string, isDefault = false) => {\n    const safeName = exportName.replace(/[^A-Za-z0-9_$]/g, \"_\");\n    const wrapperName = `__farm_isolated_boundary_${safeName || \"default\"}__`;\n    wrapperStatements.push(\n      `const ${wrapperName} = __farm_create_isolated_boundary__(__farm_isolated_react__, ${localName}, ${JSON.stringify(options.moduleReference)}, ${JSON.stringify(exportName)}, ${JSON.stringify(options.islandStrategy)});`,\n    );\n    wrapperStatements.push(\n      isDefault ? `export default ${wrapperName};` : `export { ${wrapperName} as ${exportName} };`,\n    );\n    originalEntries.push(`${JSON.stringify(exportName)}: ${localName}`);\n    transformedExports++;\n  };\n\n  for (const node of body) {\n    if (node?.type === \"ExportDefaultDeclaration\" && node.declaration) {\n      const declaration = node.declaration;\n      if (\n        (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n        declaration.id?.name\n      ) {\n        replacements.push({\n          start: node.start,\n          end: node.end,\n          code: options.code.slice(declaration.start, declaration.end),\n        });\n        addWrapper(declaration.id.name, \"default\", true);\n      } else {\n        const originalName = \"__farm_isolated_original_default__\";\n        replacements.push({\n          start: node.start,\n          end: node.end,\n          code: `const ${originalName} = (${options.code.slice(declaration.start, declaration.end)});`,\n        });\n        addWrapper(originalName, \"default\", true);\n      }\n      continue;\n    }\n\n    if (node?.type !== \"ExportNamedDeclaration\" || !node.declaration) continue;\n    const declaration = node.declaration;\n    const declaredNames: string[] = [];\n    if (\n      (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n      declaration.id?.name\n    ) {\n      declaredNames.push(declaration.id.name);\n    } else if (declaration.type === \"VariableDeclaration\") {\n      for (const declarator of declaration.declarations || []) {\n        if (declarator.id?.type === \"Identifier\") declaredNames.push(declarator.id.name);\n      }\n    }\n    const componentNames = declaredNames.filter((name) => /^[A-Z]/.test(name));\n    if (componentNames.length === 0) continue;\n\n    replacements.push({\n      start: node.start,\n      end: node.end,\n      code: options.code.slice(declaration.start, declaration.end),\n    });\n    for (const name of declaredNames) {\n      if (/^[A-Z]/.test(name)) addWrapper(name, name);\n      else wrapperStatements.push(`export { ${name} };`);\n    }\n  }\n\n  if (transformedExports === 0) return null;\n  let output = options.code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n\n  return `import * as __farm_isolated_react__ from \"react\";\\nimport { createFarmIsolatedClientBoundary as __farm_create_isolated_boundary__ } from \"@farm.js/core/internal/isolated-boundary\";\\n${output}\\n${wrapperStatements.join(\"\\n\")}\\nexport const __farm_client_boundary_originals__ = Object.freeze({ ${originalEntries.join(\", \")} });\\n`;\n}\n\nfunction walkModuleAst(node: FarmModuleAstNode, visit: (node: FarmModuleAstNode) => void): void {\n  visit(node);\n\n  for (const [key, value] of Object.entries(node)) {\n    if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n    if (isFarmModuleAstNode(value)) {\n      walkModuleAst(value, visit);\n      continue;\n    }\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        if (isFarmModuleAstNode(item)) walkModuleAst(item, visit);\n      }\n    }\n  }\n}\n\nfunction isFarmModuleAstNode(value: unknown): value is FarmModuleAstNode {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as FarmModuleAstNode).type === \"string\" &&\n    typeof (value as FarmModuleAstNode).start === \"number\" &&\n    typeof (value as FarmModuleAstNode).end === \"number\"\n  );\n}\n\nfunction isFarmConfigFile(file: string, root: string): boolean {\n  const normalized = file.replace(/\\\\/g, \"/\");\n  const rootSlug = root.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n  const relative = normalized.startsWith(`${rootSlug}/`)\n    ? normalized.slice(rootSlug.length + 1)\n    : normalized;\n\n  return FARM_CONFIG_FILENAMES.has(relative);\n}\n\nconst warnedClientBoundaryIds = new Set<string>();\n\n/**\n * Warn once per module about server-only access in client-compiled code:\n * module-scope non-public process.env reads (undefined in the browser, #560)\n * and node: builtin imports (silently stubbed by farm:browser-external-stub).\n * Diagnostics only; behavior is unchanged (#1065).\n */\nfunction warnClientBoundaryOnce(\n  context: { parse(code: string): unknown },\n  id: string,\n  code: string,\n  config: FarmVitePluginOptions,\n): void {\n  if (warnedClientBoundaryIds.has(id)) return;\n\n  let program: unknown;\n  try {\n    program = context.parse(code);\n  } catch {\n    // Unparseable at this stage; another transform will surface the error.\n    return;\n  }\n  const publicKeys = new Set(Object.keys((config as any).env?.public ?? {}));\n  const findings = analyzeClientBoundary(program as any, publicKeys);\n\n  if (\n    findings.envKeys.length === 0 &&\n    findings.publicEnvKeys.length === 0 &&\n    findings.builtinImports.length === 0\n  ) {\n    return;\n  }\n  warnedClientBoundaryIds.add(id);\n  logger.warn(formatClientBoundaryWarning(id, findings));\n}\n\n/**\n * Whether Farm should append its own client-root HMR handler to a\n * `\"use client\"` module.\n *\n * Re-rendering the whole root on every edit only makes sense for a renderer\n * that diffs the result against the live DOM. On Solid and Svelte `render()`\n * tears the tree down and rebuilds it, so a one character change in any client\n * component would wipe the page's state. Those renderers ship their own HMR\n * integration (solid-refresh, svelte's hot API) which preserves component\n * state, and appending an `import.meta.hot.accept` here would swallow the\n * update before theirs could run.\n */\nexport function shouldEmitFarmClientRootHmr(renderer?: FarmRenderer): boolean {\n  return getFarmRendererCapabilities(resolveFarmRenderer(renderer)).reconcilesRerenders;\n}\n\nexport function farmPlugin(\n  options: FarmVitePluginOptions = {},\n  initialPluginManager?: PluginManager,\n): Plugin {\n  const imageImports = farmImageImportsPlugin();\n  const fontImports = farmFontImportsPlugin({\n    root: options.root,\n    basePath: options.basePath,\n    publicDir: options.publicDir,\n  });\n  let farmApp: FarmApp;\n  let server: ViteDevServer;\n  let apiRouteManager: APIRouteManager;\n  let openAPIManager: OpenAPIManager | null = null;\n  let middlewareManager: MiddlewareManager;\n  let refreshRouteDiscovery: ((reason: string) => Promise<void>) | null = null;\n  let workflowHandler: ((request: Request) => Promise<Response | null>) | null = null;\n  const logUpdate = (tag: \"PAGE\" | \"API\" | \"MIDDLEWARE\" | \"TYPE\", message: string) => {\n    const pc = createCliColors();\n    const log = [\n      pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.yellow(\"UPDATE\")) + pc.dim(\"]\"),\n      pc.gray(message),\n    ].join(\" \");\n    console.log(log);\n  };\n\n  return {\n    name: \"farm\",\n\n    config(_userConfig, configEnv) {\n      const layerAliases = getFarmLayerAliases(options.layers);\n      const layerRoots = (options.layers ?? []).map((layer) => layer.root);\n      return {\n        // Honor Farm's publicDir so the dev server serves the same static\n        // directory the production client build emits.\n        ...(options.publicDir ? { publicDir: options.publicDir } : {}),\n        define: getEnvDefines(options, configEnv),\n        resolve: {\n          alias: layerAliases,\n        },\n        ...(layerRoots.length\n          ? {\n              server: {\n                fs: {\n                  allow: [path.resolve(options.root || process.cwd()), ...layerRoots],\n                },\n              },\n            }\n          : {}),\n      };\n    },\n\n    async configResolved(config) {\n      if (typeof fontImports.configResolved === \"function\") {\n        await fontImports.configResolved.call(this, config);\n      }\n      // Defer Farm application initialization until Vite server is available.\n    },\n\n    async configureServer(viteServer) {\n      if (typeof fontImports.configureServer === \"function\") {\n        await fontImports.configureServer.call(this, viteServer);\n      }\n      server = viteServer;\n\n      // Store the plugin manager passed during creation\n      const pm = initialPluginManager;\n      const emitPluginError = async (\n        phase: string,\n        error: unknown,\n        meta?: Record<string, unknown>,\n      ) => {\n        if (!pm) return;\n        try {\n          await pm.runHookParallel(\"onError\", { phase, error, meta });\n        } catch {\n          // Ignore plugin error reporter failures\n        }\n      };\n\n      farmApp = new FarmApp(\n        {\n          root: server.config.root,\n          ...options,\n        },\n        server,\n      );\n\n      const globalsCSSPath = path.join(server.config.root, \"src/app/globals.css\");\n      if (!fs.existsSync(globalsCSSPath)) {\n        const appDir = path.join(server.config.root, \"src/app\");\n        if (!fs.existsSync(appDir)) {\n          fs.mkdirSync(appDir, { recursive: true });\n        }\n        fs.writeFileSync(globalsCSSPath, defaultGlobalCSS);\n      }\n\n      await farmApp.initialize();\n\n      const farmConfig = farmApp.getConfig();\n      const apiServerBasePath = resolveFarmAPIServerBasePath(farmConfig.api);\n      const serverConfig = resolveFarmServerConfig(farmConfig.server);\n      let imageHandler: FarmImageHandler | null = null;\n      if (farmConfig.images.provider !== \"none\") {\n        const { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } =\n          await import(\"./image-sharp\");\n        imageHandler = createFarmImageHandler(farmConfig.images, {\n          transform: createSharpImageTransformer(),\n          fetchRemote: createNodeImageFetcher(farmConfig.images),\n          validateRemoteUrl: createNodeImageUrlValidator(farmConfig.images),\n          onError(error) {\n            logger.error(\n              `Image optimization failed: ${error instanceof Error ? error.message : String(error)}`,\n            );\n          },\n        });\n      }\n      const sourceRoots = getFarmSourceRoots(farmConfig);\n      server.watcher.add(sourceRoots.map((source) => path.join(source.root, source.srcDir)));\n      if (farmConfig.i18n.enabled) {\n        server.watcher.add(\n          farmConfig.i18n.locales.map((locale) =>\n            resolveFarmI18nMessagePath(farmConfig.i18n, locale),\n          ),\n        );\n      }\n      const workflowConfig = farmConfig.workflows;\n      const farmDocsDevRuntime = farmConfig.docs.enabled ? await loadFarmDocsDevRuntime() : null;\n      const getExtraRouteTypes = () => [\n        ...(options.openapi?.enabled && options.openapi.route ? [options.openapi.route] : []),\n        ...(farmDocsDevRuntime?.getFarmDocsRouteTypeEntries(farmConfig.docs) ?? []),\n      ];\n      const appDirSlugs = sourceRoots.map((source) =>\n        path.join(source.root, source.srcDir, \"app\").replace(/\\\\/g, \"/\"),\n      );\n      const generateTypeArtifacts = async (\n        reason: string,\n        selection: TypeArtifactSelection = ALL_TYPE_ARTIFACTS,\n        log = false,\n      ) => {\n        try {\n          const result = await generateFarmTypeArtifacts({\n            root: farmConfig.root,\n            srcDir: farmConfig.srcDir,\n            layers: farmConfig.layers,\n            plugins: farmConfig.plugins,\n            extraRoutes: getExtraRouteTypes(),\n            suppressLintOnLink: farmConfig.suppressLintOnLink,\n            componentExtensions: farmConfig.renderer.componentExtensions,\n            i18nConfig: farmConfig.i18n,\n            ...selection,\n          });\n          if (log) {\n            const refreshed = [\n              selection.routes !== false && \"route\",\n              selection.api !== false && \"API\",\n              selection.env !== false && \"env\",\n              selection.images !== false && \"image\",\n              selection.i18n !== false && farmConfig.i18n.enabled && \"i18n\",\n            ].filter(Boolean);\n            logUpdate(\n              \"TYPE\",\n              `${reason} - refreshed ${refreshed.join(\", \")} types${\n                selection.api !== false\n                  ? ` (${result.apiRoutes.length} API route${result.apiRoutes.length === 1 ? \"\" : \"s\"})`\n                  : \"\"\n              }`,\n            );\n          }\n          if (openAPIManager) {\n            await openAPIManager.invalidateCache();\n          }\n        } catch (e) {\n          const message = e instanceof Error ? e.message : String(e);\n          logger.warn(`Route type generation failed (farm.d.ts may be stale): ${message}`);\n          if (pm) {\n            await emitPluginError(\"type-artifact-generation\", e, { reason });\n          }\n        }\n      };\n      await generateTypeArtifacts(\"startup\");\n\n      const srcDirSlugs = sourceRoots.map((source) =>\n        path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"),\n      );\n      const layerConfigFiles = new Set(\n        farmConfig.layers\n          .map((layer) => layer.configFile?.replace(/\\\\/g, \"/\"))\n          .filter((file): file is string => Boolean(file)),\n      );\n      const isPageFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n          /page\\.(ts|tsx|js|jsx|md|mdx)$/.test(normalized)\n        );\n      };\n      const isApiRouteFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/api/`)) &&\n          /route\\.(ts|tsx|js|jsx)$/.test(normalized)\n        );\n      };\n      const isProgrammaticRouteFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          srcDirSlugs.some((srcDir) => normalized.startsWith(`${srcDir}/`)) &&\n          isProgrammaticRoutesFileName(normalized)\n        );\n      };\n      const isProgrammaticRouteSourceFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return srcDirSlugs.some((srcDir) =>\n          isPotentialProgrammaticRouteSourceFile(normalized, srcDir),\n        );\n      };\n      const isAppRuntimeFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n          /\\/(?:page|default|layout|loading|error|middleware|route)\\.(?:ts|tsx|js|jsx|md|mdx)$|\\/(?:sitemap|robots|manifest)\\.(?:ts|js)$|\\/(?:opengraph-image|twitter-image)(?:\\.(?:ts|tsx|js|jsx|png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n            normalized,\n          )\n        );\n      };\n      const isStaticMetadataImageFile = (file: string) =>\n        /\\/(?:opengraph-image|twitter-image)(?:\\.(?:png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n          file.replace(/\\\\/g, \"/\"),\n        );\n      const isI18nCatalogFile = (file: string) => isFarmI18nCatalogFile(farmConfig.i18n, file);\n      let typeArtifactGenScheduled: ReturnType<typeof setTimeout> | null = null;\n      let pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n      let pendingTypeArtifactReason = \"\";\n      let routeRefreshScheduled: ReturnType<typeof setTimeout> | null = null;\n      let pendingRouteRefreshIncludesMiddleware = false;\n      const scheduleTypeArtifactGen = (\n        file: string,\n        event: string,\n        selection: TypeArtifactSelection,\n      ) => {\n        const normalizedFile = toPosixPath(file);\n        for (const [artifact, enabled] of Object.entries(selection)) {\n          if (enabled) {\n            pendingTypeArtifacts[artifact as keyof TypeArtifactSelection] = true;\n          }\n        }\n        pendingTypeArtifactReason ||= `${event} ${normalizedFile.split(\"/app/\")[1] || normalizedFile}`;\n        if (typeArtifactGenScheduled) return;\n        typeArtifactGenScheduled = setTimeout(() => {\n          typeArtifactGenScheduled = null;\n          const artifacts = pendingTypeArtifacts;\n          const reason = pendingTypeArtifactReason;\n          pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n          pendingTypeArtifactReason = \"\";\n          generateTypeArtifacts(reason, artifacts, true).catch(() => {});\n        }, 100);\n      };\n      [\"add\", \"change\", \"unlink\"].forEach((ev) => {\n        server.watcher.on(ev as \"add\", (file: string) => {\n          const normalizedFile = file.replace(/\\\\/g, \"/\");\n          const configChanged =\n            isFarmConfigFile(file, farmConfig.root) || layerConfigFiles.has(normalizedFile);\n          const programmaticRouteChanged =\n            isProgrammaticRouteFile(file) ||\n            (isProgrammaticRouteSourceFile(file) &&\n              (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file)));\n          const typeArtifacts: TypeArtifactSelection = configChanged\n            ? ALL_TYPE_ARTIFACTS\n            : {\n                routes: (ev !== \"change\" && isPageFile(file)) || programmaticRouteChanged,\n                api: isApiRouteFile(file) || programmaticRouteChanged,\n                env: false,\n                images: false,\n                i18n: isI18nCatalogFile(file),\n              };\n          if (Object.values(typeArtifacts).some(Boolean)) {\n            scheduleTypeArtifactGen(file, ev, typeArtifacts);\n          }\n          if (isI18nCatalogFile(file)) {\n            farmApp\n              ?.getI18nRuntime()\n              .reload()\n              .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n              .catch((error) => logger.warn(`i18n catalog reload failed: ${error.message}`));\n          }\n          const isRouteRefreshEvent =\n            (ev !== \"change\" || isStaticMetadataImageFile(file)) &&\n            (isAppRuntimeFile(file) ||\n              isProgrammaticRouteFile(file) ||\n              (isProgrammaticRouteSourceFile(file) &&\n                (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file))));\n          if (isRouteRefreshEvent) {\n            if (file.includes(\"middleware.\")) {\n              pendingRouteRefreshIncludesMiddleware = true;\n            }\n            if (!routeRefreshScheduled) {\n              routeRefreshScheduled = setTimeout(() => {\n                routeRefreshScheduled = null;\n                const reloadsMiddleware = pendingRouteRefreshIncludesMiddleware;\n                pendingRouteRefreshIncludesMiddleware = false;\n                Promise.all([\n                  refreshRouteDiscovery?.(`${ev} ${file}`),\n                  reloadsMiddleware ? middlewareManager?.reload() : undefined,\n                ])\n                  .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n                  .catch((error) => logger.warn(`Route refresh failed: ${error.message}`));\n              }, 50);\n            }\n          }\n        });\n      });\n\n      // Initialize API route manager\n      const appDirs = getFarmAppDirectories(farmConfig);\n      const routeManager = farmApp.getRouteManager();\n      const discoveredRoutes: Array<{\n        kind: \"page\" | \"layout\";\n        pattern: string;\n        modulePath: string;\n      }> = [];\n      for (const [pattern, entry] of routeManager.getRoutes()) {\n        discoveredRoutes.push({\n          kind: \"page\",\n          pattern,\n          modulePath: entry.modulePath,\n        });\n      }\n      for (const [pattern, entry] of routeManager.getLayouts()) {\n        discoveredRoutes.push({\n          kind: \"layout\",\n          pattern,\n          modulePath: entry.modulePath,\n        });\n      }\n      if (pm) {\n        for (const route of discoveredRoutes) {\n          await pm.runHookParallel(\"routeDiscovered\", route);\n        }\n        await pm.runHookParallel(\"routesGenerated\", {\n          routes: discoveredRoutes,\n          pageCount: discoveredRoutes.filter((r) => r.kind === \"page\").length,\n          layoutCount: discoveredRoutes.filter((r) => r.kind === \"layout\").length,\n        });\n      }\n\n      apiRouteManager = new APIRouteManager(appDirs, server, {\n        plugins: farmConfig.plugins,\n        i18n: farmApp.getI18nRuntime(),\n        bodySizeLimit: serverConfig.bodySizeLimit,\n        basePath: apiServerBasePath,\n      });\n      await apiRouteManager.discoverRoutes();\n      let discoveredWorkflows: FarmDiscoveredWorkflow[] = [];\n      const hasWorkflowDirectory =\n        workflowConfig.enabled &&\n        workflowConfig.dirs.some((dir) =>\n          fs.existsSync(path.isAbsolute(dir) ? dir : path.join(farmConfig.root, dir)),\n        );\n      if (hasWorkflowDirectory) {\n        const { createFarmWorkflowRequestHandler, discoverFarmWorkflows } =\n          await loadFarmWorkflowsDevRuntime();\n        discoveredWorkflows = await discoverFarmWorkflows(\n          { ...farmConfig, workflows: workflowConfig },\n          {\n            loadModule: async (filePath) =>\n              server.ssrLoadModule(filePath) as Promise<Record<string, any>>,\n          },\n        );\n        if (discoveredWorkflows.length > 0) {\n          workflowHandler = createFarmWorkflowRequestHandler({\n            workflows: discoveredWorkflows,\n            config: workflowConfig,\n            loadModule: async (workflow: FarmDiscoveredWorkflow) =>\n              server.ssrLoadModule(workflow.filePath) as Promise<Record<string, any>>,\n            server: farmConfig.server,\n          });\n          logger.success(`✅ Discovered ${discoveredWorkflows.length} Farm workflow task(s)`);\n        }\n      }\n      if (pm) {\n        for (const [, apiRoute] of apiRouteManager.getRoutes()) {\n          await pm.runHookParallel(\"apiRouteDiscovered\", {\n            path: apiRoute.path,\n            filePath: apiRoute.filePath,\n            methods: apiRoute.methods,\n          });\n        }\n      }\n\n      middlewareManager = new MiddlewareManager(\n        appDirs,\n        server,\n        farmConfig.middleware,\n        farmConfig.i18n,\n        farmConfig.server,\n      );\n      await middlewareManager.discover();\n      if (pm) {\n        for (const middleware of middlewareManager.getMiddlewares()) {\n          await pm.runHookParallel(\"middlewareDiscovered\", {\n            path: middleware.path,\n            filePath: middleware.filePath,\n            handlerCount: middleware.handlers.length,\n          });\n        }\n      }\n\n      // Initialize OpenAPI manager if enabled\n      if (options.openapi?.enabled) {\n        const { OpenAPIManager } = await loadFarmOpenAPIDevRuntime();\n        openAPIManager = new OpenAPIManager(appDirs, options.openapi);\n        const spec = await openAPIManager.generateSpec();\n        reportOpenAPIDevGenerationResult(spec);\n      }\n\n      refreshRouteDiscovery = async (reason: string) => {\n        await routeManager.discoverRoutes();\n        await apiRouteManager.discoverRoutes();\n        const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n        if (manifestModule) {\n          server.moduleGraph.invalidateModule(manifestModule);\n        }\n        if (openAPIManager) {\n          await openAPIManager.invalidateCache();\n        }\n        if (process.env.FARM_VERBOSE) {\n          logger.info(`Refreshed routes: ${reason}`);\n        }\n      };\n\n      const farmDocsFontAssetList = farmDocsDevRuntime\n        ? resolveFarmDocsFontAssets(farmConfig.root)\n        : [];\n      const resolveDocsLayoutFonts = async (pathname: string) => {\n        const layouts = routeManager.matchRoute(pathname).layouts;\n        const layoutModules = await Promise.all(\n          layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n        );\n        return resolveFarmLayoutFonts(layoutModules);\n      };\n      const farmDocsHandler = farmDocsDevRuntime\n        ? farmDocsDevRuntime.hasFarmDocsRuntimeAdapter(farmConfig.docs)\n          ? await farmDocsDevRuntime.createFarmDocsAdapterHandler(farmConfig.docs, {\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              clientEntry: \"/@farm/client.js\",\n              resolveLayoutFonts: resolveDocsLayoutFonts,\n              fontStylesheetHref: \"/@farm/fonts.css\",\n              globalStylesheetHref: \"/src/app/globals.css\",\n              loadModule: async (specifier) => {\n                const resolved = await server.pluginContainer.resolveId(specifier, undefined, {\n                  ssr: true,\n                });\n                if (specifier === farmConfig.docs.adapter?.server && resolved?.id) {\n                  return import(/* @vite-ignore */ pathToFileURL(resolved.id).href);\n                }\n                return server.ssrLoadModule(resolved?.id ?? specifier);\n              },\n            })\n          : farmDocsDevRuntime.createFarmDocsHandler(farmConfig.docs, {\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              clientEntry: \"/@farm/client.js\",\n              fontAssets: toFarmDocsPublicFontAssets(farmDocsFontAssetList),\n              resolveLayoutFonts: resolveDocsLayoutFonts,\n              fontStylesheetHref: \"/@farm/fonts.css\",\n              globalStylesheetHref: \"/src/app/globals.css\",\n            })\n        : null;\n      const wrapFarmDocsResponseWithLayouts = async (\n        request: Request,\n        response: Response,\n      ): Promise<Response> => {\n        if (\n          request.method === \"HEAD\" ||\n          response.headers.has(\"x-farm-docs-adapter\") ||\n          !response.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")\n        ) {\n          return response;\n        }\n\n        const pathname = new URL(request.url).pathname;\n        const matchedRoute = routeManager.matchRoute(pathname);\n        const layoutEntries = matchedRoute.layouts.map((layout) => ({\n          ...layout,\n          metadata: getClientModuleMetadata(layout.modulePath, farmConfig.root),\n        }));\n        if (!layoutEntries.some((layout) => layout.metadata.shouldHydrate)) {\n          return response;\n        }\n\n        const source = await response.text();\n        const bodyMatch = source.match(/<body([^>]*)>([\\s\\S]*?)<\\/body>/i);\n        if (!bodyMatch) {\n          return new Response(source, {\n            status: response.status,\n            statusText: response.statusText,\n            headers: response.headers,\n          });\n        }\n\n        // The app's layouts are authored for whichever renderer it selected, so\n        // they have to be composed and rendered through that renderer's server\n        // module. The production entry already resolves this the same way\n        // (nitro/universal-build.ts, rendererServerImports); importing react\n        // and react-dom/server literally here made dev disagree with prod for\n        // every non-React app.\n        const docsRenderer = resolveFarmRenderer((farmApp?.getConfig() ?? options).renderer);\n        const [rendererRuntime, layoutModules] = await Promise.all([\n          isReactRenderer(docsRenderer)\n            ? import(\"./renderer/react/server\")\n            : server.ssrLoadModule(docsRenderer.server),\n          Promise.all(\n            layoutEntries.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n          ),\n        ]);\n        const hydrationStrategies = layoutEntries.flatMap((layout) =>\n          layout.metadata.shouldHydrate && layout.metadata.islandStrategy\n            ? [layout.metadata.islandStrategy]\n            : [],\n        );\n        const islandStrategy = hydrationStrategies.every(\n          (strategy) => strategy === hydrationStrategies[0],\n        )\n          ? (hydrationStrategies[0] ?? \"load\")\n          : \"load\";\n        const params = matchedRoute.params || {};\n        const toUrlPath = (absolutePath: string) => toViteModuleId(absolutePath, farmConfig.root);\n        const clientLayouts = Object.fromEntries(\n          layoutEntries.map((layout) => [\n            layout.pattern,\n            {\n              modulePath: toUrlPath(layout.modulePath),\n              pattern: layout.pattern,\n              shouldHydrate: layout.metadata.shouldHydrate,\n              islandStrategy: layout.metadata.islandStrategy,\n              preloads: [toUrlPath(layout.modulePath)],\n              assets: [],\n            },\n          ]),\n        );\n        const inlineValue = (value: unknown) =>\n          JSON.stringify(value).replace(/</g, \"\\\\u003c\").replace(/>/g, \"\\\\u003e\");\n        const pageModulePath = matchedRoute.route?.modulePath\n          ? toUrlPath(matchedRoute.route.modulePath)\n          : \"\";\n        const bootstrapScript = `<script>\nwindow.__FARM_PROPS__ = ${inlineValue({ params })};\nwindow.__FARM_ROUTE_SLOTS__ = [];\nwindow.__FARM_DEPLOYMENT_ID__ = ${inlineValue(farmConfig.deploymentId)};\nwindow.__FARM_PATH__ = ${inlineValue(pathname)};\nwindow.__FARM_IS_CLIENT__ = false;\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = false;\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = true;\nwindow.__FARM_SHOULD_HYDRATE__ = true;\nwindow.__FARM_ISLAND_STRATEGY__ = ${inlineValue(islandStrategy)};\nwindow.__FARM_PAGE_MODULE__ = ${inlineValue(pageModulePath)};\nwindow.__FARM_LOADING_MODULE__ = null;\nwindow.__FARM_MANIFEST__ = ${inlineValue({\n          routes: {},\n          layouts: clientLayouts,\n          slots: [],\n          clientEntry: \"/@farm/client.js\",\n          sharedAssets: [],\n        })};\n</script>`;\n\n        let wrappedElement: any = rendererRuntime.createElement(\"div\", {\n          id: \"__farm_page__\",\n          \"data-farm-client\": \"false\",\n          \"data-farm-layout-client\": \"true\",\n          \"data-farm-island\": \"page\",\n          \"data-farm-island-strategy\": islandStrategy,\n          dangerouslySetInnerHTML: { __html: bootstrapScript + bodyMatch[2] },\n        });\n        for (let index = layoutModules.length - 1; index >= 0; index--) {\n          const LayoutComponent = layoutModules[index].default;\n          if (LayoutComponent) {\n            wrappedElement = rendererRuntime.createElement(LayoutComponent, {\n              children: wrappedElement,\n              params,\n            });\n          }\n        }\n\n        const rootMarkup = await rendererRuntime.renderToString(\n          rendererRuntime.createElement(\"div\", { id: \"root\" }, wrappedElement),\n        );\n        const html = source.replace(bodyMatch[0], `<body${bodyMatch[1]}>${rootMarkup}</body>`);\n        const headers = new Headers(response.headers);\n        headers.delete(\"content-length\");\n        headers.delete(\"etag\");\n        return new Response(html, {\n          status: response.status,\n          statusText: response.statusText,\n          headers,\n        });\n      };\n      const farmDocsAPIHandler: FarmDocsAPIHandler | null =\n        farmDocsDevRuntime && !farmDocsDevRuntime.hasFarmDocsRuntimeAdapter(farmConfig.docs)\n          ? farmDocsDevRuntime.createFarmDocsAPIHandler({\n              rootDir: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              docs: farmConfig.docs,\n            })\n          : null;\n      const farmDocsFontAssets = new Map(\n        farmDocsFontAssetList.map(({ url, sourcePath }) => [url, sourcePath]),\n      );\n      const logResponse = (\n        method: string,\n        urlPath: string,\n        status: number,\n        duration: number,\n        tag: \"API\" | \"PAGE\",\n      ) => {\n        // In dev, browsers can trigger bursts of identical requests (reload/prefetch).\n        // Collapse near-identical page logs to keep terminal output readable.\n        const now = Date.now();\n        const dedupeKey = `${tag}:${method}:${urlPath}:${status}`;\n        const dedupeWindowMs = 250;\n        const last = (logResponse as any).__last as { key: string; ts: number } | undefined;\n        if (tag === \"PAGE\" && last && last.key === dedupeKey && now - last.ts < dedupeWindowMs) {\n          return;\n        }\n        (logResponse as any).__last = { key: dedupeKey, ts: now };\n\n        const pc = createCliColors();\n        let statusColor = pc.green;\n        if (status >= 500) statusColor = pc.red;\n        else if (status >= 400) statusColor = pc.yellow;\n        else if (status >= 300) statusColor = pc.cyan;\n\n        const log = [\n          pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n          pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n          pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n          pc.gray(urlPath),\n          pc.dim(\"-\"),\n          statusColor(status.toString()),\n          pc.dim(`(${duration}ms)`),\n        ].join(\" \");\n        console.log(log);\n      };\n\n      // Register middleware directly (not in return function) to ensure it runs early\n      const withAPIRequestTracing = (handler: Parameters<typeof withFarmRequestTracing>[0]) =>\n        withFarmRequestTracing(\n          handler,\n          {\n            basePath: apiServerBasePath,\n            dispatch: async (request) => {\n              // Resolve at call time so HMR never leaves a captured endpoint map.\n              const handler = apiRouteManager.getHandler();\n              return handler\n                ? handler(request)\n                : Response.json({ error: \"Not Found\" }, { status: 404 });\n            },\n          },\n          (request) => {\n            const currentConfig = farmApp?.getConfig() ?? options;\n            const currentServerConfig = resolveFarmServerConfig(currentConfig.server);\n            return resolveFarmRequestURL(request as FarmRequest, {\n              trustProxy: currentServerConfig.trustProxy,\n            });\n          },\n        );\n      server.middlewares.use(\n        withAPIRequestTracing(async (req, res, next) => {\n          const requestUrl = req.url || \"/\";\n          const requestMethod = req.method || \"GET\";\n          const currentConfig = farmApp?.getConfig() ?? options;\n          const currentServerConfig = resolveFarmServerConfig(currentConfig.server);\n          const parsedRequestUrl = resolveFarmRequestURL(req as FarmRequest, {\n            trustProxy: currentServerConfig.trustProxy,\n          });\n          const fullUrl = parsedRequestUrl.toString();\n          const requestPathname = parsedRequestUrl.pathname;\n\n          if (imageHandler && requestPathname === farmConfig.images.path) {\n            const imageResponse = await imageHandler(\n              createRequestFromNodeRequest(req, new URL(fullUrl)),\n            );\n            if (imageResponse) {\n              await sendWebResponse(res, imageResponse);\n              return;\n            }\n          }\n\n          const farmDocsFontPath = farmDocsFontAssets.get(requestPathname);\n          if (\n            (requestMethod === \"GET\" || requestMethod === \"HEAD\") &&\n            farmDocsFontPath &&\n            fs.existsSync(farmDocsFontPath)\n          ) {\n            res.statusCode = 200;\n            res.setHeader(\"Content-Type\", \"font/woff2\");\n            res.setHeader(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n            if (requestMethod === \"HEAD\") res.end();\n            else fs.createReadStream(farmDocsFontPath).pipe(res);\n            return;\n          }\n\n          if (\n            requestMethod === \"GET\" &&\n            (requestPathname === FARM_DEVTOOLS_PATH ||\n              requestPathname === `${FARM_DEVTOOLS_PATH}.json`)\n          ) {\n            if (!farmConfig.devtools.enabled) {\n              res.statusCode = 404;\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.end(\"Farm DevTools are disabled.\");\n              return;\n            }\n\n            if (\n              requestPathname === FARM_DEVTOOLS_PATH &&\n              parsedRequestUrl.searchParams.get(\"embedded\") !== \"1\"\n            ) {\n              let launchUrl = new URL(farmConfig.basePath || \"/\", parsedRequestUrl.origin);\n              const referrer = req.headers.referer;\n              if (referrer) {\n                try {\n                  const referrerUrl = new URL(referrer);\n                  if (\n                    referrerUrl.origin === parsedRequestUrl.origin &&\n                    !referrerUrl.pathname.startsWith(FARM_DEVTOOLS_PATH)\n                  ) {\n                    launchUrl = referrerUrl;\n                  }\n                } catch {\n                  // Ignore malformed referrers and return to the application root.\n                }\n              }\n              launchUrl.searchParams.set(FARM_DEVTOOLS_LAUNCH_PARAM, \"1\");\n              res.statusCode = 302;\n              res.setHeader(\n                \"Location\",\n                `${launchUrl.pathname}${launchUrl.search}${launchUrl.hash}`,\n              );\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.setHeader(\"Vary\", \"Referer\");\n              res.end();\n              return;\n            }\n\n            const { createFarmDevtoolsSnapshot } = await loadFarmDevtoolsSnapshotRuntime();\n            const snapshot = await createFarmDevtoolsSnapshot({\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              routeManager: farmApp.getRouteManager(),\n              apiRouteManager,\n              middlewareManager,\n              config: {\n                ...currentConfig,\n                openapi: options.openapi,\n              },\n              workflows: discoveredWorkflows,\n            });\n\n            res.statusCode = 200;\n            res.setHeader(\n              \"Content-Type\",\n              requestPathname.endsWith(\".json\")\n                ? \"application/json; charset=utf-8\"\n                : \"text/html; charset=utf-8\",\n            );\n            res.setHeader(\"Cache-Control\", \"no-store\");\n            if (requestPathname.endsWith(\".json\")) {\n              res.end(JSON.stringify(snapshot, null, 2));\n            } else {\n              if (!warnedDeprecatedDevtoolsDashboard) {\n                warnedDeprecatedDevtoolsDashboard = true;\n                logger.warn(\n                  \"The built-in DevTools dashboard is deprecated. Install @farm.js/devtools and add devtools() to plugins in farm.config.ts.\",\n                );\n              }\n              const { renderFarmDevtoolsHtml } = await loadFarmDevtoolsUIRuntime();\n              res.end(renderFarmDevtoolsHtml(snapshot));\n            }\n            return;\n          }\n\n          // The OpenAPI spec and reference, docs, raw markdown-source, the\n          // markdown mirror, and the Markdown 404 fallback expose page content\n          // or route-existence, so app middleware must pass before they are\n          // sent — matching the production entry, where these handlers run\n          // after the middleware runner.\n          const runAppMiddlewareForContentRoute = async (): Promise<boolean> => {\n            if (!middlewareManager?.hasMiddleware()) return false;\n            const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n            return farmApp\n              .getServerRenderer()\n              .runWithRequestContext(middlewareRequest, () => middlewareManager!.execute(req, res));\n          };\n\n          // Serve the raw OpenAPI spec as JSON at a predictable URL for agents\n          // and API tooling.\n          if (\n            openAPIManager &&\n            options.openapi?.specRoute &&\n            requestPathname === options.openapi.specRoute\n          ) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n              res.statusCode = 405;\n              res.setHeader(\"Allow\", \"GET, HEAD\");\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.end(\"Method Not Allowed\");\n              return;\n            }\n            const spec = await openAPIManager.getSpec();\n            const body = JSON.stringify(spec);\n            res.statusCode = 200;\n            res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n            res.setHeader(\"Cache-Control\", \"no-store\");\n            res.end(requestMethod === \"HEAD\" ? undefined : body);\n            return;\n          }\n\n          // Handle OpenAPI docs route\n          if (openAPIManager && requestPathname === options.openapi?.route) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            const docsHandler = openAPIManager.getDocsRouteHandler();\n            return docsHandler(req, res);\n          }\n\n          const docsHeaders = new Headers();\n          for (const [key, value] of Object.entries(req.headers)) {\n            if (value) {\n              docsHeaders.set(key, Array.isArray(value) ? value.join(\", \") : value);\n            }\n          }\n          if (farmDocsHandler) {\n            const docsRequest = new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            });\n            const docsResponse = await farmDocsHandler(docsRequest.clone());\n            if (docsResponse) {\n              if (await runAppMiddlewareForContentRoute()) return;\n              await sendWebResponse(\n                res,\n                await wrapFarmDocsResponseWithLayouts(docsRequest, docsResponse),\n              );\n              return;\n            }\n          }\n\n          const markdownSourceResponse = await createFarmMarkdownSourceResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().mdx,\n            resolveSource: async (pathname) => {\n              const match = farmApp.getRouteManager().matchRoute(pathname);\n              const sourcePath =\n                match.route?.markdownSourcePath ||\n                (match.route && isFarmMarkdownPageFile(match.route.modulePath)\n                  ? match.route.modulePath\n                  : null);\n              if (!sourcePath) {\n                return null;\n              }\n              return {\n                source: await fs.promises.readFile(sourcePath, \"utf8\"),\n                filePath: sourcePath,\n              };\n            },\n          });\n          if (markdownSourceResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownSourceResponse);\n            return;\n          }\n\n          const markdownResponse = await createMarkdownMirrorResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().md,\n            routeExists: (pathname) =>\n              Boolean(farmApp.getRouteManager().matchRoute(pathname).route),\n            renderPage: async (request) => fetch(request),\n          });\n          if (markdownResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownResponse);\n            return;\n          }\n\n          // No Markdown source or mirror matched. When the client explicitly\n          // asked for Markdown (a `.md` URL or `Accept: text/markdown`) and no\n          // page route exists, return a Markdown 404 body rather than letting a\n          // `.md` request fall through to a static-asset 404 or an HTML shell.\n          if (farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {\n            const markdownRoute = farmApp\n              .getRouteManager()\n              .matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));\n            if (!markdownRoute.route) {\n              if (await runAppMiddlewareForContentRoute()) return;\n              res.statusCode = 404;\n              res.setHeader(\"Content-Type\", FARM_MARKDOWN_CONTENT_TYPE);\n              res.setHeader(\"X-Farm-Markdown-Error\", \"404\");\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.end(\n                createFarmMarkdownErrorBody(404, requestPathname, farmConfig.basePath || \"/\"),\n              );\n              return;\n            }\n          }\n\n          const markdownPageTarget = resolveMarkdownMirrorTarget(\n            farmApp.getConfig().md,\n            requestPathname,\n            {\n              accept: \"text/markdown\",\n            },\n          );\n          if (\n            markdownPageTarget &&\n            farmApp.getRouteManager().matchRoute(markdownPageTarget.pathname).route\n          ) {\n            const vary = res.getHeader(\"Vary\");\n            const varyValues = String(vary || \"\")\n              .split(\",\")\n              .map((value) => value.trim())\n              .filter(Boolean);\n            if (!varyValues.some((value) => value.toLowerCase() === \"accept\")) {\n              res.setHeader(\"Vary\", [...varyValues, \"Accept\"].join(\", \"));\n            }\n            const alternatePath =\n              markdownPageTarget.pathname === \"/\"\n                ? \"/index.md\"\n                : `${markdownPageTarget.pathname}.md`;\n            const alternateLink = `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`;\n            const currentLink = res.getHeader(\"Link\");\n            res.setHeader(\n              \"Link\",\n              currentLink ? `${String(currentLink)}, ${alternateLink}` : alternateLink,\n            );\n          }\n\n          if (\n            workflowHandler &&\n            (requestPathname === workflowConfig.route ||\n              requestPathname.startsWith(`${workflowConfig.route}/`))\n          ) {\n            let workflowBody: Buffer | undefined;\n            try {\n              if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n                workflowBody = await readNodeRequestBody(\n                  req as any,\n                  currentServerConfig.bodySizeLimit,\n                );\n              }\n            } catch (error) {\n              const response = createFarmRequestBodyErrorResponse(error);\n              if (!response) throw error;\n              await sendWebResponse(res, response);\n              return;\n            }\n            const workflowResponse = await workflowHandler(\n              new Request(fullUrl, {\n                method: requestMethod,\n                headers: docsHeaders,\n                body: toRequestBody(workflowBody),\n              }),\n            );\n            if (workflowResponse) {\n              await sendWebResponse(res, workflowResponse);\n              return;\n            }\n          }\n\n          const configuredIntegrations = currentConfig.integrations;\n\n          const tryConfiguredIntegrationRoute = async () => {\n            const matchedRoute = matchIntegrationRoute(configuredIntegrations, {\n              pathname: requestPathname,\n              method: requestMethod,\n            });\n\n            if (!matchedRoute) {\n              return false;\n            }\n\n            const startTime = Date.now();\n\n            try {\n              if (pm) {\n                await pm.runHookParallelFiltered(\n                  \"beforeRequest\",\n                  (plugin) => {\n                    const owner = getFarmIntegrationPluginOwner(plugin);\n                    return (\n                      plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME &&\n                      (owner?.source !== \"lifecycle\" || owner.key !== matchedRoute.key)\n                    );\n                  },\n                  req,\n                  res,\n                );\n              }\n\n              if (res.writableEnded) {\n                const duration = Date.now() - startTime;\n                logResponse(requestMethod, requestUrl, res.statusCode || 200, duration, \"API\");\n                return true;\n              }\n\n              const headers = new Headers();\n              for (const [key, value] of Object.entries(req.headers)) {\n                if (value) {\n                  headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                }\n              }\n\n              let body: Buffer | undefined;\n              if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n              }\n\n              const integrationRequest = new Request(fullUrl, {\n                method: req.method,\n                headers,\n                body: toRequestBody(body),\n              });\n\n              const dispatchIntegration = async (request: Request) => {\n                const result = await dispatchIntegrationRequest(\n                  {\n                    integration: matchedRoute.integration,\n                    config: currentConfig,\n                    isDev: true,\n                    isProd: false,\n                  },\n                  request,\n                );\n                if (!result) {\n                  throw new Error(`Matched integration route did not return a response`);\n                }\n                return result;\n              };\n              const response = pm\n                ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {\n                    kind: \"integration\",\n                    route: {\n                      pathname: requestPathname,\n                      pattern: matchedRoute.route.path,\n                    },\n                  })\n                : await dispatchIntegration(integrationRequest);\n\n              if (!response) {\n                return false;\n              }\n\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, response.status, duration, \"API\");\n\n              await sendWebResponse(res, response);\n              return true;\n            } catch (error) {\n              const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n              if (bodyErrorResponse) {\n                await sendWebResponse(res, bodyErrorResponse);\n                return true;\n              }\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, 500, duration, \"API\");\n              await emitPluginError(\"integration-handler\", error, {\n                pathname: requestPathname,\n                routePath: requestUrl,\n                method: requestMethod,\n                integration: matchedRoute.key,\n              });\n              logger.error(`Integration route error: ${error}`);\n              if (!res.writableEnded) {\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n              }\n              return true;\n            }\n          };\n\n          if (await tryConfiguredIntegrationRoute()) {\n            return;\n          }\n\n          const redirectMatch = farmApp\n            .getRouteManager()\n            .matchRedirect(requestPathname, parsedRequestUrl.search);\n          if (redirectMatch) {\n            res.statusCode = redirectMatch.statusCode;\n            res.setHeader(\"Location\", redirectMatch.destination);\n            res.end(`Redirecting to ${redirectMatch.destination}`);\n            return;\n          }\n\n          // Handle API routes first\n          const matchedApiRoute = apiRouteManager.matchRoute(requestPathname);\n          const hasMatchedApiRoute = Boolean(matchedApiRoute);\n          if (hasMatchedApiRoute || isFarmAPIPathname(requestPathname, apiServerBasePath)) {\n            const startTime = Date.now();\n            const method = req.method || \"GET\";\n            const urlPath = req.url || \"/\";\n            const pathname = resolveFarmRequestURL(req as FarmRequest, {\n              trustProxy: currentServerConfig.trustProxy,\n            }).pathname;\n\n            try {\n              if (pm) {\n                if (hasMatchedApiRoute) {\n                  await pm.runHookParallelFiltered(\n                    \"beforeRequest\",\n                    (plugin) => plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,\n                    req,\n                    res,\n                  );\n                } else {\n                  await pm.runHookParallel(\"beforeRequest\", req, res);\n                }\n              }\n\n              if (res.writableEnded) {\n                const duration = Date.now() - startTime;\n                logResponse(method, urlPath, res.statusCode || 200, duration, \"API\");\n                return;\n              }\n            } catch (error) {\n              await emitPluginError(\"before-request\", error, {\n                urlPath,\n                method,\n              });\n              logger.error(`Request hook error: ${error}`);\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify({ error: \"Internal server error\" }));\n              return;\n            }\n\n            // Let this request boundary observe endpoint failures before it\n            // converts them into the development 500 response below.\n            const apiHandler = apiRouteManager.getHandler({ throwOnError: true });\n            const hasExplicitAPIRoute =\n              hasMatchedApiRoute || Boolean(apiRouteManager.matchRoute(pathname));\n            if (apiHandler && hasExplicitAPIRoute) {\n              const apiRoutePattern =\n                matchedApiRoute?.route.path ||\n                apiRouteManager.matchRoute(pathname)?.route.path ||\n                urlPath;\n              emitFarmEvent({\n                type: \"route.matched\",\n                pathname,\n                route: apiRoutePattern,\n              });\n              emitFarmEvent({\n                type: \"api.request.start\",\n                pathname,\n                route: apiRoutePattern,\n                method,\n              });\n              try {\n                // Convert Node.js request to Web Request\n                const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n                const headers = new Headers();\n                for (const [key, value] of Object.entries(req.headers)) {\n                  if (value) {\n                    headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                  }\n                }\n\n                // Get body for POST/PUT/PATCH\n                let body: Buffer | undefined;\n                if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                  body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n                }\n\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname: new URL(url).pathname,\n                  method,\n                  routePath: apiRoutePattern,\n                };\n                const invokeAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n\n                  const response = await apiHandler(handledRequest);\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const handledResponse: Response = pm\n                  ? await pm.runRuntimeRequest(request, invokeAPIHandler, {\n                      kind: \"api\",\n                      route: {\n                        pathname: apiLifecyclePayload.pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeAPIHandler(request);\n\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.request.complete\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  status: handledResponse.status,\n                  durationMs: duration,\n                });\n                logResponse(method, urlPath, handledResponse.status, duration, \"API\");\n\n                // Send response\n                await sendWebResponse(res, handledResponse);\n                return;\n              } catch (error) {\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.error\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  durationMs: duration,\n                  error,\n                });\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  logResponse(method, urlPath, bodyErrorResponse.status, duration, \"API\");\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname)) {\n              try {\n                const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n                const headers = new Headers();\n                for (const [key, value] of Object.entries(req.headers)) {\n                  if (value) {\n                    headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                  }\n                }\n\n                let body: Buffer | undefined;\n                if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                  body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n                }\n\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname,\n                  method,\n                  routePath: urlPath,\n                };\n                const invokeDocsAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n                  const response = await farmDocsAPIHandler(handledRequest);\n                  if (!response) {\n                    return new Response(null, { status: 404 });\n                  }\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const docsResponse = pm\n                  ? await pm.runRuntimeRequest(request, invokeDocsAPIHandler, {\n                      kind: \"docs\",\n                      route: {\n                        pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeDocsAPIHandler(request);\n                if (docsResponse) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, docsResponse.status, duration, \"API\");\n                  await sendWebResponse(res, docsResponse);\n                  return;\n                }\n              } catch (error) {\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"docs-api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`Docs API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 404, duration, \"API\");\n            res.statusCode = 404;\n            res.setHeader(\"Content-Type\", \"application/json\");\n            res.end(JSON.stringify({ error: \"API route not found\", pathname }));\n            return;\n          }\n\n          // Skip internal Vite requests\n          if (req.url?.startsWith(\"/@\") || req.url?.startsWith(\"/node_modules\")) {\n            return next();\n          }\n\n          // Dotted paths are usually static assets (modules, images, source\n          // maps), but dots are also valid inside route segments and in\n          // application metadata routes (/manifest.webmanifest, /sitemap.xml,\n          // /robots.txt, metadata images). Only skip the router when the\n          // request maps to a real file on disk or nothing in the app matches\n          // the pathname.\n          if (\n            shouldBypassFarmRouterForDottedPath(requestPathname, farmApp?.getRouteManager(), [\n              server.config.publicDir,\n              server.config.root,\n            ])\n          ) {\n            return next();\n          }\n\n          // Handle SPA page-data requests for client-side navigation\n          if (req.url?.startsWith(\"/__farm/page-data\")) {\n            const urlObj = parsedRequestUrl;\n            const targetPath = urlObj.searchParams.get(\"path\") || \"/\";\n\n            try {\n              const request = createRequestFromNodeRequest(\n                req,\n                urlObj,\n                createFarmNodeRequestAbortSignal(req, res),\n              );\n              const deploymentMismatch = getFarmDeploymentMismatch(\n                request,\n                farmConfig.deploymentId,\n              );\n              if (deploymentMismatch) {\n                await sendWebResponse(\n                  res,\n                  createFarmDeploymentMismatchResponse(deploymentMismatch),\n                );\n                return;\n              }\n\n              const targetRequestUrl = new URL(targetPath, request.url);\n              const targetRequest = new Request(targetRequestUrl, {\n                method: \"GET\",\n                headers: request.headers,\n                signal: request.signal,\n              });\n              await farmApp.getServerRenderer().runWithRequestContext(targetRequest, async () => {\n                const routeManager = farmApp.getRouteManager();\n                if (pm) {\n                  await pm.runHookParallel(\"beforeRouteMatch\", {\n                    pathname: targetPath,\n                    method: req.method || \"GET\",\n                  });\n                }\n                const interceptFromHeader =\n                  request.headers.get(\"x-farm-intercept-from\") || undefined;\n                const match = routeManager.matchRoute(targetRequestUrl.pathname, {\n                  interceptFrom: interceptFromHeader,\n                });\n                if (pm) {\n                  await pm.runHookParallel(\"afterRouteMatch\", {\n                    pathname: targetPath,\n                    matched: !!match?.route,\n                    routePattern: match?.route?.pattern || null,\n                    params: match?.params || {},\n                    layoutPatterns: (match?.layouts || []).map((l) => l.pattern),\n                  });\n                }\n\n                if (!match) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                const { route, params, layouts, slots } = match;\n\n                // Check if route was found\n                if (!route) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                // Load route module to get metadata\n                const routeModule = await routeManager.loadRouteModule(route.modulePath);\n                const loadingBoundary = routeManager.getMatchingLoading(targetRequestUrl.pathname);\n                const loadingModule = loadingBoundary\n                  ? await routeManager.loadRouteModule(loadingBoundary.modulePath)\n                  : null;\n\n                const navigationManifest = routeManager.generateClientManifest(server.config.root);\n                const moduleMetadata =\n                  navigationManifest.routes.find((entry) => entry.pattern === route.pattern) ??\n                  getClientModuleMetadata(route.modulePath, server.config.root);\n                const isClientComponent = moduleMetadata.isClientComponent;\n                const shouldHydrate = moduleMetadata.shouldHydrate;\n\n                // Collect metadata from layouts and page\n                let mergedMetadata: Record<string, any> = {};\n                const layoutModules = await Promise.all(\n                  layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n                );\n                const layoutHydrationMetadata = layouts.map(\n                  (layout) =>\n                    navigationManifest.layouts.find((entry) => entry.pattern === layout.pattern) ??\n                    getClientModuleMetadata(layout.modulePath, server.config.root),\n                );\n                const shouldHydrateLayout = layoutHydrationMetadata.some(\n                  (metadata) => metadata.shouldHydrate,\n                );\n                const hydrationStrategies = [\n                  ...(shouldHydrate && moduleMetadata.islandStrategy\n                    ? [moduleMetadata.islandStrategy]\n                    : []),\n                  ...layoutHydrationMetadata.flatMap((metadata) =>\n                    metadata.shouldHydrate && metadata.islandStrategy\n                      ? [metadata.islandStrategy]\n                      : [],\n                  ),\n                ];\n                const hydrationIslandStrategy = hydrationStrategies.every(\n                  (strategy) => strategy === hydrationStrategies[0],\n                )\n                  ? (hydrationStrategies[0] ?? \"load\")\n                  : \"load\";\n\n                // Build search params\n                const targetUrl = new URL(targetPath, \"http://localhost\");\n                const searchParams = searchParamsToObject(targetUrl.searchParams);\n                const routeContext = await resolveFarmRouteContext(farmApp.getConfig(), {\n                  request: targetRequest,\n                  params,\n                  search: searchParams,\n                  path: targetUrl.pathname,\n                });\n                const routeProps = await parseRouteModuleProps(routeModule as RouteModuleLike, {\n                  props: withFarmRouteContext(\n                    {\n                      params,\n                      searchParams: Promise.resolve(searchParams),\n                      path: targetUrl.pathname,\n                    },\n                    routeContext,\n                  ),\n                  search: searchParams,\n                  routePath: route.pattern,\n                });\n\n                // Collect metadata exactly the way a full-page load does:\n                // static and generated interleaved per layer, deep-merged with\n                // mergeMetadata so a page's openGraph extends a layout's\n                // instead of replacing it. Layouts receive the params,\n                // the route receives its full resolved props.\n                for (const layoutModule of layoutModules) {\n                  mergedMetadata = mergeMetadata(mergedMetadata, (layoutModule as any).metadata);\n                  if (typeof (layoutModule as any).generateMetadata === \"function\") {\n                    mergedMetadata = mergeMetadata(\n                      mergedMetadata,\n                      await (layoutModule as any).generateMetadata({ params: routeProps.params }),\n                    );\n                  }\n                }\n                mergedMetadata = mergeMetadata(mergedMetadata, (routeModule as any).metadata);\n                if (typeof (routeModule as any).generateMetadata === \"function\") {\n                  mergedMetadata = mergeMetadata(\n                    mergedMetadata,\n                    await (routeModule as any).generateMetadata(routeProps),\n                  );\n                }\n\n                const routeSlots = await Promise.all(\n                  slots.map(async (slot) => {\n                    const slotModule = await routeManager.loadRouteModule(slot.route.modulePath);\n                    const slotMetadata =\n                      navigationManifest.slots.find(\n                        (entry) =>\n                          entry.name === slot.name &&\n                          entry.ownerPattern === slot.ownerPattern &&\n                          entry.pattern === slot.route.pattern,\n                      ) ?? getClientModuleMetadata(slot.route.modulePath, server.config.root);\n                    const slotContext = await resolveFarmRouteContext(farmApp.getConfig(), {\n                      request: targetRequest,\n                      params: slot.params,\n                      search: searchParams,\n                      path: targetUrl.pathname,\n                    });\n                    const slotProps = await parseRouteModuleProps(slotModule as RouteModuleLike, {\n                      props: withFarmRouteContext(\n                        {\n                          params: slot.params,\n                          searchParams: Promise.resolve(searchParams),\n                          path: targetUrl.pathname,\n                        },\n                        slotContext,\n                      ),\n                      search: searchParams,\n                      routePath: slot.route.pattern,\n                    });\n\n                    return {\n                      name: slot.name,\n                      ownerPattern: slot.ownerPattern,\n                      containerId: slot.containerId,\n                      interception: slot.interception,\n                      fallback: slot.fallback,\n                      modulePath: slot.route.modulePath,\n                      renderModule: slotModule,\n                      isClientComponent: slotMetadata.isClientComponent,\n                      shouldHydrate: slotMetadata.shouldHydrate,\n                      props: {\n                        params: slotProps.params,\n                        search: (slotProps as any).search,\n                        searchParams: (slotProps as any).search,\n                        ...(\"data\" in slotProps ? { data: (slotProps as any).data } : {}),\n                        ...((slotProps as any).__farmCanonicalPath\n                          ? {\n                              __farmCanonicalPath: (slotProps as any).__farmCanonicalPath,\n                            }\n                          : {}),\n                        ...((slotProps as any).__farmRoutePropsResolved\n                          ? { __farmRoutePropsResolved: true }\n                          : {}),\n                        path: targetUrl.pathname,\n                      },\n                    };\n                  }),\n                );\n\n                // Convert absolute paths to URL paths (relative to project root)\n                const projectRoot = server.config.root;\n                const toUrlPath = (absolutePath: string) =>\n                  toViteModuleId(absolutePath, projectRoot);\n\n                const renderPlan = createFarmRouteRenderPlan({\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  islandStrategy: hydrationIslandStrategy,\n                  rendering: resolveRouteRenderingConfig(routeModule as any),\n                });\n                const destinationLayoutPatterns = layouts.map((layout) => layout.pattern);\n                const layoutStartIndex = getSharedLayoutPrefixLength(\n                  parseFarmLayoutChainHeader(request.headers.get(\"x-farm-layout-chain\")),\n                  destinationLayoutPatterns,\n                );\n                const fragmentHtml = await farmApp.getServerRenderer().renderNavigationFragment({\n                  PageComponent: (routeModule as any).default,\n                  LoadingComponent: (loadingModule as any)?.default,\n                  pageProps: routeProps as Record<string, unknown>,\n                  params,\n                  layouts: layouts.map((layout, index) => ({\n                    pattern: layout.pattern,\n                    module: layoutModules[index] as any,\n                  })),\n                  layoutStartIndex,\n                  slots: routeSlots.map((slot) => ({\n                    name: slot.name,\n                    ownerPattern: slot.ownerPattern,\n                    containerId: slot.containerId,\n                    module: slot.renderModule as any,\n                    props: slot.props,\n                  })),\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  islandStrategy: hydrationIslandStrategy,\n                });\n\n                // Return page data for SPA navigation\n                const pageData = {\n                  props: {\n                    params: routeProps.params,\n                    search: (routeProps as any).search,\n                    searchParams: (routeProps as any).search,\n                    ...(\"data\" in routeProps ? { data: (routeProps as any).data } : {}),\n                    ...((routeProps as any).__farmCanonicalPath\n                      ? {\n                          __farmCanonicalPath: (routeProps as any).__farmCanonicalPath,\n                        }\n                      : {}),\n                    ...((routeProps as any).__farmRoutePropsResolved\n                      ? { __farmRoutePropsResolved: true }\n                      : {}),\n                  },\n                  canonicalPath: (routeProps as any).__farmCanonicalPath,\n                  modulePath: toUrlPath(route.modulePath),\n                  loadingModulePath: loadingBoundary ? toUrlPath(loadingBoundary.modulePath) : null,\n                  isClientComponent: routeSlots.length > 0 ? false : isClientComponent,\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  shouldHydrate:\n                    shouldHydrate ||\n                    shouldHydrateLayout ||\n                    routeSlots.some((slot) => slot.isClientComponent || slot.shouldHydrate),\n                  islandStrategy: hydrationIslandStrategy,\n                  renderPlan,\n                  fragment: {\n                    html: fragmentHtml,\n                    layoutPatterns: destinationLayoutPatterns,\n                  },\n                  // The full merged metadata, not a title/description\n                  // projection: client navigation reconciles the same head\n                  // tags a full-page load renders, so it needs the same input.\n                  metadata: mergedMetadata,\n                  layoutModules: layouts.map((l) => toUrlPath(l.modulePath)),\n                  routeSlots: routeSlots.map(({ renderModule: _renderModule, ...slot }) => ({\n                    ...slot,\n                    modulePath: toUrlPath(slot.modulePath),\n                  })),\n                  interception: routeSlots.some((slot) => slot.interception)\n                    ? {\n                        from: interceptFromHeader,\n                        slots: routeSlots\n                          .filter((slot) => slot.interception)\n                          .map((slot) => slot.name),\n                      }\n                    : undefined,\n                  i18n: getFarmI18nClientSnapshot(),\n                };\n\n                await sendWebResponse(\n                  res,\n                  createDeferredDataResponse(\n                    pageData,\n                    {\n                      status: 200,\n                      headers: {\n                        \"Cache-Control\": getFarmFragmentCacheControl(renderPlan),\n                        \"X-Farm-Navigation\": \"html-fragment\",\n                        Vary: \"X-Farm-Layout-Chain\",\n                        [FARM_DEPLOYMENT_ID_HEADER]: farmConfig.deploymentId,\n                      },\n                    },\n                    {\n                      onError(error, id) {\n                        logger.error(`Deferred route data ${id} failed: ${error}`);\n                      },\n                    },\n                  ),\n                );\n                return;\n              });\n              return;\n            } catch (error) {\n              const failure = resolveFarmPageDataFailure(error);\n              if (failure.status >= 500) {\n                await emitPluginError(\"page-data\", error, {\n                  path: targetPath,\n                });\n                console.error(\"[Farm.js] Page data error:\", error);\n              }\n              res.statusCode = failure.status;\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify(failure.payload));\n              return;\n            }\n          }\n\n          const startTime = Date.now();\n          const method = req.method || \"GET\";\n          const urlPath = req.url || \"/\";\n          const pathname = resolveFarmRequestURL(req as FarmRequest, {\n            trustProxy: currentServerConfig.trustProxy,\n          }).pathname;\n          const routeManager = farmApp.getRouteManager();\n          const hasBeforeRouteMatchHook = pm?.hasHook(\"beforeRouteMatch\") ?? false;\n          const hasAfterRouteMatchHook = pm?.hasHook(\"afterRouteMatch\") ?? false;\n          const hasBeforeRequestHook = pm?.hasHook(\"beforeRequest\") ?? false;\n          const hasBeforeRenderHook = pm?.hasHook(\"beforeRender\") ?? false;\n          const hasAfterResponseHook = pm?.hasHook(\"afterResponse\") ?? false;\n          const hasHTMLTransformHook =\n            (pm?.hasHook(\"transformHTML\") ?? false) || (pm?.hasHook(\"afterRender\") ?? false);\n          const hasRuntimeRequestHooks = pm?.hasRuntimeRequestHooks() ?? false;\n          const hasRuntimeAfterHook = pm?.hasRuntimeHook(\"after\") ?? false;\n\n          if (pm && hasBeforeRouteMatchHook) {\n            await pm.runHookParallel(\"beforeRouteMatch\", {\n              pathname,\n              method,\n            });\n          }\n          const routeMatch = routeManager.matchRoute(pathname);\n          if (pm && hasAfterRouteMatchHook) {\n            await pm.runHookParallel(\"afterRouteMatch\", {\n              pathname,\n              matched: !!routeMatch?.route,\n              routePattern: routeMatch?.route?.pattern || null,\n              params: routeMatch?.params || {},\n              layoutPatterns: (routeMatch?.layouts || []).map((l) => l.pattern),\n            });\n          }\n          const renderPayload = {\n            pathname,\n            method,\n            routePattern: routeMatch?.route?.pattern || null,\n            params: routeMatch?.params || {},\n          };\n          let runtimeSession: FarmPluginRuntimeSession | undefined;\n          if (pm && hasRuntimeRequestHooks) {\n            try {\n              runtimeSession = await pm.beginRuntimeRequest(\n                createRequestFromNodeRequest(req, new URL(fullUrl)),\n                {\n                  kind: \"page\",\n                  route: {\n                    pathname,\n                    pattern: renderPayload.routePattern,\n                    params: renderPayload.params,\n                  },\n                },\n              );\n              pm.copyRequestContext(runtimeSession.request, req);\n              applyWebRequestToNodeRequest(runtimeSession.request, req);\n\n              if (runtimeSession.response) {\n                const response = await pm.endRuntimeRequest(\n                  runtimeSession,\n                  runtimeSession.response,\n                );\n                await sendWebResponse(res, response);\n                return;\n              }\n            } catch (error) {\n              await emitPluginError(\"runtime-before\", error, { pathname });\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.end(\"Internal Server Error\");\n              return;\n            }\n          }\n\n          // Runtime response transforms need the complete byte stream, including\n          // responses completed by middleware or beforeRequest hooks.\n          const shouldInterceptResponse = Boolean(\n            pm &&\n            (hasAfterResponseHook ||\n              hasHTMLTransformHook ||\n              (runtimeSession && hasRuntimeAfterHook)),\n          );\n          const responseInterceptor =\n            pm && shouldInterceptResponse\n              ? interceptFarmDevPageResponse({\n                  req,\n                  res,\n                  pm,\n                  runtimeSession,\n                  hasRuntimeAfterHook,\n                  hasAfterResponseHook,\n                  hasHTMLTransformHook,\n                  renderPayload,\n                  method,\n                  urlPath,\n                  pathname,\n                  startTime,\n                  logResponse,\n                  emitError: (error) => emitPluginError(\"response-end\", error, { pathname }),\n                })\n              : undefined;\n\n          try {\n            if (middlewareManager?.hasMiddleware()) {\n              const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n              const handled = await farmApp\n                .getServerRenderer()\n                .runWithRequestContext(middlewareRequest, () =>\n                  middlewareManager!.execute(req, res),\n                );\n              if (handled) {\n                if (!responseInterceptor?.isEnded()) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n                }\n                return; // Middleware handled the response\n              }\n            }\n\n            // Run beforeRequest hooks\n            if (pm && hasBeforeRequestHook) {\n              const currentPathname = new URL(\n                req.url || \"/\",\n                `http://${req.headers.host || \"localhost:3000\"}`,\n              ).pathname;\n              const hasLocalPageRoute = Boolean(routeManager.matchRoute(currentPathname)?.route);\n              await pm.runHookParallelFiltered(\n                \"beforeRequest\",\n                (plugin) => !hasLocalPageRoute || plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,\n                req,\n                res,\n              );\n            }\n\n            if (res.writableEnded || responseInterceptor?.isEnded()) {\n              if (!responseInterceptor?.isEnded()) {\n                const duration = Date.now() - startTime;\n                logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n              }\n              return;\n            }\n\n            // Note: __FARM_PROPS__ is set by the renderer with actual page props (params, searchParams)\n\n            const renderer = farmApp.getServerRenderer();\n            if (pm && hasBeforeRenderHook) {\n              await pm.runHookParallel(\"beforeRender\", renderPayload);\n            }\n            await renderer.renderPage(req as any, res as any);\n            if (!shouldInterceptResponse) {\n              logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n            }\n          } catch (error) {\n            // Log error response\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 500, duration, \"PAGE\");\n            if (pm && runtimeSession) {\n              await pm.failRuntimeRequest(runtimeSession, error);\n            }\n            await emitPluginError(\"render-page\", error, { pathname });\n            next(error);\n          }\n        }),\n      );\n    },\n\n    async resolveId(id, importer, resolveOptions) {\n      if (typeof fontImports.resolveId === \"function\") {\n        const fontId = await fontImports.resolveId.call(this, id, importer, resolveOptions);\n        if (fontId) return fontId;\n      }\n\n      if (typeof imageImports.resolveId === \"function\") {\n        const imageId = await imageImports.resolveId.call(this, id, importer, resolveOptions);\n        if (imageId) return imageId;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        return id;\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        return id;\n      }\n\n      if (id === \"/@farm/server\") {\n        return id;\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      if (id === \"virtual:farm-manifest\" || id === \"/@farm/manifest\") {\n        return \"/@farm/manifest\";\n      }\n    },\n\n    async load(id) {\n      if (typeof fontImports.load === \"function\") {\n        const fontModule = await fontImports.load.call(this, id);\n        if (fontModule) return fontModule;\n      }\n\n      if (typeof imageImports.load === \"function\") {\n        const imageModule = await imageImports.load.call(this, id);\n        if (imageModule) return imageModule;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        const renderer = farmApp?.getConfig().renderer || resolveFarmRenderer(options.renderer);\n        return generateProgrammaticRouteModule(id, server?.config.root || options.root, renderer);\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        const resolvedConfig = farmApp?.getConfig();\n        const renderer = resolvedConfig?.renderer || resolveFarmRenderer(options.renderer);\n        const integrations = resolvedConfig?.integrations || options.integrations;\n        const root = resolvedConfig?.root || server?.config.root || process.cwd();\n        const docs = resolvedConfig?.docs;\n        const adapterOwnsDocsRuntime = Boolean(\n          isReactRenderer(renderer) && docs?.adapter?.server && docs.adapter.react,\n        );\n        const devtools = resolvedConfig?.devtools ?? resolveFarmDevtoolsConfig(false, \"production\");\n        const [docsRuntime, docsSearchRuntime, devtoolsClientRuntime] = await Promise.all([\n          docs?.enabled ? loadFarmDocsDevRuntime() : null,\n          docs?.enabled && !adapterOwnsDocsRuntime ? loadFarmDocsSearchDevRuntime() : null,\n          devtools.enabled ? loadFarmDevtoolsClientRuntime() : null,\n        ]);\n        const docsSearchEnabled = docsSearchRuntime?.isFarmDocsSearchEnabled(docs) ?? false;\n        const generatedDocsSearchRuntime = docsSearchRuntime\n          ? docsSearchRuntime.generateFarmDocsSearchClientRuntime(\n              docsSearchEnabled,\n              docsSearchEnabled\n                ? docsSearchRuntime.resolveFarmDocsSearchClientModule(root)\n                : undefined,\n            )\n          : EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME;\n        const generatedDevtoolsClientRuntime = devtoolsClientRuntime\n          ? devtoolsClientRuntime.generateFarmDevtoolsClientRuntime(devtools)\n          : \"\";\n        const generatedDevIndicatorsClientRuntime = farmApp\n          ? generateFarmDevIndicatorsClientRuntime(farmApp.getConfig().devIndicators)\n          : \"\";\n        const integrationProviders = isReactRenderer(renderer)\n          ? getIntegrationProviders(integrations)\n          : [];\n        const isolatedHydrationMode = resolveFarmIsolatedClientHydrationMode(\n          resolvedConfig?.experimental?.isolatedClientHydration,\n          {\n            serverComponents: resolvedConfig?.experimental?.serverComponents === true,\n            hasUnsupportedIntegrationProvider: integrationProviders\n              .filter((provider) => provider.component || provider.type === \"clerk\")\n              .some((provider) => provider.supportsIsolatedHydration !== true),\n          },\n        );\n\n        return generateClientCode(\n          integrationProviders,\n          [\n            ...getIntegrationDocumentNavigationMatchers(integrations),\n            ...(docsRuntime?.getFarmDocsDocumentNavigationMatchers(docs) ?? []),\n          ],\n          generatedDocsSearchRuntime,\n          `${generatedDevtoolsClientRuntime}\\n${generatedDevIndicatorsClientRuntime}`,\n          resolvedConfig?.plugins || [],\n          root,\n          resolvedConfig?.srcDir || options.srcDir || \"src\",\n          resolvedConfig?.publicRuntimeConfig || options.publicRuntimeConfig,\n          isReactRenderer(renderer) ? docs?.adapter?.react : undefined,\n          renderer,\n          isolatedHydrationMode === \"enabled\",\n          resolvedConfig?.trailingSlash ?? false,\n          resolvedConfig?.basePath ?? \"/\",\n          generateClientCachePersistenceCode(\n            resolveFarmClientCacheAdapterEntry(root, resolvedConfig?.cache),\n          ),\n        );\n      }\n\n      if (id === \"/@farm/server\") {\n        return generateServerCode();\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      // Manifest is generated at build time and inlined\n      if (id === \"/@farm/manifest\") {\n        const routeManager = farmApp?.getRouteManager();\n        if (!routeManager) {\n          return `\nexport const getManifest = () => ({\n  routes: {},\n  layouts: {},\n  slots: [],\n  clientEntry: \"/@farm/client.js\",\n  sharedAssets: []\n});\n`;\n        }\n\n        const manifest = routeManager.generateClientManifest(server.config.root);\n\n        // Convert to full manifest format\n        const fullManifest = {\n          clientEntry: \"/@farm/client.js\",\n          routes: {} as Record<string, any>,\n          layouts: {} as Record<string, any>,\n          slots: [] as Array<Record<string, any>>,\n          sharedAssets: [\n            {\n              tag: \"link\",\n              attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n            },\n          ],\n        };\n\n        // Convert routes array to object keyed by pattern\n        for (const route of manifest.routes) {\n          fullManifest.routes[route.pattern] = {\n            modulePath: route.modulePath,\n            pattern: route.pattern,\n            segments: route.segments,\n            search: route.search,\n            isClientComponent: route.isClientComponent,\n            shouldHydrate: route.shouldHydrate,\n            islandStrategy: route.islandStrategy,\n            renderPlan: route.renderPlan,\n            preloads: [route.modulePath], // In dev, preload is just the module\n            assets: [],\n          };\n        }\n\n        // Convert layouts array to object keyed by pattern\n        for (const layout of manifest.layouts) {\n          fullManifest.layouts[layout.pattern] = {\n            modulePath: layout.modulePath,\n            pattern: layout.pattern,\n            shouldHydrate: layout.shouldHydrate,\n            islandStrategy: layout.islandStrategy,\n            preloads: [layout.modulePath],\n            assets: [],\n          };\n        }\n\n        for (const slot of manifest.slots) {\n          fullManifest.slots.push({\n            ...slot,\n            preloads: [slot.modulePath],\n            assets: [],\n          });\n        }\n\n        return `\n// Auto-generated manifest for SPA navigation (TanStack Start pattern)\n// This manifest is inlined in the server bundle - no file on disk\n// Client receives this via window.__FARM_MANIFEST__ in HTML\nexport const getManifest = () => (${JSON.stringify(fullManifest, null, 2)});\nexport const manifest = getManifest();\n`;\n      }\n    },\n\n    async transform(code, id, transformOptions) {\n      if (!transformOptions?.ssr) {\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        if (currentConfig.experimental?.serverActions !== true) {\n          // Without the server-function transform there is no client stub for\n          // server queries: bundling the defining module into the browser\n          // executes the server handler there. Fail with an actionable\n          // boundary error instead of Vite's Node-builtin externalization\n          // failure at runtime.\n          const violation = findClientServerFnViolation(code, id);\n          if (violation) {\n            this.error(formatServerFnBoundaryError(violation, id));\n          }\n        }\n      }\n\n      if (!transformOptions?.ssr && shouldInspectClientBoundary(id, code)) {\n        warnClientBoundaryOnce(this, id, code, farmApp?.getConfig() ?? options);\n      }\n\n      if (typeof imageImports.transform === \"function\") {\n        const imageModule = await imageImports.transform.call(this, code, id, transformOptions);\n        if (imageModule) return imageModule;\n      }\n\n      let transformedCode = code;\n      let transformed = false;\n\n      if (typeof fontImports.transform === \"function\") {\n        const fontResult = await fontImports.transform.call(\n          this,\n          transformedCode,\n          id,\n          transformOptions,\n        );\n        const fontCode = typeof fontResult === \"string\" ? fontResult : fontResult?.code;\n        if (fontCode) {\n          transformedCode = fontCode;\n          transformed = true;\n        }\n      }\n\n      if (transformOptions?.ssr && server) {\n        const rewrittenImports = rewriteEarlySsrRelativeImports({\n          code: transformedCode,\n          id,\n          root: server.config.root,\n          parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n        });\n        if (rewrittenImports) {\n          transformedCode = rewrittenImports;\n          transformed = true;\n        }\n      }\n\n      if (hasUseClientDirective(transformedCode)) {\n        const clientBoundarySource = transformedCode;\n        const moduleInfo = this.getModuleInfo(id);\n        if (moduleInfo) {\n          (moduleInfo as any).isClientComponent = true;\n        }\n\n        transformedCode = stripUseClientDirective(transformedCode);\n        transformed = true;\n\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        const configuredProviders = getIntegrationProviders(currentConfig.integrations).filter(\n          (provider) => provider.component || provider.type === \"clerk\",\n        );\n        const isolatedHydrationEnabled =\n          resolveFarmIsolatedClientHydrationMode(\n            currentConfig.experimental?.isolatedClientHydration,\n            {\n              serverComponents: currentConfig.experimental?.serverComponents === true,\n              hasUnsupportedIntegrationProvider: configuredProviders.some(\n                (provider) => provider.supportsIsolatedHydration !== true,\n              ),\n            },\n          ) === \"enabled\" && isReactRenderer(resolveFarmRenderer(currentConfig.renderer));\n        let isolatedModuleReference: string | null = null;\n        const root = currentConfig.root || server?.config.root || process.cwd();\n        const cleanId = id.split(\"?\", 1)[0];\n        const selectedIsolatedModules =\n          options.isolatedClientBoundaryModules ??\n          farmApp?.getRouteManager().getIsolatedClientBoundaryModules(root);\n        const selectedForIsolatedHydration =\n          selectedIsolatedModules?.has(path.resolve(cleanId)) === true;\n        if (\n          isolatedHydrationEnabled &&\n          selectedForIsolatedHydration &&\n          isIsolatableClientBoundarySource(clientBoundarySource)\n        ) {\n          isolatedModuleReference = toViteModuleId(cleanId, root);\n          const transformedBoundary = transformIsolatedClientBoundaryModule({\n            code: transformedCode,\n            moduleReference: isolatedModuleReference,\n            islandStrategy: getIslandStrategyExport(clientBoundarySource) ?? \"load\",\n            parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n          });\n          if (!transformedBoundary) {\n            this.error(\n              `[Farm.js] Could not compile isolated client boundary ${cleanId}. ` +\n                `Use experimental.isolatedClientHydration = \"analyze\" to inspect eligibility ` +\n                `or \"off\" to retain route-wide hydration.`,\n            );\n          }\n          transformedCode = transformedBoundary;\n        }\n\n        // Store client component for later injection\n        if (!farmApp) {\n          return {\n            code: transformedCode,\n            map: null,\n          };\n        }\n\n        const clientComponents = (farmApp as any).__clientComponents__ || new Set();\n        clientComponents.add(id);\n        (farmApp as any).__clientComponents__ = clientComponents;\n\n        // Add HMR support for client components\n        // This ensures React re-renders when the component updates\n        const isolatedHmrUpdate = isolatedModuleReference\n          ? `\n    if (\n      newModule &&\n      newModule.__farm_client_boundary_originals__ &&\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__\n    ) {\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__.updateModule(\n        ${JSON.stringify(isolatedModuleReference)},\n        newModule,\n      );\n      return;\n    }`\n          : \"\";\n        // Re-rendering the whole root on every edit only makes sense for a\n        // renderer that diffs the result against the live DOM. On Solid and\n        // Svelte `render()` tears the tree down and rebuilds it, so a one\n        // character change in any client component would wipe the page's\n        // state. Those renderers ship their own HMR integration (solid-refresh\n        // and svelte's hot API) which preserves component state, so leave the\n        // module for them to accept: appending our own `import.meta.hot.accept`\n        // here would swallow the update instead of letting theirs run.\n        const hmrCode = !shouldEmitFarmClientRootHmr(currentConfig.renderer)\n          ? \"\"\n          : `\nif (import.meta.hot) {\n  import.meta.hot.accept((newModule) => {\n    ${isolatedHmrUpdate}\n    if (newModule && newModule.default && window.__FARM_REACT_ROOT__) {\n      // Re-render with the new component\n      const React = window.__FARM_REACT__;\n      const props = window.__FARM_PROPS__ || {};\n      const nextElement = React.createElement(newModule.default, props);\n      const wrapProviders = window.__FARM_WRAP_PROVIDERS__;\n      const wrapClientGraph = window.__FARM_WRAP_CLIENT_GRAPH__;\n      Promise.resolve(\n        typeof wrapProviders === 'function' ? wrapProviders(nextElement) : nextElement\n      ).then((wrappedElement) => {\n        window.__FARM_REACT_ROOT__.render(\n          typeof wrapClientGraph === 'function'\n            ? wrapClientGraph(wrappedElement)\n            : wrappedElement\n        );\n      });\n    }\n  });\n}\n`;\n        return {\n          code: transformedCode + \"\\n\" + hmrCode,\n          map: null,\n        };\n      }\n\n      return transformed ? { code: transformedCode, map: null } : null;\n    },\n\n    async generateBundle(options, bundle) {\n      if (typeof fontImports.generateBundle === \"function\") {\n        await fontImports.generateBundle.call(this, options, bundle, false);\n      }\n      const clientManifest = generateClientManifest(bundle);\n      this.emitFile({\n        type: \"asset\",\n        fileName: \"farm-client-manifest.json\",\n        source: JSON.stringify(clientManifest, null, 2),\n      });\n    },\n\n    async closeBundle() {\n      // SSG: Pre-render static pages at build time\n      if (!farmApp) return;\n\n      try {\n        const routeManager = farmApp.getRouteManager();\n        if (!routeManager) return;\n\n        const { ssg: ssgPages, ssr: ssrRoutes } = await routeManager.collectSSGPages();\n\n        if (ssgPages.length === 0) {\n          logger.info(\"No SSG pages found - all pages will use SSR\");\n          return;\n        }\n\n        logger.info(`Found ${ssgPages.length} SSG pages, ${ssrRoutes.length} SSR routes`);\n        logger.info(\"Pre-rendering SSG pages...\");\n\n        const outDir = path.join(server?.config.root || process.cwd(), options.outDir || \"dist\");\n        const clientDir = path.join(outDir, \"client\");\n\n        // Pre-render each SSG page\n        for (const page of ssgPages) {\n          try {\n            const staticRequest = new Request(new URL(page.urlPath, \"http://farm.static\"));\n            await farmApp.getServerRenderer().runWithRequestContext(staticRequest, async () => {\n              // Load the route module\n              const mod = await routeManager.loadRouteModule(page.filePath);\n              if (!mod?.default) return;\n\n              // Find matching layouts\n              const { layouts } = routeManager.matchRoute(page.urlPath);\n              const layoutModules = await Promise.all(\n                layouts.map((l) => routeManager.loadLayoutModule(l.modulePath)),\n              );\n\n              // Render the page\n              const React = await import(\"react\");\n              const { renderToString } = await import(\"react-dom/server\");\n\n              const PageComponent = mod.default;\n              const pageProps = {\n                params: page.params,\n                searchParams: Promise.resolve({}),\n                path: page.urlPath,\n              };\n\n              let pageElement = React.createElement(\n                PageComponent as React.ComponentType<unknown>,\n                pageProps as React.Attributes,\n              );\n\n              // Wrap with layouts\n              for (let i = layoutModules.length - 1; i >= 0; i--) {\n                const layoutModule = layoutModules[i];\n                const LayoutComponent = layoutModule.default;\n                pageElement = React.createElement(\n                  LayoutComponent as React.ComponentType<unknown>,\n                  {\n                    children: pageElement,\n                    params: page.params,\n                  } as React.Attributes,\n                );\n              }\n\n              const html = renderToString(pageElement);\n\n              // Generate full HTML with proper structure\n              const i18nSnapshot = getFarmI18nClientSnapshot();\n              const i18nHead = renderFarmI18nStaticHead(page.urlPath, i18nSnapshot);\n              const fullHtml = `<!DOCTYPE html>\n<html lang=\"${escapeFarmHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n                i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n              }>\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <link rel=\"icon\" href=\"data:,\">\n  <link rel=\"stylesheet\" href=\"/assets/globals.css\">\n  ${page.revalidate ? `<meta name=\"x-farm-revalidate\" content=\"${page.revalidate}\">` : \"\"}\n  ${i18nHead}\n</head>\n<body>\n  <div id=\"root\">${html}</div>\n  <script type=\"module\" src=\"/assets/client.js\"></script>\n</body>\n</html>`;\n\n              // Write to output directory\n              const outputPath =\n                page.urlPath === \"/\"\n                  ? path.join(clientDir, \"index.html\")\n                  : path.join(clientDir, page.urlPath + \".html\");\n\n              fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n              fs.writeFileSync(outputPath, fullHtml);\n\n              const revalidateInfo = page.revalidate ? ` (revalidate: ${page.revalidate}s)` : \"\";\n              logger.success(`  ✓ ${page.urlPath}${revalidateInfo}`);\n            });\n          } catch (error) {\n            logger.error(`  ✗ ${page.urlPath}: ${error}`);\n          }\n        }\n\n        // Write SSG manifest for server to know which pages are pre-rendered\n        const manifestPath = path.join(outDir, \"__ssg_manifest.json\");\n        fs.writeFileSync(\n          manifestPath,\n          JSON.stringify(\n            ssgPages.map((p) => ({\n              urlPath: p.urlPath,\n              params: p.params,\n              revalidate: p.revalidate,\n            })),\n            null,\n            2,\n          ),\n        );\n\n        logger.success(`SSG complete: ${ssgPages.length} pages pre-rendered`);\n      } catch (error) {\n        logger.error(`SSG build failed: ${error}`);\n      }\n    },\n\n    async handleHotUpdate(ctx: HmrContext) {\n      const { file, server, modules } = ctx;\n      if (initialPluginManager) {\n        try {\n          await initialPluginManager.runHookParallel(\"hmrUpdate\", {\n            file,\n            modules: modules.map((m) => m.id || m.url || \"\").filter(Boolean),\n          });\n        } catch (error) {\n          await initialPluginManager.runHookParallel(\"onError\", {\n            phase: \"hmrUpdate\",\n            error,\n            meta: { file },\n          });\n        }\n      }\n\n      const currentFarmConfig = farmApp?.getConfig();\n      const normalizedFile = file.replace(/\\\\/g, \"/\");\n      if (\n        currentFarmConfig &&\n        /\\/route\\.(?:ts|tsx|js|jsx)$/.test(normalizedFile) &&\n        getFarmAppDirectories(currentFarmConfig).some((appDir) =>\n          normalizedFile.startsWith(`${toPosixPath(appDir)}/api/`),\n        )\n      ) {\n        // Vite has not invalidated these modules yet. Refreshing only generated\n        // types leaves both HTTP and direct server calls bound to old handlers.\n        for (const mod of modules) server.moduleGraph.invalidateModule(mod);\n        await refreshRouteDiscovery?.(`updated ${file}`);\n        server.ws.send({ type: \"full-reload\", path: \"*\" });\n        return [];\n      }\n      const currentSrcRoot = currentFarmConfig\n        ? getFarmSourceRoots(currentFarmConfig)\n            .map((source) => path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"))\n            .find((sourceRoot) => normalizedFile.startsWith(`${sourceRoot}/`)) || null\n        : null;\n      if (\n        currentSrcRoot &&\n        normalizedFile.startsWith(`${currentSrcRoot}/`) &&\n        isProgrammaticRoutesFileName(normalizedFile)\n      ) {\n        logUpdate(\"PAGE\", `updated ${path.basename(file)}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        await refreshRouteDiscovery?.(`updated ${file}`);\n\n        server.ws.send({\n          type: \"full-reload\",\n          path: \"*\",\n        });\n\n        return [];\n      }\n\n      if (\n        currentSrcRoot &&\n        isPotentialProgrammaticRouteSourceFile(normalizedFile, currentSrcRoot) &&\n        fileContainsProgrammaticPageRoute(file)\n      ) {\n        const shortPath = normalizedFile.slice(currentSrcRoot.length + 1);\n        logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        await refreshRouteDiscovery?.(`updated ${file}`);\n\n        server.ws.send({\n          type: \"full-reload\",\n          path: \"*\",\n        });\n\n        return [];\n      }\n\n      const isolatedHydrationMode = currentFarmConfig?.experimental?.isolatedClientHydration;\n      if (\n        currentSrcRoot &&\n        (isolatedHydrationMode === \"enabled\" || isolatedHydrationMode === \"analyze\") &&\n        /\\.[cm]?[jt]sx?$/.test(normalizedFile)\n      ) {\n        const routeManager = farmApp?.getRouteManager();\n        if (routeManager) {\n          const previousPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          routeManager.invalidateClientManifest();\n          const nextPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          const planChanged = previousPlan !== nextPlan;\n          const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n          if (manifestModule) server.moduleGraph.invalidateModule(manifestModule);\n          if (planChanged) {\n            for (const mod of modules) server.moduleGraph.invalidateModule(mod);\n            server.ws.send({ type: \"full-reload\", path: \"*\" });\n            return [];\n          }\n        }\n      }\n\n      if (normalizedFile.includes(\"/app/\")) {\n        // Hot reload middleware changes\n        if (normalizedFile.includes(\"middleware.\")) {\n          if (middlewareManager) {\n            await middlewareManager.reload();\n            logger.success(\"✅ Middleware reloaded!\");\n            if (initialPluginManager) {\n              for (const middleware of middlewareManager.getMiddlewares()) {\n                await initialPluginManager.runHookParallel(\"middlewareDiscovered\", {\n                  path: middleware.path,\n                  filePath: middleware.filePath,\n                  handlerCount: middleware.handlers.length,\n                });\n              }\n            }\n          }\n\n          return [];\n        }\n\n        farmApp?.getRouteManager().invalidateClientManifest();\n        const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n        if (manifestModule) {\n          server.moduleGraph.invalidateModule(manifestModule);\n        }\n\n        if (normalizedFile.includes(\"page.\") || normalizedFile.includes(\"layout.\")) {\n          const shortPath = normalizedFile.split(\"/app/\")[1] || normalizedFile;\n          logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n          for (const mod of modules) {\n            server.moduleGraph.invalidateModule(mod);\n          }\n\n          server.ws.send({\n            type: \"full-reload\",\n            path: \"*\",\n          });\n\n          return [];\n        }\n      }\n\n      return modules;\n    },\n  };\n}\n\nfunction isFarmClientVirtualId(id: string): boolean {\n  const pathname = id.split(\"?\", 1)[0];\n  return pathname === \"/@farm/client\" || pathname === \"/@farm/client.js\";\n}\n\nfunction generateProgrammaticRouteModule(\n  moduleId: string,\n  root?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n): string {\n  const parsed = parseProgrammaticRouteModuleId(moduleId);\n  if (!parsed) {\n    return \"\";\n  }\n\n  const routeFile = toProgrammaticRouteImportSpecifier(parsed.filePath, root);\n\n  if (parsed.kind === \"api\") {\n    return generateProgrammaticApiRouteModule(parsed.routePath, routeFile);\n  }\n\n  return `\nimport {\n  createElement as __farmCreateElement,\n  Suspense as __farmSuspense,\n} from ${JSON.stringify(renderer.server)};\nimport {\n  createLayoutModuleFromProgrammaticLayout as __farmCreateLayoutRouteModule,\n  createRouteModuleFromProgrammaticPage as __farmCreatePageRouteModule,\n} from \"@farm.js/core/routes\";\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value &&\n  typeof value === \"object\" &&\n  (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\n\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (routePath) => {\n  const withSlash = routePath && routePath.startsWith(\"/\") ? routePath : \"/\" + (routePath || \"\");\n  const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n  return withoutTrailing || \"/\";\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route &&\n  route.kind === ${JSON.stringify(parsed.kind)} &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(parsed.routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic ${parsed.kind} route \"${parsed.routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nconst __farmRouteModule = __farmRoute.kind === \"layout\"\n  ? __farmCreateLayoutRouteModule(__farmRoute)\n  : __farmCreatePageRouteModule(__farmRoute, {\n      createElement: __farmCreateElement,\n      Suspense: __farmSuspense,\n    });\n\nexport const metadata = __farmRouteModule.metadata;\nexport const generateMetadata = __farmRouteModule.generateMetadata;\nconst __farmIsSearchSchema = (value) => value && typeof value.parse === \"function\";\nconst __farmGetSearchSchema = (search) => __farmIsSearchSchema(search) ? search : search?.schema;\nconst __farmGetSearchOptions = (search) => __farmIsSearchSchema(search) ? undefined : search;\nconst __farmSearchSchema = __farmGetSearchSchema(__farmRoute.search);\nconst __farmSearchOptions = __farmGetSearchOptions(__farmRoute.search);\nexport const __farmRouteSchemas = __farmRouteModule.__farmRouteSchemas;\nexport const __farmRouteSearch = __farmRouteModule.__farmRouteSearch;\nexport const __farmRouteData = __farmRouteModule.__farmRouteData;\nexport const __farmRouteGuard = __farmRouteModule.__farmRouteGuard;\nexport const __farmRouteParsesProps = __farmRouteModule.__farmRouteParsesProps;\nexport const __farmRouteComponents = __farmRouteModule.__farmRouteComponents;\nexport const __farmResolveRouteCanonicalPath =\n  __farmRouteModule.__farmResolveRouteCanonicalPath;\nexport const ssg = __farmRouteModule.ssg;\nexport const dynamic = __farmRouteModule.dynamic;\nexport const revalidate = __farmRouteModule.revalidate;\nexport const ppr = __farmRouteModule.ppr;\nexport const getStaticPaths = __farmRouteModule.getStaticPaths;\n\nconst __farmParseSchema = (schema, value, label) => {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error(\"Invalid \" + label + \" for route \" + JSON.stringify(__farmRoute.path) + \": \" + (error?.message || String(error)));\n  }\n};\n\nconst __farmMarkRoutePropsResolved = (props) => ({\n  ...props,\n  __farmRoutePropsResolved: true,\n});\n\nconst __farmAddCanonicalPath = (props, canonicalPath) => (\n  canonicalPath ? { ...props, __farmCanonicalPath: canonicalPath } : props\n);\n\nconst __farmStripRoutePropsMarker = (props) => {\n  if (!props || props.__farmRoutePropsResolved !== true) {\n    return props;\n  }\n\n  const {\n    __farmRoutePropsResolved,\n    __farmCanonicalPath,\n    __farmRoutePropsPromise,\n    ...componentProps\n  } = props;\n  return componentProps;\n};\n\nconst __farmCreateSearchParams = (value) => {\n  const params = new URLSearchParams();\n  for (const [key, item] of Object.entries(value || {})) {\n    if (item == null) continue;\n    const values = Array.isArray(item) ? item : [item];\n    for (const entry of values) {\n      if (entry != null) params.append(key, String(entry));\n    }\n  }\n  return params;\n};\n\nconst __farmComparable = (value) => {\n  if (Array.isArray(value)) return value.map(__farmComparable);\n  if (value && typeof value === \"object\") {\n    return Object.keys(value).sort().reduce((output, key) => {\n      output[key] = __farmComparable(value[key]);\n      return output;\n    }, {});\n  }\n  return value;\n};\n\nconst __farmEqual = (left, right) => (\n  JSON.stringify(__farmComparable(left)) === JSON.stringify(__farmComparable(right))\n);\n\nconst __farmReadSearchValue = (value, key) => (\n  value && typeof value === \"object\" ? value[key] : undefined\n);\n\nconst __farmParseDefaultSearch = () => {\n  if (!__farmSearchSchema) return undefined;\n  try {\n    const value = __farmSearchSchema.parse({});\n    return value && typeof value === \"object\" ? value : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\nconst __farmResolveCanonicalPath = (rawSearch, parsedSearch, path) => {\n  if (!__farmSearchOptions?.temporary?.length && !__farmSearchOptions?.stripDefaults) {\n    return undefined;\n  }\n\n  const params = __farmCreateSearchParams(rawSearch);\n  const original = params.toString();\n\n  for (const key of __farmSearchOptions.temporary || []) {\n    params.delete(key);\n  }\n\n  if (__farmSearchOptions.stripDefaults) {\n    const defaults = __farmParseDefaultSearch();\n    if (defaults) {\n      const keys = __farmSearchOptions.stripDefaults === true\n        ? Array.from(new Set(Array.from(params.keys())))\n        : [...__farmSearchOptions.stripDefaults];\n      for (const key of keys) {\n        if (params.has(key) && __farmEqual(__farmReadSearchValue(parsedSearch, key), __farmReadSearchValue(defaults, key))) {\n          params.delete(key);\n        }\n      }\n    }\n  }\n\n  const next = params.toString();\n  if (next === original) return undefined;\n  return next ? path + \"?\" + next : path;\n};\n\nexport async function __farmResolveRouteProps(props) {\n  return typeof __farmRouteModule.__farmResolveRouteProps === \"function\"\n    ? __farmRouteModule.__farmResolveRouteProps(props)\n    : props;\n}\n\nconst __farmNeedsPageWrapper = __farmRoute.kind === \"page\" && !!(\n  __farmRoute.params ||\n  __farmRoute.search ||\n  __farmRoute.data\n);\n\nasync function __farmProgrammaticPage(props) {\n  const deferredRouteProps = props?.__farmRoutePropsPromise;\n  const resolvedProps = props?.__farmRoutePropsResolved === true\n    ? props\n    : deferredRouteProps && typeof deferredRouteProps.then === \"function\"\n      ? await deferredRouteProps\n      : await __farmResolveRouteProps(props);\n\n  return __farmCreateElement(\n    __farmRoute.component,\n    __farmStripRoutePropsMarker(resolvedProps)\n  );\n}\n\nexport default __farmRouteModule.default;\n`;\n}\n\nfunction generateProgrammaticApiRouteModule(routePath: string, routeFile: string): string {\n  return `\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value && typeof value === \"object\" && (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (value) => {\n  const withSlash = value && value.startsWith(\"/\") ? value : \"/\" + (value || \"\");\n  return withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route?.kind === \"api\" &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic api route \"${routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nexport const GET = __farmRoute.methods.GET;\nexport const HEAD = __farmRoute.methods.HEAD;\nexport const QUERY = __farmRoute.methods.QUERY;\nexport const POST = __farmRoute.methods.POST;\nexport const PUT = __farmRoute.methods.PUT;\nexport const DELETE = __farmRoute.methods.DELETE;\nexport const PATCH = __farmRoute.methods.PATCH;\nexport const OPTIONS = __farmRoute.methods.OPTIONS;\n`.trim();\n}\n\nfunction toProgrammaticRouteImportSpecifier(filePath: string, root?: string): string {\n  return root ? toViteModuleId(filePath, root) : filePath;\n}\n\ntype RouteModuleLike = {\n  __farmRouteParsesProps?: boolean;\n  __farmResolveRouteProps?: (props: {\n    params: Record<string, string>;\n    searchParams: Promise<Record<string, string | string[] | undefined>>;\n    path: string;\n    [key: string]: unknown;\n  }) => Promise<Record<string, unknown>>;\n  __farmRouteSchemas?: {\n    params?: { parse?: (value: unknown) => unknown };\n    search?: { parse?: (value: unknown) => unknown };\n  };\n};\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModuleLike,\n  input: {\n    props: {\n      params: Record<string, string>;\n      searchParams: Promise<Record<string, string | string[] | undefined>>;\n      path: string;\n      [key: string]: unknown;\n    };\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<Record<string, unknown>> {\n  if (typeof routeModule.__farmResolveRouteProps === \"function\") {\n    return await routeModule.__farmResolveRouteProps(input.props);\n  }\n\n  if (routeModule.__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = routeModule.__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction generateClientCode(\n  integrationProviders: ReturnType<typeof getIntegrationProviders> = [],\n  documentNavigationMatchers: string[] = [],\n  docsSearchClientRuntime = EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME,\n  devtoolsClientRuntime = \"\",\n  plugins: readonly FarmPlugin[] = [],\n  root = process.cwd(),\n  srcDir = \"src\",\n  publicRuntimeConfig: Record<string, unknown> | undefined = undefined,\n  docsAdapterReact?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n  isolatedHydrationEnabled = false,\n  trailingSlash = false,\n  basePath = \"/\",\n  clientCachePersistence: ClientCachePersistenceEntryCode = { imports: \"\", init: \"\" },\n): string {\n  const providerClientCode = generateFarmIntegrationProviderClientCode(integrationProviders, root);\n  const clientPluginEntry = generateFarmClientPluginEntryCode(\n    plugins,\n    root,\n    srcDir,\n    publicRuntimeConfig,\n  );\n  const rendererClientImports = isReactRenderer(renderer)\n    ? `import React from 'react'\\nimport { hydrateRoot, createRoot } from 'react-dom/client'`\n    : `import React, { hydrateRoot, createRoot } from ${JSON.stringify(renderer.client)}`;\n  const isolatedHydrationImport = isolatedHydrationEnabled\n    ? `import { createFarmIsolatedHydrationRuntime, wrapFarmIsolatedClientGraph } from '@farm.js/core/internal/isolated-boundary'`\n    : \"\";\n  const docsAdapterImportBlock = docsAdapterReact\n    ? `import * as FarmDocsAdapterReact from ${JSON.stringify(docsAdapterReact)};\n\nasync function hydrateFarmDocsAdapterRuntime() {\n  const runtime = window.__FARM_DOCS_ADAPTER__;\n  if (!runtime) return false;\n  if (typeof FarmDocsAdapterReact.hydrateFarmDocs !== 'function') {\n    throw new Error('The configured Farm docs adapter does not export hydrateFarmDocs().');\n  }\n  FarmDocsAdapterReact.hydrateFarmDocs({\n    config: runtime.config || {},\n    data: runtime.data,\n  });\n  return true;\n}`\n    : `async function hydrateFarmDocsAdapterRuntime() { return false; }`;\n  const isolatedHydrationRuntime = isolatedHydrationEnabled\n    ? `const farmIsolatedHydrationRuntime = createFarmIsolatedHydrationRuntime({\n  ReactRuntime: React,\n  hydrateRoot,\n  load: (reference) => import(/* @vite-ignore */ reference),\n  schedule: scheduleFarmIslandHydration,\n  wrap: wrapWithIntegrationProviders,\n});\nwindow.__FARM_ISOLATED_HYDRATION_RUNTIME__ = farmIsolatedHydrationRuntime;\n\nfunction disposeFarmIsolatedClientBoundaries(scope) {\n  farmIsolatedHydrationRuntime.dispose(scope);\n}\n\nasync function hydrateFarmIsolatedClientBoundaries(scope = document, signal) {\n  await farmIsolatedHydrationRuntime.hydrate(scope, signal);\n}`\n    : \"\";\n\n  return `\n${rendererClientImports}\n${isolatedHydrationImport}\nimport { installChunkErrorRecovery, SPARouter } from '@farm.js/core/client'\nimport { createClientPluginManager } from '@farm.js/core/plugin/client'\nimport { isFarmRouteActive } from '@farm.js/core/router'\nimport { scheduleFarmIslandHydration, searchParamsToObject, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from '@farm.js/core/internal/client-runtime'\nimport { reviveDeferredData } from '@farm.js/core/deferred'\nimport {\n  createFarmDeploymentMismatchError,\n  createFarmDeploymentRequestHeaders,\n  isFarmDeploymentMismatchResponse,\n} from '@farm.js/core/deployment'\n${providerClientCode.imports}\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${docsSearchClientRuntime}\n${devtoolsClientRuntime}\n${docsAdapterImportBlock}\n\n// ⭐ Farm.js SPA Client Runtime (TanStack Start pattern)\n// Uses manifest-based chunk loading - NO HTML fetching!\n// Manifest is inlined in HTML via window.__FARM_MANIFEST__\n\n// Expose React for HMR\nwindow.__FARM_REACT__ = React;\nconst integrationDocumentNavigationMatchers = ${JSON.stringify(documentNavigationMatchers)};\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\n\nlet reactRoot = null;\n${isolatedHydrationRuntime}\n\nfunction matchesDocumentNavigation(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  return integrationDocumentNavigationMatchers.some((matcher) => {\n    if (matcher === '/(.*)' || matcher === '*') {\n      return true;\n    }\n    if (matcher.endsWith('(.*)')) {\n      const prefix = matcher.slice(0, -4);\n      return pathname === prefix || pathname.startsWith(prefix + '/');\n    }\n    return matcher === pathname;\n  });\n}\n\n${providerClientCode.runtime}\n\nwindow.__FARM_WRAP_PROVIDERS__ = wrapWithIntegrationProviders;\n${isolatedHydrationEnabled ? \"window.__FARM_WRAP_CLIENT_GRAPH__ = (element) => wrapFarmIsolatedClientGraph(React, element);\" : \"\"}\n\n// Get manifest from window (inlined by server in HTML)\n// Fallback to empty manifest if not available yet\nconst getManifest = () => window.__FARM_MANIFEST__ || { routes: {}, layouts: {}, slots: [], clientEntry: '', sharedAssets: [] };\n\n// ====== CLIENT-SIDE ROUTE MATCHING ======\n// Matches URL to route using manifest (no server request!)\n\nfunction matchSegment(urlSegment, routeSegment) {\n  if (!routeSegment.isDynamic) {\n    return urlSegment === routeSegment.segment ? {} : null;\n  }\n  if (routeSegment.isCatchAll) {\n    return { [routeSegment.segment]: urlSegment };\n  }\n  return { [routeSegment.segment]: urlSegment };\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction matchRoute(pathname, routeSegments) {\n  const normalizedPath = pathname === '/' ? '' : pathname.replace(/^\\\\//, '').replace(/\\\\/$/, '');\n  const pathSegments = normalizedPath ? normalizedPath.split('/').map(decodeRouteSegment) : [];\n  \n  // Handle catch-all routes\n  const hasCatchAll = routeSegments.some(s => s.isCatchAll);\n  \n  if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n    return null;\n  }\n  \n  const params = {};\n  \n  for (let i = 0; i < routeSegments.length; i++) {\n    const routeSeg = routeSegments[i];\n    const pathSeg = pathSegments[i];\n\n    if (routeSeg.isCatchAll) {\n      // Collect remaining segments\n      params[routeSeg.segment] = pathSegments.slice(i).join('/');\n      return params;\n    }\n    \n    if (pathSeg === undefined) {\n      if (routeSeg.isOptional) continue;\n      return null;\n    }\n    \n    const match = matchSegment(pathSeg, routeSeg);\n    if (match === null) return null;\n    Object.assign(params, match);\n  }\n  \n  return params;\n}\n\nfunction findRoute(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const routes = Object.values(manifest.routes);\n  \n  for (const route of routes) {\n    const params = matchRoute(pathname, route.segments);\n    if (params !== null) {\n      return { route, params };\n    }\n  }\n  return null;\n}\n\nfunction findLayouts(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const layouts = Object.values(manifest.layouts);\n  const matchingLayouts = [];\n  \n  for (const layout of layouts) {\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, pathname, { exact: false })) {\n      matchingLayouts.push(layout);\n    }\n  }\n  \n  return matchingLayouts.sort((a, b) => a.pattern.length - b.pattern.length);\n}\n\n// ====== SPA ROUTER ======\n// Client-side router - no server requests needed!\n\nclass LegacyManifestSPARouter {\n  constructor() {\n    this.moduleCache = new Map();\n    this.prefetchingUrls = new Set();\n    this.observers = new Map();\n    \n    if (typeof window !== 'undefined') {\n      window.addEventListener('popstate', this.handlePopState.bind(this));\n    }\n  }\n\n  setNavigationHandler(handler) {\n    this.onNavigate = handler;\n  }\n\n  async navigate(href, options = {}) {\n    const { replace = false, scroll = true } = options;\n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n    const search = url.search;\n    const fullPath = pathname + search;\n\n    if (matchesDocumentNavigation(pathname)) {\n      if (replace) {\n        window.location.replace(url.toString());\n      } else {\n        window.location.assign(url.toString());\n      }\n      return;\n    }\n\n    // Same page - update fragment history without loading route data.\n    if (pathname === window.location.pathname && search === window.location.search) {\n      if (url.hash === window.location.hash) return;\n      if (replace) {\n        window.history.replaceState(window.history.state, '', url);\n      } else {\n        window.history.pushState(window.history.state, '', url);\n      }\n      if (scroll) {\n        if (url.hash) document.querySelector(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n\n    // Save scroll position\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n\n    try {\n      // CLIENT-SIDE route matching - no server request!\n      const match = findRoute(pathname);\n      if (!match) {\n        console.warn('[Farm.js] Route not found:', pathname);\n        window.location.href = href;\n        return;\n      }\n\n      const { route, params } = match;\n\n      // Parse search params\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      // Build page data from manifest (no server request!)\n      const pageData = {\n        route: route, // Full route entry from manifest\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      // Update URL\n      if (replace) {\n        window.history.replaceState({ path: fullPath }, '', fullPath);\n      } else {\n        window.history.pushState({ path: fullPath }, '', fullPath);\n      }\n\n      // Navigate using the handler\n      if (this.onNavigate) {\n        await this.onNavigate(pageData);\n      }\n      applyCanonicalPathFromProps(currentPageProps);\n\n      // Handle scroll\n      if (scroll) {\n        if (url.hash) {\n          const element = document.querySelector(url.hash);\n          if (element) element.scrollIntoView();\n        } else {\n          window.scrollTo(0, 0);\n        }\n      }\n    } catch (error) {\n      console.error('[Farm.js] Navigation error:', error);\n      window.location.href = href; // Fallback\n    }\n  }\n\n  async prefetch(href) {\n    // Prefetching disabled in dev mode to avoid Vite dep optimization issues\n    // In production, assets are already bundled and prefetched via link tags\n    if (import.meta.env?.DEV) return;\n    \n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n\n    if (this.prefetchingUrls.has(pathname)) return;\n\n    // Find route in manifest\n    const match = findRoute(pathname);\n    if (!match) return;\n\n    // Only prefetch routes that will hydrate on the client.\n    if (!match.route.isClientComponent && !match.route.shouldHydrate) return;\n    if (match.route.islandStrategy && match.route.islandStrategy !== 'load') return;\n\n    const modulePath = match.route.modulePath;\n    if (this.moduleCache.has(modulePath)) return;\n\n    this.prefetchingUrls.add(pathname);\n    try {\n      // Prefetch by importing the module (Vite caches it)\n      const module = await import(/* @vite-ignore */ modulePath);\n      this.moduleCache.set(modulePath, module);\n      pageModuleCache.set(modulePath, module);\n    } catch (error) {\n      // Silently fail for prefetch\n    } finally {\n      this.prefetchingUrls.delete(pathname);\n    }\n  }\n\n  observeForPrefetch(element) {\n    if (typeof IntersectionObserver === 'undefined') return;\n    const href = element.getAttribute('href');\n    if (!href || this.isExternalUrl(href)) return;\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          if (entry.isIntersecting) {\n            setTimeout(() => this.prefetch(href), 100);\n            observer.unobserve(element);\n            this.observers.delete(element);\n          }\n        }\n      },\n      { rootMargin: '200px' }\n    );\n    observer.observe(element);\n    this.observers.set(element, observer);\n  }\n\n  unobserveForPrefetch(element) {\n    const observer = this.observers.get(element);\n    if (observer) {\n      observer.unobserve(element);\n      this.observers.delete(element);\n    }\n  }\n\n  async handlePopState(event) {\n    if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n    const pathname = window.location.pathname;\n    const search = window.location.search;\n    \n    try {\n      // Client-side route matching for back/forward\n      const match = findRoute(pathname);\n      if (!match) {\n        window.location.reload();\n        return;\n      }\n\n      const { route, params } = match;\n      const url = new URL(window.location.href);\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      const pageData = {\n        route: route,\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      if (this.onNavigate) await this.onNavigate(pageData);\n      this.restoreScrollPosition(pathname + search);\n    } catch (error) {\n      console.error('[Farm.js] Popstate error:', error);\n      window.location.reload();\n    }\n  }\n\n  isExternalUrl(href) {\n    return href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//');\n  }\n\n  saveScrollPosition(path) {\n    try {\n      sessionStorage.setItem('farm-scroll-' + path, JSON.stringify({ x: window.scrollX, y: window.scrollY }));\n    } catch {}\n  }\n\n  restoreScrollPosition(path) {\n    try {\n      const saved = sessionStorage.getItem('farm-scroll-' + path);\n      if (saved) {\n        const { x, y } = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(x, y), 0);\n      }\n    } catch {}\n  }\n}\n\n// Initialize the SPA router\nconst spaRouter = new SPARouter({\n  shouldUseDocumentNavigation: matchesDocumentNavigation,\n});\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: import.meta.env?.DEV === true,\n    isProd: import.meta.env?.PROD === true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nspaRouter.setClientPluginManager(farmClientRuntime);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\nif (import.meta.hot) {\n  // Vite awaits a promise returned from dispose before evaluating the new\n  // module, so the old runtime is fully closed before its successor starts.\n  // The router is destroyed afterwards — plugins may still touch navigation\n  // during close — and unconditionally, or every entry reload would leave\n  // another popstate/beforeunload listener behind.\n  import.meta.hot.dispose(async () => {\n    try {\n      await farmClientRuntime.close('hmr');\n    } finally {\n      spaRouter.destroy();\n    }\n  });\n}\n\n// Cache for loaded page modules\nconst pageModuleCache = new Map();\n\n// Current page state for React rendering\nlet currentPageComponent = null;\nlet currentPageProps = {};\nlet appRoot = null;\n\n// Layout modules are cached independently so nested client-aware layouts are\n// composed with the same root-to-leaf structure that the server rendered.\nconst layoutComponentCache = new Map();\n\n// Track if we've taken over rendering from SSR\nlet hasClientTakenOver = false;\nconst routeSlotRoots = new Map();\nconst routeSlotDefinitions = new Map();\nlet activeRouteInterception = null;\nlet pendingPageHydrationController = null;\n\nfunction cancelPendingPageHydration() {\n  pendingPageHydrationController?.abort();\n  pendingPageHydrationController = null;\n}\n\nfunction normalizeServerProps(rawProps) {\n  const props = rawProps && typeof rawProps === 'object' ? { ...rawProps } : {};\n  if (props.middleware && props.middleware.data && !(props.middleware.data instanceof Map)) {\n    props.middleware = { ...props.middleware, data: new Map(Object.entries(props.middleware.data)) };\n  }\n  if (props.context && props.context.data && !(props.context.data instanceof Map)) {\n    props.context = { ...props.context, data: new Map(Object.entries(props.context.data)) };\n  }\n  return props;\n}\n\nfunction getRouteSlotKey(slot) {\n  return slot.ownerPattern + ':' + slot.name;\n}\n\nasync function renderRouteSlot(slot, mode = 'render') {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !slot.modulePath) return false;\n  if (mode === 'intercept' && !slot.isClientComponent && !slot.shouldHydrate) {\n    return false;\n  }\n\n  let slotModule = pageModuleCache.get(slot.modulePath);\n  if (!slotModule) {\n    slotModule = await import(/* @vite-ignore */ slot.modulePath);\n    pageModuleCache.set(slot.modulePath, slotModule);\n  }\n  const SlotComponent = slotModule?.default;\n  if (!SlotComponent) return false;\n\n  const props = reviveDeferredData(\n    normalizeServerProps(slot.props || {}),\n    window.__FARM_DEFERRED_DATA__ || {},\n  );\n  let element = wrapWithIntegrationProviders(React.createElement(SlotComponent, props));\n  ${isolatedHydrationEnabled ? \"element = wrapFarmIsolatedClientGraph(React, element);\" : \"\"}\n  const key = getRouteSlotKey(slot);\n  const existingRoot = routeSlotRoots.get(key);\n\n  if (mode === 'hydrate') {\n    if (existingRoot) return true;\n    const root = hydrateRoot(container, element);\n    routeSlotRoots.set(key, root);\n  } else {\n    if (existingRoot) {\n      try { existingRoot.unmount(); } catch (error) {}\n    }\n    const root = createRoot(container);\n    root.render(element);\n    routeSlotRoots.set(key, root);\n  }\n\n  routeSlotDefinitions.set(key, slot);\n  return true;\n}\n\nasync function hydrateInitialRouteSlots() {\n  const slots = Array.isArray(window.__FARM_ROUTE_SLOTS__)\n    ? window.__FARM_ROUTE_SLOTS__\n    : [];\n  let hydrated = false;\n\n  for (const slot of slots) {\n    routeSlotDefinitions.set(getRouteSlotKey(slot), slot);\n    if (!slot.isClientComponent && !slot.shouldHydrate) continue;\n    try {\n      const slotHydrated = await renderRouteSlot(slot, 'hydrate');\n      hydrated = slotHydrated || hydrated;\n      if (slotHydrated) {\n        replayPreHydrationClicks(document.getElementById(slot.containerId));\n      }\n    } catch (error) {\n      console.warn('[Farm.js] Could not hydrate route slot:', slot.name, error);\n    }\n  }\n\n  return hydrated;\n}\n\nasync function renderRouteInterception(pageData) {\n  const slots = Array.isArray(pageData.routeSlots)\n    ? pageData.routeSlots.filter((slot) => slot.interception)\n    : [];\n  if (!pageData.interception || slots.length === 0) return false;\n\n  const previous = new Map();\n  for (const slot of slots) {\n    const key = getRouteSlotKey(slot);\n    previous.set(key, routeSlotDefinitions.get(key) || null);\n    if (!(await renderRouteSlot(slot, 'intercept'))) {\n      return false;\n    }\n  }\n\n  activeRouteInterception = {\n    from: pageData.interception.from,\n    slots,\n    previous,\n  };\n  return true;\n}\n\nasync function clearRouteInterception(destination) {\n  if (!activeRouteInterception) return false;\n  const active = activeRouteInterception;\n  activeRouteInterception = null;\n\n  for (const slot of active.slots) {\n    const key = getRouteSlotKey(slot);\n    const root = routeSlotRoots.get(key);\n    if (root) {\n      try { root.unmount(); } catch (error) {}\n      routeSlotRoots.delete(key);\n    }\n\n    const previous = active.previous.get(key);\n    if (previous && (previous.isClientComponent || previous.shouldHydrate)) {\n      await renderRouteSlot(previous, 'render');\n    } else {\n      const container = document.getElementById(slot.containerId);\n      if (container) container.replaceChildren();\n      if (previous) routeSlotDefinitions.set(key, previous);\n      else routeSlotDefinitions.delete(key);\n    }\n  }\n\n  if (!active.from) return false;\n  const background = new URL(active.from, window.location.origin);\n  return destination === background.pathname + background.search;\n}\n\nfunction applyCanonicalPathFromProps(props) {\n  const canonicalPath = props && typeof props.__farmCanonicalPath === 'string'\n    ? props.__farmCanonicalPath\n    : null;\n  if (!canonicalPath) return;\n  const currentPath = window.location.pathname + window.location.search;\n  if (canonicalPath === currentPath) return;\n  window.history.replaceState({ ...(window.history.state || {}), path: canonicalPath }, '', canonicalPath);\n}\n\nfunction replayPreHydrationClicks(container = null) {\n  if (!container) {\n    markFarmHydrated();\n  } else {\n    container.dataset.farmIslandHydrated = 'true';\n  }\n\n  const queue = Array.isArray(window.__FARM_PREHYDRATION_CLICK_QUEUE__)\n    ? window.__FARM_PREHYDRATION_CLICK_QUEUE__\n    : [];\n  if (queue.length === 0) return;\n\n  const queuedClicks = [];\n  const remainingClicks = [];\n  for (const queuedClick of queue) {\n    const target = queuedClick?.target;\n    if (!container || (target instanceof Node && container.contains(target))) {\n      queuedClicks.push(queuedClick);\n    } else {\n      remainingClicks.push(queuedClick);\n    }\n  }\n  queue.splice(0, queue.length, ...remainingClicks);\n  for (const queuedClick of queuedClicks) {\n    const target = queuedClick?.target;\n    if (!target || typeof target.click !== 'function') continue;\n    if (target.isConnected === false) continue;\n    setTimeout(() => target.click(), 0);\n  }\n}\n\nfunction markFarmHydrated() {\n  window.__FARM_HYDRATED__ = true;\n  document.documentElement.dataset.farmHydrated = 'true';\n}\n\nasync function buildClientHydrationElement(\n  PageComponent,\n  pageProps,\n  loadingModuleOverride,\n) {\n  let element = React.createElement(PageComponent, pageProps);\n  const loadingModulePath = loadingModuleOverride === undefined\n    ? window.__FARM_LOADING_MODULE__\n    : loadingModuleOverride;\n\n  if (loadingModulePath) {\n    try {\n      const loadingModule = await import(/* @vite-ignore */ loadingModulePath);\n      const LoadingComponent = loadingModule?.default;\n      if (LoadingComponent) {\n        const loadingFallback = React.createElement(LoadingComponent, {\n          params: pageProps?.params || {},\n          path: pageProps?.path || window.location.pathname,\n        });\n        element = React.createElement(React.Suspense, { fallback: loadingFallback }, element);\n      }\n    } catch (error) {\n      console.error(\n        '[Farm.js] Loading boundary failed to load and was skipped: ' + loadingModulePath,\n        error,\n      );\n    }\n  }\n\n  return element;\n}\n\nasync function loadLayoutComponents(layouts = []) {\n  const loadedLayouts = [];\n\n  for (const layout of layouts) {\n    if (!layout?.modulePath) continue;\n    try {\n      let LayoutComponent = layoutComponentCache.get(layout.modulePath);\n      if (!LayoutComponent) {\n        const layoutModule = await import(/* @vite-ignore */ layout.modulePath);\n        LayoutComponent = layoutModule.default;\n        if (LayoutComponent) {\n          layoutComponentCache.set(layout.modulePath, LayoutComponent);\n        }\n      }\n      if (LayoutComponent) loadedLayouts.push({ ...layout, Component: LayoutComponent });\n    } catch (error) {\n      // Skipping the layout leaves the client tree different from the server's,\n      // so React discards the server rendered markup for this branch, including\n      // whatever the layout drew. Losing visible UI deserves more than a warning.\n      console.error(\n        '[Farm.js] Layout failed to load and was skipped: ' + layout.modulePath +\n          '. The client tree no longer matches the server, so React will discard the ' +\n          'server rendered markup for this route, including anything this layout renders.',\n        error,\n      );\n    }\n  }\n\n  return loadedLayouts;\n}\n\nfunction wrapWithLoadedLayouts(element, loadedLayouts, params) {\n  let wrapped = element;\n  for (let index = loadedLayouts.length - 1; index >= 0; index--) {\n    const layout = loadedLayouts[index];\n    wrapped = React.createElement(layout.Component, {\n      children: wrapped,\n      params,\n    });\n    wrapped = React.createElement('div', {\n      'data-farm-layout-boundary': 'true',\n      'data-farm-layout-pattern': layout.pattern,\n      style: { display: 'contents' },\n    }, wrapped);\n  }\n  return wrapped;\n}\n\nfunction getCurrentSearchParams() {\n  const url = new URL(window.location.href);\n  return searchParamsToObject(url.searchParams);\n}\n\nfunction parseClientRouteSchema(schema, value, label) {\n  if (!schema || typeof schema.parse !== 'function') {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error('Invalid route ' + label + ': ' + (error?.message || String(error)));\n  }\n}\n\nasync function buildRouteComponentProps(pageModule, params, searchParams, path, existingProps) {\n  if (existingProps?.__farmRoutePropsResolved === true) {\n    const revivedProps = reviveDeferredData(\n      existingProps,\n      window.__FARM_DEFERRED_DATA__ || {},\n    );\n    window.__FARM_PROPS__ = revivedProps;\n    return {\n      ...revivedProps,\n      searchParams: Promise.resolve(revivedProps.search ?? revivedProps.searchParams ?? {}),\n      path: revivedProps.path || path,\n    };\n  }\n\n  if (typeof pageModule?.__farmResolveRouteProps === 'function') {\n    const rawProps = {\n      ...(existingProps || {}),\n      params,\n      searchParams: Promise.resolve(searchParams),\n      path,\n    };\n    // Keep top-level route errors inside the router's navigation transaction.\n    // Explicit defer() values can still suspend nested UI after this resolves.\n    return await pageModule.__farmResolveRouteProps(rawProps);\n  }\n\n  const schemas = pageModule?.__farmRouteSchemas;\n  const parsedParams = parseClientRouteSchema(schemas?.params, params, 'params');\n  const parsedSearch = parseClientRouteSchema(schemas?.search, searchParams, 'search');\n\n  return {\n    ...(existingProps || {}),\n    params: parsedParams,\n    search: parsedSearch,\n    searchParams: schemas ? Promise.resolve(parsedSearch) : parsedSearch,\n    path,\n  };\n}\n\nasync function buildWrappedHydrationElement(PageComponent, pageProps, layouts = []) {\n  const loadedLayouts = await loadLayoutComponents(layouts);\n  const pageElement = await buildClientHydrationElement(PageComponent, pageProps);\n  const wrappedTree = wrapWithLoadedLayouts(\n    pageElement,\n    loadedLayouts,\n    pageProps?.params || {},\n  );\n  return wrapWithIntegrationProviders(wrappedTree);\n}\n\nfunction createLayoutPageBoundary(\n  pageShouldHydrate,\n  islandStrategy,\n  pageElement,\n  serverHtml,\n) {\n  const props = {\n    id: '__farm_page__',\n    'data-farm-client': pageShouldHydrate ? 'true' : 'false',\n    'data-farm-layout-client': 'true',\n    'data-farm-island': 'page',\n    'data-farm-island-strategy': islandStrategy || 'load',\n  };\n  if (typeof serverHtml === 'string') {\n    props.suppressHydrationWarning = true;\n    props.dangerouslySetInnerHTML = { __html: serverHtml };\n    return React.createElement('div', props);\n  }\n  return React.createElement('div', props, pageElement);\n}\n\nasync function tryHydrateImportedPage(\n  container,\n  route,\n  params,\n  layouts,\n  useHydrate = false,\n  existingProps = null,\n  signal = null,\n  hydrationOptions = {},\n) {\n  const modulePath = route?.modulePath;\n  if (!modulePath || signal?.aborted) {\n    return false;\n  }\n\n  const pageShouldHydrate = hydrationOptions.pageShouldHydrate !== false;\n  const layoutShouldHydrate = hydrationOptions.layoutShouldHydrate === true;\n  const islandStrategy = hydrationOptions.islandStrategy || route.islandStrategy || 'load';\n  let pageElement = null;\n\n  if (pageShouldHydrate) {\n    let pageModule = pageModuleCache.get(modulePath);\n    if (!pageModule) {\n      pageModule = await import(/* @vite-ignore */ modulePath);\n      pageModuleCache.set(modulePath, pageModule);\n    }\n    if (signal?.aborted || !container?.isConnected) return false;\n\n    const PageComponent = pageModule?.default;\n    if (!PageComponent) return false;\n\n    if (\n      typeof PageComponent === 'function' &&\n      PageComponent.constructor &&\n      PageComponent.constructor.name === 'AsyncFunction'\n    ) {\n      console.warn(\n        '[Farm.js] Skipping hydration for ' + modulePath +\n        ': async server components cannot run in the browser. ' +\n        'Server-rendered HTML is preserved; move interactive UI into a \"use client\" child of a synchronous page.'\n      );\n      return false;\n    }\n\n    currentPageComponent = PageComponent;\n    currentPageProps = await buildRouteComponentProps(\n      pageModule,\n      params,\n      getCurrentSearchParams(),\n      window.location.pathname,\n      existingProps,\n    );\n    pageElement = await buildClientHydrationElement(\n      PageComponent,\n      currentPageProps,\n      hydrationOptions.loadingModulePath,\n    );\n  } else if (layoutShouldHydrate) {\n    currentPageProps = existingProps || { params };\n    const serverPage = document.getElementById('__farm_page__');\n    pageElement = createLayoutPageBoundary(\n      false,\n      islandStrategy,\n      null,\n      typeof hydrationOptions.serverHtml === 'string'\n        ? hydrationOptions.serverHtml\n        : serverPage ? serverPage.innerHTML : '',\n    );\n  }\n  if (signal?.aborted || !container?.isConnected || !pageElement) return false;\n\n  let wrappedElement;\n  if (layoutShouldHydrate) {\n    const loadedLayouts = await loadLayoutComponents(layouts);\n    if (pageShouldHydrate) {\n      pageElement = createLayoutPageBoundary(true, islandStrategy, pageElement);\n    }\n    const wrappedTree = wrapWithLoadedLayouts(pageElement, loadedLayouts, params);\n    wrappedElement = wrapWithIntegrationProviders(wrappedTree);\n  } else if (useHydrate && container?.id === '__farm_page__') {\n    wrappedElement = wrapWithIntegrationProviders(pageElement);\n  } else {\n    wrappedElement = await buildWrappedHydrationElement(\n      currentPageComponent,\n      currentPageProps,\n      layouts,\n    );\n  }\n  if (signal?.aborted || !container?.isConnected) return false;\n\n  ${isolatedHydrationEnabled ? \"wrappedElement = wrapFarmIsolatedClientGraph(React, wrappedElement);\" : \"\"}\n\n  if (useHydrate) {\n    try {\n      reactRoot = hydrateRoot(container, wrappedElement);\n      window.__FARM_REACT_ROOT__ = reactRoot;\n      return true;\n    } catch (error) {\n      appRoot = createRoot(container);\n      appRoot.render(wrappedElement);\n      window.__FARM_REACT_ROOT__ = appRoot;\n      hasClientTakenOver = true;\n      return true;\n    }\n  }\n\n  hasClientTakenOver = true;\n  const existingRoot = appRoot || reactRoot;\n  if (existingRoot && layoutShouldHydrate) {\n    existingRoot.render(wrappedElement);\n    appRoot = existingRoot;\n    reactRoot = null;\n    window.__FARM_REACT_ROOT__ = appRoot;\n    return true;\n  }\n  if (reactRoot) { try { reactRoot.unmount(); } catch (e) {} reactRoot = null; }\n  if (appRoot) { try { appRoot.unmount(); } catch (e) {} appRoot = null; }\n  appRoot = createRoot(container);\n  window.__FARM_REACT_ROOT__ = appRoot;\n  appRoot.render(wrappedElement);\n  return true;\n}\n\nfunction findLayoutBoundary(root, pattern) {\n  const boundaries = root.querySelectorAll\n    ? root.querySelectorAll('[data-farm-layout-boundary=\"true\"]')\n    : [];\n  for (const boundary of boundaries) {\n    if (boundary.getAttribute('data-farm-layout-pattern') === pattern) return boundary;\n  }\n  return null;\n}\n\nfunction readActiveLayoutPatterns() {\n  return Array.from(document.querySelectorAll('[data-farm-layout-boundary=\"true\"]'))\n    .map((element) => element.getAttribute('data-farm-layout-pattern'))\n    .filter(Boolean);\n}\n\nfunction activateFragmentScripts(root) {\n  for (const script of Array.from(root.querySelectorAll?.('script') || [])) {\n    const freshScript = document.createElement('script');\n    for (const attribute of Array.from(script.attributes)) {\n      freshScript.setAttribute(attribute.name, attribute.value);\n    }\n    freshScript.textContent = script.textContent || '';\n    script.replaceWith(freshScript);\n  }\n}\n\nfunction parseNavigationFragment(html) {\n  const template = document.createElement('template');\n  template.innerHTML = html;\n  return template.content;\n}\n\nfunction replaceNavigationBoundary(container, fragment, currentPatterns, nextPatterns) {\n  let sharedCount = 0;\n  while (\n    sharedCount < currentPatterns.length &&\n    sharedCount < nextPatterns.length &&\n    currentPatterns[sharedCount] === nextPatterns[sharedCount]\n  ) {\n    sharedCount++;\n  }\n\n  const fragmentTreeRoot = nextPatterns.length > 0\n    ? findLayoutBoundary(fragment, nextPatterns[0])\n    : fragment.querySelector('#__farm_page__');\n  const currentTarget = sharedCount < currentPatterns.length\n    ? findLayoutBoundary(container, currentPatterns[sharedCount])\n    : container.querySelector('#__farm_page__');\n  const nextTarget = sharedCount < nextPatterns.length\n    ? findLayoutBoundary(fragment, nextPatterns[sharedCount])\n    : fragment.querySelector('#__farm_page__');\n\n  if (!currentTarget || !nextTarget) {\n    ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n    container.replaceChildren(fragment);\n    activateFragmentScripts(container);\n    return container;\n  }\n\n  ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentTarget);\" : \"\"}\n  currentTarget.replaceWith(nextTarget);\n  activateFragmentScripts(nextTarget);\n  if (fragmentTreeRoot && fragmentTreeRoot !== nextTarget) fragmentTreeRoot.remove();\n\n  // React's completed streaming markup can include reveal instructions next\n  // to the route tree. Execute those support nodes after the boundary exists.\n  if (fragment.childNodes.length > 0) {\n    const support = document.createElement('div');\n    support.hidden = true;\n    support.dataset.farmFragmentSupport = 'true';\n    support.append(fragment);\n    document.body.appendChild(support);\n    activateFragmentScripts(support);\n    setTimeout(() => support.remove(), 0);\n  }\n  return nextTarget;\n}\n\nlet activeLayoutPatterns = readActiveLayoutPatterns();\nlet activeLayoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n\n// ====== MANIFEST-DRIVEN HTML-FRAGMENT NAVIGATION ======\n// One page-data response carries both server HTML and the hydration plan.\nasync function renderPage(pageData) {\n  const container = document.getElementById('root');\n  if (!container) return;\n  cancelPendingPageHydration();\n  const destination = window.location.pathname + window.location.search;\n\n  if (pageData.interception) {\n    if (await renderRouteInterception(pageData)) return;\n    window.location.assign(destination);\n    return;\n  }\n\n  if (await clearRouteInterception(destination)) {\n    return;\n  }\n\n  const manifestRoute = findRoute(window.location.pathname)?.route;\n  const renderPlan = pageData.renderPlan || manifestRoute?.renderPlan;\n  const hydrationMode = renderPlan?.hydration;\n  const route = {\n    modulePath: pageData.modulePath,\n    isClientComponent: pageData.isClientComponent === true,\n    pageShouldHydrate:\n      hydrationMode === 'route-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.pageShouldHydrate === true,\n    layoutShouldHydrate:\n      hydrationMode === 'layout-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.layoutShouldHydrate === true,\n    shouldHydrate: pageData.shouldHydrate === true,\n    islandStrategy: renderPlan?.islandStrategy || pageData.islandStrategy || 'load',\n    loadingModulePath: pageData.loadingModulePath,\n  };\n  const params = pageData.props?.params || {};\n  const nextLayoutPatterns = Array.isArray(pageData.fragment?.layoutPatterns)\n    ? pageData.fragment.layoutPatterns\n    : [];\n  const layouts = (pageData.layoutModules || []).map((modulePath, index) => ({\n    modulePath,\n    pattern: nextLayoutPatterns[index] || (index === 0 ? '/' : modulePath),\n  }));\n  const path = window.location.pathname + window.location.search;\n\n  // A legacy server may omit the fragment. Keep one compatibility fallback,\n  // but current servers send HTML in the page-data response and avoid this\n  // second network round trip.\n  const fetchAndSwapHTML = async () => {\n    let fragmentHtml = pageData.fragment?.html;\n    let layoutPatterns = nextLayoutPatterns;\n\n    if (typeof fragmentHtml !== 'string') {\n      const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n      const response = await fetch(path, {\n        headers: createFarmDeploymentRequestHeaders(deploymentId, { 'Accept': 'text/html' }),\n      });\n      if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n        const error = createFarmDeploymentMismatchError(response, deploymentId || 'unknown');\n        window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));\n        window.location.assign(path);\n        return false;\n      }\n      const documentHtml = await response.text();\n      const doc = new DOMParser().parseFromString(documentHtml, 'text/html');\n      const nextRoot = doc.getElementById('root');\n      if (!nextRoot) return false;\n      fragmentHtml = nextRoot.innerHTML;\n      layoutPatterns = Array.from(\n        nextRoot.querySelectorAll('[data-farm-layout-boundary=\"true\"]'),\n      ).map((element) => element.getAttribute('data-farm-layout-pattern')).filter(Boolean);\n    }\n\n    const fragment = parseNavigationFragment(fragmentHtml);\n    const nextPage = fragment.querySelector('#__farm_page__');\n    const pageShouldHydrate = route.pageShouldHydrate || route.isClientComponent;\n    const layoutShouldHydrate = route.layoutShouldHydrate;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries = Boolean(\n      fragment.querySelector('farm-client-boundary[data-farm-client-boundary]'),\n    );\n    const shouldHydrate =\n      pageShouldHydrate || layoutShouldHydrate || (route.shouldHydrate && !hasIsolatedClientBoundaries);`\n        : \"const shouldHydrate = route.shouldHydrate || pageShouldHydrate || layoutShouldHydrate;\"\n    }\n\n    // A React-owned layout can update in place. Rendering the same layout\n    // component chain preserves its state while changing only the route child.\n    if (activeLayoutShouldHydrate && layoutShouldHydrate && (appRoot || reactRoot)) {\n      await tryHydrateImportedPage(\n        container,\n        route,\n        params,\n        layouts,\n        false,\n        pageData.props,\n        null,\n        {\n          pageShouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: route.islandStrategy,\n          serverHtml: nextPage ? nextPage.innerHTML : '',\n          loadingModulePath: route.loadingModulePath,\n        },\n      );\n    } else {\n      ${isolatedHydrationEnabled ? \"let isolatedHydrationScope = container;\" : \"\"}\n      if (activeLayoutShouldHydrate) {\n        ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        container.replaceChildren(fragment);\n        activateFragmentScripts(container);\n      } else {\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        delete window.__FARM_REACT_ROOT__;\n        ${\n          isolatedHydrationEnabled\n            ? \"isolatedHydrationScope = replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns) || container;\"\n            : \"replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns);\"\n        }\n      }\n\n      const hydrationController = new AbortController();\n      if (\n        shouldHydrate${\n          isolatedHydrationEnabled\n            ? \" || (hasIsolatedClientBoundaries && !layoutShouldHydrate)\"\n            : \"\"\n        }\n      ) {\n        pendingPageHydrationController = hydrationController;\n      }\n      if (shouldHydrate) {\n        const hydrationContainer = layoutShouldHydrate\n          ? container\n          : document.getElementById('__farm_page__') || container;\n        const scheduledHydration = scheduleFarmIslandHydration({\n          container: hydrationContainer,\n          strategy: route.islandStrategy,\n          signal: hydrationController.signal,\n          hydrate: async () => {\n            await tryHydrateImportedPage(\n              hydrationContainer,\n              route,\n              params,\n              layouts,\n              true,\n              pageData.props,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy: route.islandStrategy,\n                loadingModulePath: route.loadingModulePath,\n              },\n            );\n          },\n        });\n        if (route.islandStrategy === 'load') {\n          await scheduledHydration;\n        } else {\n          void scheduledHydration.catch((error) => {\n            console.warn('[Farm.js] Deferred island hydration failed:', error);\n          });\n        }\n      }\n      ${\n        isolatedHydrationEnabled\n          ? `if (hasIsolatedClientBoundaries && !layoutShouldHydrate) {\n        await hydrateFarmIsolatedClientBoundaries(\n          isolatedHydrationScope,\n          hydrationController.signal,\n        );\n        if (hydrationController.signal.aborted) return;\n      }`\n          : \"\"\n      }\n    }\n\n    activeLayoutPatterns = layoutPatterns;\n    activeLayoutShouldHydrate = layoutShouldHydrate;\n    window.__FARM_LOADING_MODULE__ = route.loadingModulePath || null;\n    return true;\n  };\n\n  try {\n    await fetchAndSwapHTML();\n  } catch (error) {\n    console.error('[Farm.js] Render error:', error);\n    // Fallback to full navigation\n    window.location.href = path;\n  }\n}\n\n// Set up the navigation handler\nspaRouter.setNavigationHandler(renderPage);\n\nasync function hydrate() {\n  await farmClientRuntime.start();\n\n  if (isFarmDocsSearchPage()) {\n    await mountFarmDocsSearch();\n  }\n\n  if (await hydrateFarmDocsAdapterRuntime()) {\n    return;\n  }\n\n  const rootContainer = document.getElementById('root')\n  \n  if (!rootContainer) {\n    console.error('[Farm.js] Root container not found')\n    return\n  }\n\n  try {\n    // Check if this is a client component (set by SSR)\n    const isClientComponent = window.__FARM_IS_CLIENT__ === true;\n    const modulePath = window.__FARM_PAGE_MODULE__;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries =\n      window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true ||\n      Boolean(rootContainer.querySelector('farm-client-boundary[data-farm-client-boundary]'));`\n        : \"\"\n    }\n\n    let pageProps = normalizeServerProps(window.__FARM_PROPS__);\n    applyCanonicalPathFromProps(pageProps);\n\n    const pageShouldHydrate =\n      typeof window.__FARM_PAGE_SHOULD_HYDRATE__ === 'boolean'\n        ? window.__FARM_PAGE_SHOULD_HYDRATE__\n        : isClientComponent ||\n          findRoute(window.location.pathname)?.route?.shouldHydrate === true;\n    const layoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n    const shouldHydrate =\n      window.__FARM_SHOULD_HYDRATE__ === true ||\n      pageShouldHydrate ||\n      layoutShouldHydrate;\n    const hydratedSlots = await hydrateInitialRouteSlots();\n    ${\n      isolatedHydrationEnabled\n        ? `if (hasIsolatedClientBoundaries && !pageShouldHydrate && !layoutShouldHydrate) {\n      const hydrationController = new AbortController();\n      pendingPageHydrationController = hydrationController;\n      await hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal);\n      if (hydrationController.signal.aborted) return;\n      return;\n    }`\n        : \"\"\n    }\n    if (!shouldHydrate) {\n      if (hydratedSlots) replayPreHydrationClicks();\n      return\n    }\n    if (!modulePath) {\n      console.error('[Farm.js] No page module path found')\n      return\n    }\n\n    // Get props - either from server-injected props or by matching the current URL\n    if (!pageProps || !pageProps.params || Object.keys(pageProps.params).length === 0) {\n      // Extract params from URL using manifest route matching (fallback)\n      const pathname = window.location.pathname;\n      const foundRoute = findRoute(pathname);\n      pageProps = normalizeServerProps({\n        params: foundRoute?.params || {},\n        search: getCurrentSearchParams(),\n        searchParams: getCurrentSearchParams(),\n        path: pathname,\n      });\n    }\n    currentPageProps = pageProps;\n\n    // Prefer the exact root-to-leaf layout chain selected by the server. The\n    // manifest lookup remains a fallback for generated/static responses.\n    const layouts = Array.isArray(window.__FARM_LAYOUTS__)\n      ? window.__FARM_LAYOUTS__\n      : findLayouts(window.location.pathname);\n    const pageContainer = layoutShouldHydrate\n      ? rootContainer\n      : document.getElementById('__farm_page__') || rootContainer;\n\n    if (!pageContainer) {\n      return\n    }\n\n    const currentRoute = findRoute(window.location.pathname)?.route;\n    const islandStrategy = window.__FARM_ISLAND_STRATEGY__ || currentRoute?.islandStrategy || 'load';\n    pageContainer.dataset.farmIsland = 'page';\n    pageContainer.dataset.farmIslandStrategy = islandStrategy;\n\n    const hydrationPathname = window.location.pathname;\n    const hydrationController = new AbortController();\n    pendingPageHydrationController = hydrationController;\n    try {\n      const pageHydration = scheduleFarmIslandHydration({\n        container: pageContainer,\n        strategy: islandStrategy,\n        signal: hydrationController.signal,\n        hydrate: async () => {\n          if (\n            hydrationController.signal.aborted ||\n            !pageContainer.isConnected ||\n            window.location.pathname !== hydrationPathname\n          ) {\n            return;\n          }\n\n          const hydrationSession = await farmClientRuntime.beginHydration({\n            container: pageContainer,\n            mode: shouldHydrate ? 'hydrate' : 'render',\n          });\n\n          let hydrated = false;\n          try {\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            hydrated = await tryHydrateImportedPage(\n              pageContainer,\n              { modulePath },\n              currentPageProps.params || {},\n              layouts,\n              shouldHydrate,\n              currentPageProps,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy,\n              },\n            );\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            await farmClientRuntime.completeHydration(hydrationSession);\n          } catch (error) {\n            await farmClientRuntime.failHydration(hydrationSession, error);\n            throw error;\n          }\n\n          if (hydrated) {\n            // The scheduler owns queue draining and exactly-once click replay.\n            markFarmHydrated();\n            return;\n          }\n        },\n      });\n      ${\n        isolatedHydrationEnabled\n          ? `const isolatedHydration =\n        hasIsolatedClientBoundaries &&\n        !layoutShouldHydrate\n          ? hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal)\n          : Promise.resolve();\n      await Promise.all([pageHydration, isolatedHydration]);`\n          : \"await pageHydration;\"\n      }\n    } finally {\n      if (pendingPageHydrationController === hydrationController) {\n        pendingPageHydrationController = null;\n      }\n    }\n  } catch (error) {\n    console.error('[Farm.js] Hydration error:', error)\n  }\n}\n\nif (document.readyState === 'loading') {\n  document.addEventListener('DOMContentLoaded', hydrate)\n} else {\n  hydrate()\n}\n\n// ====== EVENT DELEGATION FOR LINKS ======\n// This catches all link clicks even without React hydration\n// This is essential for server component pages where React doesn't hydrate\n\nfunction isModifierEvent(e) {\n  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction hasAbsoluteNavigationHref(href) {\n  return /^[a-zA-Z][a-zA-Z\\\\d+.-]*:/.test(href) || href.startsWith('//');\n}\n\ndocument.addEventListener('click', function(event) {\n  if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n  // Find the closest anchor element\n  let target = event.target;\n  while (target && target.tagName !== 'A') {\n    target = target.parentElement;\n  }\n  \n  if (!target || target.tagName !== 'A') return;\n  \n  const href = target.getAttribute('href');\n  if (!href) return;\n  if (target.hasAttribute('download')) return;\n  \n  // Leave absolute URLs and non-HTTP schemes to the browser.\n  if (hasAbsoluteNavigationHref(href)) return;\n  \n  // Don't intercept hash-only links\n  if (href.startsWith('#')) return;\n  \n  // Don't intercept if target is set to open in new window\n  const linkTarget = target.getAttribute('target');\n  if (linkTarget && linkTarget !== '_self') return;\n  \n  // Don't intercept modifier clicks (Ctrl+Click = new tab)\n  if (isModifierEvent(event)) return;\n  \n  // Don't intercept non-left clicks\n  if (event.button !== 0) return;\n  \n  // Don't intercept if already prevented\n  if (event.defaultPrevented) return;\n  \n  // Use SPA router\n  event.preventDefault();\n  const replace = target.hasAttribute('data-replace');\n  const scroll = !target.hasAttribute('data-no-scroll');\n  const viewTransitionValue = target.getAttribute('data-view-transition');\n  const viewTransition = viewTransitionValue === 'auto'\n    ? 'auto'\n    : viewTransitionValue === 'true';\n  \n  spaRouter.navigate(href, { replace, scroll, viewTransition });\n});\n\nif (import.meta.hot) {\n  import.meta.hot.on('vite:beforeUpdate', () => {\n    // Clear module cache on HMR to pick up changes\n    pageModuleCache.clear();\n  })\n}\n`;\n}\n\nfunction generateServerCode(): string {\n  return `\nexport { FarmApp, createFarmApp } from './app'\nexport { ServerRenderer } from './server/renderer'\nexport { RouteManager } from './routing/route-manager'\nexport * from './types'\n`;\n}\n\nfunction generateClientManifest(bundle: any): Record<string, any> {\n  const manifest: Record<string, any> = {};\n\n  for (const [fileName, chunk] of Object.entries(bundle)) {\n    if ((chunk as any).type === \"chunk\") {\n      manifest[fileName] = {\n        id: fileName,\n        chunks: [fileName],\n        name: (chunk as any).name || fileName,\n      };\n    }\n  }\n\n  return manifest;\n}\n\nexport async function defineConfig(config: FarmVitePluginOptions = {}): Promise<UserConfig> {\n  const tailwindcss = (await import(\"@tailwindcss/vite\")).default;\n  const appRoot = path.resolve(config.root || process.cwd());\n  if (config.extends?.length) {\n    const { config: layeredConfig } = await import(\"./layers\").then(({ resolveFarmLayers }) =>\n      resolveFarmLayers(config, {\n        root: appRoot,\n        mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      }),\n    );\n    config = layeredConfig;\n  }\n  config.renderer = resolveFarmRenderer(config.renderer);\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, appRoot, {\n    ssr: true,\n  });\n  // Node.js built-in module stubs for browser\n  const nodeBuiltinStubs: Record<string, string> = {\n    \"node:string_decoder\":\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    \"node:buffer\":\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    \"node:stream\":\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    \"node:util\":\n      \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    \"node:events\":\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    \"node:path\":\n      \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    \"node:fs\": \"data:text/javascript,export default {};\",\n    \"node:url\":\n      \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    \"node:crypto\":\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    \"node:os\":\n      \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    \"node:child_process\": \"data:text/javascript,export default {};\",\n    \"node:http\": \"data:text/javascript,export default {};\",\n    \"node:https\": \"data:text/javascript,export default {};\",\n    \"node:net\": \"data:text/javascript,export default {};\",\n    \"node:tls\": \"data:text/javascript,export default {};\",\n    \"node:zlib\": \"data:text/javascript,export default {};\",\n    \"node:async_hooks\":\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    \"node:worker_threads\": \"data:text/javascript,export default {};\",\n    \"node:perf_hooks\":\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n    string_decoder:\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    buffer:\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    stream:\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    util: \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    events:\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    path: \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    fs: \"data:text/javascript,export default {};\",\n    url: \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    crypto:\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    os: \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    child_process: \"data:text/javascript,export default {};\",\n    http: \"data:text/javascript,export default {};\",\n    https: \"data:text/javascript,export default {};\",\n    net: \"data:text/javascript,export default {};\",\n    tls: \"data:text/javascript,export default {};\",\n    zlib: \"data:text/javascript,export default {};\",\n    async_hooks:\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    worker_threads: \"data:text/javascript,export default {};\",\n    perf_hooks:\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n  };\n\n  // Plugin to intercept __vite-browser-external requests\n  const viteBrowserExternalPlugin = {\n    name: \"farm:browser-external-stub\",\n    enforce: \"pre\" as const,\n    resolveId(id: string) {\n      // Handle Vite's browser external markers\n      if (id.includes(\"__vite-browser-external:\")) {\n        const moduleName = id.replace(/__vite-browser-external:/, \"\");\n        const stub = nodeBuiltinStubs[moduleName];\n        if (stub) return stub;\n        // Generic stub for unknown node modules\n        return \"data:text/javascript,export default {};\";\n      }\n      // Handle direct node: imports\n      if (id.startsWith(\"node:\")) {\n        const stub = nodeBuiltinStubs[id];\n        if (stub) return stub;\n        return \"data:text/javascript,export default {};\";\n      }\n      return null;\n    },\n  };\n\n  // Custom logger to replace Vite's default logs with Farm.js branding\n  const pc = createCliColors();\n  let serverStarted = false;\n  let startTime = Date.now();\n\n  const farmLogger = {\n    info: (msg: string) => {\n      // Suppress ALL Vite startup messages - we print our own Farm.js branded output\n      if (\n        msg.includes(\"VITE\") ||\n        msg.includes(\"vite\") ||\n        msg.includes(\"ready in\") ||\n        msg.includes(\"Local:\") ||\n        msg.includes(\"Network:\") ||\n        msg.includes(\"➜\") ||\n        msg.includes(\"Port\") ||\n        msg.includes(\"trying another\")\n      ) {\n        return;\n      }\n      // Pass through other info messages\n      console.log(msg);\n    },\n    warn: (msg: string) => console.warn(pc.yellow(msg)),\n    warnOnce: (msg: string) => console.warn(pc.yellow(msg)),\n    error: (msg: string) => console.error(pc.red(msg)),\n    clearScreen: () => {},\n    hasErrorLogged: () => false,\n    hasWarned: false,\n  };\n\n  // Plugin to print Farm.js branding after server starts\n  const farmBrandingPlugin = {\n    name: \"farm:branding\",\n    enforce: \"pre\" as const,\n    configureServer(server: ViteDevServer) {\n      startTime = Date.now();\n\n      const originalListen = server.listen.bind(server);\n      server.listen = async (port?: number, ...args: any[]) => {\n        const result = await originalListen(port, ...args);\n        if (!serverStarted) {\n          serverStarted = true;\n          const elapsed = Date.now() - startTime;\n          const address = server.httpServer?.address();\n          const resolvedPort =\n            typeof address === \"object\" && address\n              ? address.port\n              : server.config.server.port || port || 3000;\n          const hostConfig = server.config.server.host;\n          const isExposed = hostConfig === true || hostConfig === \"0.0.0.0\";\n\n          console.log(\"\");\n          console.log(\n            `  ${pc.bold(pc.green(\"Farm.js\"))} ${pc.dim(`v${FARM_VERSION}`)} ${pc.dim(`ready in ${elapsed}ms`)}`,\n          );\n          console.log(\"\");\n          console.log(\n            `  ${pc.dim(\"➜\")}  ${pc.bold(\"Local:\")}   ${pc.cyan(`http://localhost:${resolvedPort}/`)}`,\n          );\n          if (isExposed) {\n            // Get actual network address\n            const os = require(\"os\");\n            const interfaces = os.networkInterfaces();\n            for (const name of Object.keys(interfaces)) {\n              for (const iface of interfaces[name] || []) {\n                if (iface.family === \"IPv4\" && !iface.internal) {\n                  console.log(\n                    `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.cyan(`http://${iface.address}:${resolvedPort}/`)}`,\n                  );\n                  break;\n                }\n              }\n            }\n          } else {\n            console.log(\n              `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.dim(\"use --host to expose\")}`,\n            );\n          }\n          console.log(\"\");\n        }\n        return result;\n      };\n    },\n  };\n\n  return {\n    plugins: [\n      createFarmThemeCssPlugin(config.theme, config.basePath),\n      tailwindcss(),\n      ...(rendererVitePlugins as any[]),\n      viteBrowserExternalPlugin,\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config),\n      farmEnvironmentFunctionsPlugin(),\n      farmBrandingPlugin,\n    ],\n    customLogger: farmLogger,\n    clearScreen: false,\n    optimizeDeps: {\n      ...createFarmClientOptimizeDepsConfig(\n        createFarmClientOptimizeDepsEntries(\n          appRoot,\n          getFarmAppDirectories({ ...config, root: appRoot }),\n        ),\n        config.renderer,\n      ),\n      // Pre-bundle every framework client-runtime entry with the renderer. Without\n      // this, Vite can discover a linked Farm entry after the page has loaded,\n      // regenerate the optimizer browser hash, and leave the browser runtime\n      // holding a different renderer instance from a client component.\n      // Exclude server-side packages from browser bundling\n      exclude: [\n        \"@farm.js/core/server\",\n        \"@farm.js/core/api\",\n        \"@farm.js/core/middleware\",\n        \"@farm.js/core/config\",\n        \"nitro\",\n        \"h3\",\n        \"vite\",\n        \"esbuild\",\n        \"rollup\",\n        \"fsevents\",\n        \"nf3\",\n        \"better-call\",\n        \"zod\",\n        \"supports-color\",\n        \"node-fetch\",\n        \"consola\",\n        \"mock-aws-s3\",\n        \"aws-sdk\",\n        \"nock\",\n      ],\n    },\n    ssr: {\n      noExternal: [\"farm\", \"@farm.js/core\"],\n      // Externalize the renderer to prevent multiple runtime instances during SSR.\n      external: [...(config.renderer.dedupe || [])],\n    },\n    resolve: {\n      // Ensure one renderer instance across application and framework modules.\n      dedupe: [...(config.renderer.dedupe || [])],\n      // Stub out problematic server-only modules during dev mode\n      alias: {\n        ...getFarmLayerAliases(config.layers),\n        ...createFarmSourceAlias(appRoot, config.srcDir),\n        // Nitro internals that should not be resolved in browser\n        \"supports-color\":\n          \"data:text/javascript,export default false; export const supportsColor = false; export const stdout = false; export const stderr = false;\",\n        \"@poppinss/dumper\": \"data:text/javascript,export default {};\",\n        \"@poppinss/dumper/html\":\n          \"data:text/javascript,export const createScript = () => ''; export const createStyleSheet = () => '';\",\n        \"consola/basic\":\n          \"data:text/javascript,export default { log: console.log, info: console.info, warn: console.warn, error: console.error };\",\n        youch:\n          \"data:text/javascript,export default class Youch { toJSON() { return {}; } toHTML() { return ''; } };\",\n        // Add all node stubs to alias as well\n        ...nodeBuiltinStubs,\n      },\n    },\n    define: {\n      __FARM_DEV__: JSON.stringify(process.env.NODE_ENV === \"development\"),\n      __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),\n      __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n    },\n  };\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\n\ninterface DottedPathRouteMatcher {\n  matchRoute(pathname: string): { route: unknown } | null | undefined;\n  matchMetadataRoute(pathname: string): object | null;\n  matchMetadataImage(pathname: string): object | null;\n}\n\n/**\n * Decide whether the dev server should hand a dotted request path to the\n * static pipeline instead of Farm's renderer. Dotted paths are usually asset\n * requests, but they are also how page routes with dotted segments and\n * application metadata routes (/manifest.webmanifest, /sitemap.xml,\n * /robots.txt, generated metadata images) are addressed, so the router is\n * only bypassed when nothing in the app matches the pathname or a real file\n * shadows it.\n */\nexport function shouldBypassFarmRouterForDottedPath(\n  pathname: string,\n  routeManager: DottedPathRouteMatcher | null | undefined,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  if (!pathname.includes(\".\") || pathname.endsWith(\".html\")) return false;\n  const matchesAppRoute = Boolean(\n    routeManager?.matchRoute(pathname)?.route ||\n    routeManager?.matchMetadataRoute(pathname) ||\n    routeManager?.matchMetadataImage(pathname),\n  );\n  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);\n}\n\n/**\n * Route segments may legitimately contain dots (e.g. /kinfish/farm.js), so a\n * dot alone cannot classify a dev request as a static asset. A dotted path is\n * only treated as an asset when it maps to a real file under one of the\n * servable base dirs (project root, public dir), matching the\n * filesystem-first behavior of production hosting.\n */\nexport function devServableFileExists(\n  pathname: string,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  let decodedPathname: string;\n  try {\n    decodedPathname = decodeURIComponent(pathname);\n  } catch {\n    return false;\n  }\n  const relativePathname = decodedPathname.replace(/^\\/+/, \"\");\n  if (!relativePathname) return false;\n  for (const baseDir of baseDirs) {\n    if (typeof baseDir !== \"string\" || baseDir.length === 0) continue;\n    const resolvedBase = path.resolve(baseDir);\n    const candidate = path.resolve(resolvedBase, relativePathname);\n    if (!candidate.startsWith(resolvedBase + path.sep)) continue;\n    try {\n      if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n        return true;\n      }\n    } catch {\n      // Ignore filesystem errors and keep checking other base dirs.\n    }\n  }\n  return false;\n}\n","const SERVER_FN_FACTORIES = [\"createServerQuery\", \"createServerFn\"] as const;\n\nconst FARM_CORE_IMPORT_RE =\n  /import\\s*(?!type\\b)(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*([\"'])@farm\\.js\\/core(?:\\/[\\w./-]+)?\\2/g;\n\nexport type ServerFnBoundaryViolation = {\n  factory: (typeof SERVER_FN_FACTORIES)[number];\n};\n\n/**\n * Detect a module that defines a Farm server function (createServerQuery /\n * createServerFn) while being compiled for the client environment. Without\n * the server-function transform (@farm.js/plugin/rsc with\n * experimental.serverActions enabled) there is no client stub: the server\n * handler and its dependency graph would be bundled into the browser and\n * executed there, surfacing as confusing Vite externalization errors for\n * Node built-ins (#408).\n */\nexport function findClientServerFnViolation(\n  code: string,\n  id: string,\n): ServerFnBoundaryViolation | null {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return null;\n  // Markdown modules never execute import statements: matched text is\n  // documentation (fenced code examples), not code, before and after the\n  // markdown transform (fences compile to string content).\n  if (/\\.(md|mdx)(\\?|$)/.test(id)) return null;\n  if (!code.includes(\"@farm.js/core\")) return null;\n\n  for (const match of code.matchAll(FARM_CORE_IMPORT_RE)) {\n    const specifiers = match[1];\n    for (const factory of SERVER_FN_FACTORIES) {\n      if (!new RegExp(`(?:^|[\\\\s{,])${factory}(?:[\\\\s},]|$)`).test(specifiers)) continue;\n      // Only a call site makes the module a server-function definition; a\n      // type-only or re-exported symbol never executes a handler.\n      if (new RegExp(`(?<![\\\\w$.])${factory}\\\\s*(?:<[^>]*>)?\\\\s*\\\\(`).test(code)) {\n        return { factory };\n      }\n    }\n  }\n  return null;\n}\n\nexport function formatServerFnBoundaryError(\n  violation: ServerFnBoundaryViolation,\n  id: string,\n): string {\n  return [\n    `${violation.factory} handlers run only on the server, but ${id} is being bundled into the client.`,\n    `Importing a ${violation.factory} module from client code executes the server handler (and its Node-only imports) in the browser.`,\n    `Either enable the server-function transform (add @farm.js/plugin/rsc and set experimental.serverActions: true in farm.config.ts) so client imports become server references,`,\n    `or keep the query on the server: call it from server components, or expose an API route and use createAPIClient from the client.`,\n  ].join(\"\\n\");\n}\n","/**\n * Diagnostics for server-only access in modules compiled for the client.\n *\n * A module entering the client graph runs in the browser. Module-scope reads\n * of non-public process.env values evaluate to undefined there and broke\n * layout hydration in #560, and node: builtin imports are silently stubbed\n * with empty objects by farm:browser-external-stub. Both deserve a clear\n * build-time warning naming the module instead of a runtime mystery (#1065).\n */\n\ntype EstreeNode = { type: string; [key: string]: unknown };\n\nconst FUNCTION_BODY_TYPES = new Set([\n  \"FunctionDeclaration\",\n  \"FunctionExpression\",\n  \"ArrowFunctionExpression\",\n]);\n\nexport function shouldInspectClientBoundary(id: string, code: string): boolean {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return false;\n  return code.includes(\"process.env\") || code.includes(\"node:\");\n}\n\nexport interface ClientBoundaryFindings {\n  /** Non-public process.env keys read at module scope. */\n  envKeys: string[];\n  /**\n   * Declared-public keys read via process.env at module scope. The value is\n   * still undefined in the browser — only publicEnv is populated there — so\n   * these get their own warning pointing at the supported accessor.\n   */\n  publicEnvKeys: string[];\n  /** node: builtin specifiers imported into the module. */\n  builtinImports: string[];\n}\n\n/**\n * One walk over the module AST for both diagnostics.\n *\n * Reads and dynamic imports inside function bodies are skipped: they may be\n * server-gated at runtime — a lazy `await import(\"node:fs\")` behind a server\n * check is the recommended escape hatch — and flagging them would drown the\n * signal in noise. Static import/export-from declarations always execute at\n * module scope, so they are always flagged.\n */\nexport function analyzeClientBoundary(\n  program: EstreeNode,\n  publicKeys: ReadonlySet<string>,\n): ClientBoundaryFindings {\n  const envKeys = new Set<string>();\n  const publicEnvKeys = new Set<string>();\n  const builtinImports = new Set<string>();\n\n  const visit = (node: unknown, inFunction: boolean): void => {\n    if (!node || typeof node !== \"object\") return;\n    if (Array.isArray(node)) {\n      for (const entry of node) visit(entry, inFunction);\n      return;\n    }\n    const estree = node as EstreeNode;\n    if (typeof estree.type !== \"string\") return;\n\n    if (!inFunction) {\n      const builtin = readNodeBuiltinSource(estree);\n      if (builtin !== undefined) builtinImports.add(builtin);\n\n      const key = readProcessEnvKey(estree);\n      if (key !== undefined) {\n        if (key !== \"NODE_ENV\") {\n          (publicKeys.has(key) ? publicEnvKeys : envKeys).add(key);\n        }\n        return;\n      }\n    }\n\n    // Params and defaults evaluate at call time along with the body.\n    const nextInFunction = inFunction || FUNCTION_BODY_TYPES.has(estree.type);\n    for (const [childKey, value] of Object.entries(estree)) {\n      if (childKey === \"type\") continue;\n      visit(value, nextInFunction);\n    }\n  };\n\n  visit((program as { body?: unknown }).body, false);\n  return {\n    envKeys: [...envKeys],\n    publicEnvKeys: [...publicEnvKeys],\n    builtinImports: [...builtinImports],\n  };\n}\n\nfunction readNodeBuiltinSource(node: EstreeNode): string | undefined {\n  if (\n    node.type === \"ImportDeclaration\" ||\n    node.type === \"ExportNamedDeclaration\" ||\n    node.type === \"ExportAllDeclaration\" ||\n    node.type === \"ImportExpression\"\n  ) {\n    const value = (node.source as { value?: unknown } | null | undefined)?.value;\n    return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n  }\n  if (node.type === \"CallExpression\") {\n    const callee = node.callee as EstreeNode | undefined;\n    if (callee?.type === \"Identifier\" && (callee as { name?: string }).name === \"require\") {\n      const arg = (node.arguments as EstreeNode[] | undefined)?.[0];\n      const value = arg?.type === \"Literal\" ? (arg as { value?: unknown }).value : undefined;\n      return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n    }\n  }\n  return undefined;\n}\n\nfunction readProcessEnvKey(node: EstreeNode): string | undefined {\n  if (node.type !== \"MemberExpression\") return undefined;\n  const object = node.object as EstreeNode | undefined;\n  if (\n    !object ||\n    object.type !== \"MemberExpression\" ||\n    (object.object as EstreeNode | undefined)?.type !== \"Identifier\" ||\n    (object.object as { name?: string }).name !== \"process\" ||\n    (object.property as { name?: string })?.name !== \"env\"\n  ) {\n    return undefined;\n  }\n\n  const property = node.property as EstreeNode | undefined;\n  if (!property) return undefined;\n  if (!node.computed && property.type === \"Identifier\") {\n    return (property as { name?: string }).name;\n  }\n  if (node.computed && property.type === \"Literal\") {\n    const value = (property as { value?: unknown }).value;\n    return typeof value === \"string\" ? value : undefined;\n  }\n  return undefined;\n}\n\nexport function formatClientBoundaryWarning(id: string, findings: ClientBoundaryFindings): string {\n  const { envKeys, publicEnvKeys, builtinImports } = findings;\n  const lines = [`${id} is compiled for the client but uses server-only APIs:`];\n  if (envKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${envKeys.join(\", process.env.\")} — undefined in the browser. Move the read behind a server boundary, or expose it through env.public in farm.config.ts.`,\n    );\n  }\n  if (publicEnvKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${publicEnvKeys.join(\", process.env.\")} — process.env is not populated in the browser even for public keys. Read it through publicEnv from \"@farm.js/core/env\".`,\n    );\n  }\n  if (builtinImports.length > 0) {\n    lines.push(\n      `- import of ${builtinImports.join(\", \")} — stubbed with an empty object in the browser. Move the import into server-only code.`,\n    );\n  }\n  return lines.join(\"\\n\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\nimport type { Plugin } from \"vite\";\n\nconst FARM_IMAGE_ID_PREFIX = \"\\0farm:image:\";\nconst STATIC_IMAGE_RE = /\\.(?:avif|gif|jpe?g|png|webp)$/i;\nconst SCRIPT_IMPORTER_RE = /\\.(?:[cm]?[jt]sx?|mdx?)$/i;\n\nexport function farmImageImportsPlugin(): Plugin {\n  return {\n    name: \"farm-image-imports\",\n    enforce: \"pre\",\n\n    async resolveId(source, importer, options) {\n      if (\n        !importer ||\n        source.includes(\"?\") ||\n        !STATIC_IMAGE_RE.test(source) ||\n        !SCRIPT_IMPORTER_RE.test(importer.split(\"?\", 1)[0])\n      ) {\n        return null;\n      }\n\n      const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n      if (!resolved || resolved.external) return null;\n\n      return `${FARM_IMAGE_ID_PREFIX}${encodeURIComponent(resolved.id.split(\"?\", 1)[0])}`;\n    },\n\n    async load(id) {\n      if (!id.startsWith(FARM_IMAGE_ID_PREFIX)) return null;\n\n      const filePath = decodeURIComponent(id.slice(FARM_IMAGE_ID_PREFIX.length));\n      const assetRequest = `${filePath.replace(/\\\\/g, \"/\")}?url`;\n      return createStaticImageModule(filePath, `import src from ${JSON.stringify(assetRequest)};`);\n    },\n\n    async transform(code, id) {\n      const filePath = id.split(\"?\", 1)[0];\n      if (id.includes(\"?\") || !STATIC_IMAGE_RE.test(filePath)) return null;\n\n      const defaultExport = code.match(/^\\s*export\\s+default\\s+(.+?);?\\s*$/s)?.[1];\n      if (!defaultExport) return null;\n      return createStaticImageModule(filePath, `const src = ${defaultExport};`);\n    },\n  };\n}\n\nasync function createStaticImageModule(\n  filePath: string,\n  sourceDeclaration: string,\n): Promise<string> {\n  const bytes = await readFile(filePath);\n  const dimensions = imageSize(bytes);\n  if (!dimensions.width || !dimensions.height) {\n    throw new Error(`Could not determine image dimensions for ${filePath}`);\n  }\n\n  const blurDataURL = await createBlurDataURL(bytes);\n  return [\n    sourceDeclaration,\n    `const image = ${JSON.stringify({\n      width: dimensions.width,\n      height: dimensions.height,\n      ...(blurDataURL ? { blurDataURL } : {}),\n    })};`,\n    \"image.src = src;\",\n    \"export { src };\",\n    \"export const width = image.width;\",\n    \"export const height = image.height;\",\n    \"export const blurDataURL = image.blurDataURL;\",\n    \"export default image;\",\n  ].join(\"\\n\");\n}\n\nasync function createBlurDataURL(bytes: Buffer): Promise<string | undefined> {\n  try {\n    const { default: sharp } = await import(\"sharp\");\n    const placeholder = await sharp(bytes)\n      .rotate()\n      .resize({ width: 8, height: 8, fit: \"inside\", withoutEnlargement: true })\n      .webp({ quality: 35 })\n      .toBuffer();\n    return `data:image/webp;base64,${placeholder.toString(\"base64\")}`;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function isFarmStaticImageFile(filePath: string): boolean {\n  return STATIC_IMAGE_RE.test(path.extname(filePath));\n}\n","import path from \"node:path\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport type { FarmRenderer } from \"../renderer\";\n\nconst FARM_CLIENT_ENTRY_PATTERN =\n  \"**/{page,layout,loading,error,not-found,default}.{js,jsx,ts,tsx}\";\n\n/**\n * Client runtimes that must be optimized in the same generation as React.\n * Farm loads route modules dynamically, so Vite's HTML crawl cannot reliably\n * discover these linked-package entry points before hydration begins.\n */\nexport const FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE = [\n  \"react\",\n  \"react-dom\",\n  \"react-dom/client\",\n  \"react/jsx-runtime\",\n  \"react/jsx-dev-runtime\",\n  \"@farm.js/core/client\",\n  \"@farm.js/core/plugin/client\",\n  \"@farm.js/core/deferred\",\n  \"@farm.js/core/deployment\",\n  \"@farm.js/core/i18n/client\",\n  \"@farm.js/core/query/client\",\n  \"@farm.js/core/server-fn/client\",\n  \"@farm.js/core/server-query/client\",\n] as const;\n\nexport function getFarmClientOptimizeDepsInclude(renderer?: FarmRenderer): string[] {\n  return Array.from(\n    new Set([...FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE, ...(renderer?.optimizeDeps || [])]),\n  );\n}\n\nexport function createFarmClientOptimizeDepsEntries(\n  projectRoot: string,\n  appDirectories: readonly string[],\n): string[] {\n  const resolvedProjectRoot = path.resolve(projectRoot);\n\n  return appDirectories.map((appDirectory) => {\n    const relativeAppDirectory = path\n      .relative(resolvedProjectRoot, path.resolve(appDirectory))\n      .replace(/\\\\/g, \"/\");\n    const prefix = relativeAppDirectory || \".\";\n    return `${prefix}/${FARM_CLIENT_ENTRY_PATTERN}`;\n  });\n}\n\nexport function createFarmClientOptimizeDepsConfig(\n  entries?: readonly string[],\n  renderer?: FarmRenderer,\n): ViteUserConfig[\"optimizeDeps\"] {\n  return {\n    // Keep normal application dependency discovery for CJS-only packages, but\n    // seed every Farm browser runtime so React is present in the first crawl.\n    noDiscovery: false,\n    // Waiting for the crawl avoids serving a partial optimizer generation and\n    // then changing browser hashes while hydration is already in progress.\n    holdUntilCrawlEnd: true,\n    include: getFarmClientOptimizeDepsInclude(renderer),\n    // Farm's HTML boots through a virtual module and imports route UI lazily.\n    // Explicit entries let Vite finish that crawl before a navigation can\n    // rotate the optimizer hash underneath a hydrated React runtime.\n    ...(entries?.length ? { entries: [...entries] } : {}),\n  };\n}\n\n/**\n * Farm's application-source alias. Keep this shared by development, route\n * discovery, and production bundling so `@/…` always follows `srcDir`.\n */\nexport function createFarmSourceAlias(projectRoot: string, srcDir = \"src\"): Record<string, string> {\n  return {\n    \"@\": path.resolve(projectRoot, srcDir),\n  };\n}\n\ntype ViteNoExternal = NonNullable<NonNullable<ViteUserConfig[\"ssr\"]>[\"noExternal\"]>;\ntype ViteAlias = NonNullable<NonNullable<ViteUserConfig[\"resolve\"]>[\"alias\"]>;\n\nfunction mergeNoExternal(\n  farmValue: ViteNoExternal | undefined,\n  userValue: ViteNoExternal | undefined,\n): ViteNoExternal {\n  if (farmValue === true || userValue === true) return true;\n\n  const normalize = (value: ViteNoExternal | undefined): Array<string | RegExp> =>\n    value == null || value === true ? [] : Array.isArray(value) ? value : [value];\n\n  return Array.from(new Set([...normalize(farmValue), ...normalize(userValue)]));\n}\n\nfunction mergeAlias(farmValue: ViteAlias | undefined, userValue: ViteAlias | undefined): ViteAlias {\n  if (!farmValue) return userValue || {};\n  if (!userValue) return farmValue;\n\n  if (!Array.isArray(farmValue) && !Array.isArray(userValue)) {\n    return {\n      ...farmValue,\n      ...userValue,\n    };\n  }\n\n  const normalize = (value: ViteAlias): Exclude<ViteAlias, Record<string, string>> =>\n    Array.isArray(value)\n      ? [...value]\n      : Object.entries(value).map(([find, replacement]) => ({ find, replacement }));\n\n  // Vite uses the first matching array entry. Put application entries first\n  // so an explicit user alias can intentionally override a Farm default.\n  return [...normalize(userValue), ...normalize(farmValue)];\n}\n\nexport function mergeFarmViteConfig(\n  farmConfig: ViteUserConfig,\n  userConfig: ViteUserConfig = {},\n): ViteUserConfig {\n  const noDiscovery = userConfig.optimizeDeps?.noDiscovery ?? farmConfig.optimizeDeps?.noDiscovery;\n  const holdUntilCrawlEnd =\n    userConfig.optimizeDeps?.holdUntilCrawlEnd ??\n    (userConfig.optimizeDeps?.noDiscovery === true\n      ? false\n      : farmConfig.optimizeDeps?.holdUntilCrawlEnd);\n\n  return {\n    ...farmConfig,\n    ...userConfig,\n    plugins: [...(farmConfig.plugins || []), ...(userConfig.plugins || [])],\n    server: {\n      ...farmConfig.server,\n      ...userConfig.server,\n    },\n    resolve: {\n      ...farmConfig.resolve,\n      ...userConfig.resolve,\n      alias: mergeAlias(farmConfig.resolve?.alias, userConfig.resolve?.alias),\n      dedupe: Array.from(\n        new Set([...(farmConfig.resolve?.dedupe || []), ...(userConfig.resolve?.dedupe || [])]),\n      ),\n    },\n    optimizeDeps: {\n      ...farmConfig.optimizeDeps,\n      ...userConfig.optimizeDeps,\n      noDiscovery,\n      holdUntilCrawlEnd,\n      include: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.include || []),\n          ...(userConfig.optimizeDeps?.include || []),\n        ]),\n      ),\n      exclude: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.exclude || []),\n          ...(userConfig.optimizeDeps?.exclude || []),\n        ]),\n      ),\n    },\n    ssr: {\n      ...farmConfig.ssr,\n      ...userConfig.ssr,\n      noExternal: mergeNoExternal(farmConfig.ssr?.noExternal, userConfig.ssr?.noExternal),\n    },\n  };\n}\n","import type { Plugin } from \"vite\";\nimport { resolveFarmThemeConfig } from \"./config\";\nimport type { FarmThemeConfig, ResolvedFarmThemeConfig } from \"./types\";\n\nconst FARM_DARK_VARIANT =\n  '@custom-variant dark (&:where([data-theme=\"dark\"], [data-theme=\"dark\"] *));';\n\nexport function createFarmThemeCssPlugin(\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): Plugin {\n  const config = resolveFarmThemeConfig(input, basePath);\n\n  return {\n    name: \"farm:theme-css\",\n    enforce: \"pre\",\n    transform(code, id) {\n      if (\n        !config.enabled ||\n        !/\\.css(?:\\?.*)?$/.test(id) ||\n        !/@import\\s+[\"']tailwindcss[\"']/.test(code) ||\n        /@custom-variant\\s+dark\\b/.test(code)\n      ) {\n        return null;\n      }\n\n      return {\n        code: `${code.trimEnd()}\\n\\n${FARM_DARK_VARIANT}\\n`,\n        map: null,\n      };\n    },\n  };\n}\n","import path from \"node:path\";\nimport type { FarmIntegrationProvider } from \"./integrations\";\nimport { isFarmIntegrationProviderComponentReference } from \"./integrations\";\nimport { toViteModuleId } from \"./utils\";\n\nexport type FarmIntegrationProviderClientCode = {\n  hasProviders: boolean;\n  imports: string;\n  runtime: string;\n};\n\nexport function generateFarmIntegrationProviderClientCode(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): FarmIntegrationProviderClientCode {\n  const renderedProviders = providers.filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const imports: string[] = [];\n  const registrations: string[] = [];\n  let hasClerkProvider = false;\n\n  renderedProviders.forEach((provider, index) => {\n    let componentExpression = \"null\";\n    if (isFarmIntegrationProviderComponentReference(provider.component)) {\n      const namespace = `FarmIntegrationProviderModule${index}`;\n      imports.push(\n        `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n      );\n      componentExpression = `${namespace}[${JSON.stringify(provider.component.export || \"default\")}]`;\n    } else if (typeof provider.component === \"function\") {\n      throw new Error(\n        `Integration provider \"${provider.name}\" must use an importable component reference for client hydration, for example component: { module: \"@/components/provider\" }.`,\n      );\n    } else if (provider.type === \"clerk\") {\n      hasClerkProvider = true;\n      componentExpression = \"FarmClerkProvider\";\n    }\n\n    registrations.push(`{\n  name: ${JSON.stringify(provider.name)},\n  type: ${JSON.stringify(provider.type)},\n  props: ${JSON.stringify(provider.props || {})},\n  Component: ${componentExpression},\n}`);\n  });\n\n  if (hasClerkProvider) {\n    imports.unshift(`import { ClerkProvider as FarmClerkProvider } from \"@clerk/react\";`);\n  }\n\n  return {\n    hasProviders: renderedProviders.length > 0,\n    imports: imports.join(\"\\n\"),\n    runtime: `const integrationProviders = [${registrations.join(\",\\n\")}];\n\nfunction wrapWithIntegrationProviders(element) {\n  let wrapped = element;\n  for (let index = integrationProviders.length - 1; index >= 0; index--) {\n    const provider = integrationProviders[index];\n    if (!provider.Component) {\n      throw new Error(\"Integration provider \" + provider.name + \" did not export its configured component.\");\n    }\n    wrapped = React.createElement(provider.Component, provider.props || {}, wrapped);\n  }\n  return wrapped;\n}`,\n  };\n}\n\nexport function createFarmIntegrationProviderModuleKey(component: {\n  module: string;\n  export?: string;\n}): string {\n  return `${component.module}\\0${component.export || \"default\"}`;\n}\n\nexport function generateFarmIntegrationProviderServerModules(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): { imports: string; entries: string; hasClerkProvider: boolean } {\n  const imports: string[] = [];\n  const entries: string[] = [];\n\n  providers.forEach((provider, index) => {\n    if (!isFarmIntegrationProviderComponentReference(provider.component)) return;\n    const namespace = `FarmServerIntegrationProviderModule${index}`;\n    imports.push(\n      `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n    );\n    entries.push(\n      `[${JSON.stringify(createFarmIntegrationProviderModuleKey(provider.component))}, ${namespace}[${JSON.stringify(provider.component.export || \"default\")}]]`,\n    );\n  });\n\n  return {\n    imports: imports.join(\"\\n\"),\n    entries: entries.join(\",\\n\"),\n    hasClerkProvider: providers.some(\n      (provider) => provider.type === \"clerk\" && !provider.component,\n    ),\n  };\n}\n\nfunction resolveProviderModule(moduleId: string, root: string): string {\n  if (!moduleId.startsWith(\".\")) return moduleId;\n  return toViteModuleId(path.resolve(root, moduleId), root);\n}\n","import { isFarmNotFoundError } from \"../navigation-errors\";\n\nexport interface FarmPageDataFailure {\n  status: number;\n  payload: {\n    error: string;\n    message: string;\n    code?: string;\n  };\n}\n\n/**\n * Preserve expected route outcomes when a page-data render fails. Internal\n * navigation must report the same HTTP class as a full document render so a\n * missing resource never masquerades as a framework crash.\n */\nexport function resolveFarmPageDataFailure(error: unknown): FarmPageDataFailure {\n  if (isFarmNotFoundError(error)) {\n    return {\n      status: 404,\n      payload: {\n        error: \"Route not found\",\n        message: \"The requested route did not resolve to a resource.\",\n        code: \"FARM_NOT_FOUND\",\n      },\n    };\n  }\n\n  if (error instanceof Response) {\n    return {\n      status: error.status || 500,\n      payload: {\n        error: error.statusText || \"Page data request failed\",\n        message: error.statusText || `The route returned HTTP ${error.status || 500}.`,\n      },\n    };\n  }\n\n  return {\n    status: 500,\n    payload: {\n      error: \"Failed to load page data\",\n      message: error instanceof Error ? error.message : \"Unknown error\",\n    },\n  };\n}\n","import { logger } from \"../utils\";\n\ninterface OpenAPIDevStatusLogger {\n  success(message: string): void;\n  warn(message: string): void;\n}\n\nexport function reportOpenAPIDevGenerationResult(\n  spec: unknown,\n  output: OpenAPIDevStatusLogger = logger,\n): void {\n  if (spec) {\n    output.success(\"✅ OpenAPI documentation enabled\");\n    return;\n  }\n\n  output.warn(\"OpenAPI documentation is enabled, but its specification failed to generate.\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,gBAAgB;AA+CzB,IAAM,6BAA6B;AACnC,IAAM,6BAA6B;AACnC,IAAM,2BAA2B;AAEjC,IAAM,qBAAqB,oBAAI,IAAoB;AAAA,EACjD,CAAC,WAAW,iBAAiB;AAAA,EAC7B,CAAC,WAAW,iBAAiB;AAAA,EAC7B,CAAC,qBAAqB,qBAAqB;AAAA,EAC3C,CAAC,mBAAmB,uBAAuB;AAAA,EAC3C,CAAC,QAAQ,wBAAwB;AAAA,EACjC,CAAC,oBAAoB,wBAAwB;AAAA,EAC7C,CAAC,cAAc,wBAAwB;AAAA,EACvC,CAAC,eAAe,wBAAwB;AAC1C,CAAC;AAED,IAAM,oBAAoB,oBAAI,IAAoB;AAAA,EAChD,CAAC,gBAAgB,uBAAuB;AAAA,EACxC,CAAC,cAAc,yBAAyB;AAAA,EACxC,CAAC,kBAAkB,yBAAyB;AAAA,EAC5C,CAAC,WAAW,iBAAiB;AAC/B,CAAC;AAMD,SAAS,sCACP,KACA,QACA,SACsB;AACtB,QAAM,aAAa,SAAS,oBAAoB;AAChD,QAAM,kBAAkB,6BAA6B,MAAM;AAC3D,MAAI,MAAM,iBAAiB,OAAO;AAClC,MAAI,eAAe,iBAAiB,OAAO;AAC3C,MAAI,aAAa,iBAAiB;AAClC,QAA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File","path","readFile","path","path","fs","path","fs","path","path","fs","createHash","readFile","path","createHash","bytes","path","readFile","relative","pathToFileURL","fs","path","fileURLToPath","relative","fileURLToPath","escapeHtmlAttribute","pathToFileURL","resolve","html","path","path","promises","definePlugin","fs","path","path","fs","fs","path","path","fs","existsSync","mkdirSync","readFileSync","dirname","isAbsolute","join","resolve","path","fs","mkdirSync","path","path","mkdirSync","fs","path","registries","mkdirSync","dirname","join","resolve","resolve","join","mkdirSync","dirname","resolve","join","existsSync","isAbsolute","mkdirSync","dirname","readFileSync","fs","path","pathToFileURL","fs","path","readFile","path","imageSize","readFile","imageSize","path","path","path","path","declaration","relative","isStaticMetadataImageFile","pathToFileURL","handler","pathname","startTime","duration","method","urlPath","routeManager","parseRouteModuleProps","options","server","parseRouteModuleSchema"]}