@ngrok/app-server 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +659 -70
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/build-manifest-UDNk81Ce.js +63 -0
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  7. package/dist/bun-BCz6K_Xv.js.map +1 -0
  8. package/dist/cli.js +47 -27
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client.d.ts +141 -0
  11. package/dist/client.js +326 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/compression-7_gToa8R.js +97 -0
  14. package/dist/compression-7_gToa8R.js.map +1 -0
  15. package/dist/create-server-iE1-s6Bi.js +1409 -0
  16. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  17. package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-DZ3qo7qF.js +116 -0
  20. package/dist/entry-DZ3qo7qF.js.map +1 -0
  21. package/dist/entry-DmJEqVfd.d.ts +622 -0
  22. package/dist/gzip-Doi4wqjX.js +294 -0
  23. package/dist/gzip-Doi4wqjX.js.map +1 -0
  24. package/dist/header-hook-Vzw9J9BY.js +159 -0
  25. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  26. package/dist/index-Bo5G9LuQ.d.ts +127 -0
  27. package/dist/index.d.ts +110 -95
  28. package/dist/index.js +56 -57
  29. package/dist/index.js.map +1 -1
  30. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  31. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  32. package/dist/load-entry-AfYS_zS9.js +37 -0
  33. package/dist/load-entry-AfYS_zS9.js.map +1 -0
  34. package/dist/log-BP6xXXZl.js +122 -0
  35. package/dist/log-BP6xXXZl.js.map +1 -0
  36. package/dist/node-BFH82eeL.js +333 -0
  37. package/dist/node-BFH82eeL.js.map +1 -0
  38. package/dist/node-tBVQPjQv.js +41 -0
  39. package/dist/node-tBVQPjQv.js.map +1 -0
  40. package/dist/node-vite.d.ts +11 -0
  41. package/dist/node-vite.js +3 -0
  42. package/dist/node.d.ts +86 -0
  43. package/dist/node.js +4 -0
  44. package/dist/react-router-vite.d.ts +10 -0
  45. package/dist/react-router-vite.js +3 -0
  46. package/dist/react-router.d.ts +11 -24
  47. package/dist/react-router.js +21 -30
  48. package/dist/react-router.js.map +1 -1
  49. package/dist/request-context-BtQ87VYb.js +40 -0
  50. package/dist/request-context-BtQ87VYb.js.map +1 -0
  51. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  52. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  53. package/dist/response-writer-B7FoJjEE.js +289 -0
  54. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  55. package/dist/script-hashes-hqUk6kG7.js +53 -0
  56. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  57. package/dist/serve-CDNgThjk.js +29 -0
  58. package/dist/serve-CDNgThjk.js.map +1 -0
  59. package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
  60. package/dist/start-TLIprD74.js.map +1 -0
  61. package/dist/static-files-Beju9riB.js +302 -0
  62. package/dist/static-files-Beju9riB.js.map +1 -0
  63. package/dist/tanstack-start-vite.d.ts +12 -0
  64. package/dist/tanstack-start-vite.js +3 -0
  65. package/dist/tanstack-start.d.ts +34 -0
  66. package/dist/tanstack-start.js +41 -0
  67. package/dist/tanstack-start.js.map +1 -0
  68. package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
  69. package/dist/tcp-Dd1Mt6sN.js.map +1 -0
  70. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  71. package/dist/types-DLYxYS6M.d.ts +392 -0
  72. package/dist/vercel-vite.d.ts +35 -0
  73. package/dist/vercel-vite.js +142 -0
  74. package/dist/vercel-vite.js.map +1 -0
  75. package/dist/vercel.d.ts +35 -0
  76. package/dist/vercel.js +89 -0
  77. package/dist/vercel.js.map +1 -0
  78. package/dist/vite-B-GfswoH.js +22 -0
  79. package/dist/vite-B-GfswoH.js.map +1 -0
  80. package/dist/vite-D4hfj3ph.js +19 -0
  81. package/dist/vite-D4hfj3ph.js.map +1 -0
  82. package/dist/vite-DyrhyKEr.js +25 -0
  83. package/dist/vite-DyrhyKEr.js.map +1 -0
  84. package/dist/vite-iioAoxSt.js +752 -0
  85. package/dist/vite-iioAoxSt.js.map +1 -0
  86. package/dist/vite.d.ts +2 -27
  87. package/dist/vite.js +2 -2
  88. package/package.json +50 -4
  89. package/dist/bun-DCGnDEPn.js.map +0 -1
  90. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  91. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  92. package/dist/deno-BnMfk2n1.js.map +0 -1
  93. package/dist/entry-CIpwaayZ.d.ts +0 -293
  94. package/dist/entry-ChjmFwX5.js +0 -755
  95. package/dist/entry-ChjmFwX5.js.map +0 -1
  96. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  97. package/dist/node-2wWBMFeO.js +0 -3
  98. package/dist/node-79my3Uix.js +0 -58
  99. package/dist/node-79my3Uix.js.map +0 -1
  100. package/dist/serve-ByeedcRB.js +0 -16
  101. package/dist/serve-ByeedcRB.js.map +0 -1
  102. package/dist/start-BVMb8Pyt.js.map +0 -1
  103. package/dist/tcp-Dau_IONd.js.map +0 -1
  104. package/dist/vite-CrNqpoeK.js +0 -102
  105. package/dist/vite-CrNqpoeK.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { C as NodeMiddleware, D as SetupInfo, E as ServerBindings, O as StartedListener, S as LogSink, T as RequestLogger, _ as FetchHandler, a as DefaultPluginsOptions, b as ListenerBindings, c as defaultPlugins, d as prerendered, f as RequestIdOptions, g as AppServerEnv, h as accessLog, i as CreateServerOptions, l as PrerenderedOptions, m as AccessLogOptions, n as createEntry, o as RunningServer, p as requestId, r as AppServer, s as createServer, t as AppServerEntry, u as assets, v as FrameworkAdapter, w as Plugin, x as LogLevel, y as Listener } from "./entry-CIpwaayZ.js";
