@ngrok/app-server 0.4.1 → 0.5.1

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 (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
@@ -0,0 +1,438 @@
1
+ import { a as forbidsTransform, i as copyPath, s as preferredEncoding, t as COPY_ENCODINGS } from "./compression-uJxu0JVb.js";
2
+ import { i as hookedView, t as bodyHooks } from "./header-hook-JfqaTt34.js";
3
+ import { getMimeType } from "hono/utils/mime";
4
+
5
+ // src/core/vary.ts
6
+ /**
7
+ * A `Vary` value with `name` added, or `undefined` when `vary` already covers
8
+ * it. The existing values stay as they are.
9
+ *
10
+ * @example
11
+ * withVary("Accept", "Accept-Encoding"); // => "Accept, Accept-Encoding"
12
+ * withVary("accept-encoding", "Accept-Encoding"); // => undefined
13
+ */
14
+ function withVary(vary, name) {
15
+ if (vary == null || vary.trim() === "") return name;
16
+ const lower = name.toLowerCase();
17
+ for (const part of vary.split(",")) {
18
+ const value = part.trim().toLowerCase();
19
+ if (value === lower || value === "*") return;
20
+ }
21
+ return `${vary}, ${name}`;
22
+ }
23
+
24
+ // src/core/static-files.ts
25
+ /** The content types that `mime` lacks and that no framework owns. */
26
+ const CORE_CONTENT_TYPES = {
27
+ ".atom": "application/atom+xml",
28
+ ".md": "text/markdown; charset=utf-8",
29
+ ".pem": "application/x-pem-file",
30
+ ".rss": "application/rss+xml",
31
+ ".sh": "application/x-sh",
32
+ ".yaml": "text/yaml; charset=utf-8",
33
+ ".yml": "text/yaml; charset=utf-8"
34
+ };
35
+ /**
36
+ * A segment that starts with a dot: one after the first segment, or a first
37
+ * segment that is not `.well-known`. Why an expression: a `split` makes an
38
+ * array and a string for each segment of each request path.
39
+ */
40
+ const DOT_SEGMENT = /(?!^)\/\.|^\/\.(?!well-known(?:\/|$))/u;
41
+ /**
42
+ * Whether a URL path, which starts with `/`, names a dotfile or goes through
43
+ * a dot directory, `.` and `..` included. `/.well-known/` stays reachable.
44
+ *
45
+ * @example
46
+ * hasDotSegment("/assets/.private/key.json"); // => true
47
+ * hasDotSegment("/.well-known/security.txt"); // => false
48
+ */
49
+ function hasDotSegment(path) {
50
+ return DOT_SEGMENT.test(path);
51
+ }
52
+ /**
53
+ * Whether a decoded URL path, such as Hono's `context.req.path`, can name a
54
+ * file of the client build. Dotfiles, paths that leave the client build, and
55
+ * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.
56
+ *
57
+ * @example
58
+ * isFilePath("/docs/button"); // => true
59
+ * isFilePath("/docs/../.env"); // => false
60
+ */
61
+ function isFilePath(path) {
62
+ return path.startsWith("/") && !path.includes("\0") && !path.includes("\\") && !path.includes("//") && !path.endsWith("/index.html") && !hasDotSegment(path);
63
+ }
64
+ /**
65
+ * Finds the file in `files` that answers a decoded URL path, such as Hono's
66
+ * `context.req.path`. A directory answers with its `index.html` and no
67
+ * redirect, so a prerendered page keeps its URL. A path that fails
68
+ * `isFilePath` finds nothing.
69
+ *
70
+ * Each file has one URL, because the headers for a file are keyed by that
71
+ * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
72
+ * the path but keeps an encoded `/` as `%2F`, so this function does not
73
+ * decode it again.
74
+ *
75
+ * @example
76
+ * await findStaticFile(files, "/components/button");
77
+ * // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
78
+ */
79
+ async function findStaticFile(files, path) {
80
+ if (!isFilePath(path)) return;
81
+ const info = await files.stat(path);
82
+ if (info?.kind === "file") return {
83
+ path,
84
+ size: info.size,
85
+ mtimeMs: info.mtimeMs
86
+ };
87
+ if (info?.kind === "directory") {
88
+ const index = `${path.replace(/\/$/u, "")}/index.html`;
89
+ const indexInfo = await files.stat(index);
90
+ if (indexInfo?.kind === "file") return {
91
+ path: index,
92
+ size: indexInfo.size,
93
+ mtimeMs: indexInfo.mtimeMs
94
+ };
95
+ }
96
+ }
97
+ /** The content type of a file, by its extension. `contentTypes` win over `mime`. */
98
+ function contentType(path, contentTypes) {
99
+ const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
100
+ return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
101
+ }
102
+ /** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
103
+ function opaqueTag(etag) {
104
+ return etag.trim().replace(/^W\//u, "");
105
+ }
106
+ /** Whether an `If-None-Match` header lists an ETag. */
107
+ function matchesEtag(ifNoneMatch, etag) {
108
+ return ifNoneMatch?.split(",").some((candidate) => {
109
+ const trimmed = candidate.trim();
110
+ return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
111
+ }) ?? false;
112
+ }
113
+ /** The most lists of `etagParts` whose hash the process keeps. */
114
+ const MAX_PARTS_HASHES = 16;
115
+ /**
116
+ * The hash of each list of `etagParts` that a request had, oldest first. Why
117
+ * more than one: a plugin with an `etagPart` between two static stages gives
118
+ * the requests of each stage their own list, and so does each app of the
119
+ * process. Why a limit: a part can change while the server runs.
120
+ */
121
+ const partsHashes = [];
122
+ /** The kept hash of `parts`, or `undefined` before the first request with them ends its digest. */
123
+ function keptPartsHash(parts) {
124
+ for (const kept of partsHashes) {
125
+ let same = kept.parts.length === parts.length;
126
+ for (let index = 0; same && index < parts.length; index += 1) same = kept.parts[index] === parts[index];
127
+ if (same) return kept.hash;
128
+ }
129
+ }
130
+ /** A short hash of the request's `etagParts`, which the process then keeps. */
131
+ async function partsHash(parts) {
132
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\0")));
133
+ const hash = btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16);
134
+ if (keptPartsHash(parts) == null) {
135
+ if (partsHashes.length === MAX_PARTS_HASHES) partsHashes.shift();
136
+ partsHashes.push({
137
+ parts,
138
+ hash
139
+ });
140
+ }
141
+ return hash;
142
+ }
143
+ /** Where {@link hexTime} splits a number: the low half has 24 bits, which are 6 hexadecimal digits. */
144
+ const HEX_SPLIT = 2 ** 24;
145
+ /**
146
+ * The whole milliseconds of a time in hexadecimal, as
147
+ * `Math.trunc(ms).toString(16)` gives them. Why two halves: V8 converts a
148
+ * whole number under 2^31 in about 20 ns, and a larger one, as the time of a
149
+ * file is, in about 350 ns. The halves of a safe integer are under 2^29.
150
+ */
151
+ function hexTime(ms) {
152
+ const whole = Math.trunc(ms);
153
+ if (whole >= HEX_SPLIT && whole <= Number.MAX_SAFE_INTEGER) {
154
+ const high = Math.floor(whole / HEX_SPLIT);
155
+ const low = whole - high * HEX_SPLIT;
156
+ return `${high.toString(16)}${low.toString(16).padStart(6, "0")}`;
157
+ }
158
+ return whole.toString(16);
159
+ }
160
+ /**
161
+ * A weak ETag from a file's size, its modification time, the hash of the
162
+ * request's `etagParts`, and the encoding of the body. Why the encoding:
163
+ * after a 304, a cache that holds more than one encoding of the file picks
164
+ * the stored response by its ETag (RFC 9111, section 4.3.4).
165
+ */
166
+ function fileEtag(file, hash, encoding) {
167
+ const parts = hash == null ? "" : `-${hash}`;
168
+ const coding = encoding == null ? "" : `-${encoding}`;
169
+ return `W/"${file.size.toString(16)}-${hexTime(file.mtimeMs)}${parts}${coding}"`;
170
+ }
171
+ /**
172
+ * The byte range that a `Range` header asks for in a file of `size` bytes.
173
+ * It gives `"unsatisfiable"` for a range that starts after the end of the
174
+ * file, and `undefined` for a header to ignore: a header that is not valid,
175
+ * or one with more than one range.
176
+ *
177
+ * @example
178
+ * byteRange("bytes=-100", 1000); // => { start: 900, end: 999 }
179
+ */
180
+ function byteRange(header, size) {
181
+ const groups = /^bytes=(?<first>\d*)-(?<last>\d*)$/u.exec(header.trim())?.groups;
182
+ const first = groups?.first ?? "";
183
+ const last = groups?.last ?? "";
184
+ if (first === "" && last === "") return;
185
+ if (first === "") {
186
+ const suffix = Number(last);
187
+ return suffix === 0 || size === 0 ? "unsatisfiable" : {
188
+ start: Math.max(0, size - suffix),
189
+ end: size - 1
190
+ };
191
+ }
192
+ const start = Number(first);
193
+ const end = last === "" ? Number.POSITIVE_INFINITY : Number(last);
194
+ if (end < start) return;
195
+ return start >= size ? "unsatisfiable" : {
196
+ start,
197
+ end: Math.min(end, size - 1)
198
+ };
199
+ }
200
+ /** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */
201
+ const KEPT_FILE_BYTES = 262144;
202
+ const KEPT_TOTAL_BYTES = 33554432;
203
+ /**
204
+ * `files` that keep the bytes of each small file in memory after the first
205
+ * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that
206
+ * do not change while the server runs, such as a `StaticFiles.snapshot()`.
207
+ *
208
+ * @example
209
+ * const files = keptFiles(await nodeFiles("build/client").snapshot());
210
+ */
211
+ function keptFiles(files) {
212
+ const kept = /* @__PURE__ */ new Map();
213
+ let total = 0;
214
+ return {
215
+ stat: files.stat,
216
+ open: async (path, options) => {
217
+ let bytes = kept.get(path);
218
+ const info = bytes == null ? await files.stat(path) : void 0;
219
+ bytes ??= kept.get(path);
220
+ if (bytes == null) {
221
+ if (info?.kind !== "file" || info.size > KEPT_FILE_BYTES || total + info.size > KEPT_TOTAL_BYTES) return files.open(path, options);
222
+ total += info.size;
223
+ bytes = files.open(path, { range: {
224
+ start: 0,
225
+ end: info.size - 1
226
+ } }).then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));
227
+ kept.set(path, bytes);
228
+ bytes.catch(() => {
229
+ kept.delete(path);
230
+ total -= info.size;
231
+ });
232
+ }
233
+ const range = options?.range;
234
+ const chunk = (await bytes).slice(range?.start ?? 0, range == null ? void 0 : range.end + 1);
235
+ return new ReadableStream({ start(controller) {
236
+ controller.enqueue(chunk);
237
+ controller.close();
238
+ } });
239
+ }
240
+ };
241
+ }
242
+ /**
243
+ * `value` as `Headers` keeps it. Why `Headers` only for a value with white
244
+ * space at its ends, or one that is not a string: it removes only the HTTP
245
+ * white space, converts the value, and throws for one that is not valid.
246
+ */
247
+ function headerValue(name, value) {
248
+ return typeof value === "string" && value.trim() === value ? value : new Headers([[name, String(value)]]).get(name) ?? "";
249
+ }
250
+ /**
251
+ * The headers of a file: its content type, then each record of `layers`. A
252
+ * later header replaces an earlier one, and a name matches in any case.
253
+ */
254
+ function fileHead(type, layers) {
255
+ const head = /* @__PURE__ */ new Map([["content-type", type]]);
256
+ for (const layer of layers) for (const [name, value] of Object.entries(layer ?? {})) head.set(name.toLowerCase(), headerValue(name, value));
257
+ return head;
258
+ }
259
+ /**
260
+ * The `Cache-Control` of `head` where the response leaves: after the header
261
+ * hook of each stage that the request passed, when one of them can change
262
+ * the body that the stage picks. The hooks change only a copy of `head`.
263
+ */
264
+ function sentCacheControl(context, head) {
265
+ const hooks = bodyHooks(context);
266
+ if (hooks == null) return head.get("cache-control") ?? null;
267
+ const list = [];
268
+ for (const [name, value] of head) list.push(name, value);
269
+ return hookedView(hooks, list).get("Cache-Control");
270
+ }
271
+ /**
272
+ * The copy of the file at `path` that the request prefers, from the copies
273
+ * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the
274
+ * `Vary` in `head`, also for a request that gets no copy.
275
+ */
276
+ async function preferredCopy(context, { files, path, head }) {
277
+ if (head.has("content-encoding")) return;
278
+ const copies = [];
279
+ for (const encoding of COPY_ENCODINGS) {
280
+ const copy = copyPath(path, encoding);
281
+ const info = await files.stat(copy);
282
+ if (info?.kind === "file") copies.push({
283
+ path: copy,
284
+ size: info.size,
285
+ mtimeMs: info.mtimeMs,
286
+ encoding
287
+ });
288
+ }
289
+ if (copies.length === 0) return;
290
+ const vary = withVary(head.get("vary") ?? null, "Accept-Encoding");
291
+ if (vary != null) head.set("vary", vary);
292
+ if (forbidsTransform(sentCacheControl(context, head))) return;
293
+ const encoding = preferredEncoding(context.req.header("Accept-Encoding"), copies.map((copy) => copy.encoding));
294
+ return copies.find((copy) => copy.encoding === encoding);
295
+ }
296
+ /**
297
+ * All bytes of a file. Why the size as a range: the body then never has more
298
+ * bytes than its `Content-Length`, even when the file grew after `stat`, and
299
+ * a small file reads into a small buffer.
300
+ */
301
+ async function wholeFile(files, file) {
302
+ return file.size === 0 ? null : files.open(file.path, { range: {
303
+ start: 0,
304
+ end: file.size - 1
305
+ } });
306
+ }
307
+ /**
308
+ * A response with the headers of `head`. Why not a `headers` option: the
309
+ * response converts and copies it, which costs about 30% more for six
310
+ * headers than a `set` for each.
311
+ */
312
+ function respond(body, status, head) {
313
+ const response = new Response(body, { status });
314
+ for (const [name, value] of head) response.headers.set(name, value);
315
+ return response;
316
+ }
317
+ /** The requests of {@link rewritesHtmlWithEtagPart}. */
318
+ const changedWithEtagPart = /* @__PURE__ */ new WeakSet();
319
+ /**
320
+ * Tells the static stages that a stage of the request changes the bytes of
321
+ * each HTML page, as `rewritesHtml` does, and that the `etagPart` of its
322
+ * plugin has each value that the change depends on. So the page keeps an
323
+ * ETag, which has that value, and a matching `If-None-Match` gets a 304.
324
+ * Call it before `next()`, in place of `rewritesHtml`.
325
+ *
326
+ * @example
327
+ * rewritesHtmlWithEtagPart(context);
328
+ * await next();
329
+ */
330
+ function rewritesHtmlWithEtagPart(context) {
331
+ changedWithEtagPart.add(context);
332
+ }
333
+ /** Whether a stage of the request changes the bytes of each HTML page. */
334
+ function changesPages(context) {
335
+ return context.get("rewritesHtml") === true || changedWithEtagPart.has(context);
336
+ }
337
+ /**
338
+ * The response for an HTML file that a stage of the request changes: the
339
+ * file as it is on disk, with no compressed copy and no `Content-Length`,
340
+ * because the stage changes the bytes and their length.
341
+ *
342
+ * With `rewritesHtml`, the page gets no ETag and no 304. Why: the server
343
+ * does not know which values the change depends on, so a 304 could keep a
344
+ * page that the stage made with an old value. Without it, the request's
345
+ * `etagParts` have these values (see {@link rewritesHtmlWithEtagPart}).
346
+ */
347
+ async function changedPage(context, { files, file, head }) {
348
+ head.delete("etag");
349
+ head.delete("content-length");
350
+ if (context.get("rewritesHtml") !== true) {
351
+ const parts = context.get("etagParts") ?? [];
352
+ const etag = fileEtag(file, parts.length === 0 ? void 0 : keptPartsHash(parts) ?? await partsHash(parts), void 0);
353
+ head.set("etag", etag);
354
+ if (matchesEtag(context.req.header("If-None-Match"), etag)) {
355
+ head.delete("content-type");
356
+ return respond(null, 304, head);
357
+ }
358
+ }
359
+ return respond(context.req.method === "HEAD" ? null : await wholeFile(files, file), 200, head);
360
+ }
361
+ /**
362
+ * The response for a static file, with a weak ETag from its size,
363
+ * modification time, the request's `etagParts`, and its encoding. A matching
364
+ * `If-None-Match` gets a 304, and `HEAD` gets the headers only.
365
+ *
366
+ * A GET with one `bytes` range gets a 206 with those bytes, and a range
367
+ * after the end of the file gets a 416. A request with `If-Range` gets the
368
+ * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An
369
+ * HTML file gets no ranges.
370
+ *
371
+ * When the build wrote a compressed copy of the file (`.<file>.br` or
372
+ * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets
373
+ * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its
374
+ * `Content-Encoding`, an ETag for that encoding, and no range. A response
375
+ * marked `no-transform`, also by the header hook of an earlier stage, and a
376
+ * response that `headers` encode, never get a copy.
377
+ *
378
+ * When an earlier stage changes the bytes of each HTML page, an HTML file
379
+ * goes out as it is on disk, with no copy and no `Content-Length`. With
380
+ * `rewritesHtml`, it also has no ETag, and an `If-None-Match` gets the full
381
+ * page. With {@link rewritesHtmlWithEtagPart}, it keeps an ETag and its 304.
382
+ *
383
+ * @example
384
+ * const file = await findStaticFile(files, "/llms.txt");
385
+ * if (file != null) {
386
+ * return staticResponse(context, { files, file, headers: [], contentTypes: {} });
387
+ * }
388
+ */
389
+ async function staticResponse(context, { files, file, headers, contentTypes }) {
390
+ const head = fileHead(contentType(file.path, contentTypes), headers);
391
+ const html = head.get("content-type")?.startsWith("text/html") ?? false;
392
+ if (html) {
393
+ context.set("staticDocument", file.path);
394
+ if (changesPages(context)) return changedPage(context, {
395
+ files,
396
+ file,
397
+ head
398
+ });
399
+ }
400
+ const copy = await preferredCopy(context, {
401
+ files,
402
+ path: file.path,
403
+ head
404
+ });
405
+ let etag = head.get("etag");
406
+ if (etag == null) {
407
+ const parts = context.get("etagParts") ?? [];
408
+ etag = fileEtag(file, parts.length === 0 ? void 0 : keptPartsHash(parts) ?? await partsHash(parts), copy?.encoding);
409
+ head.set("etag", etag);
410
+ }
411
+ if (matchesEtag(context.req.header("If-None-Match"), etag)) {
412
+ head.delete("content-type");
413
+ return respond(null, 304, head);
414
+ }
415
+ if (copy != null) {
416
+ head.set("content-encoding", copy.encoding);
417
+ head.set("content-length", String(copy.size));
418
+ return respond(context.req.method === "HEAD" ? null : await wholeFile(files, copy), 200, head);
419
+ }
420
+ if (!html) head.set("accept-ranges", "bytes");
421
+ head.set("content-length", String(file.size));
422
+ if (context.req.method === "HEAD") return respond(null, 200, head);
423
+ const rangeHeader = context.req.header("Range");
424
+ const range = html || rangeHeader == null || context.req.header("If-Range") != null ? void 0 : byteRange(rangeHeader, file.size);
425
+ if (range === "unsatisfiable") {
426
+ head.set("content-range", `bytes */${file.size}`);
427
+ head.delete("content-length");
428
+ return respond(null, 416, head);
429
+ }
430
+ if (range != null) {
431
+ head.set("content-range", `bytes ${range.start}-${range.end}/${file.size}`);
432
+ head.set("content-length", String(range.end - range.start + 1));
433
+ return respond(await files.open(file.path, { range }), 206, head);
434
+ }
435
+ return respond(await wholeFile(files, file), 200, head);
436
+ }
437
+
438
+ export { keptFiles as a, withVary as c, isFilePath as i, findStaticFile as n, rewritesHtmlWithEtagPart as o, hasDotSegment as r, staticResponse as s, contentType as t };
@@ -0,0 +1,30 @@
1
+ /** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */
2
+ type CdnPage = {
3
+ /** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */
4
+ file: string;
5
+ /** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */
6
+ body: Uint8Array;
7
+ /**
8
+ * The response headers for each case of the presence headers. `present`
9
+ * lists the headers that the request has. With no presence headers, there
10
+ * is one case.
11
+ */
12
+ answers: {
13
+ present: readonly string[];
14
+ headers: Readonly<Record<string, string>>;
15
+ }[];
16
+ /**
17
+ * The path of the page's markdown twin. A request whose `Accept` names
18
+ * `text/markdown` must reach the server, which negotiates the answer.
19
+ */
20
+ twin?: string;
21
+ };
22
+ /** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */
23
+ type StaticPage = {
24
+ path: string;
25
+ } & ({
26
+ cdn: CdnPage;
27
+ } | {
28
+ reason: string;
29
+ });
30
+ export { StaticPage as n, CdnPage as t };
@@ -1,4 +1,4 @@
1
- import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
1
+ import { n as FrameworkBuild } from "./index-gzGs53Ue.js";
2
2
  /**
3
3
  * The build side of the TanStack Start adapter. `appServer` uses it when the
4
4
  * Vite config has the TanStack Start plugin, so pass it only to override that.
@@ -8,5 +8,4 @@ import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
8
8
  * @example
9
9
  * appServer({ framework: tanstackStartAdapter() });
10
10
  */
