@ngrok/app-server 0.3.6 → 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 (53) hide show
  1. package/README.md +40 -9
  2. package/dist/cli.js +3 -3
  3. package/dist/client.js +1 -1
  4. package/dist/{create-server-C_90R50y.js → create-server-C63luLkn.js} +71 -30
  5. package/dist/create-server-C63luLkn.js.map +1 -0
  6. package/dist/{create-server-kxyhCdhv.d.ts → create-server-DKJ0wASH.d.ts} +33 -13
  7. package/dist/{entry-65IESBSA.js → entry-BSbsQ_kq.js} +13 -5
  8. package/dist/entry-BSbsQ_kq.js.map +1 -0
  9. package/dist/{entry-CNL4OsEn.d.ts → entry-C9bBcYeP.d.ts} +3 -3
  10. package/dist/index.d.ts +18 -5
  11. package/dist/index.js +6 -6
  12. package/dist/{load-entry-BftQ3qlz.js → load-entry-DgZyPtoD.js} +4 -4
  13. package/dist/{load-entry-BftQ3qlz.js.map → load-entry-DgZyPtoD.js.map} +1 -1
  14. package/dist/log-CW_g1pWk.js +304 -0
  15. package/dist/log-CW_g1pWk.js.map +1 -0
  16. package/dist/{node-Fo6EodEV.js → node-DBwgrye_.js} +2 -2
  17. package/dist/{node-Fo6EodEV.js.map → node-DBwgrye_.js.map} +1 -1
  18. package/dist/{node-CA7t-s6D.js → node-DiMwdTOC.js} +3 -3
  19. package/dist/{node-CA7t-s6D.js.map → node-DiMwdTOC.js.map} +1 -1
  20. package/dist/node.d.ts +1 -1
  21. package/dist/node.js +2 -2
  22. package/dist/react-router.d.ts +2 -2
  23. package/dist/react-router.js +3 -4
  24. package/dist/react-router.js.map +1 -1
  25. package/dist/request-context-BdAH1D-2.js +80 -0
  26. package/dist/request-context-BdAH1D-2.js.map +1 -0
  27. package/dist/{response-edge-D3CAjukJ.js → response-edge-7eUl2ewl.js} +3 -3
  28. package/dist/response-edge-7eUl2ewl.js.map +1 -0
  29. package/dist/{response-writer-BUyOW4n2.js → response-writer-CLtCseu5.js} +2 -2
  30. package/dist/{response-writer-BUyOW4n2.js.map → response-writer-CLtCseu5.js.map} +1 -1
  31. package/dist/{serve-CEecObwD.js → serve-DCaIBTM-.js} +2 -2
  32. package/dist/{serve-CEecObwD.js.map → serve-DCaIBTM-.js.map} +1 -1
  33. package/dist/{start-CDnHKNca.js → start-D2IVWkow.js} +29 -13
  34. package/dist/start-D2IVWkow.js.map +1 -0
  35. package/dist/tanstack-start.d.ts +2 -2
  36. package/dist/tanstack-start.js +1 -1
  37. package/dist/{tcp-BPeUZaNg.js → tcp-B8aFGQRB.js} +2 -2
  38. package/dist/{tcp-BPeUZaNg.js.map → tcp-B8aFGQRB.js.map} +1 -1
  39. package/dist/testing.d.ts +2 -2
  40. package/dist/testing.js +4 -4
  41. package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D_52DJaQ.d.ts} +2 -2
  42. package/dist/{types-BKJxtIuj.d.ts → types-C_I3i62n.d.ts} +32 -4
  43. package/dist/vercel.d.ts +2 -2
  44. package/dist/vercel.js +4 -4
  45. package/package.json +1 -1
  46. package/dist/create-server-C_90R50y.js.map +0 -1
  47. package/dist/entry-65IESBSA.js.map +0 -1
  48. package/dist/log-C8LGQ23s.js +0 -149
  49. package/dist/log-C8LGQ23s.js.map +0 -1
  50. package/dist/request-context-BtQ87VYb.js +0 -40
  51. package/dist/request-context-BtQ87VYb.js.map +0 -1
  52. package/dist/response-edge-D3CAjukJ.js.map +0 -1
  53. package/dist/start-CDnHKNca.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as requestContext } from "./request-context-BtQ87VYb.js";
1
+ import { i as jsonSink } from "./log-CW_g1pWk.js";
2
+ import { r as requestContext, t as logger } from "./request-context-BdAH1D-2.js";
2
3
  import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
3
4
  import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
