@ngrok/app-server 0.1.0 → 0.2.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 (70) hide show
  1. package/README.md +77 -22
  2. package/dist/build-manifest-8NfD1wnO.js +45 -0
  3. package/dist/build-manifest-8NfD1wnO.js.map +1 -0
  4. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  5. package/dist/bun-BCz6K_Xv.js.map +1 -0
  6. package/dist/cli.js +15 -13
  7. package/dist/cli.js.map +1 -1
  8. package/dist/{deno-BnMfk2n1.js → deno-DNRgzHrk.js} +4 -4
  9. package/dist/deno-DNRgzHrk.js.map +1 -0
  10. package/dist/{entry-2XXp2Ukh.js → entry-BkdUub2S.js} +179 -334
  11. package/dist/entry-BkdUub2S.js.map +1 -0
  12. package/dist/index-oSE-tYRW.d.ts +88 -0
  13. package/dist/index.d.ts +212 -27
  14. package/dist/index.js +26 -14
  15. package/dist/index.js.map +1 -1
  16. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  17. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  18. package/dist/load-entry-C03qqmhr.js +33 -0
  19. package/dist/load-entry-C03qqmhr.js.map +1 -0
  20. package/dist/log-CsjaKM8U.js +59 -0
  21. package/dist/log-CsjaKM8U.js.map +1 -0
  22. package/dist/{node-79my3Uix.js → node-CG7qXuWZ.js} +4 -4
  23. package/dist/node-CG7qXuWZ.js.map +1 -0
  24. package/dist/node-YWPGmzAk.js +215 -0
  25. package/dist/node-YWPGmzAk.js.map +1 -0
  26. package/dist/node-ZMowKZDB.js +3 -0
  27. package/dist/node-vite.d.ts +10 -0
  28. package/dist/node-vite.js +18 -0
  29. package/dist/node-vite.js.map +1 -0
  30. package/dist/node.d.ts +67 -0
  31. package/dist/node.js +4 -0
  32. package/dist/react-router-vite.d.ts +9 -0
  33. package/dist/react-router-vite.js +21 -0
  34. package/dist/react-router-vite.js.map +1 -0
  35. package/dist/react-router.d.ts +11 -24
  36. package/dist/react-router.js +15 -25
  37. package/dist/react-router.js.map +1 -1
  38. package/dist/serve-Cleo8RMO.js +29 -0
  39. package/dist/serve-Cleo8RMO.js.map +1 -0
  40. package/dist/start-CINALHxy.js +230 -0
  41. package/dist/start-CINALHxy.js.map +1 -0
  42. package/dist/tanstack-start-vite.d.ts +11 -0
  43. package/dist/tanstack-start-vite.js +24 -0
  44. package/dist/tanstack-start-vite.js.map +1 -0
  45. package/dist/tanstack-start.d.ts +17 -0
  46. package/dist/tanstack-start.js +50 -0
  47. package/dist/tanstack-start.js.map +1 -0
  48. package/dist/tcp-C-9AmFuM.js +41 -0
  49. package/dist/tcp-C-9AmFuM.js.map +1 -0
  50. package/dist/types-BfCkS7kQ.d.ts +203 -0
  51. package/dist/vite-mYZ2Y69u.js +144 -0
  52. package/dist/vite-mYZ2Y69u.js.map +1 -0
  53. package/dist/vite.d.ts +2 -27
  54. package/dist/vite.js +2 -2
  55. package/package.json +28 -2
  56. package/dist/bun-DCGnDEPn.js.map +0 -1
  57. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  58. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  59. package/dist/deno-BnMfk2n1.js.map +0 -1
  60. package/dist/dev-DCytOhpM.js +0 -132
  61. package/dist/dev-DCytOhpM.js.map +0 -1
  62. package/dist/entry-2XXp2Ukh.js.map +0 -1
  63. package/dist/entry-CIpwaayZ.d.ts +0 -293
  64. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  65. package/dist/node-2wWBMFeO.js +0 -3
  66. package/dist/node-79my3Uix.js.map +0 -1
  67. package/dist/start-kxw_NM4q.js +0 -16
  68. package/dist/start-kxw_NM4q.js.map +0 -1
  69. package/dist/vite-CrNqpoeK.js +0 -102
  70. package/dist/vite-CrNqpoeK.js.map +0 -1
