@ngrok/app-server 0.3.5 → 0.4.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 (56) hide show
  1. package/README.md +41 -10
  2. package/dist/cli.js +3 -3
  3. package/dist/client.js +1 -1
  4. package/dist/{compress-CO0Nwc8x.js → compress-Cp5NfXCC.js} +138 -29
  5. package/dist/compress-Cp5NfXCC.js.map +1 -0
  6. package/dist/{create-server-C_90R50y.js → create-server-C63luLkn.js} +71 -30
  7. package/dist/create-server-C63luLkn.js.map +1 -0
  8. package/dist/{create-server-kxyhCdhv.d.ts → create-server-DKJ0wASH.d.ts} +33 -13
  9. package/dist/{entry-65IESBSA.js → entry-BSbsQ_kq.js} +13 -5
  10. package/dist/entry-BSbsQ_kq.js.map +1 -0
  11. package/dist/{entry-CNL4OsEn.d.ts → entry-C9bBcYeP.d.ts} +3 -3
  12. package/dist/index.d.ts +18 -5
  13. package/dist/index.js +6 -6
  14. package/dist/{load-entry-svVuPIFq.js → load-entry-DgZyPtoD.js} +4 -4
  15. package/dist/{load-entry-svVuPIFq.js.map → load-entry-DgZyPtoD.js.map} +1 -1
  16. package/dist/log-CW_g1pWk.js +304 -0
  17. package/dist/log-CW_g1pWk.js.map +1 -0
  18. package/dist/{node-Bgzhwix0.js → node-DBwgrye_.js} +2 -2
  19. package/dist/{node-Bgzhwix0.js.map → node-DBwgrye_.js.map} +1 -1
  20. package/dist/{node-DFI5TjTk.js → node-DiMwdTOC.js} +4 -4
  21. package/dist/{node-DFI5TjTk.js.map → node-DiMwdTOC.js.map} +1 -1
  22. package/dist/node.d.ts +1 -1
  23. package/dist/node.js +2 -2
  24. package/dist/react-router.d.ts +2 -2
  25. package/dist/react-router.js +3 -4
  26. package/dist/react-router.js.map +1 -1
  27. package/dist/request-context-BdAH1D-2.js +80 -0
  28. package/dist/request-context-BdAH1D-2.js.map +1 -0
  29. package/dist/{response-edge-D3CAjukJ.js → response-edge-7eUl2ewl.js} +3 -3
  30. package/dist/response-edge-7eUl2ewl.js.map +1 -0
  31. package/dist/{response-writer-5SOKsW3C.js → response-writer-CLtCseu5.js} +3 -3
  32. package/dist/{response-writer-5SOKsW3C.js.map → response-writer-CLtCseu5.js.map} +1 -1
  33. package/dist/{serve-DKoZxZj4.js → serve-DCaIBTM-.js} +2 -2
  34. package/dist/{serve-DKoZxZj4.js.map → serve-DCaIBTM-.js.map} +1 -1
  35. package/dist/{start-3_WlRLdK.js → start-D2IVWkow.js} +29 -13
  36. package/dist/start-D2IVWkow.js.map +1 -0
  37. package/dist/tanstack-start.d.ts +2 -2
  38. package/dist/tanstack-start.js +1 -1
  39. package/dist/{tcp-CKMCT9RP.js → tcp-B8aFGQRB.js} +2 -2
  40. package/dist/{tcp-CKMCT9RP.js.map → tcp-B8aFGQRB.js.map} +1 -1
  41. package/dist/testing.d.ts +2 -2
  42. package/dist/testing.js +4 -4
  43. package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D_52DJaQ.d.ts} +2 -2
  44. package/dist/{types-BKJxtIuj.d.ts → types-C_I3i62n.d.ts} +32 -4
  45. package/dist/vercel.d.ts +2 -2
  46. package/dist/vercel.js +4 -4
  47. package/package.json +1 -1
  48. package/dist/compress-CO0Nwc8x.js.map +0 -1
  49. package/dist/create-server-C_90R50y.js.map +0 -1
  50. package/dist/entry-65IESBSA.js.map +0 -1
  51. package/dist/log-C8LGQ23s.js +0 -149
  52. package/dist/log-C8LGQ23s.js.map +0 -1
  53. package/dist/request-context-BtQ87VYb.js +0 -40
  54. package/dist/request-context-BtQ87VYb.js.map +0 -1
  55. package/dist/response-edge-D3CAjukJ.js.map +0 -1
  56. package/dist/start-3_WlRLdK.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { g as Plugin, m as LogSink, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-BKJxtIuj.js";
2
- import { t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
1
+ import { C as SentResponse, g as LogSink, h as LogOptions, t as AppServerEnv, u as Listener, v as Plugin } from "./types-C_I3i62n.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-D_52DJaQ.js";
3
3
  import { Context, Hono } from "hono";
4
4
  /** Options for {@link accessLog}. */
5
5
  type AccessLogOptions = {
@@ -12,10 +12,13 @@ type AccessLogOptions = {
12
12
  /**
13
13
  * More attributes for each request line, such as the app's user ID. It
14
14
  * runs when the line goes out, with what went out. Read a response header
15
- * from `sent.headers`, not from `c.res`, which can lack the changes of the
15
+ * from `sent.headers`, not from `context.res`, which can lack the changes of the
16
16
  * header hooks.
17
17
  */
18
- attributes?: (context: Context<AppServerEnv>, sent: SentResponse) => Readonly<Record<string, unknown>>;
18
+ attributes?: (response: {
19
+ context: Context<AppServerEnv>;
20
+ sent: SentResponse;
21
+ }) => Readonly<Record<string, unknown>>;
19
22
  /**
20
23
  * Set `Server-Timing: app;dur=<ms>` on each HTML document: the time until
21
24
  * the response headers were ready. The browser's DevTools show it.
@@ -240,7 +243,10 @@ type ContentSecurityPolicyOptions = {
240
243
  * `context` is the request, so the policy can change by path. It runs in a
241
244
  * header hook, so it can run more than once for one request.
242
245
  */
243
- policy: (scriptSrc: string, context: Context<AppServerEnv>) => string;
246
+ policy: (document: {
247
+ scriptSrc: string;
248
+ context: Context<AppServerEnv>;
249
+ }) => string;
244
250
  };
245
251
  /**
246
252
  * Sets the `Content-Security-Policy` from `policy` on each HTML document. The
@@ -262,7 +268,7 @@ type ContentSecurityPolicyOptions = {
262
268
  * @example
263
269
  * defaultPlugins({
264
270
  * contentSecurityPolicy: {
265
- * policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
271
+ * policy: ({ scriptSrc }) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
266
272
  * },
267
273
  * });
268
274
  */
@@ -376,7 +382,10 @@ type PrerenderedOptions = {
376
382
  * Extra headers for a served file, by its URL path. They replace the
377
383
  * headers captured at build time.
378
384
  */
379
- headers?: (path: string, context: Context<AppServerEnv>) => Readonly<Record<string, string>> | undefined;
385
+ headers?: (file: {
386
+ path: string;
387
+ context: Context<AppServerEnv>;
388
+ }) => Readonly<Record<string, string>> | undefined;
380
389
  /**
381
390
  * Maps a request path to the URL path of the file to serve, for content
382
391
  * negotiation. Return the path unchanged to serve the usual file. The
@@ -385,7 +394,10 @@ type PrerenderedOptions = {
385
394
  * answer depends on a request header, add a `Vary` for it in a plugin.
386
395
  * With `markdownTwins: true`, a request that `rewrite` changes gets no twin.
387
396
  */
388
- rewrite?: (path: string, context: Context<AppServerEnv>) => string;
397
+ rewrite?: (request: {
398
+ path: string;
399
+ context: Context<AppServerEnv>;
400
+ }) => string;
389
401
  /**
390
402
  * Serves the markdown twin of a page, such as `/docs/button.md` for
391
403
  * `/docs/button`, to a request that {@link prefersMarkdown} accepts. A
@@ -417,7 +429,7 @@ type PrerenderedOptions = {
417
429
  * the rules of a request path.
418
430
  *
419
431
  * @example
420
- * prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });
432
+ * prerendered({ markdownTwins: { twinOf: ({ path }) => `/markdown${path}.md` } });
421
433
  */
422
434
  markdownTwins?: boolean | {
423
435
  twinOf: TwinOf;
@@ -448,7 +460,10 @@ type PrerenderedOptions = {
448
460
  cacheControl?: (path: string) => string | undefined;
449
461
  };
450
462
  /** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */
451
- type TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefined;
463
+ type TwinOf = (request: {
464
+ path: string;
465
+ context: Context<AppServerEnv>;
466
+ }) => string | undefined;
452
467
  /**
453
468
  * Serves the client build: prerendered pages at their own URL with a 200,
454
469
  * plus every other file in it. It sends no redirect. The `trailingSlash`
@@ -463,7 +478,7 @@ type TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefin
463
478
  *
464
479
  * @example
465
480
  * prerendered({
466
- * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
481
+ * headers: ({ path }) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
467
482
  * });
468
483
  */
469
484
  declare function prerendered(options?: PrerenderedOptions): Plugin;
@@ -562,6 +577,11 @@ type CreateServerOptions = {
562
577
  plugins?: readonly Plugin[];
563
578
  /** @default jsonSink() */
564
579
  logger?: LogSink;
580
+ /**
581
+ * Hooks that change each log line of the server and of `logger()`, such
582
+ * as to redact a field.
583
+ */
584
+ log?: LogOptions;
565
585
  /** @default the host's listeners, such as `[tcp()]` on the node host */
566
586
  listeners?: readonly Listener[];
567
587
  /**
@@ -607,6 +627,6 @@ type CreateServerOptions = {
607
627
  * app.get("/api/status", (c) => c.json({ ok: true }));
608
628
  * export default app;
609
629
  */
610
- declare function createServer({ plugins, logger, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
630
+ declare function createServer({ plugins, logger: sink, log, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
611
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 };
612
- //# sourceMappingURL=create-server-kxyhCdhv.d.ts.map
632
+ //# sourceMappingURL=create-server-DKJ0wASH.d.ts.map
@@ -1,6 +1,6 @@
1
- import { t as errorAttributes } from "./log-C8LGQ23s.js";
1
+ import { t as asError } from "./log-CW_g1pWk.js";
2
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-C_90R50y.js";
3
+ import { p as abortShutdownSignal, r as serverInternals } from "./create-server-C63luLkn.js";
4
4
  import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
5
5
 
6
6
  // src/core/static-pages.ts
@@ -297,13 +297,21 @@ function createEntry({ app, host, framework, clientDirectory }) {
297
297
  const runtime = await production();
298
298
  const server = await internals.listen(runtime, host.listeners?.());
299
299
  host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
300
- internals.logger.log("error", "shutdown failed", errorAttributes(error));
300
+ internals.logger.log({
301
+ level: "error",
302
+ message: "shutdown failed",
303
+ attributes: { error: asError(error) }
304
+ });
301
305
  throw error;
302
306
  }));
303
307
  },
304
308
  fetch: async (request, bindings) => {
305
309
  const runtime = await production().catch((error) => {
306
- internals.logger.log("error", "setup failed", errorAttributes(error));
310
+ internals.logger.log({
311
+ level: "error",
312
+ message: "setup failed",
313
+ attributes: { error: asError(error) }
314
+ });
307
315
  throw error;
308
316
  });
309
317
  return app.fetch(request, {
@@ -349,4 +357,4 @@ function isAppServerEntry(value) {
349
357
  }
350
358
 
351
359
  export { isAppServerEntry as n, createEntry as t };
352
- //# sourceMappingURL=entry-65IESBSA.js.map
360
+ //# sourceMappingURL=entry-BSbsQ_kq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-BSbsQ_kq.js","names":[],"sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { asError } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log({\n\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\tmessage: \"shutdown failed\",\n\t\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log({\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tmessage: \"setup failed\",\n\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAAM,UAAU,CACf;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EAAE,QAAQ;EAAgB,cAAc;CAAmB;AACrE,GACA;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EACR,QAAQ;EACR,mBAAmB;EACnB,eAAe;EACf,QAAQ;EACR,SAAS;EACT,cAAc;EACd,oBAAoB;EACpB,uBAAuB;EACvB,8BAA8B;CAC/B;AACD,CACD;;;;;AAMA,eAAe,OACd,OACA,MACA,EACC,QACA,UACA,WAMiB;CAElB,MAAM,UAAU,IAAI,QAAQ;EAAE,GAAG,OAAO;EAAS,MAAM,IAAI,IAAI,OAAO,MAAM,CAAC,CAAC;CAAK,CAAC;CACpF,KAAK,MAAM,QAAQ,UAClB,IAAI,QAAQ,SAAS,IAAI,GACxB,QAAQ,IAAI,MAAM,OAAO,YAAY;MAErC,QAAQ,OAAO,IAAI;CAGrB,MAAM,UAAU,IAAI,QAAQ,GAAG,OAAO,SAAS,OAAO,OAAO,SAAS,EAAE,QAAQ,CAAC;CACjF,IAAI;CACJ,MAAM,WAAW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D;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
@@ -1,5 +1,5 @@
1
- import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, h as Mode, r as FetchHandler, t as AppServerEnv } from "./types-BKJxtIuj.js";
2
- import { t as AppServer } from "./create-server-kxyhCdhv.js";
1
+ import { _ as Mode, a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, r as FetchHandler, t as AppServerEnv } from "./types-C_I3i62n.js";
2
+ import { t as AppServer } from "./create-server-DKJ0wASH.js";
3
3
  import { MiddlewareHandler } from "hono";
4
4
  /** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */
5
5
  type CdnPage = {
@@ -91,4 +91,4 @@ type CreateEntryOptions = {
91
91
  */
92
92
  declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
93
93
  export { CreateEntryOptions as n, createEntry as r, AppServerEntry as t };
94
- //# sourceMappingURL=entry-CNL4OsEn.d.ts.map
94
+ //# sourceMappingURL=entry-C9bBcYeP.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { C as SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } from "./types-BKJxtIuj.js";
2
- import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-kxyhCdhv.js";
3
- import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
4
- import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-CNL4OsEn.js";
1
+ import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Mode, a as FrameworkRuntime, b as RequestLogger, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as LogSink, h as LogOptions, i as FileInfo, l as Lifecycle, m as LogLine, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as Plugin, w as ServerBindings, x as RequestStore, y as RequestContext } from "./types-C_I3i62n.js";
2
+ import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-DKJ0wASH.js";
3
+ import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-D_52DJaQ.js";
4
+ import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-C9bBcYeP.js";
5
5
  import { Context, Next } from "hono";
6
6
  /** One server-sent event. */
7
7
  type ServerSentEvent = {
@@ -168,6 +168,19 @@ export declare function prefersMarkdown(request: Request): boolean;
168
168
  * }
169
169
  */
170
170
  export declare function requestContext(): RequestContext | undefined;
171
+ /**
172
+ * The logger of the request that runs. Outside a request, such as at module
173
+ * load or in a prerender pass, it gives a logger that writes to the sink and
174
+ * the hooks of the last `createServer` call, else to `jsonSink()`.
175
+ *
176
+ * @example
177
+ * import { logger } from "@ngrok/app-server";
178
+ *
179
+ * export async function loader() {
180
+ * logger().info("loading the dashboard", { "usr.id": userId });
181
+ * }
182
+ */
183
+ export declare function logger(): RequestLogger;
171
184
  /**
172
185
  * A signal that aborts when the server starts to shut down. Read it for each
173
186
  * request: each start of a server makes a new one. A handler that
@@ -179,5 +192,5 @@ export declare function requestContext(): RequestContext | undefined;
179
192
  * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
180
193
  */
181
194
  export declare function shutdownSignal(): AbortSignal;
182
- export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type FrameworkRuntimeFactory, type HeaderHook, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogSink, type Mode, type NoindexOptions, PUBLIC_ENV_SCRIPT_ID, type Plugin, type PrerenderedOptions, type RedirectRule, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestStore, ResponseEdge, type ResponseHeaders, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
195
+ export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type FrameworkRuntimeFactory, type HeaderHook, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogLine, type LogOptions, type LogSink, type Mode, type NoindexOptions, PUBLIC_ENV_SCRIPT_ID, type Plugin, type PrerenderedOptions, type RedirectRule, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestStore, ResponseEdge, type ResponseHeaders, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
183
196
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as requestContext } from "./request-context-BtQ87VYb.js";
1
+ import { i as jsonSink } from "./log-CW_g1pWk.js";
2
+ import { r as requestContext, t as logger } from "./request-context-BdAH1D-2.js";
2
3
  import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
3
4
  import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
4
- import { r as jsonSink } from "./log-C8LGQ23s.js";
5
- import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
6
- import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-C_90R50y.js";
7
- import { t as createEntry } from "./entry-65IESBSA.js";
5
+ import { t as ResponseEdge } from "./response-edge-7eUl2ewl.js";
6
+ import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-C63luLkn.js";
7
+ import { t as createEntry } from "./entry-BSbsQ_kq.js";
8
8
 
9
9
  // src/core/event-stream.ts
10
10
  function formatEvent({ data, event, id }) {
@@ -197,5 +197,5 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
197
197
  });
198
198
  }
199
199
 
200
- export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
200
+ export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, logger, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
201
201
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
- import { t as createServer } from "./create-server-C_90R50y.js";
2
- import { n as isAppServerEntry, t as createEntry } from "./entry-65IESBSA.js";
3
- import { t as host } from "./node-DFI5TjTk.js";
1
+ import { t as createServer } from "./create-server-C63luLkn.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-BSbsQ_kq.js";
3
+ import { t as host } from "./node-DiMwdTOC.js";
4
4
 
5
5
  // src/cli/load-entry.ts
6
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -34,4 +34,4 @@ async function loadEntry(build) {
34
34
  }
35
35
 
36
36
  export { loadEntry as t };
37
- //# sourceMappingURL=load-entry-svVuPIFq.js.map
37
+ //# sourceMappingURL=load-entry-DgZyPtoD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-svVuPIFq.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-DgZyPtoD.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
@@ -0,0 +1,304 @@
1
+ // src/core/log.ts
2
+ /** The standard output (stdout) lines that wait for {@link flushLogs}. */
3
+ let pending = "";
4
+ /** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */
5
+ let exiting = false;
6
+ process.on("exit", () => {
7
+ exiting = true;
8
+ process.stdout._handle?.setBlocking?.(true);
9
+ for (const line of pending.match(/[^\n]*\n/gu) ?? []) process.stdout.write(line);
10
+ pending = "";
11
+ });
12
+ /**
13
+ * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it
14
+ * before the process exits.
15
+ */
16
+ function flushLogs() {
17
+ if (pending === "") return;
18
+ const lines = pending;
19
+ pending = "";
20
+ process.stdout.write(lines);
21
+ }
22
+ /**
23
+ * Adds `line` to the next stdout write. Why one write for each turn of the
24
+ * event loop: a write to a pipe, such as stdout in Docker, is a system call,
25
+ * and under load many requests end in one turn.
26
+ */
27
+ function writeStdout(line) {
28
+ if (exiting) {
29
+ process.stdout.write(line);
30
+ return;
31
+ }
32
+ if (pending === "") setImmediate(flushLogs);
33
+ pending += line;
34
+ }
35
+ /** The end of a {@link jsonSink} line whose attributes have no JSON. */
36
+ const NO_JSON = "\"log.error\":\"attributes not written as JSON\"}";
37
+ /**
38
+ * A log sink that writes one JSON object per line. Each line has `time`,
39
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
40
+ * standard attributes. The default writes the lines of one event-loop turn
41
+ * to stdout at the end of the turn.
42
+ *
43
+ * @param write - Where each line goes. Defaults to stdout.
44
+ *
45
+ * @example
46
+ * createServer({ logger: jsonSink() });
47
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
48
+ */
49
+ function jsonSink(write = writeStdout) {
50
+ return { log: ({ level, message, attributes }) => {
51
+ const time = isoNow();
52
+ const head = `{"time":"${time}","level":"${level}","message":${JSON.stringify(message)}`;
53
+ const ownKeys = "time" in attributes || "level" in attributes || "message" in attributes;
54
+ const json = toJson(ownKeys ? {
55
+ time,
56
+ level,
57
+ message,
58
+ ...attributes
59
+ } : attributes);
60
+ let line = `${head},${NO_JSON}`;
61
+ if (json != null) line = ownKeys ? json : `${head}${json === "{}" ? "}" : `,${json.slice(1)}`}`;
62
+ write(`${line}\n`);
63
+ } };
64
+ }
65
+ /**
66
+ * A log sink that writes one line of `key=value` pairs per event, in the text
67
+ * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control
68
+ * character is quoted, so an escape sequence cannot reach the terminal.
69
+ * `app-server start` uses it, because a person reads those lines.
70
+ *
71
+ * @param write - Where each line goes. Defaults to stdout, at once. Why not
72
+ * one write for each turn: the lines then keep their order with Vite's lines.
73
+ *
74
+ * @example
75
+ * textSink().log({ level: "info", message: "port in use, trying the next port", attributes: { "server.port": 3000 } });
76
+ * // time=2026-11-11T12:00:00.000Z level=INFO msg="port in use, trying the next port" server.port=3000
77
+ */
78
+ function textSink(write = (line) => {
79
+ process.stdout.write(line);
80
+ }) {
81
+ return { log: ({ level, message, attributes }) => {
82
+ let line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;
83
+ for (const [key, value] of Object.entries(attributes)) line += ` ${key}=${textValue(value)}`;
84
+ write(`${line}\n`);
85
+ } };
86
+ }
87
+ /** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */
88
+ function textValue(value) {
89
+ if (typeof value === "bigint") return `${value}n`;
90
+ const text = typeof value === "string" ? value : toJson(value) ?? String(value);
91
+ return /^[^\s"=\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);
92
+ }
93
+ /**
94
+ * `value` as JSON, with each bigint as a string such as `"1n"`, and each
95
+ * cycle as `"[Circular]"`. Gives `undefined` for a value with no JSON, such
96
+ * as a function, or one whose `toJSON` throws. Why try the plain call first:
97
+ * the replacer runs for each value, and a log line seldom needs it.
98
+ */
99
+ function toJson(value) {
100
+ try {
101
+ return JSON.stringify(value);
102
+ } catch {
103
+ try {
104
+ return JSON.stringify(value, safeReplacer());
105
+ } catch {
106
+ return;
107
+ }
108
+ }
109
+ }
110
+ /** A `JSON.stringify` replacer for {@link toJson}. */
111
+ function safeReplacer() {
112
+ const ancestors = [];
113
+ return function replace(_key, value) {
114
+ if (typeof value === "bigint") return `${value}n`;
115
+ if (typeof value !== "object" || value == null) return value;
116
+ while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
117
+ if (ancestors.includes(value)) return "[Circular]";
118
+ ancestors.push(value);
119
+ return value;
120
+ };
121
+ }
122
+ /** The millisecond of the last `time`, and its ISO string. */
123
+ let lastMs = NaN;
124
+ let lastTime = "";
125
+ /** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */
126
+ let lastSecond = NaN;
127
+ let secondPrefix = "";
128
+ /**
129
+ * The time now, as `new Date().toISOString()` gives it. Why keep the last
130
+ * time: under load, many lines share a millisecond. Why keep the prefix of
131
+ * the second: `toISOString()` costs more than the rest of a line.
132
+ */
133
+ function isoNow() {
134
+ const now = Date.now();
135
+ if (now !== lastMs) {
136
+ lastMs = now;
137
+ const second = Math.floor(now / 1e3);
138
+ if (second !== lastSecond) {
139
+ lastSecond = second;
140
+ secondPrefix = new Date(now).toISOString().slice(0, -4);
141
+ }
142
+ lastTime = `${secondPrefix}${String(now - second * 1e3).padStart(3, "0")}Z`;
143
+ }
144
+ return lastTime;
145
+ }
146
+ /**
147
+ * A thrown value as an `Error`, so a log line gives it the `error.*` fields.
148
+ * Hono sends only an `Error` to `onError`, and rethrows any other value.
149
+ */
150
+ function asError(error) {
151
+ return error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
152
+ }
153
+ /** The fields of an error that {@link errorFields} writes on its own, not as an own field. */
154
+ const ERROR_KEYS = /* @__PURE__ */ new Set([
155
+ "name",
156
+ "message",
157
+ "stack",
158
+ "cause"
159
+ ]);
160
+ /**
161
+ * The dotted fields of `error` under `prefix`: `kind`, `message`, `stack`,
162
+ * each own field, such as `code`, the `cause` chain, and the `errors` of an
163
+ * `AggregateError`. An error with `toJSON` gives its own fields from it. An
164
+ * error that is its own ancestor in the chain gives `"[Circular]"`.
165
+ *
166
+ * @example
167
+ * errorFields(new Error("no row", { cause: new RangeError("bad id") }), "error");
168
+ * // => { "error.kind": "Error", "error.message": "no row", "error.stack": "…",
169
+ * // "error.cause.kind": "RangeError", "error.cause.message": "bad id", "error.cause.stack": "…" }
170
+ */
171
+ function errorFields(error, prefix) {
172
+ const ancestors = [];
173
+ const addError = (fields, base, current) => {
174
+ const at = (key) => base === "" ? key : `${base}.${key}`;
175
+ const add = (key, value) => {
176
+ if (!(value instanceof Error)) fields[key] = value;
177
+ else if (ancestors.includes(value)) fields[key] = "[Circular]";
178
+ else addError(fields, key, value);
179
+ };
180
+ ancestors.push(current);
181
+ fields[at("kind")] = current.name;
182
+ fields[at("message")] = current.message;
183
+ fields[at("stack")] = current.stack;
184
+ const toJSON = "toJSON" in current ? current.toJSON : void 0;
185
+ const own = typeof toJSON === "function" ? Reflect.apply(toJSON, current, []) : current;
186
+ if (typeof own === "object" && own != null) {
187
+ for (const [key, value] of Object.entries(own)) if (!ERROR_KEYS.has(key)) add(at(key), value);
188
+ }
189
+ if (current.cause != null) add(at("cause"), current.cause);
190
+ if (current instanceof AggregateError) fields[at("errors")] = current.errors.map((member) => {
191
+ if (!(member instanceof Error)) return member;
192
+ if (ancestors.includes(member)) return "[Circular]";
193
+ const memberFields = {};
194
+ addError(memberFields, "", member);
195
+ return memberFields;
196
+ });
197
+ ancestors.pop();
198
+ };
199
+ const fields = {};
200
+ addError(fields, prefix, error);
201
+ return fields;
202
+ }
203
+ /** `attributes` with each `Error` value replaced by its fields, after the `change` hook. */
204
+ function flattenErrors(attributes, change) {
205
+ let hasError = false;
206
+ for (const key in attributes) if (attributes[key] instanceof Error) {
207
+ hasError = true;
208
+ break;
209
+ }
210
+ if (!hasError) return attributes;
211
+ const flat = {};
212
+ for (const [key, value] of Object.entries(attributes)) if (value instanceof Error) {
213
+ const fields = errorFields(value, key);
214
+ Object.assign(flat, change == null ? fields : change({
215
+ error: value,
216
+ prefix: key,
217
+ fields
218
+ }));
219
+ } else flat[key] = value;
220
+ return flat;
221
+ }
222
+ /**
223
+ * A sink that writes each line to `sink`, after it replaces each `Error`
224
+ * value with its fields, and then runs the `attributes` hook.
225
+ *
226
+ * @example
227
+ * hookSink(jsonSink()).log({ level: "error", message: "failed", attributes: { error: new Error("boom") } });
228
+ * // {"time":"…","level":"error","message":"failed","error.kind":"Error","error.message":"boom","error.stack":"…"}
229
+ */
230
+ function hookSink(sink, { attributes: changeAttributes, error: changeError } = {}) {
231
+ return { log: (line) => {
232
+ const flat = flattenErrors(line.attributes, changeError);
233
+ const flatLine = flat === line.attributes ? line : {
234
+ ...line,
235
+ attributes: flat
236
+ };
237
+ sink.log(changeAttributes == null ? flatLine : {
238
+ ...flatLine,
239
+ attributes: changeAttributes(flatLine)
240
+ });
241
+ } };
242
+ }
243
+ /**
244
+ * A logger that writes to `sink`. `withBase` gives the attributes of each
245
+ * line as a new object, from the attributes that the caller gives.
246
+ */
247
+ function sinkLogger(sink, withBase = (attributes) => ({ ...attributes })) {
248
+ return {
249
+ debug: (message, attributes = {}) => {
250
+ sink.log({
251
+ level: "debug",
252
+ message,
253
+ attributes: withBase(attributes)
254
+ });
255
+ },
256
+ info: (message, attributes = {}) => {
257
+ sink.log({
258
+ level: "info",
259
+ message,
260
+ attributes: withBase(attributes)
261
+ });
262
+ },
263
+ warn: (message, attributes = {}) => {
264
+ sink.log({
265
+ level: "warn",
266
+ message,
267
+ attributes: withBase(attributes)
268
+ });
269
+ },
270
+ error: (message, attributes = {}) => {
271
+ sink.log({
272
+ level: "error",
273
+ message,
274
+ attributes: withBase(attributes)
275
+ });
276
+ }
277
+ };
278
+ }
279
+ /**
280
+ * A logger whose lines carry the request's ID, method, path, and
281
+ * `logAttributes`. These fields win over a caller's field of the same name.
282
+ */
283
+ function requestLogger(sink, context) {
284
+ return sinkLogger(sink, (attributes) => {
285
+ const requestId = context.get("requestId");
286
+ const { method, path } = context.req;
287
+ const logAttributes = context.get("logAttributes");
288
+ const line = {
289
+ "http.request_id": requestId,
290
+ "http.method": method,
291
+ "http.url_details.path": path,
292
+ ...logAttributes,
293
+ ...attributes
294
+ };
295
+ line["http.request_id"] = requestId;
296
+ line["http.method"] = method;
297
+ line["http.url_details.path"] = path;
298
+ Object.assign(line, logAttributes);
299
+ return line;
300
+ });
301
+ }
302
+
303
+ export { requestLogger as a, jsonSink as i, flushLogs as n, sinkLogger as o, hookSink as r, textSink as s, asError as t };
304
+ //# sourceMappingURL=log-CW_g1pWk.js.map