@ngrok/app-server 0.0.0-stage → 0.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-2XXp2Ukh.js","names":["requestId","honoRequestId","requestId"],"sources":["../src/log.ts","../src/plugins/access-log.ts","../src/plugins/request-id.ts","../src/static-files.ts","../src/plugins/static.ts","../src/plugins/streaming-compress.ts","../src/shutdown.ts","../src/tcp.ts","../src/create-server.ts","../src/entry.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","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 = Array.from(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 { createHash } from \"node:crypto\";\nimport { open, stat, type FileHandle } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport type { AppServerEnv } from \"./types.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The absolute file path. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\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\nasync function fileStats(path: string) {\n\ttry {\n\t\treturn await stat(path);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Finds the file under `root` that answers a decoded URL path, such as\n * Hono's `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside\n * `root` 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(\"/app/build/client\", \"/components/button\");\n * // => { path: \"/app/build/client/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(root: string, path: string): Promise<StaticFile | undefined> {\n\tif (\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 candidate = join(root, path);\n\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\treturn undefined;\n\t}\n\tconst stats = await fileStats(candidate);\n\tif (stats?.isFile()) {\n\t\treturn { path: candidate, size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\tif (stats?.isDirectory()) {\n\t\tconst index = join(candidate, \"index.html\");\n\t\tconst indexStats = await fileStats(index);\n\t\tif (indexStats?.isFile()) {\n\t\t\treturn { path: index, size: indexStats.size, mtimeMs: indexStats.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\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: () => handle.close(),\n\t});\n}\n\n/** The content type of a file, with the React Router and markdown types that `mime` lacks. */\nfunction contentType(path: string): string {\n\tif (path.endsWith(\".md\")) {\n\t\treturn \"text/markdown; charset=utf-8\";\n\t}\n\tif (path.endsWith(\".data\")) {\n\t\treturn \"text/x-script\";\n\t}\n\treturn getMimeType(path) ?? \"application/octet-stream\";\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\\//, \"\");\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`. */\nfunction fileEtag(file: StaticFile, parts: readonly string[]): 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\tconst hash = createHash(\"sha256\").update(parts.join(\"\\0\")).digest(\"base64url\").slice(0, 16);\n\treturn `W/\"${base}-${hash}\"`;\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. `headers`\n * replace the defaults, so a captured `Content-Type` wins over the one from\n * the file name.\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\tfile: StaticFile,\n\theaders: Readonly<Record<string, string>>,\n): Promise<Response> {\n\tconst etag = fileEtag(file, context.get(\"etagParts\") ?? []);\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path), ETag: etag });\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\tif (context.req.method === \"HEAD\") {\n\t\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\treturn new Response(fileStream(await open(file.path)), { headers: responseHeaders });\n}\n","import { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { capturedHeadersKey, readCapturedHeaders } from \"../captured-headers.js\";\nimport { findStaticFile, staticResponse } from \"../static-files.js\";\nimport type { AppServerEnv, NodeMiddleware, Plugin } from \"../types.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */\nfunction viteStage(viteMiddleware: NodeMiddleware): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (incoming == null || outgoing == null) {\n\t\t\treturn next();\n\t\t}\n\t\t// Why before Vite: it sends the headers itself, so the headers the earlier stages set, such\n\t\t// 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\tviteMiddleware(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(\"Vite 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 Vite'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\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 * Vite serves the source modules, the HMR client, and the CSS here 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 = viteStage(info.viteMiddleware);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst root = info.clientDirectory;\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(root, 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, file, { \"Cache-Control\": IMMUTABLE });\n\t\t\t};\n\t\t},\n\t\tmiddleware: (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 `serverEntry` 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 root = info.clientDirectory;\n\t\t\tconst captured = await readCapturedHeaders(root);\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(root, 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(root, 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, file, {\n\t\t\t\t\t...captured.get(capturedHeadersKey(path)),\n\t\t\t\t\t...options.headers?.(path, context),\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { accepts } from \"hono/accepts\";\nimport { constants, createGzip } from \"node:zlib\";\nimport type { Plugin } from \"../types.js\";\n\nconst COMPRESSIBLE =\n\t/^(text\\/|application\\/(json|javascript|xml|schema\\+json|manifest\\+json|x-ndjson|connect\\+json)|image\\/svg\\+xml)/;\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 */\nfunction 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\tcancel(reason) {\n\t\t\tgzip.destroy();\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n}\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`. Always sets `Vary: Accept-Encoding`.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\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/.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(gzipStream(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","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 type { Listener } from \"./types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n","import { Hono } from \"hono\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog, type AccessLogOptions } from \"./plugins/access-log.js\";\nimport { requestId, type RequestIdOptions } from \"./plugins/request-id.js\";\nimport { assets, prerendered, type PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { abortShutdownSignal, renewShutdownSignal } from \"./shutdown.js\";\nimport { tcp } from \"./tcp.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkAdapter,\n\tListener,\n\tLogSink,\n\tPlugin,\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/** Starts the listeners. Call `prepare` first. */\n\tlisten: (framework: FrameworkAdapter) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<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 [tcp()] */\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 = [tcp()],\n\ttrustForwardedProto = false,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tconst app = new Hono<AppServerEnv>();\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 = (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 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((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((_, 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\tprepare: (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(\"*\", (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) => {\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(listeners.map((listener) => listener.start(fetch)));\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((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: () => {\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\tawait Promise.all([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map((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\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: () => {\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 { serverInternals, type AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport type { FrameworkAdapter, ListenerBindings, NodeMiddleware, SetupInfo } from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 1;\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/** Production: runs each plugin's `setup`, listens, and shuts down on `SIGTERM` or `SIGINT`. */\n\tstart: () => Promise<void>;\n\t/** Development: answers one request with Vite's middleware inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tviteMiddleware: NodeMiddleware,\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/**\n * The `appServer` export of a server build: an app from `createServer` and\n * the framework adapter for each mode. The `serverEntry` Vite plugin makes\n * this export for a React Router build. Call this for another framework.\n *\n * @example\n * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });\n */\nexport function createEntry({\n\tapp,\n\tframework,\n}: {\n\tapp: AppServer;\n\tframework: (mode: SetupInfo[\"mode\"]) => FrameworkAdapter;\n}): 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\tlet development: FrameworkAdapter | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst adapter = framework(\"production\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"production\",\n\t\t\t\tclientDirectory: adapter.clientDirectory,\n\t\t\t\tprerenderedPaths: adapter.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\n\t\t\t});\n\t\t\tconst server = await internals.listen(adapter);\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tfetchDev: async (request, bindings, viteMiddleware) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"development\",\n\t\t\t\tviteMiddleware,\n\t\t\t\tclientDirectory: development.clientDirectory,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\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\nfunction 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\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 * `serverEntry` Vite plugin made it, else this copy of the package over a\n * plain React Router build 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 { appServerEntry, isServerBuild } = await import(\"./react-router.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 = appServerEntry(build);\n\tplainEntries.set(build, entry);\n\treturn entry;\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,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{ Context, Hono, MiddlewareHandler } from "hono";
2
+ import { IncomingMessage, ServerResponse } from "node:http";
3
+ /** A log level the server writes. */
4
+ type LogLevel = "debug" | "info" | "warn" | "error";
5
+ /**
6
+ * Where the server writes log lines. Pass the app's own formatter, or use
7
+ * {@link jsonSink}. Attribute names are flat and dotted, such as `http.method`.
8
+ */
9
+ type LogSink = {
10
+ log: (level: LogLevel, message: string, attributes: Readonly<Record<string, unknown>>) => void;
11
+ };
12
+ /** The logger for one request. Each line carries the request ID, method, and path. */
13
+ type RequestLogger = Record<LogLevel, (message: string, attributes?: Readonly<Record<string, unknown>>) => void>;
14
+ /** The framework that answers each request that no plugin or route answers. */
15
+ type FrameworkAdapter = {
16
+ /** Renders one request. */
17
+ fetch: (request: Request, context: Context<AppServerEnv>) => Promise<Response>;
18
+ /** The absolute path of the client build, such as `<root>/build/client`. */
19
+ clientDirectory: string;
20
+ /** The URL paths that the build prerendered. */
21
+ prerenderedPaths: readonly string[];
22
+ };
23
+ /** What a listener passes to the app with each request. */
24
+ type ListenerBindings = {
25
+ /** The client's IP address, when the runtime knows it. */
26
+ remoteAddress?: string;
27
+ /** Node's request, on a `node:http` listener only. */
28
+ incoming?: IncomingMessage;
29
+ /** Node's response, on a `node:http` listener only. */
30
+ outgoing?: ServerResponse;
31
+ };
32
+ /** The Hono bindings of an app server: the listener's values and the framework. */
33
+ type ServerBindings = ListenerBindings & {
34
+ framework: FrameworkAdapter;
35
+ };
36
+ /** The Hono environment of an app server. */
37
+ type AppServerEnv = {
38
+ Bindings: ServerBindings;
39
+ Variables: {
40
+ /** The request ID, set by the `requestId` plugin. */
41
+ requestId?: string;
42
+ logger: RequestLogger;
43
+ /**
44
+ * The `etagPart` of each plugin that the request passed, in order. The
45
+ * static stages add them to each file's ETag. The server sets this list.
46
+ */
47
+ etagParts?: readonly string[];
48
+ };
49
+ };
50
+ /** The request handler that a listener calls. */
51
+ type FetchHandler = (request: Request, bindings: ListenerBindings) => Response | Promise<Response>;
52
+ /** A Connect middleware, such as `vite.middlewares`. */
53
+ type NodeMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
54
+ /** What a plugin learns at startup, before the first request. */
55
+ type SetupInfo = {
56
+ /** The absolute path of the client build. */
57
+ clientDirectory: string;
58
+ /** The URL paths that the build prerendered. */
59
+ prerenderedPaths: readonly string[];
60
+ logger: LogSink;
61
+ } & ({
62
+ mode: "production";
63
+ } | {
64
+ mode: "development";
65
+ /** Vite's middleware stack, which serves source modules and HMR. */
66
+ viteMiddleware: NodeMiddleware;
67
+ });
68
+ /**
69
+ * One step of the request pipeline. Plugins run in list order, so the order is
70
+ * the contract.
71
+ *
72
+ * @example
73
+ * const livez: Plugin = {
74
+ * name: "livez",
75
+ * middleware: async (c, next) => (c.req.path === "/livez" ? c.text("ok") : next()),
76
+ * };
77
+ */
78
+ type Plugin = {
79
+ /** A name for logs and errors. */
80
+ name: string;
81
+ /** The Hono middleware for this step. */
82
+ middleware?: MiddlewareHandler<AppServerEnv>;
83
+ /** Runs once before the server takes requests. A thrown error stops startup. */
84
+ setup?: (info: SetupInfo) => void | Promise<void>;
85
+ /** Runs at shutdown while the listeners drain. The server stops waiting for it at the drain deadline. */
86
+ onShutdown?: () => Promise<void>;
87
+ /**
88
+ * A value that this plugin's changes to a response depend on, such as the
89
+ * env values it writes into each document. The server adds it to the ETag
90
+ * of each static file that the request reaches after this plugin, so a 304
91
+ * never keeps a response made with an old value. Return `undefined` when
92
+ * the plugin changes nothing.
93
+ */
94
+ etagPart?: () => string | undefined;
95
+ };
96
+ /** A running listener. */
97
+ type StartedListener = {
98
+ /** The URL the listener answers on. */
99
+ url: string;
100
+ /**
101
+ * Stops new connections and waits for open requests. At the deadline, it
102
+ * closes the connections that are still open.
103
+ */
104
+ stop: (options: {
105
+ deadlineMs: number;
106
+ }) => Promise<void>;
107
+ };
108
+ /**
109
+ * How the server receives connections, separate from the request pipeline.
110
+ *
111
+ * @example
112
+ * createServer({ listeners: [tcp({ port: 8080 })] });
113
+ */
114
+ type Listener = {
115
+ /** A name for logs. */
116
+ name: string;
117
+ start: (fetch: FetchHandler) => Promise<StartedListener>;
118
+ };
119
+ /** Options for {@link accessLog}. */
120
+ type AccessLogOptions = {
121
+ /**
122
+ * Replace each query value with `REDACTED`, so a single-use code in a URL
123
+ * never reaches a log.
124
+ * @default true
125
+ */
126
+ redactQuery?: boolean;
127
+ };
128
+ /**
129
+ * One log line per request, static hits included, with Datadog standard
130
+ * attribute names. The line goes out when the body ends or the client
131
+ * disconnects, so a streamed response logs its full duration and size.
132
+ *
133
+ * @example
134
+ * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
135
+ * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
136
+ */
137
+ declare function accessLog({ redactQuery }?: AccessLogOptions): Plugin;
138
+ /** Options for {@link requestId}. */
139
+ type RequestIdOptions = {
140
+ /** @default "X-Request-Id" */
141
+ headerName?: string;
142
+ };
143
+ /**
144
+ * Gives each request an ID: a valid incoming header (up to 255 word
145
+ * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
146
+ * every log line, and into the framework's context.
147
+ *
148
+ * @example
149
+ * const app = createServer({ plugins: [requestId()] });
150
+ * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
151
+ * response.headers.get("X-Request-Id"); // => "abc-123"
152
+ */
153
+ declare function requestId({ headerName }?: RequestIdOptions): Plugin;
154
+ /**
155
+ * Serves the hashed files under `/assets/` with a one-year immutable cache.
156
+ * A missing asset gets a plain 404, not a rendered page. In development,
157
+ * Vite serves the source modules, the HMR client, and the CSS here instead.
158
+ *
159
+ * @example
160
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
161
+ */
162
+ declare function assets(): Plugin;
163
+ /** Options for {@link prerendered}. */
164
+ type PrerenderedOptions = {
165
+ /**
166
+ * Extra headers for a served file, by its URL path. They replace the
167
+ * headers captured at build time.
168
+ */
169
+ headers?: (path: string, context: Context<AppServerEnv>) => Readonly<Record<string, string>> | undefined;
170
+ /**
171
+ * Maps a request path to the URL path of the file to serve, for content
172
+ * negotiation. Return the path unchanged to serve the usual file. The
173
+ * returned path follows the rules of a request path: one URL for each
174
+ * file, no dotfiles, and nothing outside the client build. When the
175
+ * answer depends on a request header, add a `Vary` for it in a plugin.
176
+ */
177
+ rewrite?: (path: string, context: Context<AppServerEnv>) => string;
178
+ };
179
+ /**
180
+ * Serves the client build: prerendered pages at their own URL with a 200 and
181
+ * no trailing-slash redirect, plus every other file in it. Each response gets
182
+ * the headers its loader sent at build time (the `serverEntry` Vite plugin
183
+ * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
184
+ * with no file goes on to the framework. Off in development.
185
+ *
186
+ * At startup, it warns about each prerendered path that has no file.
187
+ *
188
+ * @example
189
+ * prerendered({
190
+ * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
191
+ * });
192
+ */
193
+ declare function prerendered(options?: PrerenderedOptions): Plugin;
194
+ /** A Hono app from {@link createServer}. Add routes to it before you export it. */
195
+ type AppServer = Hono<AppServerEnv>;
196
+ /** A server that listens. */
197
+ type RunningServer = {
198
+ /** The URL of each listener. */
199
+ urls: readonly string[];
200
+ /**
201
+ * Aborts `shutdownSignal()`, then runs each plugin's `onShutdown` while the
202
+ * listeners stop and drain open requests. Both stop at the deadline.
203
+ */
204
+ shutdown: () => Promise<void>;
205
+ };
206
+ /** Options for {@link defaultPlugins}. */
207
+ type DefaultPluginsOptions = {
208
+ requestId?: RequestIdOptions;
209
+ accessLog?: AccessLogOptions;
210
+ prerendered?: PrerenderedOptions;
211
+ /**
212
+ * Plugins that go after compression and before the static stages, so they
213
+ * see every response, prerendered pages included. `runtimeEnv` and
214
+ * `buildId` go here.
215
+ */
216
+ beforeStatic?: readonly Plugin[];
217
+ };
218
+ /**
219
+ * The default pipeline, in order: `requestId`, `accessLog`,
220
+ * `streamingCompress`, the `beforeStatic` plugins, `assets`, and
221
+ * `prerendered`. It is a plain array, so an app can filter it or splice into it.
222
+ *
223
+ * @example
224
+ * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });
225
+ */
226
+ declare function defaultPlugins(options?: DefaultPluginsOptions): Plugin[];
227
+ /** Options for {@link createServer}. */
228
+ type CreateServerOptions = {
229
+ /** @default defaultPlugins() */
230
+ plugins?: readonly Plugin[];
231
+ /** @default jsonSink() */
232
+ logger?: LogSink;
233
+ /** @default [tcp()] */
234
+ listeners?: readonly Listener[];
235
+ /**
236
+ * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a
237
+ * proxy that overwrites that header, else a client can spoof it.
238
+ * @default false
239
+ */
240
+ trustForwardedProto?: boolean;
241
+ /**
242
+ * How long open requests get to finish after a stop signal.
243
+ * @default 10000
244
+ */
245
+ shutdownDeadlineMs?: number;
246
+ };
247
+ /**
248
+ * Builds an app server: a Hono app that runs the plugins in list order, then
249
+ * the app's own routes, then the framework. It does not listen; the
250
+ * `app-server` CLI starts it.
251
+ *
252
+ * @example
253
+ * // server.ts
254
+ * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });
255
+ * app.get("/livez", (c) => c.text("ok"));
256
+ * export default app;
257
+ */
258
+ declare function createServer$1({ plugins, logger, listeners, trustForwardedProto, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
259
+ /** The version of the contract between the CLI and the `appServer` export of a build. */
260
+ declare const ENTRY_PROTOCOL = 1;
261
+ /**
262
+ * What a server build exports as `appServer`. The CLI calls it, so the copy
263
+ * of this package in the build runs the server, and the CLI's copy runs
264
+ * nothing.
265
+ */
266
+ type AppServerEntry = {
267
+ /** The CLI refuses an entry with another version. */
268
+ protocol: typeof ENTRY_PROTOCOL;
269
+ /** The app. Two entries with the same app share its plugins. */
270
+ app: AppServer;
271
+ /** Production: runs each plugin's `setup`, listens, and shuts down on `SIGTERM` or `SIGINT`. */
272
+ start: () => Promise<void>;
273
+ /** Development: answers one request with Vite's middleware inside the pipeline. */
274
+ fetchDev: (request: Request, bindings: ListenerBindings, viteMiddleware: NodeMiddleware) => Promise<Response>;
275
+ /** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */
276
+ stopPlugins: () => Promise<void>;
277
+ /** Aborts `shutdownSignal()` of this copy of the package. */
278
+ abortShutdownSignal: () => void;
279
+ };
280
+ /**
281
+ * The `appServer` export of a server build: an app from `createServer` and
282
+ * the framework adapter for each mode. The `serverEntry` Vite plugin makes
283
+ * this export for a React Router build. Call this for another framework.
284
+ *
285
+ * @example
286
+ * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });
287
+ */
288
+ declare function createEntry({ app, framework }: {
289
+ app: AppServer;
290
+ framework: (mode: SetupInfo["mode"]) => FrameworkAdapter;
291
+ }): AppServerEntry;
292
+ export { NodeMiddleware as C, SetupInfo as D, ServerBindings as E, StartedListener as O, LogSink as S, RequestLogger as T, FetchHandler as _, DefaultPluginsOptions as a, ListenerBindings as b, defaultPlugins as c, prerendered as d, RequestIdOptions as f, AppServerEnv as g, accessLog as h, CreateServerOptions as i, PrerenderedOptions as l, AccessLogOptions as m, createEntry as n, RunningServer as o, requestId as p, AppServer as r, createServer$1 as s, AppServerEntry as t, assets as u, FrameworkAdapter as v, Plugin as w, LogLevel as x, Listener as y };
293
+ //# sourceMappingURL=entry-CIpwaayZ.d.ts.map
@@ -0,0 +1,176 @@
1
+ import { C as NodeMiddleware, D as SetupInfo, E as ServerBindings, O as StartedListener, S as LogSink, T as RequestLogger, _ as FetchHandler, a as DefaultPluginsOptions, b as ListenerBindings, c as defaultPlugins, d as prerendered, f as RequestIdOptions, g as AppServerEnv, h as accessLog, i as CreateServerOptions, l as PrerenderedOptions, m as AccessLogOptions, n as createEntry, o as RunningServer, p as requestId, r as AppServer, s as createServer, t as AppServerEntry, u as assets, v as FrameworkAdapter, w as Plugin, x as LogLevel, y as Listener } from "./entry-CIpwaayZ.js";
2
+ import { Context } from "hono";
3
+ /** One server-sent event. */
4
+ type ServerSentEvent = {
5
+ data: string;
6
+ event?: string;
7
+ id?: string;
8
+ };
9
+ /** What {@link eventStream} passes to its producer. */
10
+ type EventStreamSink = {
11
+ send: (event: ServerSentEvent) => void;
12
+ /** Aborts when the client disconnects or the server shuts down. Stop the work on it. */
13
+ signal: AbortSignal;
14
+ };
15
+ /** Options for {@link eventStream}. */
16
+ type EventStreamOptions = {
17
+ /** The request's signal, so a client disconnect stops the stream. */
18
+ signal?: AbortSignal;
19
+ /**
20
+ * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.
21
+ * @default 15000
22
+ */
23
+ heartbeatMs?: number;
24
+ /** Extra response headers. */
25
+ headers?: HeadersInit;
26
+ };
27
+ /**
28
+ * A `text/event-stream` response that stays correct for its whole life: it
29
+ * sends a heartbeat comment, it stops when the client disconnects, and it
30
+ * closes at server shutdown so the drain does not wait for the deadline. The
31
+ * stream closes when `produce` resolves.
32
+ *
33
+ * @example
34
+ * export async function loader({ request }: Route.LoaderArgs) {
35
+ * return eventStream({ signal: request.signal }, async ({ send, signal }) => {
36
+ * for await (const update of watchUpdates({ signal })) {
37
+ * send({ event: "update", data: JSON.stringify(update) });
38
+ * }
39
+ * });
40
+ * }
41
+ */
42
+ export declare function eventStream({ signal, heartbeatMs, headers }: EventStreamOptions, produce: (sink: EventStreamSink) => void | Promise<void>): Response;
43
+ /**
44
+ * A log sink that writes one JSON object per line. Each line has `time`,
45
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
46
+ * standard attributes.
47
+ *
48
+ * @param write - Where each line goes. Defaults to stdout.
49
+ *
50
+ * @example
51
+ * createServer({ logger: jsonSink() });
52
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
53
+ */
54
+ export declare function jsonSink(write?: (line: string) => void): LogSink;
55
+ /** Options for {@link buildId}. */
56
+ type BuildIdOptions = {
57
+ /** @default "X-Build-Id" */
58
+ header?: string;
59
+ /** The deployed build, such as the image tag. Read it from the runtime env, not the build. */
60
+ value: string;
61
+ };
62
+ /**
63
+ * Sets a build ID header on documents and React Router `.data` responses, so
64
+ * a client can see that a deploy happened under it.
65
+ *
66
+ * @example
67
+ * buildId({ value: env.values.PUBLIC_APP_VERSION });
68
+ */
69
+ export declare function buildId({ header, value }: BuildIdOptions): Plugin;
70
+ type StandardIssue = {
71
+ readonly message: string;
72
+ readonly path?: ReadonlyArray<PropertyKey | {
73
+ readonly key: PropertyKey;
74
+ }> | undefined;
75
+ };
76
+ type StandardResult<Output> = {
77
+ readonly value: Output;
78
+ readonly issues?: undefined;
79
+ } | {
80
+ readonly issues: ReadonlyArray<StandardIssue>;
81
+ };
82
+ /** A schema that follows the Standard Schema interface, such as a zod object. */
83
+ type StandardSchemaV1<Input = unknown, Output = Input> = {
84
+ readonly "~standard": {
85
+ readonly version: 1;
86
+ readonly vendor: string;
87
+ readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
88
+ readonly types?: {
89
+ readonly input: Input;
90
+ readonly output: Output;
91
+ } | undefined;
92
+ };
93
+ };
94
+ /** The parsed type of a Standard Schema. */
95
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
96
+ /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
97
+ export declare const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
98
+ /** Options for {@link runtimeEnv}. */
99
+ type RuntimeEnvOptions = {
100
+ /** @default process.env */
101
+ source?: Readonly<Record<string, string | undefined>>;
102
+ /**
103
+ * Values whose names start with this prefix reach the browser.
104
+ * @default "PUBLIC_"
105
+ */
106
+ publicPrefix?: string;
107
+ };
108
+ /** The plugin that {@link runtimeEnv} returns, with the parsed values. */
109
+ type RuntimeEnv<Values> = Plugin & {
110
+ /** The parsed values. The first read parses, and a bad value throws. */
111
+ readonly values: Values;
112
+ /** The parsed values whose names start with the public prefix. */
113
+ readonly publicValues: Readonly<Record<string, unknown>>;
114
+ };
115
+ /**
116
+ * Validates the environment once, at startup, against a schema. A missing or
117
+ * bad value stops the server with a message that names it. The typed values
118
+ * are on `.values`.
119
+ *
120
+ * The values whose names start with `PUBLIC_` go into each HTML document,
121
+ * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
122
+ * So one image serves every environment, and a prerendered page never keeps
123
+ * the values of the build. Put this plugin before the static stages, so it
124
+ * sees the prerendered pages.
125
+ *
126
+ * @example
127
+ * export const env = runtimeEnv(
128
+ * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
129
+ * );
130
+ * env.values.SESSION_KEY; // => string
131
+ *
132
+ * // In the browser:
133
+ * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
134
+ */
135
+ export declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Schema, { source, publicPrefix }?: RuntimeEnvOptions): RuntimeEnv<InferOutput<Schema>>;
136
+ /**
137
+ * Gzips text responses and flushes after each chunk, so a streamed page shell
138
+ * or a server-sent event reaches the client at once. `hono/compress` holds a
139
+ * stream until it ends. Skips a response that is already encoded, a partial
140
+ * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.
141
+ *
142
+ * @example
143
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
144
+ */
145
+ export declare function streamingCompress(): Plugin;
146
+ /**
147
+ * A signal that aborts when the server starts to shut down. Read it for each
148
+ * request: each start of a server makes a new one. A handler that
149
+ * holds a response open, such as an event stream, stops on it so that the
150
+ * drain does not wait for the deadline.
151
+ *
152
+ * @example
153
+ * const timer = setInterval(sendUpdate, 1_000);
154
+ * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
155
+ */
156
+ export declare function shutdownSignal(): AbortSignal;
157
+ /** Options for {@link tcp}. */
158
+ type TcpOptions = {
159
+ /** @default the `PORT` environment variable, else 3000 */
160
+ port?: number;
161
+ /** @default the `HOST` environment variable, else every interface */
162
+ host?: string;
163
+ /** @default 95000 */
164
+ idleTimeoutMs?: number;
165
+ };
166
+ /**
167
+ * The default listener: a TCP port, served by the runtime's own HTTP server
168
+ * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
169
+ * `PORT` and `HOST` when it starts.
170
+ *
171
+ * @example
172
+ * createServer({ listeners: [tcp({ port: 8080 })] });
173
+ */
174
+ export declare function tcp({ port, host, idleTimeoutMs }?: TcpOptions): Listener;
175
+ export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BuildIdOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FrameworkAdapter, type InferOutput, type Listener, type ListenerBindings, type LogLevel, type LogSink, type NodeMiddleware, type Plugin, type PrerenderedOptions, type RequestIdOptions, type RequestLogger, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type TcpOptions, accessLog, assets, createEntry, createServer, defaultPlugins, prerendered, requestId };
176
+ //# sourceMappingURL=index.d.ts.map