@ngrok/app-server 0.3.5 → 0.4.0

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 (56) hide show
  1. package/README.md +41 -10
  2. package/dist/cli.js +3 -3
  3. package/dist/client.js +1 -1
  4. package/dist/{compress-CO0Nwc8x.js → compress-Cp5NfXCC.js} +138 -29
  5. package/dist/compress-Cp5NfXCC.js.map +1 -0
  6. package/dist/{create-server-C_90R50y.js → create-server-C63luLkn.js} +71 -30
  7. package/dist/create-server-C63luLkn.js.map +1 -0
  8. package/dist/{create-server-kxyhCdhv.d.ts → create-server-DKJ0wASH.d.ts} +33 -13
  9. package/dist/{entry-65IESBSA.js → entry-BSbsQ_kq.js} +13 -5
  10. package/dist/entry-BSbsQ_kq.js.map +1 -0
  11. package/dist/{entry-CNL4OsEn.d.ts → entry-C9bBcYeP.d.ts} +3 -3
  12. package/dist/index.d.ts +18 -5
  13. package/dist/index.js +6 -6
  14. package/dist/{load-entry-svVuPIFq.js → load-entry-DgZyPtoD.js} +4 -4
  15. package/dist/{load-entry-svVuPIFq.js.map → load-entry-DgZyPtoD.js.map} +1 -1
  16. package/dist/log-CW_g1pWk.js +304 -0
  17. package/dist/log-CW_g1pWk.js.map +1 -0
  18. package/dist/{node-Bgzhwix0.js → node-DBwgrye_.js} +2 -2
  19. package/dist/{node-Bgzhwix0.js.map → node-DBwgrye_.js.map} +1 -1
  20. package/dist/{node-DFI5TjTk.js → node-DiMwdTOC.js} +4 -4
  21. package/dist/{node-DFI5TjTk.js.map → node-DiMwdTOC.js.map} +1 -1
  22. package/dist/node.d.ts +1 -1
  23. package/dist/node.js +2 -2
  24. package/dist/react-router.d.ts +2 -2
  25. package/dist/react-router.js +3 -4
  26. package/dist/react-router.js.map +1 -1
  27. package/dist/request-context-BdAH1D-2.js +80 -0
  28. package/dist/request-context-BdAH1D-2.js.map +1 -0
  29. package/dist/{response-edge-D3CAjukJ.js → response-edge-7eUl2ewl.js} +3 -3
  30. package/dist/response-edge-7eUl2ewl.js.map +1 -0
  31. package/dist/{response-writer-5SOKsW3C.js → response-writer-CLtCseu5.js} +3 -3
  32. package/dist/{response-writer-5SOKsW3C.js.map → response-writer-CLtCseu5.js.map} +1 -1
  33. package/dist/{serve-DKoZxZj4.js → serve-DCaIBTM-.js} +2 -2
  34. package/dist/{serve-DKoZxZj4.js.map → serve-DCaIBTM-.js.map} +1 -1
  35. package/dist/{start-3_WlRLdK.js → start-D2IVWkow.js} +29 -13
  36. package/dist/start-D2IVWkow.js.map +1 -0
  37. package/dist/tanstack-start.d.ts +2 -2
  38. package/dist/tanstack-start.js +1 -1
  39. package/dist/{tcp-CKMCT9RP.js → tcp-B8aFGQRB.js} +2 -2
  40. package/dist/{tcp-CKMCT9RP.js.map → tcp-B8aFGQRB.js.map} +1 -1
  41. package/dist/testing.d.ts +2 -2
  42. package/dist/testing.js +4 -4
  43. package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D_52DJaQ.d.ts} +2 -2
  44. package/dist/{types-BKJxtIuj.d.ts → types-C_I3i62n.d.ts} +32 -4
  45. package/dist/vercel.d.ts +2 -2
  46. package/dist/vercel.js +4 -4
  47. package/package.json +1 -1
  48. package/dist/compress-CO0Nwc8x.js.map +0 -1
  49. package/dist/create-server-C_90R50y.js.map +0 -1
  50. package/dist/entry-65IESBSA.js.map +0 -1
  51. package/dist/log-C8LGQ23s.js +0 -149
  52. package/dist/log-C8LGQ23s.js.map +0 -1
  53. package/dist/request-context-BtQ87VYb.js +0 -40
  54. package/dist/request-context-BtQ87VYb.js.map +0 -1
  55. package/dist/response-edge-D3CAjukJ.js.map +0 -1
  56. package/dist/start-3_WlRLdK.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-CW_g1pWk.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogOptions, 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/** The end of a {@link jsonSink} line whose attributes have no JSON. */\nconst NO_JSON = '\"log.error\":\"attributes not written as JSON\"}';\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\tconst time = isoNow();\n\t\t\tconst head = `{\"time\":\"${time}\",\"level\":\"${level}\",\"message\":${JSON.stringify(message)}`;\n\t\t\t// Why the key check: a caller's `time`, `level`, or `message` replaces the sink's, as in a spread.\n\t\t\tconst ownKeys = \"time\" in attributes || \"level\" in attributes || \"message\" in attributes;\n\t\t\t// Why a splice, not one object: a copy of each attribute costs more than the rest of the line.\n\t\t\tconst json = toJson(ownKeys ? { time, level, message, ...attributes } : attributes);\n\t\t\tlet line = `${head},${NO_JSON}`;\n\t\t\tif (json != null) {\n\t\t\t\tline = ownKeys ? json : `${head}${json === \"{}\" ? \"}\" : `,${json.slice(1)}`}`;\n\t\t\t}\n\t\t\twrite(`${line}\\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({ level: \"info\", message: \"port in use, trying the next port\", attributes: { \"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\tif (typeof value === \"bigint\") {\n\t\treturn `${value}n`;\n\t}\n\tconst text = typeof value === \"string\" ? value : (toJson(value) ?? String(value));\n\treturn /^[^\\s\"=\\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);\n}\n\n/**\n * `value` as JSON, with each bigint as a string such as `\"1n\"`, and each\n * cycle as `\"[Circular]\"`. Gives `undefined` for a value with no JSON, such\n * as a function, or one whose `toJSON` throws. Why try the plain call first:\n * the replacer runs for each value, and a log line seldom needs it.\n */\nfunction toJson(value: unknown): string | undefined {\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\ttry {\n\t\t\treturn JSON.stringify(value, safeReplacer());\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\n/** A `JSON.stringify` replacer for {@link toJson}. */\nfunction safeReplacer(): (this: unknown, key: string, value: unknown) => unknown {\n\t// Why the ancestors, not each object seen: an object that two fields share is not a cycle.\n\tconst ancestors: unknown[] = [];\n\treturn function replace(this: unknown, _key: string, value: unknown): unknown {\n\t\tif (typeof value === \"bigint\") {\n\t\t\treturn `${value}n`;\n\t\t}\n\t\tif (typeof value !== \"object\" || value == null) {\n\t\t\treturn value;\n\t\t}\n\t\t// Why `this`: it is the object that holds `value`, so each ancestor after it is done.\n\t\twhile (ancestors.length > 0 && ancestors.at(-1) !== this) {\n\t\t\tancestors.pop();\n\t\t}\n\t\tif (ancestors.includes(value)) {\n\t\t\treturn \"[Circular]\";\n\t\t}\n\t\tancestors.push(value);\n\t\treturn value;\n\t};\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\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A thrown value as an `Error`, so a log line gives it the `error.*` fields.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nexport function asError(error: unknown): Error {\n\treturn error instanceof Error\n\t\t? error\n\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n}\n\n/** The fields of an error that {@link errorFields} writes on its own, not as an own field. */\nconst ERROR_KEYS = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * The dotted fields of `error` under `prefix`: `kind`, `message`, `stack`,\n * each own field, such as `code`, the `cause` chain, and the `errors` of an\n * `AggregateError`. An error with `toJSON` gives its own fields from it. An\n * error that is its own ancestor in the chain gives `\"[Circular]\"`.\n *\n * @example\n * errorFields(new Error(\"no row\", { cause: new RangeError(\"bad id\") }), \"error\");\n * // => { \"error.kind\": \"Error\", \"error.message\": \"no row\", \"error.stack\": \"…\",\n * // \"error.cause.kind\": \"RangeError\", \"error.cause.message\": \"bad id\", \"error.cause.stack\": \"…\" }\n */\nfunction errorFields(error: Error, prefix: string): Record<string, unknown> {\n\t// Why the ancestors, not each error seen: an error that two fields share is not a cycle.\n\tconst ancestors: Error[] = [];\n\tconst addError = (fields: Record<string, unknown>, base: string, current: Error): void => {\n\t\tconst at = (key: string) => (base === \"\" ? key : `${base}.${key}`);\n\t\tconst add = (key: string, value: unknown) => {\n\t\t\tif (!(value instanceof Error)) {\n\t\t\t\tfields[key] = value;\n\t\t\t} else if (ancestors.includes(value)) {\n\t\t\t\tfields[key] = \"[Circular]\";\n\t\t\t} else {\n\t\t\t\taddError(fields, key, value);\n\t\t\t}\n\t\t};\n\t\tancestors.push(current);\n\t\tfields[at(\"kind\")] = current.name;\n\t\tfields[at(\"message\")] = current.message;\n\t\tfields[at(\"stack\")] = current.stack;\n\t\tconst toJSON: unknown = \"toJSON\" in current ? current.toJSON : undefined;\n\t\tconst own: unknown =\n\t\t\ttypeof toJSON === \"function\" ? Reflect.apply(toJSON, current, []) : current;\n\t\tif (typeof own === \"object\" && own != null) {\n\t\t\tfor (const [key, value] of Object.entries(own)) {\n\t\t\t\tif (!ERROR_KEYS.has(key)) {\n\t\t\t\t\tadd(at(key), value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (current.cause != null) {\n\t\t\tadd(at(\"cause\"), current.cause);\n\t\t}\n\t\tif (current instanceof AggregateError) {\n\t\t\tfields[at(\"errors\")] = current.errors.map((member: unknown) => {\n\t\t\t\tif (!(member instanceof Error)) {\n\t\t\t\t\treturn member;\n\t\t\t\t}\n\t\t\t\tif (ancestors.includes(member)) {\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tconst memberFields: Record<string, unknown> = {};\n\t\t\t\taddError(memberFields, \"\", member);\n\t\t\t\treturn memberFields;\n\t\t\t});\n\t\t}\n\t\tancestors.pop();\n\t};\n\tconst fields: Record<string, unknown> = {};\n\taddError(fields, prefix, error);\n\treturn fields;\n}\n\n/** `attributes` with each `Error` value replaced by its fields, after the `change` hook. */\nfunction flattenErrors(attributes: Attributes, change: LogOptions[\"error\"]): Attributes {\n\t// Why look first: a line seldom holds an error, and then it needs no copy. Why `for...in`: it\n\t// makes no array, and costs about half of `Object.values(...).some(...)` for each line.\n\tlet hasError = false;\n\tfor (const key in attributes) {\n\t\tif (attributes[key] instanceof Error) {\n\t\t\thasError = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!hasError) {\n\t\treturn attributes;\n\t}\n\tconst flat: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (value instanceof Error) {\n\t\t\tconst fields = errorFields(value, key);\n\t\t\tObject.assign(flat, change == null ? fields : change({ error: value, prefix: key, fields }));\n\t\t} else {\n\t\t\tflat[key] = value;\n\t\t}\n\t}\n\treturn flat;\n}\n\n/**\n * A sink that writes each line to `sink`, after it replaces each `Error`\n * value with its fields, and then runs the `attributes` hook.\n *\n * @example\n * hookSink(jsonSink()).log({ level: \"error\", message: \"failed\", attributes: { error: new Error(\"boom\") } });\n * // {\"time\":\"…\",\"level\":\"error\",\"message\":\"failed\",\"error.kind\":\"Error\",\"error.message\":\"boom\",\"error.stack\":\"…\"}\n */\nexport function hookSink(\n\tsink: LogSink,\n\t{ attributes: changeAttributes, error: changeError }: LogOptions = {},\n): LogSink {\n\treturn {\n\t\tlog: (line) => {\n\t\t\tconst flat = flattenErrors(line.attributes, changeError);\n\t\t\t// Why keep `line` when nothing changes: a line seldom holds an error, and then it needs no copy.\n\t\t\tconst flatLine = flat === line.attributes ? line : { ...line, attributes: flat };\n\t\t\tsink.log(\n\t\t\t\tchangeAttributes == null\n\t\t\t\t\t? flatLine\n\t\t\t\t\t: { ...flatLine, attributes: changeAttributes(flatLine) },\n\t\t\t);\n\t\t},\n\t};\n}\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({ level: \"debug\", message, attributes: withBase(attributes) });\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"info\", message, attributes: withBase(attributes) });\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"warn\", message, attributes: withBase(attributes) });\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"error\", message, attributes: withBase(attributes) });\n\t\t},\n\t};\n}\n\n/**\n * A logger whose lines carry the request's ID, method, path, and\n * `logAttributes`. These fields win over a caller's field of the same name.\n */\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.\n\treturn sinkLogger(sink, (attributes) => {\n\t\tconst requestId = context.get(\"requestId\");\n\t\tconst { method, path } = context.req;\n\t\tconst logAttributes = context.get(\"logAttributes\");\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.request_id\": requestId,\n\t\t\t\"http.method\": method,\n\t\t\t\"http.url_details.path\": path,\n\t\t\t...logAttributes,\n\t\t\t...attributes,\n\t\t};\n\t\t// Why write them again, not merge a base object: a caller's field must not replace a request\n\t\t// field, and a merge copies each attribute two times. A key keeps its first place.\n\t\t// oxlint-disable-next-line unicorn/no-immediate-mutation -- the spread above must not win.\n\t\tline[\"http.request_id\"] = requestId;\n\t\tline[\"http.method\"] = method;\n\t\tline[\"http.url_details.path\"] = path;\n\t\tObject.assign(line, logAttributes);\n\t\treturn line;\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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C,MAAM,gBAAgB,QAAQ,IAAI,eAAe;EACjD,MAAM,OAAgC;GACrC,mBAAmB;GACnB,eAAe;GACf,yBAAyB;GACzB,GAAG;GACH,GAAG;EACJ;EAIA,KAAK,qBAAqB;EAC1B,KAAK,iBAAiB;EACtB,KAAK,2BAA2B;EAChC,OAAO,OAAO,MAAM,aAAa;EACjC,OAAO;CACR,CAAC;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as requestListener } from "./response-writer-5SOKsW3C.js";
