@ngrok/app-server 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +652 -77
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client-browser.d.ts +12 -0
  9. package/dist/client-browser.js +3 -0
  10. package/dist/client.d.ts +21 -0
  11. package/dist/client.js +27 -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-DkTeIJ8L.js +1409 -0
  16. package/dist/create-server-DkTeIJ8L.js.map +1 -0
  17. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-CM6Ma-Tv.d.ts +626 -0
  20. package/dist/entry-CenmvESk.js +116 -0
  21. package/dist/entry-CenmvESk.js.map +1 -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-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  27. package/dist/index.d.ts +99 -269
  28. package/dist/index.js +47 -59
  29. package/dist/index.js.map +1 -1
  30. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  31. package/dist/{load-entry-C03qqmhr.js → load-entry-CmkdlmDX.js} +8 -4
  32. package/dist/{load-entry-C03qqmhr.js.map → load-entry-CmkdlmDX.js.map} +1 -1
  33. package/dist/log-BP6xXXZl.js +122 -0
  34. package/dist/log-BP6xXXZl.js.map +1 -0
  35. package/dist/node-BFH82eeL.js +333 -0
  36. package/dist/node-BFH82eeL.js.map +1 -0
  37. package/dist/node-tBVQPjQv.js +41 -0
  38. package/dist/node-tBVQPjQv.js.map +1 -0
  39. package/dist/node-vite.d.ts +5 -4
  40. package/dist/node-vite.js +2 -17
  41. package/dist/node.d.ts +23 -4
  42. package/dist/node.js +2 -2
  43. package/dist/react-router-vite.d.ts +4 -3
  44. package/dist/react-router-vite.js +2 -20
  45. package/dist/react-router.d.ts +1 -1
  46. package/dist/react-router.js +8 -7
  47. package/dist/react-router.js.map +1 -1
  48. package/dist/request-context-BtQ87VYb.js +40 -0
  49. package/dist/request-context-BtQ87VYb.js.map +1 -0
  50. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  51. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  52. package/dist/response-writer-B7FoJjEE.js +289 -0
  53. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  54. package/dist/script-hashes-hqUk6kG7.js +53 -0
  55. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  56. package/dist/{serve-Cleo8RMO.js → serve-Cc-ADdhZ.js} +3 -3
  57. package/dist/{serve-Cleo8RMO.js.map → serve-Cc-ADdhZ.js.map} +1 -1
  58. package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
  59. package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
  60. package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
  61. package/dist/{start-CINALHxy.js → start-Cb3kknlF.js} +14 -19
  62. package/dist/start-Cb3kknlF.js.map +1 -0
  63. package/dist/static-files-Beju9riB.js +302 -0
  64. package/dist/static-files-Beju9riB.js.map +1 -0
  65. package/dist/tanstack-start-vite.d.ts +6 -5
  66. package/dist/tanstack-start-vite.js +2 -23
  67. package/dist/tanstack-start.d.ts +19 -2
  68. package/dist/tanstack-start.js +5 -14
  69. package/dist/tanstack-start.js.map +1 -1
  70. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  71. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  72. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  73. package/dist/types-DLYxYS6M.d.ts +392 -0
  74. package/dist/vercel-vite.d.ts +35 -0
  75. package/dist/vercel-vite.js +142 -0
  76. package/dist/vercel-vite.js.map +1 -0
  77. package/dist/vercel.d.ts +35 -0
  78. package/dist/vercel.js +89 -0
  79. package/dist/vercel.js.map +1 -0
  80. package/dist/vite-B-GfswoH.js +22 -0
  81. package/dist/vite-B-GfswoH.js.map +1 -0
  82. package/dist/vite-D4hfj3ph.js +19 -0
  83. package/dist/vite-D4hfj3ph.js.map +1 -0
  84. package/dist/vite-DyrhyKEr.js +25 -0
  85. package/dist/vite-DyrhyKEr.js.map +1 -0
  86. package/dist/vite-iioAoxSt.js +752 -0
  87. package/dist/vite-iioAoxSt.js.map +1 -0
  88. package/dist/vite.d.ts +2 -2
  89. package/dist/vite.js +1 -1
  90. package/package.json +25 -4
  91. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  92. package/dist/deno-DNRgzHrk.js.map +0 -1
  93. package/dist/entry-BkdUub2S.js +0 -638
  94. package/dist/entry-BkdUub2S.js.map +0 -1
  95. package/dist/log-CsjaKM8U.js +0 -59
  96. package/dist/log-CsjaKM8U.js.map +0 -1
  97. package/dist/node-CG7qXuWZ.js +0 -58
  98. package/dist/node-CG7qXuWZ.js.map +0 -1
  99. package/dist/node-YWPGmzAk.js +0 -215
  100. package/dist/node-YWPGmzAk.js.map +0 -1
  101. package/dist/node-ZMowKZDB.js +0 -3
  102. package/dist/node-vite.js.map +0 -1
  103. package/dist/react-router-vite.js.map +0 -1
  104. package/dist/start-CINALHxy.js.map +0 -1
  105. package/dist/tanstack-start-vite.js.map +0 -1
  106. package/dist/types-BfCkS7kQ.d.ts +0 -203
  107. package/dist/vite-mYZ2Y69u.js +0 -144
  108. package/dist/vite-mYZ2Y69u.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