11
- export declare function tanstackStartAdapter(): FrameworkBuild;
12
- //# sourceMappingURL=tanstack-start-vite.d.ts.map
11
+ export declare function tanstackStartAdapter(): FrameworkBuild;
@@ -1,3 +1,3 @@
1
- import { t as tanstackStartAdapter } from "./vite-DyrhyKEr.js";
1
+ import { t as tanstackStartAdapter } from "./vite-DjlHdyTM.js";
2
2
 
3
3
  export { tanstackStartAdapter };
@@ -1,5 +1,5 @@
1
- import { _ as Mode, a as FrameworkRuntime } from "./types-MgFtkNQW.js";
2
- import { t as TrailingSlash } from "./trailing-slash-D2QWKWEu.js";
1
+ import { t as TrailingSlash } from "./trailing-slash-C-yBKCib.js";
2
+ import { a as FrameworkRuntime, g as Mode } from "./types-KsKRDwAv.js";
3
3
  import { AnyRouter, RegisteredRouter } from "@tanstack/react-router";
4
4
  /**
5
5
  * The `trailingSlash` mode of a TanStack router: the app's registered router
@@ -30,5 +30,4 @@ export declare function runtime(serverModule: unknown, { serverFnBase }: {
30
30
  mode: Mode;
31
31
  serverFnBase?: string;
32
32
  }): FrameworkRuntime;
33
- export {};
34
- //# sourceMappingURL=tanstack-start.d.ts.map
33
+ export {};
@@ -1,4 +1,4 @@
1
- import { i as requestContextValues } from "./request-context-Bxdbk5P1.js";
1
+ import { o as requestContextValues } from "./request-context-Cslbrscf.js";
2
2
 
3
3
  // src/tanstack-start/index.ts
4
4
  /** The prefix of Start's server functions when the config sets none. */
