@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,3 @@
1
+ import { i as withForwardedProto, n as defaultPlugins, r as serverInternals, t as createServer } from "./create-server-DVTZun6D.js";
2
+
3
+ export { createServer, defaultPlugins, serverInternals, withForwardedProto };
@@ -1,5 +1,5 @@
1
- import { C as SentResponse, g as LogSink, h as LogOptions, t as AppServerEnv, u as Listener, v as Plugin } from "./types-MgFtkNQW.js";
2
- import { t as TrailingSlash } from "./trailing-slash-D2QWKWEu.js";
1
+ import { C as SentResponse, _ as Plugin, h as LogSink, l as Listener, m as LogOptions, t as AppServerEnv } from "./types-KsKRDwAv.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-C-yBKCib.js";
3
3
  import { Context, Hono } from "hono";
4
4
  /** Options for {@link accessLog}. */
5
5
  type AccessLogOptions = {
@@ -34,25 +34,35 @@ type AccessLogOptions = {
34
34
  * with an `edge`, such as the node listener, counts the bytes.
35
35
  *
36
36
  * - A 5xx line has the level `error`, and each other line has the level `info`.
37
+ * - A 5xx whose client went away before the app answered has the status
38
+ * `499` and the level `info`.
37
39
  * - A line has `http.route` when the framework adapter gives the route
38
40
  * pattern that it matched, such as `/domains/:domainId`.
41
+ * - A line has `http.aborted: true` when the body stopped before its end: the
42
+ * client left, the body failed, or the server closed the connection.
39
43
  * - In development, a request that Vite answers, such as a source module,
40
44
  * gets no line.
41
45
  * - A request of the build's check of the CDN pages gets no line.
42
46
  *
43
47
  * @example
44
- * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
48
+ * createServer({ plugins: [requestId(), accessLog({ redactQuery: false }), assets()] });
45
49
  * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
46
50
  */
47
51
  declare function accessLog({ redactQuery, attributes, serverTiming }?: AccessLogOptions): Plugin;
48
52
  /** Options for {@link buildId}. */
49
53
  type BuildIdOptions = {
50
- /** @default "X-Build-Id" */
51
- header?: string;
54
+ /**
55
+ * The response header that carries the build. Give the same name to
56
+ * `staleBuildReactRouter()` or `staleBuildTanStack()`. A name that is not
57
+ * an HTTP header name stops startup.
58
+ * @default "X-Build-Id"
59
+ */
60
+ headerName?: string;
52
61
  /**
53
62
  * The deployed build, such as the image tag. With no value or `""`, the
54
63
  * plugin sends the ID that the `appServer` Vite plugin derives from the
55
- * client build. In development, it then sends no build.
64
+ * client build. In development, it then sends no build. A value that a
65
+ * header cannot hold, such as one with a line break, stops startup.
56
66
  * @default the `buildId` of `.app-server.json` in the client build
57
67
  */
58
68
  value?: string | undefined;
@@ -89,12 +99,19 @@ type BuildIdOptions = {
89
99
  * @example
90
100
  * buildId({ value: process.env.IMAGE_TAG });
91
101
  */
92
- declare function buildId({ header, value: given, paths }?: BuildIdOptions): Plugin;
102
+ declare function buildId({ headerName, value: given, paths }?: BuildIdOptions): Plugin;
93
103
  /** Options for {@link health}. */
94
104
  type HealthOptions = {
95
- /** @default "/livez" */
105
+ /**
106
+ * The path of the liveness probe. It must start with `/`.
107
+ * @default "/livez"
108
+ */
96
109
  livePath?: string;
97
- /** @default "/readyz" */
110
+ /**
111
+ * The path of the readiness probe. It must start with `/`, and it must not
112
+ * be `livePath`.
113
+ * @default "/readyz"
114
+ */
98
115
  readyPath?: string;
99
116
  /**
100
117
  * An app check for readiness, such as a database ping. A `false` or a
@@ -113,6 +130,10 @@ type HealthOptions = {
113
130
  * `defaultPlugins()` runs it first, so a probe skips the access log. Its
114
131
  * `health` option takes these options, and `false` turns it off.
115
132
  *
133
+ * A path that does not start with `/`, a path with `?` or `#`, or one path
134
+ * for both probes stops startup. For a platform with one health URL, set only
135
+ * `readyPath`.
136
+ *
116
137
  * @example
117
138
  * createServer({
118
139
  * plugins: defaultPlugins({ health: { ready: async () => db.ping() } }),
@@ -126,6 +147,7 @@ type NoindexOptions = {
126
147
  * A request with this header gets no `X-Robots-Tag`, and each response
127
148
  * gets the header in `Vary`. The `vercel` host can then serve a
128
149
  * prerendered page from the CDN, which picks the answer by the same header.
150
+ * A name that is not an HTTP header name, such as `""`, stops startup.
129
151
  */
130
152
  unlessHeader: string;
131
153
  };
@@ -148,7 +170,10 @@ type RedirectRule = {
148
170
  * The old URL path. A `:name` segment matches one path segment, and a `*`
149
171
  * last segment matches the rest of the path, or nothing: `/docs/*` also
150
172
  * matches `/docs`. A trailing slash does not change the match. Write the
151
- * path as it is in the URL, percent-encoded.
173
+ * path as it is in the URL, percent-encoded. A rule matches the path only,
174
+ * so a query, a fragment, or a character that is not percent-encoded stops
175
+ * startup. So does a segment that starts with `:` or has `*` and is not
176
+ * `:name` or `*`, such as `:slug*` or `*.html`.
152
177
  */
153
178
  from: string;
154
179
  /**
@@ -160,10 +185,23 @@ type RedirectRule = {
160
185
  /** @default 301 */
161
186
  status?: 301 | 308;
162
187
  };
188
+ /** Options for {@link redirects}. */
189
+ type RedirectsOptions = {
190
+ /**
191
+ * The mode of the `trailingSlash` plugin that runs after this plugin. In
192
+ * the `never` mode, a local target loses its trailing slash. Each other
193
+ * mode sends the target as the rule has it. `defaultPlugins()` gives its
194
+ * own mode, which is `never` by default.
195
+ * @default "preserve"
196
+ */
197
+ trailingSlash?: TrailingSlash;
198
+ };
163
199
  /**
164
200
  * Sends a redirect from each old URL path in `rules` to its new URL, with
165
201
  * the query string. The first rule that matches wins. An exact path is a
166
- * map lookup. A rule with `:name` or `*` is a pattern.
202
+ * map lookup. A rule with `:name` or `*` is a pattern. A request tests only
203
+ * the patterns that start with its first path segment, and the patterns
204
+ * whose first segment is `:name` or `*`.
167
205
  *
168
206
  * The rules compile at startup, and a rule that is not valid stops startup.
169
207
  * A local target must be a safe local path. An absolute target must keep the
@@ -172,9 +210,10 @@ type RedirectRule = {
172
210
  * target. It applies to GET and HEAD only.
173
211
  *
174
212
  * Put it before `trailingSlash`, so `/old/` gets one redirect to the final
175
- * URL, and give it the same `trailingSlash` mode. In `never` mode, a local
176
- * target loses its trailing slash, so `trailingSlash` does not redirect it
177
- * again. `defaultPlugins({ redirects })` does both.
213
+ * URL, and give it the same `trailingSlash` mode. Its default is
214
+ * `"preserve"`, which is not the `"never"` of `defaultPlugins()`. In `never`
215
+ * mode, a local target loses its trailing slash, so `trailingSlash` does not
216
+ * redirect it again. `defaultPlugins({ redirects })` does both.
178
217
  *
179
218
  * @example
180
219
  * redirects([
@@ -182,9 +221,7 @@ type RedirectRule = {
182
221
  * { from: "/docs/*", to: "https://docs.example.com/*", status: 308 },
183
222
  * ]);
184
223
  */
185
- declare function redirects(rules: readonly RedirectRule[], { trailingSlash }?: {
186
- trailingSlash?: TrailingSlash;
187
- }): Plugin;
224
+ declare function redirects(rules: readonly RedirectRule[], { trailingSlash }?: RedirectsOptions): Plugin;
188
225
  /** The headers that {@link securityHeaders} sets, by name. */
189
226
  type SecurityHeaderValues = {
190
227
  "X-Content-Type-Options"?: string | false;
@@ -205,7 +242,10 @@ type SecurityHeaderValues = {
205
242
  };
206
243
  /** Options for {@link securityHeaders}. */
207
244
  type SecurityHeadersOptions = {
208
- /** Values that replace the defaults. `false` turns a header off. */
245
+ /**
246
+ * Values that replace the defaults. `false` turns a header off. A value
247
+ * that a header cannot hold, such as one with a curly quote, stops startup.
248
+ */
209
249
  headers?: SecurityHeaderValues;
210
250
  };
211
251
  /**
@@ -253,8 +293,9 @@ type ContentSecurityPolicyOptions = {
253
293
  * policy trusts the document's scripts, and only them:
254
294
  *
255
295
  * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce
256
- * for each request. The app reads the nonce from `requestContext()` and
257
- * gives it to the framework's render, so each inline script gets it.
296
+ * for each request. The app gives `cspNonce()` from
297
+ * `@ngrok/app-server/client` to the framework's render, so each inline
298
+ * script gets the nonce.
258
299
  * - A prerendered document gets `'self'` and the hash of each of its inline
259
300
  * scripts, which the Vite plugin records. Its file has one nonce for every
260
301
  * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,
@@ -275,7 +316,11 @@ type ContentSecurityPolicyOptions = {
275
316
  declare function contentSecurityPolicy({ policy }: ContentSecurityPolicyOptions): Plugin;
276
317
  /** Options for {@link requestId}. */
277
318
  type RequestIdOptions = {
278
- /** @default "X-Request-Id" */
319
+ /**
320
+ * The request header that the ID comes from, and the response header that
321
+ * carries it. A name that is not an HTTP header name stops startup.
322
+ * @default "X-Request-Id"
323
+ */
279
324
  headerName?: string;
280
325
  /**
281
326
  * Also log the trace IDs as `dd.trace_id` and `dd.span_id`, the lower 64
@@ -293,7 +338,7 @@ type RequestIdOptions = {
293
338
  * line of the request.
294
339
  *
295
340
  * @example
296
- * const app = createServer({ plugins: [requestId()] });
341
+ * const app = createServer({ plugins: [requestId(), assets()] });
297
342
  * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
298
343
  * response.headers.get("X-Request-Id"); // => "abc-123"
299
344
  */
@@ -324,8 +369,6 @@ type StandardSchemaV1<Input = unknown, Output = Input> = {
324
369
  };
325
370
  /** The parsed type of a Standard Schema. */
326
371
  type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
327
- /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
328
- declare const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
329
372
  /** Options for {@link runtimeEnv}. */
330
373
  type RuntimeEnvOptions = {
331
374
  /** @default process.env */
@@ -370,7 +413,8 @@ declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Schema, { s
370
413
  * default, with a one-year immutable cache. The `appServer` Vite plugin
371
414
  * records the directory. A missing asset gets a plain 404 with
372
415
  * `Cache-Control: no-store`, not a rendered page. In development, the dev
373
- * server serves the source modules, the HMR client, and the CSS here instead.
416
+ * server serves the source modules, the HMR client, and the CSS here instead,
417
+ * so a development plugin list needs this plugin.
374
418
  *
375
419
  * @example
376
420
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
@@ -379,11 +423,15 @@ declare function assets(): Plugin;
379
423
  /** Options for {@link prerendered}. */
380
424
  type PrerenderedOptions = {
381
425
  /**
382
- * Extra headers for a served file, by its URL path. They replace the
383
- * headers captured at build time.
426
+ * Extra headers for a served file. They replace the headers captured at
427
+ * build time. `path` is the URL path that names the file: the request path,
428
+ * or the path that `rewrite` or a markdown twin gives, such as `/about`.
429
+ * `file` is the URL path of the file in the client build, such as
430
+ * `/about/index.html`, the same path that `cacheControl` gets.
384
431
  */
385
- headers?: (file: {
432
+ headers?: (served: {
386
433
  path: string;
434
+ file: string;
387
435
  context: Context<AppServerEnv>;
388
436
  }) => Readonly<Record<string, string>> | undefined;
389
437
  /**
@@ -435,10 +483,10 @@ type PrerenderedOptions = {
435
483
  twinOf: TwinOf;
436
484
  };
437
485
  /**
438
- * Sends a request path to the next stage, with no file lookup. Use it for
439
- * private pages, so the auth check in the app or the framework runs for
440
- * them. A data request has its own path, such as `/app.data` in React
441
- * Router.
486
+ * Sends a request path to the next stage, with no file lookup. It gets the
487
+ * request path, before `rewrite`. Use it for private pages, so the auth
488
+ * check in the app or the framework runs for them. A data request has its
489
+ * own path, such as `/app.data` in React Router.
442
490
  *
443
491
  * @example
444
492
  * prerendered({ skip: (path) => path === "/app" || path.startsWith("/app/") || path.startsWith("/app.") });
@@ -446,8 +494,8 @@ type PrerenderedOptions = {
446
494
  skip?: (path: string) => boolean;
447
495
  /**
448
496
  * The `Cache-Control` of a served file, by the file's URL path, such as
449
- * `/about/index.html`. `undefined` sends none. A header that the build
450
- * captured, and the `headers` option, win over it.
497
+ * `/about/index.html`. `undefined` gives the default for the file. A
498
+ * header that the build captured, and the `headers` option, win over it.
451
499
  *
452
500
  * The default gives an HTML page, a markdown file, and a data file of the
453
501
  * framework `public, max-age=0, must-revalidate`, so a visitor always sees
@@ -455,9 +503,9 @@ type PrerenderedOptions = {
455
503
  * `public, max-age=3600, stale-while-revalidate=86400`.
456
504
  *
457
505
  * @example
458
- * prerendered({ cacheControl: (path) => (path.startsWith("/images/") ? "public, max-age=86400" : undefined) });
506
+ * prerendered({ cacheControl: (file) => (file.startsWith("/images/") ? "public, max-age=86400" : undefined) });
459
507
  */
460
- cacheControl?: (path: string) => string | undefined;
508
+ cacheControl?: (file: string) => string | undefined;
461
509
  };
462
510
  /** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */
463
511
  type TwinOf = (request: {
@@ -484,17 +532,6 @@ type TwinOf = (request: {
484
532
  declare function prerendered(options?: PrerenderedOptions): Plugin;
485
533
  /** A Hono app from {@link createServer}. Add routes to it before you export it. */
486
534
  type AppServer = Hono<AppServerEnv>;
487
- /** A server that listens. */
488
- type RunningServer = {
489
- /** The URL of each listener. */
490
- urls: readonly string[];
491
- /**
492
- * Marks the server as not ready, and waits for the shutdown delay. Then it
493
- * aborts `shutdownSignal()` and runs each plugin's `onShutdown` while the
494
- * listeners stop and drain open requests. Both stop at the deadline.
495
- */
496
- shutdown: () => Promise<void>;
497
- };
498
535
  /** Options for {@link defaultPlugins}. */
499
536
  type DefaultPluginsOptions = {
500
537
  /**
@@ -503,8 +540,21 @@ type DefaultPluginsOptions = {
503
540
  * @default {}
504
541
  */
505
542
  health?: HealthOptions | false;
543
+ /**
544
+ * The options of the request ID of each request. See {@link requestId}.
545
+ * @default {}
546
+ */
506
547
  requestId?: RequestIdOptions;
548
+ /**
549
+ * The options of the log line of each request. See {@link accessLog}.
550
+ * @default {}
551
+ */
507
552
  accessLog?: AccessLogOptions;
553
+ /**
554
+ * The options of the files of the client build, such as `headers`, `skip`,
555
+ * and `markdownTwins`. See {@link prerendered}.
556
+ * @default {}
557
+ */
508
558
  prerendered?: PrerenderedOptions;
509
559
  /**
510
560
  * Redirects from old URL paths to new URLs. They run before
@@ -526,6 +576,7 @@ type DefaultPluginsOptions = {
526
576
  /**
527
577
  * The options of the security headers. `false` turns them off. See
528
578
  * {@link securityHeaders}.
579
+ * @default {}
529
580
  */
530
581
  securityHeaders?: SecurityHeadersOptions | false;
531
582
  /**
@@ -563,19 +614,30 @@ type DefaultPluginsOptions = {
563
614
  * set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the
564
615
  * `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),
565
616
  * `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain
566
- * array, so an app can filter it or splice into it.
617
+ * array, so an app can filter it or splice into it. To find a plugin in the
618
+ * array, compare its `name`: the name of its function in kebab-case, such as
619
+ * `streaming-compress`. A filter on a name that no plugin has removes nothing.
567
620
  *
568
621
  * @example
569
622
  * createServer({
570
623
  * plugins: defaultPlugins({ env, noindex: process.env.PREVIEW === "1", health: { ready: async () => db.ping() } }),
571
624
  * });
625
+ *
626
+ * @example
627
+ * // Behind a proxy that compresses each response.
628
+ * createServer({
629
+ * plugins: defaultPlugins().filter((plugin) => plugin.name !== "streaming-compress"),
630
+ * });
572
631
  */
573
632
  declare function defaultPlugins(options?: DefaultPluginsOptions): Plugin[];
574
633
  /** Options for {@link createServer}. */
575
634
  type CreateServerOptions = {
576
635
  /** @default defaultPlugins() */
577
636
  plugins?: readonly Plugin[];
578
- /** @default jsonSink() */
637
+ /**
638
+ * @default jsonSink(). In `app-server start`, the default writes the text format of the CLI's
639
+ * lines, because a person reads those lines.
640
+ */
579
641
  logger?: LogSink;
580
642
  /**
581
643
  * Hooks that change each log line of the server and of `logger()`, such
@@ -618,8 +680,9 @@ type CreateServerOptions = {
618
680
  * the app's own routes, then the framework. It does not listen; the
619
681
  * `app-server` CLI starts it.
620
682
  *
621
- * Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,
622
- * stop startup.
683
+ * A plugin list with an entry that is not a plugin, a second plugin of one
684
+ * option, or a plugin that the prerendered pages need after `prerendered()`
685
+ * stops startup. The README section "The pipeline" gives each rule.
623
686
  *
624
687
  * @example
625
688
  * // server.ts
@@ -627,6 +690,5 @@ type CreateServerOptions = {
627
690
  * app.get("/api/status", (c) => c.json({ ok: true }));
628
691
  * export default app;
629
692
  */
630
- declare function createServer({ plugins, logger: sink, log, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
631
- export { buildId as A, RedirectRule as C, HealthOptions as D, noindex as E, accessLog as M, health as O, securityHeaders as S, NoindexOptions as T, requestId as _, createServer as a, SecurityHeadersOptions as b, assets as c, PUBLIC_ENV_SCRIPT_ID as d, RuntimeEnv as f, RequestIdOptions as g, runtimeEnv as h, RunningServer as i, AccessLogOptions as j, BuildIdOptions as k, prerendered as l, StandardSchemaV1 as m, CreateServerOptions as n, defaultPlugins as o, RuntimeEnvOptions as p, DefaultPluginsOptions as r, PrerenderedOptions as s, AppServer as t, InferOutput as u, ContentSecurityPolicyOptions as v, redirects as w, contentSecurityPolicy as x, SecurityHeaderValues as y };
632
- //# sourceMappingURL=create-server-X2GR-U6t.d.ts.map
693
+ declare function createServer({ plugins, logger: appSink, log, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
694
+ export { AccessLogOptions as A, redirects as C, health as D, HealthOptions as E, BuildIdOptions as O, RedirectsOptions as S, noindex as T, SecurityHeaderValues as _, defaultPlugins as a, securityHeaders as b, prerendered as c, RuntimeEnvOptions as d, StandardSchemaV1 as f, ContentSecurityPolicyOptions as g, requestId as h, createServer as i, accessLog as j, buildId as k, InferOutput as l, RequestIdOptions as m, CreateServerOptions as n, PrerenderedOptions as o, runtimeEnv as p, DefaultPluginsOptions as r, assets as s, AppServer as t, RuntimeEnv as u, SecurityHeadersOptions as v, NoindexOptions as w, RedirectRule as x, contentSecurityPolicy as y };
@@ -70,5 +70,4 @@ async function listen(fetch, options) {
70
70
  };
71
71
  }
72
72
 
73
- export { listen };
74
- //# sourceMappingURL=deno-aqhikNMG.js.map
73
+ export { listen };
@@ -1,13 +1,12 @@
1
- import { t as asError } from "./log-DQAS5gGT.js";
2
- import { i as readBuildManifest, n as DEFAULT_ASSETS_PATH } from "./build-manifest-DBMWe3Lx.js";
3
- import { p as abortShutdownSignal, r as serverInternals } from "./create-server-Bp1yILQk.js";
4
- import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
1
+ import { n as DEFAULT_ASSETS_PATH, o as readBuildManifest } from "./build-manifest-CoBztw_6.js";
2
+ import { a as abortShutdownSignal, r as serverInternals } from "./create-server-DVTZun6D.js";
3
+ import { n as flushLogs, o as setLogWriter, s as sinkLogger, t as asError } from "./log-DfC9D5_T.js";
4
+ import { a as keptFiles } from "./static-files-BdTPam5b.js";
5
5
 
6
6
  // src/core/static-pages.ts
7
- /** The headers that change with each request, such as the request ID. A CDN answer drops them. */
8
- const PER_REQUEST = /* @__PURE__ */ new Set(["x-request-id", "date"]);
9
7
  /** The headers that the CDN sets for each file itself. */
10
8
  const CDN_OWN = /* @__PURE__ */ new Set([
9
+ "date",
11
10
  "content-length",
12
11
  "etag",
13
12
  "last-modified",
@@ -89,12 +88,18 @@ async function answer(fetch, path, { client, presence, present }) {
89
88
  file
90
89
  };
91
90
  }
91
+ /** Why a loop: `every` calls a function for each byte of each page. */
92
92
  function sameBytes(first, second) {
93
- return first.length === second.length && first.every((byte, index) => byte === second[index]);
93
+ if (first.length !== second.length) return false;
94
+ for (let index = 0; index < first.length; index += 1) if (first[index] !== second[index]) return false;
95
+ return true;
94
96
  }
95
- /** The headers of `headers` that a CDN answer keeps, sorted by name. */
96
- function keptHeaders(headers) {
97
- return [...headers].filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name)).toSorted(([first], [second]) => first < second ? -1 : 1);
97
+ /**
98
+ * The headers of `headers` that a CDN answer keeps, sorted by name. `perRequest`
99
+ * names the headers that a plugin gives a new value for each request.
100
+ */
101
+ function keptHeaders(headers, perRequest) {
102
+ return [...headers].filter(([name]) => !perRequest.includes(name) && !CDN_OWN.has(name)).toSorted(([first], [second]) => first < second ? -1 : 1);
98
103
  }
99
104
  /** The path of the markdown twin in a `Link` header, if any. */
100
105
  function twinIn(link) {
@@ -115,9 +120,9 @@ function uncacheable(first, allowedVary) {
115
120
  return vary == null ? void 0 : `the answer varies on ${vary}`;
116
121
  }
117
122
  /** Why `second` differs from `first`, or `undefined` when they match. */
118
- function difference(first, second) {
123
+ function difference(first, second, perRequest) {
119
124
  if (first.status !== second.status || first.file !== second.file) return "the status or the file changes with the request";
120
- const changed = [...new Set([...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name))].find((name) => first.headers.get(name) !== second.headers.get(name));
125
+ const changed = [...new Set([...keptHeaders(first.headers, perRequest), ...keptHeaders(second.headers, perRequest)].map(([name]) => name))].find((name) => first.headers.get(name) !== second.headers.get(name));
121
126
  if (changed != null) return `the ${changed} header changes with the request`;
122
127
  return sameBytes(first.body, second.body) ? void 0 : "the body changes with the request";
123
128
  }
@@ -128,7 +133,8 @@ function subsets(names) {
128
133
  return all;
129
134
  }
130
135
  /** The CDN answer of one path, or the reason that the server must answer it. */
131
- async function staticPage(fetch, path, presence) {
136
+ async function staticPage(fetch, path, marked) {
137
+ const { presence, perRequest } = marked;
132
138
  if (!PLAIN_PATH.test(path)) return {
133
139
  path,
134
140
  reason: "the path has a character that a CDN route can match two ways"
@@ -138,7 +144,7 @@ async function staticPage(fetch, path, presence) {
138
144
  presence,
139
145
  present: []
140
146
  });
141
- if (probe.status === 308 && probe.headers.get("location") === `${path}/`) return staticPage(fetch, `${path}/`, presence);
147
+ if (probe.status === 308 && probe.headers.get("location") === `${path}/`) return staticPage(fetch, `${path}/`, marked);
142
148
  if (presence.length > MAX_PRESENCE_HEADERS) return {
143
149
  path,
144
150
  reason: `more than ${MAX_PRESENCE_HEADERS} presence headers`
@@ -162,7 +168,7 @@ async function staticPage(fetch, path, presence) {
162
168
  "accept-encoding",
163
169
  ...presence,
164
170
  ...caseTwin == null ? [] : ["accept"]
165
- ])) ?? difference(first, second);
171
+ ])) ?? difference(first, second, perRequest);
166
172
  if (reason != null) return {
167
173
  path,
168
174
  reason
@@ -179,7 +185,7 @@ async function staticPage(fetch, path, presence) {
179
185
  twin = caseTwin;
180
186
  answers.push({
181
187
  present,
182
- headers: Object.fromEntries(keptHeaders(first.headers))
188
+ headers: Object.fromEntries(keptHeaders(first.headers, perRequest))
183
189
  });
184
190
  }
185
191
  if (base?.file == null) return {
@@ -206,11 +212,11 @@ async function staticPage(fetch, path, presence) {
206
212
  *
207
213
  * - is a 200 from a prerendered file, with no cookie and no `private`,
208
214
  * `no-store`, or `no-cache`
209
- * - is the same, except for the request ID, for a second client with another
210
- * host, client address, query, and value of each presence header, and with
211
- * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN
212
- * route matches only the path, a markdown `Accept`, and the presence of
213
- * each presence header.
215
+ * - is the same, except for the `perRequest` headers, for a second client
216
+ * with another host, client address, query, and value of each presence
217
+ * header, and with a cookie, `Authorization`, `Accept-Language`, and geo
218
+ * headers. Why: a CDN route matches only the path, a markdown `Accept`, and
219
+ * the presence of each presence header.
214
220
  * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on
215
221
  * the presence headers. Each case of the presence headers gets its own
216
222
  * headers, and all cases must send the same body.
@@ -220,17 +226,16 @@ async function staticPage(fetch, path, presence) {
220
226
  *
221
227
  * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.
222
228
  * @example
223
- * for await (const page of staticPages(fetch, ["/", "/about"], { presence: ["x-ngrok-edge"] })) {
229
+ * const marked = { presence: ["x-ngrok-edge"], perRequest: ["x-request-id"] };
230
+ * for await (const page of staticPages(fetch, ["/", "/about"], marked)) {
224
231
  * console.log(page.path, "cdn" in page ? "CDN" : page.reason);
225
232
  * }
226
233
  */
227
- async function* staticPages(fetch, paths, { presence }) {
228
- for (const path of paths) yield await staticPage(fetch, path, presence);
234
+ async function* staticPages(fetch, paths, marked) {
235
+ for (const path of paths) yield await staticPage(fetch, path, marked);
229
236
  }
230
237
 
231
238
  // src/core/entry.ts
232
- /** The version of the contract between the CLI and the `appServer` export of a build. */
233
- const ENTRY_PROTOCOL = 2;
234
239
  /**
235
240
  * The `appServer` export of a server build: an app from `createServer`, the
236
241
  * host, and the framework adapter for each mode. The `appServer` Vite plugin
@@ -243,6 +248,8 @@ function createEntry({ app, host, framework, clientDirectory }) {
243
248
  const internals = serverInternals(app);
244
249
  if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
245
250
  internals.setRequestStore(host.storage);
251
+ setLogWriter(host.logWriter);
252
+ const logger = sinkLogger(internals.logger);
246
253
  const setupInfo = async (runtime) => {
247
254
  const directory = clientDirectory ?? runtime.clientDirectory;
248
255
  if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
@@ -252,17 +259,20 @@ function createEntry({ app, host, framework, clientDirectory }) {
252
259
  contentTypes: runtime.contentTypes ?? {},
253
260
  gzip: host.gzip,
254
261
  brotli: host.brotli,
255
- logger: internals.logger
262
+ logger
256
263
  };
257
264
  };
258
265
  let prerenderedPaths = [];
266
+ /** The production run side, after each `setup` ran. */
267
+ let ready;
259
268
  /** Runs each plugin's `setup` for production, and gives the framework's run side. */
260
269
  const prepareProduction = async () => {
261
270
  const runtime = framework("production");
262
271
  const shared = await setupInfo(runtime);
263
272
  const snapshot = await shared.files.snapshot?.();
273
+ const manifest = await readBuildManifest(snapshot ?? shared.files);
264
274
  const files = snapshot == null ? shared.files : keptFiles(snapshot);
265
- const manifest = await readBuildManifest(files);
275
+ if (await files.stat("/") == null) logger.warn("client build not found", { "app_server.client_directory": clientDirectory ?? runtime.clientDirectory });
266
276
  const info = {
267
277
  ...shared,
268
278
  files,
@@ -275,6 +285,7 @@ function createEntry({ app, host, framework, clientDirectory }) {
275
285
  };
276
286
  await internals.prepare(info);
277
287
  ({prerenderedPaths} = info);
288
+ ready = runtime;
278
289
  return runtime;
279
290
  };
280
291
  let preparing;
@@ -289,47 +300,63 @@ function createEntry({ app, host, framework, clientDirectory }) {
289
300
  });
290
301
  return preparing;
291
302
  };
303
+ /** Answers a request that comes before the setup ends. */
304
+ const fetchAfterSetup = async (request, bindings) => {
305
+ const runtime = await production().catch((error) => {
306
+ internals.logger.log({
307
+ level: "error",
308
+ message: "setup failed",
309
+ attributes: { error: asError(error) }
310
+ });
311
+ throw error;
312
+ });
313
+ return app.fetch(request, {
314
+ ...bindings,
315
+ framework: runtime
316
+ });
317
+ };
292
318
  let development;
319
+ let developmentReady = false;
293
320
  return {
294
- protocol: 2,
321
+ protocol: 3,
295
322
  app,
296
323
  start: async () => {
297
- const runtime = await production();
298
- const server = await internals.listen(runtime, host.listeners?.());
299
- host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
324
+ const server = await production().then(async (runtime) => internals.listen(runtime, host.listeners)).catch((error) => {
300
325
  internals.logger.log({
301
326
  level: "error",
302
- message: "shutdown failed",
327
+ message: "startup failed",
303
328
  attributes: { error: asError(error) }
304
329
  });
330
+ flushLogs();
305
331
  throw error;
306
- }));
307
- },
308
- fetch: async (request, bindings) => {
309
- const runtime = await production().catch((error) => {
332
+ });
333
+ host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
310
334
  internals.logger.log({
311
335
  level: "error",
312
- message: "setup failed",
336
+ message: "shutdown failed",
313
337
  attributes: { error: asError(error) }
314
338
  });
315
339
  throw error;
316
- });
317
- return app.fetch(request, {
318
- ...bindings,
319
- framework: runtime
320
- });
340
+ }));
321
341
  },
322
- fetchDev: async (request, bindings, devServer) => {
342
+ fetch: (request, bindings) => ready == null ? fetchAfterSetup(request, bindings) : app.fetch(request, {
343
+ ...bindings,
344
+ framework: ready
345
+ }),
346
+ fetchDev: async (request, { bindings, devServer }) => {
323
347
  development ??= framework("development");
324
- await internals.prepare({
325
- ...await setupInfo(development),
326
- mode: "development",
327
- devServer,
328
- prerenderedPaths: development.prerenderedPaths,
329
- capturedHeaders: /* @__PURE__ */ new Map(),
330
- scriptHashes: /* @__PURE__ */ new Map(),
331
- buildId: void 0
332
- });
348
+ if (!developmentReady) {
349
+ await internals.prepare({
350
+ ...await setupInfo(development),
351
+ mode: "development",
352
+ devServer,
353
+ prerenderedPaths: development.prerenderedPaths,
354
+ capturedHeaders: /* @__PURE__ */ new Map(),
355
+ scriptHashes: /* @__PURE__ */ new Map(),
356
+ buildId: void 0
357
+ });
358
+ developmentReady = true;
359
+ }
333
360
  return app.fetch(request, {
334
361
  ...bindings,
335
362
  framework: development
@@ -340,21 +367,14 @@ function createEntry({ app, host, framework, clientDirectory }) {
340
367
  yield* staticPages(async (request, bindings) => app.fetch(request, {
341
368
  ...bindings,
342
369
  framework: runtime
343
- }), prerenderedPaths, { presence: internals.presenceHeaders });
370
+ }), prerenderedPaths, {
371
+ presence: internals.presenceHeaders,
372
+ perRequest: internals.perRequestHeaders
373
+ });
344
374
  },
345
375
  stopPlugins: internals.stopPlugins,
346
376
  abortShutdownSignal
347
377
  };
348
378
  }
349
- /**
350
- * Whether a value is an entry of this protocol version.
351
- *
352
- * @example
353
- * isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
354
- */
355
- function isAppServerEntry(value) {
356
- return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
357
- }
358
379
 
359
- export { isAppServerEntry as n, createEntry as t };
360
- //# sourceMappingURL=entry-BoxCqc6w.js.map
380
+ export { createEntry as t };