4
- import { r as jsonSink } from "./log-C8LGQ23s.js";
5
- import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
6
- import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-C_90R50y.js";
7
- import { t as createEntry } from "./entry-65IESBSA.js";
5
+ import { t as ResponseEdge } from "./response-edge-7eUl2ewl.js";
6
+ import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-C63luLkn.js";
7
+ import { t as createEntry } from "./entry-BSbsQ_kq.js";
8
8
 
9
9
  // src/core/event-stream.ts
10
10
  function formatEvent({ data, event, id }) {
@@ -197,5 +197,5 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
197
197
  });
198
198
  }
199
199
 
200
- export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
200
+ export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, logger, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
201
201
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
- import { t as createServer } from "./create-server-C_90R50y.js";
2
- import { n as isAppServerEntry, t as createEntry } from "./entry-65IESBSA.js";
3
- import { t as host } from "./node-CA7t-s6D.js";
1
+ import { t as createServer } from "./create-server-C63luLkn.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-BSbsQ_kq.js";
3
+ import { t as host } from "./node-DiMwdTOC.js";
4
4
 
5
5
  // src/cli/load-entry.ts
6
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -34,4 +34,4 @@ async function loadEntry(build) {
34
34
  }
35
35
 
36
36
  export { loadEntry as t };
37
- //# sourceMappingURL=load-entry-BftQ3qlz.js.map
37
+ //# sourceMappingURL=load-entry-DgZyPtoD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-BftQ3qlz.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-DgZyPtoD.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
@@ -0,0 +1,304 @@
1
+ // src/core/log.ts
2
+ /** The standard output (stdout) lines that wait for {@link flushLogs}. */
3
+ let pending = "";
4
+ /** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */
5
+ let exiting = false;
6
+ process.on("exit", () => {
7
+ exiting = true;
8
+ process.stdout._handle?.setBlocking?.(true);
9
+ for (const line of pending.match(/[^\n]*\n/gu) ?? []) process.stdout.write(line);
10
+ pending = "";
11
+ });
12
+ /**
13
+ * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it
14
+ * before the process exits.
15
+ */
16
+ function flushLogs() {
17
+ if (pending === "") return;
18
+ const lines = pending;
19
+ pending = "";
20
+ process.stdout.write(lines);
21
+ }
22
+ /**
23
+ * Adds `line` to the next stdout write. Why one write for each turn of the
24
+ * event loop: a write to a pipe, such as stdout in Docker, is a system call,
25
+ * and under load many requests end in one turn.
26
+ */
27
+ function writeStdout(line) {
28
+ if (exiting) {
29
+ process.stdout.write(line);
30
+ return;
31
+ }
32
+ if (pending === "") setImmediate(flushLogs);
33
+ pending += line;
34
+ }
35
+ /** The end of a {@link jsonSink} line whose attributes have no JSON. */
36
+ const NO_JSON = "\"log.error\":\"attributes not written as JSON\"}";
37
+ /**
38
+ * A log sink that writes one JSON object per line. Each line has `time`,
39
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
40
+ * standard attributes. The default writes the lines of one event-loop turn
41
+ * to stdout at the end of the turn.
42
+ *
43
+ * @param write - Where each line goes. Defaults to stdout.
44
+ *
45
+ * @example
46
+ * createServer({ logger: jsonSink() });
47
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
48
+ */
49
+ function jsonSink(write = writeStdout) {
50
+ return { log: ({ level, message, attributes }) => {
51
+ const time = isoNow();
52
+ const head = `{"time":"${time}","level":"${level}","message":${JSON.stringify(message)}`;
53
+ const ownKeys = "time" in attributes || "level" in attributes || "message" in attributes;
54
+ const json = toJson(ownKeys ? {
55
+ time,
56
+ level,
57
+ message,
58
+ ...attributes
59
+ } : attributes);
60
+ let line = `${head},${NO_JSON}`;
61
+ if (json != null) line = ownKeys ? json : `${head}${json === "{}" ? "}" : `,${json.slice(1)}`}`;
62
+ write(`${line}\n`);
63
+ } };
64
+ }
65
+ /**
66
+ * A log sink that writes one line of `key=value` pairs per event, in the text
67
+ * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control
68
+ * character is quoted, so an escape sequence cannot reach the terminal.
69
+ * `app-server start` uses it, because a person reads those lines.
70
+ *
71
+ * @param write - Where each line goes. Defaults to stdout, at once. Why not
72
+ * one write for each turn: the lines then keep their order with Vite's lines.
73
+ *
74
+ * @example
75
+ * textSink().log({ level: "info", message: "port in use, trying the next port", attributes: { "server.port": 3000 } });
76
+ * // time=2026-11-11T12:00:00.000Z level=INFO msg="port in use, trying the next port" server.port=3000
77
+ */
78
+ function textSink(write = (line) => {
79
+ process.stdout.write(line);
80
+ }) {
81
+ return { log: ({ level, message, attributes }) => {
82
+ let line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;
83
+ for (const [key, value] of Object.entries(attributes)) line += ` ${key}=${textValue(value)}`;
84
+ write(`${line}\n`);
85
+ } };
86
+ }
87
+ /** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */
88
+ function textValue(value) {
89
+ if (typeof value === "bigint") return `${value}n`;
90
+ const text = typeof value === "string" ? value : toJson(value) ?? String(value);
91
+ return /^[^\s"=\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);
92
+ }
93
+ /**
94
+ * `value` as JSON, with each bigint as a string such as `"1n"`, and each
95
+ * cycle as `"[Circular]"`. Gives `undefined` for a value with no JSON, such
96
+ * as a function, or one whose `toJSON` throws. Why try the plain call first:
97
+ * the replacer runs for each value, and a log line seldom needs it.
98
+ */
99
+ function toJson(value) {
100
+ try {
101
+ return JSON.stringify(value);
102
+ } catch {
103
+ try {
104
+ return JSON.stringify(value, safeReplacer());
105
+ } catch {
106
+ return;
107
+ }
108
+ }
109
+ }
110
+ /** A `JSON.stringify` replacer for {@link toJson}. */
111
+ function safeReplacer() {
112
+ const ancestors = [];
113
+ return function replace(_key, value) {
114
+ if (typeof value === "bigint") return `${value}n`;
115
+ if (typeof value !== "object" || value == null) return value;
116
+ while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
117
+ if (ancestors.includes(value)) return "[Circular]";
118
+ ancestors.push(value);
119
+ return value;
120
+ };
121
+ }
122
+ /** The millisecond of the last `time`, and its ISO string. */
123
+ let lastMs = NaN;
124
+ let lastTime = "";
125
+ /** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */
126
+ let lastSecond = NaN;
127
+ let secondPrefix = "";
128
+ /**
129
+ * The time now, as `new Date().toISOString()` gives it. Why keep the last
130
+ * time: under load, many lines share a millisecond. Why keep the prefix of
131
+ * the second: `toISOString()` costs more than the rest of a line.
132
+ */
133
+ function isoNow() {
134
+ const now = Date.now();
135
+ if (now !== lastMs) {
136
+ lastMs = now;
137
+ const second = Math.floor(now / 1e3);
138
+ if (second !== lastSecond) {
139
+ lastSecond = second;
140
+ secondPrefix = new Date(now).toISOString().slice(0, -4);
141
+ }
142
+ lastTime = `${secondPrefix}${String(now - second * 1e3).padStart(3, "0")}Z`;
143
+ }
144
+ return lastTime;
145
+ }
146
+ /**
147
+ * A thrown value as an `Error`, so a log line gives it the `error.*` fields.
148
+ * Hono sends only an `Error` to `onError`, and rethrows any other value.
149
+ */
150
+ function asError(error) {
151
+ return error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
152
+ }
153
+ /** The fields of an error that {@link errorFields} writes on its own, not as an own field. */
154
+ const ERROR_KEYS = /* @__PURE__ */ new Set([
155
+ "name",
156
+ "message",
157
+ "stack",
158
+ "cause"
159
+ ]);
160
+ /**
161
+ * The dotted fields of `error` under `prefix`: `kind`, `message`, `stack`,
162
+ * each own field, such as `code`, the `cause` chain, and the `errors` of an
163
+ * `AggregateError`. An error with `toJSON` gives its own fields from it. An
164
+ * error that is its own ancestor in the chain gives `"[Circular]"`.
165
+ *
166
+ * @example
167
+ * errorFields(new Error("no row", { cause: new RangeError("bad id") }), "error");
168
+ * // => { "error.kind": "Error", "error.message": "no row", "error.stack": "…",
169
+ * // "error.cause.kind": "RangeError", "error.cause.message": "bad id", "error.cause.stack": "…" }
170
+ */
171
+ function errorFields(error, prefix) {
172
+ const ancestors = [];
173
+ const addError = (fields, base, current) => {
174
+ const at = (key) => base === "" ? key : `${base}.${key}`;
175
+ const add = (key, value) => {
176
+ if (!(value instanceof Error)) fields[key] = value;
177
+ else if (ancestors.includes(value)) fields[key] = "[Circular]";
178
+ else addError(fields, key, value);
179
+ };
180
+ ancestors.push(current);
181
+ fields[at("kind")] = current.name;
182
+ fields[at("message")] = current.message;
183
+ fields[at("stack")] = current.stack;
184
+ const toJSON = "toJSON" in current ? current.toJSON : void 0;
185
+ const own = typeof toJSON === "function" ? Reflect.apply(toJSON, current, []) : current;
186
+ if (typeof own === "object" && own != null) {
187
+ for (const [key, value] of Object.entries(own)) if (!ERROR_KEYS.has(key)) add(at(key), value);
188
+ }
189
+ if (current.cause != null) add(at("cause"), current.cause);
190
+ if (current instanceof AggregateError) fields[at("errors")] = current.errors.map((member) => {
191
+ if (!(member instanceof Error)) return member;
192
+ if (ancestors.includes(member)) return "[Circular]";
193
+ const memberFields = {};
194
+ addError(memberFields, "", member);
195
+ return memberFields;
196
+ });
197
+ ancestors.pop();
198
+ };
199
+ const fields = {};
200
+ addError(fields, prefix, error);
201
+ return fields;
202
+ }
203
+ /** `attributes` with each `Error` value replaced by its fields, after the `change` hook. */
204
+ function flattenErrors(attributes, change) {
205
+ let hasError = false;
206
+ for (const key in attributes) if (attributes[key] instanceof Error) {
207
+ hasError = true;
208
+ break;
209
+ }
210
+ if (!hasError) return attributes;
211
+ const flat = {};
212
+ for (const [key, value] of Object.entries(attributes)) if (value instanceof Error) {
213
+ const fields = errorFields(value, key);
214
+ Object.assign(flat, change == null ? fields : change({
215
+ error: value,
216
+ prefix: key,
217
+ fields
218
+ }));
219
+ } else flat[key] = value;
220
+ return flat;
221
+ }
222
+ /**
223
+ * A sink that writes each line to `sink`, after it replaces each `Error`
224
+ * value with its fields, and then runs the `attributes` hook.
225
+ *
226
+ * @example
227
+ * hookSink(jsonSink()).log({ level: "error", message: "failed", attributes: { error: new Error("boom") } });
228
+ * // {"time":"…","level":"error","message":"failed","error.kind":"Error","error.message":"boom","error.stack":"…"}
229
+ */
230
+ function hookSink(sink, { attributes: changeAttributes, error: changeError } = {}) {
231
+ return { log: (line) => {
232
+ const flat = flattenErrors(line.attributes, changeError);
233
+ const flatLine = flat === line.attributes ? line : {
234
+ ...line,
235
+ attributes: flat
236
+ };
237
+ sink.log(changeAttributes == null ? flatLine : {
238
+ ...flatLine,
239
+ attributes: changeAttributes(flatLine)
240
+ });
241
+ } };
242
+ }
243
+ /**
244
+ * A logger that writes to `sink`. `withBase` gives the attributes of each
245
+ * line as a new object, from the attributes that the caller gives.
246
+ */
247
+ function sinkLogger(sink, withBase = (attributes) => ({ ...attributes })) {
248
+ return {
249
+ debug: (message, attributes = {}) => {
250
+ sink.log({
251
+ level: "debug",
252
+ message,
253
+ attributes: withBase(attributes)
254
+ });
255
+ },
256
+ info: (message, attributes = {}) => {
257
+ sink.log({
258
+ level: "info",
259
+ message,
260
+ attributes: withBase(attributes)
261
+ });
262
+ },
263
+ warn: (message, attributes = {}) => {
264
+ sink.log({
265
+ level: "warn",
266
+ message,
267
+ attributes: withBase(attributes)
268
+ });
269
+ },
270
+ error: (message, attributes = {}) => {
271
+ sink.log({
272
+ level: "error",
273
+ message,
274
+ attributes: withBase(attributes)
275
+ });
276
+ }
277
+ };
278
+ }
279
+ /**
280
+ * A logger whose lines carry the request's ID, method, path, and
281
+ * `logAttributes`. These fields win over a caller's field of the same name.
282
+ */
283
+ function requestLogger(sink, context) {
284
+ return sinkLogger(sink, (attributes) => {
285
+ const requestId = context.get("requestId");
286
+ const { method, path } = context.req;
287
+ const logAttributes = context.get("logAttributes");
288
+ const line = {
289
+ "http.request_id": requestId,
290
+ "http.method": method,
291
+ "http.url_details.path": path,
292
+ ...logAttributes,
293
+ ...attributes
294
+ };
295
+ line["http.request_id"] = requestId;
296
+ line["http.method"] = method;
297
+ line["http.url_details.path"] = path;
298
+ Object.assign(line, logAttributes);
299
+ return line;
300
+ });
301
+ }
302
+
303
+ export { requestLogger as a, jsonSink as i, flushLogs as n, sinkLogger as o, hookSink as r, textSink as s, asError as t };
304
+ //# sourceMappingURL=log-CW_g1pWk.js.map
@@ -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,aAAa,SAAS;CAEvB,WAAW;AACZ;;AAGA,MAAM,UAAU;;;;;;;;;;;;;AAchB,SAAgB,SAAS,QAAgC,aAAsB;CAC9E,OAAO,EACN,MAAM,EAAE,OAAO,SAAS,iBAAiB;EACxC,MAAM,OAAO,OAAO;EACpB,MAAM,OAAO,YAAY,KAAK,aAAa,MAAM,cAAc,KAAK,UAAU,OAAO;EAErF,MAAM,UAAU,UAAU,cAAc,WAAW,cAAc,aAAa;EAE9E,MAAM,OAAO,OAAO,UAAU;GAAE;GAAM;GAAO;GAAS,GAAG;EAA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AW;EAEvD,MAAM,WAAW,SAAS,KAAK,aAAa,OAAO;GAAE,GAAG;GAAM,YAAY;EAAK;EAC/E,KAAK,IACJ,oBAAoB,OACjB,WACA;GAAE,GAAG;GAAU,YAAY,iBAAiB,QAAQ;EAAE,CAC1D;CACD,EACD;AACD;;;;;AAMA,SAAgB,WACf,MACA,YAAoD,gBAAgB,EAAE,GAAG,WAAW,IACpE;CAEhB,OAAO;EACN,QAAQ,SAAS,aAAa,CAAC,MAAM;GACpC,KAAK,IAAI;IAAE,OAAO;IAAS;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACvE;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI;IAAE,OAAO;IAAQ;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACtE;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI;IAAE,OAAO;IAAQ;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACtE;EACA,QAAQ,SAAS,aAAa,CAAC,MAAM;GACpC,KAAK,IAAI;IAAE,OAAO;IAAS;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACvE;CACD;AACD;;;;;AAMA,SAAgB,cAAc,MAAe,SAA+C;CAE3F,OAAO,WAAW,OAAO,eAAe;EACvC,MAAM,YAAY,QAAQ,IAAI,WAAW;EACzC,MAAM,EAAE,QAAQ,SAAS,QAAQ;EACjC,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-BUyOW4n2.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-Fo6EodEV.js.map
41
+ //# sourceMappingURL=node-DBwgrye_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-Fo6EodEV.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { requestListener } from \"../response-writer.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** Listens with `node:http`, and writes each response with the node response writer. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });\n\tconst server = createServer(\n\t\t{\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t\t(incoming, outgoing) => {\n\t\t\tvoid listener(incoming, outgoing);\n\t\t},\n\t);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tserver.closeIdleConnections();\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;AAOA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,WAAW,gBAAgB,OAAO,EAAE,qBAAqB,QAAQ,oBAAoB,CAAC;CAC5F,MAAM,SAAS,aACd;EACC,kBAAkB,QAAQ;EAG1B,gBAAgB,QAAQ,gBAAgB;CACzC,IACC,UAAU,aAAa;EACvB,AAAK,SAAS,UAAU,QAAQ;CACjC,CACD;CACA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,OAAO,oBAAoB;GAC5B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,OAAO,qBAAqB;EAC7B,CAAC;CACH;AACD"}
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,5 +1,5 @@
1
- import { n as tcp } from "./tcp-BPeUZaNg.js";
2
- import { n as flushLogs } from "./log-C8LGQ23s.js";
1
+ import { n as tcp } from "./tcp-B8aFGQRB.js";
2
+ import { n as flushLogs } from "./log-CW_g1pWk.js";
3
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";
@@ -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-CA7t-s6D.js.map
334
+ //# sourceMappingURL=node-DiMwdTOC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-CA7t-s6D.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { brotliStream, gzipStream } from \"./compress.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tbrotli: brotliStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\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,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wB,aAAa;IAElD,IAAI,SAAS,MACZ,QAAQ,KAAK;SAEb,OAAO,IAAI,MAAM,oCAAoC,EAAE,OAAO,MAAM,CAAC,CAAC;GAExE,CAAC;EACF,CAAC,GACa;GAGb,MAAM,SAAS;GAIf,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,QAAQ;CACR,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,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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oC,EAAE,OAAO,MAAM,CAAC,CAAC;GAExE,CAAC;EACF,CAAC,GACa;GAGb,MAAM,SAAS;GAIf,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,QAAQ;CACR,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,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-BPeUZaNg.js";
2
- import { n as devServerStage, r as nodeFiles, t as host } from "./node-CA7t-s6D.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
  });