@ngrok/app-server 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +3 -3
  3. package/dist/{compress-JuJf2HaO.js → compress-Cp5NfXCC.js} +141 -23
  4. package/dist/compress-Cp5NfXCC.js.map +1 -0
  5. package/dist/{create-server-BX2rH6-E.js → create-server-C_90R50y.js} +11 -9
  6. package/dist/{create-server-BX2rH6-E.js.map → create-server-C_90R50y.js.map} +1 -1
  7. package/dist/{entry-ChHgs269.js → entry-65IESBSA.js} +3 -3
  8. package/dist/{entry-ChHgs269.js.map → entry-65IESBSA.js.map} +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.js +4 -4
  11. package/dist/{load-entry-BOgJPt1I.js → load-entry-BftQ3qlz.js} +4 -4
  12. package/dist/{load-entry-BOgJPt1I.js.map → load-entry-BftQ3qlz.js.map} +1 -1
  13. package/dist/{log-BP6xXXZl.js → log-C8LGQ23s.js} +29 -2
  14. package/dist/log-C8LGQ23s.js.map +1 -0
  15. package/dist/{node-B0AYf_IA.js → node-CA7t-s6D.js} +4 -4
  16. package/dist/{node-B0AYf_IA.js.map → node-CA7t-s6D.js.map} +1 -1
  17. package/dist/{node-C0Ad7CVL.js → node-Fo6EodEV.js} +2 -2
  18. package/dist/{node-C0Ad7CVL.js.map → node-Fo6EodEV.js.map} +1 -1
  19. package/dist/node.js +2 -2
  20. package/dist/react-router.js +1 -1
  21. package/dist/{response-edge-Bc1-C_Cx.js → response-edge-D3CAjukJ.js} +2 -2
  22. package/dist/{response-edge-Bc1-C_Cx.js.map → response-edge-D3CAjukJ.js.map} +1 -1
  23. package/dist/{response-writer-DzvUAz9x.js → response-writer-BUyOW4n2.js} +3 -3
  24. package/dist/{response-writer-DzvUAz9x.js.map → response-writer-BUyOW4n2.js.map} +1 -1
  25. package/dist/{serve-BUJ7ZonG.js → serve-CEecObwD.js} +2 -2
  26. package/dist/{serve-BUJ7ZonG.js.map → serve-CEecObwD.js.map} +1 -1
  27. package/dist/{start-DiQf9ttp.js → start-CDnHKNca.js} +63 -8
  28. package/dist/start-CDnHKNca.js.map +1 -0
  29. package/dist/{tcp-Bws6oEau.js → tcp-BPeUZaNg.js} +2 -2
  30. package/dist/{tcp-Bws6oEau.js.map → tcp-BPeUZaNg.js.map} +1 -1
  31. package/dist/testing.js +3 -3
  32. package/dist/vercel.js +4 -4
  33. package/package.json +1 -1
  34. package/dist/compress-JuJf2HaO.js.map +0 -1
  35. package/dist/log-BP6xXXZl.js.map +0 -1
  36. package/dist/start-DiQf9ttp.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { t as errorAttributes } from "./log-BP6xXXZl.js";
1
+ import { t as errorAttributes } from "./log-C8LGQ23s.js";
2
2
  import { i as readBuildManifest, n as DEFAULT_ASSETS_PATH } from "./build-manifest-DBMWe3Lx.js";
3
- import { p as abortShutdownSignal, r as serverInternals } from "./create-server-BX2rH6-E.js";
3
+ import { p as abortShutdownSignal, r as serverInternals } from "./create-server-C_90R50y.js";
4
4
  import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
5
5
 
6
6
  // src/core/static-pages.ts
@@ -349,4 +349,4 @@ function isAppServerEntry(value) {
349
349
  }
350
350
 
351
351
  export { isAppServerEntry as n, createEntry as t };
352
- //# sourceMappingURL=entry-ChHgs269.js.map
352
+ //# sourceMappingURL=entry-65IESBSA.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry-ChHgs269.js","names":[],"sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, 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 { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.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/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\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\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\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\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = 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\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\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":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAAM,UAAU,CACf;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EAAE,QAAQ;EAAgB,cAAc;CAAmB;AACrE,GACA;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EACR,QAAQ;EACR,mBAAmB;EACnB,eAAe;EACf,QAAQ;EACR,SAAS;EACT,cAAc;EACd,oBAAoB;EACpB,uBAAuB;EACvB,8BAA8B;CAC/B;AACD,CACD;;;;;AAMA,eAAe,OACd,OACA,MACA,EACC,QACA,UACA,WAMiB;CAElB,MAAM,UAAU,IAAI,QAAQ;EAAE,GAAG,OAAO;EAAS,MAAM,IAAI,IAAI,OAAO,MAAM,CAAC,CAAC;CAAK,CAAC;CACpF,KAAK,MAAM,QAAQ,UAClB,IAAI,QAAQ,SAAS,IAAI,GACxB,QAAQ,IAAI,MAAM,OAAO,YAAY;MAErC,QAAQ,OAAO,IAAI;CAGrB,MAAM,UAAU,IAAI,QAAQ,GAAG,OAAO,SAAS,OAAO,OAAO,SAAS,EAAE,QAAQ,CAAC;CACjF,IAAI;CACJ,MAAM,WAAW,MAAM,MAAM,SAAS;EACrC,eAAe,OAAO;EACtB,eAAe,WAAW;GACzB,OAAO;EACR;CACD,CAAC;CACD,IA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sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, 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 { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.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/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\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\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\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\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = 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\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\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":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAAM,UAAU,CACf;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EAAE,QAAQ;EAAgB,cAAc;CAAmB;AACrE,GACA;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EACR,QAAQ;EACR,mBAAmB;EACnB,eAAe;EACf,QAAQ;EACR,SAAS;EACT,cAAc;EACd,oBAAoB;EACpB,uBAAuB;EACvB,8BAA8B;CAC/B;AACD,CACD;;;;;AAMA,eAAe,OACd,OACA,MACA,EACC,QACA,UACA,WAMiB;CAElB,MAAM,UAAU,IAAI,QAAQ;EAAE,GAAG,OAAO;EAAS,MAAM,IAAI,IAAI,OAAO,MAAM,CAAC,CAAC;CAAK,CAAC;CACpF,KAAK,MAAM,QAAQ,UAClB,IAAI,QAAQ,SAAS,IAAI,GACxB,Q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SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC,GACnF,kBACA,EAAE,UAAU,UAAU,gBAAgB,CACvC;EACD;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
package/dist/index.d.ts CHANGED
@@ -115,7 +115,7 @@ export declare function privateDocuments(): Plugin;
115
115
  * chunk, so a streamed page shell or a server-sent event reaches the client
