@ngrok/app-server 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +68 -7
  2. package/dist/cli.js +2 -2
  3. package/dist/client-browser.d.ts +12 -0
  4. package/dist/client-browser.js +3 -0
  5. package/dist/client.d.ts +14 -134
  6. package/dist/client.js +17 -316
  7. package/dist/client.js.map +1 -1
  8. package/dist/{create-server-iE1-s6Bi.js → create-server-D0De6R7Q.js} +25 -15
  9. package/dist/create-server-D0De6R7Q.js.map +1 -0
  10. package/dist/{entry-DmJEqVfd.d.ts → create-server-kzZWd_Lo.d.ts} +16 -63
  11. package/dist/entry-DuGgSKeB.d.ts +58 -0
  12. package/dist/{entry-DZ3qo7qF.js → entry-UDsxuqBC.js} +2 -2
  13. package/dist/{entry-DZ3qo7qF.js.map → entry-UDsxuqBC.js.map} +1 -1
  14. package/dist/index.d.ts +4 -3
  15. package/dist/index.js +3 -3
  16. package/dist/{load-entry-AfYS_zS9.js → load-entry-Bodyd2Ok.js} +4 -4
  17. package/dist/{load-entry-AfYS_zS9.js.map → load-entry-Bodyd2Ok.js.map} +1 -1
  18. package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
  19. package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
  20. package/dist/node.d.ts +1 -1
  21. package/dist/node.js +1 -1
  22. package/dist/react-router.d.ts +1 -1
  23. package/dist/react-router.js +1 -1
  24. package/dist/request-context-BtQ87VYb.js.map +1 -1
  25. package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
  26. package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
  27. package/dist/{serve-CDNgThjk.js → serve-caOkS3o5.js} +2 -2
  28. package/dist/{serve-CDNgThjk.js.map → serve-caOkS3o5.js.map} +1 -1
  29. package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
  30. package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
  31. package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
  32. package/dist/{start-TLIprD74.js → start-DREqYrZh.js} +4 -4
  33. package/dist/{start-TLIprD74.js.map → start-DREqYrZh.js.map} +1 -1
  34. package/dist/tanstack-start.d.ts +2 -2
  35. package/dist/testing.d.ts +56 -0
  36. package/dist/testing.js +114 -0
  37. package/dist/testing.js.map +1 -0
  38. package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-BrymAEGv.d.ts} +2 -2
  39. package/dist/{types-DLYxYS6M.d.ts → types-CEvzAmcn.d.ts} +2 -2
  40. package/dist/vercel.d.ts +2 -2
  41. package/dist/vercel.js +2 -2
  42. package/dist/{vite-iioAoxSt.js → vite-tTxVimP6.js} +2 -15
  43. package/dist/vite-tTxVimP6.js.map +1 -0
  44. package/dist/vite.js +1 -1
  45. package/package.json +6 -1
  46. package/dist/create-server-iE1-s6Bi.js.map +0 -1
  47. package/dist/script-hashes-hqUk6kG7.js.map +0 -1
  48. package/dist/vite-iioAoxSt.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../src/client/stale-build-navigation.ts"],"sourcesContent":["import {\n\tBUILD_ID_HEADER,\n\tBUILD_ID_METRIC,\n\tisBuildMetric,\n\tserverTimingMetrics,\n} from \"../core/plugins/build-id.js\";\n\n/** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */\nexport type StaleBuildOptions = {\n\t/**\n\t * The header that `buildId()` sets on data responses.\n\t * @default \"X-Build-Id\"\n\t */\n\theader?: string;\n\t/**\n\t * The build that this document runs. Set it only when the server does not\n\t * send it.\n\t * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends\n\t */\n\tbuild?: string;\n\t/**\n\t * Runs once, when the tab first sees a response from another build. Use\n\t * it to count stale tabs in the app's RUM tool.\n\t */\n\tonNewBuild?: (served: string) => void;\n};\n\n/** The context that React Router gives `unstable_fetch` with each request. */\nexport type RouterFetchContext = {\n\t/** `\"navigation\"` for the data request of a navigation that the router started. */\n\ttype: string;\n\t/** `\"PUSH\"`, `\"REPLACE\"`, or `\"POP\"` for a navigation. */\n\tnavigationType?: string | null;\n\t/** The fetcher that sends the request, also in a navigation that revalidates it. */\n\tfetcherKey?: string | null;\n};\n\n/** The location in a TanStack Router event. */\ntype EventLocation = { pathname: string; searchStr: string };\n\n/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */\nexport type NavigationEvents = {\n\thistory: { flush: () => void };\n\tclearCache: () => void;\n\tsubscribe: (\n\t\ttype: \"onBeforeNavigate\" | \"onResolved\",\n\t\tlistener: (event: { fromLocation?: EventLocation; toLocation: EventLocation }) => void,\n\t) => () => void;\n};\n\n/** Whether `url` is on the origin of this page. */\nfunction isOwn(url: string): boolean {\n\treturn new URL(url, location.href).origin === location.origin;\n}\n\n/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */\nfunction timingBuild(entries: PerformanceEntryList): string | undefined {\n\treturn (\n\t\tentries\n\t\t\t.filter(\n\t\t\t\t(entry): entry is PerformanceResourceTiming => \"serverTiming\" in entry && isOwn(entry.name),\n\t\t\t)\n\t\t\t// Why: a redirected resource keeps its first URL as its name, and the redirect can end on\n\t\t\t// another origin. A document entry has its final URL.\n\t\t\t.filter((entry) => entry.entryType !== \"resource\" || entry.redirectStart === 0)\n\t\t\t.flatMap((entry) => entry.serverTiming)\n\t\t\t.find((metric) => metric.name === BUILD_ID_METRIC)?.description\n\t);\n}\n\n/** The build in a `Server-Timing` header, as `buildId()` writes it. */\nfunction headerBuild(header: string | null): string | undefined {\n\tconst { quoted, token } =\n\t\tserverTimingMetrics(header)\n\t\t\t.find((metric) => isBuildMetric(metric))\n\t\t\t?.match(/;\\s*desc\\s*=\\s*(?:\"(?<quoted>(?:[^\"\\\\]|\\\\.)*)\"|(?<token>[^;\\s]*))/iu)?.groups ?? {};\n\treturn quoted?.replaceAll(/\\\\(?<char>.)/gu, \"$<char>\") ?? token;\n}\n\n/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */\nfunction pageOf(url: string): string {\n\tconst { origin, pathname, search } = new URL(url, location.href);\n\treturn `${origin}${pathname}${search}`;\n}\n\n/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */\nfunction eventPage({ pathname, searchStr }: EventLocation): string {\n\treturn `${pathname}${searchStr}`;\n}\n\n/** The URL of a `fetch` call. */\nfunction urlOf(input: RequestInfo | URL): string {\n\treturn input instanceof Request ? input.url : String(input);\n}\n\n/** The method of a `fetch` call. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n\treturn (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n}\n\n/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */\nfunction targetOf(request: Request): string {\n\tconst url = new URL(request.url);\n\turl.pathname = url.pathname.replace(/\\/_\\.data$/u, \"/\").replace(/\\.data$/u, \"\");\n\turl.searchParams.delete(\"_routes\");\n\treturn url.href;\n}\n\n/**\n * Reloads a document that the back/forward cache shows again. Why: Back can\n * show the document that {@link loadDocument} left, with its router still in a\n * navigation that never ends. Why one function: the browser adds it once.\n */\nfunction reloadIfRestored(event: PageTransitionEvent): void {\n\tif (event.persisted) {\n\t\tlocation.reload();\n\t}\n}\n\n/**\n * Loads `target` as a document, so the old code never gets the new build's\n * data. It returns a promise that never settles, because the page unloads.\n */\nasync function loadDocument(\n\ttarget: string,\n\t{\n\t\tresponse,\n\t\tnavigationType,\n\t}: { response?: Response | undefined; navigationType?: string | null | undefined } = {},\n): Promise<never> {\n\t// Why no wait: the cancel of a cloned body waits for the other branch.\n\tresponse?.body?.cancel().catch(() => undefined);\n\t// Why reload on this page: the router can move history first, and `assign` to the same page\n\t// with a fragment scrolls with no document load. A history step already moved history. Why\n\t// not to remove a fragment: `assign` to a URL with no fragment loads the document.\n\tconst isSamePage = pageOf(target) === pageOf(location.href);\n\tconst removesFragment = new URL(target, location.href).hash === \"\" && location.hash !== \"\";\n\taddEventListener(\"pageshow\", reloadIfRestored, { once: true });\n\tif (navigationType === \"POP\" || (isSamePage && !removesFragment)) {\n\t\tlocation.reload();\n\t} else if (navigationType === \"REPLACE\") {\n\t\tlocation.replace(target);\n\t} else {\n\t\tlocation.assign(target);\n\t}\n\treturn new Promise<never>(() => {});\n}\n\n/**\n * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a\n * newer one starts, such as after the visitor stays on the page at a leave prompt.\n */\nfunction onAbort(signal: AbortSignal, clear: () => void): void {\n\tsignal.addEventListener(\"abort\", clear, { once: true });\n}\n\n/** Reads the build of each response, and tells when the server runs a new build. */\nfunction watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }: StaleBuildOptions) {\n\t// Why: on the server, such as in a router factory that runs for each request, there is no tab to move.\n\tif (typeof document === \"undefined\") {\n\t\treturn null;\n\t}\n\tconst current = build ?? timingBuild(performance.getEntriesByType(\"navigation\"));\n\tif (current == null) {\n\t\treturn null;\n\t}\n\tlet stale = false;\n\tconst see = (served: string | null | undefined) => {\n\t\tif (served == null || served === current || stale) {\n\t\t\treturn;\n\t\t}\n\t\tstale = true;\n\t\t// Why a catch: an error in the app's callback must not fail the request that found the build.\n\t\ttry {\n\t\t\tonNewBuild?.(served);\n\t\t} catch (error) {\n\t\t\treportError(error);\n\t\t}\n\t};\n\t// Why resource timing: it shows the build of a response that no script fetched, such as a\n\t// prefetch on hover, so the tab can find a new build before the click. Why buffered: a prefetch\n\t// can finish before this module runs.\n\tconst observer =\n\t\ttypeof PerformanceObserver === \"function\"\n\t\t\t? new PerformanceObserver((list) => {\n\t\t\t\t\t// Why each entry: one delivery can hold the old build first and the new build after it.\n\t\t\t\t\tfor (const entry of list.getEntries()) {\n\t\t\t\t\t\tsee(timingBuild([entry]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined;\n\tobserver?.observe({ type: \"resource\", buffered: true });\n\treturn {\n\t\tisStale: () => stale,\n\t\t/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */\n\t\tisNew: (response: Response, url: string) => {\n\t\t\t// Why the final URL: a redirect can end on another origin. Why `Server-Timing`: a proxy\n\t\t\t// route of `buildId({ paths })` sends no build header.\n\t\t\tconst served = isOwn(response.url === \"\" ? url : response.url)\n\t\t\t\t? (response.headers.get(header) ?? headerBuild(response.headers.get(\"Server-Timing\")))\n\t\t\t\t: null;\n\t\t\tsee(served);\n\t\t\treturn served != null && served !== current;\n\t\t},\n\t\tstop: () => observer?.disconnect(),\n\t};\n}\n\n/** The `navigate` call of a React Router instrumentation. */\ntype NavigateInfo = { to: string | number; formMethod?: string };\n\n/** The router instrumentations that {@link staleBuildReactRouter} adds. */\ntype RouterInstrumentations = {\n\tnavigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;\n};\n\n/**\n * The arguments of a client middleware call. Why the `unstable_` fields: React\n * Router gives the middleware the arguments of its data strategy, which tell a\n * navigation from a fetcher and give its history action.\n */\ntype MiddlewareArgs = {\n\trequest: Request;\n\tunstable_initiator?: string;\n\tunstable_navigationType?: string | null;\n};\n\n/** The hooks that {@link staleBuildReactRouter} gives to React Router. */\nexport type StaleBuildReactRouter = {\n\t/** Give it to `HydratedRouter` as `unstable_fetch`. */\n\tfetch: (request: Request, context: RouterFetchContext) => Promise<Response>;\n\t/** Give it to `HydratedRouter` in `instrumentations`. */\n\tinstrumentation: {\n\t\trouter: (router: { instrument: (instrumentations: RouterInstrumentations) => void }) => void;\n\t};\n\t/** Export it from `app/root.tsx` in `clientMiddleware`. */\n\tmiddleware: <Result>(args: { request: Request }, next: () => Promise<Result>) => Promise<Result>;\n};\n\n/** The fragment of a `navigate` target, such as `#usage`, or `\"\"`. */\nfunction hashOf(to: string | number): string {\n\treturn typeof to === \"string\" && to.includes(\"#\") ? to.slice(to.indexOf(\"#\")) : \"\";\n}\n\n/**\n * Moves an open React Router tab to a new build at a navigation, so the old\n * client code never renders data from the new server, and the page that the\n * visitor reads never reloads. Create it in a module that the client entry\n * and `app/root.tsx` both import. It reads no browser state until React\n * Router calls it, so the server can import it.\n *\n * - When the data request of a navigation gets a response from a new build,\n * the browser loads the target URL as a document.\n * - When the tab already knows of a new build, a `navigate` call, such as a\n * link click, loads its target as a document before the router renders it\n * or sends a data request. The root middleware does this also for a route\n * with no loader.\n * - A revalidation, a fetcher, an action, and the loaders after an action\n * get their response. They only mark the tab, so the page that the visitor\n * reads never reloads.\n * - The router's blockers run first, and a canceled navigation never loads\n * its target.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n *\n * @example\n * // app/stale-build.ts\n * export const staleBuild = staleBuildReactRouter();\n *\n * // app/root.tsx\n * export const clientMiddleware = [staleBuild.middleware];\n *\n * // app/entry.client.tsx\n * startTransition(() => {\n * \thydrateRoot(\n * \t\tdocument,\n * \t\t<HydratedRouter\n * \t\t\tunstable_fetch={staleBuild.fetch}\n * \t\t\tinstrumentations={[staleBuild.instrumentation]}\n * \t\t/>,\n * \t);\n * });\n */\nexport function staleBuildReactRouter(options: StaleBuildOptions = {}): StaleBuildReactRouter {\n\t// Why lazy: `app/root.tsx` also runs on the server, which has no tab to watch.\n\tlet watched: { watch: ReturnType<typeof watchBuild> } | undefined;\n\tconst watch = () => {\n\t\twatched ??= { watch: watchBuild(options) };\n\t\treturn watched.watch;\n\t};\n\t/**\n\t * The path of the last action of a navigation, until its loaders run. The\n\t * router revalidates the page with one or more loader requests after it.\n\t * `loading` is true while they run.\n\t */\n\tlet action: { path: string; loading: boolean } | undefined;\n\t/** The target that the tab loads as a document now. */\n\tlet leaving: string | undefined;\n\t/**\n\t * The last `navigate` call. `claimed` is true when its first middleware call\n\t * already ran, or when it is not a page load. `page` is the target page of\n\t * that first call.\n\t */\n\tlet navigating: { hash: string; claimed: boolean; page?: string } | undefined;\n\tconst load = async (\n\t\trequest: Request,\n\t\ttarget: string,\n\t\t{ response, navigationType }: { response?: Response; navigationType?: string | null } = {},\n\t) => {\n\t\tif (leaving === target) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<never>(() => {});\n\t\t}\n\t\tleaving = target;\n\t\tonAbort(request.signal, () => {\n\t\t\tif (leaving === target) {\n\t\t\t\tleaving = undefined;\n\t\t\t}\n\t\t});\n\t\treturn loadDocument(target, { response, navigationType });\n\t};\n\treturn {\n\t\tfetch: async (request, context) => {\n\t\t\tconst navigationType =\n\t\t\t\tcontext.type === \"navigation\" && context.fetcherKey == null\n\t\t\t\t\t? context.navigationType\n\t\t\t\t\t: undefined;\n\t\t\t// Why the global at each call: an app can wrap `fetch` after this module, such as for RUM.\n\t\t\tconst send = async () => {\n\t\t\t\tconst response = await globalThis.fetch(request);\n\t\t\t\treturn { response, isNew: watch()?.isNew(response, request.url) === true };\n\t\t\t};\n\t\t\tif (watch() == null || navigationType == null) {\n\t\t\t\treturn (await send()).response;\n\t\t\t}\n\t\t\t// Why the hash of the `navigate` call: the router removes it from the data request. Why\n\t\t\t// its page only: a redirect goes to another page with no `navigate` call.\n\t\t\tconst page = targetOf(request);\n\t\t\tconst hash =\n\t\t\t\tnavigationType !== \"POP\" && navigating?.page === pageOf(page) ? navigating.hash : \"\";\n\t\t\tconst target = page + hash;\n\t\t\tconst path = new URL(target).pathname;\n\t\t\tconst isAfterAction = request.method === \"GET\" && action?.path === path;\n\t\t\t// Why check the signal: a canceled navigation must never load its target.\n\t\t\tconst isNavigation = () =>\n\t\t\t\trequest.method === \"GET\" && !isAfterAction && !request.signal.aborted;\n\t\t\tif (isNavigation() && watch()?.isStale() === true) {\n\t\t\t\treturn load(request, target, { navigationType });\n\t\t\t}\n\t\t\tconst { response, isNew } = await send();\n\t\t\tif (!isNew || !isNavigation()) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn load(request, target, { response, navigationType });\n\t\t},\n\t\tinstrumentation: {\n\t\t\trouter: ({ instrument }) => {\n\t\t\t\twatch();\n\t\t\t\tinstrument({\n\t\t\t\t\tnavigate: async (handler, { to, formMethod }) => {\n\t\t\t\t\t\t// Why claimed: a history step and a form submission are not a page load to take over.\n\t\t\t\t\t\tconst current = {\n\t\t\t\t\t\t\thash: hashOf(to),\n\t\t\t\t\t\t\tclaimed: typeof to === \"number\" || (formMethod ?? \"GET\").toUpperCase() !== \"GET\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnavigating = current;\n\t\t\t\t\t\tawait handler();\n\t\t\t\t\t\t// Why keep an unclaimed call: a blocker stops it, and `blocker.proceed()` starts it\n\t\t\t\t\t\t// again with no `navigate` call.\n\t\t\t\t\t\tif (navigating === current && current.claimed) {\n\t\t\t\t\t\t\tnavigating = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmiddleware: async (args, next) => {\n\t\t\tconst {\n\t\t\t\trequest,\n\t\t\t\tunstable_initiator: initiator,\n\t\t\t\tunstable_navigationType: navigationType,\n\t\t\t} = args as MiddlewareArgs;\n\t\t\tconst current = navigating;\n\t\t\tif (initiator === \"navigation\") {\n\t\t\t\t// Why here: a `clientAction` sends no request, and the router runs the middleware once\n\t\t\t\t// for an action and once for all the loaders after it.\n\t\t\t\tconst path = new URL(request.url).pathname;\n\t\t\t\tconst mark = action;\n\t\t\t\tif (navigationType === \"POP\") {\n\t\t\t\t\taction = undefined;\n\t\t\t\t} else if (request.method !== \"GET\") {\n\t\t\t\t\tconst started = { path, loading: false };\n\t\t\t\t\taction = started;\n\t\t\t\t\tonAbort(request.signal, () => {\n\t\t\t\t\t\tif (action === started) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn next();\n\t\t\t\t} else if (mark?.path === path) {\n\t\t\t\t\tmark.loading = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (action === mark) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (mark?.loading === false) {\n\t\t\t\t\t// Why: a redirect after the action goes to another page, and its loaders never run.\n\t\t\t\t\t// Why not while they run: the router revalidates the fetchers next to them.\n\t\t\t\t\taction = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Why no history step: it comes from no `navigate` call, and the fetch hook reloads it.\n\t\t\t// Why the first call only: the router runs the middleware of a navigation before the\n\t\t\t// fetchers that it revalidates, and they have the same initiator.\n\t\t\tif (\n\t\t\t\tinitiator !== \"navigation\" ||\n\t\t\t\tnavigationType == null ||\n\t\t\t\tnavigationType === \"POP\" ||\n\t\t\t\tcurrent == null ||\n\t\t\t\tcurrent.claimed\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tcurrent.claimed = true;\n\t\t\tcurrent.page = pageOf(request.url);\n\t\t\tif (\n\t\t\t\trequest.signal.aborted ||\n\t\t\t\twatch()?.isStale() !== true ||\n\t\t\t\tpageOf(request.url) === pageOf(location.href)\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\treturn load(request, request.url + current.hash, { navigationType });\n\t\t},\n\t};\n}\n\n/**\n * Moves an open TanStack Router tab to a new build at a navigation, so the\n * old client code never renders data from the new server, and the page that\n * the visitor reads never reloads. Call it with the router on the client.\n *\n * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router\n * moves history and runs its blockers before it.\n * - When a GET response from a new build comes back while a navigation\n * runs, such as from a server function in a loader, the browser loads the\n * page as a document.\n * - When the tab already knows of a new build, a navigation to a new path or\n * query clears the router cache and loads the page as a document.\n * - A request outside a navigation gets its response, and only marks the tab.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n * It returns a function that stops it and gives back `fetch`. If the app\n * wrapped `fetch` after it, the wrapper stays, and each request passes on.\n *\n * @example\n * // src/router.tsx\n * export function getRouter() {\n * \tconst router = createRouter({ routeTree });\n * \tif (!router.isServer) {\n * \t\tstaleBuildTanStack(router);\n * \t}\n * \treturn router;\n * }\n */\nexport function staleBuildTanStack(\n\trouter: NavigationEvents,\n\toptions: StaleBuildOptions = {},\n): () => void {\n\tconst watch = watchBuild(options);\n\tif (watch == null) {\n\t\treturn () => {};\n\t}\n\t/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */\n\tlet navigation: { leaving: boolean } | undefined;\n\tconst reload = async (current: { leaving: boolean }, response?: Response) => {\n\t\tif (current.leaving) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<Response>(() => {});\n\t\t}\n\t\tcurrent.leaving = true;\n\t\t// Why flush: the router's history moves the browser's URL in a microtask, after\n\t\t// `onBeforeNavigate`. A reload before that loads the page that the visitor leaves.\n\t\trouter.history.flush();\n\t\treturn loadDocument(location.href, { response });\n\t};\n\tconst unsubscribe = [\n\t\trouter.subscribe(\"onBeforeNavigate\", ({ fromLocation, toLocation }) => {\n\t\t\t// Why clear first: a change to the fragment replaces a navigation that has not ended.\n\t\t\tnavigation = undefined;\n\t\t\tif (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnavigation = { leaving: false };\n\t\t\tif (watch.isStale()) {\n\t\t\t\t// Why clear: the router matches the target after this event, and a preload can hold the\n\t\t\t\t// new build's data. With no cache, each loader fetches again, and `fetch` holds it.\n\t\t\t\trouter.clearCache();\n\t\t\t\tvoid reload(navigation);\n\t\t\t}\n\t\t}),\n\t\trouter.subscribe(\"onResolved\", () => {\n\t\t\tnavigation = undefined;\n\t\t}),\n\t];\n\tconst send = globalThis.fetch;\n\tlet isStopped = false;\n\tconst patched: typeof fetch = async (input, init) => {\n\t\tif (isStopped) {\n\t\t\treturn send.call(globalThis, input, init);\n\t\t}\n\t\tconst isGet = methodOf(input, init) === \"GET\";\n\t\tif (isGet && navigation != null && watch.isStale()) {\n\t\t\treturn reload(navigation);\n\t\t}\n\t\tconst response = await send.call(globalThis, input, init);\n\t\t// Why the navigation at the response: a navigation can take the pending loader of a preload,\n\t\t// or of the navigation that it replaced.\n\t\tif (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) {\n\t\t\treturn response;\n\t\t}\n\t\treturn reload(navigation, response);\n\t};\n\tglobalThis.fetch = patched;\n\treturn () => {\n\t\tfor (const stop of unsubscribe) {\n\t\t\tstop();\n\t\t}\n\t\twatch.stop();\n\t\tisStopped = true;\n\t\tnavigation = undefined;\n\t\t// Why check: a wrapper that the app adds later still calls this one, and must stay.\n\t\tif (globalThis.fetch === patched) {\n\t\t\tglobalThis.fetch = send;\n\t\t}\n\t};\n}\n"],"mappings":";;;;AAmDA,SAAS,MAAM,KAAsB;CACpC,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,SAAS;AACxD;;AAGA,SAAS,YAAY,SAAmD;CACvE,OACC,QACE,QACC,UAA8C,kBAAkB,SAAS,MAAM,MAAM,IAAI,CAC3F,CAAC,CAGA,QAAQ,UAAU,MAAM,cAAc,cAAc,MAAM,kBAAkB,CAAC,CAAC,CAC9E,SAAS,UAAU,MAAM,YAAY,CAAC,CACtC,MAAM,WAAW,OAAO,SAAS,eAAe,CAAC,EAAE;AAEvD;;AAGA,SAAS,YAAY,QAA2C;CAC/D,MAAM,EAAE,QAAQ,UACf,oBAAoB,MAAM,CAAC,CACzB,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,EACtC,MAAM,qEAAqE,CAAC,EAAE,UAAU,CAAC;CAC7F,OAAO,QAAQ,WAAW,kBAAkB,SAAS,KAAK;AAC3D;;AAGA,SAAS,OAAO,KAAqB;CACpC,MAAM,EAAE,QAAQ,UAAU,WAAW,IAAI,IAAI,KAAK,SAAS,IAAI;CAC/D,OAAO,GAAG,SAAS,WAAW;AAC/B;;AAGA,SAAS,UAAU,EAAE,UAAU,aAAoC;CAClE,OAAO,GAAG,WAAW;AACtB;;AAGA,SAAS,MAAM,OAAkC;CAChD,OAAO,iBAAiB,UAA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UAAU,MAAM,OAAO,CAAC,CAAC,YAAY,MAAS;GACnD,OAAO,IAAI,cAAwB,CAAC,CAAC;EACtC;EACA,QAAQ,UAAU;EAGlB,OAAO,QAAQ,MAAM;EACrB,OAAO,aAAa,SAAS,MAAM,EAAE,SAAS,CAAC;CAChD;CACA,MAAM,cAAc,CACnB,OAAO,UAAU,qBAAqB,EAAE,cAAc,iBAAiB;EAEtE,aAAa;EACb,IAAI,gBAAgB,QAAQ,UAAU,YAAY,MAAM,UAAU,UAAU,GAC3E;EAED,aAAa,EAAE,SAAS,MAAM;EAC9B,IAAI,MAAM,QAAQ,GAAG;GAGpB,OAAO,WAAW;GAClB,AAAK,OAAO,UAAU;EACvB;CACD,CAAC,GACD,OAAO,UAAU,oBAAoB;EACpC,aAAa;CACd,CAAC,CACF;CACA,MAAM,OAAO,WAAW;CACxB,IAAI,YAAY;CAChB,MAAM,UAAwB,OAAO,OAAO,SAAS;EACpD,IAAI,WACH,OAAO,KAAK,KAAK,YAAY,OAAO,IAAI;EAEzC,MAAM,QAAQ,SAAS,OAAO,IAAI,MAAM;EACxC,IAAI,SAAS,cAAc,QAAQ,MAAM,QAAQ,GAChD,OAAO,OAAO,UAAU;EAEzB,MAAM,WAAW,MAAM,KAAK,KAAK,YAAY,OAAO,IAAI;EAGxD,IAAI,CAAC,MAAM,MAAM,UAAU,MAAM,KAAK,CAAC,KAAK,CAAC,SAAS,cAAc,MACnE,OAAO;EAER,OAAO,OAAO,YAAY,QAAQ;CACnC;CACA,WAAW,QAAQ;CACnB,aAAa;EACZ,KAAK,MAAM,QAAQ,aAClB,KAAK;EAEN,MAAM,KAAK;EACX,YAAY;EACZ,aAAa;EAEb,IAAI,WAAW,UAAU,SACxB,WAAW,QAAQ;CAErB;AACD"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../src/client/csp-nonce.ts"],"sourcesContent":["import { requestContext } from \"../core/request-context.js\";\nimport { documentNonce } from \"./document-nonce.js\";\n\n/**\n * The CSP nonce of the document, for the framework's render. It gives the\n * same value on the server and in the browser, so the hydration matches.\n *\n * - On the server, the nonce of the request that runs, from `requestContext()`.\n * - In the browser, the nonce of the document's first element with a nonce.\n * Why: React Router's `<HydratedRouter>` takes no nonce, so the app reads it\n * from the document.\n *\n * It gives `undefined` when the page has no nonce: with no\n * `contentSecurityPolicy` plugin, during a prerender, and on a prerendered page.\n * A bundler that resolves the `browser` condition, such as Vite for the\n * client, gets a build with no server code.\n *\n * @example\n * <Scripts nonce={cspNonce()} />\n */\nexport function cspNonce(): string | undefined {\n\treturn typeof document === \"undefined\" ? requestContext()?.cspNonce : documentNonce();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,WAA+B;CAC9C,OAAO,OAAO,aAAa,cAAc,eAAe,CAAC,EAAE,WAAW,cAAc;AACrF"}