@@ -1,72 +1,11 @@
1
- import { n as capturedHeadersKey, r as readCapturedHeaders } from "./captured-headers-ewL_t3MQ.js";
1
+ import { n as jsonSink, r as requestLogger, t as errorAttributes } from "./log-CsjaKM8U.js";
2
+ import { n as manifestKey, r as readBuildManifest } from "./build-manifest-8NfD1wnO.js";
2
3
  import { Hono } from "hono";
3
4
  import { requestId } from "hono/request-id";
4
- import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
5
- import { open, stat } from "node:fs/promises";
6
- import { join, sep } from "node:path";
7
- import { createHash } from "node:crypto";
8
5
  import { getMimeType } from "hono/utils/mime";
9
6
  import { accepts } from "hono/accepts";
10
- import { constants, createGzip } from "node:zlib";
11
7
 
12
- // src/log.ts
13
- /**
14
- * A log sink that writes one JSON object per line. Each line has `time`,
15
- * `level`, `message`, and the flat attributes, which Datadog reads as its
16
- * standard attributes.
17
- *
18
- * @param write - Where each line goes. Defaults to stdout.
19
- *
20
- * @example
21
- * createServer({ logger: jsonSink() });
22
- * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
23
- */
24
- function jsonSink(write = (line) => {
25
- process.stdout.write(line);
26
- }) {
27
- return { log: (level, message, attributes) => {
28
- write(`${JSON.stringify({
29
- time: (/* @__PURE__ */ new Date()).toISOString(),
30
- level,
31
- message,
32
- ...attributes
33
- })}\n`);
34
- } };
35
- }
36
- /** Flat `error.*` attributes for a thrown value. */
37
- function errorAttributes(error) {
38
- if (error instanceof Error) return {
39
- "error.kind": error.name,
40
- "error.message": error.message,
41
- "error.stack": error.stack
42
- };
43
- return { "error.message": String(error) };
44
- }
45
- /** A logger that writes to `sink`, with the attributes from `base` first on each line. */
46
- function sinkLogger(sink, base = () => ({})) {
47
- const line = (level) => (message, attributes = {}) => {
48
- sink.log(level, message, {
49
- ...base(),
50
- ...attributes
51
- });
52
- };
53
- return {
54
- debug: line("debug"),
55
- info: line("info"),
56
- warn: line("warn"),
57
- error: line("error")
58
- };
59
- }
60
- /** A logger whose lines carry the request's ID, method, and path. */
61
- function requestLogger(sink, context) {
62
- return sinkLogger(sink, () => ({
63
- "http.request_id": context.get("requestId"),
64
- "http.method": context.req.method,
65
- "http.url_details.path": context.req.path
66
- }));
67
- }
68
-
69
- // src/plugins/access-log.ts
8
+ // src/core/plugins/access-log.ts
70
9
  /**
71
10
  * A URL's path and query, with each query value replaced when `redact` is set.
72
11
  *
@@ -75,7 +14,7 @@ function requestLogger(sink, context) {
75
14
  */
76
15
  function loggedUrl(url, { redact }) {
77
16
  if (!redact || url.search === "") return `${url.pathname}${url.search}`;
78
- const query = Array.from(url.searchParams.keys()).map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
17
+ const query = [...url.searchParams.keys()].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
79
18
  return `${url.pathname}?${query}`;
80
19
  }
81
20
  /** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
@@ -172,7 +111,7 @@ function accessLog({ redactQuery = true } = {}) {
172
111
  }
173
112
  }
174
113
 
175
- // src/plugins/request-id.ts
114
+ // src/core/plugins/request-id.ts
176
115
  /**
177
116
  * Gives each request an ID: a valid incoming header (up to 255 word
178
117
  * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
@@ -195,7 +134,9 @@ function requestId$1({ headerName = "X-Request-Id" } = {}) {
195
134
  };
196
135
  }
197
136
 
198
- // src/static-files.ts
137
+ // src/core/static-files.ts
138
+ /** The content types that `mime` lacks and that no framework owns. */
139
+ const CORE_CONTENT_TYPES = { ".md": "text/markdown; charset=utf-8" };
199
140
  /**
200
141
  * Whether a URL path names a dotfile or goes through a dot directory.
201
142
  * `/.well-known/` stays reachable.
@@ -203,18 +144,11 @@ function requestId$1({ headerName = "X-Request-Id" } = {}) {
203
144
  function hasDotSegment(path) {
204
145
  return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
205
146
  }
206
- async function fileStats(path) {
207
- try {
208
- return await stat(path);
209
- } catch {
210
- return;
211
- }
212
- }
213
147
  /**
214
- * Finds the file under `root` that answers a decoded URL path, such as
215
- * Hono's `context.req.path`. A directory answers with its `index.html` and no
216
- * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside
217
- * `root` find nothing.
148
+ * Finds the file in `files` that answers a decoded URL path, such as Hono's
149
+ * `context.req.path`. A directory answers with its `index.html` and no
150
+ * redirect, so a prerendered page keeps its URL. Dotfiles and paths that
151
+ * leave the client build find nothing.
218
152
  *
219
153
  * Each file has one URL, because the headers for a file are keyed by that
220
154
  * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
@@ -222,59 +156,35 @@ async function fileStats(path) {
222
156
  * decode it again.
223
157
  *
224
158
  * @example
225
- * await findStaticFile("/app/build/client", "/components/button");
226
- * // => { path: "/app/build/client/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
159
+ * await findStaticFile(files, "/components/button");
160
+ * // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
227
161
  */
