@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
@@ -30,7 +30,10 @@ declare class ResponseEdge {
30
30
  * Keeps `headers`, the headers of the response after each header hook, and
31
31
  * `base`, its headers before the hooks. The server calls it.
32
32
  */
33
- useHeaders(base: readonly string[], headers: string[]): void;
33
+ useHeaders({ base, headers }: {
34
+ base: readonly string[];
35
+ headers: string[];
36
+ }): void;
34
37
  /**
35
38
  * The headers to write for `response`: lowercase names and their values in
36
39
  * turn, as Node's `writeHead` takes them. They are the headers after the
@@ -49,11 +52,16 @@ declare class ResponseEdge {
49
52
  /** Logs `error`, which stopped the response, with the logger of the request. */
50
53
  fail(error: unknown): void;
51
54
  /**
52
- * Reports what went out, once: the status and the headers that the
53
- * listener sent, the bytes, and whether the body stopped before its end.
54
- * `head` is the flat list that the listener gave `writeHead`.
55
+ * Reports what went out, once: `status`, the headers that the listener
56
+ * sent, the bytes, and `aborted`, which says whether the body stopped
57
+ * before its end. `head` is the flat list that the listener gave
58
+ * `writeHead`.
55
59
  */
56
- close(status: number, aborted: boolean, head: string[]): void;
60
+ close({ status, aborted, head }: {
61
+ status: number;
62
+ aborted: boolean;
63
+ head: string[];
64
+ }): void;
57
65
  }
58
66
  /** A log level the server writes. */
59
67
  type LogLevel = "debug" | "info" | "warn" | "error";
@@ -135,16 +143,18 @@ type FrameworkRuntime = {
135
143
  /** Content types that `mime` does not know, by file extension, such as `{ ".data": "text/x-script" }`. */
136
144
  contentTypes?: Readonly<Record<string, string>>;
137
145
  };
138
- /** Makes the run side of a framework adapter from the framework's server module. */
139
- type FrameworkRuntimeFactory = (serverModule: unknown, info: {
140
- mode: Mode;
141
- }) => FrameworkRuntime;
142
- /** What a host knows about a file under the client build. */
146
+ /**
147
+ * What a host knows about a file or a directory under the client build. Why
148
+ * a union: no code reads a size or a time of a directory, so a host gives
149
+ * none.
150
+ */
143
151
  type FileInfo = {
144
- kind: "file" | "directory";
152
+ kind: "file";
145
153
  /** The size in bytes. */
146
154
  size: number;
147
155
  mtimeMs: number;
156
+ } | {
157
+ kind: "directory";
148
158
  };
149
159
  /** A range of bytes in a file. `start` and `end` are both inclusive. */