@@ -37,5 +37,4 @@ function runtime(serverModule, { serverFnBase = DEFAULT_SERVER_FN_BASE }) {
37
37
  };
38
38
  }
39
39
 
40
- export { runtime };
41
- //# sourceMappingURL=tanstack-start.js.map
40
+ export { runtime };
@@ -0,0 +1,58 @@
1
+ import { n as checkCount, t as MAX_TIMER_MS } from "./check-count-DQl5z_qe.js";
2
+
3
+ // src/node/tcp.ts
4
+ /** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
5
+ const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
6
+ /**
7
+ * The largest `idleTimeoutMs`. Why 1 s under the limit of a timer: Node.js
8
+ * adds 1 s to the value for the timer of each socket.
9
+ */
10
+ const MAX_IDLE_TIMEOUT_MS = MAX_TIMER_MS - 1e3;
11
+ /**
12
+ * Reads a port number. A value that is not an integer from 0 to 65535 throws,
13
+ * so a bad `PORT` stops startup.
14
+ *
15
+ * @example
16
+ * parsePort("8080"); // => 8080
17
+ */
18
+ function parsePort(value) {
19
+ const port = Number(value);
20
+ if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
21
+ return port;
22
+ }
23
+ /**
24
+ * The default listener: a TCP port, served by the runtime's own HTTP server
25
+ * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
26
+ * `PORT` and `HOST` when it starts, unless the options give a port or a host.
27
+ * When it cannot listen on the host from `HOST`, the error names `HOST` and
28
+ * has the error of the runtime as its `cause`. A port in use keeps the error of
29
+ * the runtime.
30
+ * An `idleTimeoutMs` that is not an integer from 0 to 2147482647 throws, so a
31
+ * bad value stops startup.
32
+ *
33
+ * @example
34
+ * createServer({ listeners: [tcp({ idleTimeoutMs: 120_000 })] });
35
+ */
36
+ function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
37
+ checkCount("idleTimeoutMs", idleTimeoutMs, MAX_IDLE_TIMEOUT_MS);
38
+ return { start: async (fetch, { trustForwardedProto = false } = {}) => {
39
+ const envHost = host == null ? process.env.HOST || void 0 : void 0;
40
+ const options = {
41
+ port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
42
+ hostname: host ?? envHost,
43
+ idleTimeoutMs,
44
+ trustForwardedProto
45
+ };
46
+ try {
47
+ if ("Bun" in globalThis) return await (await import("./bun-BCz6K_Xv.js")).listen(fetch, options);
48
+ if ("Deno" in globalThis) return await (await import("./deno-aqhikNMG.js")).listen(fetch, options);
49
+ return await (await import("./node-DQPrMFyc.js")).listen(fetch, options);
50
+ } catch (error) {
51
+ const portInUse = !("Bun" in globalThis) && error instanceof Error && "code" in error && error.code === "EADDRINUSE";
52
+ if (envHost == null || portInUse) throw error;
53
+ throw new Error(`The server cannot listen on host "${envHost}", port ${options.port}. The host is from the HOST environment variable.`, { cause: error });
54
+ }
55
+ } };
56
+ }
57
+
58
+ export { tcp as n, parsePort as t };
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as FrameworkRuntime, y as RequestContext } from "./types-MgFtkNQW.js";
2
- import { t as AppServer } from "./create-server-X2GR-U6t.js";
1
+ import { t as AppServer } from "./create-server-UVsHFQyK.js";
2
+ import { a as FrameworkRuntime, v as RequestContext } from "./types-KsKRDwAv.js";
3
3
  /** Options for {@link createTestServer}. */
