@ngrok/app-server 0.1.1 → 0.3.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 (105) hide show
  1. package/README.md +659 -70
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/build-manifest-UDNk81Ce.js +63 -0
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  7. package/dist/bun-BCz6K_Xv.js.map +1 -0
  8. package/dist/cli.js +47 -27
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client.d.ts +141 -0
  11. package/dist/client.js +326 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/compression-7_gToa8R.js +97 -0
  14. package/dist/compression-7_gToa8R.js.map +1 -0
  15. package/dist/create-server-iE1-s6Bi.js +1409 -0
  16. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  17. package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-DZ3qo7qF.js +116 -0
  20. package/dist/entry-DZ3qo7qF.js.map +1 -0
  21. package/dist/entry-DmJEqVfd.d.ts +622 -0
  22. package/dist/gzip-Doi4wqjX.js +294 -0
  23. package/dist/gzip-Doi4wqjX.js.map +1 -0
  24. package/dist/header-hook-Vzw9J9BY.js +159 -0
  25. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  26. package/dist/index-Bo5G9LuQ.d.ts +127 -0
  27. package/dist/index.d.ts +110 -95
  28. package/dist/index.js +56 -57
  29. package/dist/index.js.map +1 -1
  30. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  31. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  32. package/dist/load-entry-AfYS_zS9.js +37 -0
  33. package/dist/load-entry-AfYS_zS9.js.map +1 -0
  34. package/dist/log-BP6xXXZl.js +122 -0
  35. package/dist/log-BP6xXXZl.js.map +1 -0
  36. package/dist/node-BFH82eeL.js +333 -0
  37. package/dist/node-BFH82eeL.js.map +1 -0
  38. package/dist/node-tBVQPjQv.js +41 -0
  39. package/dist/node-tBVQPjQv.js.map +1 -0
  40. package/dist/node-vite.d.ts +11 -0
  41. package/dist/node-vite.js +3 -0
  42. package/dist/node.d.ts +86 -0
  43. package/dist/node.js +4 -0
  44. package/dist/react-router-vite.d.ts +10 -0
  45. package/dist/react-router-vite.js +3 -0
  46. package/dist/react-router.d.ts +11 -24
  47. package/dist/react-router.js +21 -30
  48. package/dist/react-router.js.map +1 -1
  49. package/dist/request-context-BtQ87VYb.js +40 -0
  50. package/dist/request-context-BtQ87VYb.js.map +1 -0
  51. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  52. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  53. package/dist/response-writer-B7FoJjEE.js +289 -0
  54. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  55. package/dist/script-hashes-hqUk6kG7.js +53 -0
  56. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  57. package/dist/serve-CDNgThjk.js +29 -0
  58. package/dist/serve-CDNgThjk.js.map +1 -0
  59. package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
  60. package/dist/start-TLIprD74.js.map +1 -0
  61. package/dist/static-files-Beju9riB.js +302 -0
  62. package/dist/static-files-Beju9riB.js.map +1 -0
  63. package/dist/tanstack-start-vite.d.ts +12 -0
  64. package/dist/tanstack-start-vite.js +3 -0
  65. package/dist/tanstack-start.d.ts +34 -0
  66. package/dist/tanstack-start.js +41 -0
  67. package/dist/tanstack-start.js.map +1 -0
  68. package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
  69. package/dist/tcp-Dd1Mt6sN.js.map +1 -0
  70. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  71. package/dist/types-DLYxYS6M.d.ts +392 -0
  72. package/dist/vercel-vite.d.ts +35 -0
  73. package/dist/vercel-vite.js +142 -0
  74. package/dist/vercel-vite.js.map +1 -0
  75. package/dist/vercel.d.ts +35 -0
  76. package/dist/vercel.js +89 -0
  77. package/dist/vercel.js.map +1 -0
  78. package/dist/vite-B-GfswoH.js +22 -0
  79. package/dist/vite-B-GfswoH.js.map +1 -0
  80. package/dist/vite-D4hfj3ph.js +19 -0
  81. package/dist/vite-D4hfj3ph.js.map +1 -0
  82. package/dist/vite-DyrhyKEr.js +25 -0
  83. package/dist/vite-DyrhyKEr.js.map +1 -0
  84. package/dist/vite-iioAoxSt.js +752 -0
  85. package/dist/vite-iioAoxSt.js.map +1 -0
  86. package/dist/vite.d.ts +2 -27
  87. package/dist/vite.js +2 -2
  88. package/package.json +50 -4
  89. package/dist/bun-DCGnDEPn.js.map +0 -1
  90. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  91. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  92. package/dist/deno-BnMfk2n1.js.map +0 -1
  93. package/dist/entry-CIpwaayZ.d.ts +0 -293
  94. package/dist/entry-ChjmFwX5.js +0 -755
  95. package/dist/entry-ChjmFwX5.js.map +0 -1
  96. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  97. package/dist/node-2wWBMFeO.js +0 -3
  98. package/dist/node-79my3Uix.js +0 -58
  99. package/dist/node-79my3Uix.js.map +0 -1
  100. package/dist/serve-ByeedcRB.js +0 -16
  101. package/dist/serve-ByeedcRB.js.map +0 -1
  102. package/dist/start-BVMb8Pyt.js.map +0 -1
  103. package/dist/tcp-Dau_IONd.js.map +0 -1
  104. package/dist/vite-CrNqpoeK.js +0 -102
  105. package/dist/vite-CrNqpoeK.js.map +0 -1