116
116
  * at once. A client gets brotli when its `Accept-Encoding` ranks `br` at
117
117
  * least as high as `gzip`. Chunks that the body has queued together are one
118
- * chunk, up to 16 KiB. `hono/compress` holds a stream until it ends. Skips a
118
+ * chunk, up to 64 KiB. `hono/compress` holds a stream until it ends. Skips a
119
119
  * response that is already encoded, a partial response, one marked
120
120
  * `no-transform`, and one whose `Content-Length` is under 1 KiB. It adds
121
121
  * `Accept-Encoding` to the `Vary` of each response that it can compress. The
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { t as requestContext } from "./request-context-BtQ87VYb.js";
2
2
  import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
3
3
  import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
4
- import { r as jsonSink } from "./log-BP6xXXZl.js";
5
- import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
6
- import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-BX2rH6-E.js";
7
- import { t as createEntry } from "./entry-ChHgs269.js";
4
+ import { r as jsonSink } from "./log-C8LGQ23s.js";
5
+ import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
6
+ import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-C_90R50y.js";
7
+ import { t as createEntry } from "./entry-65IESBSA.js";
8
8
 
9
9
  // src/core/event-stream.ts
10
10
  function formatEvent({ data, event, id }) {
@@ -1,6 +1,6 @@
1
- import { t as createServer } from "./create-server-BX2rH6-E.js";
2
- import { n as isAppServerEntry, t as createEntry } from "./entry-ChHgs269.js";
3
- import { t as host } from "./node-B0AYf_IA.js";
1
+ import { t as createServer } from "./create-server-C_90R50y.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-65IESBSA.js";
3
+ import { t as host } from "./node-CA7t-s6D.js";
4
4
 
5
5
  // src/cli/load-entry.ts
6
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -34,4 +34,4 @@ async function loadEntry(build) {
34
34
  }
35
35
 
36
36
  export { loadEntry as t };
37
- //# sourceMappingURL=load-entry-BOgJPt1I.js.map
37
+ //# sourceMappingURL=load-entry-BftQ3qlz.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-BOgJPt1I.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-BftQ3qlz.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
@@ -54,6 +54,33 @@ function jsonSink(write = writeStdout) {
54
54
  })}\n`);
55
55
  } };
56
56
  }
57
+ /**
58
+ * A log sink that writes one line of `key=value` pairs per event, in the text
59
+ * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control
60
+ * character is quoted, so an escape sequence cannot reach the terminal.
61
+ * `app-server start` uses it, because a person reads those lines.
62
+ *
63
+ * @param write - Where each line goes. Defaults to stdout, at once. Why not
64
+ * one write for each turn: the lines then keep their order with Vite's lines.
65
+ *
66
+ * @example
67
+ * textSink().log("info", "port in use, trying the next port", { "server.port": 3000 });
68
+ * // time=2026-11-11T12:00:00.000Z level=INFO msg="port in use, trying the next port" server.port=3000
69
+ */
70
+ function textSink(write = (line) => {
71
+ process.stdout.write(line);
72
+ }) {
73
+ return { log: (level, message, attributes) => {
74
+ let line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;
75
+ for (const [key, value] of Object.entries(attributes)) line += ` ${key}=${textValue(value)}`;
76
+ write(`${line}\n`);
77
+ } };
78
+ }
79
+ /** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */
80
+ function textValue(value) {
81
+ const text = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
82
+ return /^[^\s"=\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);
83
+ }
57
84
  /** The millisecond of the last `time`, and its ISO string. */
58
85
  let lastMs = NaN;
59
86
  let lastTime = "";
@@ -118,5 +145,5 @@ function requestLogger(sink, context) {
118
145
  }));
119
146
  }
120
147
 
121
- export { sinkLogger as a, requestLogger as i, flushLogs as n, jsonSink as r, errorAttributes as t };
122
- //# sourceMappingURL=log-BP6xXXZl.js.map
148
+ export { sinkLogger as a, requestLogger as i, flushLogs as n, textSink as o, jsonSink as r, errorAttributes as t };
149
+ //# sourceMappingURL=log-C8LGQ23s.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-C8LGQ23s.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(`${JSON.stringify({ time: isoNow(), level, message, ...attributes })}\\n`);\n\t\t},\n\t};\n}\n\n/**\n * A log sink that writes one line of `key=value` pairs per event, in the text\n * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control\n * character is quoted, so an escape sequence cannot reach the terminal.\n * `app-server start` uses it, because a person reads those lines.\n *\n * @param write - Where each line goes. Defaults to stdout, at once. Why not\n * one write for each turn: the lines then keep their order with Vite's lines.\n *\n * @example\n * textSink().log(\"info\", \"port in use, trying the next port\", { \"server.port\": 3000 });\n * // time=2026-11-11T12:00:00.000Z level=INFO msg=\"port in use, trying the next port\" server.port=3000\n */\nexport function textSink(\n\twrite: (line: string) => void = (line) => {\n\t\tprocess.stdout.write(line);\n\t},\n): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\tlet line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;\n\t\t\tfor (const [key, value] of Object.entries(attributes)) {\n\t\t\t\tline += ` ${key}=${textValue(value)}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */\nfunction textValue(value: unknown): string {\n\tconst text = typeof value === \"string\" ? value : (JSON.stringify(value) ?? String(value));\n\treturn /^[^\\s\"=\\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\n/** Flat `error.*` attributes for a thrown value. */\nexport function errorAttributes(error: unknown): Record<string, unknown> {\n\tif (error instanceof Error) {\n\t\treturn { \"error.kind\": error.name, \"error.message\": error.message, \"error.stack\": error.stack };\n\t}\n\treturn { \"error.message\": String(error) };\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log(\"debug\", message, withBase(attributes));\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log(\"info\", message, withBase(attributes));\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log(\"warn\", message, withBase(attributes));\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log(\"error\", message, withBase(attributes));\n\t\t},\n\t};\n}\n\n/** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */\nexport function requestLogger(sink: LogSink, context: Context<AppServerEnv>): RequestLogger {\n\t// Why read at call time: the `requestId` plugin runs after this logger is made. Why one object:\n\t// a base object and then a merge copy each attribute two times.\n\treturn sinkLogger(sink, (attributes) => ({\n\t\t\"http.request_id\": context.get(\"requestId\"),\n\t\t\"http.method\": context.req.method,\n\t\t\"http.url_details.path\": context.req.path,\n\t\t...context.get(\"logAttributes\"),\n\t\t...attributes,\n\t}));\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAEjF,KAAK,MAAM,QAAQ,QAAQ,MAAM,YAAY,KAAK,CAAC,GAClD,QAAQ,OAAO,MAAM,IAAI;CAE1B,UAAU;AACX,CAAC;;;;;AAMD,SAAgB,YAAkB;CACjC,IAAI,YAAY,IACf;CAED,MAAM,QAAQ;CACd,UAAU;CACV,QAAQ,OAAO,MAAM,KAAK;AAC3B;;;;;;AAOA,SAAS,YAAY,MAAoB;CACxC,IAAI,SAAS;EACZ,QAAQ,OAAO,MAAM,IAAI;EACzB;CACD;CACA,IAAI,YAAY,IACf,aAAa,SAAS;CAEvB,WAAW;AACZ;;;;;;;;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c,MAAM;EAAM,iBAAiB,MAAM;EAAS,eAAe,MAAM;CAAM;CAE/F,OAAO,EAAE,iBAAiB,OAAO,KAAK,EAAE;AACzC;;;;;AAQA,SAAgB,WACf,MACA,YAAoD,gBAAgB,EAAE,GAAG,WAAW,IACpE;CAEhB,OAAO;EACN,QAAQ,SAAS,aAAa,CAAC,MAAM;GACpC,KAAK,IAAI,SAAS,SAAS,SAAS,UAAU,CAAC;EAChD;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI,QAAQ,SAAS,SAAS,UAAU,CAAC;EAC/C;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI,QAAQ,SAAS,SAAS,UAAU,CAAC;EAC/C;EACA,QAAQ,SAAS,aAAa,CAAC,MAAM;GACpC,KAAK,IAAI,SAAS,SAAS,SAAS,UAAU,CAAC;EAChD;CACD;AACD;;AAGA,SAAgB,cAAc,MAAe,SAA+C;CAG3F,OAAO,WAAW,OAAO,gBAAgB;EACxC,mBAAmB,QAAQ,IAAI,WAAW;EAC1C,eAAe,QAAQ,IAAI;EAC3B,yBAAyB,QAAQ,IAAI;EACrC,GAAG,QAAQ,IAAI,eAAe;EAC9B,GAAG;CACJ,EAAE;AACH"}
@@ -1,6 +1,6 @@
1
- import { n as tcp } from "./tcp-Bws6oEau.js";
2
- import { n as flushLogs } from "./log-BP6xXXZl.js";
3
- import { n as gzipStream, t as brotliStream } from "./compress-JuJf2HaO.js";
1
+ import { n as tcp } from "./tcp-BPeUZaNg.js";
2
+ import { n as flushLogs } from "./log-C8LGQ23s.js";
3
+ import { n as gzipStream, t as brotliStream } from "./compress-Cp5NfXCC.js";
4
4
  import { t as publicScriptHashes } from "./script-hashes-CU7P9oZU.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { setTimeout } from "node:timers";
