@ngrok/app-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +610 -76
  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.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"entry-BkdUub2S.js","names":["requestId","honoRequestId","requestId"],"sources":["../src/core/plugins/access-log.ts","../src/core/plugins/request-id.ts","../src/core/static-files.ts","../src/core/plugins/static.ts","../src/core/plugins/streaming-compress.ts","../src/core/request-context.ts","../src/core/shutdown.ts","../src/core/create-server.ts","../src/core/entry.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = [...url.searchParams.keys()]\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the body ends or the client\n * disconnects, so a streamed response logs its full duration and size.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({ redactQuery = true }: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\tawait next();\n\t\t\tconst write = ({ bytes, aborted }: { bytes: number; aborted: boolean }) => {\n\t\t\t\tcontext.var.logger.info(\"request\", lineAttributes(context, { bytes, aborted, started }));\n\t\t\t};\n\t\t\tconst response = context.res;\n\t\t\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\t\t\tif (context.req.method === \"HEAD\") {\n\t\t\t\twrite({ bytes: 0, aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t\t\t// development, gives a response with no body and the length it sent.\n\t\t\tif (response.body == null) {\n\t\t\t\twrite({ bytes: Number(response.headers.get(\"Content-Length\") ?? 0), aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tlet bytes = 0;\n\t\t\tconst counted = new ReadableStream<Uint8Array>({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = await reader.read();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tconst { done, value } = result;\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\twrite({ bytes, aborted: false });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tbytes += value.byteLength;\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t},\n\t\t\t\tasync cancel(reason) {\n\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontext.res = new Response(counted, response);\n\t\t},\n\t};\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ bytes, aborted, started }: { bytes: number; aborted: boolean; started: number },\n\t): Record<string, unknown> {\n\t\treturn {\n\t\t\t\"http.url\": loggedUrl(new URL(context.req.url), { redact: redactQuery }),\n\t\t\t\"http.status_code\": context.res.status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.env.remoteAddress,\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t\t...(aborted ? { \"http.client_aborted\": true } : {}),\n\t\t};\n\t}\n}\n","import { requestId as honoRequestId } from \"hono/request-id\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n};\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({ headerName = \"X-Request-Id\" }: RequestIdOptions = {}): Plugin {\n\tconst assign = honoRequestId({ headerName });\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait assign(context, next);\n\t\t\t// Why set it again: a `Response` that the framework returns replaces the headers set before `next`.\n\t\t\t// `context.header` also copies a response whose headers are immutable.\n\t\t\tconst id = context.get(\"requestId\");\n\t\t\tif (id != null) {\n\t\t\t\tcontext.header(headerName, id);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport type { AppServerEnv, StaticFiles } from \"./types.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The URL path of the file, such as `/components/button/index.html`. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/** The content types that `mime` lacks and that no framework owns. */\nconst CORE_CONTENT_TYPES: Readonly<Record<string, string>> = {\n\t\".md\": \"text/markdown; charset=utf-8\",\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n */\nfunction hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\n/**\n * Finds the file in `files` that answers a decoded URL path, such as Hono's\n * `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. Dotfiles and paths that\n * leave the client build find nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(files, \"/components/button\");\n * // => { path: \"/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(\n\tfiles: StaticFiles,\n\tpath: string,\n): Promise<StaticFile | undefined> {\n\tif (\n\t\t!path.startsWith(\"/\") ||\n\t\tpath.includes(\"\\0\") ||\n\t\tpath.includes(\"\\\\\") ||\n\t\tpath.split(\"/\").includes(\"..\") ||\n\t\tpath.includes(\"//\") ||\n\t\tpath.endsWith(\"/index.html\") ||\n\t\thasDotSegment(path)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst info = await files.stat(path);\n\tif (info?.kind === \"file\") {\n\t\treturn { path, size: info.size, mtimeMs: info.mtimeMs };\n\t}\n\tif (info?.kind === \"directory\") {\n\t\tconst index = `${path.replace(/\\/$/u, \"\")}/index.html`;\n\t\tconst indexInfo = await files.stat(index);\n\t\tif (indexInfo?.kind === \"file\") {\n\t\t\treturn { path: index, size: indexInfo.size, mtimeMs: indexInfo.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The content type of a file, by its extension. `contentTypes` win over `mime`. */\nfunction contentType(path: string, contentTypes: Readonly<Record<string, string>>): string {\n\tconst extension = /\\.[^./]+$/u.exec(path)?.[0] ?? \"\";\n\treturn (\n\t\tcontentTypes[extension] ??\n\t\tCORE_CONTENT_TYPES[extension] ??\n\t\tgetMimeType(path) ??\n\t\t\"application/octet-stream\"\n\t);\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//u, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */\nasync function fileEtag(file: StaticFile, parts: readonly string[]): Promise<string> {\n\tconst base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;\n\tif (parts.length === 0) {\n\t\treturn `W/\"${base}\"`;\n\t}\n\t// Why Web Crypto: each host has it, and the core imports no Node module.\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(parts.join(\"\\0\")));\n\tconst hash = btoa(String.fromCodePoint(...new Uint8Array(digest)))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.slice(0, 16);\n\treturn `W/\"${base}-${hash}\"`;\n}\n\n/** What {@link staticResponse} needs besides the request. */\nexport type StaticResponseOptions = {\n\tfiles: StaticFiles;\n\tfile: StaticFile;\n\t/** Headers that replace the defaults, so a captured `Content-Type` wins over the one from the file name. */\n\theaders: Readonly<Record<string, string>>;\n\tcontentTypes: Readonly<Record<string, string>>;\n};\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, and the request's `etagParts`. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only.\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\t{ files, file, headers, contentTypes }: StaticResponseOptions,\n): Promise<Response> {\n\tconst etag = await fileEtag(file, context.get(\"etagParts\") ?? []);\n\tconst responseHeaders = new Headers({\n\t\t\"Content-Type\": contentType(file.path, contentTypes),\n\t\tETag: etag,\n\t});\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why the final header: `headers` can replace the ETag.\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), responseHeaders.get(\"ETag\") ?? etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\tif (context.req.method === \"HEAD\") {\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\treturn new Response(await files.open(file.path), { headers: responseHeaders });\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { manifestKey } from \"../build-manifest.js\";\nimport { findStaticFile, staticResponse } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/**\n * Serves the hashed files under `/assets/` with a one-year immutable cache.\n * A missing asset gets a plain 404, not a rendered page. In development,\n * the dev server serves the source modules, the HMR client, and the CSS here\n * instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tstage = info.devServer;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes } = info;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(\"/assets/\") || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(files, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn context.text(\"Not Found\", 404);\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: { \"Cache-Control\": IMMUTABLE },\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (\n\t\tpath: string,\n\t\tcontext: Context<AppServerEnv>,\n\t) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t */\n\trewrite?: (path: string, context: Context<AppServerEnv>) => string;\n};\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200 and\n * no trailing-slash redirect, plus every other file in it. Each response gets\n * the headers its loader sent at build time (the `appServer` Vite plugin\n * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path\n * with no file goes on to the framework. Off in development.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: (path) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes, capturedHeaders } = info;\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(files, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log(\"warn\", \"prerendered paths with no file\", {\n\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t});\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst path = options.rewrite?.(context.req.path, context) ?? context.req.path;\n\t\t\t\tconst file = await findStaticFile(files, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...capturedHeaders.get(manifestKey(path)),\n\t\t\t\t\t\t...options.headers?.(path, context),\n\t\t\t\t\t},\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { accepts } from \"hono/accepts\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\n\nconst COMPRESSIBLE =\n\t/^(?:text\\/|application\\/(?:json|javascript|xml|schema\\+json|manifest\\+json|x-ndjson|connect\\+json)|image\\/svg\\+xml)/u;\n\n/**\n * Gzips text responses and flushes after each chunk, so a streamed page shell\n * or a server-sent event reaches the client at once. `hono/compress` holds a\n * stream until it ends. Skips a response that is already encoded, a partial\n * response, and one marked `no-transform`. It sets `Vary: Accept-Encoding` on\n * each response. The host gives the gzip stream. On a host with none, the\n * plugin does nothing.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\tlet gzip: SetupInfo[\"gzip\"];\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tsetup: (info) => {\n\t\t\t({ gzip } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tif (gzip == null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why `context.header`: it copies a response whose headers are immutable, such as one from `fetch`.\n\t\t\tcontext.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tresponse.body == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\taccepts(context, { header: \"Accept-Encoding\", supports: [\"gzip\"], default: \"identity\" }) !==\n\t\t\t\t\t\"gzip\" ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: gzip 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/\\bno-transform\\b/u.test(response.headers.get(\"Cache-Control\") ?? \"\") ||\n\t\t\t\t!COMPRESSIBLE.test(response.headers.get(\"Content-Type\") ?? \"\")\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontext.res = new Response(gzip(response.body), response);\n\t\t\t// Why after the assignment: Hono copies the old response's headers onto the new one.\n\t\t\tcontext.res.headers.set(\"Content-Encoding\", \"gzip\");\n\t\t\tcontext.res.headers.delete(\"Content-Length\");\n\t\t},\n\t};\n}\n","import type { Context } from \"hono\";\nimport type { AppServerEnv, RequestContext, RequestStore } from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<void>,\n): Promise<void> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID and logger of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn { requestId: context.get(\"requestId\"), logger: context.var.logger };\n\t\t}\n\t}\n\treturn undefined;\n}\n","let controller = new AbortController();\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import { Hono } from \"hono\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog } from \"./plugins/access-log.js\";\nimport type { AccessLogOptions } from \"./plugins/access-log.js\";\nimport { requestId } from \"./plugins/request-id.js\";\nimport type { RequestIdOptions } from \"./plugins/request-id.js\";\nimport { assets, prerendered } from \"./plugins/static.js\";\nimport type { PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { withRequestContext } from \"./request-context.js\";\nimport { abortShutdownSignal, renewShutdownSignal } from \"./shutdown.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tListener,\n\tLogSink,\n\tPlugin,\n\tRequestStore,\n\tSetupInfo,\n} from \"./types.js\";\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Aborts `shutdownSignal()`, then runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/**\n\t * Starts the app's listeners, else `defaultListeners`, the host's. Call\n\t * `prepare` first.\n\t */\n\tlisten: (\n\t\tframework: FrameworkRuntime,\n\t\tdefaultListeners: readonly Listener[],\n\t) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Sets the storage for `requestContext()` in this app's requests. `createEntry` sets the host's. */\n\tsetRequestStore: (store: RequestStore | undefined) => void;\n};\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Plugins that go after compression and before the static stages, so they\n\t * see every response, prerendered pages included. `runtimeEnv` and\n\t * `buildId` go here.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `requestId`, `accessLog`,\n * `streamingCompress`, the `beforeStatic` plugins, `assets`, and\n * `prerendered`. It is a plain array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\treturn [\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\tprerendered(options.prerendered),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/** @default the host's listeners, such as `[tcp()]` on the node host */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How long open requests get to finish after a stop signal.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */\nfunction withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\tif (proto !== \"http\" && proto !== \"https\") {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\treturn new Request(url, request);\n}\n\n/**\n * Runs `step`, and rethrows a thrown value that is not an `Error` as one.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nasync function asError<Result>(step: () => Promise<Result>): Promise<Result> {\n\ttry {\n\t\treturn await step();\n\t} catch (error) {\n\t\tthrow error instanceof Error\n\t\t\t? error\n\t\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n\t}\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });\n * app.get(\"/livez\", (c) => c.text(\"ok\"));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger = jsonSink(),\n\tlisteners,\n\ttrustForwardedProto = false,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tconst app = new Hono<AppServerEnv>();\n\tlet requestStore: RequestStore | undefined;\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tcontext.set(\"logger\", requestLogger(logger, context));\n\t\tawait withRequestContext(requestStore, context, next);\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use(async (context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\treturn asError(async () => (middleware == null ? next() : middleware(context, next)));\n\t\t});\n\t}\n\tapp.use(async (_, next) => asError(next));\n\tapp.onError((error, context) => {\n\t\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\t\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\t\tconst response: unknown = error.getResponse();\n\t\t\tif (response instanceof Response) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}\n\t\tcontext.var.logger.error(\"unhandled error\", errorAttributes(error));\n\t\treturn context.text(\"Internal Server Error\", 500);\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tsetRequestStore: (store) => {\n\t\t\trequestStore = store;\n\t\t},\n\t\tprepare: async (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", async (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})();\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework, defaultListeners) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst starts = await Promise.allSettled(\n\t\t\t\t(listeners ?? defaultListeners).map(async (listener) => listener.start(fetch)),\n\t\t\t);\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log(\"info\", \"listening\", { \"app_server.urls\": urls });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: async () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tlogger.log(\"info\", \"draining\", { \"app_server.deadline_ms\": shutdownDeadlineMs });\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\t// Why settle all: the process exits after shutdown, so one failed stop must not cut\n\t\t\t\t\t\t// the other stops short.\n\t\t\t\t\t\tconst results = await Promise.allSettled([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tconst rejected = results.find((result) => result.status === \"rejected\");\n\t\t\t\t\t\tif (rejected != null) {\n\t\t\t\t\t\t\tthrow rejected.reason;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log(\"info\", \"stopped\", {});\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: async () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log(\"error\", \"plugin shutdown failed\", errorAttributes(result.reason));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log(\"warn\", \"plugin shutdown passed the deadline\", {\n\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport type {\n\tAppServerEnv,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = framework(\"production\");\n\t\t\tconst shared = await setupInfo(runtime);\n\t\t\tconst { prerendered, headers } = await readBuildManifest(shared.files);\n\t\t\tconst info: SetupInfo = {\n\t\t\t\t...shared,\n\t\t\t\tmode: \"production\",\n\t\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? prerendered,\n\t\t\t\tcapturedHeaders: new Map(Object.entries(headers)),\n\t\t\t};\n\t\t\tawait internals.prepare(info);\n\t\t\tconst server = await internals.listen(runtime, host.listeners());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths ?? [],\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,SAAgB,UAAU,KAAU,EAAE,UAAuC;CAC5E,IAAI,CAAC,UAAU,IAAI,WAAW,IAC7B,OAAO,GAAG,IAAI,WAAW,IAAI;CAE9B,MAAM,QAAQ,CAAC,GAAG,IA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AO;EACN;EACA;EACA,OAAO,YAAY;GAClB,MAAM,UAAU,UAAU,YAAY;GACtC,MAAM,SAAS,MAAM,UAAU,OAAO;GACtC,MAAM,EAAE,aAAa,YAAY,MAAM,kBAAkB,OAAO,KAAK;GACrE,MAAM,OAAkB;IACvB,GAAG;IACH,MAAM;IACN,kBAAkB,QAAQ,oBAAoB;IAC9C,iBAAiB,IAAI,IAAI,OAAO,QAAQ,OAAO,CAAC;GACjD;GACA,MAAM,UAAU,QAAQ,IAAI;GAC5B,MAAM,SAAS,MAAM,UAAU,OAAO,SAAS,KAAK,UAAU,CAAC;GAC/D,KAAK,WAAW,OAAO,YACtB,OAAO,SAAS,CAAC,CAAC,OAAO,UAAmB;IAC3C,UAAU,OAAO,IAAI,SAAS,mBAAmB,gBAAgB,KAAK,CAAC;IACvE,MAAM;GACP,CAAC,CACF;EACD;EACA,UAAU,OAAO,SAAS,UAAU,cAAc;GACjD,gBAAgB,UAAU,aAAa;GACvC,MAAM,UAAU,QAAQ;IACvB,GAAI,MAAM,UAAU,WAAW;IAC/B,MAAM;IACN;IACA,kBAAkB,YAAY,oBAAoB,CAAC;IACnD,iCAAiB,IAAI,IAAI;GAC1B,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
@@ -1,59 +0,0 @@
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
@@ -1 +0,0 @@
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,58 +0,0 @@
1
- import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
2
- import { IncomingMessage, ServerResponse } from "node:http";
3
- import { createAdaptorServer } from "@hono/node-server";
4
-
5
- // src/node/runtimes/node.ts
6
- /**
7
- * Cancels the body of a response whose socket closed first, and returns the
8
- * response. `@hono/node-server` drops such a body with no cancel, and its
9
- * producer runs on.
10
- */
11
- async function cancelIfClosed(response, outgoing) {
12
- if (outgoing.destroyed) await response.body?.cancel();
13
- return response;
14
- }
15
- /** Listens with `node:http` through `@hono/node-server`. */
16
- async function listen(fetch, options) {
17
- const server = createAdaptorServer({
18
- fetch: async (request, { incoming, outgoing }) => {
19
- return cancelIfClosed(await fetch(request, {
20
- remoteAddress: incoming.socket.remoteAddress,
21
- ...incoming instanceof IncomingMessage && outgoing instanceof ServerResponse ? {
22
- incoming,
23
- outgoing
24
- } : {}
25
- }), outgoing);
26
- },
27
- serverOptions: {
28
- keepAliveTimeout: options.idleTimeoutMs,
29
- headersTimeout: options.idleTimeoutMs + 1e3
30
- }
31
- });
32
- await new Promise((resolve, reject) => {
33
- server.once("error", reject);
34
- server.listen(options.port, options.hostname, () => {
35
- server.off("error", reject);
36
- resolve();
37
- });
38
- });
39
- const address = server.address();
40
- const port = typeof address === "object" && address != null ? address.port : options.port;
41
- return {
42
- url: listenerUrl(options.hostname, port),
43
- stop: async ({ deadlineMs }) => new Promise((resolve, reject) => {
44
- const deadline = setTimeout(() => {
45
- if ("closeAllConnections" in server) server.closeAllConnections();
46
- }, deadlineMs);
47
- server.close((error) => {
48
- clearTimeout(deadline);
49
- if (error == null) resolve();
50
- else reject(error);
51
- });
52
- if ("closeIdleConnections" in server) server.closeIdleConnections();
53
- })
54
- };
55
- }
56
-
57
- export { listen as n, cancelIfClosed as t };
58
- //# sourceMappingURL=node-CG7qXuWZ.js.map
@@ -1 +0,0 @@
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"}
@@ -1,215 +0,0 @@
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
@@ -1 +0,0 @@
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,I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,KAAK;EAIb,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ,IAAI,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"}
@@ -1,3 +0,0 @@
1
- import { n as listen, t as cancelIfClosed } from "./node-CG7qXuWZ.js";
2
-
3
- export { listen };
@@ -1 +0,0 @@
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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"react-router-vite.js","names":[],"sources":["../src/react-router/vite.ts"],"sourcesContent":["import type { FrameworkBuild } from \"../vite/index.js\";\n\n/**\n * The build side of the React Router adapter.\n *\n * @example\n * appServer({ framework: reactRouterAdapter(), host: node(), app: \"./server.ts\" });\n */\nexport function reactRouterAdapter(): FrameworkBuild {\n\treturn {\n\t\tname: \"react-router\",\n\t\tserverModule: \"virtual:react-router/server-build\",\n\t\truntimeModule: \"@ngrok/app-server/react-router\",\n\t\t// Why this flag: React Router sets it for the preview server of its prerender pass only.\n\t\tisPrerenderPass: () => process.env.IS_RR_BUILD_REQUEST === \"yes\",\n\t\tvalidate: (config) => {\n\t\t\tif (config.base !== \"/\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this config has the base \"${config.base}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,qBAAqC;CACpD,OAAO;EACN,MAAM;EACN,cAAc;EACd,eAAe;EAEf,uBAAuB,QAAQ,IAAI,wBAAwB;EAC3D,WAAW,WAAW;GACrB,IAAI,OAAO,SAAS,KACnB,MAAM,IAAI,MACT,+EAA+E,OAAO,KAAK,GAC5F;EAEF;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"start-CINALHxy.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer, IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { cancelIfClosed } from \"../node/runtimes/node.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares);\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = getRequestListener(async (request, { incoming, outgoing }) => {\n\t\ttry {\n\t\t\tconst response = await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) =>\n\t\t\t\t\tentry.fetchDev(\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tremoteAddress: incoming.socket.remoteAddress,\n\t\t\t\t\t\t\t// Why the check: the listener is plain `node:http`, so these are always HTTP/1 objects.\n\t\t\t\t\t\t\t...(incoming instanceof IncomingMessage && outgoing instanceof ServerResponse\n\t\t\t\t\t\t\t\t? { incoming, outgoing }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdevServer,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\treturn await cancelIfClosed(response, outgoing);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,WAAW,MAAM;KACpB,QAAQ,WAAW;KACnB,IAAI,QAAQ,YAAY,GACvB,AAAK,OAAO,OAAO;IAErB;IACA,UAAU;KAAE;KAAO,SAAS;KAAG,UAAU;IAAM;IAC/C,OAAO,IAAI,OAAO;GACnB;GACA,MAAM,MAAM;GACZ,IAAI,WAAW;GACf,IAAI;IACH,OAAO,MAAM,OAAO,KAAK;GAC1B,UAAU;IACT,IAAI,WAAW;IACf,IAAI,IAAI,YAAY,IAAI,YAAY,GACnC,AAAK,OAAO,GAAG;GAEjB;EACD;EACA,SAAS,YAAY;GACpB,MAAM,QAAQ,IACb,MAAM,KAAK,QAAQ,OAAO,QAAQ;IACjC,IAAI,MAAM,oBAAoB;IAC9B,MAAM,OAAO,GAAG;GACjB,CA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;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tanstack-start-vite.js","names":[],"sources":["../src/tanstack-start/vite.ts"],"sourcesContent":["import type { FrameworkBuild } from \"../vite/index.js\";\n\n/**\n * The build side of the TanStack Start adapter. In `app-server start`, Vite\n * runs in middleware mode, so Start skips its own SSR middleware, and the\n * pipeline renders each page.\n *\n * @example\n * appServer({ framework: tanstackStartAdapter(), host: node(), app: \"./server.ts\" });\n */\nexport function tanstackStartAdapter(): FrameworkBuild {\n\treturn {\n\t\tname: \"tanstack-start\",\n\t\tserverModule: \"virtual:tanstack-start-server-entry\",\n\t\truntimeModule: \"@ngrok/app-server/tanstack-start\",\n\t\t// Why in the entry: Start defines `TSS_SERVER_FN_BASE` at build time, so only bundled code sees it.\n\t\truntimeOptions: \"{ serverFnBase: process.env.TSS_SERVER_FN_BASE }\",\n\t\t// Why this flag: Start sets it in the build process before it starts the preview server\n\t\t// of its prerender pass.\n\t\tisPrerenderPass: () => process.env.TSS_PRERENDERING === \"true\",\n\t\tvalidate: (config) => {\n\t\t\tif (config.base !== \"/\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this config has the base \"${config.base}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,uBAAuC;CACtD,OAAO;EACN,MAAM;EACN,cAAc;EACd,eAAe;EAEf,gBAAgB;EAGhB,uBAAuB,QAAQ,IAAI,qBAAqB;EACxD,WAAW,WAAW;GACrB,IAAI,OAAO,SAAS,KACnB,MAAM,IAAI,MACT,+EAA+E,OAAO,KAAK,GAC5F;EAEF;CACD;AACD"}