@ngrok/app-server 0.3.6 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +40 -9
  2. package/dist/cli.js +3 -3
  3. package/dist/client.js +1 -1
  4. package/dist/{create-server-C_90R50y.js → create-server-Bp1yILQk.js} +71 -30
  5. package/dist/create-server-Bp1yILQk.js.map +1 -0
  6. package/dist/{create-server-kxyhCdhv.d.ts → create-server-X2GR-U6t.d.ts} +33 -13
  7. package/dist/{entry-65IESBSA.js → entry-BoxCqc6w.js} +13 -5
  8. package/dist/entry-BoxCqc6w.js.map +1 -0
  9. package/dist/{entry-CNL4OsEn.d.ts → entry-DZTCaL3d.d.ts} +3 -3
  10. package/dist/index.d.ts +18 -5
  11. package/dist/index.js +6 -6
  12. package/dist/{load-entry-BftQ3qlz.js → load-entry-CCPWbsrj.js} +4 -4
  13. package/dist/{load-entry-BftQ3qlz.js.map → load-entry-CCPWbsrj.js.map} +1 -1
  14. package/dist/log-DQAS5gGT.js +314 -0
  15. package/dist/log-DQAS5gGT.js.map +1 -0
  16. package/dist/{node-CA7t-s6D.js → node-CVVdk2N6.js} +3 -3
  17. package/dist/{node-CA7t-s6D.js.map → node-CVVdk2N6.js.map} +1 -1
  18. package/dist/{node-Fo6EodEV.js → node-D6m6e6EI.js} +2 -2
  19. package/dist/{node-Fo6EodEV.js.map → node-D6m6e6EI.js.map} +1 -1
  20. package/dist/node.d.ts +1 -1
  21. package/dist/node.js +2 -2
  22. package/dist/react-router.d.ts +2 -2
  23. package/dist/react-router.js +3 -4
  24. package/dist/react-router.js.map +1 -1
  25. package/dist/request-context-Bxdbk5P1.js +80 -0
  26. package/dist/request-context-Bxdbk5P1.js.map +1 -0
  27. package/dist/{response-edge-D3CAjukJ.js → response-edge-CU8ZvL_F.js} +3 -3
  28. package/dist/response-edge-CU8ZvL_F.js.map +1 -0
  29. package/dist/{response-writer-BUyOW4n2.js → response-writer-D7KHfr8n.js} +2 -2
  30. package/dist/{response-writer-BUyOW4n2.js.map → response-writer-D7KHfr8n.js.map} +1 -1
  31. package/dist/{serve-CEecObwD.js → serve-W4WacdOw.js} +2 -2
  32. package/dist/{serve-CEecObwD.js.map → serve-W4WacdOw.js.map} +1 -1
  33. package/dist/{start-CDnHKNca.js → start-j0VlxeiI.js} +29 -13
  34. package/dist/start-j0VlxeiI.js.map +1 -0
  35. package/dist/tanstack-start.d.ts +2 -2
  36. package/dist/tanstack-start.js +1 -1
  37. package/dist/{tcp-BPeUZaNg.js → tcp-BgDXbjOG.js} +2 -2
  38. package/dist/{tcp-BPeUZaNg.js.map → tcp-BgDXbjOG.js.map} +1 -1
  39. package/dist/testing.d.ts +2 -2
  40. package/dist/testing.js +4 -4
  41. package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D2QWKWEu.d.ts} +2 -2
  42. package/dist/{types-BKJxtIuj.d.ts → types-MgFtkNQW.d.ts} +35 -4
  43. package/dist/vercel.d.ts +2 -2
  44. package/dist/vercel.js +4 -4
  45. package/package.json +1 -1
  46. package/dist/create-server-C_90R50y.js.map +0 -1
  47. package/dist/entry-65IESBSA.js.map +0 -1
  48. package/dist/log-C8LGQ23s.js +0 -149
  49. package/dist/log-C8LGQ23s.js.map +0 -1
  50. package/dist/request-context-BtQ87VYb.js +0 -40
  51. package/dist/request-context-BtQ87VYb.js.map +0 -1
  52. package/dist/response-edge-D3CAjukJ.js.map +0 -1
  53. package/dist/start-CDnHKNca.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"log-C8LGQ23s.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(`${JSON.stringify({ time: isoNow(), level, message, ...attributes })}\\n`);\n\t\t},\n\t};\n}\n\n/**\n * A log sink that writes one line of `key=value` pairs per event, in the text\n * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control\n * character is quoted, so an escape sequence cannot reach the terminal.\n * `app-server start` uses it, because a person reads those lines.\n *\n * @param write - Where each line goes. Defaults to stdout, at once. Why not\n * one write for each turn: the lines then keep their order with Vite's lines.\n *\n * @example\n * textSink().log(\"info\", \"port in use, trying the next port\", { \"server.port\": 3000 });\n * // time=2026-11-11T12:00:00.000Z level=INFO msg=\"port in use, trying the next port\" server.port=3000\n */\nexport function textSink(\n\twrite: (line: string) => void = (line) => {\n\t\tprocess.stdout.write(line);\n\t},\n): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\tlet line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;\n\t\t\tfor (const [key, value] of Object.entries(attributes)) {\n\t\t\t\tline += ` ${key}=${textValue(value)}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */\nfunction textValue(value: unknown): string {\n\tconst text = typeof value === \"string\" ? value : (JSON.stringify(value) ?? String(value));\n\treturn /^[^\\s\"=\\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\n/** Flat `error.*` attributes for a thrown value. */\nexport function errorAttributes(error: unknown): Record<string, unknown> {\n\tif (error instanceof Error) {\n\t\treturn { \"error.kind\": error.name, \"error.message\": error.message, \"error.stack\": error.stack };\n\t}\n\treturn { \"error.message\": String(error) };\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log(\"debug\", message, withBase(attributes));\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log(\"info\", message, withBase(attributes));\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log(\"warn\", message, withBase(attributes));\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log(\"error\", message, withBase(attributes));\n\t\t},\n\t};\n}\n\n/** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */\nexport function requestLogger(sink: LogSink, context: Context<AppServerEnv>): RequestLogger {\n\t// Why read at call time: the `requestId` plugin runs after this logger is made. Why one object:\n\t// a base object and then a merge copy each attribute two times.\n\treturn sinkLogger(sink, (attributes) => ({\n\t\t\"http.request_id\": context.get(\"requestId\"),\n\t\t\"http.method\": context.req.method,\n\t\t\"http.url_details.path\": context.req.path,\n\t\t...context.get(\"logAttributes\"),\n\t\t...attributes,\n\t}));\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAE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4