150
160
  type ByteRange = {
@@ -157,7 +167,11 @@ type ByteRange = {
157
167
  * `\`.
158
168
  */
159
169
  type StaticFiles = {
160
- /** What is at `path`, or `undefined` when nothing is there. */
170
+ /**
171
+ * What is at `path`, or `undefined` when nothing is there. `/` gives the
172
+ * directory of the client build. If `/` gives `undefined`, the production
173
+ * server warns at start that it found no client build.
174
+ */
161
175
  stat: (path: string) => Promise<FileInfo | undefined>;
162
176
  /**
163
177
  * The bytes of the file at `path`. With `range`, only the bytes from
@@ -165,7 +179,9 @@ type StaticFiles = {
165
179
  * static stages answer a `Range` request with these bytes. Open the file on
166
180
  * the first read. Why: a stage can drop a response that no one reads.
167
181
  */
168
- open: (path: string, range?: ByteRange) => Promise<ReadableStream<Uint8Array>>;
182
+ open: (path: string, options?: {
183
+ range?: ByteRange | undefined;
184
+ }) => Promise<ReadableStream<Uint8Array>>;
169
185
  /**
170
186
  * A copy whose `stat` answers from a list of the files that it reads once.
171
187
  * The production server uses it, because the client build does not change
@@ -173,12 +189,22 @@ type StaticFiles = {
173
189
  */
174
190
  snapshot?: () => Promise<StaticFiles>;
175
191
  };
192
+ /**
193
+ * What a {@link RequestStore} holds for one request. A host passes it through
194
+ * and reads no field of it.
195
+ */
196
+ type RequestScope = {
197
+ /** The Hono context of the request, until its response is sent. */
198
+ context: Context<AppServerEnv> | undefined;
199
+ /** The values of the request, when the scope has no `context`. */
200
+ values: RequestContext | undefined;
201
+ };
176
202
  /** Request-scoped storage, such as `AsyncLocalStorage`. */
177
203
  type RequestStore = {
178
204
  /** Runs `work` with `value` as the stored value. */
179
- run: <Result>(value: Context<AppServerEnv>, work: () => Result) => Result;
205
+ run: <Result>(value: RequestScope, work: () => Result) => Result;
180
206
  /** The stored value of the request that runs, else `undefined`. */
181
- get: () => Context<AppServerEnv> | undefined;
207
+ get: () => RequestScope | undefined;
182
208
  };
183
209
  /** What went out for a response, when it ends or its client goes away. */
184
210
  type SentResponse = {
@@ -211,29 +237,52 @@ type Lifecycle = {
211
237
  */
212
238
  onStop: (stop: () => Promise<void>) => void;
213
239
  };
240
+ /** A host stream that compresses a byte stream. */
241
+ type CompressStream = (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
214
242
  /** The run side of a host adapter: where the server runs. */
215
243
  type HostRuntime = {
216
- /** A name for logs and errors. */
217
- name: string;
218
244
  /** The files of the client build at `clientDirectory`, a file path or a `file:` URL. */
219
245
  files: (clientDirectory: string) => StaticFiles;
220
246
  /**
221
247
  * The listeners when the app sets none. A serverless host has none: it
222
248
  * calls the entry's `fetch` for each request.
223
249
  */
224
- listeners?: () => readonly Listener[];
250
+ listeners?: readonly Listener[];
225
251
  /** The storage for {@link requestContext}. Without it, `requestContext()` gives `undefined`. */
226
252
  storage?: RequestStore;
227
253
  /**
228
254
  * Gzips a byte stream and flushes after each chunk. Without it and
229
255
  * `brotli`, `streamingCompress` sends each response as it is.
230
256
  */
231
- gzip?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
257
+ gzip?: CompressStream;
232
258
  /**
233
259
  * Compresses a byte stream with brotli and flushes after each chunk.
234
260
  * `streamingCompress` uses it for a client that prefers brotli to gzip.
235
261
  */
236
- brotli?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
262
+ brotli?: CompressStream;
263
+ /**
264
+ * Where `jsonSink()` and the text sink of development write a line when
265
+ * they get no `write`, such as the standard output of the process. Without
266
+ * it, `console.log` writes each line.
267
+ */
268
+ logWriter?: {
269
+ /**
270
+ * Takes one line, with the `\n` at its end. It can keep the line, such
271
+ * as until the end of the turn of the event loop.
272
+ */
273
+ write: (line: string) => void;
274
+ /**
275
+ * Writes each line that `write` keeps, at once. The server calls it
276
+ * after each text line of development, and before a failed `start`
277
+ * rejects.
278
+ */
279
+ flush: () => void;
280
+ };
281
+ /**
282
+ * How the host stops the server that the entry's `start` starts. A host
283
+ * with `listeners` must give it. Without it, no code can shut the server
284
+ * down: a stop signal ends the process with no drain and no `onShutdown`.
285
+ */
237
286
  lifecycle?: Lifecycle;
238
287
  };
239
288
  /**
@@ -290,22 +339,14 @@ type AppServerEnv = {
290
339
  clientAddress?: string | undefined;
291
340
  /** Attributes that each log line of the request carries, such as the trace IDs from the `requestId` plugin. */
292
341
  logAttributes?: Readonly<Record<string, unknown>>;
293
- /**
294
- * The `etagPart` of each plugin that the request passed, in order. The
295
- * static stages add them to each file's ETag. The server sets this list.
296
- */
297
- etagParts?: readonly string[];
298
342
  /**
299
343
  * Whether a stage that the request passed changes the bytes of an HTML
300
- * body, as `runtimeEnv` does. The stage sets it before its `next()`.
301
- * The static stages then send an HTML file as it is on disk, not its
302
- * compressed copy, so the stage can change it.
344
+ * body. The stage sets it before its `next()`. The static stages then
345
+ * send an HTML file as it is on disk: not its compressed copy, and with
346
+ * no `Content-Length`, no ETag, and no 304. `runtimeEnv` does not set
347
+ * it: its pages keep their ETag.
303
348
  */
304
349
  rewritesHtml?: boolean;
305
- /** The header hook of each stage that the request passed, in order. See {@link HeaderHook}. */
306
- headerHooks?: HeaderHook[];
307
- /** The reports of `onResponseSent` for the request. The server sets this list. */
308
- sentReports?: ((sent: SentResponse) => void)[];
309
350
  };
310
351
  };
311
352
  /** The headers of a response, for a {@link HeaderHook}. */
@@ -321,8 +362,9 @@ type ResponseHeaders = {
321
362
  * response. In an app server, it changes the head once, where the response
322
363
  * leaves, after the code that each stage runs after its `next()`: the hook of
323
364
  * an inner stage runs first, so an outer stage has the last word. A hook that
324
- * throws gives a 500, as a stage that throws does. A dev server middleware
325
- * that sends its own response runs the hooks before it sends the head.
365
+ * throws gets the answer of the app's `onError`, as a stage that throws does.
366
+ * A dev server middleware that sends its own response runs the hooks before
367
+ * it sends the head.
326
368
  *
327
369
  * The static stages and `streamingCompress` also run the hooks on a view of
328
370
  * the headers, to read the `Cache-Control` that leaves. So a hook can run two
@@ -355,10 +397,11 @@ type SetupInfo = {
355
397
  /** Content types of the framework's files that `mime` does not know, by file extension. */
356
398
  contentTypes: Readonly<Record<string, string>>;
357
399
  /** The host's gzip stream, when it has one. */
358
- gzip: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
400
+ gzip: CompressStream | undefined;
359
401
  /** The host's brotli stream, when it has one. */
360
- brotli?: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
361
- logger: LogSink;
402
+ brotli?: CompressStream | undefined;
403
+ /** The server's logger. Its lines carry no request fields. */
404
+ logger: RequestLogger;
362
405
  } & ({
363
406
  mode: "production";
364
407
  /** The URL paths that the build prerendered. */
@@ -367,7 +410,10 @@ type SetupInfo = {
367
410
  assetsPath: string;
368
411
  } | {
369
412
  mode: "development";
370
- /** The dev server as a pipeline stage. It serves source modules, HMR, and CSS. */
413
+ /**
414
+ * The dev server as a pipeline stage. It serves source modules, HMR, and CSS. One plugin
415
+ * must take it, as `assets()` does. The setup throws when no plugin reads it.
416
+ */
371
417
  devServer: MiddlewareHandler<AppServerEnv>;
372
418
  /**
373
419
  * The URL paths that the build will prerender, or `undefined` when the
@@ -386,18 +432,20 @@ type SetupInfo = {
386
432
  * };
387
433
  */
388
434
  type Plugin = {
389
- /** A name for logs and errors. */
435
+ /** A name for logs and errors. An app finds the plugin in a list by it, such as in `defaultPlugins()`. */
390
436
  name: string;
391
437
  /** The Hono middleware for this step. */
392
438
  middleware?: MiddlewareHandler<AppServerEnv>;
393
439
  /**
394
440
  * Runs once before the server takes requests. A thrown error stops startup.
395
441
  * On a serverless host, a thrown error fails the request, and the next
396
- * request runs each `setup` again.
442
+ * request runs each `setup` again. Take the values that you need from
443
+ * `info`: a function that keeps `info` keeps each field of it in memory,
444
+ * such as the script hashes of each page.
397
445
  */
398
446
  setup?: (info: SetupInfo) => void | Promise<void>;
399
447
  /** Runs at shutdown while the listeners drain. The server stops waiting for it at the drain deadline. */
400
- onShutdown?: () => Promise<void>;
448
+ onShutdown?: () => void | Promise<void>;
401
449
  /**
402
450
  * A value that this plugin's changes to a response depend on, such as the
403
451
  * env values it writes into each document. The server adds it to the ETag
@@ -406,6 +454,12 @@ type Plugin = {
406
454
  * the plugin changes nothing.
407
455
  */
408
456
  etagPart?: () => string | undefined;
457
+ /**
458
+ * Never set it. Why: each function has a `name`, so without this field the
459
+ * compiler takes a Hono middleware, or a plugin factory that the app did
460
+ * not call, as a plugin.
461
+ */
462
+ call?: never;
409
463
  };
410
464
  /** A running listener. */
411
465
  type StartedListener = {
@@ -423,11 +477,9 @@ type StartedListener = {
423
477
  * How the server receives connections, separate from the request pipeline.
424
478
  *
425
479
  * @example
426
- * createServer({ listeners: [tcp({ port: 8080 })] });
480
+ * createServer({ listeners: [tcp({ idleTimeoutMs: 120_000 })] });
427
481
  */
428
482
  type Listener = {
429
- /** A name for logs. */
430
- name: string;
431
483
  start: (fetch: FetchHandler, options?: ListenerStartOptions) => Promise<StartedListener>;
432
484
  };
433
485
  /** What the server tells a listener when it starts it. */
@@ -440,5 +492,4 @@ type ListenerStartOptions = {
440
492
  */
441
493
  trustForwardedProto?: boolean;
442
494
  };
443
- export { SentResponse as C, StaticFiles as D, StartedListener as E, ResponseEdge as O, ResponseHeaders as S, SetupInfo as T, Mode as _, FrameworkRuntime as a, RequestLogger as b, HostRuntime as c, ListenerBindings as d, ListenerStartOptions as f, LogSink as g, LogOptions as h, FileInfo as i, Lifecycle as l, LogLine as m, ByteRange as n, FrameworkRuntimeFactory as o, LogLevel as p, FetchHandler as r, HeaderHook as s, AppServerEnv as t, Listener as u, Plugin as v, ServerBindings as w, RequestStore as x, RequestContext as y };
444
- //# sourceMappingURL=types-MgFtkNQW.d.ts.map
495
+ export { SentResponse as C, StaticFiles as D, StartedListener as E, ResponseEdge as O, ResponseHeaders as S, SetupInfo as T, Plugin as _, FrameworkRuntime as a, RequestScope as b, Lifecycle as c, ListenerStartOptions as d, LogLevel as f, Mode as g, LogSink as h, FileInfo as i, Listener as l, LogOptions as m, ByteRange as n, HeaderHook as o, LogLine as p, FetchHandler as r, HostRuntime as s, AppServerEnv as t, ListenerBindings as u, RequestContext as v, ServerBindings as w, RequestStore as x, RequestLogger as y };
@@ -1,5 +1,6 @@
1
+ import { t as CdnPage } from "./static-pages-6IBHdYQc.js";
1
2
  /** A prerendered path that the CDN serves, as `vercel()` writes it. */
2
- export type CdnPageReport = {
3
+ export type CdnPageReport = Omit<CdnPage, "body" | "file"> & {
3
4
  path: string;
4
5
  /**
5
6
  * The URL path of the page's body under the static directory, such as
@@ -7,11 +8,6 @@ export type CdnPageReport = {
7
8
  * such as with `prerendered({ rewrite })`, and different bodies.
8
9
  */
9
10
  file: string;
10
- answers: {
11
- present: readonly string[];
12
- headers: Readonly<Record<string, string>>;
13
- }[];
14
- twin?: string;
15
11
  };
16
12
  /** What the step found: the paths that the CDN serves, and why the function serves each other path. */
17
13
  export type PagesReport = {
@@ -20,13 +16,4 @@ export type PagesReport = {
20
16
  path: string;
21
17
  reason: string;
22
18
  }[];
23
- };
24
- /**
25
- * Writes the body of each page that the CDN can serve to `staticDirectory`,
26
- * at the path of its file, and the {@link PagesReport} to `reportFile`.
27
- *
28
- * @example
29
- * await writePages("build/server/app-server.js", ".vercel/output/static/_app-server/pages", "pages.json");
30
- */
31
- export declare function writePages(entryFile: string, staticDirectory: string, reportFile: string): Promise<void>;
32
- //# sourceMappingURL=vercel-pages.d.ts.map
19
+ };
@@ -50,5 +50,4 @@ if (import.meta.main) {
50
50
  process.exit(0);
51
51
  }
52
52
 
53
- export { writePages };
54
- //# sourceMappingURL=vercel-pages.js.map
53
+ export { };
@@ -1,4 +1,4 @@
1
- import { r as HostBuild } from "./index-B8LsM6Mh.js";
1
+ import { r as HostBuild } from "./index-gzGs53Ue.js";
2
2
  /** Options for {@link vercel}. */
3
3
  export type VercelOptions = {
4
4
  /**
@@ -46,11 +46,10 @@ export type VercelOptions = {
46
46
  * `build.assetsDir` gets a one-year immutable cache. It also holds the
47
47
  * prerendered pages that the CDN serves, with `cdnPages`.
48
48
  * - `functions/index.func/`: one Node.js function that runs the pipeline for
49
- * each other request, with the whole server build and the rest of the
50
- * client build.
49
+ * each other request, with the whole server build, the rest of the client
50
+ * build, and the list of those client files, which the function serves.
51
51
  *
52
52
  * @example
53
53
  * appServer({ host: vercel() });
54
54
  */
55
- export declare function vercel(options?: VercelOptions): HostBuild;
56
- //# sourceMappingURL=vercel-vite.d.ts.map
55
+ export declare function vercel(options?: VercelOptions): HostBuild;
@@ -1,13 +1,13 @@
1
- import { r as copyName } from "./compression-CT2mWlKM.js";
2
- import { r as hasDotSegment } from "./static-files-C2ea8KQ6.js";
3
- import { t as BROTLI_ONLY_LIST } from "./brotli-only-DrA29Ecw.js";
1
+ import { r as IMMUTABLE } from "./build-manifest-CoBztw_6.js";
2
+ import { r as copyName } from "./compression-uJxu0JVb.js";
3
+ import { r as hasDotSegment } from "./static-files-BdTPam5b.js";
4
+ import { t as FILE_LIST } from "./brotli-only-BVAagKt3.js";
4
5
  import { copyFileSync, cpSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
6
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { execFileSync } from "node:child_process";
8
9
 
9
10
  // src/vercel/vite.ts
10
- const IMMUTABLE = "public, max-age=31536000, immutable";
11
11
  /** The most routes of a deployment. See https://vercel.com/docs/limits. */
12
12
  const ROUTE_LIMIT = 2048;
13
13
  /**
@@ -19,17 +19,15 @@ const PAGES = "/_app-server/pages";
19
19
  /**
20
20
  * The script that finds the pages that the CDN serves. Why the source in a
21
21
  * `.ts` module: the tests of this package run the source, and Node.js runs a
22
- * `.ts` file with no import of its own.
22
+ * `.ts` file that imports no value of its own.
23
23
  */
24
24
  const PAGES_SCRIPT = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./pages.ts" : "./vercel-pages.js", import.meta.url));
25
25
  /** A case-insensitive pattern for `text/markdown`, in the regular expression syntax of any engine. */
26
26
  const MARKDOWN = "text/markdown".replaceAll(/[a-z]/gu, (letter) => `[${letter}${letter.toUpperCase()}]`);
27
- /** The variable that gives the function the time of the build, in milliseconds. */
28
- const BUILT_AT = "APP_SERVER_BUILT_AT";
29
27
  /** The function's file, next to the server entry. */
30
28
  const FUNCTION_FILE = "vercel-function.js";
31
29
  /** A path with `/` separators, as Vercel's config reads it. */
32
- function posix$1(path) {
30
+ function posix(path) {
33
31
  return path.split(sep).join("/");
34
32
  }
35
33
  /** A regular expression source that matches `text` as it is. */
@@ -42,15 +40,16 @@ function copyFile(from, to) {
42
40
  copyFileSync(from, to);
43
41
  }
44
42
  /**
45
- * The path of each file under `directory`, relative to it. Why follow links:
46
- * the CDN and the function each get a copy of the linked file, not a link
47
- * whose target can be in the other part. Why the inodes of the parents: a
48
- * link to a parent directory must not make the walk endless.
43
+ * The path of each file under `directory`, relative to it, with the size of
44
+ * the file. Why follow links: the CDN and the function each get a copy of the
45
+ * linked file, not a link whose target can be in the other part. Why the
46
+ * inodes of the parents: a link to a parent directory must not make the walk
47
+ * endless.
49
48
  */
50
49
  function filesUnder(directory, under = "", parents = /* @__PURE__ */ new Set()) {
51
50
  const stats = statSync(join(directory, under), { throwIfNoEntry: false });
52
51
  if (stats == null) return [];
53
- if (!stats.isDirectory()) return [under];
52
+ if (!stats.isDirectory()) return [[under, stats.size]];
54
53
  const inode = `${stats.dev}:${stats.ino}`;
55
54
  if (parents.has(inode)) return [];
56
55
  const inside = new Set(parents).add(inode);
@@ -182,19 +181,21 @@ function findCdnPages(entryFile, output, { cdnPages, routeBudget }) {
182
181
  }
183
182
  return pages;
184
183
  }
185
- /** Writes the paths that the function serves, and why, so the build log shows them. */
186
- function reportPages({ cdn, server }) {
187
- const shown = server.slice(0, 20);
188
- process.stdout.write([
189
- `@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`,
190
- ...shown.map(({ path, reason }) => ` ${path}: ${reason}`),
191
- ...server.length > shown.length ? [` and ${server.length - shown.length} more`] : [],
192
- ""
193
- ].join("\n"));
184
+ /** Logs each path that the function serves, and why, so the build log shows them. */
185
+ function reportPages({ cdn, server }, logger) {
186
+ logger.info([`@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`, ...server.map(({ path, reason }) => ` ${path}: ${reason}`)].join("\n"));
187
+ }
188
+ /**
189
+ * The URL path prefixes of the files that the CDN serves. Why `assetsPath`
190
+ * last: Vercel applies each matched rule in order, so its immutable cache wins
191
+ * over a `cdnHeaders` value for a `cdnPaths` entry that holds it.
192
+ */
193
+ function cdnPrefixes(cdnPaths, assetsPath) {
194
+ return [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];
194
195
  }
195
196
  /** Writes `.vercel/output` (the Build Output API, version 3) for one build. */
196
- function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }) {
197
- const prefixes = [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];
197
+ function writeOutput({ root, clientDirectory, entryFile, assetsPath, logger }, { cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }) {
198
+ const prefixes = cdnPrefixes(cdnPaths, assetsPath);
198
199
  const output = join(root, ".vercel/output");
199
200
  rmSync(output, {
200
201
  recursive: true,
@@ -208,18 +209,20 @@ function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPath
208
209
  pages: []
209
210
  }).length - 1
210
211
  });
211
- if (cdnPages !== false) reportPages(pages);
212
+ if (cdnPages !== false) reportPages(pages, logger);
212
213
  const fromRoot = (path) => {
213
214
  const inside = relative(root, path);
214
215
  if (inside.startsWith("..") || isAbsolute(inside)) throw new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);
215
216
  return inside;
216
217
  };
217
218
  const functionDirectory = join(output, "functions/index.func");
218
- const isCdnFile = (file) => prefixes.some((prefix) => `/${posix$1(file)}`.startsWith(prefix));
219
- const clientFiles = filesUnder(clientDirectory);
220
- const listed = new Set(clientFiles);
221
- /** The file of each brotli copy that the function keeps, with the size of the file. */
222
- const brotliOnly = {};
219
+ const isCdnFile = (file) => prefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));
220
+ const clientFiles = new Map(filesUnder(clientDirectory));
221
+ const list = {
222
+ builtAt: Date.now(),
223
+ files: {},
224
+ brotliOnly: {}
225
+ };
223
226
  /**
224
227
  * Whether the function drops `file`, a file or a gzip copy, because the
225
228
  * brotli copy of its file takes its place. Why: the function then holds one
@@ -229,16 +232,20 @@ function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPath
229
232
  const brotliCopyOnly = (file) => {
230
233
  const name = basename(file);
231
234
  const original = name.startsWith(".") ? /^\.(?<name>.+)\.gz$/u.exec(name)?.groups?.name : name;
232
- return original != null && listed.has(join(dirname(file), original)) && listed.has(join(dirname(file), copyName(original, "br")));
235
+ return original != null && clientFiles.has(join(dirname(file), original)) && clientFiles.has(join(dirname(file), copyName(original, "br")));
233
236
  };
234
- for (const file of clientFiles) {
237
+ for (const [file, size] of clientFiles) {
235
238
  const from = join(clientDirectory, file);
236
239
  if (!isCdnFile(file)) {
237
- if (!brotliCopyOnly(file)) copyFile(from, join(functionDirectory, fromRoot(from)));
238
- else if (!basename(file).startsWith(".")) brotliOnly[`/${posix$1(file)}`] = statSync(from).size;
239
- } else if (!hasDotSegment(`/${posix$1(file)}`)) copyFile(from, join(output, "static", file));
240
+ if (!brotliCopyOnly(file)) {
241
+ copyFile(from, join(functionDirectory, fromRoot(from)));
242
+ list.files[`/${posix(file)}`] = size;
243
+ } else if (!basename(file).startsWith(".")) list.brotliOnly[`/${posix(file)}`] = size;
244
+ } else if (!hasDotSegment(`/${posix(file)}`)) copyFile(from, join(output, "static", file));
240
245
  }
241
- if (Object.keys(brotliOnly).length > 0) writeFileSync(join(functionDirectory, fromRoot(clientDirectory), BROTLI_ONLY_LIST), JSON.stringify(brotliOnly));
246
+ const listFile = join(functionDirectory, fromRoot(clientDirectory), FILE_LIST);
247
+ mkdirSync(dirname(listFile), { recursive: true });
248
+ writeFileSync(listFile, JSON.stringify(list));
242
249
  const serverDirectory = dirname(entryFile);
243
250
  const functionFile = join(serverDirectory, FUNCTION_FILE);
244
251
  cpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {
@@ -253,10 +260,9 @@ function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPath
253
260
  ].join("\n"));
254
261
  writeFileSync(join(functionDirectory, ".vc-config.json"), `${JSON.stringify({
255
262
  runtime: `nodejs${process.versions.node.split(".")[0]}.x`,
256
- handler: posix$1(fromRoot(functionFile)),
263
+ handler: posix(fromRoot(functionFile)),
257
264
  launcherType: "Nodejs",
258
265
  supportsResponseStreaming: true,
259
- environment: { [BUILT_AT]: String(Date.now()) },
260
266
  ...regions == null ? {} : { regions },
261
267
  ...memory == null ? {} : { memory },
262
268
  ...maxDuration == null ? {} : { maxDuration }
@@ -283,8 +289,8 @@ function checkCdnPaths(paths) {
283
289
  * `build.assetsDir` gets a one-year immutable cache. It also holds the
284
290
  * prerendered pages that the CDN serves, with `cdnPages`.
285
291
  * - `functions/index.func/`: one Node.js function that runs the pipeline for
286
- * each other request, with the whole server build and the rest of the
287
- * client build.
292
+ * each other request, with the whole server build, the rest of the client
293
+ * build, and the list of those client files, which the function serves.
288
294
  *
289
295
  * @example
290
296
  * appServer({ host: vercel() });
@@ -292,14 +298,12 @@ function checkCdnPaths(paths) {
292
298
  function vercel(options = {}) {
293
299
  checkCdnPaths(options.cdnPaths ?? []);
294
300
  return {
295
- name: "vercel",
296
301
  runtimeModule: "@ngrok/app-server/vercel",
297
- entryFileName: "app-server.js",
302
+ copies: ({ path, assetsPath }) => cdnPrefixes(options.cdnPaths ?? [], assetsPath).some((prefix) => path.startsWith(prefix)) ? [] : ["br"],
298
303
  output: (build) => {
299
304
  writeOutput(build, options);
300
305
  }
301
306
  };
302
307
  }
303
308
 
304
- export { vercel };
305
- //# sourceMappingURL=vercel-vite.js.map
309
+ export { vercel };
package/dist/vercel.d.ts CHANGED
@@ -1,13 +1,17 @@
1
- import { c as HostRuntime } from "./types-MgFtkNQW.js";
2
- import { t as AppServerEntry } from "./entry-DZTCaL3d.js";
1
+ import { t as AppServerEntry } from "./entry-DBq_3s8X.js";
2
+ import { s as HostRuntime } from "./types-KsKRDwAv.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  /**
5
- * The vercel host: one Vercel Function on Node.js. It reads the client build
6
- * from the function's files and keeps `requestContext()` in
7
- * `AsyncLocalStorage`, as the node host does. It has no listeners and no
8
- * lifecycle: Vercel starts and stops the function, and {@link handler} calls
9
- * the entry's `fetch`. It reads a file that the function keeps only as a
10
- * brotli copy through that copy (see `vercel()`).
5
+ * The vercel host: one Vercel Function on Node.js. It keeps
6
+ * `requestContext()` in `AsyncLocalStorage`, as the node host does. It has no
7
+ * listeners and no lifecycle: Vercel starts and stops the function, and
8
+ * {@link handler} calls the entry's `fetch`.
9
+ *
10
+ * It serves the files of the client build that the list of `vercel()` names
11
+ * ({@link FILE_LIST}), so a cold start reads one file, not each directory. It
12
+ * reads a file that the function keeps only as a brotli copy through that
13
+ * copy. A client build with no list, such as in development, comes from the
14
+ * file system, as on the node host.
11
15
  *
12
16
  * Why no gzip: Vercel's CDN compresses each response, with Brotli when the
13
17
  * client accepts it.
@@ -32,5 +36,4 @@ export declare const host: HostRuntime;
32
36
  * @example
33
37
  * export default hostModule.handler(appServer);
34
38
  */
35
- export declare function handler(entry: AppServerEntry): (incoming: IncomingMessage, outgoing: ServerResponse) => Promise<void>;
36
- //# sourceMappingURL=vercel.d.ts.map
39
+ export declare function handler(entry: AppServerEntry): (incoming: IncomingMessage, outgoing: ServerResponse) => Promise<void>;