@@ -1,755 +0,0 @@
1
- import { n as tcp } from "./tcp-Dau_IONd.js";
2
- import { n as capturedHeadersKey, r as readCapturedHeaders } from "./captured-headers-ewL_t3MQ.js";
3
- import { Hono } from "hono";
4
- import { requestId } from "hono/request-id";
5
- import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
6
- import { open, stat } from "node:fs/promises";
7
- import { join, sep } from "node:path";
8
- import { createHash } from "node:crypto";
9
- import { getMimeType } from "hono/utils/mime";
10
- import { accepts } from "hono/accepts";
11
- import { constants, createGzip } from "node:zlib";
12
-
13
- // src/log.ts
14
- /**
15
- * A log sink that writes one JSON object per line. Each line has `time`,
16
- * `level`, `message`, and the flat attributes, which Datadog reads as its
17
- * standard attributes.
18
- *
19
- * @param write - Where each line goes. Defaults to stdout.
20
- *
21
- * @example
22
- * createServer({ logger: jsonSink() });
23
- * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
24
- */
25
- function jsonSink(write = (line) => {
26
- process.stdout.write(line);
27
- }) {
28
- return { log: (level, message, attributes) => {
29
- write(`${JSON.stringify({
30
- time: (/* @__PURE__ */ new Date()).toISOString(),
31
- level,
32
- message,
33
- ...attributes
34
- })}\n`);
35
- } };
36
- }
37
- /** Flat `error.*` attributes for a thrown value. */
38
- function errorAttributes(error) {
39
- if (error instanceof Error) return {
40
- "error.kind": error.name,
41
- "error.message": error.message,
42
- "error.stack": error.stack
43
- };
44
- return { "error.message": String(error) };
45
- }
46
- /** A logger that writes to `sink`, with the attributes from `base` first on each line. */
47
- function sinkLogger(sink, base = () => ({})) {
48
- const line = (level) => (message, attributes = {}) => {
49
- sink.log(level, message, {
50
- ...base(),
51
- ...attributes
52
- });
53
- };
54
- return {
55
- debug: line("debug"),
56
- info: line("info"),
57
- warn: line("warn"),
58
- error: line("error")
59
- };
60
- }
61
- /** A logger whose lines carry the request's ID, method, and path. */
62
- function requestLogger(sink, context) {
63
- return sinkLogger(sink, () => ({
64
- "http.request_id": context.get("requestId"),
65
- "http.method": context.req.method,
66
- "http.url_details.path": context.req.path
67
- }));
68
- }
69
-
70
- // src/plugins/access-log.ts
71
- /**
72
- * A URL's path and query, with each query value replaced when `redact` is set.
73
- *
74
- * @example
75
- * loggedUrl(new URL("https://example.com/verify?code=123"), { redact: true }); // => "/verify?code=REDACTED"
76
- */
77
- function loggedUrl(url, { redact }) {
78
- if (!redact || url.search === "") return `${url.pathname}${url.search}`;
79
- const query = Array.from(url.searchParams.keys()).map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
80
- return `${url.pathname}?${query}`;
81
- }
82
- /** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
83
- function loggedReferer(referer, { redact }) {
84
- if (referer == null || !redact) return referer;
85
- const url = URL.parse(referer);
86
- return url == null ? void 0 : `${url.origin}${loggedUrl(url, { redact })}`;
87
- }
88
- /**
89
- * One log line per request, static hits included, with Datadog standard
90
- * attribute names. The line goes out when the body ends or the client
91
- * disconnects, so a streamed response logs its full duration and size.
92
- *
93
- * @example
94
- * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
95
- * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
96
- */
97
- function accessLog({ redactQuery = true } = {}) {
98
- return {
99
- name: "access-log",
100
- middleware: async (context, next) => {
101
- const started = performance.now();
102
- await next();
103
- const write = ({ bytes, aborted }) => {
104
- context.var.logger.info("request", lineAttributes(context, {
105
- bytes,
106
- aborted,
107
- started
108
- }));
109
- };
110
- const response = context.res;
111
- if (context.req.method === "HEAD") {
112
- write({
113
- bytes: 0,
114
- aborted: false
115
- });
116
- return;
117
- }
118
- if (response.body == null) {
119
- write({
120
- bytes: Number(response.headers.get("Content-Length") ?? 0),
121
- aborted: false
122
- });
123
- return;
124
- }
125
- const reader = response.body.getReader();
126
- let bytes = 0;
127
- const counted = new ReadableStream({
128
- async pull(controller) {
129
- let result;
130
- try {
131
- result = await reader.read();
132
- } catch (error) {
133
- write({
134
- bytes,
135
- aborted: true
136
- });
137
- throw error;
138
- }
139
- const { done, value } = result;
140
- if (done) {
141
- controller.close();
142
- write({
143
- bytes,
144
- aborted: false
145
- });
146
- return;
147
- }
148
- bytes += value.byteLength;
149
- controller.enqueue(value);
150
- },
151
- async cancel(reason) {
152
- write({
153
- bytes,
154
- aborted: true
155
- });
156
- await reader.cancel(reason);
157
- }
158
- });
159
- context.res = new Response(counted, response);
160
- }
161
- };
162
- function lineAttributes(context, { bytes, aborted, started }) {
163
- return {
164
- "http.url": loggedUrl(new URL(context.req.url), { redact: redactQuery }),
165
- "http.status_code": context.res.status,
166
- "http.useragent": context.req.header("User-Agent"),
167
- "http.referer": loggedReferer(context.req.header("Referer"), { redact: redactQuery }),
168
- "network.client.ip": context.env.remoteAddress,
169
- "network.bytes_written": bytes,
170
- duration: Math.round((performance.now() - started) * 1e6),
171
- ...aborted ? { "http.client_aborted": true } : {}
172
- };
173
- }
174
- }
175
-
176
- // src/plugins/request-id.ts
177
- /**
178
- * Gives each request an ID: a valid incoming header (up to 255 word
179
- * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
180
- * every log line, and into the framework's context.
181
- *
182
- * @example
183
- * const app = createServer({ plugins: [requestId()] });
184
- * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
185
- * response.headers.get("X-Request-Id"); // => "abc-123"
186
- */
187
- function requestId$1({ headerName = "X-Request-Id" } = {}) {
188
- const assign = requestId({ headerName });
189
- return {
190
- name: "request-id",
191
- middleware: async (context, next) => {
192
- await assign(context, next);
193
- const id = context.get("requestId");
194
- if (id != null) context.header(headerName, id);
195
- }
196
- };
197
- }
198
-
199
- // src/static-files.ts
200
- /**
201
- * Whether a URL path names a dotfile or goes through a dot directory.
202
- * `/.well-known/` stays reachable.
203
- */
204
- function hasDotSegment(path) {
205
- return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
206
- }
207
- async function fileStats(path) {
208
- try {
209
- return await stat(path);
210
- } catch {
211
- return;
212
- }
213
- }
214
- /**
215
- * Finds the file under `root` that answers a decoded URL path, such as
216
- * Hono's `context.req.path`. A directory answers with its `index.html` and no
217
- * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside
218
- * `root` find nothing.
219
- *
220
- * Each file has one URL, because the headers for a file are keyed by that
221
- * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
222
- * the path but keeps an encoded `/` as `%2F`, so this function does not
223
- * decode it again.
224
- *
225
- * @example
226
- * await findStaticFile("/app/build/client", "/components/button");
227
- * // => { path: "/app/build/client/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
228
- */
229
- async function findStaticFile(root, path) {
230
- if (path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
231
- const candidate = join(root, path);
232
- if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) return;
233
- const stats = await fileStats(candidate);
234
- if (stats?.isFile()) return {
235
- path: candidate,
236
- size: stats.size,
237
- mtimeMs: stats.mtimeMs
238
- };
239
- if (stats?.isDirectory()) {
240
- const index = join(candidate, "index.html");
241
- const indexStats = await fileStats(index);
242
- if (indexStats?.isFile()) return {
243
- path: index,
244
- size: indexStats.size,
245
- mtimeMs: indexStats.mtimeMs
246
- };
247
- }
248
- }
249
- /**
250
- * A file's bytes, one chunk for each pull, so a slow client holds one chunk,
251
- * not the whole file. The handle closes at the end, on an error, or on cancel.
252
- */
253
- function fileStream(handle) {
254
- return new ReadableStream({
255
- async pull(controller) {
256
- try {
257
- const { bytesRead, buffer } = await handle.read({ buffer: /* @__PURE__ */ new Uint8Array(65536) });
258
- if (bytesRead === 0) {
259
- await handle.close();
260
- controller.close();
261
- } else controller.enqueue(buffer.subarray(0, bytesRead));
262
- } catch (error) {
263
- await handle.close();
264
- throw error;
265
- }
266
- },
267
- cancel: () => handle.close()
268
- });
269
- }
270
- /** The content type of a file, with the React Router and markdown types that `mime` lacks. */
271
- function contentType(path) {
272
- if (path.endsWith(".md")) return "text/markdown; charset=utf-8";
273
- if (path.endsWith(".data")) return "text/x-script";
274
- return getMimeType(path) ?? "application/octet-stream";
275
- }
276
- /** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
277
- function opaqueTag(etag) {
278
- return etag.trim().replace(/^W\//, "");
279
- }
280
- /** Whether an `If-None-Match` header lists an ETag. */
281
- function matchesEtag(ifNoneMatch, etag) {
282
- return ifNoneMatch?.split(",").some((candidate) => {
283
- const trimmed = candidate.trim();
284
- return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
285
- }) ?? false;
286
- }
287
- /** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */
288
- function fileEtag(file, parts) {
289
- const base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;
290
- if (parts.length === 0) return `W/"${base}"`;
291
- return `W/"${base}-${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 16)}"`;
292
- }
293
- /**
294
- * The response for a static file, with a weak ETag from its size,
295
- * modification time, and the request's `etagParts`. A matching
296
- * `If-None-Match` gets a 304, and `HEAD` gets the headers only. `headers`
297
- * replace the defaults, so a captured `Content-Type` wins over the one from
298
- * the file name.
299
- */
300
- async function staticResponse(context, file, headers) {
301
- const etag = fileEtag(file, context.get("etagParts") ?? []);
302
- const responseHeaders = new Headers({
303
- "Content-Type": contentType(file.path),
304
- ETag: etag
305
- });
306
- for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
307
- if (matchesEtag(context.req.header("If-None-Match"), responseHeaders.get("ETag") ?? etag)) {
308
- responseHeaders.delete("Content-Type");
309
- return new Response(null, {
310
- status: 304,
311
- headers: responseHeaders
312
- });
313
- }
314
- if (context.req.method === "HEAD") {
315
- responseHeaders.set("Content-Length", String(file.size));
316
- return new Response(null, { headers: responseHeaders });
317
- }
318
- responseHeaders.set("Content-Length", String(file.size));
319
- return new Response(fileStream(await open(file.path)), { headers: responseHeaders });
320
- }
321
-
322
- // src/plugins/static.ts
323
- const IMMUTABLE = "public, max-age=31536000, immutable";
324
- /** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */
325
- function viteStage(viteMiddleware) {
326
- return async (context, next) => {
327
- const { incoming, outgoing } = context.env;
328
- if (incoming == null || outgoing == null) return next();
329
- for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
330
- if (await new Promise((resolve, reject) => {
331
- const onFinish = () => {
332
- resolve(true);
333
- };
334
- outgoing.once("finish", onFinish);
335
- viteMiddleware(incoming, outgoing, (error) => {
336
- outgoing.off("finish", onFinish);
337
- if (error == null) resolve(false);
338
- else reject(new Error("Vite middleware failed", { cause: error }));
339
- });
340
- })) {
341
- const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
342
- const length = outgoing.getHeader("Content-Length");
343
- if (length != null) headers.set("Content-Length", String(length));
344
- return new Response(null, {
345
- status: outgoing.statusCode,
346
- headers
347
- });
348
- }
349
- return next();
350
- };
351
- }
352
- /**
353
- * Serves the hashed files under `/assets/` with a one-year immutable cache.
354
- * A missing asset gets a plain 404, not a rendered page. In development,
355
- * Vite serves the source modules, the HMR client, and the CSS here instead.
356
- *
357
- * @example
358
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
359
- */
360
- function assets() {
361
- let stage;
362
- return {
363
- name: "assets",
364
- setup: (info) => {
365
- if (info.mode === "development") {
366
- stage = viteStage(info.viteMiddleware);
367
- return;
368
- }
369
- const root = info.clientDirectory;
370
- stage = async (context, next) => {
371
- const { method, path } = context.req;
372
- if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
373
- const file = await findStaticFile(root, path);
374
- if (file == null) return context.text("Not Found", 404);
375
- return staticResponse(context, file, { "Cache-Control": IMMUTABLE });
376
- };
377
- },
378
- middleware: (context, next) => stage == null ? next() : stage(context, next)
379
- };
380
- }
381
- /**
382
- * Serves the client build: prerendered pages at their own URL with a 200 and
383
- * no trailing-slash redirect, plus every other file in it. Each response gets
384
- * the headers its loader sent at build time (the `serverEntry` Vite plugin
385
- * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
386
- * with no file goes on to the framework. Off in development.
387
- *
388
- * At startup, it warns about each prerendered path that has no file.
389
- *
390
- * @example
391
- * prerendered({
392
- * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
393
- * });
394
- */
395
- function prerendered(options = {}) {
396
- let stage;
397
- return {
398
- name: "prerendered",
399
- setup: async (info) => {
400
- if (info.mode === "development") return;
401
- const root = info.clientDirectory;
402
- const captured = await readCapturedHeaders(root);
403
- const missing = [];
404
- for (const path of info.prerenderedPaths) if (await findStaticFile(root, path) == null) missing.push(path);
405
- if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
406
- stage = async (context, next) => {
407
- const { method } = context.req;
408
- if (method !== "GET" && method !== "HEAD") return next();
409
- const path = options.rewrite?.(context.req.path, context) ?? context.req.path;
410
- const file = await findStaticFile(root, path);
411
- if (file == null) return next();
412
- return staticResponse(context, file, {
413
- ...captured.get(capturedHeadersKey(path)),
414
- ...options.headers?.(path, context)
415
- });
416
- };
417
- },
418
- middleware: (context, next) => stage == null ? next() : stage(context, next)
419
- };
420
- }
421
-
422
- // src/plugins/streaming-compress.ts
423
- const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/;
424
- /**
425
- * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
426
- * once. It reads the next source chunk only when the consumer pulls, so a slow
427
- * client holds back the source.
428
- */
429
- function gzipStream(source) {
430
- const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
431
- const reader = source.getReader();
432
- return new ReadableStream({
433
- start(controller) {
434
- gzip.on("data", (chunk) => {
435
- controller.enqueue(new Uint8Array(chunk));
436
- });
437
- gzip.on("end", () => {
438
- controller.close();
439
- });
440
- gzip.on("error", (error) => {
441
- controller.error(error);
442
- });
443
- },
444
- async pull() {
445
- try {
446
- let chunk = await reader.read();
447
- while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
448
- if (chunk.done) {
449
- gzip.end();
450
- return;
451
- }
452
- const { value } = chunk;
453
- await new Promise((resolve, reject) => {
454
- gzip.write(value, (error) => {
455
- if (error == null) resolve();
456
- else reject(error);
457
- });
458
- });
459
- } catch (error) {
460
- gzip.destroy();
461
- throw error;
462
- }
463
- },
464
- cancel(reason) {
465
- gzip.destroy();
466
- return reader.cancel(reason);
467
- }
468
- });
469
- }
470
- /**
471
- * Gzips text responses and flushes after each chunk, so a streamed page shell
472
- * or a server-sent event reaches the client at once. `hono/compress` holds a
473
- * stream until it ends. Skips a response that is already encoded, a partial
474
- * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.
475
- *
476
- * @example
477
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
478
- */
479
- function streamingCompress() {
480
- return {
481
- name: "streaming-compress",
482
- middleware: async (context, next) => {
483
- await next();
484
- context.header("Vary", "Accept-Encoding", { append: true });
485
- const response = context.res;
486
- if (response.body == null || context.req.method === "HEAD" || accepts(context, {
487
- header: "Accept-Encoding",
488
- supports: ["gzip"],
489
- default: "identity"
490
- }) !== "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;
491
- context.res = new Response(gzipStream(response.body), response);
492
- context.res.headers.set("Content-Encoding", "gzip");
493
- context.res.headers.delete("Content-Length");
494
- }
495
- };
496
- }
497
-
498
- // src/shutdown.ts
499
- let controller = new AbortController();
500
- /**
501
- * A signal that aborts when the server starts to shut down. Read it for each
502
- * request: each start of a server makes a new one. A handler that
503
- * holds a response open, such as an event stream, stops on it so that the
504
- * drain does not wait for the deadline.
505
- *
506
- * @example
507
- * const timer = setInterval(sendUpdate, 1_000);
508
- * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
509
- */
510
- function shutdownSignal() {
511
- return controller.signal;
512
- }
513
- /** Replaces {@link shutdownSignal} with a new one that has not aborted. */
514
- function renewShutdownSignal() {
515
- controller = new AbortController();
516
- }
517
- /** Aborts {@link shutdownSignal}. */
518
- function abortShutdownSignal() {
519
- controller.abort();
520
- }
521
-
522
- // src/create-server.ts
523
- const appInternals = /* @__PURE__ */ new WeakMap();
524
- /**
525
- * The default pipeline, in order: `requestId`, `accessLog`,
526
- * `streamingCompress`, the `beforeStatic` plugins, `assets`, and
527
- * `prerendered`. It is a plain array, so an app can filter it or splice into it.
528
- *
529
- * @example
530
- * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });
531
- */
532
- function defaultPlugins(options = {}) {
533
- return [
534
- requestId$1(options.requestId),
535
- accessLog(options.accessLog),
536
- streamingCompress(),
537
- ...options.beforeStatic ?? [],
538
- assets(),
539
- prerendered(options.prerendered)
540
- ];
541
- }
542
- /** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */
543
- function withForwardedProto(request) {
544
- const proto = request.headers.get("X-Forwarded-Proto");
545
- if (proto !== "http" && proto !== "https") return request;
546
- const url = new URL(request.url);
547
- url.protocol = `${proto}:`;
548
- return new Request(url, request);
549
- }
550
- /**
551
- * Runs `step`, and rethrows a thrown value that is not an `Error` as one.
552
- * Hono sends only an `Error` to `onError`, and rethrows any other value.
553
- */
554
- async function asError(step) {
555
- try {
556
- return await step();
557
- } catch (error) {
558
- throw error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
559
- }
560
- }
561
- /** Whether `work` settles before `ms` pass. */
562
- async function settlesWithin(work, ms) {
563
- let timer;
564
- const settled = await Promise.race([work.then(() => true), new Promise((resolve) => {
565
- timer = setTimeout(resolve, ms, false);
566
- })]);
567
- clearTimeout(timer);
568
- return settled;
569
- }
570
- /**
571
- * Builds an app server: a Hono app that runs the plugins in list order, then
572
- * the app's own routes, then the framework. It does not listen; the
573
- * `app-server` CLI starts it.
574
- *
575
- * @example
576
- * // server.ts
577
- * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });
578
- * app.get("/livez", (c) => c.text("ok"));
579
- * export default app;
580
- */
581
- function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners = [tcp()], trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
582
- const app = new Hono();
583
- if (trustForwardedProto) {
584
- const dispatch = app.fetch;
585
- app.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
586
- }
587
- app.use(async (context, next) => {
588
- context.set("logger", requestLogger(logger, context));
589
- await next();
590
- if (context.req.method === "HEAD") await context.res.body?.cancel();
591
- });
592
- for (const { middleware, etagPart } of plugins) app.use((context, next) => {
593
- const part = etagPart?.();
594
- if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
595
- return asError(async () => middleware == null ? next() : middleware(context, next));
596
- });
597
- app.use((_, next) => asError(next));
598
- app.onError((error, context) => {
599
- if ("getResponse" in error && typeof error.getResponse === "function") {
600
- const response = error.getResponse();
601
- if (response instanceof Response) return response;
602
- }
603
- context.var.logger.error("unhandled error", errorAttributes(error));
604
- return context.text("Internal Server Error", 500);
605
- });
606
- let prepared;
607
- let running;
608
- let stoppingPlugins;
609
- const internals = {
610
- logger,
611
- prepare: (info) => {
612
- prepared ??= (async () => {
613
- for (const plugin of plugins) await plugin.setup?.(info);
614
- app.all("*", (context) => context.env.framework.fetch(context.req.raw, context));
615
- })();
616
- return prepared;
617
- },
618
- listen: async (framework) => {
619
- if (running != null) throw new Error("This app server is already listening.");
620
- renewShutdownSignal();
621
- let deadlinePassed = false;
622
- const fetch = async (request, bindings) => {
623
- const response = await app.fetch(request, {
624
- ...bindings,
625
- framework
626
- });
627
- if (deadlinePassed) await response.body?.cancel();
628
- return response;
629
- };
630
- const starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));
631
- const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
632
- const failed = starts.find((start) => start.status === "rejected");
633
- if (failed != null) {
634
- await Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));
635
- throw failed.reason;
636
- }
637
- const urls = started.map((listener) => listener.url);
638
- logger.log("info", "listening", { "app_server.urls": urls });
639
- let stopping;
640
- running = {
641
- urls,
642
- shutdown: () => {
643
- stopping ??= (async () => {
644
- logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
645
- abortShutdownSignal();
646
- const deadline = setTimeout(() => {
647
- deadlinePassed = true;
648
- }, shutdownDeadlineMs);
649
- await Promise.all([internals.stopPlugins(), ...started.map((listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
650
- clearTimeout(deadline);
651
- logger.log("info", "stopped", {});
652
- })();
653
- return stopping;
654
- }
655
- };
656
- return running;
657
- },
658
- stopPlugins: () => {
659
- stoppingPlugins ??= (async () => {
660
- if (!await settlesWithin((async () => {
661
- const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
662
- for (const result of results) if (result.status === "rejected") logger.log("error", "plugin shutdown failed", errorAttributes(result.reason));
663
- })(), shutdownDeadlineMs)) logger.log("warn", "plugin shutdown passed the deadline", { "app_server.deadline_ms": shutdownDeadlineMs });
664
- })();
665
- return stoppingPlugins;
666
- }
667
- };
668
- appInternals.set(app, internals);
669
- return app;
670
- }
671
- /** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */
672
- function serverInternals(app) {
673
- return appInternals.get(app);
674
- }
675
-
676
- // src/entry.ts
677
- /** The version of the contract between the CLI and the `appServer` export of a build. */
678
- const ENTRY_PROTOCOL = 1;
679
- /**
680
- * The `appServer` export of a server build: an app from `createServer` and
681
- * the framework adapter for each mode. The `serverEntry` Vite plugin makes
682
- * this export for a React Router build. Call this for another framework.
683
- *
684
- * @example
685
- * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });
686
- */
687
- function createEntry({ app, framework }) {
688
- const internals = serverInternals(app);
689
- if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
690
- let development;
691
- return {
692
- protocol: 1,
693
- app,
694
- start: async () => {
695
- const adapter = framework("production");
696
- await internals.prepare({
697
- mode: "production",
698
- clientDirectory: adapter.clientDirectory,
699
- prerenderedPaths: adapter.prerenderedPaths,
700
- logger: internals.logger
701
- });
702
- const server = await internals.listen(adapter);
703
- for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
704
- server.shutdown().catch((error) => {
705
- internals.logger.log("error", "shutdown failed", errorAttributes(error));
706
- process.exitCode = 1;
707
- });
708
- });
709
- },
710
- fetchDev: async (request, bindings, viteMiddleware) => {
711
- development ??= framework("development");
712
- await internals.prepare({
713
- mode: "development",
714
- viteMiddleware,
715
- clientDirectory: development.clientDirectory,
716
- prerenderedPaths: development.prerenderedPaths,
717
- logger: internals.logger
718
- });
719
- return app.fetch(request, {
720
- ...bindings,
721
- framework: development
722
- });
723
- },
724
- stopPlugins: internals.stopPlugins,
725
- abortShutdownSignal
726
- };
727
- }
728
- function isAppServerEntry(value) {
729
- return typeof value === "object" && value != null && "protocol" in value && value.protocol === 1;
730
- }
731
- /** Entries that this copy made for plain React Router builds, by build module. */
732
- const plainEntries = /* @__PURE__ */ new WeakMap();
733
- /**
734
- * The entry that runs a server build: its `appServer` export when the
735
- * `serverEntry` Vite plugin made it, else this copy of the package over a
736
- * plain React Router build with the default plugins.
737
- */
738
- async function loadEntry(build) {
739
- if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
740
- const exported = Reflect.get(build, "appServer");
741
- if (exported != null) {
742
- 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.`);
743
- return exported;
744
- }
745
- const known = plainEntries.get(build);
746
- if (known != null) return known;
747
- const { appServerEntry, isServerBuild } = await import("./react-router.js");
748
- if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
749
- const entry = appServerEntry(build);
750
- plainEntries.set(build, entry);
751
- return entry;
752
- }
753
-
754
- export { shutdownSignal as a, prerendered as c, errorAttributes as d, jsonSink as f, defaultPlugins as i, requestId$1 as l, loadEntry as n, streamingCompress as o, sinkLogger as p, createServer as r, assets as s, createEntry as t, accessLog as u };
755
- //# sourceMappingURL=entry-ChjmFwX5.js.map