2
- import { Context } from "hono";
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-DLYxYS6M.js";
2
+ import { A as BuildIdOptions, C as SecurityHeadersOptions, D as redirects, E as RedirectRule, M as AccessLogOptions, N as accessLog, O as HealthOptions, S as SecurityHeaderValues, T as securityHeaders, _ as StandardSchemaV1, a as CreateServerOptions, b as requestId, c as createServer, d as assets, f as prerendered, g as RuntimeEnvOptions, h as RuntimeEnv, i as AppServer, j as buildId, k as health, l as defaultPlugins, m as PUBLIC_ENV_SCRIPT_ID, n as CreateEntryOptions, o as DefaultPluginsOptions, p as InferOutput, r as createEntry, s as RunningServer, t as AppServerEntry, u as PrerenderedOptions, v as runtimeEnv, w as contentSecurityPolicy, x as ContentSecurityPolicyOptions, y as RequestIdOptions } from "./entry-DmJEqVfd.js";
3
+ import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
4
+ import { Context, Next } from "hono";
3
5
  /** One server-sent event. */
4
6
  type ServerSentEvent = {
5
7
  data: string;
@@ -40,10 +42,29 @@ type EventStreamOptions = {
40
42
  * }
41
43
  */
42
44
  export declare function eventStream({ signal, heartbeatMs, headers }: EventStreamOptions, produce: (sink: EventStreamSink) => void | Promise<void>): Response;
45
+ /**
46
+ * Runs `hook` on the response headers after the later stages. In an app
47
+ * server, the hook changes the head once, where the response leaves, so the
48
+ * response needs no copy. That run comes after the code that each stage runs
49
+ * after its `next()`, so a stage can decide there what its hook does. A hook
50
+ * that throws gives a 500. See {@link HeaderHook} for the order of the hooks
51
+ * and the views that also run them.
52
+ *
53
+ * @example
54
+ * const frameOptions: Plugin = {
55
+ * name: "frame-options",
56
+ * middleware: async (c, next) =>
57
+ * withHeaderHook(c, next, (response) => {
58
+ * response.set("X-Frame-Options", "DENY");
59
+ * }),
60
+ * };
61
+ */
62
+ export declare function withHeaderHook(context: Context<AppServerEnv>, next: Next, hook: HeaderHook): Promise<void>;
43
63
  /**
44
64
  * A log sink that writes one JSON object per line. Each line has `time`,
45
65
  * `level`, `message`, and the flat attributes, which Datadog reads as its
46
- * standard attributes.
66
+ * standard attributes. The default writes the lines of one event-loop turn
67
+ * to stdout at the end of the turn.
47
68
  *
48
69
  * @param write - Where each line goes. Defaults to stdout.
49
70
  *
@@ -52,97 +73,109 @@ export declare function eventStream({ signal, heartbeatMs, headers }: EventStrea
52
73
  * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
53
74
  */
54
75
  export declare function jsonSink(write?: (line: string) => void): LogSink;
55
- /** Options for {@link buildId}. */
56
- type BuildIdOptions = {
57
- /** @default "X-Build-Id" */
58
- header?: string;
59
- /** The deployed build, such as the image tag. Read it from the runtime env, not the build. */
60
- value: string;
76
+ /** Options for {@link bodyLimit}. */
77
+ type BodyLimitOptions = {
78
+ /** The largest request body, in bytes. */
79
+ maxBytes: number;
61
80
  };
62
81
  /**
63
- * Sets a build ID header on documents and React Router `.data` responses, so
64
- * a client can see that a deploy happened under it.
82
+ * Sends a 413 for a request body that is larger than `maxBytes`. A request
83
+ * whose `Content-Length` is too large gets the 413 before the app reads the
84
+ * body, and a request whose `Content-Length` fits goes on unchanged. A
85
+ * streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response
86
+ * becomes a 413. When the app streams the body into its response, the
87
+ * response stream errors. A `maxBytes` that is not a whole number of 0 or
88
+ * more stops startup.
89
+ *
90
+ * Why not `hono/body-limit`: it reads a streamed body into memory before the
91
+ * next stage runs, so an upload cannot stream.
65
92
  *
66
93
  * @example
67
- * buildId({ value: env.values.PUBLIC_APP_VERSION });
94
+ * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });
68
95
  */
69
- export declare function buildId({ header, value }: BuildIdOptions): Plugin;
70
- type StandardIssue = {
71
- readonly message: string;
72
- readonly path?: ReadonlyArray<PropertyKey | {
73
- readonly key: PropertyKey;
74
- }> | undefined;
75
- };
76
- type StandardResult<Output> = {
77
- readonly value: Output;
78
- readonly issues?: undefined;
79
- } | {
80
- readonly issues: ReadonlyArray<StandardIssue>;
81
- };
82
- /** A schema that follows the Standard Schema interface, such as a zod object. */
83
- type StandardSchemaV1<Input = unknown, Output = Input> = {
84
- readonly "~standard": {
85
- readonly version: 1;
86
- readonly vendor: string;
87
- readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
88
- readonly types?: {
89
- readonly input: Input;
90
- readonly output: Output;
91
- } | undefined;
92
- };
93
- };
94
- /** The parsed type of a Standard Schema. */
95
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
96
- /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
97
- export declare const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
98
- /** Options for {@link runtimeEnv}. */
99
- type RuntimeEnvOptions = {
100
- /** @default process.env */
101
- source?: Readonly<Record<string, string | undefined>>;
102
- /**
103
- * Values whose names start with this prefix reach the browser.
104
- * @default "PUBLIC_"
105
- */
106
- publicPrefix?: string;
107
- };
108
- /** The plugin that {@link runtimeEnv} returns, with the parsed values. */
109
- type RuntimeEnv<Values> = Plugin & {
110
- /** The parsed values. The first read parses, and a bad value throws. */
111
- readonly values: Values;
112
- /** The parsed values whose names start with the public prefix. */
113
- readonly publicValues: Readonly<Record<string, unknown>>;
114
- };
96
+ export declare function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin;
115
97
  /**
116
- * Validates the environment once, at startup, against a schema. A missing or
117
- * bad value stops the server with a message that names it. The typed values
118
- * are on `.values`.
119
- *
120
- * The values whose names start with `PUBLIC_` go into each HTML document,
121
- * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
122
- * So one image serves every environment, and a prerendered page never keeps
123
- * the values of the build. Put this plugin before the static stages, so it
124
- * sees the prerendered pages.
98
+ * Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search
99
+ * engine does not index a preview deploy. Turn it on from the environment
100
+ * with the `noindex` option of `defaultPlugins()`, which puts it before the
101
+ * static stages, so it also sees prerendered pages.
125
102
  *
126
103
  * @example
127
- * export const env = runtimeEnv(
128
- * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
129
- * );
130
- * env.values.SESSION_KEY; // => string
104
+ * defaultPlugins({ noindex: process.env.PREVIEW === "1" });
105
+ */
106
+ export declare function noindex(): Plugin;
107
+ /**
108
+ * Sets `Cache-Control: private, no-cache` on each HTML document and each
109
+ * framework data response, such as a React Router `.data` request, that has
110
+ * no `Cache-Control`. A shared cache then never keeps a page or loader data
111
+ * that the server rendered for one user. A response with its own
112
+ * `Cache-Control` keeps it. A resource route that sends per-user JSON sets
113
+ * its own `Cache-Control`.
131
114
  *
132
- * // In the browser:
133
- * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
115
+ * Put it after the static stages, so it sees only the responses of the app's
116
+ * routes and the framework. `defaultPlugins()` puts it last.
117
+ *
118
+ * @example
119
+ * createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });
134
120
  */
135
- export declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Schema, { source, publicPrefix }?: RuntimeEnvOptions): RuntimeEnv<InferOutput<Schema>>;
121
+ export declare function privateDocuments(): Plugin;
136
122
  /**
137
123
  * Gzips text responses and flushes after each chunk, so a streamed page shell
138
- * or a server-sent event reaches the client at once. `hono/compress` holds a
124
+ * or a server-sent event reaches the client at once. Chunks that the body has
125
+ * queued together are one chunk, up to 16 KiB. `hono/compress` holds a
139
126
  * stream until it ends. Skips a response that is already encoded, a partial
140
- * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.
127
+ * response, one marked `no-transform`, and one whose `Content-Length` is
128
+ * under 1 KiB. It adds `Accept-Encoding` to the `Vary` of each response that
129
+ * it can gzip. The host gives the gzip stream. On a host with none, the
130
+ * plugin does nothing.
141
131
  *
142
132
  * @example
143
133
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
144
134
  */
145
135
  export declare function streamingCompress(): Plugin;
136
+ /**
137
+ * Whether a request asks for markdown before HTML, per
138
+ * https://acceptmarkdown.com. Use it to choose between the HTML and the
139
+ * markdown answer for one URL.
140
+ *
141
+ * The rules:
142
+ *
143
+ * - Only an explicit `text/markdown` range counts for markdown. A wildcard,
144
+ * such as `*\/*` or `text/*`, never selects markdown, so a browser and a
145
+ * client with no `Accept` get HTML.
146
+ * - `text/markdown;q=0` refuses markdown.
147
+ * - The `q` of markdown must be equal to or higher than the `q` of HTML. The
148
+ * `q` of HTML comes from the most specific range that matches it:
149
+ * `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
150
+ * the client named it.
151
+ * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
152
+ * than a range with no charset, and a range with another charset does not
153
+ * match. Other parameters, such as `variant`, do not change the match.
154
+ * - Media types and parameter names are not case-sensitive. A quoted
155
+ * parameter value can hold a `,` or a `;`.
156
+ *
157
+ * When the answer for a URL depends on this function, send `Vary: Accept` on
158
+ * both the HTML and the markdown answer. Else a shared cache can give the
159
+ * markdown to a browser.
160
+ *
161
+ * @example
162
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
163
+ * // => true
164
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
165
+ * // => false
166
+ */
167
+ export declare function prefersMarkdown(request: Request): boolean;
168
+ /**
169
+ * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
170
+ * outside a server request, such as in a prerender pass, or on a host with no
171
+ * request storage.
172
+ *
173
+ * @example
174
+ * export async function loader() {
175
+ * requestContext()?.logger.info("loading the dashboard");
176
+ * }
177
+ */
178
+ export declare function requestContext(): RequestContext | undefined;
146
179
  /**
147
180
  * A signal that aborts when the server starts to shut down. Read it for each
148
181
  * request: each start of a server makes a new one. A handler that
@@ -154,23 +187,5 @@ export declare function streamingCompress(): Plugin;
154
187
  * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
155
188
  */
156
189
  export declare function shutdownSignal(): AbortSignal;
157
- /** Options for {@link tcp}. */
158
- type TcpOptions = {
159
- /** @default the `PORT` environment variable, else 3000 */
160
- port?: number;
161
- /** @default the `HOST` environment variable, else every interface */
162
- host?: string;
163
- /** @default 95000 */
164
- idleTimeoutMs?: number;
165
- };
166
- /**
167
- * The default listener: a TCP port, served by the runtime's own HTTP server
168
- * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
169
- * `PORT` and `HOST` when it starts.
170
- *
171
- * @example
172
- * createServer({ listeners: [tcp({ port: 8080 })] });
173
- */
174
- export declare function tcp({ port, host, idleTimeoutMs }?: TcpOptions): Listener;
175
- export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BuildIdOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FrameworkAdapter, type InferOutput, type Listener, type ListenerBindings, type LogLevel, type LogSink, type NodeMiddleware, type Plugin, type PrerenderedOptions, type RequestIdOptions, type RequestLogger, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type TcpOptions, accessLog, assets, createEntry, createServer, defaultPlugins, prerendered, requestId };
190
+ 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, 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, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
176
191
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
- import { n as tcp } from "./tcp-Dau_IONd.js";
2
- import { a as shutdownSignal, c as prerendered, f as jsonSink, i as defaultPlugins, l as requestId, o as streamingCompress, r as createServer, s as assets, t as createEntry, u as accessLog } from "./entry-ChjmFwX5.js";
1
+ import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
2
+ import { r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
3
+ import { r as jsonSink } from "./log-BP6xXXZl.js";
4
+ import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
5
+ import { a as streamingCompress, b as accessLog, c as prefersMarkdown, d as securityHeaders, f as redirects, g as health, h as noindex, l as requestId, m as privateDocuments, n as defaultPlugins, o as assets, p as trailingSlash, s as prerendered, t as createServer, u as contentSecurityPolicy, v as shutdownSignal, y as bodyLimit } from "./create-server-iE1-s6Bi.js";
6
+ import { t as requestContext } from "./request-context-BtQ87VYb.js";
7
+ import { t as createEntry } from "./entry-DZ3qo7qF.js";
3
8
 
4
- // src/event-stream.ts
9
+ // src/core/event-stream.ts
5
10
  function formatEvent({ data, event, id }) {
6
- if (/[\r\n]/.test(`${event ?? ""}${id ?? ""}`)) throw new TypeError("An event's `event` and `id` cannot contain a line break.");
11
+ if (/[\r\n]/u.test(`${event ?? ""}${id ?? ""}`)) throw new TypeError("An event's `event` and `id` cannot contain a line break.");
7
12
  return `${[
8
13
  ...event == null ? [] : [`event: ${event}`],
9
14
  ...id == null ? [] : [`id: ${id}`],
10
- ...data.split(/\r\n|\r|\n/).map((line) => `data: ${line}`)
15
+ ...data.split(/\r\n|\r|\n/u).map((line) => `data: ${line}`)
11
16
  ].join("\n")}\n\n`;
12
17
  }
13
18
  /**
@@ -55,8 +60,10 @@ function eventStream({ signal, heartbeatMs = 15e3, headers }, produce) {
55
60
  close();
56
61
  return;
57
62
  }
58
- Promise.resolve().then(() => produce({
59
- send: (event) => write(formatEvent(event)),
63
+ Promise.resolve().then(async () => produce({
64
+ send: (event) => {
65
+ write(formatEvent(event));
66
+ },
60
67
  signal: stopSignal
61
68
  })).then(close, (error) => {
62
69
  closed = true;
@@ -77,26 +84,7 @@ function eventStream({ signal, heartbeatMs = 15e3, headers }, produce) {
77
84
  return new Response(body, { headers: responseHeaders });
78
85
  }
79
86
 
80
- // src/plugins/build-id.ts
81
- /**
82
- * Sets a build ID header on documents and React Router `.data` responses, so
83
- * a client can see that a deploy happened under it.
84
- *
85
- * @example
86
- * buildId({ value: env.values.PUBLIC_APP_VERSION });
87
- */
88
- function buildId({ header = "X-Build-Id", value }) {
89
- return {
90
- name: "build-id",
91
- etagPart: () => value,
92
- middleware: async (context, next) => {
93
- await next();
94
- if ((context.res.headers.get("Content-Type")?.startsWith("text/html") ?? false) || context.req.path.endsWith(".data")) context.header(header, value);
95
- }
96
- };
97
- }
98
-
99
- // src/plugins/runtime-env.ts
87
+ // src/core/plugins/runtime-env.ts
100
88
  /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
101
89
  const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
102
90
  /** Stops the search for `</head>` after this many characters, so a page with none still streams. */
@@ -107,36 +95,44 @@ function formatIssue(issue) {
107
95
  }
108
96
  /** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */
109
97
  function publicEnvScript(values) {
110
- const json = JSON.stringify(values).replaceAll("<", "\\u003c");
98
+ const json = JSON.stringify(values).replaceAll("<", String.raw`\u003c`);
111
99
  return `<script id="${PUBLIC_ENV_SCRIPT_ID}" type="application/json">${json}<\/script>`;
112
100
  }
113
101
  /** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */
114
102
  function injectBeforeHeadEnd(body, html) {
115
103
  const decoder = new TextDecoder();
116
104
  const encoder = new TextEncoder();
105
+ const reader = body.getReader();
117
106
  let pending = "";
118
- return body.pipeThrough(new TransformStream({
119
- transform(chunk, controller) {
120
- const text = decoder.decode(chunk, { stream: true });
121
- if (pending == null) {
122
- controller.enqueue(encoder.encode(text));
123
- return;
124
- }
125
- pending += text;
126
- const index = pending.search(/<\/head>/i);
127
- if (index !== -1) {
128
- controller.enqueue(encoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`));
129
- pending = void 0;
130
- } else if (pending.length > HEAD_SEARCH_LIMIT) {
131
- controller.enqueue(encoder.encode(pending));
132
- pending = void 0;
107
+ /** The text to send for `text`, or `undefined` while the search for `</head>` goes on. */
108
+ const transform = (text) => {
109
+ if (pending == null) return text;
110
+ pending += text;
111
+ const index = pending.search(/<\/head>/iu);
112
+ if (index === -1 && pending.length <= HEAD_SEARCH_LIMIT) return;
113
+ const out = index === -1 ? pending : `${pending.slice(0, index)}${html}${pending.slice(index)}`;
114
+ pending = void 0;
115
+ return out;
116
+ };
117
+ return new ReadableStream({
118
+ async pull(controller) {
119
+ for (;;) {
120
+ const { done, value } = await reader.read();
121
+ if (done) {
122
+ const rest = `${pending ?? ""}${decoder.decode()}`;
123
+ if (rest !== "") controller.enqueue(encoder.encode(rest));
124
+ controller.close();
125
+ return;
126
+ }
127
+ const out = transform(decoder.decode(value, { stream: true }));
128
+ if (out != null) {
129
+ controller.enqueue(encoder.encode(out));
130
+ return;
131
+ }
133
132
  }
134
133
  },
135
- flush(controller) {
136
- const rest = `${pending ?? ""}${decoder.decode()}`;
137
- if (rest !== "") controller.enqueue(encoder.encode(rest));
138
- }
139
- }));
134
+ cancel: async (reason) => reader.cancel(reason)
135
+ }, { highWaterMark: 0 });
140
136
  }
141
137
  /**
142
138
  * Validates the environment once, at startup, against a schema. A missing or
@@ -146,14 +142,15 @@ function injectBeforeHeadEnd(body, html) {
146
142
  * The values whose names start with `PUBLIC_` go into each HTML document,
147
143
  * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
148
144
  * So one image serves every environment, and a prerendered page never keeps
149
- * the values of the build. Put this plugin before the static stages, so it
150
- * sees the prerendered pages.
145
+ * the values of the build. Give it to the `env` option of `defaultPlugins()`,
146
+ * which puts it before the static stages, so it sees the prerendered pages.
151
147
  *
152
148
  * @example
153
149
  * export const env = runtimeEnv(
154
150
  * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
155
151
  * );
156
152
  * env.values.SESSION_KEY; // => string
153
+ * createServer({ plugins: defaultPlugins({ env }) });
157
154
  *
158
155
  * // In the browser:
159
156
  * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
@@ -174,7 +171,7 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
174
171
  };
175
172
  return parsed;
176
173
  };
177
- return {
174
+ return optionPlugin("env", {
178
175
  name: "runtime-env",
179
176
  get values() {
180
177
  return parse().values;
@@ -187,16 +184,18 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
187
184
  },
188
185
  etagPart: () => parse().script,
189
186
  middleware: async (context, next) => {
190
- await next();
191
187
  const { script } = parse();
188
+ if (script != null) context.set("rewritesHtml", true);
189
+ await next();
192
190
  const response = context.res;
193
191
  if (script == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || !(response.headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
194
- if (response.body != null) context.res = new Response(injectBeforeHeadEnd(response.body, script), response);
195
- context.header("Content-Length", void 0);
196
- context.header("ETag", void 0);
192
+ if (response.body != null) replaceResponse(context, new Response(injectBeforeHeadEnd(response.body, script), response));
193
+ const headers = writableHeaders(context);
194
+ headers.delete("Content-Length");
195
+ headers.delete("ETag");
197
196
  }
198
- };
197
+ });
199
198
  }
200
199
 
201
- export { PUBLIC_ENV_SCRIPT_ID, accessLog, assets, buildId, createEntry, createServer, defaultPlugins, eventStream, jsonSink, prerendered, requestId, runtimeEnv, shutdownSignal, streamingCompress, tcp };
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 };
202
201
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/event-stream.ts","../src/plugins/build-id.ts","../src/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => produce({ send: (event) => write(formatEvent(event)), signal: stopSignal }))\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import type { Plugin } from \"../types.js\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/** The deployed build, such as the image tag. Read it from the runtime env, not the build. */\n\tvalue: string;\n};\n\n/**\n * Sets a build ID header on documents and React Router `.data` responses, so\n * a client can see that a deploy happened under it.\n *\n * @example\n * buildId({ value: env.values.PUBLIC_APP_VERSION });\n */\nexport function buildId({ header = \"X-Build-Id\", value }: BuildIdOptions): Plugin {\n\treturn {\n\t\tname: \"build-id\",\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst isDocument = context.res.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\t\t\tif (isDocument || context.req.path.endsWith(\".data\")) {\n\t\t\t\tcontext.header(header, value);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: ReadonlyArray<StandardIssue> };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", \"\\\\u003c\");\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tlet pending: string | undefined = \"\";\n\treturn body.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\tif (pending == null) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending += text;\n\t\t\t\tconst index = pending.search(/<\\/head>/i);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tencoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`),\n\t\t\t\t\t);\n\t\t\t\t\tpending = undefined;\n\t\t\t\t} else if (pending.length > HEAD_SEARCH_LIMIT) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(pending));\n\t\t\t\t\tpending = undefined;\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Put this plugin before the static stages, so it\n * sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst { script } = parse();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\tcontext.res = new Response(injectBeforeHeadEnd(response.body, script), response);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tcontext.header(\"Content-Length\", undefined);\n\t\t\tcontext.header(\"ETag\", undefined);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,SAAS,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC5C,MAAM,I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AAC,CAAC;EAChB;EACA,IAAI,eAAe;GAClB,OAAO,MAAM,CAAC,CAAC;EAChB;EACA,aAAa;GACZ,MAAM;EACP;EACA,gBAAgB,MAAM,CAAC,CAAC;EACxB,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,KAAK;GACX,MAAM,EAAE,WAAW,MAAM;GACzB,MAAM,WAAW,QAAQ;GACzB,IACC,UAAU,QACV,SAAS,QAAQ,IAAI,kBAAkB,KAEvC,SAAS,QAAQ,IAAI,eAAe,KACpC,EAAE,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,QAEnE;GAED,IAAI,SAAS,QAAQ,MACpB,QAAQ,MAAM,IAAI,SAAS,oBAAoB,SAAS,MAAM,MAAM,GAAG,QAAQ;GAIhF,QAAQ,OAAO,kBAAkB,MAAS;GAC1C,QAAQ,OAAO,QAAQ,MAAS;EACjC;CACD;AACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/event-stream.ts","../src/core/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/u.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/u).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(async () =>\n\t\t\t\t\tproduce({\n\t\t\t\t\t\tsend: (event) => {\n\t\t\t\t\t\t\twrite(formatEvent(event));\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal: stopSignal,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import { replaceResponse, writableHeaders } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: readonly StandardIssue[] };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", String.raw`\\u003c`);\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tconst reader = body.getReader();\n\tlet pending: string | undefined = \"\";\n\t/** The text to send for `text`, or `undefined` while the search for `</head>` goes on. */\n\tconst transform = (text: string): string | undefined => {\n\t\tif (pending == null) {\n\t\t\treturn text;\n\t\t}\n\t\tpending += text;\n\t\tconst index = pending.search(/<\\/head>/iu);\n\t\tif (index === -1 && pending.length <= HEAD_SEARCH_LIMIT) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst out = index === -1 ? pending : `${pending.slice(0, index)}${html}${pending.slice(index)}`;\n\t\tpending = undefined;\n\t\treturn out;\n\t};\n\t// Why not `pipeThrough`: a pipe reads the source before the client reads. On Node.js 26, a\n\t// static file that a later stage drops then holds an open `FileHandle` until garbage collection.\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\t// Why a loop: a pull that enqueues nothing is not called again.\n\t\t\t\tfor (;;) {\n\t\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read depends on the one before it.\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst out = transform(decoder.decode(value, { stream: true }));\n\t\t\t\t\tif (out != null) {\n\t\t\t\t\t\tcontroller.enqueue(encoder.encode(out));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: async (reason) => reader.cancel(reason),\n\t\t},\n\t\t// Why 0: the stream reads its source only when the client reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Give it to the `env` option of `defaultPlugins()`,\n * which puts it before the static stages, so it sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n * createServer({ plugins: defaultPlugins({ env }) });\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn optionPlugin(\"env\", {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { script } = parse();\n\t\t\t// Why a request value, not an option: the static stages send the HTML file, not its compressed\n\t\t\t// copy, only to a request that gets the script. An app with no public values keeps the copies.\n\t\t\tif (script != null) {\n\t\t\t\tcontext.set(\"rewritesHtml\", true);\n\t\t\t}\n\t\t\tawait next();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\treplaceResponse(\n\t\t\t\t\tcontext,\n\t\t\t\t\tnew Response(injectBeforeHeadEnd(response.body, script), response),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tconst headers = writableHeaders(context);\n\t\t\theaders.delete(\"Content-Length\");\n\t\t\theaders.delete(\"ETag\");\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,UAAU,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC7C,MAAM,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IA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,WAAW,MAAM;GAGzB,IAAI,UAAU,MACb,QAAQ,IAAI,gBAAgB,IAAI;GAEjC,MAAM,KAAK;GACX,MAAM,WAAW,QAAQ;GACzB,IACC,UAAU,QACV,SAAS,QAAQ,IAAI,kBAAkB,KAEvC,SAAS,QAAQ,IAAI,eAAe,KACpC,EAAE,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,QAEnE;GAED,IAAI,SAAS,QAAQ,MACpB,gBACC,SACA,IAAI,SAAS,oBAAoB,SAAS,MAAM,MAAM,GAAG,QAAQ,CAClE;GAID,MAAM,UAAU,gBAAgB,OAAO;GACvC,QAAQ,OAAO,gBAAgB;GAC/B,QAAQ,OAAO,MAAM;EACtB;CACD,CAAC;AACF"}
@@ -1,4 +1,4 @@
1
- // src/runtimes/listen-options.ts
1
+ // src/node/runtimes/listen-options.ts
2
2
  /**
3
3
  * The URL a listener answers on. A wildcard bind reads as `localhost`.
4
4
  *
@@ -12,4 +12,4 @@ function listenerUrl(hostname, port) {
12
12
  }
13
13
 
14
14
  export { listenerUrl as t };
15
- //# sourceMappingURL=listen-options-DHWmSWGi.js.map
15
+ //# sourceMappingURL=listen-options-7TaXjyrk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listen-options-7TaXjyrk.js","names":[],"sources":["../src/node/runtimes/listen-options.ts"],"sourcesContent":["/** What every runtime listener takes. */\nexport type ListenOptions = {\n\tport: number;\n\t/** The interface to bind. When omitted, the listener binds every interface. */\n\thostname: string | undefined;\n\t/** How long an idle keep-alive connection stays open. */\n\tidleTimeoutMs: number;\n\t/** The `trustForwardedProto` of the server. */\n\ttrustForwardedProto: boolean;\n};\n\n/**\n * The URL a listener answers on. A wildcard bind reads as `localhost`.\n *\n * @example\n * listenerUrl(\"0.0.0.0\", 3000); // => \"http://localhost:3000/\"\n * listenerUrl(\"::1\", 3000); // => \"http://[::1]:3000/\"\n */\nexport function listenerUrl(hostname: string | undefined, port: number): string {\n\tif (hostname == null || hostname === \"\" || hostname === \"0.0.0.0\" || hostname === \"::\") {\n\t\treturn `http://localhost:${port}/`;\n\t}\n\treturn hostname.includes(\":\") ? `http://[${hostname}]:${port}/` : `http://${hostname}:${port}/`;\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,YAAY,UAA8B,MAAsB;CAC/E,IAAI,YAAY,QAAQ,aAAa,MAAM,aAAa,aAAa,aAAa,MACjF,OAAO,oBAAoB,KAAK;CAEjC,OAAO,SAAS,SAAS,GAAG,IAAI,WAAW,SAAS,IAAI,KAAK,KAAK,UAAU,SAAS,GAAG,KAAK;AAC9F"}
@@ -0,0 +1,37 @@
1
+ import { t as createServer } from "./create-server-iE1-s6Bi.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-DZ3qo7qF.js";
3
+ import { t as host } from "./node-BFH82eeL.js";
4
+
5
+ // src/cli/load-entry.ts
6
+ /** Entries that this copy made for plain React Router builds, by build module. */
7
+ const plainEntries = /* @__PURE__ */ new WeakMap();
8
+ /**
9
+ * The entry that runs a server build: its `appServer` export when the
10
+ * `appServer` Vite plugin made it, else this copy of the package over a
11
+ * plain React Router build, on the node host, with the default plugins.
12
+ */
13
+ async function loadEntry(build) {
14
+ if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
15
+ const exported = Reflect.get(build, "appServer");
16
+ if (exported != null) {
17
+ if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${2}. Install the same version of @ngrok/app-server that the build uses.`);
18
+ return exported;
19
+ }
20
+ const known = plainEntries.get(build);
21
+ if (known != null) return known;
22
+ const { isServerBuild, runtime } = await import("./react-router.js");
23
+ if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
24
+ const entry = createEntry({
25
+ app: createServer({
26
+ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1",
27
+ trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0)
28
+ }),
29
+ host,
30
+ framework: (mode) => runtime(build, { mode })
31
+ });
32
+ plainEntries.set(build, entry);
33
+ return entry;
34
+ }
35
+
36
+ export { loadEntry as t };
37
+ //# sourceMappingURL=load-entry-AfYS_zS9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-entry-AfYS_zS9.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"}