@ngrok/app-server 0.1.1 → 0.2.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 (70) hide show
  1. package/README.md +75 -20
  2. package/dist/build-manifest-8NfD1wnO.js +45 -0
  3. package/dist/build-manifest-8NfD1wnO.js.map +1 -0
  4. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  5. package/dist/bun-BCz6K_Xv.js.map +1 -0
  6. package/dist/cli.js +6 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/{deno-BnMfk2n1.js → deno-DNRgzHrk.js} +4 -4
  9. package/dist/deno-DNRgzHrk.js.map +1 -0
  10. package/dist/{entry-ChjmFwX5.js → entry-BkdUub2S.js} +179 -296
  11. package/dist/entry-BkdUub2S.js.map +1 -0
  12. package/dist/index-oSE-tYRW.d.ts +88 -0
  13. package/dist/index.d.ts +212 -27
  14. package/dist/index.js +26 -15
  15. package/dist/index.js.map +1 -1
  16. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  17. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  18. package/dist/load-entry-C03qqmhr.js +33 -0
  19. package/dist/load-entry-C03qqmhr.js.map +1 -0
  20. package/dist/log-CsjaKM8U.js +59 -0
  21. package/dist/log-CsjaKM8U.js.map +1 -0
  22. package/dist/{node-79my3Uix.js → node-CG7qXuWZ.js} +4 -4
  23. package/dist/node-CG7qXuWZ.js.map +1 -0
  24. package/dist/node-YWPGmzAk.js +215 -0
  25. package/dist/node-YWPGmzAk.js.map +1 -0
  26. package/dist/node-ZMowKZDB.js +3 -0
  27. package/dist/node-vite.d.ts +10 -0
  28. package/dist/node-vite.js +18 -0
  29. package/dist/node-vite.js.map +1 -0
  30. package/dist/node.d.ts +67 -0
  31. package/dist/node.js +4 -0
  32. package/dist/react-router-vite.d.ts +9 -0
  33. package/dist/react-router-vite.js +21 -0
  34. package/dist/react-router-vite.js.map +1 -0
  35. package/dist/react-router.d.ts +11 -24
  36. package/dist/react-router.js +15 -25
  37. package/dist/react-router.js.map +1 -1
  38. package/dist/serve-Cleo8RMO.js +29 -0
  39. package/dist/serve-Cleo8RMO.js.map +1 -0
  40. package/dist/{start-BVMb8Pyt.js → start-CINALHxy.js} +92 -72
  41. package/dist/start-CINALHxy.js.map +1 -0
  42. package/dist/tanstack-start-vite.d.ts +11 -0
  43. package/dist/tanstack-start-vite.js +24 -0
  44. package/dist/tanstack-start-vite.js.map +1 -0
  45. package/dist/tanstack-start.d.ts +17 -0
  46. package/dist/tanstack-start.js +50 -0
  47. package/dist/tanstack-start.js.map +1 -0
  48. package/dist/{tcp-Dau_IONd.js → tcp-C-9AmFuM.js} +5 -5
  49. package/dist/tcp-C-9AmFuM.js.map +1 -0
  50. package/dist/types-BfCkS7kQ.d.ts +203 -0
  51. package/dist/vite-mYZ2Y69u.js +144 -0
  52. package/dist/vite-mYZ2Y69u.js.map +1 -0
  53. package/dist/vite.d.ts +2 -27
  54. package/dist/vite.js +2 -2
  55. package/package.json +28 -2
  56. package/dist/bun-DCGnDEPn.js.map +0 -1
  57. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  58. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  59. package/dist/deno-BnMfk2n1.js.map +0 -1
  60. package/dist/entry-CIpwaayZ.d.ts +0 -293
  61. package/dist/entry-ChjmFwX5.js.map +0 -1
  62. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  63. package/dist/node-2wWBMFeO.js +0 -3
  64. package/dist/node-79my3Uix.js.map +0 -1
  65. package/dist/serve-ByeedcRB.js +0 -16
  66. package/dist/serve-ByeedcRB.js.map +0 -1
  67. package/dist/start-BVMb8Pyt.js.map +0 -1
  68. package/dist/tcp-Dau_IONd.js.map +0 -1
  69. package/dist/vite-CrNqpoeK.js +0 -102
  70. package/dist/vite-CrNqpoeK.js.map +0 -1
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,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,UAAU,OAAO;EAC3C,GAAI,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI;EAElC,GAAG,KAAK,MAAM,YAAY,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM;CAE5C,CAAC,CAAC,KAAK,IAAI,EAAE;AAC5B;;;;;;;;;;;;;;;;AAiBA,SAAgB,YACf,EAAE,QAAQ,cAAc,MAAQ,WAChC,SACW;CACX,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,YAAY,IAAI;EAClC,QAAQ;EACR,eAAe;EACf,GAAI,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM;CAClC,CAAC;CACD,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,MAAM,cAAc;IACnB,IAAI,QACH;IAED,SAAS;IACT,cAAc,SAAS;IAEvB,WAAW,oBAAoB,SAAS,KAAK;IAC7C,WAAW,MAAM;GAClB;GACA,MAAM,SAAS,SAAiB;IAC/B,IAAI,CAAC,QACJ,WAAW,QAAQ,QAAQ,OAAO,IAAI,CAAC;GAEzC;GACA,YAAY,kBAAkB;IAC7B,MAAM,YAAY;GACnB,GAAG,WAAW;GACd,WAAW,iBAAiB,SAAS,OAAO,EAAE,M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,OAAO;EAC3C,MAAM,eACL,OAAO,WAAW,YAAY,UAAU,OACrC,OAAO,YACP,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,WAAW,YAAY,CAAC,CACxE,IACC,CAAC;EACL,SAAS;GACR;GACA;GACA,QAAQ,OAAO,KAAK,YAAY,CAAC,CAAC,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/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,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,UAAU,OAAO;EAC3C,GAAI,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI;EAElC,GAAG,KAAK,MAAM,aAAa,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM;CAE7C,CAAC,CAAC,KAAK,IAAI,EAAE;AAC5B;;;;;;;;;;;;;;;;AAiBA,SAAgB,YACf,EAAE,QAAQ,cAAc,MAAQ,WAChC,SACW;CACX,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,YAAY,IAAI;EAClC,QAAQ;EACR,eAAe;EACf,GAAI,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM;CAClC,CAAC;CACD,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,MAAM,cAAc;IACnB,IAAI,QACH;IAED,SAAS;IACT,cAAc,SAAS;IAEvB,WAAW,oBAAoB,SAAS,KAAK;IAC7C,WAAW,MAAM;GAClB;GACA,MAAM,SAAS,SAAiB;IAC/B,IAAI,CAAC,QACJ,WAAW,QAAQ,QAAQ,OAAO,IAAI,CAAC;GAEzC;GACA,YAAY,kBAAkB;IAC7B,MAAM,YAAY;GACnB,GAAG,WAAW;GACd,WAAW,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;GAC1D,I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MACpB,MAAM,IAAI,MACT,kCAAkC,OAAO,OAAO,IAAI,WAAW,CAAC,CAAC,KAAK,IAAI,GAC3E;EAED,MAAM,SAA8B,OAAO;EAC3C,MAAM,eACL,OAAO,WAAW,YAAY,UAAU,OACrC,OAAO,YACP,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,WAAW,YAAY,CAAC,CACxE,IACC,CAAC;EACL,SAAS;GACR;GACA;GACA,QAAQ,OAAO,KAAK,YAAY,CAAC,CAAC,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,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};\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"}
@@ -0,0 +1,33 @@
1
+ import { n as isAppServerEntry, r as createServer, t as createEntry } from "./entry-BkdUub2S.js";
2
+ import { t as host } from "./node-YWPGmzAk.js";
3
+
4
+ // src/cli/load-entry.ts
5
+ /** Entries that this copy made for plain React Router builds, by build module. */
6
+ const plainEntries = /* @__PURE__ */ new WeakMap();
7
+ /**
8
+ * The entry that runs a server build: its `appServer` export when the
9
+ * `appServer` Vite plugin made it, else this copy of the package over a
10
+ * plain React Router build, on the node host, with the default plugins.
11
+ */
12
+ async function loadEntry(build) {
13
+ if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
14
+ const exported = Reflect.get(build, "appServer");
15
+ if (exported != null) {
16
+ 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.`);
17
+ return exported;
18
+ }
19
+ const known = plainEntries.get(build);
20
+ if (known != null) return known;
21
+ const { isServerBuild, runtime } = await import("./react-router.js");
22
+ if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
23
+ const entry = createEntry({
24
+ app: createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" }),
25
+ host,
26
+ framework: (mode) => runtime(build, { mode })
27
+ });
28
+ plainEntries.set(build, entry);
29
+ return entry;
30
+ }
31
+
32
+ export { loadEntry as t };
33
+ //# sourceMappingURL=load-entry-C03qqmhr.js.map
@@ -0,0 +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"}
@@ -0,0 +1,59 @@
1
+ // src/core/log.ts
2
+ /**
3
+ * A log sink that writes one JSON object per line. Each line has `time`,
4
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
5
+ * standard attributes.
6
+ *
7
+ * @param write - Where each line goes. Defaults to stdout.
8
+ *
9
+ * @example
10
+ * createServer({ logger: jsonSink() });
11
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
12
+ */
13
+ function jsonSink(write = (line) => {
14
+ process.stdout.write(line);
15
+ }) {
16
+ return { log: (level, message, attributes) => {
17
+ write(`${JSON.stringify({
18
+ time: (/* @__PURE__ */ new Date()).toISOString(),
19
+ level,
20
+ message,
21
+ ...attributes
22
+ })}\n`);
23
+ } };
24
+ }
25
+ /** Flat `error.*` attributes for a thrown value. */
26
+ function errorAttributes(error) {
27
+ if (error instanceof Error) return {
28
+ "error.kind": error.name,
29
+ "error.message": error.message,
30
+ "error.stack": error.stack
31
+ };
32
+ return { "error.message": String(error) };
33
+ }
34
+ /** A logger that writes to `sink`, with the attributes from `base` first on each line. */
35
+ function sinkLogger(sink, base = () => ({})) {
36
+ const line = (level) => (message, attributes = {}) => {
37
+ sink.log(level, message, {
38
+ ...base(),
39
+ ...attributes
40
+ });
41
+ };
42
+ return {
43
+ debug: line("debug"),
44
+ info: line("info"),
45
+ warn: line("warn"),
46
+ error: line("error")
47
+ };
48
+ }
49
+ /** A logger whose lines carry the request's ID, method, and path. */
50
+ function requestLogger(sink, context) {
51
+ return sinkLogger(sink, () => ({
52
+ "http.request_id": context.get("requestId"),
53
+ "http.method": context.req.method,
54
+ "http.url_details.path": context.req.path
55
+ }));
56
+ }
57
+
58
+ export { sinkLogger as i, jsonSink as n, requestLogger as r, errorAttributes as t };
59
+ //# sourceMappingURL=log-CsjaKM8U.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-CsjaKM8U.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\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.\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(\n\twrite: (line: string) => void = (line) => {\n\t\tprocess.stdout.write(line);\n\t},\n): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(\n\t\t\t\t`${JSON.stringify({ time: new Date().toISOString(), level, message, ...attributes })}\\n`,\n\t\t\t);\n\t\t},\n\t};\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\n/** A logger that writes to `sink`, with the attributes from `base` first on each line. */\nexport function sinkLogger(\n\tsink: LogSink,\n\tbase: () => Readonly<Record<string, unknown>> = () => ({}),\n): RequestLogger {\n\tconst line =\n\t\t(level: \"debug\" | \"info\" | \"warn\" | \"error\") =>\n\t\t(message: string, attributes: Readonly<Record<string, unknown>> = {}) => {\n\t\t\tsink.log(level, message, { ...base(), ...attributes });\n\t\t};\n\treturn { debug: line(\"debug\"), info: line(\"info\"), warn: line(\"warn\"), error: line(\"error\") };\n}\n\n/** A logger whose lines carry the request's ID, method, and path. */\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.\n\treturn sinkLogger(sink, () => ({\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}));\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,SACf,SAAiC,SAAS;CACzC,QAAQ,OAAO,MAAM,IAAI;AAC1B,GACU;CACV,OAAO,EACN,MAAM,OAAO,SAAS,eAAe;EACpC,MACC,GAAG,KAAK,UAAU;GAAE,uBAAM,IAAI,KAAK,EAAC,CAAC,YAAY;GAAG;GAAO;GAAS,GAAG;EAAW,CAAC,EAAE,GACtF;CACD,EACD;AACD;;AAGA,SAAgB,gBAAgB,OAAyC;CACxE,IAAI,iBAAiB,OACpB,OAAO;EAAE,cAAc,MAAM;EAAM,iBAAiB,MAAM;EAAS,eAAe,MAAM;CAAM;CAE/F,OAAO,EAAE,iBAAiB,OAAO,KAAK,EAAE;AACzC;;AAGA,SAAgB,WACf,MACA,cAAuD,CAAC,IACxC;CAChB,MAAM,QACJ,WACA,SAAiB,aAAgD,CAAC,MAAM;EACxE,KAAK,IAAI,OAAO,SAAS;GAAE,GAAG,KAAK;GAAG,GAAG;EAAW,CAAC;CACtD;CACD,OAAO;EAAE,OAAO,KAAK,OAAO;EAAG,MAAM,KAAK,MAAM;EAAG,MAAM,KAAK,MAAM;EAAG,OAAO,KAAK,OAAO;CAAE;AAC7F;;AAGA,SAAgB,cAAc,MAAe,SAA+C;CAE3F,OAAO,WAAW,aAAa;EAC9B,mBAAmB,QAAQ,IAAI,WAAW;EAC1C,eAAe,QAAQ,IAAI;EAC3B,yBAAyB,QAAQ,IAAI;CACtC,EAAE;AACH"}
@@ -1,8 +1,8 @@
1
- import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
1
+ import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
2
2
  import { IncomingMessage, ServerResponse } from "node:http";
3
3
  import { createAdaptorServer } from "@hono/node-server";
4
4
 
5
- // src/runtimes/node.ts
5
+ // src/node/runtimes/node.ts
6
6
  /**
7
7
  * Cancels the body of a response whose socket closed first, and returns the
8
8
  * response. `@hono/node-server` drops such a body with no cancel, and its
@@ -40,7 +40,7 @@ async function listen(fetch, options) {
40
40
  const port = typeof address === "object" && address != null ? address.port : options.port;
41
41
  return {
42
42
  url: listenerUrl(options.hostname, port),
43
- stop: ({ deadlineMs }) => new Promise((resolve, reject) => {
43
+ stop: async ({ deadlineMs }) => new Promise((resolve, reject) => {
44
44
  const deadline = setTimeout(() => {
45
45
  if ("closeAllConnections" in server) server.closeAllConnections();
46
46
  }, deadlineMs);
@@ -55,4 +55,4 @@ async function listen(fetch, options) {
55
55
  }
56
56
 
57
57
  export { listen as n, cancelIfClosed as t };
58
- //# sourceMappingURL=node-79my3Uix.js.map
58
+ //# sourceMappingURL=node-CG7qXuWZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-CG7qXuWZ.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { createAdaptorServer } from \"@hono/node-server\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/**\n * Cancels the body of a response whose socket closed first, and returns the\n * response. `@hono/node-server` drops such a body with no cancel, and its\n * producer runs on.\n */\nexport async function cancelIfClosed(\n\tresponse: Response,\n\toutgoing: { destroyed: boolean },\n): Promise<Response> {\n\tif (outgoing.destroyed) {\n\t\tawait response.body?.cancel();\n\t}\n\treturn response;\n}\n\n/** Listens with `node:http` through `@hono/node-server`. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst server = createAdaptorServer({\n\t\tfetch: async (request, { incoming, outgoing }) => {\n\t\t\tconst response = await fetch(request, {\n\t\t\t\tremoteAddress: incoming.socket.remoteAddress,\n\t\t\t\t...(incoming instanceof IncomingMessage && outgoing instanceof ServerResponse\n\t\t\t\t\t? { incoming, outgoing }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\treturn cancelIfClosed(response, outgoing);\n\t\t},\n\t\tserverOptions: {\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t});\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tif (\"closeAllConnections\" in server) {\n\t\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t\t}\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (\"closeIdleConnections\" in server) {\n\t\t\t\t\tserver.closeIdleConnections();\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;;;;;AAWA,eAAsB,eACrB,UACA,UACoB;CACpB,IAAI,SAAS,WACZ,MAAM,SAAS,MAAM,OAAO;CAE7B,OAAO;AACR;;AAGA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,SAAS,oBAAoB;EAClC,OAAO,OAAO,SAAS,EAAE,UAAU,eAAe;GAOjD,OAAO,eAAe,MANC,MAAM,SAAS;IACrC,eAAe,SAAS,OAAO;IAC/B,GAAI,oBAAoB,mBAAmB,oBAAoB,iBAC5D;KAAE;KAAU;IAAS,IACrB,CAAC;GACL,CAAC,GAC+B,QAAQ;EACzC;EACA,eAAe;GACd,kBAAkB,QAAQ;GAG1B,gBAAgB,QAAQ,gBAAgB;EACzC;CACD,CAAC;CACD,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,IAAI,yBAAyB,QAC5B,OAAO,oBAAoB;GAE7B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,IAAI,0BAA0B,QAC7B,OAAO,qBAAqB;EAE9B,CAAC;CACH;AACD"}
@@ -0,0 +1,215 @@
1
+ import { n as tcp } from "./tcp-C-9AmFuM.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { setTimeout } from "node:timers";
4
+ import { open, stat } from "node:fs/promises";
5
+ import { join, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { constants, createGzip } from "node:zlib";
8
+ import { IncomingMessage, ServerResponse } from "node:http";
9
+ import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
10
+
11
+ // src/node/exit.ts
12
+ /** How long the exit waits for stdout and stderr. */
13
+ const FLUSH_TIMEOUT_MS = 1e3;
14
+ /**
15
+ * Exits the process after stdout and stderr write what they hold, so the last
16
+ * log lines are not lost. The exit code is `process.exitCode`, else 0.
17
+ *
18
+ * Why exit at all: when shutdown is done, the server holds nothing open. A
19
+ * timer that the app left, such as the render abort timer in React Router's
20
+ * `entry.server`, would otherwise keep the stopped process alive.
21
+ */
22
+ function exitAfterFlush() {
23
+ let pending = 2;
24
+ const done = () => {
25
+ pending -= 1;
26
+ if (pending === 0) process.exit();
27
+ };
28
+ flush(process.stdout, done);
29
+ flush(process.stderr, done);
30
+ setTimeout(() => {
31
+ process.exit();
32
+ }, FLUSH_TIMEOUT_MS).unref();
33
+ }
34
+ /** Calls `done` after `stream` writes what it holds. */
35
+ function flush(stream, done) {
36
+ if ("Bun" in globalThis) {
37
+ stream.end(done);
38
+ return;
39
+ }
40
+ stream.write("", done);
41
+ }
42
+
43
+ // src/node/files.ts
44
+ /**
45
+ * A file's bytes, one chunk for each pull, so a slow client holds one chunk,
46
+ * not the whole file. The handle closes at the end, on an error, or on cancel.
47
+ */
48
+ function fileStream(handle) {
49
+ return new ReadableStream({
50
+ async pull(controller) {
51
+ try {
52
+ const { bytesRead, buffer } = await handle.read({ buffer: /* @__PURE__ */ new Uint8Array(65536) });
53
+ if (bytesRead === 0) {
54
+ await handle.close();
55
+ controller.close();
56
+ } else controller.enqueue(buffer.subarray(0, bytesRead));
57
+ } catch (error) {
58
+ await handle.close();
59
+ throw error;
60
+ }
61
+ },
62
+ cancel: async () => handle.close()
63
+ });
64
+ }
65
+ /**
66
+ * The client build on the file system. A relative `clientDirectory` is
67
+ * relative to the working directory.
68
+ *
69
+ * @example
70
+ * nodeFiles("build/client").stat("/llms.txt");
71
+ */
72
+ function nodeFiles(clientDirectory) {
73
+ const root = resolve(clientDirectory.startsWith("file:") ? fileURLToPath(clientDirectory) : clientDirectory);
74
+ const filePath = (path) => {
75
+ const candidate = join(root, path);
76
+ if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) throw new Error(`The path ${path} is outside the client build.`);
77
+ return candidate;
78
+ };
79
+ return {
80
+ stat: async (path) => {
81
+ const stats = await stat(filePath(path)).catch(() => void 0);
82
+ if (stats?.isFile() === true) return {
83
+ kind: "file",
84
+ size: stats.size,
85
+ mtimeMs: stats.mtimeMs
86
+ };
87
+ return stats?.isDirectory() === true ? {
88
+ kind: "directory",
89
+ size: 0,
90
+ mtimeMs: stats.mtimeMs
91
+ } : void 0;
92
+ },
93
+ open: async (path) => fileStream(await open(filePath(path)))
94
+ };
95
+ }
96
+
97
+ // src/node/gzip.ts
98
+ /**
99
+ * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
100
+ * once. It reads the next source chunk only when the consumer pulls, so a slow
101
+ * client holds back the source.
102
+ */
103
+ function gzipStream(source) {
104
+ const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
105
+ const reader = source.getReader();
106
+ return new ReadableStream({
107
+ start(controller) {
108
+ gzip.on("data", (chunk) => {
109
+ controller.enqueue(new Uint8Array(chunk));
110
+ });
111
+ gzip.on("end", () => {
112
+ controller.close();
113
+ });
114
+ gzip.on("error", (error) => {
115
+ controller.error(error);
116
+ });
117
+ },
118
+ async pull() {
119
+ try {
120
+ let chunk = await reader.read();
121
+ while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
122
+ if (chunk.done) {
123
+ gzip.end();
124
+ return;
125
+ }
126
+ const { value } = chunk;
127
+ await new Promise((resolve, reject) => {
128
+ gzip.write(value, (error) => {
129
+ if (error == null) resolve();
130
+ else reject(error);
131
+ });
132
+ });
133
+ } catch (error) {
134
+ gzip.destroy();
135
+ throw error;
136
+ }
137
+ },
138
+ async cancel(reason) {
139
+ gzip.destroy();
140
+ return reader.cancel(reason);
141
+ }
142
+ });
143
+ }
144
+
145
+ // src/node/dev-server.ts
146
+ function isServerResponse(value) {
147
+ return value instanceof ServerResponse;
148
+ }
149
+ /**
150
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
151
+ * middleware answers or calls `next`. A request with no Node request and
152
+ * response goes on.
153
+ *
154
+ * @example
155
+ * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares));
156
+ */
157
+ function devServerStage(middleware) {
158
+ return async (context, next) => {
159
+ const { incoming, outgoing } = context.env;
160
+ if (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) return next();
161
+ for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
162
+ if (await new Promise((resolve, reject) => {
163
+ const onFinish = () => {
164
+ resolve(true);
165
+ };
166
+ outgoing.once("finish", onFinish);
167
+ middleware(incoming, outgoing, (error) => {
168
+ outgoing.off("finish", onFinish);
169
+ if (error == null) resolve(false);
170
+ else reject(new Error("The dev server middleware failed", { cause: error }));
171
+ });
172
+ })) {
173
+ const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
174
+ const length = outgoing.getHeader("Content-Length");
175
+ if (length != null) headers.set("Content-Length", String(length));
176
+ return new Response(null, {
177
+ status: outgoing.statusCode,
178
+ headers
179
+ });
180
+ }
181
+ return next();
182
+ };
183
+ }
184
+
185
+ // src/node/index.ts
186
+ const storage = new AsyncLocalStorage();
187
+ /**
188
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
189
+ * Docker image. It listens with `tcp()`, reads the client build from the file
190
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
191
+ * `SIGINT`, it shuts down, then exits the process.
192
+ *
193
+ * @example
194
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
195
+ */
196
+ const host = {
197
+ name: "node",
198
+ files: nodeFiles,
199
+ listeners: () => [tcp()],
200
+ storage: {
201
+ run: (value, work) => storage.run(value, work),
202
+ get: () => storage.getStore()
203
+ },
204
+ gzip: gzipStream,
205
+ lifecycle: { onStop: (stop) => {
206
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
207
+ stop().catch(() => {
208
+ process.exitCode = 1;
209
+ }).finally(exitAfterFlush);
210
+ });
211
+ } }
212
+ };
213
+
214
+ export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
215
+ //# sourceMappingURL=node-YWPGmzAk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-YWPGmzAk.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/gzip.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { open, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { StaticFiles } from \"../core/types.js\";\n\n/**\n * A file's bytes, one chunk for each pull, so a slow client holds one chunk,\n * not the whole file. The handle closes at the end, on an error, or on cancel.\n */\nfunction fileStream(handle: FileHandle): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { bytesRead, buffer } = await handle.read({ buffer: new Uint8Array(65_536) });\n\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\tawait handle.close();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tawait handle.close();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel: async () => handle.close(),\n\t});\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\treturn {\n\t\tstat: async (path) => {\n\t\t\tconst stats = await stat(filePath(path)).catch(() => undefined);\n\t\t\tif (stats?.isFile() === true) {\n\t\t\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t\t\t}\n\t\t\treturn stats?.isDirectory() === true\n\t\t\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t\t\t: undefined;\n\t\t},\n\t\topen: async (path) => fileStream(await open(filePath(path))),\n\t};\n}\n","import { constants, createGzip } from \"node:zlib\";\n\n/**\n * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at\n * once. It reads the next source chunk only when the consumer pulls, so a slow\n * client holds back the source.\n */\nexport function gzipStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\tconst gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n\tconst reader = source.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tgzip.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tcontroller.enqueue(new Uint8Array(chunk));\n\t\t\t});\n\t\t\tgzip.on(\"end\", () => {\n\t\t\t\tcontroller.close();\n\t\t\t});\n\t\t\tgzip.on(\"error\", (error) => {\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\t\t},\n\t\tasync pull() {\n\t\t\ttry {\n\t\t\t\tlet chunk = await reader.read();\n\t\t\t\t// Why skip empty chunks: gzip writes nothing for one, and a pull that enqueues nothing\n\t\t\t\t// is not called again.\n\t\t\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\t\t\tchunk = await reader.read();\n\t\t\t\t}\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tgzip.end();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { value } = chunk;\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tgzip.write(value, (error) => {\n\t\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tgzip.destroy();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t// Why cancel the source: a client disconnect must reach the handler, so it stops its work.\n\t\tasync cancel(reason) {\n\t\t\tgzip.destroy();\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, ListenerBindings } from \"../core/types.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares));\n */\nexport function devServerStage(middleware: NodeMiddleware): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and length\n\t\t\t// are the middleware's, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tconst length = outgoing.getHeader(\"Content-Length\");\n\t\t\tif (length != null) {\n\t\t\t\theaders.set(\"Content-Length\", String(length));\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { gzipStream } from \"./gzip.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;AAGA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,IAAI,UAAU;CACd,MAAM,aAAa;EAClB,WAAW;EACX,IAAI,YAAY,GACf,QAAQ,KAAK;CAEf;CACA,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,QAAQ,QAAQ,IAAI;CAE1B,iBAAiB;EA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SACvC,SAAS,aAAa,MAAM,KAAK;EAgBlC,IAAI,MAdmB,IAAI,SAAkB,SAAS,WAAW;GAChE,MAAM,iBAAiB;IACtB,QAAQ,IAAI;GACb;GACA,SAAS,KAAK,UAAU,QAAQ;GAChC,WAAW,UAAU,WAAW,UAAU;IACzC,SAAS,IAAI,UAAU,QAAQ;IAC/B,IAAI,SAAS,MACZ,QAAQ,KAAK;SAEb,OAAO,IAAI,MAAM,oCAAoC,EAAE,OAAO,MAAM,CAAC,CAAC;GAExE,CAAC;EACF,CAAC,GACa;GAIb,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,MAAM,SAAS,SAAS,UAAU,gBAAgB;GAClD,IAAI,UAAU,MACb,QAAQ,IAAI,kBAAkB,OAAO,MAAM,CAAC;GAE7C,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACtCA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
@@ -0,0 +1,3 @@
1
+ import { n as listen, t as cancelIfClosed } from "./node-CG7qXuWZ.js";
2
+
3
+ export { listen };
@@ -0,0 +1,10 @@
1
+ import { r as HostBuild } from "./index-oSE-tYRW.js";
2
+ /**
3
+ * The build side of the node host: the server build gets
4
+ * `server/app-server.js`, which `app-server serve` runs.
5
+ *
6
+ * @example
7
+ * appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" });
8
+ */
9
+ export declare function node(): HostBuild;
10
+ //# sourceMappingURL=node-vite.d.ts.map
@@ -0,0 +1,18 @@
1
+ // src/node/vite.ts
2
+ /**
3
+ * The build side of the node host: the server build gets
4
+ * `server/app-server.js`, which `app-server serve` runs.
5
+ *
6
+ * @example
7
+ * appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" });
8
+ */
9
+ function node() {
10
+ return {
11
+ name: "node",
12
+ runtimeModule: "@ngrok/app-server/node",
13
+ entryFileName: "app-server.js"
14
+ };
15
+ }
16
+
17
+ export { node };
18
+ //# sourceMappingURL=node-vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-vite.js","names":[],"sources":["../src/node/vite.ts"],"sourcesContent":["import type { HostBuild } from \"../vite/index.js\";\n\n/**\n * The build side of the node host: the server build gets\n * `server/app-server.js`, which `app-server serve` runs.\n *\n * @example\n * appServer({ framework: reactRouterAdapter(), host: node(), app: \"./server.ts\" });\n */\nexport function node(): HostBuild {\n\treturn {\n\t\tname: \"node\",\n\t\truntimeModule: \"@ngrok/app-server/node\",\n\t\tentryFileName: \"app-server.js\",\n\t};\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,OAAkB;CACjC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;CAChB;AACD"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { b as StaticFiles, c as Listener, l as ListenerBindings, o as HostRuntime, t as AppServerEnv } from "./types-BfCkS7kQ.js";
2
+ import { MiddlewareHandler } from "hono";
3
+ import { IncomingMessage, ServerResponse } from "node:http";
4
+ /** A Connect middleware, such as `vite.middlewares`. */
5
+ type NodeMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
6
+ /** What a `node:http` listener passes to the app with each request. */
7
+ type NodeBindings = ListenerBindings & {
8
+ /** Node's request. */
9
+ incoming?: IncomingMessage;
10
+ /** Node's response. */
11
+ outgoing?: ServerResponse;
12
+ };
13
+ /**
14
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
15
+ * middleware answers or calls `next`. A request with no Node request and
16
+ * response goes on.
17
+ *
18
+ * @example
19
+ * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares));
20
+ */
21
+ export declare function devServerStage(middleware: NodeMiddleware): MiddlewareHandler<AppServerEnv>;
22
+ /**
23
+ * The client build on the file system. A relative `clientDirectory` is
24
+ * relative to the working directory.
25
+ *
26
+ * @example
27
+ * nodeFiles("build/client").stat("/llms.txt");
28
+ */
29
+ export declare function nodeFiles(clientDirectory: string): StaticFiles;
30
+ /** Options for {@link tcp}. */
31
+ type TcpOptions = {
32
+ /** @default the `PORT` environment variable, else 3000 */
33
+ port?: number;
34
+ /** @default the `HOST` environment variable, else every interface */
35
+ host?: string;
36
+ /** @default 95000 */
37
+ idleTimeoutMs?: number;
38
+ };
39
+ /**
40
+ * Reads a port number. A value that is not an integer from 0 to 65535 throws,
41
+ * so a bad `PORT` stops startup.
42
+ *
43
+ * @example
44
+ * parsePort("8080"); // => 8080
45
+ */
46
+ export declare function parsePort(value: string): number;
47
+ /**
48
+ * The default listener: a TCP port, served by the runtime's own HTTP server
49
+ * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
50
+ * `PORT` and `HOST` when it starts.
51
+ *
52
+ * @example
53
+ * createServer({ listeners: [tcp({ port: 8080 })] });
54
+ */
55
+ export declare function tcp({ port, host, idleTimeoutMs }?: TcpOptions): Listener;
56
+ /**
57
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
58
+ * Docker image. It listens with `tcp()`, reads the client build from the file
59
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
60
+ * `SIGINT`, it shuts down, then exits the process.
61
+ *
62
+ * @example
63
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
64
+ */
65
+ declare const host$1: HostRuntime;
66
+ export { type NodeBindings, type NodeMiddleware, type TcpOptions, host$1 as host };
67
+ //# sourceMappingURL=node.d.ts.map
package/dist/node.js ADDED
@@ -0,0 +1,4 @@
1
+ import { n as tcp, t as parsePort } from "./tcp-C-9AmFuM.js";
2
+ import { n as devServerStage, r as nodeFiles, t as host } from "./node-YWPGmzAk.js";
3
+
4
+ export { devServerStage, host, nodeFiles, parsePort, tcp };
@@ -0,0 +1,9 @@
1
+ import { n as FrameworkBuild } from "./index-oSE-tYRW.js";
2
+ /**
3
+ * The build side of the React Router adapter.
4
+ *
5
+ * @example
6
+ * appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" });
7
+ */
8
+ export declare function reactRouterAdapter(): FrameworkBuild;
9
+ //# sourceMappingURL=react-router-vite.d.ts.map
@@ -0,0 +1,21 @@
1
+ // src/react-router/vite.ts
2
+ /**
3
+ * The build side of the React Router adapter.
4
+ *
5
+ * @example
6
+ * appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" });
7
+ */
8
+ function reactRouterAdapter() {
9
+ return {
10
+ name: "react-router",
11
+ serverModule: "virtual:react-router/server-build",
12
+ runtimeModule: "@ngrok/app-server/react-router",
13
+ isPrerenderPass: () => process.env.IS_RR_BUILD_REQUEST === "yes",
14
+ validate: (config) => {
15
+ if (config.base !== "/") throw new Error(`@ngrok/app-server serves a build at "/" only, and this config has the base "${config.base}".`);
16
+ }
17
+ };
18
+ }
19
+
20
+ export { reactRouterAdapter };
21
+ //# sourceMappingURL=react-router-vite.js.map