1
+ import { t as requestListener } from "./response-writer-CLtCseu5.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-Bgzhwix0.js.map
41
+ //# sourceMappingURL=node-DBwgrye_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-Bgzhwix0.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-DBwgrye_.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,6 +1,6 @@
1
- import { n as tcp } from "./tcp-CKMCT9RP.js";
2
- import { n as flushLogs } from "./log-C8LGQ23s.js";
3
- import { n as gzipStream, t as brotliStream } from "./compress-CO0Nwc8x.js";
1
+ import { n as tcp } from "./tcp-B8aFGQRB.js";
2
+ import { n as flushLogs } from "./log-CW_g1pWk.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-DFI5TjTk.js.map
334
+ //# sourceMappingURL=node-DiMwdTOC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-DFI5TjTk.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\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI,UAAU;CACd,MAAM,aAAa;EAClB,WAAW;EACX,IAAI,YAAY,GACf,QAAQ,KAAK;CAEf;CACA,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,QAAQ,QAAQ,IAAI;CAE1B,iBAAiB;EAChB,QAAQ,KAAK;CACd,GAAG,gBAAgB,CAAC,CAAC,MAAM;AAC5B;;AAGA,SAAS,MAAM,QAA4B,MAAwB;CAClE,IAAI,SAAS,YAAY;EAGxB,OAAO,IAAI,IAAI;EACf;CACD;CAGA,OAAO,MAAM,IAAI,IAAI;AACtB;;;;ACjCA,MAAM,cAAc;;;;;;;;;;AAWpB,SAAS,WAAW,MAAc,OAA0D;CAC3F,IAAI;CACJ,IAAI,WAAW,OAAO,SAAS;CAC/B,MAAM,MAAM,SAAS,OAAO,OAAO,oBAAoB,MAAM,MAAM;CACnE,MAAM,QAAQ,YAAY;EACzB,MAAM,SAAS;EACf,SAAS;EACT,MAAM,QAAQ,MAAM;CACrB;CACA,OAAO,IAAI,eACV;EACC,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,MAAM,SAAS,KAAK,IAAI,aAAa,MAAM,QAAQ;IACnD,IAAI,SAAS,GACZ,WAAW,MAAM,KAAK,IAAI;IAE3B,MAAM,EAAE,WA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AAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
1
+ {"version":3,"file":"node-DiMwdTOC.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\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI,UAAU;CACd,MAAM,aAAa;EAClB,WAAW;EACX,IAAI,YAAY,GACf,QAAQ,KAAK;CAEf;CACA,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,QAAQ,QAAQ,IAAI;CAE1B,iBAAiB;EAChB,QAAQ,KAAK;CACd,GAAG,gBAAgB,CAAC,CAAC,MAAM;AAC5B;;AAGA,SAAS,MAAM,QAA4B,MAAwB;CAClE,IAAI,SAAS,YAAY;EAGxB,OAAO,IAAI,IAAI;EACf;CACD;CAGA,OAAO,MAAM,IAAI,IAAI;AACtB;;;;ACjCA,MAAM,cAAc;;;;;;;;;;AAWpB,SAAS,WAAW,MAAc,OAA0D;CAC3F,IAAI;CACJ,IAAI,WAAW,OAAO,SAAS;CAC/B,MAAM,MAAM,SAAS,OAAO,OAAO,oBAAoB,MAAM,MAAM;CACnE,MAAM,QAAQ,YAAY;EACzB,MAAM,SAAS;EACf,SAAS;EACT,MAAM,QAAQ,MAAM;CACrB;CACA,OAAO,IAAI,eACV;EACC,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,MAAM,SAAS,KAAK,IAAI,aAAa,MAAM,QAAQ;IACnD,IAAI,SAAS,GACZ,WAAW,MAAM,KAAK,IAAI;IAE3B,MAAM,EAAE,WAAW,WAClB,UAAU,KAAK,UAAU,OACtB;KAAE,WAAW;KAAG,wBAAQ,IAAI,WAAW,CAA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WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-BKJxtIuj.js";
1
+ import { D as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-C_I3i62n.js";
2
2
  import { MiddlewareHandler } from "hono";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  /** A Connect middleware, such as `vite.middlewares`. */
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as tcp, t as parsePort } from "./tcp-CKMCT9RP.js";
2
- import { n as devServerStage, r as nodeFiles, t as host } from "./node-DFI5TjTk.js";
1
+ import { n as tcp, t as parsePort } from "./tcp-B8aFGQRB.js";
2
+ import { n as devServerStage, r as nodeFiles, t as host } from "./node-DiMwdTOC.js";
3
3
 
4
4
  export { devServerStage, host, nodeFiles, parsePort, tcp };
@@ -1,11 +1,11 @@
1
- import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-BKJxtIuj.js";
1
+ import { _ as Mode, a as FrameworkRuntime, y as RequestContext } from "./types-C_I3i62n.js";
2
2
  import { ServerBuild } from "react-router";
3
3
  /** What the server puts in React Router's context for each request. */
4
4
  export type AppServerContext = RequestContext;
5
5
  /**
6
6
  * The React Router context key for {@link AppServerContext}. Outside a server
7
7
  * request, such as in React Router's prerender pass, it holds no request ID
8
- * and a logger that writes to `jsonSink()`. `requestContext()` from
8
+ * and the logger that `logger()` gives there. `requestContext()` from
9
9
  * `@ngrok/app-server` gives the same values.
10
10
  *
11
11
  * @example
@@ -1,12 +1,11 @@
1
- import { n as requestContextValues } from "./request-context-BtQ87VYb.js";
2
- import { a as sinkLogger, r as jsonSink } from "./log-C8LGQ23s.js";
1
+ import { i as requestContextValues, n as outsideLogger } from "./request-context-BdAH1D-2.js";
3
2
  import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
4
3
 
5
4
  // src/react-router/index.ts
6
5
  /**
7
6
  * The React Router context key for {@link AppServerContext}. Outside a server
8
7
  * request, such as in React Router's prerender pass, it holds no request ID
9
- * and a logger that writes to `jsonSink()`. `requestContext()` from
8
+ * and the logger that `logger()` gives there. `requestContext()` from
10
9
  * `@ngrok/app-server` gives the same values.
11
10
  *
12
11
  * @example
@@ -16,7 +15,7 @@ import { RouterContextProvider, createContext, createRequestHandler } from "reac
16
15
  */
17
16
  const appServerContext = createContext({
18
17
  requestId: void 0,
19
- logger: sinkLogger(jsonSink()),
18
+ logger: outsideLogger,
20
19
  cspNonce: void 0,
21
20
  clientAddress: void 0
22
21
  });
@@ -1 +1 @@
1
- {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { MiddlewareFunction, ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { AppServerEnv, FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/** The Hono context of the request, for {@link recordRoutePattern}. */\nconst honoContext = createContext<Context<AppServerEnv>>();\n\n/**\n * Sets `routePattern` on the Hono context to the route pattern that React\n * Router matched, such as `/domains/:domainId`, so the access log writes\n * `http.route`. Why a root middleware: it runs for each document, data, and\n * resource request, and it costs less for each request than a request\n * handler instrumentation.\n */\nconst recordRoutePattern: MiddlewareFunction<Response> = async ({ pattern, context }, next) => {\n\tif (pattern !== \"\") {\n\t\t// Why the slash: React Router joins the relative paths of the routes, such as `domains/:domainId`.\n\t\tcontext.get(honoContext).set(\"routePattern\", pattern.startsWith(\"/\") ? pattern : `/${pattern}`);\n\t}\n\treturn next();\n};\n\n/** `build` with {@link recordRoutePattern} before the middleware of each root route. */\nfunction withRoutePattern(build: ServerBuild): ServerBuild {\n\tconst routes = Object.fromEntries(\n\t\tObject.entries(build.routes).map(([id, route]) => [\n\t\t\tid,\n\t\t\troute == null || route.parentId != null\n\t\t\t\t? route\n\t\t\t\t: {\n\t\t\t\t\t\t...route,\n\t\t\t\t\t\tmodule: {\n\t\t\t\t\t\t\t...route.module,\n\t\t\t\t\t\t\tmiddleware: [recordRoutePattern, ...(route.module.middleware ?? [])],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t]),\n\t);\n\treturn { ...build, routes };\n}\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}. The\n * access log gets the route pattern that React Router matched.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(withRoutePattern(build), mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\trouterContext.set(honoContext, context);\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;CAC7B,UAAU;CACV,eAAe;AAChB,CAAC;;AAGD,MAAM,cAAc,cAAqC;;;;;;;;AASzD,MAAM,qBAAmD,OAAO,EAAE,SAAS,WAAW,SAAS;CAC9F,IAAI,YAAY,IAEf,QAAQ,IAAI,WAAW,CAAC,CAAC,IAAI,gBAAgB,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI,SAAS;CAE/F,OAAO,KAAK;AACb;;AAGA,SAAS,iBAAiB,OAAiC;CAC1D,MAAM,SAAS,OAAO,YACrB,OAAO,QAAQ,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,WAAW,CACjD,IACA,SAAS,QAAQ,MAAM,YAAY,OAChC,QACA;EACA,GAAG;EACH,QAAQ;GACP,GAAG,MAAM;GACT,YAAY,CAAC,oBAAoB,GAAI,MAAM,OAAO,cAAc,CAAC,CAAE;EACpE;CACD,CACH,CAAC,CACF;CACA,OAAO;EAAE,GAAG;EAAO;CAAO;AAC3B;;;;;;;AAQA,SAAgB,cAAc,OAAsC;CACnE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,YAAY,SACZ,WAAW,SACX,0BAA0B,SAC1B,OAAO,MAAM,yBAAyB;AAExC;;;;;;;;;AAUA,SAAgB,QAAQ,OAAgB,EAAE,QAA0C;CACnF,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,uDAAuD;CAGxE,IAAI,MAAM,eAAe,KACxB,MAAM,IAAI,MACT,oFAAoF,MAAM,WAAW,GACtG;CAED,MAAM,UAAU,qBAAqB,iBAAiB,KAAK,GAAG,IAAI;CAElE,MAAM,eACL,MAAM,eAAe,SAAS,SAC3B,CAAC,MAAM,YAAY,IAAI,MAAM,eAAe,gBAAgB,aAAa,CAAC,CACzE,KAAK,GAAG,CAAC,CACT,WAAW,SAAS,GAAG,IACxB;CACJ,OAAO;EACN,MAAM;EACN,iBAAiB,MAAM;EACvB,kBAAkB,MAAM;EACxB,gBAAgB,SAAS,KAAK,SAAS,OAAO,KAAK,SAAS;EAC5D,cAAc,EAAE,SAAS,gBAAgB;EACzC,OAAO,OAAO,SAAS,YAAY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,cAAc,IAAI,aAAa,OAAO;GACtC,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
1
+ {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { MiddlewareFunction, ServerBuild } from \"react-router\";\nimport { outsideLogger, requestContextValues } from \"../core/request-context.js\";\nimport type { AppServerEnv, FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and the logger that `logger()` gives there. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: outsideLogger,\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/** The Hono context of the request, for {@link recordRoutePattern}. */\nconst honoContext = createContext<Context<AppServerEnv>>();\n\n/**\n * Sets `routePattern` on the Hono context to the route pattern that React\n * Router matched, such as `/domains/:domainId`, so the access log writes\n * `http.route`. Why a root middleware: it runs for each document, data, and\n * resource request, and it costs less for each request than a request\n * handler instrumentation.\n */\nconst recordRoutePattern: MiddlewareFunction<Response> = async ({ pattern, context }, next) => {\n\tif (pattern !== \"\") {\n\t\t// Why the slash: React Router joins the relative paths of the routes, such as `domains/:domainId`.\n\t\tcontext.get(honoContext).set(\"routePattern\", pattern.startsWith(\"/\") ? pattern : `/${pattern}`);\n\t}\n\treturn next();\n};\n\n/** `build` with {@link recordRoutePattern} before the middleware of each root route. */\nfunction withRoutePattern(build: ServerBuild): ServerBuild {\n\tconst routes = Object.fromEntries(\n\t\tObject.entries(build.routes).map(([id, route]) => [\n\t\t\tid,\n\t\t\troute == null || route.parentId != null\n\t\t\t\t? route\n\t\t\t\t: {\n\t\t\t\t\t\t...route,\n\t\t\t\t\t\tmodule: {\n\t\t\t\t\t\t\t...route.module,\n\t\t\t\t\t\t\tmiddleware: [recordRoutePattern, ...(route.module.middleware ?? [])],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t]),\n\t);\n\treturn { ...build, routes };\n}\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}. The\n * access log gets the route pattern that React Router matched.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(withRoutePattern(build), mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\trouterContext.set(honoContext, context);\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;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,kBAAkB,MAAM;EACxB,gBAAgB,SAAS,KAAK,SAAS,OAAO,KAAK,SAAS;EAC5D,cAAc,EAAE,SAAS,gBAAgB;EACzC,OAAO,OAAO,SAAS,YAAY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,cAAc,IAAI,aAAa,OAAO;GACtC,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
@@ -0,0 +1,80 @@
1
+ import { i as jsonSink, o as sinkLogger, r as hookSink } from "./log-CW_g1pWk.js";
2
+
3
+ // src/core/request-context.ts
4
+ /**
5
+ * Each store that a request ran in. Why a set: two entries in one process can
6
+ * have two hosts, and each request uses the store of its own app.
7
+ */
8
+ const stores = /* @__PURE__ */ new Set();
9
+ /** The {@link RequestContext} values of a request. */
10
+ function requestContextValues(context) {
11
+ return {
12
+ requestId: context.get("requestId"),
13
+ logger: context.get("logger"),
14
+ cspNonce: context.get("cspNonce"),
15
+ clientAddress: context.get("clientAddress")
16
+ };
17
+ }
18
+ /** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
19
+ async function withRequestContext(store, context, work) {
20
+ if (store == null) return work();
21
+ stores.add(store);
22
+ return store.run(context, work);
23
+ }
24
+ /**
25
+ * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
26
+ * outside a server request, such as in a prerender pass, or on a host with no
27
+ * request storage.
28
+ *
29
+ * @example
30
+ * export async function loader() {
31
+ * requestContext()?.logger.info("loading the dashboard");
32
+ * }
33
+ */
34
+ function requestContext() {
35
+ const context = currentContext();
36
+ return context == null ? void 0 : requestContextValues(context);
37
+ }
38
+ /** The Hono context of the request that runs, else `undefined`. */
39
+ function currentContext() {
40
+ for (const store of stores) {
41
+ const context = store.get();
42
+ if (context != null) return context;
43
+ }
44
+ }
45
+ /** The sink of the process. `createServer` sets it to its own sink, with its hooks. */
46
+ let processSink = hookSink(jsonSink());
47
+ /** Sets the sink of the logger that {@link logger} gives outside a request. The last call wins. */
48
+ function setProcessSink(sink) {
49
+ processSink = sink;
50
+ }
51
+ /**
52
+ * A logger that writes to the sink of the process at the time of each call.
53
+ * Why: a value made before `createServer`, such as a context default, then
54
+ * writes to the sink of the server.
55
+ */
56
+ const outsideLogger = sinkLogger({ log: ({ level, message, attributes }) => {
57
+ processSink.log({
58
+ level,
59
+ message,
60
+ attributes
61
+ });
62
+ } });
63
+ /**
64
+ * The logger of the request that runs. Outside a request, such as at module
65
+ * load or in a prerender pass, it gives a logger that writes to the sink and
66
+ * the hooks of the last `createServer` call, else to `jsonSink()`.
67
+ *
68
+ * @example
69
+ * import { logger } from "@ngrok/app-server";
70
+ *
71
+ * export async function loader() {
72
+ * logger().info("loading the dashboard", { "usr.id": userId });
73
+ * }
74
+ */
75
+ function logger() {
76
+ return currentContext()?.get("logger") ?? outsideLogger;
77
+ }
78
+
79
+ export { setProcessSink as a, requestContextValues as i, outsideLogger as n, withRequestContext as o, requestContext as r, logger as t };
80
+ //# sourceMappingURL=request-context-BdAH1D-2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context-BdAH1D-2.js","names":[],"sources":["../src/core/request-context.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { hookSink, jsonSink, sinkLogger } from \"./log.js\";\nimport type {\n\tAppServerEnv,\n\tLogSink,\n\tRequestContext,\n\tRequestLogger,\n\tRequestStore,\n} from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** The {@link RequestContext} values of a request. */\nexport function requestContextValues(context: Context<AppServerEnv>): RequestContext {\n\treturn {\n\t\trequestId: context.get(\"requestId\"),\n\t\tlogger: context.get(\"logger\"),\n\t\tcspNonce: context.get(\"cspNonce\"),\n\t\tclientAddress: context.get(\"clientAddress\"),\n\t};\n}\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext<Result>(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<Result>,\n): Promise<Result> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tconst context = currentContext();\n\treturn context == null ? undefined : requestContextValues(context);\n}\n\n/** The Hono context of the request that runs, else `undefined`. */\nfunction currentContext(): Context<AppServerEnv> | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn context;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The sink of the process. `createServer` sets it to its own sink, with its hooks. */\nlet processSink: LogSink = hookSink(jsonSink());\n\n/** Sets the sink of the logger that {@link logger} gives outside a request. The last call wins. */\nexport function setProcessSink(sink: LogSink): void {\n\tprocessSink = sink;\n}\n\n/**\n * A logger that writes to the sink of the process at the time of each call.\n * Why: a value made before `createServer`, such as a context default, then\n * writes to the sink of the server.\n */\nexport const outsideLogger: RequestLogger = sinkLogger({\n\tlog: ({ level, message, attributes }) => {\n\t\tprocessSink.log({ level, message, attributes });\n\t},\n});\n\n/**\n * The logger of the request that runs. Outside a request, such as at module\n * load or in a prerender pass, it gives a logger that writes to the sink and\n * the hooks of the last `createServer` call, else to `jsonSink()`.\n *\n * @example\n * import { logger } from \"@ngrok/app-server\";\n *\n * export async function loader() {\n * \tlogger().info(\"loading the dashboard\", { \"usr.id\": userId });\n * }\n */\nexport function logger(): RequestLogger {\n\treturn currentContext()?.get(\"logger\") ?? outsideLogger;\n}\n"],"mappings":";;;;;;;AAcA,MAAM,yBAAS,IAAI,IAAkB;;AAGrC,SAAgB,qBAAqB,SAAgD;CACpF,OAAO;EACN,WAAW,QAAQ,IAAI,WAAW;EAClC,QAAQ,QAAQ,IAAI,QAAQ;EAC5B,UAAU,QAAQ,IAAI,UAAU;EAChC,eAAe,QAAQ,IAAI,eAAe;CAC3C;AACD;;AAGA,eAAsB,mBACrB,OACA,SACA,MACkB;CAClB,IAAI,SAAS,MACZ,OAAO,KAAK;CAEb,OAAO,IAAI,KAAK;CAChB,OAAO,MAAM,IAAI,SAAS,IAAI;AAC/B;;;;;;;;;;;AAYA,SAAgB,iBAA6C;CAC5D,MAAM,UAAU,eAAe;CAC/B,OAAO,WAAW,OAAO,SAAY,qBAAqB,OAAO;AAClE;;AAGA,SAAS,iBAAoD;CAC5D,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,WAAW,MACd,OAAO;CAET;AAED;;AAGA,IAAI,cAAuB,SAAS,SAAS,CAAC;;AAG9C,SAAgB,eAAe,MAAqB;CACnD,cAAc;AACf;;;;;;AAOA,MAAa,gBAA+B,WAAW,EACtD,MAAM,EAAE,OAAO,SAAS,iBAAiB;CACxC,YAAY,IAAI;EAAE;EAAO;EAAS;CAAW,CAAC;AAC/C,EACD,CAAC;;;;;;;;;;;;;AAcD,SAAgB,SAAwB;CACvC,OAAO,eAAe,CAAC,EAAE,IAAI,QAAQ,KAAK;AAC3C"}
@@ -1,5 +1,5 @@
1
+ import { t as asError } from "./log-CW_g1pWk.js";
1
2
  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-C8LGQ23s.js";
3
3
 
4
4
  // src/core/response-edge.ts
5
5
  function ignore() {}
@@ -116,7 +116,7 @@ var ResponseEdge = class {
116
116
  fail(error) {
117
117
  try {
118
118
  if (this.#logger != null) {
119
- this.#logger.error("unhandled error", errorAttributes(error));
119
+ this.#logger.error("unhandled error", { error: asError(error) });
120
120
  return;
121
121
  }
122
122
  } catch {}
@@ -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-D3CAjukJ.js.map
327
+ //# sourceMappingURL=response-edge-7eUl2ewl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-edge-7eUl2ewl.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { asError } 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\", { error: asError(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,SAA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O,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,7 +1,7 @@
1
1
  import { n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
- import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
2
+ import { t as ResponseEdge } from "./response-edge-7eUl2ewl.js";
3
3
  import { s as readIfQueued } from "./compression-CT2mWlKM.js";
4
- import { r as waitsForZlib } from "./compress-CO0Nwc8x.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-5SOKsW3C.js.map
289
+ //# sourceMappingURL=response-writer-CLtCseu5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"response-writer-5SOKsW3C.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./compress.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":";;;;;;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;;AAGA,SAAS,WACR,QACwC;CACxC,OAAO,yBACN,mBAAmB,OAAO,SAAS,EAAE,UAAU,eAAe;EAC7D,MAAM,EAAE,kBAAkB,SAAS;EAEnC,IAAI,EAAE,oBAAoB,oBAAoB,EAAE,oBAAoB,iBACnE,OAAO,OAAO,SAAS,EAAE,cAAc,CAA4B;EAGpE,MAAM,SAASA,SAAS;EAExB,IAAI,UAAU,MACb,SAAS,MAAM;EAEhB,IAAI,CAAC,iBAAiB;GACrB,MAAM,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;GAAS,CAAC;GAE5E,IAAI,SAAS,WACZ,MAAM,SAAS,MAAM,OAAO;GAE7B,OAAO;EACR;EACA,MAAM,OAAO,IAAI,aAAa;EAC9B,IAAI;EACJ,IAAI;GACH,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;IAAU;GAAK,CAAC;EAC7E,SAAS,OAAO;GAEf,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;GACzB,MAAM;EACP;EACA,MAAM,cAAc,UAAU,UAAU,IAAI;EAC5C,OAAO;CACR,CAAC,CACF;AACD"}
1
+ {"version":3,"file":"response-writer-CLtCseu5.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./compress.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;;AAE5B,MAAM,eAAe,IAAI,SAAS,MAAM,EAAE,SAAS,GAAG,sBAAsB,OAAO,EAAE,CAAC;;AAEtF,MAAM,uBAAuB;;AAE7B,MAAM,aAAa,OAAO,KAAK,uBAAuB;;AAGtD,eAAe,kBAAiC;CAC/C,OAAO,IAAI,SAAS,YAAY;EAC/B,QAAQ,SAAS,OAAO;CACzB,CAAC;AACF;;AAGA,eAAe,QAAQ,UAAyC;CAC/D,OAAO,IAAI,SAAS,YAAY;EAC/B,MAAM,aAAa;GAClB,SAAS,IAAI,SAAS,IAAI;GAC1B,SAAS,IAAI,SAAS,IAAI;GAC1B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