@@ -331,4 +331,4 @@ const host = {
331
331
  };
332
332
 
333
333
  export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
334
- //# sourceMappingURL=node-B0AYf_IA.js.map
334
+ //# sourceMappingURL=node-CA7t-s6D.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-B0AYf_IA.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { brotliStream, gzipStream } from \"./compress.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tbrotli: brotliStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTER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EACD;AACD"}
1
+ {"version":3,"file":"node-CA7t-s6D.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { brotliStream, gzipStream } from \"./compress.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tbrotli: brotliStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\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{ t as requestListener } from "./response-writer-BUyOW4n2.js";
2
2
  import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
3
3
  import { createServer } from "node:http";
4
4
 
@@ -38,4 +38,4 @@ async function listen(fetch, options) {
38
38
  }
39
39
 
40
40
  export { listen };
41
- //# sourceMappingURL=node-C0Ad7CVL.js.map
41
+ //# sourceMappingURL=node-Fo6EodEV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-C0Ad7CVL.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { requestListener } from \"../response-writer.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** Listens with `node:http`, and writes each response with the node response writer. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });\n\tconst server = createServer(\n\t\t{\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t\t(incoming, outgoing) => {\n\t\t\tvoid listener(incoming, outgoing);\n\t\t},\n\t);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tserver.closeIdleConnections();\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;AAOA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,WAAW,gBAAgB,OAAO,EAAE,qBAAqB,QAAQ,oBAAoB,CAAC;CAC5F,MAAM,SAAS,aACd;EACC,kBAAkB,QAAQ;EAG1B,gBAAgB,QAAQ,gBAAgB;CACzC,IACC,UAAU,aAAa;EACvB,AAAK,SAAS,UAAU,QAAQ;CACjC,CACD;CACA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,OAAO,oBAAoB;GAC5B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,OAAO,qBAAqB;EAC7B,CAAC;CACH;AACD"}
1
+ {"version":3,"file":"node-Fo6EodEV.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { requestListener } from \"../response-writer.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** Listens with `node:http`, and writes each response with the node response writer. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });\n\tconst server = createServer(\n\t\t{\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t\t(incoming, outgoing) => {\n\t\t\tvoid listener(incoming, outgoing);\n\t\t},\n\t);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tserver.closeIdleConnections();\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;AAOA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,WAAW,gBAAgB,OAAO,EAAE,qBAAqB,QAAQ,oBAAoB,CAAC;CAC5F,MAAM,SAAS,aACd;EACC,kBAAkB,QAAQ;EAG1B,gBAAgB,QAAQ,gBAAgB;CACzC,IACC,UAAU,aAAa;EACvB,AAAK,SAAS,UAAU,QAAQ;CACjC,CACD;CACA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,OAAO,oBAAoB;GAC5B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,OAAO,qBAAqB;EAC7B,CAAC;CACH;AACD"}
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as tcp, t as parsePort } from "./tcp-Bws6oEau.js";
2
- import { n as devServerStage, r as nodeFiles, t as host } from "./node-B0AYf_IA.js";
1
+ import { n as tcp, t as parsePort } from "./tcp-BPeUZaNg.js";
2
+ import { n as devServerStage, r as nodeFiles, t as host } from "./node-CA7t-s6D.js";
3
3
 