228
- async function findStaticFile(root, path) {
229
- if (path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
230
- const candidate = join(root, path);
231
- if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) return;
232
- const stats = await fileStats(candidate);
233
- if (stats?.isFile()) return {
234
- path: candidate,
235
- size: stats.size,
236
- mtimeMs: stats.mtimeMs
162
+ async function findStaticFile(files, path) {
163
+ if (!path.startsWith("/") || path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
164
+ const info = await files.stat(path);
165
+ if (info?.kind === "file") return {
166
+ path,
167
+ size: info.size,
168
+ mtimeMs: info.mtimeMs
237
169
  };
238
- if (stats?.isDirectory()) {
239
- const index = join(candidate, "index.html");
240
- const indexStats = await fileStats(index);
241
- if (indexStats?.isFile()) return {
170
+ if (info?.kind === "directory") {
171
+ const index = `${path.replace(/\/$/u, "")}/index.html`;
172
+ const indexInfo = await files.stat(index);
173
+ if (indexInfo?.kind === "file") return {
242
174
  path: index,
243
- size: indexStats.size,
244
- mtimeMs: indexStats.mtimeMs
175
+ size: indexInfo.size,
176
+ mtimeMs: indexInfo.mtimeMs
245
177
  };
246
178
  }
247
179
  }
248
- /**
249
- * A file's bytes, one chunk for each pull, so a slow client holds one chunk,
250
- * not the whole file. The handle closes at the end, on an error, or on cancel.
251
- */
252
- function fileStream(handle) {
253
- return new ReadableStream({
254
- async pull(controller) {
255
- try {
256
- const { bytesRead, buffer } = await handle.read({ buffer: /* @__PURE__ */ new Uint8Array(65536) });
257
- if (bytesRead === 0) {
258
- await handle.close();
259
- controller.close();
260
- } else controller.enqueue(buffer.subarray(0, bytesRead));
261
- } catch (error) {
262
- await handle.close();
263
- throw error;
264
- }
265
- },
266
- cancel: () => handle.close()
267
- });
268
- }
269
- /** The content type of a file, with the React Router and markdown types that `mime` lacks. */
270
- function contentType(path) {
271
- if (path.endsWith(".md")) return "text/markdown; charset=utf-8";
272
- if (path.endsWith(".data")) return "text/x-script";
273
- return getMimeType(path) ?? "application/octet-stream";
180
+ /** The content type of a file, by its extension. `contentTypes` win over `mime`. */
181
+ function contentType(path, contentTypes) {
182
+ const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
183
+ return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
274
184
  }
275
185
  /** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
276
186
  function opaqueTag(etag) {
277
- return etag.trim().replace(/^W\//, "");
187
+ return etag.trim().replace(/^W\//u, "");
278
188
  }
279
189
  /** Whether an `If-None-Match` header lists an ETag. */
280
190
  function matchesEtag(ifNoneMatch, etag) {
@@ -284,22 +194,21 @@ function matchesEtag(ifNoneMatch, etag) {
284
194
  }) ?? false;
285
195
  }
286
196
  /** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */
287
- function fileEtag(file, parts) {
197
+ async function fileEtag(file, parts) {
288
198
  const base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;
289
199
  if (parts.length === 0) return `W/"${base}"`;
290
- return `W/"${base}-${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 16)}"`;
200
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\0")));
201
+ return `W/"${base}-${btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16)}"`;
291
202
  }
292
203
  /**
293
204
  * The response for a static file, with a weak ETag from its size,
294
205
  * modification time, and the request's `etagParts`. A matching
295
- * `If-None-Match` gets a 304, and `HEAD` gets the headers only. `headers`
296
- * replace the defaults, so a captured `Content-Type` wins over the one from
297
- * the file name.
206
+ * `If-None-Match` gets a 304, and `HEAD` gets the headers only.
298
207
  */
299
- async function staticResponse(context, file, headers) {
300
- const etag = fileEtag(file, context.get("etagParts") ?? []);
208
+ async function staticResponse(context, { files, file, headers, contentTypes }) {
209
+ const etag = await fileEtag(file, context.get("etagParts") ?? []);
301
210
  const responseHeaders = new Headers({
302
- "Content-Type": contentType(file.path),
211
+ "Content-Type": contentType(file.path, contentTypes),
303
212
  ETag: etag
304
213
  });
305
214
  for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
@@ -310,48 +219,18 @@ async function staticResponse(context, file, headers) {
310
219
  headers: responseHeaders
311
220
  });
312
221
  }
313
- if (context.req.method === "HEAD") {
314
- responseHeaders.set("Content-Length", String(file.size));
315
- return new Response(null, { headers: responseHeaders });
316
- }
317
222
  responseHeaders.set("Content-Length", String(file.size));
318
- return new Response(fileStream(await open(file.path)), { headers: responseHeaders });
223
+ if (context.req.method === "HEAD") return new Response(null, { headers: responseHeaders });
224
+ return new Response(await files.open(file.path), { headers: responseHeaders });
319
225
  }
320
226
 
321
- // src/plugins/static.ts
227
+ // src/core/plugins/static.ts
322
228
  const IMMUTABLE = "public, max-age=31536000, immutable";
323
- /** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */
324
- function viteStage(viteMiddleware) {
325
- return async (context, next) => {
326
- const { incoming, outgoing } = context.env;
327
- if (incoming == null || outgoing == null) return next();
328
- for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
329
- if (await new Promise((resolve, reject) => {
330
- const onFinish = () => {
331
- resolve(true);
332
- };
333
- outgoing.once("finish", onFinish);
334
- viteMiddleware(incoming, outgoing, (error) => {
335
- outgoing.off("finish", onFinish);
336
- if (error == null) resolve(false);
337
- else reject(new Error("Vite middleware failed", { cause: error }));
338
- });
339
- })) {
340
- const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
341
- const length = outgoing.getHeader("Content-Length");
342
- if (length != null) headers.set("Content-Length", String(length));
343
- return new Response(null, {
344
- status: outgoing.statusCode,
345
- headers
346
- });
347
- }
348
- return next();
349
- };
350
- }
351
229
  /**
352
230
  * Serves the hashed files under `/assets/` with a one-year immutable cache.
353
231
  * A missing asset gets a plain 404, not a rendered page. In development,
354
- * Vite serves the source modules, the HMR client, and the CSS here instead.
232
+ * the dev server serves the source modules, the HMR client, and the CSS here
233
+ * instead.
355
234
  *
356
235
  * @example
357
236
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
@@ -362,25 +241,30 @@ function assets() {
362
241
  name: "assets",
363
242
  setup: (info) => {
364
243
  if (info.mode === "development") {
365
- stage = viteStage(info.viteMiddleware);
244
+ stage = info.devServer;
366
245
  return;
367
246
  }
368
- const root = info.clientDirectory;
247
+ const { files, contentTypes } = info;
369
248
  stage = async (context, next) => {
370
249
  const { method, path } = context.req;
371
250
  if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
372
- const file = await findStaticFile(root, path);
251
+ const file = await findStaticFile(files, path);
373
252
  if (file == null) return context.text("Not Found", 404);
374
- return staticResponse(context, file, { "Cache-Control": IMMUTABLE });
253
+ return staticResponse(context, {
254
+ files,
255
+ file,
256
+ headers: { "Cache-Control": IMMUTABLE },
257
+ contentTypes
258
+ });
375
259
  };
376
260
  },
377
- middleware: (context, next) => stage == null ? next() : stage(context, next)
261
+ middleware: async (context, next) => stage == null ? next() : stage(context, next)
378
262
  };
379
263
  }
380
264
  /**
381
265
  * Serves the client build: prerendered pages at their own URL with a 200 and
382
266
  * no trailing-slash redirect, plus every other file in it. Each response gets
383
- * the headers its loader sent at build time (the `serverEntry` Vite plugin
267
+ * the headers its loader sent at build time (the `appServer` Vite plugin
384
268
  * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
385
269
  * with no file goes on to the framework. Off in development.
386
270
  *
@@ -397,104 +281,101 @@ function prerendered(options = {}) {
397
281
  name: "prerendered",
398
282
  setup: async (info) => {
399
283
  if (info.mode === "development") return;
400
- const root = info.clientDirectory;
401
- const captured = await readCapturedHeaders(root);
284
+ const { files, contentTypes, capturedHeaders } = info;
402
285
  const missing = [];
403
- for (const path of info.prerenderedPaths) if (await findStaticFile(root, path) == null) missing.push(path);
286
+ for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
404
287
  if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
405
288
  stage = async (context, next) => {
406
289
  const { method } = context.req;
407
290
  if (method !== "GET" && method !== "HEAD") return next();
408
291
  const path = options.rewrite?.(context.req.path, context) ?? context.req.path;
409
- const file = await findStaticFile(root, path);
292
+ const file = await findStaticFile(files, path);
410
293
  if (file == null) return next();
411
- return staticResponse(context, file, {
412
- ...captured.get(capturedHeadersKey(path)),
413
- ...options.headers?.(path, context)
294
+ return staticResponse(context, {
295
+ files,
296
+ file,
297
+ headers: {
298
+ ...capturedHeaders.get(manifestKey(path)),
299
+ ...options.headers?.(path, context)
300
+ },
301
+ contentTypes
414
302
  });
415
303
  };
416
304
  },
417
- middleware: (context, next) => stage == null ? next() : stage(context, next)
305
+ middleware: async (context, next) => stage == null ? next() : stage(context, next)
418
306
  };
419
307
  }
420
308
 
421
- // src/plugins/streaming-compress.ts
422
- const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/;
423
- /**
424
- * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
425
- * once. It reads the next source chunk only when the consumer pulls, so a slow
426
- * client holds back the source.
427
- */
428
- function gzipStream(source) {
429
- const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
430
- const reader = source.getReader();
431
- return new ReadableStream({
432
- start(controller) {
433
- gzip.on("data", (chunk) => {
434
- controller.enqueue(new Uint8Array(chunk));
435
- });
436
- gzip.on("end", () => {
437
- controller.close();
438
- });
439
- gzip.on("error", (error) => {
440
- controller.error(error);
441
- });
442
- },
443
- async pull() {
444
- try {
445
- let chunk = await reader.read();
446
- while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
447
- if (chunk.done) {
448
- gzip.end();
449
- return;
450
- }
451
- const { value } = chunk;
452
- await new Promise((resolve, reject) => {
453
- gzip.write(value, (error) => {
454
- if (error == null) resolve();
455
- else reject(error);
456
- });
457
- });
458
- } catch (error) {
459
- gzip.destroy();
460
- throw error;
461
- }
462
- },
463
- cancel(reason) {
464
- gzip.destroy();
465
- return reader.cancel(reason);
466
- }
467
- });
468
- }
309
+ // src/core/plugins/streaming-compress.ts
310
+ const COMPRESSIBLE = /^(?:text\/|application\/(?:json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/u;
469
311
  /**
470
312
  * Gzips text responses and flushes after each chunk, so a streamed page shell
471
313
  * or a server-sent event reaches the client at once. `hono/compress` holds a
472
314
  * stream until it ends. Skips a response that is already encoded, a partial
473
- * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.
315
+ * response, and one marked `no-transform`. It sets `Vary: Accept-Encoding` on
316
+ * each response. The host gives the gzip stream. On a host with none, the
317
+ * plugin does nothing.
474
318
  *
475
319
  * @example
476
320
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
477
321
  */
478
322
  function streamingCompress() {
323
+ let gzip;
479
324
  return {
480
325
  name: "streaming-compress",
326
+ setup: (info) => {
327
+ ({gzip} = info);
328
+ },
481
329
  middleware: async (context, next) => {
482
330
  await next();
331
+ if (gzip == null) return;
483
332
  context.header("Vary", "Accept-Encoding", { append: true });
484
333
  const response = context.res;
485
334
  if (response.body == null || context.req.method === "HEAD" || accepts(context, {
486
335
  header: "Accept-Encoding",
487
336
  supports: ["gzip"],
488
337
  default: "identity"
489
- }) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b/.test(response.headers.get("Cache-Control") ?? "") || !COMPRESSIBLE.test(response.headers.get("Content-Type") ?? "")) return;
490
- context.res = new Response(gzipStream(response.body), response);
338
+ }) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b/u.test(response.headers.get("Cache-Control") ?? "") || !COMPRESSIBLE.test(response.headers.get("Content-Type") ?? "")) return;
339
+ context.res = new Response(gzip(response.body), response);
491
340
  context.res.headers.set("Content-Encoding", "gzip");
492
341
  context.res.headers.delete("Content-Length");
493
342
  }
494
343
  };
495
344
  }
496
345
 
497
- // src/shutdown.ts
346
+ // src/core/request-context.ts
347
+ /**
348
+ * Each store that a request ran in. Why a set: two entries in one process can
349
+ * have two hosts, and each request uses the store of its own app.
350
+ */
351
+ const stores = /* @__PURE__ */ new Set();
352
+ /** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
353
+ async function withRequestContext(store, context, work) {
354
+ if (store == null) return work();
355
+ stores.add(store);
356
+ return store.run(context, work);
357
+ }
358
+ /**
359
+ * The request ID and logger of the request that runs. It gives `undefined`
360
+ * outside a server request, such as in a prerender pass, or on a host with no
361
+ * request storage.
362
+ *
363
+ * @example
364
+ * export async function loader() {
365
+ * requestContext()?.logger.info("loading the dashboard");
366
+ * }
367
+ */
368
+ function requestContext() {
369
+ for (const store of stores) {
370
+ const context = store.get();
371
+ if (context != null) return {
372
+ requestId: context.get("requestId"),
373
+ logger: context.var.logger
374
+ };
375
+ }
376
+ }
377
+
378
+ // src/core/shutdown.ts
498
379
  let controller = new AbortController();
499
380
  /**
500
381
  * A signal that aborts when the server starts to shut down. Read it for each
@@ -518,46 +399,7 @@ function abortShutdownSignal() {
518
399
  controller.abort();
519
400
  }
520
401
 
521
- // src/tcp.ts
522
- /** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
523
- const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
524
- /**
525
- * Reads a port number. A value that is not an integer from 0 to 65535 throws,
526
- * so a bad `PORT` stops startup.
527
- *
528
- * @example
529
- * parsePort("8080"); // => 8080
530
- */
531
- function parsePort(value) {
532
- const port = Number(value);
533
- if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
534
- return port;
535
- }
536
- /**
537
- * The default listener: a TCP port, served by the runtime's own HTTP server
538
- * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
539
- * `PORT` and `HOST` when it starts.
540
- *
541
- * @example
542
- * createServer({ listeners: [tcp({ port: 8080 })] });
543
- */
544
- function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
545
- return {
546
- name: "tcp",
547
- start: async (fetch) => {
548
- const options = {
549
- port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
550
- hostname: host ?? (process.env.HOST || void 0),
551
- idleTimeoutMs
552
- };
553
- if ("Bun" in globalThis) return (await import("./bun-DCGnDEPn.js")).listen(fetch, options);
554
- if ("Deno" in globalThis) return (await import("./deno-BnMfk2n1.js")).listen(fetch, options);
555
- return (await import("./node-2wWBMFeO.js")).listen(fetch, options);
556
- }
557
- };
558
- }
559
-
560
- // src/create-server.ts
402
+ // src/core/create-server.ts
561
403
  const appInternals = /* @__PURE__ */ new WeakMap();
562
404
  /**
563
405
  * The default pipeline, in order: `requestId`, `accessLog`,
@@ -616,23 +458,24 @@ async function settlesWithin(work, ms) {
616
458
  * app.get("/livez", (c) => c.text("ok"));
617
459
  * export default app;
618
460
  */
619
- function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners = [tcp()], trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
461
+ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners, trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
620
462
  const app = new Hono();
463
+ let requestStore;
621
464
  if (trustForwardedProto) {
622
465
  const dispatch = app.fetch;
623
- app.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
466
+ app.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
624
467
  }
625
468
  app.use(async (context, next) => {
626
469
  context.set("logger", requestLogger(logger, context));
627
- await next();
470
+ await withRequestContext(requestStore, context, next);
628
471
  if (context.req.method === "HEAD") await context.res.body?.cancel();
629
472
  });
630
- for (const { middleware, etagPart } of plugins) app.use((context, next) => {
473
+ for (const { middleware, etagPart } of plugins) app.use(async (context, next) => {
631
474
  const part = etagPart?.();
632
475
  if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
633
476
  return asError(async () => middleware == null ? next() : middleware(context, next));
634
477
  });
635
- app.use((_, next) => asError(next));
478
+ app.use(async (_, next) => asError(next));
636
479
  app.onError((error, context) => {
637
480
  if ("getResponse" in error && typeof error.getResponse === "function") {
638
481
  const response = error.getResponse();
@@ -646,14 +489,17 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
646
489
  let stoppingPlugins;
647
490
  const internals = {
648
491
  logger,
649
- prepare: (info) => {
492
+ setRequestStore: (store) => {
493
+ requestStore = store;
494
+ },
495
+ prepare: async (info) => {
650
496
  prepared ??= (async () => {
651
497
  for (const plugin of plugins) await plugin.setup?.(info);
652
- app.all("*", (context) => context.env.framework.fetch(context.req.raw, context));
498
+ app.all("*", async (context) => context.env.framework.fetch(context.req.raw, context));
653
499
  })();
654
500
  return prepared;
655
501
  },
656
- listen: async (framework) => {
502
+ listen: async (framework, defaultListeners) => {
657
503
  if (running != null) throw new Error("This app server is already listening.");
658
504
  renewShutdownSignal();
659
505
  let deadlinePassed = false;
@@ -665,11 +511,11 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
665
511
  if (deadlinePassed) await response.body?.cancel();
666
512
  return response;
667
513
  };
668
- const starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));
514
+ const starts = await Promise.allSettled((listeners ?? defaultListeners).map(async (listener) => listener.start(fetch)));
669
515
  const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
670
516
  const failed = starts.find((start) => start.status === "rejected");
671
517
  if (failed != null) {
672
- await Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));
518
+ await Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));
673
519
  throw failed.reason;
674
520
  }
675
521
  const urls = started.map((listener) => listener.url);
@@ -677,15 +523,17 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
677
523
  let stopping;
678
524
  running = {
679
525
  urls,
680
- shutdown: () => {
526
+ shutdown: async () => {
681
527
  stopping ??= (async () => {
682
528
  logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
683
529
  abortShutdownSignal();
684
530
  const deadline = setTimeout(() => {
685
531
  deadlinePassed = true;
686
532
  }, shutdownDeadlineMs);
687
- await Promise.all([internals.stopPlugins(), ...started.map((listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
533
+ const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
688
534
  clearTimeout(deadline);
535
+ const rejected = results.find((result) => result.status === "rejected");
536
+ if (rejected != null) throw rejected.reason;
689
537
  logger.log("info", "stopped", {});
690
538
  })();
691
539
  return stopping;
@@ -693,7 +541,7 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
693
541
  };
694
542
  return running;
695
543
  },
696
- stopPlugins: () => {
544
+ stopPlugins: async () => {
697
545
  stoppingPlugins ??= (async () => {
698
546
  if (!await settlesWithin((async () => {
699
547
  const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
@@ -711,48 +559,61 @@ function serverInternals(app) {
711
559
  return appInternals.get(app);
712
560
  }
713
561
 
714
- // src/entry.ts
562
+ // src/core/entry.ts
715
563
  /** The version of the contract between the CLI and the `appServer` export of a build. */
716
- const ENTRY_PROTOCOL = 1;
564
+ const ENTRY_PROTOCOL = 2;
717
565
  /**
718
- * The `appServer` export of a server build: an app from `createServer` and
719
- * the framework adapter for each mode. The `serverEntry` Vite plugin makes
720
- * this export for a React Router build. Call this for another framework.
566
+ * The `appServer` export of a server build: an app from `createServer`, the
567
+ * host, and the framework adapter for each mode. The `appServer` Vite plugin
568
+ * generates this export. Call this for a build without the plugin.
721
569
  *
722
570
  * @example
723
- * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });
571
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
724
572
  */
725
- function createEntry({ app, framework }) {
573
+ function createEntry({ app, host, framework, clientDirectory }) {
726
574
  const internals = serverInternals(app);
727
575
  if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
576
+ internals.setRequestStore(host.storage);
577
+ const setupInfo = async (runtime) => {
578
+ const directory = clientDirectory ?? runtime.clientDirectory;
579
+ if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
580
+ return {
581
+ files: host.files(directory),
582
+ isDataRequest: runtime.isDataRequest ?? (() => false),
583
+ contentTypes: runtime.contentTypes ?? {},
584
+ gzip: host.gzip,
585
+ logger: internals.logger
586
+ };
587
+ };
728
588
  let development;
729
589
  return {
730
- protocol: 1,
590
+ protocol: 2,
731
591
  app,
732
592
  start: async () => {
733
- const adapter = framework("production");
734
- await internals.prepare({
593
+ const runtime = framework("production");
594
+ const shared = await setupInfo(runtime);
595
+ const { prerendered, headers } = await readBuildManifest(shared.files);
596
+ const info = {
597
+ ...shared,
735
598
  mode: "production",
736
- clientDirectory: adapter.clientDirectory,
737
- prerenderedPaths: adapter.prerenderedPaths,
738
- logger: internals.logger
739
- });
740
- const server = await internals.listen(adapter);
741
- for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
742
- server.shutdown().catch((error) => {
743
- internals.logger.log("error", "shutdown failed", errorAttributes(error));
744
- process.exitCode = 1;
745
- });
746
- });
599
+ prerenderedPaths: runtime.prerenderedPaths ?? prerendered,
600
+ capturedHeaders: new Map(Object.entries(headers))
601
+ };
602
+ await internals.prepare(info);
603
+ const server = await internals.listen(runtime, host.listeners());
604
+ host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
605
+ internals.logger.log("error", "shutdown failed", errorAttributes(error));
606
+ throw error;
607
+ }));
747
608
  },
748
- fetchDev: async (request, bindings, viteMiddleware) => {
609
+ fetchDev: async (request, bindings, devServer) => {
749
610
  development ??= framework("development");
750
611
  await internals.prepare({
612
+ ...await setupInfo(development),
751
613
  mode: "development",
752
- viteMiddleware,
753
- clientDirectory: development.clientDirectory,
754
- prerenderedPaths: development.prerenderedPaths,
755
- logger: internals.logger
614
+ devServer,
615
+ prerenderedPaths: development.prerenderedPaths ?? [],
616
+ capturedHeaders: /* @__PURE__ */ new Map()
756
617
  });
757
618
  return app.fetch(request, {
758
619
  ...bindings,
@@ -763,31 +624,15 @@ function createEntry({ app, framework }) {
763
624
  abortShutdownSignal
764
625
  };
765
626
  }
766
- function isAppServerEntry(value) {
767
- return typeof value === "object" && value != null && "protocol" in value && value.protocol === 1;
768
- }
769
- /** Entries that this copy made for plain React Router builds, by build module. */
770
- const plainEntries = /* @__PURE__ */ new WeakMap();
771
627
  /**
772
- * The entry that runs a server build: its `appServer` export when the
773
- * `serverEntry` Vite plugin made it, else this copy of the package over a
774
- * plain React Router build with the default plugins.
628
+ * Whether a value is an entry of this protocol version.
629
+ *
630
+ * @example
631
+ * isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
775
632
  */
776
- async function loadEntry(build) {
777
- if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
778
- const exported = Reflect.get(build, "appServer");
779
- if (exported != null) {
780
- if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${1}. Install the same version of @ngrok/app-server that the build uses.`);
781
- return exported;
782
- }
783
- const known = plainEntries.get(build);
784
- if (known != null) return known;
785
- const { appServerEntry, isServerBuild } = await import("./react-router.js");
786
- if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
787
- const entry = appServerEntry(build);
788
- plainEntries.set(build, entry);
789
- return entry;
633
+ function isAppServerEntry(value) {
634
+ return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
790
635
  }
791
636
 
792
- export { parsePort as a, streamingCompress as c, requestId$1 as d, accessLog as f, sinkLogger as h, defaultPlugins as i, assets as l, jsonSink as m, loadEntry as n, tcp as o, errorAttributes as p, createServer as r, shutdownSignal as s, createEntry as t, prerendered as u };
793
- //# sourceMappingURL=entry-2XXp2Ukh.js.map
637
+ export { shutdownSignal as a, assets as c, accessLog as d, defaultPlugins as i, prerendered as l, isAppServerEntry as n, requestContext as o, createServer as r, streamingCompress as s, createEntry as t, requestId$1 as u };
638
+ //# sourceMappingURL=entry-BkdUub2S.js.map