@ngrok/app-server 0.3.3 → 0.3.5
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.
- package/README.md +14 -10
- package/dist/brotli-only-DrA29Ecw.js +97 -0
- package/dist/brotli-only-DrA29Ecw.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/compress-CO0Nwc8x.js +386 -0
- package/dist/compress-CO0Nwc8x.js.map +1 -0
- package/dist/{compression-7_gToa8R.js → compression-CT2mWlKM.js} +9 -2
- package/dist/compression-CT2mWlKM.js.map +1 -0
- package/dist/{create-server-jMl2ltHD.js → create-server-C_90R50y.js} +54 -33
- package/dist/{create-server-jMl2ltHD.js.map → create-server-C_90R50y.js.map} +1 -1
- package/dist/{create-server-D4-nVOVJ.d.ts → create-server-kxyhCdhv.d.ts} +3 -3
- package/dist/{entry-D9H4LA9c.js → entry-65IESBSA.js} +5 -4
- package/dist/{entry-D9H4LA9c.js.map → entry-65IESBSA.js.map} +1 -1
- package/dist/{entry-BPrgE_6K.d.ts → entry-CNL4OsEn.d.ts} +3 -3
- package/dist/{index-Db7dspq6.d.ts → index-B8LsM6Mh.d.ts} +21 -1
- package/dist/index.d.ts +13 -12
- package/dist/index.js +4 -4
- package/dist/{load-entry-D7r0mjEp.js → load-entry-svVuPIFq.js} +4 -4
- package/dist/{load-entry-D7r0mjEp.js.map → load-entry-svVuPIFq.js.map} +1 -1
- package/dist/{log-BP6xXXZl.js → log-C8LGQ23s.js} +29 -2
- package/dist/log-C8LGQ23s.js.map +1 -0
- package/dist/{node-tBVQPjQv.js → node-Bgzhwix0.js} +2 -2
- package/dist/{node-tBVQPjQv.js.map → node-Bgzhwix0.js.map} +1 -1
- package/dist/{node-C1qudLs_.js → node-DFI5TjTk.js} +6 -5
- package/dist/{node-C1qudLs_.js.map → node-DFI5TjTk.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- package/dist/react-router-vite.d.ts +1 -1
- package/dist/react-router.d.ts +1 -1
- package/dist/react-router.js +1 -1
- package/dist/{response-edge-Bc1-C_Cx.js → response-edge-D3CAjukJ.js} +2 -2
- package/dist/{response-edge-Bc1-C_Cx.js.map → response-edge-D3CAjukJ.js.map} +1 -1
- package/dist/{response-writer-B7FoJjEE.js → response-writer-5SOKsW3C.js} +4 -4
- package/dist/response-writer-5SOKsW3C.js.map +1 -0
- package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
- package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
- package/dist/{serve-E0hSGe6_.js → serve-DKoZxZj4.js} +2 -2
- package/dist/{serve-E0hSGe6_.js.map → serve-DKoZxZj4.js.map} +1 -1
- package/dist/{start-CifYPRq1.js → start-3_WlRLdK.js} +64 -9
- package/dist/start-3_WlRLdK.js.map +1 -0
- package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
- package/dist/static-files-C2ea8KQ6.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/{tcp-Dd1Mt6sN.js → tcp-CKMCT9RP.js} +2 -2
- package/dist/{tcp-Dd1Mt6sN.js.map → tcp-CKMCT9RP.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +4 -4
- package/dist/{trailing-slash-CFSv_Gzx.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
- package/dist/{types-j29vspx_.d.ts → types-BKJxtIuj.d.ts} +10 -3
- package/dist/vercel-vite.d.ts +1 -1
- package/dist/vercel-vite.js +24 -4
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +4 -3
- package/dist/vercel.js +8 -6
- package/dist/vercel.js.map +1 -1
- package/dist/{vite-BDREIgiH.js → vite-DPiSKHDn.js} +139 -33
- package/dist/vite-DPiSKHDn.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +2 -1
- package/dist/compression-7_gToa8R.js.map +0 -1
- package/dist/gzip-Doi4wqjX.js +0 -294
- package/dist/gzip-Doi4wqjX.js.map +0 -1
- package/dist/log-BP6xXXZl.js.map +0 -1
- package/dist/response-writer-B7FoJjEE.js.map +0 -1
- package/dist/start-CifYPRq1.js.map +0 -1
- package/dist/static-files-Beju9riB.js.map +0 -1
- package/dist/vite-BDREIgiH.js.map +0 -1
package/dist/react-router.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as requestContextValues } from "./request-context-BtQ87VYb.js";
|
|
2
|
-
import { a as sinkLogger, r as jsonSink } from "./log-
|
|
2
|
+
import { a as sinkLogger, r as jsonSink } from "./log-C8LGQ23s.js";
|
|
3
3
|
import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
|
|
4
4
|
|
|
5
5
|
// src/react-router/index.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as replaceResponse, i as listView, n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
|
|
2
|
-
import { t as errorAttributes } from "./log-
|
|
2
|
+
import { t as errorAttributes } from "./log-C8LGQ23s.js";
|
|
3
3
|
|
|
4
4
|
// src/core/response-edge.ts
|
|
5
5
|
function ignore() {}
|
|
@@ -324,4 +324,4 @@ function finishResponse(context, finish) {
|
|
|
324
324
|
}
|
|
325
325
|
|
|
326
326
|
export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
|
|
327
|
-
//# sourceMappingURL=response-edge-
|
|
327
|
+
//# sourceMappingURL=response-edge-D3CAjukJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-edge-Bc1-C_Cx.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { errorAttributes } from \"./log.js\";\nimport type { AppServerEnv, HeaderHook, RequestLogger, SentResponse } from \"./types.js\";\n\nfunction ignore(): void {}\n\n/** Calls `report` with `sent`, and drops a throw from it. */\nfunction callReport(report: (sent: SentResponse) => void, sent: SentResponse): void {\n\ttry {\n\t\treport(sent);\n\t} catch {\n\t\t// Why drop it: a listener calls a report from an event of its socket, where a throw stops the process.\n\t}\n}\n\n/** The `Set-Cookie` values of a flat header list, one on each line. */\nfunction cookiesOf(head: readonly string[]): string {\n\tlet cookies = \"\";\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === \"set-cookie\") {\n\t\t\tcookies += `${head[index + 1] ?? \"\"}\\n`;\n\t\t}\n\t}\n\treturn cookies;\n}\n\n/** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */\nfunction valueOf(head: readonly string[], name: string): string | undefined {\n\tconst index = headerIndex(head, name);\n\treturn index === -1 ? undefined : head[index + 1];\n}\n\n/** Whether two flat header lists are the same. */\nfunction sameHead(first: readonly string[], second: readonly string[]): boolean {\n\tif (first.length !== second.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tif (first[index] !== second[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */\nfunction withChanges(\n\thead: readonly string[],\n\tbase: readonly string[],\n\tlive: readonly string[],\n): string[] {\n\tconst changed = [...head];\n\tconst view = listView(changed);\n\tfor (let index = 0; index < base.length; index += 2) {\n\t\tconst name = base[index] ?? \"\";\n\t\tif (headerIndex(live, name) === -1) {\n\t\t\tview.delete(name);\n\t\t}\n\t}\n\tif (cookiesOf(base) !== cookiesOf(live)) {\n\t\tview.delete(\"set-cookie\");\n\t\tfor (let index = 0; index < live.length; index += 2) {\n\t\t\tif (live[index] === \"set-cookie\") {\n\t\t\t\tview.append(\"set-cookie\", live[index + 1] ?? \"\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (let index = 0; index < live.length; index += 2) {\n\t\tconst name = live[index] ?? \"\";\n\t\tconst value = live[index + 1] ?? \"\";\n\t\tif (name !== \"set-cookie\" && valueOf(base, name) !== value) {\n\t\t\tview.set(name, value);\n\t\t}\n\t}\n\treturn changed;\n}\n\n/**\n * What the server and a listener that writes each response itself share for\n * one request. The listener makes one for each request and gives it as the\n * `edge` binding. The server then runs the header hooks on a list of the\n * headers, so it copies no response for them. The listener:\n *\n * - writes {@link ResponseEdge.headersFor} in place of the headers of the response\n * - adds each body byte that it writes to {@link ResponseEdge.bytes}\n * - gives an error that stops the response to {@link ResponseEdge.fail}\n * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away\n *\n * @example\n * const edge = new ResponseEdge();\n * const response = await fetch(request, { remoteAddress, edge });\n * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());\n */\nexport class ResponseEdge {\n\t/** The body bytes that the listener gave to its socket. */\n\tpublic bytes = 0;\n\t#logger: RequestLogger | undefined = undefined;\n\t#base: readonly string[] | undefined = undefined;\n\t#headers: string[] | undefined = undefined;\n\treadonly #reports: ((sent: SentResponse) => void)[] = [];\n\t#sent: SentResponse | undefined = undefined;\n\n\t/**\n\t * Gives the edge to the request of `logger`, and gives `true`, the first\n\t * time only. The server calls it when a request starts. Why once: a\n\t * request that the app sends through itself again with the same bindings\n\t * must change its own response.\n\t */\n\tpublic claim(logger: RequestLogger): boolean {\n\t\tif (this.#logger != null) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.#logger = logger;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Keeps `headers`, the headers of the response after each header hook, and\n\t * `base`, its headers before the hooks. The server calls it.\n\t */\n\tpublic useHeaders(base: readonly string[], headers: string[]): void {\n\t\tthis.#base = base;\n\t\tthis.#headers = headers;\n\t}\n\n\t/**\n\t * The headers to write for `response`: lowercase names and their values in\n\t * turn, as Node's `writeHead` takes them. They are the headers after the\n\t * hooks, with each change that the headers of `response` have from the\n\t * response that the hooks ran on. Why: Hono answers HEAD with a copy that\n\t * has no body, and a wrapper of the app's `fetch` can change the headers or\n\t * return a copy. It gives `undefined` when the server kept no headers.\n\t */\n\tpublic headersFor(response: Response): string[] | undefined {\n\t\tconst base = this.#base;\n\t\tconst headers = this.#headers;\n\t\tif (base == null || headers == null) {\n\t\t\treturn headers;\n\t\t}\n\t\tconst live = headerList(response.headers);\n\t\treturn sameHead(base, live) ? headers : withChanges(headers, base, live);\n\t}\n\n\t/**\n\t * Calls `report` once, when the response ends or its client goes away. It\n\t * calls it at once when that happened already. A throw from `report` never\n\t * reaches the listener.\n\t */\n\tpublic onSent(report: (sent: SentResponse) => void): void {\n\t\tif (this.#sent == null) {\n\t\t\tthis.#reports.push(report);\n\t\t} else {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n\n\t/** Logs `error`, which stopped the response, with the logger of the request. */\n\tpublic fail(error: unknown): void {\n\t\ttry {\n\t\t\tif (this.#logger != null) {\n\t\t\t\tthis.#logger.error(\"unhandled error\", errorAttributes(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Why fall through: the sink failed, and the error must still reach the operator.\n\t\t}\n\t\t// oxlint-disable-next-line no-console -- no app logger took the edge, or its sink failed.\n\t\tconsole.error(error);\n\t}\n\n\t/**\n\t * Reports what went out, once: the status and the headers that the\n\t * listener sent, the bytes, and whether the body stopped before its end.\n\t * `head` is the flat list that the listener gave `writeHead`.\n\t */\n\tpublic close(status: number, aborted: boolean, head: string[]): void {\n\t\tif (this.#sent != null) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#sent = { status, headers: listView(head), bytes: this.bytes, aborted };\n\t\tfor (const report of this.#reports) {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n}\n\n/**\n * `body` again, with a count of its bytes for `report`. `report` runs once:\n * at the end of the body, at a failure, or at a cancel.\n */\nfunction countedBody(\n\tbody: ReadableStream<Uint8Array>,\n\treport: (bytes: number, aborted: boolean) => void,\n): ReadableStream<Uint8Array> {\n\tconst reader = body.getReader();\n\tlet bytes = 0;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treport(bytes, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbytes += result.value.byteLength;\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\ttry {\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t} finally {\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Why 0: a pass-through stream must not read ahead of the client.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * The body of `context.res` with a count for `report`, or `undefined` when\n * `report` ran at once: a HEAD response and a response with no body send no\n * body bytes. `headers` are the headers that go out with the response.\n */\nfunction reportedBody(\n\tcontext: Context<AppServerEnv>,\n\theaders: Headers,\n\treport: (sent: SentResponse) => void,\n): ReadableStream<Uint8Array> | undefined {\n\tconst { status, body } = context.res;\n\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\tif (context.req.method === \"HEAD\") {\n\t\tcallReport(report, { status, headers, bytes: 0, aborted: false });\n\t\treturn undefined;\n\t}\n\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t// development, gives a response with no body and the length it sent.\n\tif (body == null) {\n\t\tconst length = Number(headers.get(\"Content-Length\") ?? 0);\n\t\tcallReport(report, { status, headers, bytes: length, aborted: false });\n\t\treturn undefined;\n\t}\n\treturn countedBody(body, (bytes, aborted) => {\n\t\tcallReport(report, { status, headers, bytes, aborted });\n\t});\n}\n\n/**\n * Calls `report` once, when the response of the request ends or its client\n * goes away: with the status and the headers that went out, the body bytes,\n * and whether the body stopped before its end. In an app server, it reports the response that\n * the server returns, after each stage and header hook. A listener with an\n * `edge` counts the bytes as it writes them; else the server counts them with\n * a stream around the body.\n *\n * @example\n * middleware: async (c, next) => {\n * \tawait next();\n * \tonResponseSent(c, ({ status, bytes }) => c.get(\"logger\").info(\"sent\", { status, bytes }));\n * },\n */\nexport function onResponseSent(\n\tcontext: Context<AppServerEnv>,\n\treport: (sent: SentResponse) => void,\n): void {\n\tconst reports = context.get(\"sentReports\");\n\tif (reports != null) {\n\t\treports.push(report);\n\t\treturn;\n\t}\n\t// Why now: outside an app server, nothing reports later, so this counts the response as it is.\n\tconst response = context.res;\n\tconst body = reportedBody(context, response.headers, report);\n\tif (body != null) {\n\t\treplaceResponse(context, new Response(body, response));\n\t}\n}\n\n/** What {@link finishResponse} needs from the server. */\ntype Finish = {\n\thooks: readonly HeaderHook[];\n\treports: readonly ((sent: SentResponse) => void)[];\n\t/** The edge that the request claimed, if any. */\n\tedge: ResponseEdge | undefined;\n\t/**\n\t * The response for an error that a header hook throws, as the app's\n\t * `onError` gives it. It runs while `context.res` is cleared.\n\t */\n\tfail: (error: unknown, context: Context<AppServerEnv>) => Response | Promise<Response>;\n};\n\n/**\n * Puts the response that `fail` gives for `error` in place of the response of\n * the request, and cancels the body that no one reads now.\n */\nasync function useErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfail: Finish[\"fail\"],\n\terror: unknown,\n): Promise<void> {\n\tconst { body } = context.res;\n\t// Why clear first: Hono's `c.text` copies each header of the response that the context holds.\n\tcontext.res = undefined;\n\tcontext.res = await fail(error, context);\n\tvoid body?.cancel().catch(ignore);\n}\n\n/**\n * Gives `reports` the response of the request. With no edge, it makes one new\n * response with `headers`, when the hooks made them, and a body that counts\n * its bytes.\n */\nfunction reportResponse(\n\tcontext: Context<AppServerEnv>,\n\treports: Finish[\"reports\"],\n\theaders: Headers | undefined,\n): void {\n\tconst response = context.res;\n\tconst [only] = reports;\n\tconst report =\n\t\treports.length > 1\n\t\t\t? (sent: SentResponse) => {\n\t\t\t\t\tfor (const each of reports) {\n\t\t\t\t\t\tcallReport(each, sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: only;\n\t// Why keep `headers`: Bun empties the headers of the response that it sends, but not this object.\n\tconst body =\n\t\treport == null ? undefined : reportedBody(context, headers ?? response.headers, report);\n\tif (headers == null && body == null) {\n\t\treturn;\n\t}\n\tcontext.res = undefined;\n\tcontext.res = new Response(body ?? response.body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: headers ?? response.headers,\n\t});\n}\n\n/** Puts the error response for `error` in place, then runs the hooks from `from` on it. */\nasync function finishAfterError(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\t{ error, from }: { error: unknown; from: number },\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\tawait finishFrom(context, finish, from);\n}\n\n/** Puts the error response for `error` in place, and gives it to the reports. */\nasync function reportErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\terror: unknown,\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\treportResponse(context, finish.reports, undefined);\n}\n\n/** {@link finishResponse} from the hook at `from`, down to the first one. */\nfunction finishFrom(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\tfrom: number,\n): Promise<void> | undefined {\n\tconst { hooks, reports, edge } = finish;\n\tconst base = headerList(context.res.headers);\n\t// Why a copy with an edge: the edge compares the response that the listener gets with `base`.\n\tconst head = edge == null ? base : [...base];\n\tconst view = listView(head);\n\tfor (let index = from; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch (error) {\n\t\t\treturn finishAfterError(context, finish, { error, from: index - 1 });\n\t\t}\n\t}\n\tif (edge != null) {\n\t\tedge.useHeaders(base, head);\n\t\tfor (const report of reports) {\n\t\t\tedge.onSent(report);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hooks.length === 0) {\n\t\treportResponse(context, reports, undefined);\n\t\treturn undefined;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\theaders.append(head[index] ?? \"\", head[index + 1] ?? \"\");\n\t\t}\n\t} catch (error) {\n\t\t// Why: a hook set a value that `Headers` rejects. The error response keeps its own headers.\n\t\treturn reportErrorResponse(context, finish, error);\n\t}\n\treportResponse(context, reports, headers);\n\treturn undefined;\n}\n\n/**\n * Finishes the response of the request, after each stage. The server calls it\n * once, in the request's `requestContext()`.\n *\n * - It runs `hooks` on the head, in reverse order, so the hook of an inner\n * stage runs first and an outer stage has the last word. When a hook\n * throws, `fail` gives the response that takes the place of this one, and\n * the hooks of the outer stages run on it, as when a stage throws.\n * - It gives `reports` the response, so each one runs when it ends.\n *\n * With `edge`, the head stays a list that the listener writes, so the server\n * copies no response. Else the server makes one new response with the head\n * and a body that counts its bytes. It gives a promise only when a hook\n * throws, so a response with no error waits for no microtask.\n *\n * @example\n * await next();\n * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });\n */\nexport function finishResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n): Promise<void> | undefined {\n\treturn finishFrom(context, finish, finish.hooks.length - 1);\n}\n"],"mappings":";;;;AAKA,SAAS,SAAe,CAAC;;AAGzB,SAAS,WAAW,QAAsC,MAA0B;CACnF,IAAI;EACH,OAAO,IAAI;CACZ,QAAQ,CAER;AACD;;AAGA,SAAS,UAAU,MAAiC;CACnD,IAAI,UAAU;CACd,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GACjD,IAAI,KAAK,WAAW,cACnB,WAAW,GAAG,KAAK,QAAQ,MAAM,GAAG;CAGtC,OAAO;AACR;;AAGA,SAAS,QAAQ,MAAyB,MAAkC;CAC3E,MAAM,QAAQ,YAAY,MAAM,IAAI;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IAAI,KAAK,QAAQ,MAAM,EAAE;CAEzD,SAAS,OAAO;EAEf,OAAO,oBAAoB,SAAS,QAAQ,KAAK;CAClD;CACA,eAAe,SAAS,SAAS,OAAO;AAEzC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,eACf,SACA,QAC4B;CAC5B,OAAO,WAAW,SAAS,QAAQ,OAAO,MAAM,SAAS,CAAC;AAC3D"}
|
|
1
|
+
{"version":3,"file":"response-edge-D3CAjukJ.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { errorAttributes } from \"./log.js\";\nimport type { AppServerEnv, HeaderHook, RequestLogger, SentResponse } from \"./types.js\";\n\nfunction ignore(): void {}\n\n/** Calls `report` with `sent`, and drops a throw from it. */\nfunction callReport(report: (sent: SentResponse) => void, sent: SentResponse): void {\n\ttry {\n\t\treport(sent);\n\t} catch {\n\t\t// Why drop it: a listener calls a report from an event of its socket, where a throw stops the process.\n\t}\n}\n\n/** The `Set-Cookie` values of a flat header list, one on each line. */\nfunction cookiesOf(head: readonly string[]): string {\n\tlet cookies = \"\";\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === \"set-cookie\") {\n\t\t\tcookies += `${head[index + 1] ?? \"\"}\\n`;\n\t\t}\n\t}\n\treturn cookies;\n}\n\n/** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */\nfunction valueOf(head: readonly string[], name: string): string | undefined {\n\tconst index = headerIndex(head, name);\n\treturn index === -1 ? undefined : head[index + 1];\n}\n\n/** Whether two flat header lists are the same. */\nfunction sameHead(first: readonly string[], second: readonly string[]): boolean {\n\tif (first.length !== second.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tif (first[index] !== second[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */\nfunction withChanges(\n\thead: readonly string[],\n\tbase: readonly string[],\n\tlive: readonly string[],\n): string[] {\n\tconst changed = [...head];\n\tconst view = listView(changed);\n\tfor (let index = 0; index < base.length; index += 2) {\n\t\tconst name = base[index] ?? \"\";\n\t\tif (headerIndex(live, name) === -1) {\n\t\t\tview.delete(name);\n\t\t}\n\t}\n\tif (cookiesOf(base) !== cookiesOf(live)) {\n\t\tview.delete(\"set-cookie\");\n\t\tfor (let index = 0; index < live.length; index += 2) {\n\t\t\tif (live[index] === \"set-cookie\") {\n\t\t\t\tview.append(\"set-cookie\", live[index + 1] ?? \"\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (let index = 0; index < live.length; index += 2) {\n\t\tconst name = live[index] ?? \"\";\n\t\tconst value = live[index + 1] ?? \"\";\n\t\tif (name !== \"set-cookie\" && valueOf(base, name) !== value) {\n\t\t\tview.set(name, value);\n\t\t}\n\t}\n\treturn changed;\n}\n\n/**\n * What the server and a listener that writes each response itself share for\n * one request. The listener makes one for each request and gives it as the\n * `edge` binding. The server then runs the header hooks on a list of the\n * headers, so it copies no response for them. The listener:\n *\n * - writes {@link ResponseEdge.headersFor} in place of the headers of the response\n * - adds each body byte that it writes to {@link ResponseEdge.bytes}\n * - gives an error that stops the response to {@link ResponseEdge.fail}\n * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away\n *\n * @example\n * const edge = new ResponseEdge();\n * const response = await fetch(request, { remoteAddress, edge });\n * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());\n */\nexport class ResponseEdge {\n\t/** The body bytes that the listener gave to its socket. */\n\tpublic bytes = 0;\n\t#logger: RequestLogger | undefined = undefined;\n\t#base: readonly string[] | undefined = undefined;\n\t#headers: string[] | undefined = undefined;\n\treadonly #reports: ((sent: SentResponse) => void)[] = [];\n\t#sent: SentResponse | undefined = undefined;\n\n\t/**\n\t * Gives the edge to the request of `logger`, and gives `true`, the first\n\t * time only. The server calls it when a request starts. Why once: a\n\t * request that the app sends through itself again with the same bindings\n\t * must change its own response.\n\t */\n\tpublic claim(logger: RequestLogger): boolean {\n\t\tif (this.#logger != null) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.#logger = logger;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Keeps `headers`, the headers of the response after each header hook, and\n\t * `base`, its headers before the hooks. The server calls it.\n\t */\n\tpublic useHeaders(base: readonly string[], headers: string[]): void {\n\t\tthis.#base = base;\n\t\tthis.#headers = headers;\n\t}\n\n\t/**\n\t * The headers to write for `response`: lowercase names and their values in\n\t * turn, as Node's `writeHead` takes them. They are the headers after the\n\t * hooks, with each change that the headers of `response` have from the\n\t * response that the hooks ran on. Why: Hono answers HEAD with a copy that\n\t * has no body, and a wrapper of the app's `fetch` can change the headers or\n\t * return a copy. It gives `undefined` when the server kept no headers.\n\t */\n\tpublic headersFor(response: Response): string[] | undefined {\n\t\tconst base = this.#base;\n\t\tconst headers = this.#headers;\n\t\tif (base == null || headers == null) {\n\t\t\treturn headers;\n\t\t}\n\t\tconst live = headerList(response.headers);\n\t\treturn sameHead(base, live) ? headers : withChanges(headers, base, live);\n\t}\n\n\t/**\n\t * Calls `report` once, when the response ends or its client goes away. It\n\t * calls it at once when that happened already. A throw from `report` never\n\t * reaches the listener.\n\t */\n\tpublic onSent(report: (sent: SentResponse) => void): void {\n\t\tif (this.#sent == null) {\n\t\t\tthis.#reports.push(report);\n\t\t} else {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n\n\t/** Logs `error`, which stopped the response, with the logger of the request. */\n\tpublic fail(error: unknown): void {\n\t\ttry {\n\t\t\tif (this.#logger != null) {\n\t\t\t\tthis.#logger.error(\"unhandled error\", errorAttributes(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Why fall through: the sink failed, and the error must still reach the operator.\n\t\t}\n\t\t// oxlint-disable-next-line no-console -- no app logger took the edge, or its sink failed.\n\t\tconsole.error(error);\n\t}\n\n\t/**\n\t * Reports what went out, once: the status and the headers that the\n\t * listener sent, the bytes, and whether the body stopped before its end.\n\t * `head` is the flat list that the listener gave `writeHead`.\n\t */\n\tpublic close(status: number, aborted: boolean, head: string[]): void {\n\t\tif (this.#sent != null) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#sent = { status, headers: listView(head), bytes: this.bytes, aborted };\n\t\tfor (const report of this.#reports) {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n}\n\n/**\n * `body` again, with a count of its bytes for `report`. `report` runs once:\n * at the end of the body, at a failure, or at a cancel.\n */\nfunction countedBody(\n\tbody: ReadableStream<Uint8Array>,\n\treport: (bytes: number, aborted: boolean) => void,\n): ReadableStream<Uint8Array> {\n\tconst reader = body.getReader();\n\tlet bytes = 0;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treport(bytes, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbytes += result.value.byteLength;\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\ttry {\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t} finally {\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Why 0: a pass-through stream must not read ahead of the client.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * The body of `context.res` with a count for `report`, or `undefined` when\n * `report` ran at once: a HEAD response and a response with no body send no\n * body bytes. `headers` are the headers that go out with the response.\n */\nfunction reportedBody(\n\tcontext: Context<AppServerEnv>,\n\theaders: Headers,\n\treport: (sent: SentResponse) => void,\n): ReadableStream<Uint8Array> | undefined {\n\tconst { status, body } = context.res;\n\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\tif (context.req.method === \"HEAD\") {\n\t\tcallReport(report, { status, headers, bytes: 0, aborted: false });\n\t\treturn undefined;\n\t}\n\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t// development, gives a response with no body and the length it sent.\n\tif (body == null) {\n\t\tconst length = Number(headers.get(\"Content-Length\") ?? 0);\n\t\tcallReport(report, { status, headers, bytes: length, aborted: false });\n\t\treturn undefined;\n\t}\n\treturn countedBody(body, (bytes, aborted) => {\n\t\tcallReport(report, { status, headers, bytes, aborted });\n\t});\n}\n\n/**\n * Calls `report` once, when the response of the request ends or its client\n * goes away: with the status and the headers that went out, the body bytes,\n * and whether the body stopped before its end. In an app server, it reports the response that\n * the server returns, after each stage and header hook. A listener with an\n * `edge` counts the bytes as it writes them; else the server counts them with\n * a stream around the body.\n *\n * @example\n * middleware: async (c, next) => {\n * \tawait next();\n * \tonResponseSent(c, ({ status, bytes }) => c.get(\"logger\").info(\"sent\", { status, bytes }));\n * },\n */\nexport function onResponseSent(\n\tcontext: Context<AppServerEnv>,\n\treport: (sent: SentResponse) => void,\n): void {\n\tconst reports = context.get(\"sentReports\");\n\tif (reports != null) {\n\t\treports.push(report);\n\t\treturn;\n\t}\n\t// Why now: outside an app server, nothing reports later, so this counts the response as it is.\n\tconst response = context.res;\n\tconst body = reportedBody(context, response.headers, report);\n\tif (body != null) {\n\t\treplaceResponse(context, new Response(body, response));\n\t}\n}\n\n/** What {@link finishResponse} needs from the server. */\ntype Finish = {\n\thooks: readonly HeaderHook[];\n\treports: readonly ((sent: SentResponse) => void)[];\n\t/** The edge that the request claimed, if any. */\n\tedge: ResponseEdge | undefined;\n\t/**\n\t * The response for an error that a header hook throws, as the app's\n\t * `onError` gives it. It runs while `context.res` is cleared.\n\t */\n\tfail: (error: unknown, context: Context<AppServerEnv>) => Response | Promise<Response>;\n};\n\n/**\n * Puts the response that `fail` gives for `error` in place of the response of\n * the request, and cancels the body that no one reads now.\n */\nasync function useErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfail: Finish[\"fail\"],\n\terror: unknown,\n): Promise<void> {\n\tconst { body } = context.res;\n\t// Why clear first: Hono's `c.text` copies each header of the response that the context holds.\n\tcontext.res = undefined;\n\tcontext.res = await fail(error, context);\n\tvoid body?.cancel().catch(ignore);\n}\n\n/**\n * Gives `reports` the response of the request. With no edge, it makes one new\n * response with `headers`, when the hooks made them, and a body that counts\n * its bytes.\n */\nfunction reportResponse(\n\tcontext: Context<AppServerEnv>,\n\treports: Finish[\"reports\"],\n\theaders: Headers | undefined,\n): void {\n\tconst response = context.res;\n\tconst [only] = reports;\n\tconst report =\n\t\treports.length > 1\n\t\t\t? (sent: SentResponse) => {\n\t\t\t\t\tfor (const each of reports) {\n\t\t\t\t\t\tcallReport(each, sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: only;\n\t// Why keep `headers`: Bun empties the headers of the response that it sends, but not this object.\n\tconst body =\n\t\treport == null ? undefined : reportedBody(context, headers ?? response.headers, report);\n\tif (headers == null && body == null) {\n\t\treturn;\n\t}\n\tcontext.res = undefined;\n\tcontext.res = new Response(body ?? response.body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: headers ?? response.headers,\n\t});\n}\n\n/** Puts the error response for `error` in place, then runs the hooks from `from` on it. */\nasync function finishAfterError(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\t{ error, from }: { error: unknown; from: number },\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\tawait finishFrom(context, finish, from);\n}\n\n/** Puts the error response for `error` in place, and gives it to the reports. */\nasync function reportErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\terror: unknown,\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\treportResponse(context, finish.reports, undefined);\n}\n\n/** {@link finishResponse} from the hook at `from`, down to the first one. */\nfunction finishFrom(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\tfrom: number,\n): Promise<void> | undefined {\n\tconst { hooks, reports, edge } = finish;\n\tconst base = headerList(context.res.headers);\n\t// Why a copy with an edge: the edge compares the response that the listener gets with `base`.\n\tconst head = edge == null ? base : [...base];\n\tconst view = listView(head);\n\tfor (let index = from; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch (error) {\n\t\t\treturn finishAfterError(context, finish, { error, from: index - 1 });\n\t\t}\n\t}\n\tif (edge != null) {\n\t\tedge.useHeaders(base, head);\n\t\tfor (const report of reports) {\n\t\t\tedge.onSent(report);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hooks.length === 0) {\n\t\treportResponse(context, reports, undefined);\n\t\treturn undefined;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\theaders.append(head[index] ?? \"\", head[index + 1] ?? \"\");\n\t\t}\n\t} catch (error) {\n\t\t// Why: a hook set a value that `Headers` rejects. The error response keeps its own headers.\n\t\treturn reportErrorResponse(context, finish, error);\n\t}\n\treportResponse(context, reports, headers);\n\treturn undefined;\n}\n\n/**\n * Finishes the response of the request, after each stage. The server calls it\n * once, in the request's `requestContext()`.\n *\n * - It runs `hooks` on the head, in reverse order, so the hook of an inner\n * stage runs first and an outer stage has the last word. When a hook\n * throws, `fail` gives the response that takes the place of this one, and\n * the hooks of the outer stages run on it, as when a stage throws.\n * - It gives `reports` the response, so each one runs when it ends.\n *\n * With `edge`, the head stays a list that the listener writes, so the server\n * copies no response. Else the server makes one new response with the head\n * and a body that counts its bytes. It gives a promise only when a hook\n * throws, so a response with no error waits for no microtask.\n *\n * @example\n * await next();\n * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });\n */\nexport function finishResponse(\n\tcontext: Context<AppServerEnv>,\n\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AC3C,IAAI;EACH,MAAM,MAAM,GAAG,IAAI;CACpB,SAAS,OAAO;EACf,OAAO,iBAAiB,SAAS,QAAQ;GAAE;GAAO,MAAM,QAAQ;EAAE,CAAC;CACpE;CAED,IAAI,QAAQ,MAAM;EACjB,KAAK,WAAW,MAAM,IAAI;EAC1B,KAAK,MAAM,UAAU,SACpB,KAAK,OAAO,MAAM;EAEnB;CACD;CACA,IAAI,MAAM,WAAW,GAAG;EACvB,eAAe,SAAS,SAAS,MAAS;EAC1C;CACD;CACA,MAAM,UAAU,IAAI,QAAQ;CAC5B,IAAI;EACH,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GACjD,QAAQ,OAAO,KAAK,UAAU,IAAI,KAAK,QAAQ,MAAM,EAAE;CAEzD,SAAS,OAAO;EAEf,OAAO,oBAAoB,SAAS,QAAQ,KAAK;CAClD;CACA,eAAe,SAAS,SAAS,OAAO;AAEzC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,eACf,SACA,QAC4B;CAC5B,OAAO,WAAW,SAAS,QAAQ,OAAO,MAAM,SAAS,CAAC;AAC3D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
|
|
2
|
-
import { t as ResponseEdge } from "./response-edge-
|
|
3
|
-
import { s as readIfQueued } from "./compression-
|
|
4
|
-
import {
|
|
2
|
+
import { t as ResponseEdge } from "./response-edge-D3CAjukJ.js";
|
|
3
|
+
import { s as readIfQueued } from "./compression-CT2mWlKM.js";
|
|
4
|
+
import { r as waitsForZlib } from "./compress-CO0Nwc8x.js";
|
|
5
5
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
6
6
|
import { getRequestListener } from "@hono/node-server";
|
|
7
7
|
|
|
@@ -286,4 +286,4 @@ function listenerOf(answer) {
|
|
|
286
286
|
}
|
|
287
287
|
|
|
288
288
|
export { requestListener as t };
|
|
289
|
-
//# sourceMappingURL=response-writer-
|
|
289
|
+
//# sourceMappingURL=response-writer-5SOKsW3C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"response-writer-5SOKsW3C.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./compress.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\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 edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;;AAE5B,MAAM,eAAe,IAAI,SAAS,MAAM,EAAE,SAAS,GAAG,sBAAsB,OAAO,EAAE,CAAC;;AAEtF,MAAM,uBAAuB;;AAE7B,MAAM,aAAa,OAAO,KAAK,uBAAuB;;AAGtD,eAAe,kBAAiC;CAC/C,OAAO,IAAI,SAAS,YAAY;EAC/B,QAAQ,SAAS,OAAO;CACzB,CAAC;AACF;;AAGA,eAAe,QAAQ,UAAyC;CAC/D,OAAO,IAAI,SAAS,YAAY;EAC/B,MAAM,aAAa;GAClB,SAAS,IAAI,SAAS,IAAI;GAC1B,SAAS,IAAI,SAAS,IAAI;GAC1B,QAAQ;EACT;EACA,SAAS,GAAG,SAAS,IAAI;EACzB,SAAS,GAAG,SAAS,IAAI;CAC1B,CAAC;AACF;;AAGA,SAAS,QAAQ,OAA4B;CAC5C,IAAI,iBAAiB,YACpB,OAAO;CAER,MAAM,IAAI,UAAU,wDAAwD;AAC7E;;;;;;;AAgBA,eAAe,UACd,QACA,MACiB;CACjB,MAAM,QAAe;EAAE,QAAQ,CAAC;EAAG,MAAM;EAAG,MAAM;EAAO,SAAS;CAAU;CAC5E,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,CAAC,MAAM,QAAQ,MAAM,WAAW,MAAM,SAAS,GAAG;EAElF,IAAI,OAAO,MAAM,aAAa,MAAM;EACpC,IAAI,aAAa,QAAQ,UAAU,KAAK,aAAa,IAAI,KAAK,MAAM;GAGnE,MAAM,gBAAgB;GACtB,IAAI,aAAa,IAAI,MAAM,MAE1B,OAAO,EAAE,QAAQ,MAAM,KAAK,QAAQ;EAEtC;EACA,IAAI,aAAa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QACA,EAAE,sBAAsB,UAA6C,CAAC,GAC9B;CACxC,MAAM,WAAW,WAAW,MAAM;CAClC,OAAO,sBACJ,OAAO,UAAU,aAAa;EAC9B,IAAI,oBAAoB,iBACvB,kBAAkB,QAAQ;EAE3B,OAAO,SAAS,UAAU,QAAQ;CACnC,IACC;AACJ;;AAGA,SAAS,WACR,QACwC;CACxC,OAAO,yBACN,mBAAmB,OAAO,SAAS,EAAE,UAAU,eAAe;EAC7D,MAAM,EAAE,kBAAkB,SAAS;EAEnC,IAAI,EAAE,oBAAoB,oBAAoB,EAAE,oBAAoB,iBACnE,OAAO,OAAO,SAAS,EAAE,cAAc,CAA4B;EAGpE,MAAM,SAASA,SAAS;EAExB,IAAI,UAAU,MACb,SAAS,MAAM;EAEhB,IAAI,CAAC,iBAAiB;GACrB,MAAM,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;GAAS,CAAC;GAE5E,IAAI,SAAS,WACZ,MAAM,SAAS,MAAM,OAAO;GAE7B,OAAO;EACR;EACA,MAAM,OAAO,IAAI,aAAa;EAC9B,IAAI;EACJ,IAAI;GACH,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;IAAU;GAAK,CAAC;EAC7E,SAAS,OAAO;GAEf,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;GACzB,MAAM;EACP;EACA,MAAM,cAAc,UAAU,UAAU,IAAI;EAC5C,OAAO;CACR,CAAC,CACF;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as contentType } from "./static-files-
|
|
1
|
+
import { t as contentType } from "./static-files-C2ea8KQ6.js";
|
|
2
2
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
3
|
import { join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -68,4 +68,4 @@ function scriptHashesOf(clientDirectory) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
export { scriptHashesOf as n, publicScriptHashes as t };
|
|
71
|
-
//# sourceMappingURL=script-hashes-
|
|
71
|
+
//# sourceMappingURL=script-hashes-CU7P9oZU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"script-hashes-
|
|
1
|
+
{"version":3,"file":"script-hashes-CU7P9oZU.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.\n *\n * @example\n * scriptHashesOf(\"/app/build/client\"); // => { \"/about/index.html\": [\"…base64…\"] }\n */\nexport function scriptHashesOf(clientDirectory: string): BuildManifest[\"scriptHashes\"] {\n\tconst hashes: BuildManifest[\"scriptHashes\"] = {};\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\t// Why `contentType`: the static stages send each file of an HTML type, such as `.htm`, as a document.\n\t\tif (entry.isFile() && contentType(entry.name, {}).startsWith(\"text/html\")) {\n\t\t\tconst path = join(entry.parentPath, entry.name);\n\t\t\tconst urlPath = `/${relative(clientDirectory, path).split(sep).join(\"/\")}`;\n\t\t\thashes[urlPath] = inlineScriptHashes(readFileSync(path, \"utf8\"));\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,eAAe,iBAAwD;CACtF,MAAM,SAAwC,CAAC;CAC/C,KAAK,MAAM,SAAS,YAAY,iBAAiB;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,GAExF,IAAI,MAAM,OAAO,KAAK,YAAY,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,GAAG;EAC1E,MAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;EAC9C,MAAM,UAAU,IAAI,SAAS,iBAAiB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EACvE,OAAO,WAAW,mBAAmB,aAAa,MAAM,MAAM,CAAC;CAChE;CAED,OAAO,OAAO,YACb,OAAO,QAAQ,MAAM,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,MAAM,cAAc,MAAM,CAAC,CACnF;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as loadEntry } from "./load-entry-
|
|
1
|
+
import { t as loadEntry } from "./load-entry-svVuPIFq.js";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export { serve };
|
|
29
|
-
//# sourceMappingURL=serve-
|
|
29
|
+
//# sourceMappingURL=serve-DKoZxZj4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve-
|
|
1
|
+
{"version":3,"file":"serve-DKoZxZj4.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
|
|
@@ -1,13 +1,63 @@
|
|
|
1
|
-
import { t as parsePort } from "./tcp-
|
|
2
|
-
import {
|
|
3
|
-
import { i as exitAfterFlush, n as devServerStage } from "./node-
|
|
4
|
-
import { t as requestListener } from "./response-writer-
|
|
5
|
-
import { t as SERVER_ENTRY_ID } from "./vite-
|
|
6
|
-
import { t as loadEntry } from "./load-entry-
|
|
1
|
+
import { t as parsePort } from "./tcp-CKMCT9RP.js";
|
|
2
|
+
import { o as textSink, t as errorAttributes } from "./log-C8LGQ23s.js";
|
|
3
|
+
import { i as exitAfterFlush, n as devServerStage } from "./node-DFI5TjTk.js";
|
|
4
|
+
import { t as requestListener } from "./response-writer-5SOKsW3C.js";
|
|
5
|
+
import { t as SERVER_ENTRY_ID } from "./vite-DPiSKHDn.js";
|
|
6
|
+
import { t as loadEntry } from "./load-entry-svVuPIFq.js";
|
|
7
7
|
import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
|
|
8
|
+
import { styleText } from "node:util";
|
|
8
9
|
import { createServer } from "node:http";
|
|
10
|
+
import { networkInterfaces } from "node:os";
|
|
9
11
|
import { createServer as createServer$1 } from "node:net";
|
|
10
12
|
|
|
13
|
+
// src/cli/dev-urls.ts
|
|
14
|
+
const wildcardHosts = /* @__PURE__ */ new Set([
|
|
15
|
+
"",
|
|
16
|
+
"0.0.0.0",
|
|
17
|
+
"::"
|
|
18
|
+
]);
|
|
19
|
+
const loopbackHosts = /* @__PURE__ */ new Set([
|
|
20
|
+
"localhost",
|
|
21
|
+
"127.0.0.1",
|
|
22
|
+
"::1"
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* The lines that `app-server start` prints when it listens, in the format of `vite dev`. Each URL
|
|
26
|
+
* ends with `base`, Vite's base path. A wildcard host gets a `localhost` line, then one line for
|
|
27
|
+
* each IPv4 (Internet Protocol version 4) interface.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* devUrlLines({ hostname: "localhost", port: 3000, base: "/" }); // => [" ➜ Local: http://localhost:3000/"]
|
|
31
|
+
*/
|
|
32
|
+
function devUrlLines({ hostname, port, base }, interfaces = networkInterfaces()) {
|
|
33
|
+
const urlOf = (host) => `${listenerUrl(host, port).slice(0, -1)}${base}`;
|
|
34
|
+
const addresses = Object.entries(interfaces).flatMap(([name, details = []]) => details.map(({ address, family }) => ({
|
|
35
|
+
name,
|
|
36
|
+
address,
|
|
37
|
+
family
|
|
38
|
+
})));
|
|
39
|
+
const urls = hostname == null || wildcardHosts.has(hostname) ? [{
|
|
40
|
+
local: true,
|
|
41
|
+
url: urlOf("localhost"),
|
|
42
|
+
interfaceName: void 0
|
|
43
|
+
}, ...addresses.filter(({ address, family }) => family === "IPv4" && address !== "127.0.0.1").map(({ name, address }) => ({
|
|
44
|
+
local: false,
|
|
45
|
+
url: urlOf(address),
|
|
46
|
+
interfaceName: name
|
|
47
|
+
}))] : [{
|
|
48
|
+
local: loopbackHosts.has(hostname),
|
|
49
|
+
url: urlOf(hostname),
|
|
50
|
+
interfaceName: addresses.find(({ address }) => address === hostname)?.name
|
|
51
|
+
}];
|
|
52
|
+
const width = Math.max(0, ...urls.filter(({ local }) => !local).map(({ url }) => url.length));
|
|
53
|
+
return urls.map(({ local, url, interfaceName }) => {
|
|
54
|
+
const label = styleText("bold", local ? "Local" : "Network") + (local ? ": " : ": ");
|
|
55
|
+
const link = styleText("cyan", url.replace(`:${port}/`, `:${styleText("bold", String(port))}/`));
|
|
56
|
+
const suffix = local || interfaceName == null ? "" : " ".repeat(width - url.length + 2) + styleText("dim", interfaceName);
|
|
57
|
+
return ` ${styleText("green", "➜")} ${label}${link}${suffix}`;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
11
61
|
// src/cli/served-apps.ts
|
|
12
62
|
/**
|
|
13
63
|
* Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a
|
|
@@ -164,7 +214,7 @@ async function start() {
|
|
|
164
214
|
directory: viteServer.config.publicDir,
|
|
165
215
|
base: viteServer.config.base
|
|
166
216
|
}) });
|
|
167
|
-
const sink =
|
|
217
|
+
const sink = textSink();
|
|
168
218
|
const apps = servedApps();
|
|
169
219
|
const listener = requestListener(async (request, bindings) => {
|
|
170
220
|
try {
|
|
@@ -197,7 +247,12 @@ async function start() {
|
|
|
197
247
|
});
|
|
198
248
|
}
|
|
199
249
|
});
|
|
200
|
-
|
|
250
|
+
viteServer.config.logger.info("");
|
|
251
|
+
for (const line of devUrlLines({
|
|
252
|
+
hostname,
|
|
253
|
+
port: boundPort,
|
|
254
|
+
base: viteServer.config.base
|
|
255
|
+
})) viteServer.config.logger.info(line);
|
|
201
256
|
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
|
|
202
257
|
const pluginsStopped = apps.stopAll();
|
|
203
258
|
httpServer.closeAllConnections();
|
|
@@ -250,4 +305,4 @@ function viteHostname(host) {
|
|
|
250
305
|
}
|
|
251
306
|
|
|
252
307
|
export { start };
|
|
253
|
-
//# sourceMappingURL=start-
|
|
308
|
+
//# sourceMappingURL=start-3_WlRLdK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start-3_WlRLdK.js","names":["createServer","createHttpServer"],"sources":["../src/cli/dev-urls.ts","../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import { networkInterfaces } from \"node:os\";\nimport { styleText } from \"node:util\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\n\nconst wildcardHosts = new Set([\"\", \"0.0.0.0\", \"::\"]);\nconst loopbackHosts = new Set([\"localhost\", \"127.0.0.1\", \"::1\"]);\n\ntype DevUrl = { local: boolean; url: string; interfaceName: string | undefined };\n\n/**\n * The lines that `app-server start` prints when it listens, in the format of `vite dev`. Each URL\n * ends with `base`, Vite's base path. A wildcard host gets a `localhost` line, then one line for\n * each IPv4 (Internet Protocol version 4) interface.\n *\n * @example\n * devUrlLines({ hostname: \"localhost\", port: 3000, base: \"/\" }); // => [\" ➜ Local: http://localhost:3000/\"]\n */\nexport function devUrlLines(\n\t{ hostname, port, base }: { hostname: string | undefined; port: number; base: string },\n\tinterfaces = networkInterfaces(),\n): string[] {\n\tconst urlOf = (host: string) => `${listenerUrl(host, port).slice(0, -1)}${base}`;\n\tconst addresses = Object.entries(interfaces).flatMap(([name, details = []]) =>\n\t\tdetails.map(({ address, family }) => ({ name, address, family })),\n\t);\n\t// Why a `localhost` line with no lookup: a host with no IPv4 loopback still gets a URL to open.\n\tconst urls: DevUrl[] =\n\t\thostname == null || wildcardHosts.has(hostname)\n\t\t\t? [\n\t\t\t\t\t{ local: true, url: urlOf(\"localhost\"), interfaceName: undefined },\n\t\t\t\t\t...addresses\n\t\t\t\t\t\t.filter(({ address, family }) => family === \"IPv4\" && address !== \"127.0.0.1\")\n\t\t\t\t\t\t.map(({ name, address }) => ({\n\t\t\t\t\t\t\tlocal: false,\n\t\t\t\t\t\t\turl: urlOf(address),\n\t\t\t\t\t\t\tinterfaceName: name,\n\t\t\t\t\t\t})),\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlocal: loopbackHosts.has(hostname),\n\t\t\t\t\t\turl: urlOf(hostname),\n\t\t\t\t\t\tinterfaceName: addresses.find(({ address }) => address === hostname)?.name,\n\t\t\t\t\t},\n\t\t\t\t];\n\tconst width = Math.max(0, ...urls.filter(({ local }) => !local).map(({ url }) => url.length));\n\treturn urls.map(({ local, url, interfaceName }) => {\n\t\tconst label = styleText(\"bold\", local ? \"Local\" : \"Network\") + (local ? \": \" : \": \");\n\t\tconst link = styleText(\n\t\t\t\"cyan\",\n\t\t\turl.replace(`:${port}/`, `:${styleText(\"bold\", String(port))}/`),\n\t\t);\n\t\tconst suffix =\n\t\t\tlocal || interfaceName == null\n\t\t\t\t? \"\"\n\t\t\t\t: \" \".repeat(width - url.length + 2) + styleText(\"dim\", interfaceName);\n\t\treturn ` ${styleText(\"green\", \"➜\")} ${label}${link}${suffix}`;\n\t});\n}\n","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 } from \"node:http\";\nimport type { Server } from \"node:http\";\nimport type { Plugin } from \"vite\";\nimport { errorAttributes, textSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { devUrlLines } from \"./dev-urls.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. Vite's plugins get the CLI's HTTP server as\n * `server.httpServer`.\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\t// Why `true`, not `{ server }`: Vite then adds a proxy `upgrade` listener to the server, and a\n\t\t// restart does not remove it.\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t\tplugins: [shareHttpServer(httpServer)],\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\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = textSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\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\t// Why Vite's logger: the lines then follow the app's `logLevel` and `customLogger`, as in `vite dev`.\n\tviteServer.config.logger.info(\"\");\n\tfor (const line of devUrlLines({ hostname, port: boundPort, base: viteServer.config.base })) {\n\t\tviteServer.config.logger.info(line);\n\t}\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/**\n * A Vite plugin that sets `server.httpServer` to the CLI's HTTP server before\n * the `configureServer` hooks of the app's plugins run. Why: in middleware\n * mode, Vite sets it to `null`. Then a plugin that waits for `listening` or\n * `close` on it does nothing, with no error.\n *\n * @example\n * vite.createServer({ plugins: [shareHttpServer(httpServer)] });\n */\nfunction shareHttpServer(httpServer: Server): Plugin {\n\tconst plugin: Plugin = {\n\t\tname: \"@ngrok/app-server:http-server\",\n\t\t// Why first: Vite puts an inline plugin after the config file's plugins, so an app plugin with\n\t\t// `enforce: \"pre\"` and `order: \"pre\"` runs its `configureServer` before this one.\n\t\tconfigResolved: (config) => {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite sorts each hook from this array later.\n\t\t\tconst plugins = config.plugins as Plugin[];\n\t\t\tplugins.splice(plugins.indexOf(plugin), 1);\n\t\t\tplugins.unshift(plugin);\n\t\t},\n\t\tconfigureServer: {\n\t\t\torder: \"pre\",\n\t\t\thandler: (server) => {\n\t\t\t\tserver.httpServer = httpServer;\n\t\t\t},\n\t\t},\n\t};\n\treturn plugin;\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":";;;;;;;;;;;;;AAIA,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAI;CAAW;AAAI,CAAC;AACnD,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAK,CAAC;;;;;;;;;AAY/D,SAAgB,YACf,EAAE,UAAU,MAAM,QAClB,aAAa,kBAAkB,GACpB;CACX,MAAM,SAAS,SAAiB,GAAG,YAAY,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI;CAC1E,MAAM,YAAY,OAAO,QAAQ,UAAU,CAAC,CAAC,SAAS,CAAC,MAAM,UAAU,CAAC,OACvE,QAAQ,KAAK,EAAE,SAAS,cAAc;EAAE;EAAM;EAAS;CAAO,EAAE,CACjE;CAEA,MAAM,OACL,YAAY,QAAQ,cAAc,IAAI,QAAQ,IAC3C,CACA;EAAE,OAAO;EAAM,KAAK,MAAM,WAAW;EAAG,eAAe;CAAU,GACjE,GAAG,UACD,QAAQ,EAAE,SAAS,aAAa,WAAW,UAAU,YAAY,WAAW,CAAC,CAC7E,KAAK,EAAE,MAAM,eAAe;EAC5B,OAAO;EACP,KAAK,MAAM,OAAO;EAClB,eAAe;CAChB,EAAE,CACJ,IACC,CACA;EACC,OAAO,cAAc,IAAI,QAAQ;EACjC,KAAK,MAAM,QAAQ;EACnB,eAAe,UAAU,MAAM,EAAE,cAAc,YAAY,QAAQ,CAAC,EAAE;CACvE,CACD;CACH,MA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AAC,OAAO,UAAmB;GAC/D,KAAK,IAAI,SAAS,qBAAqB,gBAAgB,KAAK,CAAC;GAC7D,QAAQ,WAAW;EACpB,CAAC;EACD,AAAK,QAAQ,IAAI;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;;;;;;;;;AAWA,SAAS,gBAAgB,YAA4B;CACpD,MAAM,SAAiB;EACtB,MAAM;EAGN,iBAAiB,WAAW;GAE3B,MAAM,UAAU,OAAO;GACvB,QAAQ,OAAO,QAAQ,QAAQ,MAAM,GAAG,CAAC;GACzC,QAAQ,QAAQ,MAAM;EACvB;EACA,iBAAiB;GAChB,OAAO;GACP,UAAU,WAAW;IACpB,OAAO,aAAa;GACrB;EACD;CACD;CACA,OAAO;AACR;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as hookedHeaders } from "./header-hook-Vzw9J9BY.js";
|
|
2
|
-
import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-
|
|
2
|
+
import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-CT2mWlKM.js";
|
|
3
3
|
import { getMimeType } from "hono/utils/mime";
|
|
4
4
|
|
|
5
5
|
// src/core/vary.ts
|
|
@@ -19,7 +19,15 @@ function withVary(vary, name) {
|
|
|
19
19
|
|
|
20
20
|
// src/core/static-files.ts
|
|
21
21
|
/** The content types that `mime` lacks and that no framework owns. */
|
|
22
|
-
const CORE_CONTENT_TYPES = {
|
|
22
|
+
const CORE_CONTENT_TYPES = {
|
|
23
|
+
".atom": "application/atom+xml",
|
|
24
|
+
".md": "text/markdown; charset=utf-8",
|
|
25
|
+
".pem": "application/x-pem-file",
|
|
26
|
+
".rss": "application/rss+xml",
|
|
27
|
+
".sh": "application/x-sh",
|
|
28
|
+
".yaml": "text/yaml; charset=utf-8",
|
|
29
|
+
".yml": "text/yaml; charset=utf-8"
|
|
30
|
+
};
|
|
23
31
|
/**
|
|
24
32
|
* Whether a URL path names a dotfile or goes through a dot directory.
|
|
25
33
|
* `/.well-known/` stays reachable.
|
|
@@ -299,4 +307,4 @@ async function staticResponse(context, { files, file, headers, contentTypes }) {
|
|
|
299
307
|
}
|
|
300
308
|
|
|
301
309
|
export { keptFiles as a, isFilePath as i, findStaticFile as n, staticResponse as o, hasDotSegment as r, withVary as s, contentType as t };
|
|
302
|
-
//# sourceMappingURL=static-files-
|
|
310
|
+
//# sourceMappingURL=static-files-C2ea8KQ6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"static-files-C2ea8KQ6.js","names":[],"sources":["../src/core/vary.ts","../src/core/static-files.ts"],"sourcesContent":["/**\n * A `Vary` value with `name` added, or `undefined` when `vary` already covers\n * it. The existing values stay as they are.\n *\n * @example\n * withVary(\"Accept\", \"Accept-Encoding\"); // => \"Accept, Accept-Encoding\"\n * withVary(\"accept-encoding\", \"Accept-Encoding\"); // => undefined\n */\nexport function withVary(vary: string | null, name: string): string | undefined {\n\tif (vary == null || vary.trim() === \"\") {\n\t\treturn name;\n\t}\n\tconst values = new Set(vary.split(\",\").map((value) => value.trim().toLowerCase()));\n\treturn values.has(name.toLowerCase()) || values.has(\"*\") ? undefined : `${vary}, ${name}`;\n}\n","import type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { COPY_ENCODINGS, copyName, forbidsTransform, preferredEncoding } from \"./compression.js\";\nimport type { Encoding } from \"./compression.js\";\nimport { hookedHeaders } from \"./header-hook.js\";\nimport type { AppServerEnv, ByteRange, StaticFiles } from \"./types.js\";\nimport { withVary } from \"./vary.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\".atom\": \"application/atom+xml\",\n\t\".md\": \"text/markdown; charset=utf-8\",\n\t\".pem\": \"application/x-pem-file\",\n\t\".rss\": \"application/rss+xml\",\n\t\".sh\": \"application/x-sh\",\n\t// Why `text/yaml`: a browser shows a text type, and `express.static` sends it.\n\t\".yaml\": \"text/yaml; charset=utf-8\",\n\t\".yml\": \"text/yaml; 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 *\n * @example\n * hasDotSegment(\"/assets/.private/key.json\"); // => true\n * hasDotSegment(\"/.well-known/security.txt\"); // => false\n */\nexport function 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 * Whether a decoded URL path, such as Hono's `context.req.path`, can name a\n * file of the client build. Dotfiles, paths that leave the client build, and\n * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.\n */\nexport function isFilePath(path: string): boolean {\n\treturn (\n\t\tpath.startsWith(\"/\") &&\n\t\t!path.includes(\"\\0\") &&\n\t\t!path.includes(\"\\\\\") &&\n\t\t!path.split(\"/\").includes(\"..\") &&\n\t\t!path.includes(\"//\") &&\n\t\t!path.endsWith(\"/index.html\") &&\n\t\t!hasDotSegment(path)\n\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. A path that fails\n * `isFilePath` finds 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 (!isFilePath(path)) {\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`. */\nexport function 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/**\n * The last `etagParts` and their hash. Why one entry: each request has the\n * same parts for the life of the process.\n */\nlet lastParts: { key: string; hash: string } | undefined;\n\n/** A short hash of the request's `etagParts`. */\nasync function partsHash(parts: readonly string[]): Promise<string> {\n\tconst key = parts.join(\"\\0\");\n\tif (lastParts?.key === key) {\n\t\treturn lastParts.hash;\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(key));\n\tconst hash = btoa(String.fromCodePoint(...new Uint8Array(digest)))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.slice(0, 16);\n\tlastParts = { key, hash };\n\treturn hash;\n}\n\n/**\n * A weak ETag from a file's size, its modification time, the request's\n * `etagParts`, and the encoding of the body. Why the encoding: after a 304,\n * a cache that holds more than one encoding of the file picks the stored\n * response by its ETag (RFC 9111, section 4.3.4).\n */\nasync function fileEtag(\n\tfile: StaticFile,\n\tparts: readonly string[],\n\tencoding: Encoding | undefined,\n): Promise<string> {\n\tconst tag = [\n\t\tfile.size.toString(16),\n\t\tMath.trunc(file.mtimeMs).toString(16),\n\t\t...(parts.length === 0 ? [] : [await partsHash(parts)]),\n\t\t...(encoding == null ? [] : [encoding]),\n\t];\n\treturn `W/\"${tag.join(\"-\")}\"`;\n}\n\n/**\n * The byte range that a `Range` header asks for in a file of `size` bytes.\n * It gives `\"unsatisfiable\"` for a range that starts after the end of the\n * file, and `undefined` for a header to ignore: a header that is not valid,\n * or one with more than one range.\n *\n * @example\n * byteRange(\"bytes=-100\", 1000); // => { start: 900, end: 999 }\n */\nexport function byteRange(header: string, size: number): ByteRange | \"unsatisfiable\" | undefined {\n\tconst groups = /^bytes=(?<first>\\d*)-(?<last>\\d*)$/u.exec(header.trim())?.groups;\n\tconst first = groups?.first ?? \"\";\n\tconst last = groups?.last ?? \"\";\n\tif (first === \"\" && last === \"\") {\n\t\treturn undefined;\n\t}\n\tif (first === \"\") {\n\t\tconst suffix = Number(last);\n\t\treturn suffix === 0 || size === 0\n\t\t\t? \"unsatisfiable\"\n\t\t\t: { start: Math.max(0, size - suffix), end: size - 1 };\n\t}\n\tconst start = Number(first);\n\tconst end = last === \"\" ? Number.POSITIVE_INFINITY : Number(last);\n\tif (end < start) {\n\t\treturn undefined;\n\t}\n\treturn start >= size ? \"unsatisfiable\" : { start, end: Math.min(end, size - 1) };\n}\n\n/** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */\nconst KEPT_FILE_BYTES = 256 * 1024;\nconst KEPT_TOTAL_BYTES = 32 * 1024 * 1024;\n\n/**\n * `files` that keep the bytes of each small file in memory after the first\n * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that\n * do not change while the server runs, such as a `StaticFiles.snapshot()`.\n *\n * @example\n * const files = keptFiles(await nodeFiles(\"build/client\").snapshot());\n */\nexport function keptFiles(files: StaticFiles): StaticFiles {\n\tconst kept = new Map<string, Promise<Uint8Array>>();\n\tlet total = 0;\n\treturn {\n\t\tstat: files.stat,\n\t\topen: async (path, range) => {\n\t\t\tlet bytes = kept.get(path);\n\t\t\tconst info = bytes == null ? await files.stat(path) : undefined;\n\t\t\t// Why again: another request can start to read the file during the `stat`.\n\t\t\tbytes ??= kept.get(path);\n\t\t\tif (bytes == null) {\n\t\t\t\tif (\n\t\t\t\t\tinfo?.kind !== \"file\" ||\n\t\t\t\t\tinfo.size > KEPT_FILE_BYTES ||\n\t\t\t\t\ttotal + info.size > KEPT_TOTAL_BYTES\n\t\t\t\t) {\n\t\t\t\t\treturn files.open(path, range);\n\t\t\t\t}\n\t\t\t\ttotal += info.size;\n\t\t\t\t// Why the size as a range: the kept bytes then match the `Content-Length` from the lookup.\n\t\t\t\tbytes = files\n\t\t\t\t\t.open(path, { start: 0, end: info.size - 1 })\n\t\t\t\t\t.then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));\n\t\t\t\tkept.set(path, bytes);\n\t\t\t\tbytes.catch(() => {\n\t\t\t\t\tkept.delete(path);\n\t\t\t\t\ttotal -= info.size;\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Why a copy: a later stage can change the bytes that it reads.\n\t\t\tconst chunk = (await bytes).slice(\n\t\t\t\trange?.start ?? 0,\n\t\t\t\trange == null ? undefined : range.end + 1,\n\t\t\t);\n\t\t\treturn new ReadableStream<Uint8Array>({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/** A compressed copy of a static file that the build wrote. */\ntype Copy = StaticFile & { encoding: Encoding };\n\n/**\n * The copy of the file at `path` that the request prefers, from the copies\n * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the\n * `Vary` in `headers`, also for a request that gets no copy.\n */\nasync function preferredCopy(\n\tcontext: Context<AppServerEnv>,\n\t{ files, path, headers }: { files: StaticFiles; path: string; headers: Headers },\n): Promise<Copy | undefined> {\n\t// Why not for an encoded file: the copy would encode it again, under one `Content-Encoding`.\n\tif (\n\t\theaders.has(\"Content-Encoding\") ||\n\t\t(context.get(\"rewritesHtml\") === true &&\n\t\t\t(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst copies: Copy[] = [];\n\tfor (const encoding of COPY_ENCODINGS) {\n\t\tconst copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));\n\t\t// oxlint-disable-next-line no-await-in-loop -- two lookups, and a snapshot answers each at once.\n\t\tconst info = await files.stat(copyPath);\n\t\tif (info?.kind === \"file\") {\n\t\t\tcopies.push({ path: copyPath, size: info.size, mtimeMs: info.mtimeMs, encoding });\n\t\t}\n\t}\n\tif (copies.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst vary = withVary(headers.get(\"Vary\"), \"Accept-Encoding\");\n\tif (vary != null) {\n\t\theaders.set(\"Vary\", vary);\n\t}\n\tif (forbidsTransform(hookedHeaders(context, headers).get(\"Cache-Control\"))) {\n\t\treturn undefined;\n\t}\n\tconst encoding = preferredEncoding(\n\t\tcontext.req.header(\"Accept-Encoding\"),\n\t\tcopies.map((copy) => copy.encoding),\n\t);\n\treturn copies.find((copy) => copy.encoding === encoding);\n}\n\n/**\n * All bytes of a file. Why the size as a range: the body then never has more\n * bytes than its `Content-Length`, even when the file grew after `stat`, and\n * a small file reads into a small buffer.\n */\nasync function wholeFile(\n\tfiles: StaticFiles,\n\tfile: StaticFile,\n): Promise<ReadableStream<Uint8Array> | null> {\n\treturn file.size === 0 ? null : files.open(file.path, { start: 0, end: file.size - 1 });\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, the request's `etagParts`, and its encoding. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only.\n *\n * A GET with one `bytes` range gets a 206 with those bytes, and a range\n * after the end of the file gets a 416. A request with `If-Range` gets the\n * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An\n * HTML file gets no ranges.\n *\n * When the build wrote a compressed copy of the file (`.<file>.br` or\n * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets\n * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its\n * `Content-Encoding`, an ETag for that encoding, and no range. A response\n * marked `no-transform`, also by the header hook of an earlier stage, and a\n * response that `headers` encode, never get a copy. An HTML file gets no\n * copy when an earlier stage sets `rewritesHtml`.\n *\n * @example\n * const file = await findStaticFile(files, \"/llms.txt\");\n * if (file != null) {\n * return staticResponse(context, { files, file, headers: {}, contentTypes: {} });\n * }\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\t{ files, file, headers, contentTypes }: StaticResponseOptions,\n): Promise<Response> {\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path, contentTypes) });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why no ranges for HTML: a stage such as `runtimeEnv` can change the bytes of a page.\n\tconst html = responseHeaders.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\tif (html) {\n\t\tcontext.set(\"staticDocument\", file.path);\n\t}\n\t// Why before the 304: a 304 sends the `Vary` and the ETag of its 200.\n\tconst copy = await preferredCopy(context, { files, path: file.path, headers: responseHeaders });\n\t// Why the header first: `headers` can replace the ETag.\n\tconst etag =\n\t\tresponseHeaders.get(\"ETag\") ??\n\t\t(await fileEtag(file, context.get(\"etagParts\") ?? [], copy?.encoding));\n\tresponseHeaders.set(\"ETag\", etag);\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (copy != null) {\n\t\t// Why no ranges: a client asks for a range of the file, not of its compressed copy.\n\t\tresponseHeaders.set(\"Content-Encoding\", copy.encoding);\n\t\tresponseHeaders.set(\"Content-Length\", String(copy.size));\n\t\tconst body = context.req.method === \"HEAD\" ? null : await wholeFile(files, copy);\n\t\treturn new Response(body, { headers: responseHeaders });\n\t}\n\tif (!html) {\n\t\tresponseHeaders.set(\"Accept-Ranges\", \"bytes\");\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\tconst rangeHeader = context.req.header(\"Range\");\n\tconst range =\n\t\thtml || rangeHeader == null || context.req.header(\"If-Range\") != null\n\t\t\t? undefined\n\t\t\t: byteRange(rangeHeader, file.size);\n\tif (range === \"unsatisfiable\") {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes */${file.size}`);\n\t\tresponseHeaders.delete(\"Content-Length\");\n\t\treturn new Response(null, { status: 416, headers: responseHeaders });\n\t}\n\tif (range != null) {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes ${range.start}-${range.end}/${file.size}`);\n\t\tresponseHeaders.set(\"Content-Length\", String(range.end - range.start + 1));\n\t\treturn new Response(await files.open(file.path, range), {\n\t\t\tstatus: 206,\n\t\t\theaders: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;CAE7C,gBAAgB,IAAI,kBAAkB,OAAO,KAAK,IAAI,CAAC;CACvD,IAAI,QAAQ,IAAI,WAAW,QAC1B,OAAO,IAAI,SAAS,MAAM,EAAE,SAAS,gBAAgB,CAAC;CAEvD,MAAM,cAAc,QAAQ,IAAI,OAAO,OAAO;CAC9C,MAAM,QACL,QAAQ,eAAe,QAAQ,QAAQ,IAAI,OAAO,UAAU,KAAK,OAC9D,SACA,UAAU,aAAa,KAAK,IAAI;CACpC,IAAI,UAAU,iBAAiB;EAC9B,gBAAgB,IAAI,iBAAiB,WAAW,KAAK,MAAM;EAC3D,gBAAgB,OAAO,gBAAgB;EACvC,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS;EAAgB,CAAC;CACpE;CACA,IAAI,SAAS,MAAM;EAClB,gBAAgB,IAAI,iBAAiB,SAAS,MAAM,MAAM,GAAG,MAAM,IAAI,GAAG,KAAK,MAAM;EACrF,gBAAgB,IAAI,kBAAkB,OAAO,MAAM,MAAM,MAAM,QAAQ,CAAC,CAAC;EACzE,OAAO,IAAI,SAAS,MAAM,MAAM,KAAK,KAAK,MAAM,KAAK,GAAG;GACvD,QAAQ;GACR,SAAS;EACV,CAAC;CACF;CACA,OAAO,IAAI,SAAS,MAAM,UAAU,OAAO,IAAI,GAAG,EAAE,SAAS,gBAAgB,CAAC;AAC/E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as FrameworkBuild } from "./index-
|
|
1
|
+
import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
|
|
2
2
|
/**
|
|
3
3
|
* The build side of the TanStack Start adapter. `appServer` uses it when the
|
|
4
4
|
* Vite config has the TanStack Start plugin, so pass it only to override that.
|
package/dist/tanstack-start.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as FrameworkRuntime, h as Mode } from "./types-
|
|
2
|
-
import { t as TrailingSlash } from "./trailing-slash-
|
|
1
|
+
import { a as FrameworkRuntime, h as Mode } from "./types-BKJxtIuj.js";
|
|
2
|
+
import { t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
|
|
3
3
|
import { AnyRouter, RegisteredRouter } from "@tanstack/react-router";
|
|
4
4
|
/**
|
|
5
5
|
* The `trailingSlash` mode of a TanStack router: the app's registered router
|
|
@@ -33,10 +33,10 @@ function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
|
|
|
33
33
|
};
|
|
34
34
|
if ("Bun" in globalThis) return (await import("./bun-BCz6K_Xv.js")).listen(fetch, options);
|
|
35
35
|
if ("Deno" in globalThis) return (await import("./deno-aqhikNMG.js")).listen(fetch, options);
|
|
36
|
-
return (await import("./node-
|
|
36
|
+
return (await import("./node-Bgzhwix0.js")).listen(fetch, options);
|
|
37
37
|
}
|
|
38
38
|
};
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
export { tcp as n, parsePort as t };
|
|
42
|
-
//# sourceMappingURL=tcp-
|
|
42
|
+
//# sourceMappingURL=tcp-CKMCT9RP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tcp-
|
|
1
|
+
{"version":3,"file":"tcp-CKMCT9RP.js","names":[],"sources":["../src/node/tcp.ts"],"sourcesContent":["import type { Listener } from \"../core/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, { trustForwardedProto = false } = {}) => {\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\ttrustForwardedProto,\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"],"mappings":";;AAGA,MAAM,0BAA0B;;;;;;;;AAmBhC,SAAgB,UAAU,OAAuB;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OACxE,MAAM,IAAI,MAAM,iDAAiD,MAAM,GAAG;CAE3E,OAAO;AACR;;;;;;;;;AAUA,SAAgB,IAAI,EACnB,MACA,MACA,gBAAgB,4BACD,CAAC,GAAa;CAC7B,OAAO;EACN,MAAM;EACN,OAAO,OAAO,OAAO,EAAE,sBAAsB,UAAU,CAAC,MAAM;GAC7D,MAAM,UAAU;IACf,MAAM,SAAS,QAAQ,IAAI,QAAQ,OAAO,MAAO,UAAU,QAAQ,IAAI,IAAI;IAC3E,UAAU,SAAS,QAAQ,IAAI,QAAQ;IACvC;IACA;GACD;GACA,IAAI,SAAS,YACZ,QAAQ,MAAM,OAAO,qBAAoB,CAAE,OAAO,OAAO,OAAO;GAEjE,IAAI,UAAU,YACb,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;GAElE,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;EAClE;CACD;AACD"}
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _ as RequestContext, a as FrameworkRuntime } from "./types-
|
|
2
|
-
import { t as AppServer } from "./create-server-
|
|
1
|
+
import { _ as RequestContext, a as FrameworkRuntime } from "./types-BKJxtIuj.js";
|
|
2
|
+
import { t as AppServer } from "./create-server-kxyhCdhv.js";
|
|
3
3
|
/** Options for {@link createTestServer}. */
|
|
4
4
|
export type TestServerOptions = {
|
|
5
5
|
/**
|
package/dist/testing.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { r as withRequestContext$1 } from "./request-context-BtQ87VYb.js";
|
|
2
|
-
import { i as requestLogger } from "./log-
|
|
2
|
+
import { i as requestLogger } from "./log-C8LGQ23s.js";
|
|
3
3
|
import { t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
|
|
4
|
-
import { t as createEntry } from "./entry-
|
|
5
|
-
import { t as host } from "./node-
|
|
6
|
-
import { n as scriptHashesOf } from "./script-hashes-
|
|
4
|
+
import { t as createEntry } from "./entry-65IESBSA.js";
|
|
5
|
+
import { t as host } from "./node-DFI5TjTk.js";
|
|
6
|
+
import { n as scriptHashesOf } from "./script-hashes-CU7P9oZU.js";
|
|
7
7
|
import { Context } from "hono";
|
|
8
8
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
9
9
|
import { dirname, isAbsolute, join, normalize, sep } from "node:path";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { g as Plugin } from "./types-
|
|
1
|
+
import { g as Plugin } from "./types-BKJxtIuj.js";
|
|
2
2
|
/**
|
|
3
3
|
* How a page URL ends:
|
|
4
4
|
*
|
|
@@ -33,4 +33,4 @@ type TrailingSlashOptions = {
|
|
|
33
33
|
*/
|
|
34
34
|
declare function trailingSlash({ mode }: TrailingSlashOptions): Plugin;
|
|
35
35
|
export { TrailingSlashOptions as n, trailingSlash as r, TrailingSlash as t };
|
|
36
|
-
//# sourceMappingURL=trailing-slash-
|
|
36
|
+
//# sourceMappingURL=trailing-slash-DeOUxMYo.d.ts.map
|