4
4
  export { devServerStage, host, nodeFiles, parsePort, tcp };
@@ -1,5 +1,5 @@
1
1
  import { n as requestContextValues } from "./request-context-BtQ87VYb.js";
2
- import { a as sinkLogger, r as jsonSink } from "./log-BP6xXXZl.js";
2
+ import { a as sinkLogger, r as jsonSink } from "./log-C8LGQ23s.js";
3
3
  import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
4
4
 
5
5
  // src/react-router/index.ts
@@ -1,5 +1,5 @@
1
1
  import { a as replaceResponse, i as listView, n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
- import { t as errorAttributes } from "./log-BP6xXXZl.js";
2
+ import { t as errorAttributes } from "./log-C8LGQ23s.js";
3
3
 
4
4
  // src/core/response-edge.ts
5
5
  function ignore() {}
@@ -324,4 +324,4 @@ function finishResponse(context, finish) {
324
324
  }
325
325
 
326
326
  export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
327
- //# sourceMappingURL=response-edge-Bc1-C_Cx.js.map
327
+ //# sourceMappingURL=response-edge-D3CAjukJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"response-edge-Bc1-C_Cx.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { errorAttributes } from \"./log.js\";\nimport type { AppServerEnv, HeaderHook, RequestLogger, SentResponse } from \"./types.js\";\n\nfunction ignore(): void {}\n\n/** Calls `report` with `sent`, and drops a throw from it. */\nfunction callReport(report: (sent: SentResponse) => void, sent: SentResponse): void {\n\ttry {\n\t\treport(sent);\n\t} catch {\n\t\t// Why drop it: a listener calls a report from an event of its socket, where a throw stops the process.\n\t}\n}\n\n/** The `Set-Cookie` values of a flat header list, one on each line. */\nfunction cookiesOf(head: readonly string[]): string {\n\tlet cookies = \"\";\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === \"set-cookie\") {\n\t\t\tcookies += `${head[index + 1] ?? \"\"}\\n`;\n\t\t}\n\t}\n\treturn cookies;\n}\n\n/** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */\nfunction valueOf(head: readonly string[], name: string): string | undefined {\n\tconst index = headerIndex(head, name);\n\treturn index === -1 ? undefined : head[index + 1];\n}\n\n/** Whether two flat header lists are the same. */\nfunction sameHead(first: readonly string[], second: readonly string[]): boolean {\n\tif (first.length !== second.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tif (first[index] !== second[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */\nfunction withChanges(\n\thead: readonly string[],\n\tbase: readonly string[],\n\tlive: readonly string[],\n): string[] {\n\tconst changed = [...head];\n\tconst view = listView(changed);\n\tfor (let index = 0; index < base.length; index += 2) {\n\t\tconst name = base[index] ?? \"\";\n\t\tif (headerIndex(live, name) === -1) {\n\t\t\tview.delete(name);\n\t\t}\n\t}\n\tif (cookiesOf(base) !== cookiesOf(live)) {\n\t\tview.delete(\"set-cookie\");\n\t\tfor (let index = 0; index < live.length; index += 2) {\n\t\t\tif (live[index] === \"set-cookie\") {\n\t\t\t\tview.append(\"set-cookie\", live[index + 1] ?? \"\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (let index = 0; index < live.length; index += 2) {\n\t\tconst name = live[index] ?? \"\";\n\t\tconst value = live[index + 1] ?? \"\";\n\t\tif (name !== \"set-cookie\" && valueOf(base, name) !== value) {\n\t\t\tview.set(name, value);\n\t\t}\n\t}\n\treturn changed;\n}\n\n/**\n * What the server and a listener that writes each response itself share for\n * one request. The listener makes one for each request and gives it as the\n * `edge` binding. The server then runs the header hooks on a list of the\n * headers, so it copies no response for them. The listener:\n *\n * - writes {@link ResponseEdge.headersFor} in place of the headers of the response\n * - adds each body byte that it writes to {@link ResponseEdge.bytes}\n * - gives an error that stops the response to {@link ResponseEdge.fail}\n * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away\n *\n * @example\n * const edge = new ResponseEdge();\n * const response = await fetch(request, { remoteAddress, edge });\n * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());\n */\nexport class ResponseEdge {\n\t/** The body bytes that the listener gave to its socket. */\n\tpublic bytes = 0;\n\t#logger: RequestLogger | undefined = undefined;\n\t#base: readonly string[] | undefined = undefined;\n\t#headers: string[] | undefined = undefined;\n\treadonly #reports: ((sent: SentResponse) => void)[] = [];\n\t#sent: SentResponse | undefined = undefined;\n\n\t/**\n\t * Gives the edge to the request of `logger`, and gives `true`, the first\n\t * time only. The server calls it when a request starts. Why once: a\n\t * request that the app sends through itself again with the same bindings\n\t * must change its own response.\n\t */\n\tpublic claim(logger: RequestLogger): boolean {\n\t\tif (this.#logger != null) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.#logger = logger;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Keeps `headers`, the headers of the response after each header hook, and\n\t * `base`, its headers before the hooks. The server calls it.\n\t */\n\tpublic useHeaders(base: readonly string[], headers: string[]): void {\n\t\tthis.#base = base;\n\t\tthis.#headers = headers;\n\t}\n\n\t/**\n\t * The headers to write for `response`: lowercase names and their values in\n\t * turn, as Node's `writeHead` takes them. They are the headers after the\n\t * hooks, with each change that the headers of `response` have from the\n\t * response that the hooks ran on. Why: Hono answers HEAD with a copy that\n\t * has no body, and a wrapper of the app's `fetch` can change the headers or\n\t * return a copy. It gives `undefined` when the server kept no headers.\n\t */\n\tpublic headersFor(response: Response): string[] | undefined {\n\t\tconst base = this.#base;\n\t\tconst headers = this.#headers;\n\t\tif (base == null || headers == null) {\n\t\t\treturn headers;\n\t\t}\n\t\tconst live = headerList(response.headers);\n\t\treturn sameHead(base, live) ? headers : withChanges(headers, base, live);\n\t}\n\n\t/**\n\t * Calls `report` once, when the response ends or its client goes away. It\n\t * calls it at once when that happened already. A throw from `report` never\n\t * reaches the listener.\n\t */\n\tpublic onSent(report: (sent: SentResponse) => void): void {\n\t\tif (this.#sent == null) {\n\t\t\tthis.#reports.push(report);\n\t\t} else {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n\n\t/** Logs `error`, which stopped the response, with the logger of the request. */\n\tpublic fail(error: unknown): void {\n\t\ttry {\n\t\t\tif (this.#logger != null) {\n\t\t\t\tthis.#logger.error(\"unhandled error\", errorAttributes(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Why fall through: the sink failed, and the error must still reach the operator.\n\t\t}\n\t\t// oxlint-disable-next-line no-console -- no app logger took the edge, or its sink failed.\n\t\tconsole.error(error);\n\t}\n\n\t/**\n\t * Reports what went out, once: the status and the headers that the\n\t * listener sent, the bytes, and whether the body stopped before its end.\n\t * `head` is the flat list that the listener gave `writeHead`.\n\t */\n\tpublic close(status: number, aborted: boolean, head: string[]): void {\n\t\tif (this.#sent != null) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#sent = { status, headers: listView(head), bytes: this.bytes, aborted };\n\t\tfor (const report of this.#reports) {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n}\n\n/**\n * `body` again, with a count of its bytes for `report`. `report` runs once:\n * at the end of the body, at a failure, or at a cancel.\n */\nfunction countedBody(\n\tbody: ReadableStream<Uint8Array>,\n\treport: (bytes: number, aborted: boolean) => void,\n): ReadableStream<Uint8Array> {\n\tconst reader = body.getReader();\n\tlet bytes = 0;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treport(bytes, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbytes += result.value.byteLength;\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\ttry {\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t} finally {\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Why 0: a pass-through stream must not read ahead of the client.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * The body of `context.res` with a count for `report`, or `undefined` when\n * `report` ran at once: a HEAD response and a response with no body send no\n * body bytes. `headers` are the headers that go out with the response.\n */\nfunction reportedBody(\n\tcontext: Context<AppServerEnv>,\n\theaders: Headers,\n\treport: (sent: SentResponse) => void,\n): ReadableStream<Uint8Array> | undefined {\n\tconst { status, body } = context.res;\n\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\tif (context.req.method === \"HEAD\") {\n\t\tcallReport(report, { status, headers, bytes: 0, aborted: false });\n\t\treturn undefined;\n\t}\n\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t// development, gives a response with no body and the length it sent.\n\tif (body == null) {\n\t\tconst length = Number(headers.get(\"Content-Length\") ?? 0);\n\t\tcallReport(report, { status, headers, bytes: length, aborted: false });\n\t\treturn undefined;\n\t}\n\treturn countedBody(body, (bytes, aborted) => {\n\t\tcallReport(report, { status, headers, bytes, aborted });\n\t});\n}\n\n/**\n * Calls `report` once, when the response of the request ends or its client\n * goes away: with the status and the headers that went out, the body bytes,\n * and whether the body stopped before its end. In an app server, it reports the response that\n * the server returns, after each stage and header hook. A listener with an\n * `edge` counts the bytes as it writes them; else the server counts them with\n * a stream around the body.\n *\n * @example\n * middleware: async (c, next) => {\n * \tawait next();\n * \tonResponseSent(c, ({ status, bytes }) => c.get(\"logger\").info(\"sent\", { status, bytes }));\n * },\n */\nexport function onResponseSent(\n\tcontext: Context<AppServerEnv>,\n\treport: (sent: SentResponse) => void,\n): void {\n\tconst reports = context.get(\"sentReports\");\n\tif (reports != null) {\n\t\treports.push(report);\n\t\treturn;\n\t}\n\t// Why now: outside an app server, nothing reports later, so this counts the response as it is.\n\tconst response = context.res;\n\tconst body = reportedBody(context, response.headers, report);\n\tif (body != null) {\n\t\treplaceResponse(context, new Response(body, response));\n\t}\n}\n\n/** What {@link finishResponse} needs from the server. */\ntype Finish = {\n\thooks: readonly HeaderHook[];\n\treports: readonly ((sent: SentResponse) => void)[];\n\t/** The edge that the request claimed, if any. */\n\tedge: ResponseEdge | undefined;\n\t/**\n\t * The response for an error that a header hook throws, as the app's\n\t * `onError` gives it. It runs while `context.res` is cleared.\n\t */\n\tfail: (error: unknown, context: Context<AppServerEnv>) => Response | Promise<Response>;\n};\n\n/**\n * Puts the response that `fail` gives for `error` in place of the response of\n * the request, and cancels the body that no one reads now.\n */\nasync function useErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfail: Finish[\"fail\"],\n\terror: unknown,\n): Promise<void> {\n\tconst { body } = context.res;\n\t// Why clear first: Hono's `c.text` copies each header of the response that the context holds.\n\tcontext.res = undefined;\n\tcontext.res = await fail(error, context);\n\tvoid body?.cancel().catch(ignore);\n}\n\n/**\n * Gives `reports` the response of the request. With no edge, it makes one new\n * response with `headers`, when the hooks made them, and a body that counts\n * its bytes.\n */\nfunction reportResponse(\n\tcontext: Context<AppServerEnv>,\n\treports: Finish[\"reports\"],\n\theaders: Headers | undefined,\n): void {\n\tconst response = context.res;\n\tconst [only] = reports;\n\tconst report =\n\t\treports.length > 1\n\t\t\t? (sent: SentResponse) => {\n\t\t\t\t\tfor (const each of reports) {\n\t\t\t\t\t\tcallReport(each, sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: only;\n\t// Why keep `headers`: Bun empties the headers of the response that it sends, but not this object.\n\tconst body =\n\t\treport == null ? undefined : reportedBody(context, headers ?? response.headers, report);\n\tif (headers == null && body == null) {\n\t\treturn;\n\t}\n\tcontext.res = undefined;\n\tcontext.res = new Response(body ?? response.body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: headers ?? response.headers,\n\t});\n}\n\n/** Puts the error response for `error` in place, then runs the hooks from `from` on it. */\nasync function finishAfterError(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\t{ error, from }: { error: unknown; from: number },\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\tawait finishFrom(context, finish, from);\n}\n\n/** Puts the error response for `error` in place, and gives it to the reports. */\nasync function reportErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\terror: unknown,\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\treportResponse(context, finish.reports, undefined);\n}\n\n/** {@link finishResponse} from the hook at `from`, down to the first one. */\nfunction finishFrom(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\tfrom: number,\n): Promise<void> | undefined {\n\tconst { hooks, reports, edge } = finish;\n\tconst base = headerList(context.res.headers);\n\t// Why a copy with an edge: the edge compares the response that the listener gets with `base`.\n\tconst head = edge == null ? base : [...base];\n\tconst view = listView(head);\n\tfor (let index = from; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch (error) {\n\t\t\treturn finishAfterError(context, finish, { error, from: index - 1 });\n\t\t}\n\t}\n\tif (edge != null) {\n\t\tedge.useHeaders(base, head);\n\t\tfor (const report of reports) {\n\t\t\tedge.onSent(report);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hooks.length === 0) {\n\t\treportResponse(context, reports, undefined);\n\t\treturn undefined;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\theaders.append(head[index] ?? \"\", head[index + 1] ?? \"\");\n\t\t}\n\t} catch (error) {\n\t\t// Why: a hook set a value that `Headers` rejects. The error response keeps its own headers.\n\t\treturn reportErrorResponse(context, finish, error);\n\t}\n\treportResponse(context, reports, headers);\n\treturn undefined;\n}\n\n/**\n * Finishes the response of the request, after each stage. The server calls it\n * once, in the request's `requestContext()`.\n *\n * - It runs `hooks` on the head, in reverse order, so the hook of an inner\n * stage runs first and an outer stage has the last word. When a hook\n * throws, `fail` gives the response that takes the place of this one, and\n * the hooks of the outer stages run on it, as when a stage throws.\n * - It gives `reports` the response, so each one runs when it ends.\n *\n * With `edge`, the head stays a list that the listener writes, so the server\n * copies no response. Else the server makes one new response with the head\n * and a body that counts its bytes. It gives a promise only when a hook\n * throws, so a response with no error waits for no microtask.\n *\n * @example\n * await next();\n * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });\n */\nexport function finishResponse(\n\tcontext: Context<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,GAAG,SAAS,GAC3C,IAAI;EACH,MAAM,MAAM,GAAG,IAAI;CACpB,SAAS,OAAO;EACf,OAAO,iBAAiB,SAAS,QAAQ;GAAE;GAAO,MAAM,QAAQ;EAAE,CAAC;CACpE;CAED,IAAI,QAAQ,MAAM;EACjB,KAAK,WAAW,MAAM,IAAI;EAC1B,KAAK,MAAM,UAAU,SACpB,KAAK,OAAO,MAAM;EAEnB;CACD;CACA,IAAI,MAAM,WAAW,GAAG;EACvB,eAAe,SAAS,SAAS,MAAS;EAC1C;CACD;CACA,MAAM,UAAU,IAAI,QAAQ;CAC5B,IAAI;EACH,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GACjD,QAAQ,OAAO,KAAK,UAAU,IAAI,KAAK,QAAQ,MAAM,EAAE;CAEzD,SAAS,OAAO;EAEf,OAAO,oBAAoB,SAAS,QAAQ,KAAK;CAClD;CACA,eAAe,SAAS,SAAS,OAAO;AAEzC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,eACf,SACA,QAC4B;CAC5B,OAAO,WAAW,SAAS,QAAQ,OAAO,MAAM,SAAS,CAAC;AAC3D"}
1
+ {"version":3,"file":"response-edge-D3CAjukJ.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { errorAttributes } from \"./log.js\";\nimport type { AppServerEnv, HeaderHook, RequestLogger, SentResponse } from \"./types.js\";\n\nfunction ignore(): void {}\n\n/** Calls `report` with `sent`, and drops a throw from it. */\nfunction callReport(report: (sent: SentResponse) => void, sent: SentResponse): void {\n\ttry {\n\t\treport(sent);\n\t} catch {\n\t\t// Why drop it: a listener calls a report from an event of its socket, where a throw stops the process.\n\t}\n}\n\n/** The `Set-Cookie` values of a flat header list, one on each line. */\nfunction cookiesOf(head: readonly string[]): string {\n\tlet cookies = \"\";\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === \"set-cookie\") {\n\t\t\tcookies += `${head[index + 1] ?? \"\"}\\n`;\n\t\t}\n\t}\n\treturn cookies;\n}\n\n/** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */\nfunction valueOf(head: readonly string[], name: string): string | undefined {\n\tconst index = headerIndex(head, name);\n\treturn index === -1 ? undefined : head[index + 1];\n}\n\n/** Whether two flat header lists are the same. */\nfunction sameHead(first: readonly string[], second: readonly string[]): boolean {\n\tif (first.length !== second.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tif (first[index] !== second[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */\nfunction withChanges(\n\thead: readonly string[],\n\tbase: readonly string[],\n\tlive: readonly string[],\n): string[] {\n\tconst changed = [...head];\n\tconst view = listView(changed);\n\tfor (let index = 0; index < base.length; index += 2) {\n\t\tconst name = base[index] ?? \"\";\n\t\tif (headerIndex(live, name) === -1) {\n\t\t\tview.delete(name);\n\t\t}\n\t}\n\tif (cookiesOf(base) !== cookiesOf(live)) {\n\t\tview.delete(\"set-cookie\");\n\t\tfor (let index = 0; index < live.length; index += 2) {\n\t\t\tif (live[index] === \"set-cookie\") {\n\t\t\t\tview.append(\"set-cookie\", live[index + 1] ?? \"\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (let index = 0; index < live.length; index += 2) {\n\t\tconst name = live[index] ?? \"\";\n\t\tconst value = live[index + 1] ?? \"\";\n\t\tif (name !== \"set-cookie\" && valueOf(base, name) !== value) {\n\t\t\tview.set(name, value);\n\t\t}\n\t}\n\treturn changed;\n}\n\n/**\n * What the server and a listener that writes each response itself share for\n * one request. The listener makes one for each request and gives it as the\n * `edge` binding. The server then runs the header hooks on a list of the\n * headers, so it copies no response for them. The listener:\n *\n * - writes {@link ResponseEdge.headersFor} in place of the headers of the response\n * - adds each body byte that it writes to {@link ResponseEdge.bytes}\n * - gives an error that stops the response to {@link ResponseEdge.fail}\n * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away\n *\n * @example\n * const edge = new ResponseEdge();\n * const response = await fetch(request, { remoteAddress, edge });\n * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());\n */\nexport class ResponseEdge {\n\t/** The body bytes that the listener gave to its socket. */\n\tpublic bytes = 0;\n\t#logger: RequestLogger | undefined = undefined;\n\t#base: readonly string[] | undefined = undefined;\n\t#headers: string[] | undefined = undefined;\n\treadonly #reports: ((sent: SentResponse) => void)[] = [];\n\t#sent: SentResponse | undefined = undefined;\n\n\t/**\n\t * Gives the edge to the request of `logger`, and gives `true`, the first\n\t * time only. The server calls it when a request starts. Why once: a\n\t * request that the app sends through itself again with the same bindings\n\t * must change its own response.\n\t */\n\tpublic claim(logger: RequestLogger): boolean {\n\t\tif (this.#logger != null) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.#logger = logger;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Keeps `headers`, the headers of the response after each header hook, and\n\t * `base`, its headers before the hooks. The server calls it.\n\t */\n\tpublic useHeaders(base: readonly string[], headers: string[]): void {\n\t\tthis.#base = base;\n\t\tthis.#headers = headers;\n\t}\n\n\t/**\n\t * The headers to write for `response`: lowercase names and their values in\n\t * turn, as Node's `writeHead` takes them. They are the headers after the\n\t * hooks, with each change that the headers of `response` have from the\n\t * response that the hooks ran on. Why: Hono answers HEAD with a copy that\n\t * has no body, and a wrapper of the app's `fetch` can change the headers or\n\t * return a copy. It gives `undefined` when the server kept no headers.\n\t */\n\tpublic headersFor(response: Response): string[] | undefined {\n\t\tconst base = this.#base;\n\t\tconst headers = this.#headers;\n\t\tif (base == null || headers == null) {\n\t\t\treturn headers;\n\t\t}\n\t\tconst live = headerList(response.headers);\n\t\treturn sameHead(base, live) ? headers : withChanges(headers, base, live);\n\t}\n\n\t/**\n\t * Calls `report` once, when the response ends or its client goes away. It\n\t * calls it at once when that happened already. A throw from `report` never\n\t * reaches the listener.\n\t */\n\tpublic onSent(report: (sent: SentResponse) => void): void {\n\t\tif (this.#sent == null) {\n\t\t\tthis.#reports.push(report);\n\t\t} else {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n\n\t/** Logs `error`, which stopped the response, with the logger of the request. */\n\tpublic fail(error: unknown): void {\n\t\ttry {\n\t\t\tif (this.#logger != null) {\n\t\t\t\tthis.#logger.error(\"unhandled error\", errorAttributes(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Why fall through: the sink failed, and the error must still reach the operator.\n\t\t}\n\t\t// oxlint-disable-next-line no-console -- no app logger took the edge, or its sink failed.\n\t\tconsole.error(error);\n\t}\n\n\t/**\n\t * Reports what went out, once: the status and the headers that the\n\t * listener sent, the bytes, and whether the body stopped before its end.\n\t * `head` is the flat list that the listener gave `writeHead`.\n\t */\n\tpublic close(status: number, aborted: boolean, head: string[]): void {\n\t\tif (this.#sent != null) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#sent = { status, headers: listView(head), bytes: this.bytes, aborted };\n\t\tfor (const report of this.#reports) {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n}\n\n/**\n * `body` again, with a count of its bytes for `report`. `report` runs once:\n * at the end of the body, at a failure, or at a cancel.\n */\nfunction countedBody(\n\tbody: ReadableStream<Uint8Array>,\n\treport: (bytes: number, aborted: boolean) => void,\n): ReadableStream<Uint8Array> {\n\tconst reader = body.getReader();\n\tlet bytes = 0;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treport(bytes, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbytes += result.value.byteLength;\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\ttry {\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t} finally {\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Why 0: a pass-through stream must not read ahead of the client.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * The body of `context.res` with a count for `report`, or `undefined` when\n * `report` ran at once: a HEAD response and a response with no body send no\n * body bytes. `headers` are the headers that go out with the response.\n */\nfunction reportedBody(\n\tcontext: Context<AppServerEnv>,\n\theaders: Headers,\n\treport: (sent: SentResponse) => void,\n): ReadableStream<Uint8Array> | undefined {\n\tconst { status, body } = context.res;\n\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\tif (context.req.method === \"HEAD\") {\n\t\tcallReport(report, { status, headers, bytes: 0, aborted: false });\n\t\treturn undefined;\n\t}\n\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t// development, gives a response with no body and the length it sent.\n\tif (body == null) {\n\t\tconst length = Number(headers.get(\"Content-Length\") ?? 0);\n\t\tcallReport(report, { status, headers, bytes: length, aborted: false });\n\t\treturn undefined;\n\t}\n\treturn countedBody(body, (bytes, aborted) => {\n\t\tcallReport(report, { status, headers, bytes, aborted });\n\t});\n}\n\n/**\n * Calls `report` once, when the response of the request ends or its client\n * goes away: with the status and the headers that went out, the body bytes,\n * and whether the body stopped before its end. In an app server, it reports the response that\n * the server returns, after each stage and header hook. A listener with an\n * `edge` counts the bytes as it writes them; else the server counts them with\n * a stream around the body.\n *\n * @example\n * middleware: async (c, next) => {\n * \tawait next();\n * \tonResponseSent(c, ({ status, bytes }) => c.get(\"logger\").info(\"sent\", { status, bytes }));\n * },\n */\nexport function onResponseSent(\n\tcontext: Context<AppServerEnv>,\n\treport: (sent: SentResponse) => void,\n): void {\n\tconst reports = context.get(\"sentReports\");\n\tif (reports != null) {\n\t\treports.push(report);\n\t\treturn;\n\t}\n\t// Why now: outside an app server, nothing reports later, so this counts the response as it is.\n\tconst response = context.res;\n\tconst body = reportedBody(context, response.headers, report);\n\tif (body != null) {\n\t\treplaceResponse(context, new Response(body, response));\n\t}\n}\n\n/** What {@link finishResponse} needs from the server. */\ntype Finish = {\n\thooks: readonly HeaderHook[];\n\treports: readonly ((sent: SentResponse) => void)[];\n\t/** The edge that the request claimed, if any. */\n\tedge: ResponseEdge | undefined;\n\t/**\n\t * The response for an error that a header hook throws, as the app's\n\t * `onError` gives it. It runs while `context.res` is cleared.\n\t */\n\tfail: (error: unknown, context: Context<AppServerEnv>) => Response | Promise<Response>;\n};\n\n/**\n * Puts the response that `fail` gives for `error` in place of the response of\n * the request, and cancels the body that no one reads now.\n */\nasync function useErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfail: Finish[\"fail\"],\n\terror: unknown,\n): Promise<void> {\n\tconst { body } = context.res;\n\t// Why clear first: Hono's `c.text` copies each header of the response that the context holds.\n\tcontext.res = undefined;\n\tcontext.res = await fail(error, context);\n\tvoid body?.cancel().catch(ignore);\n}\n\n/**\n * Gives `reports` the response of the request. With no edge, it makes one new\n * response with `headers`, when the hooks made them, and a body that counts\n * its bytes.\n */\nfunction reportResponse(\n\tcontext: Context<AppServerEnv>,\n\treports: Finish[\"reports\"],\n\theaders: Headers | undefined,\n): void {\n\tconst response = context.res;\n\tconst [only] = reports;\n\tconst report =\n\t\treports.length > 1\n\t\t\t? (sent: SentResponse) => {\n\t\t\t\t\tfor (const each of reports) {\n\t\t\t\t\t\tcallReport(each, sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: only;\n\t// Why keep `headers`: Bun empties the headers of the response that it sends, but not this object.\n\tconst body =\n\t\treport == null ? undefined : reportedBody(context, headers ?? response.headers, report);\n\tif (headers == null && body == null) {\n\t\treturn;\n\t}\n\tcontext.res = undefined;\n\tcontext.res = new Response(body ?? response.body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: headers ?? response.headers,\n\t});\n}\n\n/** Puts the error response for `error` in place, then runs the hooks from `from` on it. */\nasync function finishAfterError(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\t{ error, from }: { error: unknown; from: number },\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\tawait finishFrom(context, finish, from);\n}\n\n/** Puts the error response for `error` in place, and gives it to the reports. */\nasync function reportErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\terror: unknown,\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\treportResponse(context, finish.reports, undefined);\n}\n\n/** {@link finishResponse} from the hook at `from`, down to the first one. */\nfunction finishFrom(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\tfrom: number,\n): Promise<void> | undefined {\n\tconst { hooks, reports, edge } = finish;\n\tconst base = headerList(context.res.headers);\n\t// Why a copy with an edge: the edge compares the response that the listener gets with `base`.\n\tconst head = edge == null ? base : [...base];\n\tconst view = listView(head);\n\tfor (let index = from; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch (error) {\n\t\t\treturn finishAfterError(context, finish, { error, from: index - 1 });\n\t\t}\n\t}\n\tif (edge != null) {\n\t\tedge.useHeaders(base, head);\n\t\tfor (const report of reports) {\n\t\t\tedge.onSent(report);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hooks.length === 0) {\n\t\treportResponse(context, reports, undefined);\n\t\treturn undefined;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\theaders.append(head[index] ?? \"\", head[index + 1] ?? \"\");\n\t\t}\n\t} catch (error) {\n\t\t// Why: a hook set a value that `Headers` rejects. The error response keeps its own headers.\n\t\treturn reportErrorResponse(context, finish, error);\n\t}\n\treportResponse(context, reports, headers);\n\treturn undefined;\n}\n\n/**\n * Finishes the response of the request, after each stage. The server calls it\n * once, in the request's `requestContext()`.\n *\n * - It runs `hooks` on the head, in reverse order, so the hook of an inner\n * stage runs first and an outer stage has the last word. When a hook\n * throws, `fail` gives the response that takes the place of this one, and\n * the hooks of the outer stages run on it, as when a stage throws.\n * - It gives `reports` the response, so each one runs when it ends.\n *\n * With `edge`, the head stays a list that the listener writes, so the server\n * copies no response. Else the server makes one new response with the head\n * and a body that counts its bytes. It gives a promise only when a hook\n * throws, so a response with no error waits for no microtask.\n *\n * @example\n * await next();\n * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });\n */\nexport function finishResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n): Promise<void> | undefined {\n\treturn finishFrom(context, finish, finish.hooks.length - 1);\n}\n"],"mappings":";;;;AAKA,SAAS,SAAe,CAAC;;AAGzB,SAAS,WAAW,QAAsC,MAA0B;CACnF,IAAI;EACH,OAAO,IAAI;CACZ,QAAQ,CAER;AACD;;AAGA,SAAS,UAAU,MAAiC;CACnD,IAAI,UAAU;CACd,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GACjD,IAAI,KAAK,WAAW,cACnB,WAAW,GAAG,KAAK,QAAQ,MAAM,GAAG;CAGtC,OAAO;AACR;;AAGA,SAAS,QAAQ,MAAyB,MAAkC;CAC3E,MAAM,QAAQ,YAAY,MAAM,IAAI;CACpC,OAAO,UAAU,KAAK,SAAY,KAAK,QAAQ;AAChD;;AAGA,SAAS,SAAS,OAA0B,QAAoC;CAC/E,IAAI,MAAM,WAAW,OAAO,QAC3B,OAAO;CAER,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAClD,IAAI,MAAM,WAAW,OAAO,QAC3B,OAAO;CAGT,OAAO;AACR;;AAGA,SAAS,YACR,MACA,MACA,MACW;CACX,MAAM,UAAU,CAAC,GAAG,IAAI;CACxB,MA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";
2
- import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
2
+ import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
3
3
  import { s as readIfQueued } from "./compression-CT2mWlKM.js";
4
- import { r as waitsForZlib } from "./compress-JuJf2HaO.js";
4
+ import { r as waitsForZlib } from "./compress-Cp5NfXCC.js";
5
5
  import { IncomingMessage, ServerResponse } from "node:http";
6
6
  import { getRequestListener } from "@hono/node-server";
7
7
 
@@ -286,4 +286,4 @@ function listenerOf(answer) {
286
286
  }
287
287
 
288
288
  export { requestListener as t };
289
- //# sourceMappingURL=response-writer-DzvUAz9x.js.map
289
+ //# sourceMappingURL=response-writer-BUyOW4n2.js.map