- * have two hosts, and each request uses the store of its own app.
5
- */
6
- const stores = /* @__PURE__ */ new Set();
7
- /** The {@link RequestContext} values of a request. */
8
- function requestContextValues(context) {
9
- return {
10
- requestId: context.get("requestId"),
11
- logger: context.get("logger"),
12
- cspNonce: context.get("cspNonce"),
13
- clientAddress: context.get("clientAddress")
14
- };
15
- }
16
- /** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
17
- async function withRequestContext(store, context, work) {
18
- if (store == null) return work();
19
- stores.add(store);
20
- return store.run(context, work);
21
- }
22
- /**
23
- * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
24
- * outside a server request, such as in a prerender pass, or on a host with no
25
- * request storage.
26
- *
27
- * @example
28
- * export async function loader() {
29
- * requestContext()?.logger.info("loading the dashboard");
30
- * }
31
- */
32
- function requestContext() {
33
- for (const store of stores) {
34
- const context = store.get();
35
- if (context != null) return requestContextValues(context);
36
- }
37
- }
38
-
39
- export { requestContextValues as n, withRequestContext as r, requestContext as t };
40
- //# sourceMappingURL=request-context-BtQ87VYb.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-context-BtQ87VYb.js","names":[],"sources":["../src/core/request-context.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, RequestContext, RequestStore } from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** The {@link RequestContext} values of a request. */\nexport function requestContextValues(context: Context<AppServerEnv>): RequestContext {\n\treturn {\n\t\trequestId: context.get(\"requestId\"),\n\t\tlogger: context.get(\"logger\"),\n\t\tcspNonce: context.get(\"cspNonce\"),\n\t\tclientAddress: context.get(\"clientAddress\"),\n\t};\n}\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext<Result>(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<Result>,\n): Promise<Result> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn requestContextValues(context);\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,yBAAS,IAAI,IAAkB;;AAGrC,SAAgB,qBAAqB,SAAgD;CACpF,OAAO;EACN,WAAW,QAAQ,IAAI,WAAW;EAClC,QAAQ,QAAQ,IAAI,QAAQ;EAC5B,UAAU,QAAQ,IAAI,UAAU;EAChC,eAAe,QAAQ,IAAI,eAAe;CAC3C;AACD;;AAGA,eAAsB,mBACrB,OACA,SACA,MACkB;CAClB,IAAI,SAAS,MACZ,OAAO,KAAK;CAEb,OAAO,IAAI,KAAK;CAChB,OAAO,MAAM,IAAI,SAAS,IAAI;AAC/B;;;;;;;;;;;AAYA,SAAgB,iBAA6C;CAC5D,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,WAAW,MACd,OAAO,qBAAqB,OAAO;CAErC;AAED"}
@@ -1 +0,0 @@
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\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;CACpC,OAAO,UAAU,KAAK,SAAY,KAAK,QAAQ;AAChD;;AAGA,SAAS,SAAS,OAA0B,QAAoC;CAC/E,IAAI,MAAM,WAAW,OAAO,QAC3B,OAAO;CAER,KAAK,IAAI,QAAQ,GAAG,QAA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,SAAgB,eACf,SACA,QAC4B;CAC5B,OAAO,WAAW,SAAS,QAAQ,OAAO,MAAM,SAAS,CAAC;AAC3D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"start-CDnHKNca.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,EAA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