@@ -1,3 +1,4 @@
1
+ import { r as withRequestContext } from "./request-context-BtQ87VYb.js";
1
2
  import { a as replaceResponse, o as withHeaderHook, r as hookedHeaders, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
2
3
  import { o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
3
4
  import { i as requestLogger, r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
@@ -5,7 +6,6 @@ import { n as finishResponse, r as onResponseSent } from "./response-edge-Bc1-C_
5
6
  import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-7_gToa8R.js";
6
7
  import { i as isFilePath$1, n as findStaticFile, o as staticResponse, s as withVary, t as contentType } from "./static-files-Beju9riB.js";
7
8
  import { n as manifestKey } from "./build-manifest-UDNk81Ce.js";
8
- import { r as withRequestContext } from "./request-context-BtQ87VYb.js";
9
9
  import { Hono } from "hono";
10
10
  import { HTTPException } from "hono/http-exception";
11
11
  import { matchedRoutes } from "hono/route";
@@ -856,13 +856,18 @@ function assets() {
856
856
  }
857
857
  const REVALIDATE = "public, max-age=0, must-revalidate";
858
858
  const ONE_HOUR = "public, max-age=3600, stale-while-revalidate=86400";
859
- /** The default markdown twin of a page: `/docs/button.md` for `/docs/button`, and `/index.md` for `/`. */
860
- function defaultTwinOf(path) {
861
- return `${trimTrailingSlashes(path) || "/index"}.md`;
859
+ /**
860
+ * The default markdown twin of a page: `/docs/button.md` for `/docs/button`,
861
+ * and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends
862
+ * it to another file or to the framework, so the page's twin does not match
863
+ * its answer.
864
+ */
865
+ function defaultTwinOf(path, rewritten) {
866
+ return rewritten === path ? `${trimTrailingSlashes(path) || "/index"}.md` : void 0;
862
867
  }
863
- /** The file of the markdown twin of `path`, or `undefined` when the page has none. */
864
- async function findTwin(files, path, twinOf) {
865
- const twinPath = twinOf?.(path);
868
+ /** The file of the markdown twin of the request, or `undefined` when the page has none. */
869
+ async function findTwin(files, context, { twinOf, rewritten }) {
870
+ const twinPath = twinOf?.(context.req.path, rewritten, context);
866
871
  const file = twinPath == null ? void 0 : await findStaticFile(files, twinPath);
867
872
  return twinPath == null || file == null ? void 0 : {
868
873
  path: twinPath,
@@ -893,10 +898,10 @@ function linkToTwin(context, twinPath) {
893
898
  * in `prerenderedPaths`, an error, or an answer that is not markdown sends the
894
899
  * request on for the HTML.
895
900
  */
896
- function developmentTwins(twinOf, skip, prerenderedPaths) {
901
+ function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
897
902
  return async (context, next) => {
898
903
  const { method, path } = context.req;
899
- const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path) : void 0;
904
+ const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.(path, context) ?? path, context) : void 0;
900
905
  if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
901
906
  const url = new URL(context.req.url);
902
907
  url.pathname = urlPath(twinPath);
@@ -917,11 +922,12 @@ function developmentTwins(twinOf, skip, prerenderedPaths) {
917
922
  varyOnAccept(context);
918
923
  };
919
924
  }
920
- /** The `twinOf` function that the `markdownTwins` option selects, or `undefined` when it is off. */
925
+ /** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */
921
926
  function twinOfOption(markdownTwins) {
922
927
  if (markdownTwins === true) return defaultTwinOf;
923
928
  if (markdownTwins == null || markdownTwins === false) return;
924
- return markdownTwins.twinOf;
929
+ const { twinOf } = markdownTwins;
930
+ return (path, _rewritten, context) => twinOf(path, context);
925
931
  }
926
932
  /**
927
933
  * Serves the client build: prerendered pages at their own URL with a 200,
@@ -948,7 +954,7 @@ function prerendered(options = {}) {
948
954
  const twinOf = twinOfOption(options.markdownTwins);
949
955
  if (info.mode === "development") {
950
956
  const paths = info.prerenderedPaths;
951
- stage = twinOf == null ? void 0 : developmentTwins(twinOf, options.skip, paths == null ? void 0 : new Set(paths));
957
+ stage = twinOf == null ? void 0 : developmentTwins(twinOf, options, paths == null ? void 0 : new Set(paths));
952
958
  return;
953
959
  }
954
960
  const { files, contentTypes, capturedHeaders } = info;
@@ -973,9 +979,13 @@ function prerendered(options = {}) {
973
979
  stage = async (context, next) => {
974
980
  const { method } = context.req;
975
981
  if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
976
- const twin = await findTwin(files, context.req.path, twinOf);
982
+ const rewritten = options.rewrite?.(context.req.path, context) ?? context.req.path;
983
+ const twin = await findTwin(files, context, {
984
+ twinOf,
985
+ rewritten
986
+ });
977
987
  const preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : void 0;
978
- const path = preferred?.path ?? options.rewrite?.(context.req.path, context) ?? context.req.path;
988
+ const path = preferred?.path ?? rewritten;
979
989
  const file = preferred?.file ?? await findStaticFile(files, path);
980
990
  if (file == null) await next();
981
991
  else context.res = await serve(context, path, file);
@@ -1406,4 +1416,4 @@ function serverInternals(app) {
1406
1416
  }
1407
1417
 
1408
1418
  export { abortShutdownSignal as _, streamingCompress as a, accessLog as b, prefersMarkdown as c, securityHeaders as d, redirects as f, health as g, noindex as h, withForwardedProto as i, requestId as l, privateDocuments as m, defaultPlugins as n, assets as o, trailingSlash as p, serverInternals as r, prerendered as s, createServer as t, contentSecurityPolicy as u, shutdownSignal as v, bodyLimit as y };
1409
- //# sourceMappingURL=create-server-iE1-s6Bi.js.map
1419
+ //# sourceMappingURL=create-server-D0De6R7Q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-server-D0De6R7Q.js","names":["isFilePath"],"sources":["../src/core/plugins/access-log.ts","../src/core/plugins/body-limit.ts","../src/core/shutdown.ts","../src/core/plugins/health.ts","../src/core/plugins/noindex.ts","../src/core/plugins/private-documents.ts","../src/core/safe-local-path.ts","../src/core/plugins/trailing-slash.ts","../src/core/plugins/redirects.ts","../src/core/plugins/security-headers.ts","../src/core/plugins/request-id.ts","../src/core/prefers-markdown.ts","../src/core/plugins/static.ts","../src/core/plugins/streaming-compress.ts","../src/core/create-server.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { errorAttributes } from \"../log.js\";\nimport { onResponseSent } from \"../response-edge.js\";\nimport type { AppServerEnv, Plugin, SentResponse } from \"../types.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n\t/**\n\t * More attributes for each request line, such as the app's user ID. It\n\t * runs when the line goes out, with what went out. Read a response header\n\t * from `sent.headers`, not from `c.res`, which can lack the changes of the\n\t * header hooks.\n\t */\n\tattributes?: (\n\t\tcontext: Context<AppServerEnv>,\n\t\tsent: SentResponse,\n\t) => Readonly<Record<string, unknown>>;\n\t/**\n\t * Set `Server-Timing: app;dur=<ms>` on each HTML document: the time until\n\t * the response headers were ready. The browser's DevTools show it.\n\t * @default false\n\t */\n\tserverTiming?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = [...url.searchParams.keys()]\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the response ends or the client\n * disconnects, so a streamed response logs its full duration and size. It\n * logs the response that leaves the server, after each stage. A listener\n * with an `edge`, such as the node listener, counts the bytes.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({\n\tredactQuery = true,\n\tattributes,\n\tserverTiming = false,\n}: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\t// Why a hook: it runs when the head is ready, which is the time that the header gives.\n\t\t\tawait (serverTiming\n\t\t\t\t? withHeaderHook(context, next, (headers) => {\n\t\t\t\t\t\tif (headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) {\n\t\t\t\t\t\t\theaders.append(\n\t\t\t\t\t\t\t\t\"Server-Timing\",\n\t\t\t\t\t\t\t\t`app;dur=${(performance.now() - started).toFixed(1)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: next());\n\t\t\t// Why a catch: a log line must never change the response or stop its stream. The listener can\n\t\t\t// call the report from an event of its socket, where a throw stops the process.\n\t\t\tonResponseSent(context, (sent) => {\n\t\t\t\tconst line = lineAttributes(context, sent, started);\n\t\t\t\ttry {\n\t\t\t\t\tcontext\n\t\t\t\t\t\t.get(\"logger\")\n\t\t\t\t\t\t.info(\"request\", attributes == null ? line : { ...line, ...attributes(context, sent) });\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontext.get(\"logger\").error(\"access log attributes failed\", {\n\t\t\t\t\t\t\t...line,\n\t\t\t\t\t\t\t...errorAttributes(error),\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Why drop it: the sink failed twice, so no line can go out.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n\n\t/** `href` as {@link loggedUrl} logs it. */\n\tfunction requestUrl(href: string): string {\n\t\tconst start = href.indexOf(\"/\", href.indexOf(\"//\") + 2);\n\t\t// Why no parse for a path alone: a request URL is the `href` of a parsed URL, or one that the\n\t\t// Node.js listener checked holds no character that a parse changes. So its path is the `pathname`.\n\t\tif (start !== -1 && !href.includes(\"?\", start) && !href.includes(\"#\", start)) {\n\t\t\treturn href.slice(start);\n\t\t}\n\t\treturn loggedUrl(new URL(href), { redact: redactQuery });\n\t}\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ status, bytes, aborted }: SentResponse,\n\t\tstarted: number,\n\t): Record<string, unknown> {\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.url\": requestUrl(context.req.url),\n\t\t\t\"http.status_code\": status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.get(\"clientAddress\"),\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t};\n\t\tif (aborted) {\n\t\t\tline[\"http.client_aborted\"] = true;\n\t\t}\n\t\treturn line;\n\t}\n}\n","import { HTTPException } from \"hono/http-exception\";\nimport { replaceResponse } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n// Why: GET and HEAD have no body, and the Fetch `Request` constructor rejects the other three.\nconst NO_BODY_METHODS = new Set([\"GET\", \"HEAD\", \"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/** Options for {@link bodyLimit}. */\nexport type BodyLimitOptions = {\n\t/** The largest request body, in bytes. */\n\tmaxBytes: number;\n};\n\n/** The 413 response. */\nfunction tooLarge(): Response {\n\treturn new Response(\"Payload Too Large\", { status: 413 });\n}\n\n/**\n * Sends a 413 for a request body that is larger than `maxBytes`. A request\n * whose `Content-Length` is too large gets the 413 before the app reads the\n * body, and a request whose `Content-Length` fits goes on unchanged. A\n * streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response\n * becomes a 413. When the app streams the body into its response, the\n * response stream errors. A `maxBytes` that is not a whole number of 0 or\n * more stops startup.\n *\n * Why not `hono/body-limit`: it reads a streamed body into memory before the\n * next stage runs, so an upload cannot stream.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });\n */\nexport function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin {\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {\n\t\tthrow new RangeError(`bodyLimit needs a maxBytes of 0 or more whole bytes, not ${maxBytes}.`);\n\t}\n\treturn {\n\t\tname: \"body-limit\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { raw } = context.req;\n\t\t\tif (NO_BODY_METHODS.has(raw.method)) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst length = context.req.header(\"Content-Length\");\n\t\t\t// Why no stream count: the host's HTTP parser ends the body at its `Content-Length`. The\n\t\t\t// original request also keeps the fast body reads of `@hono/node-server`.\n\t\t\tif (\n\t\t\t\tlength != null &&\n\t\t\t\t/^\\d+$/u.test(length) &&\n\t\t\t\tcontext.req.header(\"Transfer-Encoding\") == null\n\t\t\t) {\n\t\t\t\treturn Number(length) > maxBytes ? tooLarge() : next();\n\t\t\t}\n\t\t\tlet bytes = 0;\n\t\t\tlet exceeded = false;\n\t\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\t\tconst limited = new ReadableStream<Uint8Array>(\n\t\t\t\t{\n\t\t\t\t\tasync pull(controller) {\n\t\t\t\t\t\t// Why on the first read: on Node, `raw.body` starts to read the socket, and a dev\n\t\t\t\t\t\t// server middleware that answers the request reads it there.\n\t\t\t\t\t\treader ??= raw.body?.getReader();\n\t\t\t\t\t\tconst chunk = await reader?.read();\n\t\t\t\t\t\tif (chunk == null || chunk.done) {\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbytes += chunk.value.byteLength;\n\t\t\t\t\t\tif (bytes > maxBytes) {\n\t\t\t\t\t\t\texceeded = true;\n\t\t\t\t\t\t\t// Why an `HTTPException`: `onError` sends its 413 and logs no error.\n\t\t\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\t\t\tnew HTTPException(413, {\n\t\t\t\t\t\t\t\t\tmessage: \"The request body is larger than the body limit.\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait reader?.cancel();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk.value);\n\t\t\t\t\t},\n\t\t\t\t\t// Why `raw.body`: if the app cancels before its first read, no reader exists yet.\n\t\t\t\t\tcancel: async (reason) => (reader ?? raw.body)?.cancel(reason),\n\t\t\t\t},\n\t\t\t\t// Why 0: the stream reads nothing until the app reads it.\n\t\t\t\t{ highWaterMark: 0 },\n\t\t\t);\n\t\t\t// Why a new request from its parts: `new Request(raw)` reads `raw.body` on Node. `duplex`: a\n\t\t\t// request with a stream body needs it, and the DOM types lack it.\n\t\t\tconst init: RequestInit & { duplex: \"half\" } = {\n\t\t\t\tmethod: raw.method,\n\t\t\t\theaders: raw.headers,\n\t\t\t\tsignal: raw.signal,\n\t\t\t\tbody: limited,\n\t\t\t\tduplex: \"half\",\n\t\t\t};\n\t\t\tcontext.req.raw = new Request(raw.url, init);\n\t\t\tawait next();\n\t\t\tif (exceeded) {\n\t\t\t\tawait context.res.body?.cancel();\n\t\t\t\treplaceResponse(context, tooLarge());\n\t\t\t}\n\t\t},\n\t};\n}\n","let controller = new AbortController();\nlet stopping = false;\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted, and clears {@link isStopping}. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n\tstopping = false;\n}\n\n/** Marks the server as stopping, before the shutdown delay and the drain. */\nexport function markStopping(): void {\n\tstopping = true;\n}\n\n/** Whether the server got a stop signal. It is true during the shutdown delay, before {@link shutdownSignal} aborts. */\nexport function isStopping(): boolean {\n\treturn stopping;\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import { errorAttributes } from \"../log.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport { isStopping } from \"../shutdown.js\";\nimport type { Plugin, RequestLogger } from \"../types.js\";\n\n/** Options for {@link health}. */\nexport type HealthOptions = {\n\t/** @default \"/livez\" */\n\tlivePath?: string;\n\t/** @default \"/readyz\" */\n\treadyPath?: string;\n\t/**\n\t * An app check for readiness, such as a database ping. A `false` or a\n\t * throw makes the server not ready. When the check starts to fail, one\n\t * warn line goes to the log, and when it passes again, one info line.\n\t */\n\tready?: () => boolean | Promise<boolean>;\n};\n\n/** A probe answer that no cache keeps. */\nfunction probe(text: string, status: 200 | 503): Response {\n\treturn new Response(text, {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\", \"Cache-Control\": \"no-store\" },\n\t});\n}\n\n/**\n * Answers the liveness and readiness probes of a load balancer or\n * Kubernetes. `livePath` always answers 200. `readyPath` answers 200 until\n * the server gets a stop signal, then 503. With `shutdownDelayMs` on\n * `createServer`, the listeners serve on for that time, so the load\n * balancer removes the server before the drain starts.\n *\n * `defaultPlugins()` runs it first, so a probe skips the access log. Its\n * `health` option takes these options, and `false` turns it off.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ health: { ready: async () => db.ping() } }),\n * \tshutdownDelayMs: 5_000,\n * });\n */\nexport function health({\n\tlivePath = \"/livez\",\n\treadyPath = \"/readyz\",\n\tready,\n}: HealthOptions = {}): Plugin {\n\t// Why log on a change only: a probe comes every few seconds.\n\tlet appFailing = false;\n\tconst appCheck = async (logger: RequestLogger): Promise<boolean> => {\n\t\tif (ready == null) {\n\t\t\treturn true;\n\t\t}\n\t\tlet passed = false;\n\t\tlet failure: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tpassed = await ready();\n\t\t} catch (error) {\n\t\t\tfailure = errorAttributes(error);\n\t\t}\n\t\tif (!passed && !appFailing) {\n\t\t\tlogger.warn(\"readiness check failed\", failure);\n\t\t} else if (passed && appFailing) {\n\t\t\tlogger.info(\"readiness check passed\");\n\t\t}\n\t\tappFailing = !passed;\n\t\treturn passed;\n\t};\n\tconst isReady = async (logger: RequestLogger) => {\n\t\tif (isStopping()) {\n\t\t\treturn false;\n\t\t}\n\t\tconst appReady = await appCheck(logger);\n\t\t// Why check again: a stop signal can come while the app check runs.\n\t\treturn appReady && !isStopping();\n\t};\n\treturn optionPlugin(\"health\", {\n\t\tname: \"health\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method, path } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tif (path === livePath) {\n\t\t\t\treturn probe(\"ok\", 200);\n\t\t\t}\n\t\t\tif (path === readyPath) {\n\t\t\t\treturn (await isReady(context.get(\"logger\"))) ? probe(\"ok\", 200) : probe(\"not ready\", 503);\n\t\t\t}\n\t\t\treturn next();\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin } from \"../types.js\";\n\n/**\n * Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search\n * engine does not index a preview deploy. Turn it on from the environment\n * with the `noindex` option of `defaultPlugins()`, which puts it before the\n * static stages, so it also sees prerendered pages.\n *\n * @example\n * defaultPlugins({ noindex: process.env.PREVIEW === \"1\" });\n */\nexport function noindex(): Plugin {\n\treturn optionPlugin(\"noindex\", {\n\t\tname: \"noindex\",\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tresponse.set(\"X-Robots-Tag\", \"noindex, nofollow\");\n\t\t\t}),\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/**\n * Sets `Cache-Control: private, no-cache` on each HTML document and each\n * framework data response, such as a React Router `.data` request, that has\n * no `Cache-Control`. A shared cache then never keeps a page or loader data\n * that the server rendered for one user. A response with its own\n * `Cache-Control` keeps it. A resource route that sends per-user JSON sets\n * its own `Cache-Control`.\n *\n * Put it after the static stages, so it sees only the responses of the app's\n * routes and the framework. `defaultPlugins()` puts it last.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });\n */\nexport function privateDocuments(): Plugin {\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn {\n\t\tname: \"private-documents\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t},\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (headers) => {\n\t\t\t\tif (\n\t\t\t\t\t!headers.has(\"Cache-Control\") &&\n\t\t\t\t\t((headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) ||\n\t\t\t\t\t\tisDataRequest(context.req.path))\n\t\t\t\t) {\n\t\t\t\t\theaders.set(\"Cache-Control\", \"private, no-cache\");\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n","/**\n * Whether `value` is a safe same-origin path for a `Location` header. The\n * value starts with one `/`, the next character is not `/` or `\\`, and each\n * character is printable ASCII (0x20 to 0x7E).\n *\n * The check stops these attacks:\n *\n * - An open redirect: `//evil.com`, `/\\evil.com`, and `https://evil.com` go to\n * another host. A browser reads `/\\` as `//`.\n * - A scheme that does not navigate, such as `javascript:` or `data:`.\n * - A control character, such as CR or LF, that splits the response.\n *\n * Why strict: a short allow list is easy to audit. The check rejects some safe\n * values, such as a path with raw UTF-8. Percent-encode the path first.\n *\n * Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.\n *\n * @example\n * isSafeLocalPath(\"/components/button?tab=props\"); // => true\n * isSafeLocalPath(\"//evil.com/foo\"); // => false\n * isSafeLocalPath(\"/café\"); // => false\n */\nexport function isSafeLocalPath(value: string): boolean {\n\treturn /^\\/(?![/\\\\])/u.test(value) && !/[^\\u0020-\\u007E]/u.test(value);\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { matchedRoutes } from \"hono/route\";\nimport { isSafeLocalPath } from \"../safe-local-path.js\";\nimport { findStaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\n\n/**\n * How a page URL ends:\n *\n * - `never`: with no trailing slash, such as `/docs/button`.\n * - `always`: with a trailing slash, such as `/docs/button/`.\n * - `preserve`: as the request has it. The server sends no redirect.\n */\nexport type TrailingSlash = \"never\" | \"always\" | \"preserve\";\n\n/** Options for {@link trailingSlash}. */\nexport type TrailingSlashOptions = {\n\tmode: TrailingSlash;\n};\n\n/** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */\nfunction isFilePath(path: string): boolean {\n\treturn path.slice(path.lastIndexOf(\"/\") + 1).includes(\".\");\n}\n\n/** `path` with no trailing slashes. Why a scan, not `/\\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */\nexport function trimTrailingSlashes(path: string): string {\n\tlet end = path.length;\n\twhile (end > 0 && path[end - 1] === \"/\") {\n\t\tend -= 1;\n\t}\n\treturn path.slice(0, end);\n}\n\n/** The URL path in `mode`, or the path unchanged when `mode` keeps it. */\nfunction canonicalPath(path: string, mode: TrailingSlash): string {\n\tconst trimmed = trimTrailingSlashes(path);\n\tif (trimmed === \"\") {\n\t\treturn \"/\";\n\t}\n\tif (mode === \"never\") {\n\t\treturn trimmed;\n\t}\n\tif (mode === \"always\") {\n\t\treturn `${trimmed}/`;\n\t}\n\treturn path;\n}\n\n/**\n * Whether one of the app's own Hono routes matches the request. Why the\n * path: the plugins and the framework match at `/*`, and Hono matches a\n * route path strictly, so a redirect would move the request off its route.\n */\nfunction hasAppRoute(context: Context<AppServerEnv>): boolean {\n\treturn matchedRoutes(context).some((route) => route.path !== \"/*\");\n}\n\n/** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */\nasync function isStaticFile(files: StaticFiles, path: string): Promise<boolean> {\n\treturn (await findStaticFile(files, path))?.path === path;\n}\n\n/**\n * Sends a 308 from a page URL to the same URL in `mode`, so each page has one\n * URL. It applies to rendered and prerendered pages, because the server cannot\n * tell which paths have a route. The redirect keeps the query string.\n *\n * It sends no redirect for `/`, a method other than GET or HEAD, a data\n * request of the framework, a path that one of the app's own Hono routes\n * matches, such as `app.get(\"/livez\")`, or a path that already has the\n * mode's form. `always` adds no slash to a file in the client build, such as\n * `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.\n *\n * Set the same mode in the framework's router when it has one. Else the two\n * redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`\n * back to `/x`. For TanStack Start, check the mode against the router with\n * `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router\n * has no trailing-slash option, so it answers both forms itself.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ trailingSlash: \"always\" }) });\n */\nexport function trailingSlash({ mode }: TrailingSlashOptions): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"trailing-slash\",\n\t\tsetup: (info) => {\n\t\t\tif (mode === \"preserve\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (\n\t\t\t\t\t(method !== \"GET\" && method !== \"HEAD\") ||\n\t\t\t\t\tinfo.isDataRequest(context.req.path) ||\n\t\t\t\t\thasAppRoute(context)\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\t\tconst url = new URL(context.req.url);\n\t\t\t\tconst path = canonicalPath(url.pathname, mode);\n\t\t\t\tconst location = `${path}${url.search}`;\n\t\t\t\t// Why the check: a path such as `//evil.com/` must not make a `Location` to another host.\n\t\t\t\tif (path === url.pathname || !isSafeLocalPath(location)) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the decoded path: `/llms%2Etxt` names the file `/llms.txt`.\n\t\t\t\tif (\n\t\t\t\t\tmode === \"always\" &&\n\t\t\t\t\t(isFilePath(context.req.path) || (await isStaticFile(info.files, context.req.path)))\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn context.redirect(location, 308);\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { isSafeLocalPath } from \"../safe-local-path.js\";\nimport type { Plugin } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\nimport type { TrailingSlash } from \"./trailing-slash.js\";\n\n/** One redirect of a {@link redirects} table. */\nexport type RedirectRule = {\n\t/**\n\t * The old URL path. A `:name` segment matches one path segment, and a `*`\n\t * last segment matches the rest of the path, or nothing: `/docs/*` also\n\t * matches `/docs`. A trailing slash does not change the match. Write the\n\t * path as it is in the URL, percent-encoded.\n\t */\n\tfrom: string;\n\t/**\n\t * The new URL: a local path, or an absolute `http` or `https` URL. It can\n\t * use each `:name` and the `*` of `from`. An absolute URL is\n\t * percent-encoded as UTF-8.\n\t */\n\tto: string;\n\t/** @default 301 */\n\tstatus?: 301 | 308;\n};\n\n/** A rule, compiled at startup. */\ntype CompiledRule = {\n\t/** The `from` path with no trailing slash. */\n\tkey: string;\n\tpattern: RegExp | undefined;\n\tto: string;\n\tstatus: 301 | 308;\n\t/** The origin of an absolute `to`, else `undefined`. */\n\torigin: string | undefined;\n\t/** The position of the rule in the table. */\n\tindex: number;\n};\n\nconst PARAM = /^:(?<name>[A-Za-z_]\\w*)$/u;\nconst TARGET_TOKEN = /:(?<name>[A-Za-z_]\\w*)|\\*/gu;\n\n/** `path` with no trailing slashes, and `/` for the root. */\nfunction matchKey(path: string): string {\n\treturn trimTrailingSlashes(path) || \"/\";\n}\n\n/** The pattern of `from`, with a named group for each `:name` and for `*`, or `undefined` for an exact path. */\nfunction compilePattern(from: string): { pattern: RegExp | undefined; names: Set<string> } {\n\tconst segments = matchKey(from).split(\"/\").slice(1);\n\tconst names = new Set<string>();\n\tconst parts = segments.map((segment, index) => {\n\t\tconst name = PARAM.exec(segment)?.groups?.name;\n\t\tif (name != null) {\n\t\t\tif (names.has(name)) {\n\t\t\t\tthrow new Error(`The redirect from ${from} uses :${name} twice.`);\n\t\t\t}\n\t\t\tnames.add(name);\n\t\t\treturn `/(?<${name}>[^/]+)`;\n\t\t}\n\t\tif (segment === \"*\") {\n\t\t\tif (index !== segments.length - 1) {\n\t\t\t\tthrow new Error(`The redirect from ${from} has a * that is not the last segment.`);\n\t\t\t}\n\t\t\tnames.add(\"*\");\n\t\t\t// Why `$`: a `:name` cannot have it, so the group name is free. Why optional: `/docs/*`\n\t\t\t// also moves `/docs`.\n\t\t\treturn \"(?:/(?<$splat>.*))?\";\n\t\t}\n\t\treturn `/${segment.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`)}`;\n\t});\n\treturn {\n\t\tpattern: names.size === 0 ? undefined : new RegExp(`^${parts.join(\"\")}$`, \"u\"),\n\t\tnames,\n\t};\n}\n\n/** Compiles a rule, and throws for a rule that is not valid, so a bad table stops startup. */\nfunction compileRule({ from, to, status = 301 }: RedirectRule, index: number): CompiledRule {\n\tif (!from.startsWith(\"/\")) {\n\t\tthrow new Error(`A redirect must be from a path that starts with \"/\", not ${from}.`);\n\t}\n\tconst { pattern, names } = compilePattern(from);\n\tfor (const token of to.matchAll(TARGET_TOKEN)) {\n\t\tconst name = token.groups?.name ?? \"*\";\n\t\tif (!names.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The redirect from ${from} to ${to} uses ${token[0]}, which ${from} does not have.`,\n\t\t\t);\n\t\t}\n\t}\n\tif (to.startsWith(\"/\")) {\n\t\tif (!isSafeLocalPath(to)) {\n\t\t\tthrow new Error(`The redirect from ${from} goes to ${to}, which is not a safe local path.`);\n\t\t}\n\t\treturn { key: matchKey(from), pattern, to, status, origin: undefined, index };\n\t}\n\tconst url = URL.parse(to);\n\tif (url == null || (url.protocol !== \"https:\" && url.protocol !== \"http:\")) {\n\t\tthrow new Error(`A redirect must go to a local path or an http(s) URL, not ${to}.`);\n\t}\n\t// Why `href`: a `Location` must be ASCII, and it percent-encodes the rest as UTF-8.\n\treturn { key: matchKey(from), pattern, to: url.href, status, origin: url.origin, index };\n}\n\n/** The target of `rule` for the values that its pattern matched. */\nfunction fill(to: string, groups: Readonly<Record<string, string | undefined>>): string {\n\tconst queryStart = to.indexOf(\"?\");\n\treturn to.replaceAll(TARGET_TOKEN, (token, name: string | undefined, offset: number) => {\n\t\tconst value = name == null ? (groups.$splat ?? \"\") : (groups[name] ?? token);\n\t\t// Why: a path segment can have `&`, `=`, and `+`, but in a query they split or change the value.\n\t\treturn queryStart !== -1 && offset > queryStart\n\t\t\t? value.replaceAll(/[&+=]/gu, (char) => encodeURIComponent(char))\n\t\t\t: value;\n\t});\n}\n\n/** `target` with no trailing slash on its path, as the `never` mode of `trailingSlash` wants. */\nfunction withoutTrailingSlash(target: string): string {\n\tconst pathEnd = target.search(/[#?]/u);\n\tconst path = pathEnd === -1 ? target : target.slice(0, pathEnd);\n\tconst rest = pathEnd === -1 ? \"\" : target.slice(pathEnd);\n\treturn `${trimTrailingSlashes(path) || \"/\"}${rest}`;\n}\n\n/** `target` with the query string of the request added, before the fragment of `target`. */\nfunction withQuery(target: string, search: string): string {\n\tif (search === \"\") {\n\t\treturn target;\n\t}\n\tconst hashIndex = target.indexOf(\"#\");\n\tconst path = hashIndex === -1 ? target : target.slice(0, hashIndex);\n\tconst hash = hashIndex === -1 ? \"\" : target.slice(hashIndex);\n\treturn `${path}${path.includes(\"?\") ? `&${search.slice(1)}` : search}${hash}`;\n}\n\n/**\n * Sends a redirect from each old URL path in `rules` to its new URL, with\n * the query string. The first rule that matches wins. An exact path is a\n * map lookup. A rule with `:name` or `*` is a pattern.\n *\n * The rules compile at startup, and a rule that is not valid stops startup.\n * A local target must be a safe local path. An absolute target must keep the\n * origin that its rule names. A request whose values break either check goes\n * on to the next stage, and so does a request that is already at its\n * target. It applies to GET and HEAD only.\n *\n * Put it before `trailingSlash`, so `/old/` gets one redirect to the final\n * URL, and give it the same `trailingSlash` mode. In `never` mode, a local\n * target loses its trailing slash, so `trailingSlash` does not redirect it\n * again. `defaultPlugins({ redirects })` does both.\n *\n * @example\n * redirects([\n * \t{ from: \"/blog/:slug\", to: \"/articles/:slug\" },\n * \t{ from: \"/docs/*\", to: \"https://docs.example.com/*\", status: 308 },\n * ]);\n */\nexport function redirects(\n\trules: readonly RedirectRule[],\n\t{ trailingSlash = \"preserve\" }: { trailingSlash?: TrailingSlash } = {},\n): Plugin {\n\tconst compiled = rules.map((rule, index) => compileRule(rule, index));\n\tconst exact = new Map<string, CompiledRule>();\n\tfor (const rule of compiled.toReversed()) {\n\t\t// Why reversed: the first rule for a path wins.\n\t\tif (rule.pattern == null) {\n\t\t\texact.set(rule.key, rule);\n\t\t}\n\t}\n\tconst patterns = compiled.filter((rule) => rule.pattern != null);\n\tconst find = (path: string): { rule: CompiledRule; target: string } | undefined => {\n\t\tconst exactRule = exact.get(path);\n\t\tfor (const rule of patterns) {\n\t\t\tif (exactRule != null && rule.index > exactRule.index) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst groups = rule.pattern?.exec(path)?.groups;\n\t\t\tif (groups != null) {\n\t\t\t\treturn { rule, target: fill(rule.to, groups) };\n\t\t\t}\n\t\t}\n\t\treturn exactRule == null ? undefined : { rule: exactRule, target: exactRule.to };\n\t};\n\treturn {\n\t\tname: \"redirects\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\tconst url = new URL(context.req.url);\n\t\t\tconst found = find(matchKey(url.pathname));\n\t\t\tif (found == null) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst target =\n\t\t\t\ttrailingSlash === \"never\" && found.rule.origin == null\n\t\t\t\t\t? withoutTrailingSlash(found.target)\n\t\t\t\t\t: found.target;\n\t\t\tconst location = withQuery(target, url.search);\n\t\t\t// Why: a rule such as `/tags/:tag` to `/tags/:tag/` also matches its own target.\n\t\t\tif (new URL(location, url).href === url.href) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst safe =\n\t\t\t\tfound.rule.origin == null\n\t\t\t\t\t? isSafeLocalPath(location)\n\t\t\t\t\t: URL.parse(location)?.origin === found.rule.origin;\n\t\t\treturn safe ? context.redirect(location, found.rule.status) : next();\n\t\t},\n\t};\n}\n","import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** The headers that {@link securityHeaders} sets, by name. */\nexport type SecurityHeaderValues = {\n\t\"X-Content-Type-Options\"?: string | false;\n\t\"Referrer-Policy\"?: string | false;\n\t\"Cross-Origin-Opener-Policy\"?: string | false;\n\t/** Sent on an HTTPS request only. */\n\t\"Strict-Transport-Security\"?: string | false;\n\t/**\n\t * A policy that the plugin adds to each response, next to the app's own\n\t * policy. It has no default.\n\t */\n\t\"Content-Security-Policy\"?: string | false;\n};\n\n// Why no `includeSubDomains`: a browser keeps HSTS for a year, and on an apex domain it would force\n// HTTPS on each subdomain. An app adds it when it knows each subdomain serves HTTPS.\nconst DEFAULT_SECURITY_HEADERS: SecurityHeaderValues = {\n\t\"X-Content-Type-Options\": \"nosniff\",\n\t\"Referrer-Policy\": \"strict-origin-when-cross-origin\",\n\t\"Cross-Origin-Opener-Policy\": \"same-origin\",\n\t\"Strict-Transport-Security\": \"max-age=31536000\",\n};\n\n/** Options for {@link securityHeaders}. */\nexport type SecurityHeadersOptions = {\n\t/** Values that replace the defaults. `false` turns a header off. */\n\theaders?: SecurityHeaderValues;\n};\n\n/**\n * Sets safe default security headers on each response:\n *\n * - `X-Content-Type-Options: nosniff`\n * - `Referrer-Policy: strict-origin-when-cross-origin`\n * - `Cross-Origin-Opener-Policy: same-origin`\n * - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only\n *\n * A response that has a header keeps its own value. The exception is\n * `Content-Security-Policy`, which has no default: the plugin adds a set\n * value as a second policy, and a browser enforces both.\n * `defaultPlugins()` puts it before the static stages, so it also sees\n * prerendered pages.\n *\n * @example\n * defaultPlugins({\n * \tsecurityHeaders: {\n * \t\theaders: {\n * \t\t\t\"Cross-Origin-Opener-Policy\": \"same-origin-allow-popups\",\n * \t\t\t\"Content-Security-Policy\": \"frame-ancestors 'none'\",\n * \t\t},\n * \t},\n * });\n */\nexport function securityHeaders({ headers = {} }: SecurityHeadersOptions = {}): Plugin {\n\tconst values = Object.entries({ ...DEFAULT_SECURITY_HEADERS, ...headers })\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n\t\t.map(([name, value]) => [name, oneLine(value)] as const);\n\treturn {\n\t\tname: \"security-headers\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst isHttps = context.req.url.startsWith(\"https:\");\n\t\t\tawait withHeaderHook(context, next, (response) => {\n\t\t\t\tfor (const [name, value] of values) {\n\t\t\t\t\tif (name === \"Content-Security-Policy\") {\n\t\t\t\t\t\tresponse.append(name, value);\n\t\t\t\t\t} else if (!response.has(name) && (name !== \"Strict-Transport-Security\" || isHttps)) {\n\t\t\t\t\t\tresponse.set(name, value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * `value` on one line. Why: a header value cannot hold a line break, and a\n * policy written over several lines treats each run of whitespace as one space.\n */\nfunction oneLine(value: string): string {\n\treturn value.replaceAll(/\\s+/gu, \" \").trim();\n}\n\n/** Options for {@link contentSecurityPolicy}. */\nexport type ContentSecurityPolicyOptions = {\n\t/**\n\t * The `Content-Security-Policy` of an HTML document. `scriptSrc` is the\n\t * source list that trusts the document's scripts. Put it in `script-src`.\n\t * `context` is the request, so the policy can change by path. It runs in a\n\t * header hook, so it can run more than once for one request.\n\t */\n\tpolicy: (scriptSrc: string, context: Context<AppServerEnv>) => string;\n};\n\n/** A new random nonce: 16 bytes in base64. */\nfunction randomNonce(): string {\n\treturn btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(16))));\n}\n\n/**\n * Sets the `Content-Security-Policy` from `policy` on each HTML document. The\n * policy trusts the document's scripts, and only them:\n *\n * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce\n * for each request. The app reads the nonce from `requestContext()` and\n * gives it to the framework's render, so each inline script gets it.\n * - A prerendered document gets `'self'` and the hash of each of its inline\n * scripts, which the Vite plugin records. Its file has one nonce for every\n * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,\n * unlike a nonce, does not carry to the imports of an inline module script.\n *\n * The `contentSecurityPolicy` option of `defaultPlugins()` takes these\n * options, and puts the plugin before the static stages, so it sees the\n * prerendered documents. A response that has a `Content-Security-Policy`\n * keeps it.\n *\n * @example\n * defaultPlugins({\n * \tcontentSecurityPolicy: {\n * \t\tpolicy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,\n * \t},\n * });\n */\nexport function contentSecurityPolicy({ policy }: ContentSecurityPolicyOptions): Plugin {\n\tlet scriptHashes: ReadonlyMap<string, readonly string[]> = new Map();\n\treturn optionPlugin(\"contentSecurityPolicy\", {\n\t\tname: \"content-security-policy\",\n\t\tsetup: (info) => {\n\t\t\t({ scriptHashes } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst nonce = randomNonce();\n\t\t\tcontext.set(\"cspNonce\", nonce);\n\t\t\t// Why a header hook: in development, the dev server sends its own response, such as a file of\n\t\t\t// Vite's public directory, and runs the hooks before it sends the head.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why `staticDocument` too: a 304 has no `Content-Type`, and a browser replaces the cached policy with its policy.\n\t\t\t\tconst file = context.get(\"staticDocument\");\n\t\t\t\tconst hashes =\n\t\t\t\t\tcontext.get(\"documentScriptHashes\") ??\n\t\t\t\t\t(file == null ? undefined : (scriptHashes.get(file) ?? []));\n\t\t\t\tif (\n\t\t\t\t\theaders.has(\"Content-Security-Policy\") ||\n\t\t\t\t\t(hashes == null && !(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Why `'self'` only for a file with no hashes: the policy fails closed, so a missed script shows in a test.\n\t\t\t\tconst scriptSrc =\n\t\t\t\t\thashes == null\n\t\t\t\t\t\t? `'nonce-${nonce}' 'strict-dynamic'`\n\t\t\t\t\t\t: [\"'self'\", ...hashes.map((hash) => `'sha256-${hash}'`)].join(\" \");\n\t\t\t\theaders.set(\"Content-Security-Policy\", oneLine(policy(scriptSrc, context)));\n\t\t\t});\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n\t/**\n\t * Also log the trace IDs as `dd.trace_id` and `dd.span_id`, the lower 64\n\t * bits in decimal, so Datadog connects each log line to its trace.\n\t * @default false\n\t */\n\tdatadogTraceIds?: boolean;\n};\n\n/** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */\nconst VALID_ID = /^[\\w\\-=]{1,255}$/u;\n\n/** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */\nconst TRACEPARENT =\n\t/^(?<version>[\\da-f]{2})-(?<traceId>[\\da-f]{32})-(?<spanId>[\\da-f]{16})-[\\da-f]{2}(?<rest>-.*)?$/u;\n\n/**\n * The trace IDs of a valid W3C `traceparent` header, else `undefined`. A\n * version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.\n *\n * @example\n * parseTraceparent(\"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\");\n * // => { traceId: \"4bf92f3577b34da6a3ce929d0e0e4736\", spanId: \"00f067aa0ba902b7\" }\n */\nexport function parseTraceparent(\n\theader: string | undefined,\n): { traceId: string; spanId: string } | undefined {\n\tconst groups = TRACEPARENT.exec(header?.trim() ?? \"\")?.groups;\n\tif (\n\t\tgroups?.version == null ||\n\t\tgroups.traceId == null ||\n\t\tgroups.spanId == null ||\n\t\tgroups.version === \"ff\" ||\n\t\t(groups.version === \"00\" && groups.rest != null) ||\n\t\t/^0+$/u.test(groups.traceId) ||\n\t\t/^0+$/u.test(groups.spanId)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { traceId: groups.traceId, spanId: groups.spanId };\n}\n\n/** The log attributes for the trace IDs. */\nfunction traceAttributes(\n\t{ traceId, spanId }: { traceId: string; spanId: string },\n\t{ datadog }: { datadog: boolean },\n): Record<string, string> {\n\treturn {\n\t\ttrace_id: traceId,\n\t\tspan_id: spanId,\n\t\t...(datadog\n\t\t\t? {\n\t\t\t\t\t\"dd.trace_id\": BigInt(`0x${traceId.slice(16)}`).toString(),\n\t\t\t\t\t\"dd.span_id\": BigInt(`0x${spanId}`).toString(),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log\n * line of the request.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({\n\theaderName = \"X-Request-Id\",\n\tdatadogTraceIds = false,\n}: RequestIdOptions = {}): Plugin {\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst trace = parseTraceparent(context.req.header(\"traceparent\"));\n\t\t\tif (trace != null) {\n\t\t\t\tcontext.set(\"logAttributes\", {\n\t\t\t\t\t...context.get(\"logAttributes\"),\n\t\t\t\t\t...traceAttributes(trace, { datadog: datadogTraceIds }),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst incoming = context.req.header(headerName);\n\t\t\tconst id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();\n\t\t\tcontext.set(\"requestId\", id);\n\t\t\t// Why a header hook: a dev server middleware sends its own response, and runs the hooks first.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\theaders.set(headerName, id);\n\t\t\t});\n\t\t},\n\t};\n}\n","/** One media range of an `Accept` header. */\ntype MediaRange = {\n\t/** The media type in lowercase, such as `text/html` or `*\\/*`. */\n\ttype: string;\n\t/** The `q` value, from 0 to 1. */\n\tquality: number;\n\t/** The `charset` parameter in lowercase, when the range has one. */\n\tcharset: string | undefined;\n};\n\n/** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */\nconst QVALUE = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/u;\n\n/** The charset of each answer that a caller of {@link prefersMarkdown} sends. */\n// oxlint-disable-next-line unicorn/text-encoding-identifier-case -- HTTP names the charset `utf-8`.\nconst CHARSET = \"utf-8\";\n\n/**\n * The parts of `value` between each `separator`. Why a scan, not `split`: a\n * quoted parameter value can hold a `,` or a `;`.\n */\nfunction splitOutsideQuotes(value: string, separator: string): string[] {\n\tconst parts: string[] = [];\n\tlet part = \"\";\n\tlet quoted = false;\n\tlet escaped = false;\n\tfor (const character of value) {\n\t\tif (!quoted && character === separator) {\n\t\t\tparts.push(part);\n\t\t\tpart = \"\";\n\t\t} else {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t} else if (quoted && character === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t} else if (character === '\"') {\n\t\t\t\tquoted = !quoted;\n\t\t\t}\n\t\t\tpart += character;\n\t\t}\n\t}\n\tparts.push(part);\n\treturn parts;\n}\n\n/** The parameters of a media range, by lowercase name, with quotes removed. */\nfunction parameterMap(parameters: readonly string[]): Map<string, string> {\n\treturn new Map(\n\t\tparameters.map((parameter) => {\n\t\t\tconst index = parameter.indexOf(\"=\");\n\t\t\tconst name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();\n\t\t\tconst value = index === -1 ? \"\" : parameter.slice(index + 1).trim();\n\t\t\tconst unquoted = /^\".*\"$/su.test(value)\n\t\t\t\t? value.slice(1, -1).replaceAll(/\\\\(?<character>.)/gsu, \"$<character>\")\n\t\t\t\t: value;\n\t\t\treturn [name, unquoted];\n\t\t}),\n\t);\n}\n\n/**\n * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC\n * 9110 default. Why a malformed `q` also counts as 1: the client still named\n * the media type.\n */\nfunction mediaRanges(accept: string): MediaRange[] {\n\treturn splitOutsideQuotes(accept, \",\").map((entry) => {\n\t\tconst [type = \"\", ...parameters] = splitOutsideQuotes(entry, \";\");\n\t\tconst parameterValues = parameterMap(parameters);\n\t\tconst quality = parameterValues.get(\"q\") ?? \"1\";\n\t\treturn {\n\t\t\ttype: type.trim().toLowerCase(),\n\t\t\tquality: QVALUE.test(quality) ? Number(quality) : 1,\n\t\t\tcharset: parameterValues.get(\"charset\")?.toLowerCase(),\n\t\t};\n\t});\n}\n\n/**\n * The `q` of an answer of `type` in UTF-8, from the most specific ranges with\n * that type, or `undefined` when no range matches it. A range with\n * `charset=utf-8` is more specific than a range with no charset. A range with\n * another charset does not match. Other parameters, such as `variant`, do not\n * change the match.\n */\nfunction qualityOf(ranges: readonly MediaRange[], type: string): number | undefined {\n\tconst matches = ranges.filter(\n\t\t(range) => range.type === type && (range.charset == null || range.charset === CHARSET),\n\t);\n\tconst withCharset = matches.filter((range) => range.charset === CHARSET);\n\tconst specific = withCharset.length > 0 ? withCharset : matches;\n\treturn specific.length === 0 ? undefined : Math.max(...specific.map((range) => range.quality));\n}\n\n/**\n * Whether a request asks for markdown before HTML, per\n * https://acceptmarkdown.com. Use it to choose between the HTML and the\n * markdown answer for one URL.\n *\n * The rules:\n *\n * - Only an explicit `text/markdown` range counts for markdown. A wildcard,\n * such as `*\\/*` or `text/*`, never selects markdown, so a browser and a\n * client with no `Accept` get HTML.\n * - `text/markdown;q=0` refuses markdown.\n * - The `q` of markdown must be equal to or higher than the `q` of HTML. The\n * `q` of HTML comes from the most specific range that matches it:\n * `text/html`, then `text/*`, then `*\\/*`. A tie selects markdown, because\n * the client named it.\n * - Both answers are UTF-8. A range with `charset=utf-8` is more specific\n * than a range with no charset, and a range with another charset does not\n * match. Other parameters, such as `variant`, do not change the match.\n * - Media types and parameter names are not case-sensitive. A quoted\n * parameter value can hold a `,` or a `;`.\n *\n * When the answer for a URL depends on this function, send `Vary: Accept` on\n * both the HTML and the markdown answer. Else a shared cache can give the\n * markdown to a browser.\n *\n * @example\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/markdown\" } }));\n * // => true\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/html, text/markdown;q=0.5\" } }));\n * // => false\n */\nexport function prefersMarkdown(request: Request): boolean {\n\tconst accept = request.headers.get(\"Accept\");\n\t// Why the substring check: a browser never names markdown, and it skips the parse of its long `Accept`.\n\tif (accept == null || !/markdown/iu.test(accept)) {\n\t\treturn false;\n\t}\n\tconst ranges = mediaRanges(accept);\n\tconst markdown = qualityOf(ranges, \"text/markdown\") ?? 0;\n\tconst html =\n\t\tqualityOf(ranges, \"text/html\") ?? qualityOf(ranges, \"text/*\") ?? qualityOf(ranges, \"*/*\") ?? 0;\n\treturn markdown > 0 && markdown >= html;\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { getPath } from \"hono/utils/url\";\nimport { manifestKey } from \"../build-manifest.js\";\nimport { writableHeaders } from \"../header-hook.js\";\nimport { prefersMarkdown } from \"../prefers-markdown.js\";\nimport { contentType, findStaticFile, isFilePath, staticResponse } from \"../static-files.js\";\nimport { withVary } from \"../vary.js\";\nimport type { StaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/**\n * Serves the hashed files under `/assets/` with a one-year immutable cache.\n * A missing asset gets a plain 404 with `Cache-Control: no-store`, not a\n * rendered page. In development, the dev server serves the source modules,\n * the HMR client, and the CSS here instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tstage = info.devServer;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes } = info;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(\"/assets/\") || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(files, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\t// Why `no-store`: an old tab asks for the chunks of the build it runs, and a CDN must not keep the miss.\n\t\t\t\t\treturn context.text(\"Not Found\", 404, { \"Cache-Control\": \"no-store\" });\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: { \"Cache-Control\": IMMUTABLE },\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (\n\t\tpath: string,\n\t\tcontext: Context<AppServerEnv>,\n\t) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t * With `markdownTwins: true`, a request that `rewrite` changes gets no twin.\n\t */\n\trewrite?: (path: string, context: Context<AppServerEnv>) => string;\n\t/**\n\t * Serves the markdown twin of a page, such as `/docs/button.md` for\n\t * `/docs/button`, to a request that {@link prefersMarkdown} accepts. A\n\t * page has a twin when `twinOf` names a file in the client build. `twinOf`\n\t * gets the request path and the request's Hono context, the same as\n\t * `rewrite`. It returns `undefined` for a request with no twin.\n\t *\n\t * - A request that prefers markdown gets the twin, with the twin's\n\t * captured headers.\n\t * - Each answer for a path with a twin gets `Vary: Accept`: the twin, the\n\t * prerendered HTML, and the framework's answer. The server adds\n\t * `Accept` to the `Vary` header and keeps the values in it.\n\t * - Each answer for a path with a twin, except the twin, gets\n\t * `Link: <twin>; rel=\"alternate\"; type=\"text/markdown\"`, so a client can\n\t * find the twin.\n\t * - A path with no twin gets no `Vary: Accept` and no `Link`, so a request\n\t * for the twin's own URL gets none.\n\t * - In development, the client build has no twins. A request that prefers\n\t * markdown gets the framework's answer for the twin's URL, so an edit\n\t * shows at once. When the framework knows the paths that the build will\n\t * prerender, as React Router does, only those twins count. An error, or\n\t * an answer that is not markdown, gives the HTML.\n\t * - A plugin after `prerendered` does not see a twin, as it does not see\n\t * a prerendered file.\n\t *\n\t * `true` uses the default `twinOf`: the path with no trailing slash plus\n\t * `.md`, and `/index.md` for `/`. A request that `rewrite` changes gets no\n\t * twin, so it gets the same page as a browser. The returned path follows\n\t * the rules of a request path.\n\t *\n\t * @example\n\t * prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });\n\t */\n\tmarkdownTwins?: boolean | { twinOf: TwinOf };\n\t/**\n\t * Sends a request path to the next stage, with no file lookup. Use it for\n\t * private pages, so the auth check in the app or the framework runs for\n\t * them. A data request has its own path, such as `/app.data` in React\n\t * Router.\n\t *\n\t * @example\n\t * prerendered({ skip: (path) => path === \"/app\" || path.startsWith(\"/app/\") || path.startsWith(\"/app.\") });\n\t */\n\tskip?: (path: string) => boolean;\n\t/**\n\t * The `Cache-Control` of a served file, by the file's URL path, such as\n\t * `/about/index.html`. `undefined` sends none. A header that the build\n\t * captured, and the `headers` option, win over it.\n\t *\n\t * The default gives an HTML page, a markdown file, and a data file of the\n\t * framework `public, max-age=0, must-revalidate`, so a visitor always sees\n\t * the newest page and its markdown twin, and a 304 keeps it fast. It gives every other file\n\t * `public, max-age=3600, stale-while-revalidate=86400`.\n\t *\n\t * @example\n\t * prerendered({ cacheControl: (path) => (path.startsWith(\"/images/\") ? \"public, max-age=86400\" : undefined) });\n\t */\n\tcacheControl?: (path: string) => string | undefined;\n};\n\n/** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */\ntype TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefined;\n\n/**\n * The twin of a request, from its path and the path that `rewrite` gives for\n * it, or `undefined` when it has none.\n */\ntype FindTwinPath = (\n\tpath: string,\n\trewritten: string,\n\tcontext: Context<AppServerEnv>,\n) => string | undefined;\n\nconst REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst ONE_HOUR = \"public, max-age=3600, stale-while-revalidate=86400\";\n\n/**\n * The default markdown twin of a page: `/docs/button.md` for `/docs/button`,\n * and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends\n * it to another file or to the framework, so the page's twin does not match\n * its answer.\n */\nfunction defaultTwinOf(path: string, rewritten: string): string | undefined {\n\treturn rewritten === path ? `${trimTrailingSlashes(path) || \"/index\"}.md` : undefined;\n}\n\n/** The file of the markdown twin of the request, or `undefined` when the page has none. */\nasync function findTwin(\n\tfiles: StaticFiles,\n\tcontext: Context<AppServerEnv>,\n\t{ twinOf, rewritten }: { twinOf: FindTwinPath | undefined; rewritten: string },\n): Promise<{ path: string; file: StaticFile } | undefined> {\n\tconst twinPath = twinOf?.(context.req.path, rewritten, context);\n\tconst file = twinPath == null ? undefined : await findStaticFile(files, twinPath);\n\treturn twinPath == null || file == null ? undefined : { path: twinPath, file };\n}\n\n/** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */\nfunction varyOnAccept(context: Context<AppServerEnv>): void {\n\tconst vary = withVary(context.res.headers.get(\"Vary\"), \"Accept\");\n\tif (vary != null) {\n\t\twritableHeaders(context).set(\"Vary\", vary);\n\t}\n}\n\n/**\n * The percent-encoded URL path for a decoded path, so it holds no space,\n * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a\n * newline, which a file name can hold.\n */\nfunction urlPath(path: string): string {\n\treturn new URL(\n\t\tpath.replaceAll(/[\\t\\n\\r]/gu, (character) => encodeURIComponent(character)),\n\t\t\"http://localhost\",\n\t).pathname;\n}\n\n/** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */\nfunction linkToTwin(context: Context<AppServerEnv>, twinPath: string): void {\n\twritableHeaders(context).append(\n\t\t\"Link\",\n\t\t`<${urlPath(twinPath)}>; rel=\"alternate\"; type=\"text/markdown\"`,\n\t);\n}\n\n/**\n * The development stage of `markdownTwins`. The client build has no twins\n * then, so a request that prefers markdown gets the framework's answer for\n * the twin's URL: the route that prerenders the twin. A twin path that is not\n * in `prerenderedPaths`, an error, or an answer that is not markdown sends the\n * request on for the HTML.\n */\nfunction developmentTwins(\n\ttwinOf: FindTwinPath,\n\t{ rewrite, skip }: Pick<PrerenderedOptions, \"rewrite\" | \"skip\">,\n\tprerenderedPaths: ReadonlySet<string> | undefined,\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { method, path } = context.req;\n\t\tconst twinPath =\n\t\t\t(method === \"GET\" || method === \"HEAD\") &&\n\t\t\tskip?.(path) !== true &&\n\t\t\tprefersMarkdown(context.req.raw)\n\t\t\t\t? twinOf(path, rewrite?.(path, context) ?? path, context)\n\t\t\t\t: undefined;\n\t\t// Why both checks: production has no twin that the build does not prerender, or at a path that fails `isFilePath`.\n\t\tif (\n\t\t\ttwinPath == null ||\n\t\t\t(prerenderedPaths != null && !prerenderedPaths.has(twinPath)) ||\n\t\t\t!isFilePath(twinPath)\n\t\t) {\n\t\t\treturn next();\n\t\t}\n\t\tconst url = new URL(context.req.url);\n\t\turl.pathname = urlPath(twinPath);\n\t\t// Why: the URL can change the path, for example `%2e%2e` to `..`. Then the framework answers a path that `twinOf` did not name.\n\t\tif (getPath(new Request(url)) !== twinPath) {\n\t\t\treturn next();\n\t\t}\n\t\tconst { headers, signal } = context.req.raw;\n\t\t// Why no `Request` as the init: the Node.js listener's request is not one that `Request` can copy.\n\t\tconst twin = new Request(url, { method, headers, signal });\n\t\tconst response = await context.env.framework.fetch(twin, context);\n\t\t// Why only markdown: production serves a twin from a `.md` file, so an HTML page or an error is no twin.\n\t\t// A 304 has no body to check, and it answers a validator from the twin.\n\t\tconst markdown =\n\t\t\tresponse.headers.get(\"Content-Type\")?.toLowerCase().startsWith(\"text/markdown\") === true;\n\t\tif (response.status !== 304 && !(response.ok && markdown)) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn next();\n\t\t}\n\t\tcontext.res = response;\n\t\tvaryOnAccept(context);\n\t};\n}\n\n/** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */\nfunction twinOfOption(\n\tmarkdownTwins: PrerenderedOptions[\"markdownTwins\"],\n): FindTwinPath | undefined {\n\tif (markdownTwins === true) {\n\t\treturn defaultTwinOf;\n\t}\n\tif (markdownTwins == null || markdownTwins === false) {\n\t\treturn undefined;\n\t}\n\tconst { twinOf } = markdownTwins;\n\treturn (path, _rewritten, context) => twinOf(path, context);\n}\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200,\n * plus every other file in it. It sends no redirect. The `trailingSlash`\n * plugin does. Each response gets\n * the headers its loader sent at build time (the `appServer` Vite plugin\n * captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304\n * for a matching `If-None-Match`. A GET with one byte range gets a 206. A path\n * with no file goes on to the framework. In development, only\n * `markdownTwins` runs.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: (path) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tconst twinOf = twinOfOption(options.markdownTwins);\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tconst paths = info.prerenderedPaths;\n\t\t\t\tstage =\n\t\t\t\t\ttwinOf == null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: developmentTwins(twinOf, options, paths == null ? undefined : new Set(paths));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes, capturedHeaders } = info;\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(files, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log(\"warn\", \"prerendered paths with no file\", {\n\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst cacheControl =\n\t\t\t\toptions.cacheControl ??\n\t\t\t\t((path: string) => {\n\t\t\t\t\tconst type = contentType(path, contentTypes);\n\t\t\t\t\treturn type.startsWith(\"text/html\") ||\n\t\t\t\t\t\ttype.startsWith(\"text/markdown\") ||\n\t\t\t\t\t\tinfo.isDataRequest(path)\n\t\t\t\t\t\t? REVALIDATE\n\t\t\t\t\t\t: ONE_HOUR;\n\t\t\t\t});\n\t\t\tconst serve = async (context: Context<AppServerEnv>, path: string, file: StaticFile) => {\n\t\t\t\tconst value = cacheControl(file.path);\n\t\t\t\tconst headers = new Headers(value == null ? undefined : { \"Cache-Control\": value });\n\t\t\t\t// Why `Headers`: the build captures lowercase names, and each layer must replace the one before it in any case.\n\t\t\t\tfor (const layer of [\n\t\t\t\t\tcapturedHeaders.get(manifestKey(path)),\n\t\t\t\t\toptions.headers?.(path, context),\n\t\t\t\t]) {\n\t\t\t\t\tfor (const [name, layerValue] of Object.entries(layer ?? {})) {\n\t\t\t\t\t\theaders.set(name, layerValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: Object.fromEntries(headers),\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif ((method !== \"GET\" && method !== \"HEAD\") || options.skip?.(context.req.path) === true) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst rewritten = options.rewrite?.(context.req.path, context) ?? context.req.path;\n\t\t\t\tconst twin = await findTwin(files, context, { twinOf, rewritten });\n\t\t\t\tconst preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : undefined;\n\t\t\t\tconst path = preferred?.path ?? rewritten;\n\t\t\t\tconst file = preferred?.file ?? (await findStaticFile(files, path));\n\t\t\t\tif (file == null) {\n\t\t\t\t\tawait next();\n\t\t\t\t} else {\n\t\t\t\t\tcontext.res = await serve(context, path, file);\n\t\t\t\t}\n\t\t\t\tif (twin != null) {\n\t\t\t\t\tvaryOnAccept(context);\n\t\t\t\t}\n\t\t\t\tif (twin != null && preferred == null) {\n\t\t\t\t\tlinkToTwin(context, twin.path);\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import {\n\tforbidsTransform,\n\tisCompressible,\n\tMIN_COMPRESS_BYTES,\n\tpreferredEncoding,\n\treadIfQueued,\n} from \"../compression.js\";\nimport type { ReadResult } from \"../compression.js\";\nimport { hookedHeaders, replaceResponse, withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\nimport { withVary } from \"../vary.js\";\n\n/** The chunks that a body has queued, and the read that is still open, if any. */\ntype Queued = { chunks: Uint8Array[]; done: boolean; pending: Promise<ReadResult> | undefined };\n\n/**\n * The most bytes that one pull of {@link replay} joins. Why 16 KiB: a source\n * that makes a chunk on each read looks queued, so the join can read ahead of\n * the client by this size, the default read-ahead of a Node.js stream.\n */\nexport const MAX_JOINED_BYTES = 16 * 1024;\n\n/**\n * Reads at most two chunks that `reader` has queued, and never waits for\n * more. Why two: a body from a string or a buffer queues its bytes and its\n * end, so the plugin can see that it is small. `@hono/node-server` reads a\n * body the same way to find its length.\n */\nasync function readQueued(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<Queued> {\n\tconst chunks: Uint8Array[] = [];\n\tfor (let count = 0; count < 2; count += 1) {\n\t\tconst next = await readIfQueued(reader);\n\t\tif (\"pending\" in next) {\n\t\t\treturn { chunks, done: false, pending: next.pending };\n\t\t}\n\t\tif (next.result.done) {\n\t\t\treturn { chunks, done: true, pending: undefined };\n\t\t}\n\t\tchunks.push(next.result.value);\n\t}\n\treturn { chunks, done: false, pending: undefined };\n}\n\nfunction join(chunks: Uint8Array[], size: number): Uint8Array {\n\tconst [first] = chunks;\n\tif (chunks.length === 1 && first != null) {\n\t\treturn first;\n\t}\n\tconst joined = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tjoined.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn joined;\n}\n\n/**\n * The body again: the queued chunks, then the rest of `reader`. Each pull\n * waits for one chunk at most, and joins it with the chunks that are queued\n * after it, up to {@link MAX_JOINED_BYTES}. Why join: gzip flushes after each\n * chunk, and each flush costs more than the bytes. A renderer such as React\n * queues many small chunks at once. A chunk that comes later still goes out on\n * its own. A chunk that does not fit waits for the next pull, and an empty\n * chunk ends the join. When `queued` has the end, the first pull sends the\n * chunks and closes.\n */\nfunction replay(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tqueued: Queued,\n): ReadableStream<Uint8Array> {\n\tconst chunks = [...queued.chunks];\n\tlet { pending, done } = queued;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tconst parts: Uint8Array[] = [];\n\t\t\t\tlet size = 0;\n\t\t\t\tconst fits = (chunk: Uint8Array) =>\n\t\t\t\t\tparts.length === 0 || size + chunk.byteLength <= MAX_JOINED_BYTES;\n\t\t\t\tfor (let [chunk] = chunks; chunk != null && fits(chunk); [chunk] = chunks) {\n\t\t\t\t\tchunks.shift();\n\t\t\t\t\tparts.push(chunk);\n\t\t\t\t\tsize += chunk.byteLength;\n\t\t\t\t}\n\t\t\t\tif (parts.length === 0) {\n\t\t\t\t\tconst result = await (pending ?? reader.read());\n\t\t\t\t\tpending = undefined;\n\t\t\t\t\tif (result.done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tparts.push(result.value);\n\t\t\t\t\tsize = result.value.byteLength;\n\t\t\t\t}\n\t\t\t\t// Why no read when `done`: the host reads a body the same way as `readQueued`, and it sends\n\t\t\t\t// a body with its `Content-Length` only when the body ends within that read.\n\t\t\t\twhile (chunks.length === 0 && pending == null && !done && size < MAX_JOINED_BYTES) {\n\t\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\t\t\t\tconst next = await readIfQueued(reader);\n\t\t\t\t\tif (\"pending\" in next) {\n\t\t\t\t\t\t({ pending } = next);\n\t\t\t\t\t} else if (next.result.done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (next.result.value.byteLength === 0) {\n\t\t\t\t\t\t// Why stop: empty chunks add no bytes, so a source of them would hold the join open.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (fits(next.result.value)) {\n\t\t\t\t\t\tparts.push(next.result.value);\n\t\t\t\t\t\tsize += next.result.value.byteLength;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunks.push(next.result.value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(join(parts, size));\n\t\t\t\tif (done && chunks.length === 0) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: async (reason) => reader.cancel(reason),\n\t\t},\n\t\t// Why 0: the stream reads its source only when the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * `response` with the gzip `body` and its headers. Why not in a header hook:\n * the body and its headers go together, also to the code that an outer stage\n * runs after its `next()`.\n */\nfunction gzipped(\n\tresponse: Response,\n\tbody: ReadableStream<Uint8Array>,\n\t{ hasLength }: { hasLength: boolean },\n): Response {\n\tconst replacement = new Response(body, response);\n\treplacement.headers.set(\"Content-Encoding\", \"gzip\");\n\t// Why the flag: a delete costs as much as a set, and a streamed page has no length.\n\tif (hasLength) {\n\t\treplacement.headers.delete(\"Content-Length\");\n\t}\n\t// Why: a range of the gzip bytes cannot be served, because each response compresses again.\n\treplacement.headers.delete(\"Accept-Ranges\");\n\treturn replacement;\n}\n\n/**\n * Gzips text responses and flushes after each chunk, so a streamed page shell\n * or a server-sent event reaches the client at once. Chunks that the body has\n * queued together are one chunk, up to 16 KiB. `hono/compress` holds a\n * stream until it ends. Skips a response that is already encoded, a partial\n * response, one marked `no-transform`, and one whose `Content-Length` is\n * under 1 KiB. It adds `Accept-Encoding` to the `Vary` of each response that\n * it can gzip. The host gives the gzip stream. On a host with none, the\n * plugin does nothing.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\tlet gzip: SetupInfo[\"gzip\"];\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tsetup: (info) => {\n\t\t\t({ gzip } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tif (gzip == null) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why a hook for `Vary`: the code after `next()` decides, and a response that the plugin does\n\t\t\t// not gzip then needs no copy for it.\n\t\t\tlet gzipping = false;\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why: the bytes of a type that the plugin never gzips, such as an image, do not vary by\n\t\t\t\t// `Accept-Encoding`. A response with no type, such as a 304, keeps the `Vary` of its 200.\n\t\t\t\tconst type = headers.get(\"Content-Type\");\n\t\t\t\tconst vary =\n\t\t\t\t\ttype == null || isCompressible(type)\n\t\t\t\t\t\t? withVary(headers.get(\"Vary\"), \"Accept-Encoding\")\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (vary != null) {\n\t\t\t\t\theaders.set(\"Vary\", vary);\n\t\t\t\t}\n\t\t\t\t// Why: the hook of an inner stage can set the length of the body before gzip.\n\t\t\t\tif (gzipping) {\n\t\t\t\t\theaders.delete(\"Content-Length\");\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst response = context.res;\n\t\t\tconst type = response.headers.get(\"Content-Type\");\n\t\t\tif (type != null && !isCompressible(type)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst length = response.headers.get(\"Content-Length\");\n\t\t\tconst { body } = response;\n\t\t\tif (\n\t\t\t\ttype == null ||\n\t\t\t\tbody == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\t(length != null && Number(length) < MIN_COMPRESS_BYTES) ||\n\t\t\t\tpreferredEncoding(context.req.header(\"Accept-Encoding\"), [\"gzip\"]) == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: gzip changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\tforbidsTransform(response.headers.get(\"Cache-Control\"))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet source: ReadableStream<Uint8Array> = body;\n\t\t\tlet compress = true;\n\t\t\tif (length == null) {\n\t\t\t\tconst reader = body.getReader();\n\t\t\t\tconst queued = await readQueued(reader);\n\t\t\t\tconst size = queued.chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n\t\t\t\t// Why: gzip makes a small body larger, and a body from a string has no `Content-Length`.\n\t\t\t\tcompress = !queued.done || size >= MIN_COMPRESS_BYTES;\n\t\t\t\tsource = replay(reader, queued);\n\t\t\t}\n\t\t\t// Why the hooks: a header hook of a later stage can set these headers, and it runs only where\n\t\t\t// the response leaves.\n\t\t\tif (compress) {\n\t\t\t\tconst hooked = hookedHeaders(context, response.headers);\n\t\t\t\tcompress =\n\t\t\t\t\t!hooked.has(\"Content-Encoding\") &&\n\t\t\t\t\t!hooked.has(\"Content-Range\") &&\n\t\t\t\t\t!forbidsTransform(hooked.get(\"Cache-Control\"));\n\t\t\t}\n\t\t\tif (compress) {\n\t\t\t\tgzipping = true;\n\t\t\t\treplaceResponse(context, gzipped(response, gzip(source), { hasLength: length != null }));\n\t\t\t} else if (source !== body) {\n\t\t\t\treplaceResponse(context, new Response(source, response));\n\t\t\t}\n\t\t},\n\t};\n}\n","import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport type { ErrorHandler, HTTPResponseError } from \"hono/types\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog } from \"./plugins/access-log.js\";\nimport type { AccessLogOptions } from \"./plugins/access-log.js\";\nimport { bodyLimit } from \"./plugins/body-limit.js\";\nimport { buildId } from \"./plugins/build-id.js\";\nimport type { BuildIdOptions } from \"./plugins/build-id.js\";\nimport { health } from \"./plugins/health.js\";\nimport type { HealthOptions } from \"./plugins/health.js\";\nimport { noindex } from \"./plugins/noindex.js\";\nimport { privateDocuments } from \"./plugins/private-documents.js\";\nimport { redirects } from \"./plugins/redirects.js\";\nimport type { RedirectRule } from \"./plugins/redirects.js\";\nimport { contentSecurityPolicy, securityHeaders } from \"./plugins/security-headers.js\";\nimport type {\n\tContentSecurityPolicyOptions,\n\tSecurityHeadersOptions,\n} from \"./plugins/security-headers.js\";\nimport { requestId } from \"./plugins/request-id.js\";\nimport type { RequestIdOptions } from \"./plugins/request-id.js\";\nimport type { RuntimeEnv } from \"./plugins/runtime-env.js\";\nimport { assets, prerendered } from \"./plugins/static.js\";\nimport type { PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { trailingSlash } from \"./plugins/trailing-slash.js\";\nimport type { TrailingSlash } from \"./plugins/trailing-slash.js\";\nimport { checkOptionPlugins } from \"./plugin-options.js\";\nimport { withRequestContext } from \"./request-context.js\";\nimport { finishResponse } from \"./response-edge.js\";\nimport { abortShutdownSignal, markStopping, renewShutdownSignal } from \"./shutdown.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHeaderHook,\n\tListener,\n\tLogSink,\n\tPlugin,\n\tRequestStore,\n\tSentResponse,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The response for `error`, as `onError` gives it for a stage that throws. */\nfunction answerError(error: Error | HTTPResponseError, context: Context<AppServerEnv>): Response {\n\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\tconst response: unknown = error.getResponse();\n\t\tif (response instanceof Response) {\n\t\t\treturn response;\n\t\t}\n\t}\n\tcontext.get(\"logger\").error(\"unhandled error\", errorAttributes(error));\n\treturn context.text(\"Internal Server Error\", 500);\n}\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Marks the server as not ready, and waits for the shutdown delay. Then it\n\t * aborts `shutdownSignal()` and runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/**\n\t * Starts the app's listeners, else `defaultListeners`, the host's. Call\n\t * `prepare` first. Throws when neither has a listener.\n\t */\n\tlisten: (\n\t\tframework: FrameworkRuntime,\n\t\tdefaultListeners: readonly Listener[] | undefined,\n\t) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Sets the storage for `requestContext()` in this app's requests. `createEntry` sets the host's. */\n\tsetRequestStore: (store: RequestStore | undefined) => void;\n};\n\n/** Why 10 MiB: a form or an avatar upload fits, and a body cannot fill the memory. */\nconst DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\t/**\n\t * The options of the liveness and readiness probes. `false` turns them\n\t * off, such as for an app with its own `/livez` route. See {@link health}.\n\t * @default {}\n\t */\n\thealth?: HealthOptions | false;\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Redirects from old URL paths to new URLs. They run before\n\t * `trailingSlash`, so an old URL gets one redirect. See {@link redirects}.\n\t */\n\tredirects?: readonly RedirectRule[];\n\t/**\n\t * How a page URL ends. Set the same mode in the framework's router when it\n\t * has one, else the redirects loop. See {@link trailingSlash}.\n\t * @default \"never\"\n\t */\n\ttrailingSlash?: TrailingSlash;\n\t/**\n\t * The largest request body, in bytes. A larger body gets a 413. `false`\n\t * turns the limit off. See {@link bodyLimit}.\n\t * @default 10485760 (10 MiB)\n\t */\n\tbodyLimit?: number | false;\n\t/**\n\t * The options of the security headers. `false` turns them off. See\n\t * {@link securityHeaders}.\n\t */\n\tsecurityHeaders?: SecurityHeadersOptions | false;\n\t/**\n\t * Sets `X-Robots-Tag: noindex, nofollow` on each response, such as on a\n\t * preview deploy. See {@link noindex}.\n\t * @default false\n\t */\n\tnoindex?: boolean;\n\t/**\n\t * The options of the build ID on each document and data response. `false`\n\t * turns it off. See {@link buildId}.\n\t * @default {}, with the ID that the `appServer` Vite plugin derives from the client build\n\t */\n\tbuildId?: BuildIdOptions | false;\n\t/**\n\t * The options of the `Content-Security-Policy` of each HTML document. It\n\t * has no default. See {@link contentSecurityPolicy}.\n\t */\n\tcontentSecurityPolicy?: ContentSecurityPolicyOptions;\n\t/**\n\t * The plugin from `runtimeEnv(schema)`. It writes the public values into\n\t * each HTML document, prerendered pages included.\n\t */\n\tenv?: RuntimeEnv<unknown>;\n\t/**\n\t * The app's own plugins that see every response, prerendered pages\n\t * included, such as an auth check. They go after the plugins of the\n\t * options above and before the static stages.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `health`, `requestId`, `accessLog`,\n * `streamingCompress`, `securityHeaders`, `bodyLimit`, `noindex` (when\n * set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the\n * `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),\n * `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain\n * array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ env, noindex: process.env.PREVIEW === \"1\", health: { ready: async () => db.ping() } }),\n * });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\tconst maxBytes = options.bodyLimit ?? DEFAULT_BODY_LIMIT;\n\treturn [\n\t\t// Why first: a probe skips the access log, and a load balancer gets its answer with no other work.\n\t\t...(options.health === false ? [] : [health(options.health)]),\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t// Why before `bodyLimit`: its 413 must also get the security headers.\n\t\t...(options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)]),\n\t\t...(maxBytes === false ? [] : [bodyLimit({ maxBytes })]),\n\t\t// Why before the static stages: these plugins must see the prerendered pages. Why before\n\t\t// `beforeStatic`: an app plugin, such as an auth check, then gets the CSP nonce, and its own\n\t\t// responses get these headers. Their order among themselves changes no response.\n\t\t...(options.noindex === true ? [noindex()] : []),\n\t\t...(options.buildId === false ? [] : [buildId(options.buildId)]),\n\t\t...(options.contentSecurityPolicy == null\n\t\t\t? []\n\t\t\t: [contentSecurityPolicy(options.contentSecurityPolicy)]),\n\t\t...(options.env == null ? [] : [options.env]),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\t...(options.redirects == null || options.redirects.length === 0\n\t\t\t? []\n\t\t\t: [redirects(options.redirects, { trailingSlash: options.trailingSlash ?? \"never\" })]),\n\t\t// Why after `assets`: in development, the dev server there answers Vite's paths, such as `/@vite/client`.\n\t\ttrailingSlash({ mode: options.trailingSlash ?? \"never\" }),\n\t\tprerendered(options.prerendered),\n\t\t// Why last: it must see only the responses of the app's routes and the framework.\n\t\tprivateDocuments(),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/** @default the host's listeners, such as `[tcp()]` on the node host */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How many proxies in front of the server add the address they got a\n\t * request from to `X-Forwarded-For`. With N, the client address is the\n\t * Nth address from the right of that header. A header with fewer\n\t * addresses gives its leftmost address. Set it only to the number of\n\t * proxies that you run, else a client can spoof its address.\n\t * @default 0, the address of the socket\n\t */\n\ttrustedProxyHops?: number;\n\t/**\n\t * How long the listeners serve on after a stop signal, before the drain\n\t * starts. During this time, the `health` plugin's readiness probe answers\n\t * 503, so a load balancer stops sending requests first. The drain deadline\n\t * starts after the delay.\n\t * @default 0\n\t */\n\tshutdownDelayMs?: number;\n\t/**\n\t * How long open requests get to finish after the drain starts.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/**\n * The client address in an `X-Forwarded-For` header, with `hops` trusted\n * proxies, or `undefined` when the header has no address.\n */\nfunction forwardedClient(header: string | undefined, hops: number): string | undefined {\n\tconst addresses = (header ?? \"\")\n\t\t.split(\",\")\n\t\t.map((address) => address.trim())\n\t\t.filter((address) => address !== \"\");\n\treturn addresses[Math.max(0, addresses.length - hops)];\n}\n\n/** Why: `setTimeout` turns a longer delay into 1 ms. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/** Throws for a value that is not an integer from 0 to `max`, so a bad option stops startup. */\nfunction checkCount(name: string, value: number, max = Number.MAX_SAFE_INTEGER): void {\n\tif (!Number.isInteger(value) || value < 0 || value > max) {\n\t\tconst range = max === Number.MAX_SAFE_INTEGER ? \"of 0 or more\" : `from 0 to ${max}`;\n\t\tthrow new Error(`${name} must be an integer ${range}, not ${value}.`);\n\t}\n}\n\n/**\n * The request with the scheme from `X-Forwarded-Proto`, when that header holds one.\n *\n * @example\n * withForwardedProto(new Request(\"http://example.com/\", { headers: { \"X-Forwarded-Proto\": \"https\" } })).url;\n * // => \"https://example.com/\"\n */\nexport function withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\t// Why check the scheme first: a new `Request` costs a copy of the request on each call.\n\tif ((proto !== \"http\" && proto !== \"https\") || request.url.startsWith(`${proto}:`)) {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\t// Why copy it first: the Node listener gives a light request, which `new Request` copies only as\n\t// its first argument. As the second, its getters throw \"Illegal invocation\".\n\tconst copy = new Request(url, new Request(request));\n\t// Why: a `Request` cannot hold TRACE, so the Node listener gives a GET request that says TRACE.\n\t// The copy must say TRACE too, or a GET route answers it.\n\tif (copy.method !== request.method) {\n\t\tObject.defineProperty(copy, \"method\", { value: request.method });\n\t}\n\treturn copy;\n}\n\n/**\n * A thrown value as an `Error`. Hono sends only an `Error` to `onError`, and\n * rethrows any other value.\n */\nfunction asError(error: unknown): Error {\n\treturn error instanceof Error\n\t\t? error\n\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,\n * stop startup.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ env }) });\n * app.get(\"/api/status\", (c) => c.json({ ok: true }));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger = jsonSink(),\n\tlisteners,\n\ttrustForwardedProto = false,\n\ttrustedProxyHops = 0,\n\tshutdownDelayMs = 0,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tcheckOptionPlugins(plugins);\n\tcheckCount(\"trustedProxyHops\", trustedProxyHops);\n\tcheckCount(\"shutdownDelayMs\", shutdownDelayMs, MAX_TIMER_MS);\n\tcheckCount(\"shutdownDeadlineMs\", shutdownDeadlineMs, MAX_TIMER_MS);\n\tconst app = new Hono<AppServerEnv>();\n\t// Why keep the handler: a header hook that throws gets the app's `onError` answer, as a stage does.\n\tlet onError: ErrorHandler<AppServerEnv> = answerError;\n\tconst setOnError = app.onError.bind(app);\n\tapp.onError = (handler) => {\n\t\tonError = handler;\n\t\treturn setOnError(handler);\n\t};\n\tapp.onError(answerError);\n\tconst answerThrown = async (thrown: unknown, context: Context<AppServerEnv>) =>\n\t\tonError(asError(thrown), context);\n\tlet requestStore: RequestStore | undefined;\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tconst requestLog = requestLogger(logger, context);\n\t\tcontext.set(\"logger\", requestLog);\n\t\tconst remoteAddress = context.env?.remoteAddress;\n\t\tcontext.set(\n\t\t\t\"clientAddress\",\n\t\t\ttrustedProxyHops === 0\n\t\t\t\t? remoteAddress\n\t\t\t\t: (forwardedClient(context.req.header(\"X-Forwarded-For\"), trustedProxyHops) ??\n\t\t\t\t\t\tremoteAddress),\n\t\t);\n\t\t// Why lists here: each stage's header hook then changes the head once, where the response\n\t\t// leaves, and each report gets the response that leaves.\n\t\tconst hooks: HeaderHook[] = [];\n\t\tconst reports: ((sent: SentResponse) => void)[] = [];\n\t\tcontext.set(\"headerHooks\", hooks);\n\t\tcontext.set(\"sentReports\", reports);\n\t\tconst given = context.env?.edge;\n\t\t// Why claim before the stages: a request that the app sends through itself again with `c.env`\n\t\t// gets the same edge, and must change its own response.\n\t\tconst edge = given?.claim(requestLog) === true ? given : undefined;\n\t\t// Why finish in the request context: a header hook can read `requestContext()`.\n\t\tawait withRequestContext(requestStore, context, async () => {\n\t\t\tawait next();\n\t\t\tconst finishing = finishResponse(context, { hooks, reports, edge, fail: answerThrown });\n\t\t\tif (finishing != null) {\n\t\t\t\tawait finishing;\n\t\t\t}\n\t\t});\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use(async (context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await (middleware == null ? next() : middleware(context, next));\n\t\t\t} catch (error) {\n\t\t\t\tthrow asError(error);\n\t\t\t}\n\t\t});\n\t}\n\tapp.use(async (_, next) => {\n\t\ttry {\n\t\t\tawait next();\n\t\t} catch (error) {\n\t\t\tthrow asError(error);\n\t\t}\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tsetRequestStore: (store) => {\n\t\t\trequestStore = store;\n\t\t},\n\t\tprepare: async (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", async (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})().catch((error: unknown) => {\n\t\t\t\t// Why: the next request on a serverless host runs each `setup` again.\n\t\t\t\tprepared = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework, defaultListeners) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\tconst chosen = listeners ?? defaultListeners ?? [];\n\t\t\tif (chosen.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This app server has no listener: the app sets none, and the host has none. A serverless host calls the entry's `fetch`.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst starts = await Promise.allSettled(\n\t\t\t\tchosen.map(async (listener) => listener.start(fetch, { trustForwardedProto })),\n\t\t\t);\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log(\"info\", \"listening\", { \"app_server.urls\": urls });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: async () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tmarkStopping();\n\t\t\t\t\t\tif (shutdownDelayMs > 0) {\n\t\t\t\t\t\t\tlogger.log(\"info\", \"waiting before the drain\", {\n\t\t\t\t\t\t\t\t\"app_server.delay_ms\": shutdownDelayMs,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\t\t\t\tsetTimeout(resolve, shutdownDelayMs);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log(\"info\", \"draining\", { \"app_server.deadline_ms\": shutdownDeadlineMs });\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\t// Why settle all: the process exits after shutdown, so one failed stop must not cut\n\t\t\t\t\t\t// the other stops short.\n\t\t\t\t\t\tconst results = await Promise.allSettled([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tconst rejected = results.find((result) => result.status === \"rejected\");\n\t\t\t\t\t\tif (rejected != null) {\n\t\t\t\t\t\t\tthrow rejected.reason;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log(\"info\", \"stopped\", {});\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: async () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log(\"error\", \"plugin shutdown failed\", errorAttributes(result.reason));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log(\"warn\", \"plugin shutdown passed the deadline\", {\n\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n"],"mappings":";;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C5B"}
@@ -1,6 +1,6 @@
1
- import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, g as Plugin, h as Mode, m as LogSink, r as FetchHandler, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-DLYxYS6M.js";
2
- import { t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
3
- import { Context, Hono, MiddlewareHandler } from "hono";
1
+ import { g as Plugin, m as LogSink, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-CEvzAmcn.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-BrymAEGv.js";
3
+ import { Context, Hono } from "hono";
4
4
  /** Options for {@link accessLog}. */
5
5
  type AccessLogOptions = {
6
6
  /**
@@ -346,15 +346,18 @@ type PrerenderedOptions = {
346
346
  * returned path follows the rules of a request path: one URL for each
347
347
  * file, no dotfiles, and nothing outside the client build. When the
348
348
  * answer depends on a request header, add a `Vary` for it in a plugin.
349
+ * With `markdownTwins: true`, a request that `rewrite` changes gets no twin.
349
350
  */
350
351
  rewrite?: (path: string, context: Context<AppServerEnv>) => string;
351
352
  /**
352
353
  * Serves the markdown twin of a page, such as `/docs/button.md` for
353
354
  * `/docs/button`, to a request that {@link prefersMarkdown} accepts. A
354
- * page has a twin when `twinOf` names a file in the client build.
355
+ * page has a twin when `twinOf` names a file in the client build. `twinOf`
356
+ * gets the request path and the request's Hono context, the same as
357
+ * `rewrite`. It returns `undefined` for a request with no twin.
355
358
  *
356
359
  * - A request that prefers markdown gets the twin, with the twin's
357
- * captured headers. `rewrite` does not run for it.
360
+ * captured headers.
358
361
  * - Each answer for a path with a twin gets `Vary: Accept`: the twin, the
359
362
  * prerendered HTML, and the framework's answer. The server adds
360
363
  * `Accept` to the `Vary` header and keeps the values in it.
@@ -372,14 +375,15 @@ type PrerenderedOptions = {
372
375
  * a prerendered file.
373
376
  *
374
377
  * `true` uses the default `twinOf`: the path with no trailing slash plus
375
- * `.md`, and `/index.md` for `/`. The returned path follows the rules of a
376
- * request path.
378
+ * `.md`, and `/index.md` for `/`. A request that `rewrite` changes gets no
379
+ * twin, so it gets the same page as a browser. The returned path follows
380
+ * the rules of a request path.
377
381
  *
378
382
  * @example
379
383
  * prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });
380
384
  */
381
385
  markdownTwins?: boolean | {
382
- twinOf: (path: string) => string | undefined;
386
+ twinOf: TwinOf;
383
387
  };
384
388
  /**
385
389
  * Sends a request path to the next stage, with no file lookup. Use it for
@@ -406,6 +410,8 @@ type PrerenderedOptions = {
406
410
  */
407
411
  cacheControl?: (path: string) => string | undefined;
408
412
  };
413
+ /** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */
414
+ type TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefined;
409
415
  /**
410
416
  * Serves the client build: prerendered pages at their own URL with a 200,
411
417
  * plus every other file in it. It sends no redirect. The `trailingSlash`
@@ -565,58 +571,5 @@ type CreateServerOptions = {
565
571
  * export default app;
566
572
  */
567
573
  declare function createServer({ plugins, logger, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
568
- /** The version of the contract between the CLI and the `appServer` export of a build. */
569
- declare const ENTRY_PROTOCOL = 2;
570
- /**
571
- * What a server build exports as `appServer`. The CLI calls it, so the copy
572
- * of this package in the build runs the server, and the CLI's copy runs
573
- * nothing.
574
- */
575
- type AppServerEntry = {
576
- /** The CLI refuses an entry with another version. */
577
- protocol: typeof ENTRY_PROTOCOL;
578
- /** The app. Two entries with the same app share its plugins. */
579
- app: AppServer;
580
- /**
581
- * Production: runs each plugin's `setup` and listens. When the host's
582
- * lifecycle stops, such as on `SIGTERM`, it shuts down.
583
- */
584
- start: () => Promise<void>;
585
- /**
586
- * Production, for a serverless host: answers one request, and does not
587
- * listen. The first call runs each plugin's `setup`.
588
- */
589
- fetch: FetchHandler;
590
- /** Development: answers one request with the dev server inside the pipeline. */
591
- fetchDev: (request: Request, bindings: ListenerBindings, devServer: MiddlewareHandler<AppServerEnv>) => Promise<Response>;
592
- /** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */
593
- stopPlugins: () => Promise<void>;
594
- /** Aborts `shutdownSignal()` of this copy of the package. */
595
- abortShutdownSignal: () => void;
596
- };
597
- /** Options for {@link createEntry}. */
598
- type CreateEntryOptions = {
599
- /** The app from `createServer`. */
600
- app: AppServer;
601
- /** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */
602
- host: HostRuntime;
603
- /** Makes the run side of the framework adapter for a mode. */
604
- framework: (mode: Mode) => FrameworkRuntime;
605
- /**
606
- * The client build, as a file path or a `file:` URL. The entry that the
607
- * Vite plugin generates sets it.
608
- * @default the framework's `clientDirectory`
609
- */
610
- clientDirectory?: string;
611
- };
612
- /**
613
- * The `appServer` export of a server build: an app from `createServer`, the
614
- * host, and the framework adapter for each mode. The `appServer` Vite plugin
615
- * generates this export. Call this for a build without the plugin.
616
- *
617
- * @example
618
- * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
619
- */
620
- declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
621
- export { BuildIdOptions as A, SecurityHeadersOptions as C, redirects as D, RedirectRule as E, AccessLogOptions as M, accessLog as N, HealthOptions as O, SecurityHeaderValues as S, securityHeaders as T, StandardSchemaV1 as _, CreateServerOptions as a, requestId as b, createServer as c, assets as d, prerendered as f, RuntimeEnvOptions as g, RuntimeEnv as h, AppServer as i, buildId as j, health as k, defaultPlugins as l, PUBLIC_ENV_SCRIPT_ID as m, CreateEntryOptions as n, DefaultPluginsOptions as o, InferOutput as p, createEntry as r, RunningServer as s, AppServerEntry as t, PrerenderedOptions as u, runtimeEnv as v, contentSecurityPolicy as w, ContentSecurityPolicyOptions as x, RequestIdOptions as y };
622
- //# sourceMappingURL=entry-DmJEqVfd.d.ts.map
574
+ export { accessLog as A, RedirectRule as C, BuildIdOptions as D, health as E, buildId as O, securityHeaders as S, HealthOptions as T, requestId as _, createServer as a, SecurityHeadersOptions as b, assets as c, PUBLIC_ENV_SCRIPT_ID as d, RuntimeEnv as f, RequestIdOptions as g, runtimeEnv as h, RunningServer as i, AccessLogOptions as k, prerendered as l, StandardSchemaV1 as m, CreateServerOptions as n, defaultPlugins as o, RuntimeEnvOptions as p, DefaultPluginsOptions as r, PrerenderedOptions as s, AppServer as t, InferOutput as u, ContentSecurityPolicyOptions as v, redirects as w, contentSecurityPolicy as x, SecurityHeaderValues as y };
575
+ //# sourceMappingURL=create-server-kzZWd_Lo.d.ts.map