4
4
  export type TestServerOptions = {
5
5
  /**
@@ -13,10 +13,13 @@ export type TestServerOptions = {
13
13
  */
14
14
  files?: Readonly<Record<string, string | Uint8Array>>;
15
15
  /**
16
- * The framework's answer to a request that no stage answers.
16
+ * The framework's answer to a request that no stage answers. Give the run
17
+ * side of a framework adapter in its place to also set `isDataRequest`,
18
+ * `contentTypes`, or `prerenderedPaths`. The client build is always
19
+ * `files`: the test server ignores a `clientDirectory`.
17
20
  * @default a 404
18
21
  */
19
- framework?: FrameworkRuntime["fetch"];
22
+ framework?: FrameworkRuntime["fetch"] | FrameworkRuntime;
20
23
  };
21
24
  /** What {@link createTestServer} gives. */
22
25
  export type TestServer = {
@@ -52,5 +55,4 @@ export declare function createTestServer({ app, files, framework }: TestServerOp
52
55
  * @example
53
56
  * const html = await withRequestContext({ cspNonce: "test-nonce" }, () => renderToString(<App />));
54
57
  */
55
- export declare function withRequestContext<Result>(values: Partial<RequestContext>, work: () => Result | Promise<Result>): Promise<Result>;
56
- //# sourceMappingURL=testing.d.ts.map
58
+ export declare function withRequestContext<Result>(values: Partial<RequestContext>, work: () => Result | Promise<Result>): Promise<Result>;
package/dist/testing.js CHANGED
@@ -1,10 +1,9 @@
1
- import { a as requestLogger } from "./log-DQAS5gGT.js";
2
- import { o as withRequestContext$1 } from "./request-context-Bxdbk5P1.js";
3
- import { t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
4
- import { t as createEntry } from "./entry-BoxCqc6w.js";
5
- import { t as host } from "./node-CVVdk2N6.js";
6
- import { n as scriptHashesOf } from "./script-hashes-CU7P9oZU.js";
7
- import { Context } from "hono";
1
+ import { t as BUILD_MANIFEST_FILE } from "./build-manifest-CoBztw_6.js";
2
+ import { t as createEntry } from "./entry-CMhX3yf8.js";
3
+ import { s as sinkLogger } from "./log-DfC9D5_T.js";
4
+ import { c as withRequestContext$1 } from "./request-context-Cslbrscf.js";
5
+ import { t as host } from "./node-DyKDFII0.js";
6
+ import { n as scriptHashesOf } from "./script-hashes-BdvJ0QI_.js";
8
7
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
9
8
  import { dirname, isAbsolute, join, normalize, sep } from "node:path";
10
9
  import { tmpdir } from "node:os";
@@ -32,10 +31,10 @@ async function startEntry(clientDirectory, { app, files, framework }) {
32
31
  app,
33
32
  host,
34
33
  clientDirectory,
35
- framework: () => ({
34
+ framework: () => typeof framework === "function" ? {
36
35
  name: "test",
37
36
  fetch: framework
38
- })
37
+ } : framework
39
38
  });
40
39
  }
41
40
  /**
@@ -102,13 +101,16 @@ async function createTestServer({ app, files = {}, framework = notFound }) {
102
101
  * const html = await withRequestContext({ cspNonce: "test-nonce" }, () => renderToString(<App />));
103
102
  */
104
103
  async function withRequestContext(values, work) {
105
- const context = new Context(new Request("http://localhost/"));
106
- context.set("logger", values.logger ?? requestLogger({ log: () => {} }, context));
107
- if (values.requestId != null) context.set("requestId", values.requestId);
108
- if (values.cspNonce != null) context.set("cspNonce", values.cspNonce);
109
- context.set("clientAddress", values.clientAddress);
110
- return withRequestContext$1(host.storage, context, async () => work());
104
+ const scope = {
105
+ context: void 0,
106
+ values: {
107
+ requestId: values.requestId,
108
+ logger: values.logger ?? sinkLogger({ log: () => {} }),
109
+ cspNonce: values.cspNonce,
110
+ clientAddress: values.clientAddress
111
+ }
112
+ };
113
+ return withRequestContext$1(host.storage, scope, async () => work());
111
114
  }
112
115
 
113
- export { createTestServer, withRequestContext };
114
- //# sourceMappingURL=testing.js.map
116
+ export { createTestServer, withRequestContext };
@@ -1,4 +1,4 @@
1
- import { v as Plugin } from "./types-MgFtkNQW.js";
1
+ import { _ as Plugin } from "./types-KsKRDwAv.js";
2
2
  /**
3
3
  * How a page URL ends:
4
4
  *
@@ -32,5 +32,4 @@ type TrailingSlashOptions = {
32
32
  * createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
33
33
  */
34
34
  declare function trailingSlash({ mode }: TrailingSlashOptions): Plugin;
35
- export { TrailingSlashOptions as n, trailingSlash as r, TrailingSlash as t };
36
- //# sourceMappingURL=trailing-slash-D2QWKWEu.d.ts.map
35
+ export { TrailingSlashOptions as n, trailingSlash as r, TrailingSlash as t };