@ngrok/app-server 0.3.2 → 0.3.3
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.
- package/README.md +51 -15
- package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
- package/dist/build-id-B0448vZH.js.map +1 -0
- package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
- package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/client-browser.js +1 -1
- package/dist/client.js +1 -1
- package/dist/{create-server-kzZWd_Lo.d.ts → create-server-D4-nVOVJ.d.ts} +50 -13
- package/dist/{create-server-D0De6R7Q.js → create-server-jMl2ltHD.js} +572 -522
- package/dist/create-server-jMl2ltHD.js.map +1 -0
- package/dist/{entry-DuGgSKeB.d.ts → entry-BPrgE_6K.d.ts} +39 -3
- package/dist/entry-D9H4LA9c.js +351 -0
- package/dist/entry-D9H4LA9c.js.map +1 -0
- package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
- package/dist/index.d.ts +5 -15
- package/dist/index.js +3 -3
- package/dist/{load-entry-Bodyd2Ok.js → load-entry-D7r0mjEp.js} +3 -3
- package/dist/{load-entry-Bodyd2Ok.js.map → load-entry-D7r0mjEp.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/react-router-vite.d.ts +1 -1
- package/dist/react-router.d.ts +3 -2
- package/dist/react-router.js +31 -2
- package/dist/react-router.js.map +1 -1
- package/dist/{serve-caOkS3o5.js → serve-E0hSGe6_.js} +2 -2
- package/dist/{serve-caOkS3o5.js.map → serve-E0hSGe6_.js.map} +1 -1
- package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
- package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
- package/dist/{start-DREqYrZh.js → start-CifYPRq1.js} +33 -5
- package/dist/start-CifYPRq1.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +2 -2
- package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
- package/dist/{types-CEvzAmcn.d.ts → types-j29vspx_.d.ts} +15 -1
- package/dist/vercel-pages.d.ts +32 -0
- package/dist/vercel-pages.js +54 -0
- package/dist/vercel-pages.js.map +1 -0
- package/dist/vercel-vite.d.ts +30 -9
- package/dist/vercel-vite.js +160 -17
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +1 -1
- package/dist/{vite-tTxVimP6.js → vite-BDREIgiH.js} +44 -19
- package/dist/vite-BDREIgiH.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/build-id-C6sYO9Yp.js.map +0 -1
- package/dist/build-manifest-UDNk81Ce.js.map +0 -1
- package/dist/create-server-D0De6R7Q.js.map +0 -1
- package/dist/entry-UDsxuqBC.js +0 -116
- package/dist/entry-UDsxuqBC.js.map +0 -1
- package/dist/start-DREqYrZh.js.map +0 -1
- package/dist/vite-tTxVimP6.js.map +0 -1
package/dist/vite.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SERVER_ENTRY_ID, i as HostOutput, n as FrameworkBuild, o as appServer, r as HostBuild, s as serverEntrySource, t as AppServerOptions } from "./index-
|
|
1
|
+
import { a as SERVER_ENTRY_ID, i as HostOutput, n as FrameworkBuild, o as appServer, r as HostBuild, s as serverEntrySource, t as AppServerOptions } from "./index-Db7dspq6.js";
|
|
2
2
|
export { AppServerOptions, FrameworkBuild, HostBuild, HostOutput, SERVER_ENTRY_ID, appServer, serverEntrySource };
|
package/dist/vite.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ngrok/app-server",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "A composable Hono app server for React Router and TanStack Start: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, Deno, and Vercel.",
|
|
5
5
|
"homepage": "https://github.com/ngrok/app-server#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-id-C6sYO9Yp.js","names":[],"sources":["../src/core/plugin-options.ts","../src/core/plugins/build-id.ts"],"sourcesContent":["import type { Plugin } from \"./types.js\";\n\n/**\n * The option of `defaultPlugins()` that places each plugin, by plugin\n * object. Why the object, not the name: an app plugin can have any name.\n */\nconst options = new WeakMap<Plugin, string>();\n\n/**\n * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so\n * `createServer` finds it in the plugin list.\n *\n * @example\n * return optionPlugin(\"noindex\", { name: \"noindex\", middleware });\n */\nexport function optionPlugin<P extends Plugin>(option: string, plugin: P): P {\n\toptions.set(plugin, option);\n\treturn plugin;\n}\n\n/**\n * Stops startup when `plugins` has two plugins of one option of\n * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.\n * One sets its headers over the other, so a value that the app gave is lost.\n *\n * @example\n * checkOptionPlugins([...defaultPlugins(), buildId({ value: \"v42\" })]); // throws\n */\nexport function checkOptionPlugins(plugins: readonly Plugin[]): void {\n\tconst seen = new Set<string>();\n\tfor (const plugin of plugins) {\n\t\tconst option = options.get(plugin);\n\t\tif (option != null && seen.has(option)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the \"${option}\" option of defaultPlugins(), and do not also add the plugin.`,\n\t\t\t);\n\t\t}\n\t\tif (option != null) {\n\t\t\tseen.add(option);\n\t\t}\n\t}\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin, ResponseHeaders, SetupInfo } from \"../types.js\";\n\n/** The header that {@link buildId} sets by default. */\nexport const BUILD_ID_HEADER = \"X-Build-Id\";\n\n/**\n * The `Server-Timing` metric that holds the build of a response. Why\n * `Server-Timing`: a script can read it from the performance entries, with no\n * request and no change to the document's HTML.\n */\nexport const BUILD_ID_METRIC = \"build\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/**\n\t * The deployed build, such as the image tag. With no value or `\"\"`, the\n\t * plugin sends the ID that the `appServer` Vite plugin derives from the\n\t * client build. In development, it then sends no build.\n\t * @default the `buildId` of `.app-server.json` in the client build\n\t */\n\tvalue?: string | undefined;\n\t/**\n\t * More request paths whose responses carry the build in `Server-Timing`,\n\t * such as the app's proxy routes to its API. A tab then finds a new build\n\t * in the requests that it already sends. They get no build header, because\n\t * the header marks the router's own responses. A response that a cache can\n\t * use again without the server gets no build, so a cached copy never\n\t * reports an old build. It runs in a header hook, so it can run more than\n\t * once for one request.\n\t *\n\t * @example\n\t * buildId({ paths: (path) => path.startsWith(\"/api/\") });\n\t */\n\tpaths?: (path: string) => boolean;\n};\n\n/**\n * Whether a cache can use the response again without the server: it has a\n * fresh time, a stale time, or a date that a cache can guess a fresh time from.\n */\nfunction isReusable(response: ResponseHeaders): boolean {\n\tconst cacheControl = response.get(\"Cache-Control\") ?? \"\";\n\tif (/\\b(?:no-store|no-cache)\\b/iu.test(cacheControl)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t/\\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\\s*=\\s*\"?0*[1-9]/iu.test(\n\t\t\tcacheControl,\n\t\t) ||\n\t\t/\\bpublic\\b/iu.test(cacheControl) ||\n\t\tDate.parse(response.get(\"Expires\") ?? \"\") > Date.now() ||\n\t\tresponse.has(\"Last-Modified\")\n\t);\n}\n\n/** The metrics of a `Server-Timing` header, such as `build;desc=\"v42\"`. */\nexport function serverTimingMetrics(header: string | null): string[] {\n\t// Why match the quoted strings: a comma or an escaped quote in a description does not end a metric.\n\treturn (header?.match(/(?:[^\",]|\"(?:[^\"\\\\]|\\\\.)*\")+/gu) ?? [])\n\t\t.map((metric) => metric.trim())\n\t\t.filter((metric) => metric !== \"\");\n}\n\n/** Whether a `Server-Timing` metric is a build. */\nexport function isBuildMetric(metric: string): boolean {\n\treturn metric.split(\";\")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;\n}\n\n/** The `Server-Timing` metrics of `header` that are not a build. */\nfunction otherMetrics(header: string | null): string[] {\n\treturn serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));\n}\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/** A `Server-Timing` quoted string with the characters of `value`. */\nfunction quoted(value: string): string {\n\treturn `\"${value.replaceAll(/[\"\\\\]/gu, String.raw`\\$&`)}\"`;\n}\n\n/** The `build` metric of `value`, or `undefined` for no build. */\nfunction buildMetric(value: string | undefined): string | undefined {\n\treturn value == null ? undefined : `${BUILD_ID_METRIC};desc=${quoted(value)}`;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it. Each of them also gets the build as\n * `Server-Timing: build;desc=\"<value>\"`. The `paths` option adds the metric\n * to more routes, such as API proxy routes. The plugin removes the build\n * header and the `build` metric of an upstream API from each other\n * response, so the client reads only this app's build.\n * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric\n * from the document, and from a response that the browser fetches with no\n * script, such as a prefetch.\n *\n * With no `value`, it sends the build ID that the `appServer` Vite plugin\n * derives from the client build. Development and a build with no\n * `.app-server.json` then get no build.\n *\n * @example\n * buildId({ value: process.env.IMAGE_TAG });\n */\nexport function buildId({\n\theader = BUILD_ID_HEADER,\n\tvalue: given,\n\tpaths,\n}: BuildIdOptions = {}): Plugin {\n\t// Why `\"\"` too: a deploy can set the variable with no value, such as `IMAGE_TAG=`.\n\tconst explicit = given === \"\" ? undefined : given;\n\tlet value = explicit;\n\tlet timing = buildMetric(value);\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn optionPlugin(\"buildId\", {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t\tvalue = explicit ?? info.buildId;\n\t\t\ttiming = buildMetric(value);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tconst { path } = context.req;\n\t\t\t\tconst isRouter =\n\t\t\t\t\t(response.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) || isDataRequest(path);\n\t\t\t\tconst isStamped = isRouter || (paths?.(path) === true && !isReusable(response));\n\t\t\t\t// Why remove the build of an upstream API: the client must read only this app's build.\n\t\t\t\tconst before = response.get(\"Server-Timing\");\n\t\t\t\tconst metrics = [\n\t\t\t\t\t...otherMetrics(before),\n\t\t\t\t\t...(isStamped && timing != null ? [timing] : []),\n\t\t\t\t].join(\", \");\n\t\t\t\tif (metrics === \"\") {\n\t\t\t\t\tresponse.delete(\"Server-Timing\");\n\t\t\t\t} else if (metrics !== before) {\n\t\t\t\t\tresponse.set(\"Server-Timing\", metrics);\n\t\t\t\t}\n\t\t\t\tif (isRouter && value != null) {\n\t\t\t\t\tresponse.set(header, value);\n\t\t\t\t} else {\n\t\t\t\t\tresponse.delete(header);\n\t\t\t\t}\n\t\t\t}),\n\t});\n}\n"],"mappings":";;;;;;;AAMA,MAAM,0BAAU,IAAI,QAAwB;;;;;;;;AAS5C,SAAgB,aAA+B,QAAgB,QAAc;CAC5E,QAAQ,IAAI,QAAQ,MAAM;CAC1B,OAAO;AACR;;;;;;;;;AAUA,SAAgB,mBAAmB,SAAkC;CACpE,MAAM,uBAA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EACvB,SAAS,iBACT,OAAO,OACP,UACmB,CAAC,GAAW;CAE/B,MAAM,WAAW,UAAU,KAAK,SAAY;CAC5C,IAAI,QAAQ;CACZ,IAAI,SAAS,YAAY,KAAK;CAC9B,IAAI,gBAA4C;CAChD,OAAO,aAAa,WAAW;EAC9B,MAAM;EACN,QAAQ,SAAS;GAChB,CAAC,CAAE,iBAAkB;GACrB,QAAQ,YAAY,KAAK;GACzB,SAAS,YAAY,KAAK;EAC3B;EAGA,gBAAgB;EAChB,YAAY,OAAO,SAAS,SAC3B,eAAe,SAAS,OAAO,aAAa;GAC3C,MAAM,EAAE,SAAS,QAAQ;GACzB,MAAM,YACJ,SAAS,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,UAAU,cAAc,IAAI;GACvF,MAAM,YAAY,YAAa,QAAQ,IAAI,MAAM,QAAQ,CAAC,WAAW,QAAQ;GAE7E,MAAM,SAAS,SAAS,IAAI,eAAe;GAC3C,MAAM,UAAU,CACf,GAAG,aAAa,MAAM,GACtB,GAAI,aAAa,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,CAC/C,CAAC,CAAC,KAAK,IAAI;GACX,IAAI,YAAY,IACf,SAAS,OAAO,eAAe;QACzB,IAAI,YAAY,QACtB,SAAS,IAAI,iBAAiB,OAAO;GAEtC,IAAI,YAAY,SAAS,MACxB,SAAS,IAAI,QAAQ,KAAK;QAE1B,SAAS,OAAO,MAAM;EAExB,CAAC;CACH,CAAC;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-manifest-UDNk81Ce.js","names":[],"sources":["../src/core/build-manifest.ts"],"sourcesContent":["import type { StaticFiles } from \"./types.js\";\n\n/**\n * The file under the client build that the Vite plugin writes after the\n * client build and again after the prerender pass. It is a dotfile, so the\n * static stages never serve it.\n */\nexport const BUILD_MANIFEST_FILE = \".app-server.json\";\n\n/** What the Vite plugin records about the client build. */\nexport type BuildManifest = {\n\t/**\n\t * The ID of the client build: a hash of the files that the client build\n\t * writes. The `buildId` plugin sends it by default.\n\t */\n\tbuildId?: string;\n\t/** The URL paths that answered with a 2xx, sorted. */\n\tprerendered: string[];\n\t/** The headers of each prerendered file that is not an HTML document, by URL path. */\n\theaders: Record<string, Record<string, string>>;\n\t/**\n\t * The base64 `SHA-256` of each inline script of each HTML file in the client\n\t * build, by the file's URL path, such as `/about/index.html`. A CSP trusts\n\t * the scripts of a prerendered page by these hashes.\n\t */\n\tscriptHashes: Record<string, string[]>;\n};\n\n/**\n * The key for a URL path in {@link BuildManifest}: the path with no trailing\n * slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * manifestKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function manifestKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/u, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */\nfunction buildIdOf(manifest: object): Pick<BuildManifest, \"buildId\"> {\n\tif (!(\"buildId\" in manifest)) {\n\t\treturn {};\n\t}\n\tif (typeof manifest.buildId !== \"string\") {\n\t\tthrow new TypeError(`${BUILD_MANIFEST_FILE}: the \"buildId\" must be a string.`);\n\t}\n\treturn { buildId: manifest.buildId };\n}\n\n/**\n * Reads the build manifest of a client build. A build with no file has an\n * empty one. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readBuildManifest(files: StaticFiles): Promise<BuildManifest> {\n\tconst path = `/${BUILD_MANIFEST_FILE}`;\n\tif ((await files.stat(path))?.kind !== \"file\") {\n\t\treturn { prerendered: [], headers: {}, scriptHashes: {} };\n\t}\n\tconst parsed: unknown = await new Response(await files.open(path)).json();\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed == null ||\n\t\t!(\"prerendered\" in parsed) ||\n\t\t!isStringList(parsed.prerendered) ||\n\t\t!(\"headers\" in parsed) ||\n\t\ttypeof parsed.headers !== \"object\" ||\n\t\tparsed.headers == null ||\n\t\t!(\"scriptHashes\" in parsed) ||\n\t\ttypeof parsed.scriptHashes !== \"object\" ||\n\t\tparsed.scriptHashes == null\n\t) {\n\t\tthrow new Error(\n\t\t\t`${BUILD_MANIFEST_FILE} must hold a \"prerendered\" list and the \"headers\" and \"scriptHashes\" objects.`,\n\t\t);\n\t}\n\tconst headers: Record<string, Record<string, string>> = {};\n\tfor (const [key, value] of Object.entries(parsed.headers)) {\n\t\tif (!isStringRecord(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);\n\t\t}\n\t\theaders[key] = value;\n\t}\n\tconst scriptHashes: Record<string, string[]> = {};\n\tfor (const [key, value] of Object.entries(parsed.scriptHashes)) {\n\t\tif (!isStringList(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);\n\t\t}\n\t\tscriptHashes[key] = value;\n\t}\n\treturn {\n\t\t...buildIdOf(parsed),\n\t\tprerendered: parsed.prerendered,\n\t\theaders,\n\t\tscriptHashes,\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;;;;;;;AA4BnC,SAAgB,YAAY,UAA0B;CACrD,MAAM,UAAU,SAAS,QAAQ,SAAS,EAAE;CAC5C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;AAEA,SAAS,aAAa,OAAmC;CACxD,O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UAAU,MAAM;EACnB,aAAa,OAAO;EACpB;EACA;CACD;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
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":";;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,UAAU,KAAU,EAAE,UAAuC;CAC5E,IAAI,CAAC,UAAU,IAAI,WAAW,IAC7B,OAAO,GAAG,IAAI,WAAW,IAAI;CAE9B,MAAM,QAAQ,CAAC,GAAG,IAAI,aAAa,KAAK,CAAC,CAAC,CACxC,KAAK,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,CAAC;MACF;MACA,OAAO,IAAI,QAAQ,YAAY,EAAE,0BAA0B,mBAAmB,CAAC;MAC/E,oBAAoB;MACpB,MAAM,WAAW,iBAAiB;OACjC,iBAAiB;MAClB,GAAG,kBAAkB;MAIrB,MAAM,UAAU,MAAM,QAAQ,WAAW,CACxC,UAAU,YAAY,GACtB,GAAG,QAAQ,IAAI,OAAO,aAAa,SAAS,KAAK,EAAE,YAAY,mBAAmB,CAAC,CAAC,CACrF,CAAC;MACD,aAAa,QAAQ;MACrB,MAAM,WAAW,QAAQ,MAAM,WAAW,OAAO,WAAW,UAAU;MACtE,IAAI,YAAY,MACf,MAAM,SAAS;MAEhB,OAAO,IAAI,QAAQ,WAAW,CAAC,CAAC;KACjC,EAAC,CAAE;KACH,OAAO;IACR;GACD;GACA,OAAO;EACR;EACA,aAAa,YAAY;GACxB,qBAAqB,YAAY;IAWhC,IAAI,CAAE,MAAM,eAVG,YAAY;KAC1B,MAAM,UAAU,MAAM,QAAQ,WAC7B,QAAQ,IAAI,OAAO,WAAW,OAAO,aAAa,CAAC,CACpD;KACA,KAAK,MAAM,UAAU,SACpB,IAAI,OAAO,WAAW,YACrB,OAAO,IAAI,SAAS,0BAA0B,gBAAgB,OAAO,MAAM,CAAC;IAG/E,EAAC,CAC6B,GAAG,kBAAkB,GAClD,OAAO,IAAI,QAAQ,uCAAuC,EACzD,0BAA0B,mBAC3B,CAAC;GAEH,EAAC,CAAE;GACH,OAAO;EACR;CACD;CACA,aAAa,IAAI,KAAK,SAAS;CAC/B,OAAO;AACR;;AAGA,SAAgB,gBAAgB,KAA6C;CAC5E,OAAO,aAAa,IAAI,GAAG;AAC5B"}
|
package/dist/entry-UDsxuqBC.js
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import { t as errorAttributes } from "./log-BP6xXXZl.js";
|
|
2
|
-
import { _ as abortShutdownSignal, r as serverInternals } from "./create-server-D0De6R7Q.js";
|
|
3
|
-
import { a as keptFiles } from "./static-files-Beju9riB.js";
|
|
4
|
-
import { r as readBuildManifest } from "./build-manifest-UDNk81Ce.js";
|
|
5
|
-
|
|
6
|
-
// src/core/entry.ts
|
|
7
|
-
/** The version of the contract between the CLI and the `appServer` export of a build. */
|
|
8
|
-
const ENTRY_PROTOCOL = 2;
|
|
9
|
-
/**
|
|
10
|
-
* The `appServer` export of a server build: an app from `createServer`, the
|
|
11
|
-
* host, and the framework adapter for each mode. The `appServer` Vite plugin
|
|
12
|
-
* generates this export. Call this for a build without the plugin.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
|
|
16
|
-
*/
|
|
17
|
-
function createEntry({ app, host, framework, clientDirectory }) {
|
|
18
|
-
const internals = serverInternals(app);
|
|
19
|
-
if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
|
|
20
|
-
internals.setRequestStore(host.storage);
|
|
21
|
-
const setupInfo = async (runtime) => {
|
|
22
|
-
const directory = clientDirectory ?? runtime.clientDirectory;
|
|
23
|
-
if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
|
|
24
|
-
return {
|
|
25
|
-
files: host.files(directory),
|
|
26
|
-
isDataRequest: runtime.isDataRequest ?? (() => false),
|
|
27
|
-
contentTypes: runtime.contentTypes ?? {},
|
|
28
|
-
gzip: host.gzip,
|
|
29
|
-
logger: internals.logger
|
|
30
|
-
};
|
|
31
|
-
};
|
|
32
|
-
/** Runs each plugin's `setup` for production, and gives the framework's run side. */
|
|
33
|
-
const prepareProduction = async () => {
|
|
34
|
-
const runtime = framework("production");
|
|
35
|
-
const shared = await setupInfo(runtime);
|
|
36
|
-
const snapshot = await shared.files.snapshot?.();
|
|
37
|
-
const files = snapshot == null ? shared.files : keptFiles(snapshot);
|
|
38
|
-
const manifest = await readBuildManifest(files);
|
|
39
|
-
const info = {
|
|
40
|
-
...shared,
|
|
41
|
-
files,
|
|
42
|
-
mode: "production",
|
|
43
|
-
prerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,
|
|
44
|
-
capturedHeaders: new Map(Object.entries(manifest.headers)),
|
|
45
|
-
scriptHashes: new Map(Object.entries(manifest.scriptHashes)),
|
|
46
|
-
buildId: manifest.buildId
|
|
47
|
-
};
|
|
48
|
-
await internals.prepare(info);
|
|
49
|
-
return runtime;
|
|
50
|
-
};
|
|
51
|
-
let preparing;
|
|
52
|
-
/**
|
|
53
|
-
* The production run side, set up once. Why forget a failure: a serverless
|
|
54
|
-
* instance stays up, so the next request runs each `setup` again.
|
|
55
|
-
*/
|
|
56
|
-
const production = async () => {
|
|
57
|
-
preparing ??= prepareProduction().catch((error) => {
|
|
58
|
-
preparing = void 0;
|
|
59
|
-
throw error;
|
|
60
|
-
});
|
|
61
|
-
return preparing;
|
|
62
|
-
};
|
|
63
|
-
let development;
|
|
64
|
-
return {
|
|
65
|
-
protocol: 2,
|
|
66
|
-
app,
|
|
67
|
-
start: async () => {
|
|
68
|
-
const runtime = await production();
|
|
69
|
-
const server = await internals.listen(runtime, host.listeners?.());
|
|
70
|
-
host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
|
|
71
|
-
internals.logger.log("error", "shutdown failed", errorAttributes(error));
|
|
72
|
-
throw error;
|
|
73
|
-
}));
|
|
74
|
-
},
|
|
75
|
-
fetch: async (request, bindings) => {
|
|
76
|
-
const runtime = await production().catch((error) => {
|
|
77
|
-
internals.logger.log("error", "setup failed", errorAttributes(error));
|
|
78
|
-
throw error;
|
|
79
|
-
});
|
|
80
|
-
return app.fetch(request, {
|
|
81
|
-
...bindings,
|
|
82
|
-
framework: runtime
|
|
83
|
-
});
|
|
84
|
-
},
|
|
85
|
-
fetchDev: async (request, bindings, devServer) => {
|
|
86
|
-
development ??= framework("development");
|
|
87
|
-
await internals.prepare({
|
|
88
|
-
...await setupInfo(development),
|
|
89
|
-
mode: "development",
|
|
90
|
-
devServer,
|
|
91
|
-
prerenderedPaths: development.prerenderedPaths,
|
|
92
|
-
capturedHeaders: /* @__PURE__ */ new Map(),
|
|
93
|
-
scriptHashes: /* @__PURE__ */ new Map(),
|
|
94
|
-
buildId: void 0
|
|
95
|
-
});
|
|
96
|
-
return app.fetch(request, {
|
|
97
|
-
...bindings,
|
|
98
|
-
framework: development
|
|
99
|
-
});
|
|
100
|
-
},
|
|
101
|
-
stopPlugins: internals.stopPlugins,
|
|
102
|
-
abortShutdownSignal
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Whether a value is an entry of this protocol version.
|
|
107
|
-
*
|
|
108
|
-
* @example
|
|
109
|
-
* isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
|
|
110
|
-
*/
|
|
111
|
-
function isAppServerEntry(value) {
|
|
112
|
-
return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export { isAppServerEntry as n, createEntry as t };
|
|
116
|
-
//# sourceMappingURL=entry-UDsxuqBC.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"entry-UDsxuqBC.js","names":[],"sources":["../src/core/entry.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log(\"error\", \"setup failed\", errorAttributes(error));\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,iBAAiB;;;;;;;;;AA0D9B,SAAgB,YAAY,EAC3B,KACA,MACA,WACA,mBACsC;CACtC,MAAM,YAAY,gBAAgB,GAA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OAAO,IAAI,SAAS,mBAAmB,gBAAgB,KAAK,CAAC;IACvE,MAAM;GACP,CAAC,CACF;EACD;EACA,OAAO,OAAO,SAAS,aAAa;GAEnC,MAAM,UAAU,MAAM,WAAW,CAAC,CAAC,OAAO,UAAmB;IAC5D,UAAU,OAAO,IAAI,SAAS,gBAAgB,gBAAgB,KAAK,CAAC;IACpE,MAAM;GACP,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC;EAC9D;EACA,UAAU,OAAO,SAAS,UAAU,cAAc;GACjD,gBAAgB,UAAU,aAAa;GACvC,MAAM,UAAU,QAAQ;IACvB,GAAI,MAAM,UAAU,WAAW;IAC/B,MAAM;IACN;IACA,kBAAkB,YAAY;IAC9B,iCAAiB,IAAI,IAAI;IACzB,8BAAc,IAAI,IAAI;IAEtB,SAAS;GACV,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"start-DREqYrZh.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,W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