- import { n as jsonSink } from "./log-CsjaKM8U.js";
2
- import { a as shutdownSignal, c as assets, d as accessLog, i as defaultPlugins, l as prerendered, o as requestContext, r as createServer, s as streamingCompress, t as createEntry, u as requestId } from "./entry-BkdUub2S.js";
1
+ import { t as requestContext } from "./request-context-BtQ87VYb.js";
2
+ import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
3
+ import { r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
4
+ import { r as jsonSink } from "./log-BP6xXXZl.js";
5
+ import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
6
+ 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-DkTeIJ8L.js";
7
+ import { t as createEntry } from "./entry-CenmvESk.js";
3
8
 
4
9
  // src/core/event-stream.ts
5
10
  function formatEvent({ data, event, id }) {
@@ -79,34 +84,6 @@ function eventStream({ signal, heartbeatMs = 15e3, headers }, produce) {
79
84
  return new Response(body, { headers: responseHeaders });
80
85
  }
81
86
 
82
- // src/core/plugins/build-id.ts
83
- /** The data check before `setup` runs. */
84
- function noDataRequests() {
85
- return false;
86
- }
87
- /**
88
- * Sets a build ID header on documents and on the framework's data responses,
89
- * such as React Router `.data` files, so a client can see that a deploy
90
- * happened under it.
91
- *
92
- * @example
93
- * buildId({ value: env.values.PUBLIC_APP_VERSION });
94
- */
95
- function buildId({ header = "X-Build-Id", value }) {
96
- let isDataRequest = noDataRequests;
97
- return {
98
- name: "build-id",
99
- setup: (info) => {
100
- ({isDataRequest} = info);
101
- },
102
- etagPart: () => value,
103
- middleware: async (context, next) => {
104
- await next();
105
- if ((context.res.headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path)) context.header(header, value);
106
- }
107
- };
108
- }
109
-
110
87
  // src/core/plugins/runtime-env.ts
111
88
  /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
112
89
  const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
@@ -125,29 +102,37 @@ function publicEnvScript(values) {
125
102
  function injectBeforeHeadEnd(body, html) {
126
103
  const decoder = new TextDecoder();
127
104
  const encoder = new TextEncoder();
105
+ const reader = body.getReader();
128
106
  let pending = "";
129
- return body.pipeThrough(new TransformStream({
130
- transform(chunk, controller) {
131
- const text = decoder.decode(chunk, { stream: true });
132
- if (pending == null) {
133
- controller.enqueue(encoder.encode(text));
134
- return;
135
- }
136
- pending += text;
137
- const index = pending.search(/<\/head>/iu);
138
- if (index !== -1) {
139
- controller.enqueue(encoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`));
140
- pending = void 0;
141
- } else if (pending.length > HEAD_SEARCH_LIMIT) {
142
- controller.enqueue(encoder.encode(pending));
143
- 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
+ }
144
132
  }
145
133
  },
146
- flush(controller) {
147
- const rest = `${pending ?? ""}${decoder.decode()}`;
148
- if (rest !== "") controller.enqueue(encoder.encode(rest));
149
- }
150
- }));
134
+ cancel: async (reason) => reader.cancel(reason)
135
+ }, { highWaterMark: 0 });
151
136
  }
152
137
  /**
153
138
  * Validates the environment once, at startup, against a schema. A missing or
@@ -157,14 +142,15 @@ function injectBeforeHeadEnd(body, html) {
157
142
  * The values whose names start with `PUBLIC_` go into each HTML document,
158
143
  * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
159
144
  * So one image serves every environment, and a prerendered page never keeps
160
- * the values of the build. Put this plugin before the static stages, so it
161
- * 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.
162
147
  *
163
148
  * @example
164
149
  * export const env = runtimeEnv(
165
150
  * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
166
151
  * );
167
152
  * env.values.SESSION_KEY; // => string
153
+ * createServer({ plugins: defaultPlugins({ env }) });
168
154
  *
169
155
  * // In the browser:
170
156
  * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
@@ -185,7 +171,7 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
185
171
  };
186
172
  return parsed;
187
173
  };
188
- return {
174
+ return optionPlugin("env", {
189
175
  name: "runtime-env",
190
176
  get values() {
191
177
  return parse().values;
@@ -198,16 +184,18 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
198
184
  },
199
185
  etagPart: () => parse().script,
200
186
  middleware: async (context, next) => {
201
- await next();
202
187
  const { script } = parse();
188
+ if (script != null) context.set("rewritesHtml", true);
189
+ await next();
203
190
  const response = context.res;
204
191
  if (script == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || !(response.headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
205
- if (response.body != null) context.res = new Response(injectBeforeHeadEnd(response.body, script), response);
206
- context.header("Content-Length", void 0);
207
- 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");
208
196
  }
209
- };
197
+ });
210
198
  }
211
199
 
212
- export { PUBLIC_ENV_SCRIPT_ID, accessLog, assets, buildId, createEntry, createServer, defaultPlugins, eventStream, jsonSink, prerendered, requestContext, requestId, runtimeEnv, shutdownSignal, streamingCompress };
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 };
213
201
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/core/event-stream.ts","../src/core/plugins/build-id.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 type { Plugin, SetupInfo } 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/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * 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\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t},\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 || isDataRequest(context.req.path)) {\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?: 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\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>/iu);\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,UAAU,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC7C,MAAM,IAAI,UAAU,0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AC,SAAS,IAAI,gBAAgB,YAAY,IAAI;EAChF;EACA,OAAO;CACR;CAEA,OAAO;EACN,MAAM;EACN,IAAI,SAAS;GACZ,OAAO,MAAM,CAAC,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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AAC;EAChB;EACA,aAAa;GACZ,MAAM;EACP;EACA,gBAAgB,MAAM,CAAC,CAAC;EACxB,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,EAAE,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 +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};\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":";;;;;;;;AAgBA,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"}
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"}
@@ -1,5 +1,6 @@
1
- import { n as isAppServerEntry, r as createServer, t as createEntry } from "./entry-BkdUub2S.js";
2
- import { t as host } from "./node-YWPGmzAk.js";
1
+ import { t as createServer } from "./create-server-DkTeIJ8L.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-CenmvESk.js";
3
+ import { t as host } from "./node-BFH82eeL.js";
3
4
 
4
5
  // src/cli/load-entry.ts
5
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -21,7 +22,10 @@ async function loadEntry(build) {
21
22
  const { isServerBuild, runtime } = await import("./react-router.js");
22
23
  if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
23
24
  const entry = createEntry({
24
- app: createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" }),
25
+ app: createServer({
26
+ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1",
27
+ trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0)
28
+ }),
25
29
  host,
26
30
  framework: (mode) => runtime(build, { mode })
27
31
  });
@@ -30,4 +34,4 @@ async function loadEntry(build) {
30
34
  }
31
35
 
32
36
  export { loadEntry as t };
33
- //# sourceMappingURL=load-entry-C03qqmhr.js.map
37
+ //# sourceMappingURL=load-entry-CmkdlmDX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-C03qqmhr.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({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\" }),\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,EAAE,qBAAqB,QAAQ,IAAI,0BAA0B,IAAI,CAAC;EACpF;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-CmkdlmDX.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,122 @@
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
+ /**
36
+ * A log sink that writes one JSON object per line. Each line has `time`,
37
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
38
+ * standard attributes. The default writes the lines of one event-loop turn
39
+ * to stdout at the end of the turn.
40
+ *
41
+ * @param write - Where each line goes. Defaults to stdout.
42
+ *
43
+ * @example
44
+ * createServer({ logger: jsonSink() });
45
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
46
+ */
47
+ function jsonSink(write = writeStdout) {
48
+ return { log: (level, message, attributes) => {
49
+ write(`${JSON.stringify({
50
+ time: isoNow(),
51
+ level,
52
+ message,
53
+ ...attributes
54
+ })}\n`);
55
+ } };
56
+ }
57
+ /** The millisecond of the last `time`, and its ISO string. */
58
+ let lastMs = NaN;
59
+ let lastTime = "";
60
+ /** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */
61
+ let lastSecond = NaN;
62
+ let secondPrefix = "";
63
+ /**
64
+ * The time now, as `new Date().toISOString()` gives it. Why keep the last
65
+ * time: under load, many lines share a millisecond. Why keep the prefix of
66
+ * the second: `toISOString()` costs more than the rest of a line.
67
+ */
68
+ function isoNow() {
69
+ const now = Date.now();
70
+ if (now !== lastMs) {
71
+ lastMs = now;
72
+ const second = Math.floor(now / 1e3);
73
+ if (second !== lastSecond) {
74
+ lastSecond = second;
75
+ secondPrefix = new Date(now).toISOString().slice(0, -4);
76
+ }
77
+ lastTime = `${secondPrefix}${String(now - second * 1e3).padStart(3, "0")}Z`;
78
+ }
79
+ return lastTime;
80
+ }
81
+ /** Flat `error.*` attributes for a thrown value. */
82
+ function errorAttributes(error) {
83
+ if (error instanceof Error) return {
84
+ "error.kind": error.name,
85
+ "error.message": error.message,
86
+ "error.stack": error.stack
87
+ };
88
+ return { "error.message": String(error) };
89
+ }
90
+ /**
91
+ * A logger that writes to `sink`. `withBase` gives the attributes of each
92
+ * line as a new object, from the attributes that the caller gives.
93
+ */
94
+ function sinkLogger(sink, withBase = (attributes) => ({ ...attributes })) {
95
+ return {
96
+ debug: (message, attributes = {}) => {
97
+ sink.log("debug", message, withBase(attributes));
98
+ },
99
+ info: (message, attributes = {}) => {
100
+ sink.log("info", message, withBase(attributes));
101
+ },
102
+ warn: (message, attributes = {}) => {
103
+ sink.log("warn", message, withBase(attributes));
104
+ },
105
+ error: (message, attributes = {}) => {
106
+ sink.log("error", message, withBase(attributes));
107
+ }
108
+ };
109
+ }
110
+ /** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */
111
+ function requestLogger(sink, context) {
112
+ return sinkLogger(sink, (attributes) => ({
113
+ "http.request_id": context.get("requestId"),
114
+ "http.method": context.req.method,
115
+ "http.url_details.path": context.req.path,
116
+ ...context.get("logAttributes"),
117
+ ...attributes
118
+ }));
119
+ }
120
+
121
+ export { sinkLogger as a, requestLogger as i, flushLogs as n, jsonSink as r, errorAttributes as t };
122
+ //# sourceMappingURL=log-BP6xXXZl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-BP6xXXZl.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(`${JSON.stringify({ time: isoNow(), level, message, ...attributes })}\\n`);\n\t\t},\n\t};\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\n/** Flat `error.*` attributes for a thrown value. */\nexport function errorAttributes(error: unknown): Record<string, unknown> {\n\tif (error instanceof Error) {\n\t\treturn { \"error.kind\": error.name, \"error.message\": error.message, \"error.stack\": error.stack };\n\t}\n\treturn { \"error.message\": String(error) };\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log(\"debug\", message, withBase(attributes));\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log(\"info\", message, withBase(attributes));\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log(\"warn\", message, withBase(attributes));\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log(\"error\", message, withBase(attributes));\n\t\t},\n\t};\n}\n\n/** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */\nexport function requestLogger(sink: LogSink, context: Context<AppServerEnv>): RequestLogger {\n\t// Why read at call time: the `requestId` plugin runs after this logger is made. Why one object:\n\t// a base object and then a merge copy each attribute two times.\n\treturn sinkLogger(sink, (attributes) => ({\n\t\t\"http.request_id\": context.get(\"requestId\"),\n\t\t\"http.method\": context.req.method,\n\t\t\"http.url_details.path\": context.req.path,\n\t\t...context.get(\"logAttributes\"),\n\t\t...attributes,\n\t}));\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAEjF,KAAK,MAAM,QAAQ,QAAQ,MAAM,YAAY,KAAK,CAAC,GAClD,QAAQ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