@botiverse/porthole 0.2.4 → 0.3.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 (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
@@ -0,0 +1,395 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import type { Displays } from "../displays/displays.ts";
3
+ import type { FrameLocation, InstanceLocator, InstanceRef } from "../isolation/types.ts";
4
+ import { LocateError } from "./locator.ts";
5
+ import type { FrameOutcome } from "./types.ts";
6
+
7
+ /**
8
+ * The client half of the host kit (P072): what the app's page needs from its server's Porthole
9
+ * routes (`ContentHost.routes`, under `/porthole`): whether frames are served and so which config
10
+ * each kind shows under, frame locations, clean addresses, and (for an app whose page holds a
11
+ * token rather than a cookie) the viewer handoff.
12
+ *
13
+ * const porthole = portholeClient({ displays }); // base "/porthole"
14
+ * const config = porthole.config("page"); // null until meta is known
15
+ * createHost(config, { locator: porthole }).mount(box, { …, instance });
16
+ */
17
+
18
+ /** What `GET <prefix>/meta` answers (`ContentHost.clientMeta`). */
19
+ export interface ContentClientMeta {
20
+ readonly served: boolean;
21
+ readonly contentSource: string | null;
22
+ readonly frameSources: readonly string[];
23
+ readonly health: {
24
+ readonly state: "off" | "checking" | "healthy" | "unhealthy";
25
+ readonly reason?: string;
26
+ } | null;
27
+ }
28
+
29
+ export interface PortholeClientOptions<N extends string> {
30
+ readonly displays: Displays<N>;
31
+ /** Where the server's Porthole routes are: a path (`/porthole`) or a URL (a desktop app's). */
32
+ readonly base?: string;
33
+ /** Headers for each request (an `authorization`), or a function giving them now. */
34
+ readonly headers?: HeadersInit | (() => HeadersInit);
35
+ /** Default `same-origin` (the app's own cookies); `include` for a base on another origin. */
36
+ readonly credentials?: RequestCredentials;
37
+ /** Meta the server put in the page, so frames needn't wait for a request. */
38
+ readonly meta?: ContentClientMeta;
39
+ /**
40
+ * Keep the viewer handoff fresh (`entry.handoff`, P072): an app whose page authenticates with
41
+ * a token. Done now, when the page regains focus, and when it becomes visible.
42
+ */
43
+ readonly handoff?: boolean;
44
+ readonly fetch?: typeof fetch;
45
+ }
46
+
47
+ /**
48
+ * Every function is declared `this: void` (P074): each may be passed bare
49
+ * (`useSyncExternalStore(porthole.subscribe, porthole.meta)`), and none reads `this`.
50
+ */
51
+ export interface PortholeClient<N extends string = string> extends InstanceLocator {
52
+ readonly displays: Displays<N>;
53
+ /** Locates an instance's frame through `POST <base>/frames` (`InstanceLocator`). */
54
+ locate(this: void, instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation>;
55
+ /** The meta as last fetched, or null before it is known. */
56
+ meta(this: void): ContentClientMeta | null;
57
+ /** Called when the meta changes (frames served or not). */
58
+ subscribe(this: void, listener: () => void): () => void;
59
+ /** Fetches the meta again. */
60
+ refresh(this: void): Promise<ContentClientMeta | null>;
61
+ /**
62
+ * The config a kind shows under now: served while frames are served, else opaque (a url kind:
63
+ * null). Null until the meta is known, so a frame never starts opaque and then restarts served.
64
+ */
65
+ config(this: void, kind: N): PortholeConfig | null;
66
+ /** The same, for an instance's kind. */
67
+ configFor(this: void, instance: InstanceRef): PortholeConfig | null;
68
+ /** An instance's clean address (`entry.pathOf` on the server), or null. */
69
+ link(this: void, instance: InstanceRef): Promise<string | null>;
70
+ /** The clean address if already known (from locating the instance), for rendering. */
71
+ knownLink(this: void, instance: InstanceRef): string | null;
72
+ /**
73
+ * Opens an instance's clean address in a new tab: call it in the click (the tab opens at once,
74
+ * then goes to the address).
75
+ */
76
+ openInTab(this: void, instance: InstanceRef): void;
77
+ /** Hands the signed-in viewer to the authorize route (`entry.handoff`); true if it took. */
78
+ handoff(this: void): Promise<boolean>;
79
+ /**
80
+ * `next` if it is this server's authorize route (after a sign-in), or with `{ app: true }` any
81
+ * address on the app's own origin; else null (`entryTarget`).
82
+ */
83
+ entryTarget(this: void, next: unknown, options?: { readonly app?: boolean }): string | null;
84
+ /** Stops refreshing the handoff. */
85
+ close(this: void): void;
86
+ }
87
+
88
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
89
+ value !== null && typeof value === "object" && !Array.isArray(value);
90
+
91
+ /**
92
+ * Whether a sign-in's `next` is the app's authorize route (P072): the open-redirect guard a
93
+ * single-page app runs before going on to it. Null for anything else; with `{ app: true }`, also
94
+ * any path or address on the app's own origin (P074), so one check serves a sign-in that comes
95
+ * back to redirect entry or to the app's own pages. Never another origin.
96
+ *
97
+ * The authorize route is `<first app origin><prefix>/authorize` unless the server names another
98
+ * (`entry.authorizeUrl`): `https://app.example.com/porthole/authorize` by default.
99
+ */
100
+ export function entryTarget(
101
+ next: unknown,
102
+ authorizeUrl: string,
103
+ options: { readonly app?: boolean } = {},
104
+ ): string | null {
105
+ if (typeof next !== "string" || next.length > 8_192) {
106
+ return null;
107
+ }
108
+ let target: URL;
109
+ let route: URL;
110
+ try {
111
+ route = new URL(authorizeUrl);
112
+ target = new URL(next, route);
113
+ } catch {
114
+ return null;
115
+ }
116
+ if (
117
+ target.origin === route.origin &&
118
+ target.pathname === route.pathname &&
119
+ target.hash === "" &&
120
+ target.searchParams.has("state")
121
+ ) {
122
+ return target.href;
123
+ }
124
+ // An app path: one leading slash, no backslash (`//evil.example` and `/\evil.example` are
125
+ // other sites to a browser), and still the app's origin once resolved.
126
+ const path = /^\/(?![/\\])/u.test(next) && !next.includes("\\");
127
+ const absolute = /^https?:\/\//iu.test(next);
128
+ return options.app === true && (path || absolute) && target.origin === route.origin
129
+ ? target.href
130
+ : null;
131
+ }
132
+
133
+ export function portholeClient<N extends string>(
134
+ options: PortholeClientOptions<N>,
135
+ ): PortholeClient<N> {
136
+ const base = (options.base ?? "/porthole").replace(/\/+$/u, "");
137
+ const ask =
138
+ options.fetch ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init));
139
+ const headersNow = (): Headers =>
140
+ new Headers(typeof options.headers === "function" ? options.headers() : options.headers);
141
+ const credentials = options.credentials ?? "same-origin";
142
+ const here = () => (typeof location === "undefined" ? "http://localhost/" : location.href);
143
+ const url = (path: string) => new URL(`${base}${path}`, here()).href;
144
+
145
+ let meta: ContentClientMeta | null = options.meta ?? null;
146
+ const listeners = new Set<() => void>();
147
+ const links = new Map<string, string | null>();
148
+ const keyOf = (instance: InstanceRef) => JSON.stringify(instance);
149
+
150
+ const set = (next: ContentClientMeta | null) => {
151
+ if (JSON.stringify(next) !== JSON.stringify(meta)) {
152
+ meta = next;
153
+ for (const listener of listeners) {
154
+ listener();
155
+ }
156
+ }
157
+ };
158
+ let refreshing: Promise<ContentClientMeta | null> | null = null;
159
+ const refresh = (): Promise<ContentClientMeta | null> => {
160
+ refreshing ??= (async () => {
161
+ try {
162
+ const answer = await ask(url("/meta"), {
163
+ headers: headersNow(),
164
+ credentials,
165
+ cache: "no-store",
166
+ });
167
+ const data: unknown = answer.ok ? await answer.json() : null;
168
+ if (isRecord(data) && typeof data.served === "boolean") {
169
+ set(data as unknown as ContentClientMeta);
170
+ }
171
+ } catch {
172
+ // Keep what is known; the next refresh tries again.
173
+ } finally {
174
+ refreshing = null;
175
+ }
176
+ return meta;
177
+ })();
178
+ return refreshing;
179
+ };
180
+ if (meta === null) {
181
+ void refresh();
182
+ }
183
+
184
+ const configOf = (kind: N | null): PortholeConfig | null => {
185
+ if (meta === null || kind === null) {
186
+ return null;
187
+ }
188
+ if (meta.served && meta.contentSource !== null) {
189
+ const served = options.displays.served(meta.contentSource);
190
+ if (served !== null) {
191
+ return served[kind];
192
+ }
193
+ }
194
+ try {
195
+ return options.displays.opaque(kind);
196
+ } catch {
197
+ // A url kind has no opaque config: not shown while frames aren't served.
198
+ return null;
199
+ }
200
+ };
201
+
202
+ const issue = async (instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation> => {
203
+ const headers = headersNow();
204
+ headers.set("content-type", "application/json");
205
+ headers.set("accept", "application/json");
206
+ const answer = await ask(url("/frames"), {
207
+ method: "POST",
208
+ headers,
209
+ credentials,
210
+ redirect: "error",
211
+ body: JSON.stringify({ instance }),
212
+ ...(signal === undefined ? {} : { signal }),
213
+ });
214
+ const data: unknown = await answer.json().catch(() => null);
215
+ if (!answer.ok) {
216
+ const error = isRecord(data) && isRecord(data.error) ? data.error : {};
217
+ const code = typeof error.code === "string" ? error.code : "failed";
218
+ if (code === "not-served") {
219
+ void refresh();
220
+ }
221
+ throw new LocateError(
222
+ typeof error.message === "string"
223
+ ? error.message
224
+ : `The app's frame endpoint answered ${answer.status}`,
225
+ answer.status,
226
+ code,
227
+ );
228
+ }
229
+ if (!isRecord(data) || typeof data.url !== "string" || typeof data.origin !== "string") {
230
+ throw new LocateError(
231
+ "The app's frame endpoint gave no location",
232
+ answer.status,
233
+ "bad-location",
234
+ );
235
+ }
236
+ links.set(keyOf(instance), typeof data.link === "string" ? data.link : null);
237
+ return {
238
+ url: data.url,
239
+ origin: data.origin,
240
+ ...(typeof data.reports === "boolean" ? { reports: data.reports } : {}),
241
+ };
242
+ };
243
+
244
+ let lastHandoff = 0;
245
+ const handoff = async (): Promise<boolean> => {
246
+ lastHandoff = Date.now();
247
+ try {
248
+ const answer = await ask(url("/handoff"), {
249
+ method: "POST",
250
+ headers: headersNow(),
251
+ credentials,
252
+ cache: "no-store",
253
+ });
254
+ return answer.ok;
255
+ } catch {
256
+ return false;
257
+ }
258
+ };
259
+ // Kept fresh while the page is used: on load, focus and visibility, at most every 30 s.
260
+ const fresh = () => {
261
+ if (
262
+ Date.now() - lastHandoff > 30_000 &&
263
+ (typeof document === "undefined" || document.visibilityState !== "hidden")
264
+ ) {
265
+ void handoff();
266
+ }
267
+ };
268
+ const watching = options.handoff === true && typeof window !== "undefined";
269
+ if (watching) {
270
+ void handoff();
271
+ window.addEventListener("focus", fresh);
272
+ document.addEventListener("visibilitychange", fresh);
273
+ }
274
+
275
+ const link = async (instance: InstanceRef): Promise<string | null> => {
276
+ const key = keyOf(instance);
277
+ if (!links.has(key)) {
278
+ try {
279
+ await issue(instance);
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ return links.get(key) ?? null;
285
+ };
286
+
287
+ return {
288
+ displays: options.displays,
289
+ meta: () => meta,
290
+ subscribe: (listener) => {
291
+ listeners.add(listener);
292
+ return () => {
293
+ listeners.delete(listener);
294
+ };
295
+ },
296
+ refresh,
297
+ config: (kind) => configOf(kind),
298
+ configFor: (instance) => configOf(options.displays.kindOf(instance)),
299
+ locate: issue,
300
+ link,
301
+ knownLink: (instance) => links.get(keyOf(instance)) ?? null,
302
+ openInTab: (instance) => {
303
+ // Opened inside the click (a popup blocker lets it), then sent to the address.
304
+ const tab = typeof window === "undefined" ? null : window.open("about:blank", "_blank");
305
+ if (tab === null) {
306
+ return;
307
+ }
308
+ tab.opener = null;
309
+ void (async () => {
310
+ const found = await link(instance);
311
+ if (found === null) {
312
+ tab.close();
313
+ } else {
314
+ tab.location.href = found;
315
+ }
316
+ })();
317
+ },
318
+ handoff,
319
+ entryTarget: (next, given) => entryTarget(next, url("/authorize"), given),
320
+ close: () => {
321
+ if (watching) {
322
+ window.removeEventListener("focus", fresh);
323
+ document.removeEventListener("visibilitychange", fresh);
324
+ }
325
+ },
326
+ };
327
+ }
328
+
329
+ /** What a frame that showed nothing should offer the person, by its outcome (P072). */
330
+ export interface FrameFallback {
331
+ /** `needs-tab`: open it in a new tab (the browser keeps no cookie in a frame, sign-in, framing). */
332
+ readonly kind: "needs-tab" | "denied" | "expired" | "failed" | "timeout";
333
+ readonly title: string;
334
+ readonly message: string;
335
+ }
336
+
337
+ /**
338
+ * The fallback for a frame's outcome, worded as Porthole's own pages word it; null when it loaded.
339
+ * `url`: a url-mode app, where a timeout means it couldn't run in a frame.
340
+ */
341
+ export function frameFallback(
342
+ outcome: FrameOutcome,
343
+ options: { readonly url?: boolean } = {},
344
+ ): FrameFallback | null {
345
+ if (outcome.state === "loaded") {
346
+ return null;
347
+ }
348
+ if (outcome.state === "timeout") {
349
+ return options.url === true
350
+ ? {
351
+ kind: "needs-tab",
352
+ title: "Open this in a new tab",
353
+ message: "It didn't load inside the page.",
354
+ }
355
+ : { kind: "timeout", title: "This is taking too long", message: "It didn't finish loading." };
356
+ }
357
+ switch (outcome.reason) {
358
+ case "cookies":
359
+ return {
360
+ kind: "needs-tab",
361
+ title: "Open this in a new tab",
362
+ message: "This browser keeps no sign-in for it inside a frame.",
363
+ };
364
+ case "sign-in":
365
+ return {
366
+ kind: "needs-tab",
367
+ title: "Open this in a new tab to sign in",
368
+ message: "Signing in doesn't work inside a frame.",
369
+ };
370
+ case "framing":
371
+ return {
372
+ kind: "needs-tab",
373
+ title: "Open this in a new tab",
374
+ message: "It can't be shown inside this page.",
375
+ };
376
+ case "denied":
377
+ return {
378
+ kind: "denied",
379
+ title: "You can't open this anymore",
380
+ message: "You no longer have access to it.",
381
+ };
382
+ case "session":
383
+ return { kind: "expired", title: "This has expired", message: "Open it again." };
384
+ case "not-found":
385
+ return { kind: "failed", title: "Not found", message: "There is nothing here." };
386
+ case "upstream":
387
+ return {
388
+ kind: "failed",
389
+ title: "The app didn't answer",
390
+ message: "Its server couldn't be reached.",
391
+ };
392
+ default:
393
+ return { kind: "failed", title: "This couldn't be shown", message: "Something went wrong." };
394
+ }
395
+ }
package/src/index.ts CHANGED
@@ -130,6 +130,31 @@ export type {
130
130
  Refusal,
131
131
  } from "./bridge/types.ts";
132
132
  export { createHost } from "./host/create-host.ts";
133
+ // The client half of the host kit, and the display registry (P072).
134
+ export {
135
+ entryTarget,
136
+ frameFallback,
137
+ portholeClient,
138
+ type ContentClientMeta,
139
+ type FrameFallback,
140
+ type PortholeClient,
141
+ type PortholeClientOptions,
142
+ } from "./host/client.ts";
143
+ export { defineDisplays, type DisplayKind, type Displays } from "./displays/displays.ts";
144
+ // The agent's side: what content can be told without running it, and its tools (P073).
145
+ export { fragmentOf, lintContent, type Finding, type LintRule } from "./check/lint.ts";
146
+ export {
147
+ admitContent,
148
+ answerGuide,
149
+ checkTool,
150
+ guideChanges,
151
+ guideTool,
152
+ guideTopics,
153
+ showTool,
154
+ type AdmitResult,
155
+ type JsonSchema,
156
+ type ToolDefinition,
157
+ } from "./check/tools.ts";
133
158
  export { writeClipboard } from "./host/clipboard.ts";
134
159
  export {
135
160
  httpLocator,
package/src/node/index.ts CHANGED
@@ -9,13 +9,14 @@
9
9
  * server.on("upgrade", porthole.upgrade);
10
10
  * server.listen(8080, () => content.start());
11
11
  */
12
- import type { IncomingMessage, ServerResponse } from "node:http";
13
- import { request as httpRequest } from "node:http";
12
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
13
+ import { createServer as createHttpServer, request as httpRequest } from "node:http";
14
14
  import { request as httpsRequest } from "node:https";
15
15
  import type { LookupFunction } from "node:net";
16
16
  import type { Duplex } from "node:stream";
17
17
  import { Readable } from "node:stream";
18
18
  import type { ContentHost, HealthProbe } from "../server/host.ts";
19
+ import { withoutPortholeCookies } from "../server/proxy.ts";
19
20
  import type { Access } from "../server/types.ts";
20
21
 
21
22
  type RequestListener = (request: IncomingMessage, response: ServerResponse) => void;
@@ -219,6 +220,13 @@ export function nodeHost<V>(content: ContentHost<V>, app: NodeHostOptions): Node
219
220
  if (access === null) {
220
221
  refuseSocket(socket);
221
222
  } else {
223
+ // The app's socket never sees Porthole's own cookies, as its HTTP requests don't (P072).
224
+ const cookie = withoutPortholeCookies(request.headers.cookie);
225
+ if (cookie === null) {
226
+ delete request.headers.cookie;
227
+ } else {
228
+ request.headers.cookie = cookie;
229
+ }
222
230
  appSocket(access, request, socket, head);
223
231
  }
224
232
  },
@@ -282,3 +290,105 @@ export function nodeProbe(): HealthProbe {
282
290
  asked.end();
283
291
  });
284
292
  }
293
+
294
+ export interface NodeServerOptions {
295
+ /**
296
+ * The content host, or a function giving it when it exists: a host made after the server listens
297
+ * (its content domain names the port `listen(0)` chose, P074). Until it gives one, every request
298
+ * is the app's; the health gate starts when it first does.
299
+ */
300
+ readonly content: ContentHost<unknown> | (() => ContentHost<unknown> | null);
301
+ /**
302
+ * The app, fetch-style (Hono's `app.fetch`, or the app's own handler): every request that
303
+ * isn't the content domain's. Or `request`, a Node listener (Express).
304
+ */
305
+ readonly app?: (request: Request) => Response | Promise<Response>;
306
+ readonly request?: RequestListener;
307
+ readonly upgrade?: UpgradeListener;
308
+ readonly appSocket?: NodeHostOptions["appSocket"];
309
+ /** Whether the app's own requests came over https (behind a TLS edge): their URL's scheme. */
310
+ readonly scheme?: "https" | "http";
311
+ }
312
+
313
+ /**
314
+ * The whole Node server (P072): the content domain to Porthole, everything else to the app, its
315
+ * WebSockets included; the health gate started when it listens and stopped when it closes.
316
+ *
317
+ * nodeServer({ content, app: (request) => app.fetch(request) }).listen(8790);
318
+ */
319
+ export function nodeServer(options: NodeServerOptions): Server {
320
+ const scheme = options.scheme ?? "http";
321
+ const fromFetch = options.app;
322
+ const request: RequestListener | undefined =
323
+ options.request ??
324
+ (fromFetch === undefined
325
+ ? undefined
326
+ : (incoming, response) => {
327
+ Promise.resolve(fromFetch(toRequest(incoming, scheme))).then(
328
+ (answer) => sendResponse(response, answer),
329
+ () => {
330
+ if (response.headersSent) {
331
+ response.destroy();
332
+ return;
333
+ }
334
+ response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
335
+ response.end("Something went wrong.");
336
+ },
337
+ );
338
+ });
339
+ if (request === undefined) {
340
+ throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
341
+ }
342
+ const adapters = new WeakMap<ContentHost<unknown>, NodeHost>();
343
+ const started = new WeakSet<ContentHost<unknown>>();
344
+ let listening = false;
345
+ const given = options.content;
346
+ /** The host now (made once, adapted once), started once the server listens. */
347
+ const current = (): NodeHost | null => {
348
+ const host = typeof given === "function" ? given() : given;
349
+ if (host === null) {
350
+ return null;
351
+ }
352
+ let adapter = adapters.get(host);
353
+ if (adapter === undefined) {
354
+ adapter = nodeHost(host, {
355
+ request,
356
+ ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
357
+ ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
358
+ });
359
+ adapters.set(host, adapter);
360
+ }
361
+ if (listening && !started.has(host)) {
362
+ started.add(host);
363
+ host.start();
364
+ }
365
+ return adapter;
366
+ };
367
+ const server = createHttpServer((incoming, response) => {
368
+ const adapter = current();
369
+ if (adapter === null) {
370
+ request(incoming, response);
371
+ } else {
372
+ adapter.request(incoming, response);
373
+ }
374
+ });
375
+ server.on("upgrade", (incoming: IncomingMessage, socket: Duplex, head: Buffer) => {
376
+ const adapter = current();
377
+ if (adapter !== null) {
378
+ adapter.upgrade(incoming, socket, head);
379
+ } else if (options.upgrade !== undefined) {
380
+ options.upgrade(incoming, socket, head);
381
+ } else {
382
+ refuseSocket(socket);
383
+ }
384
+ });
385
+ server.on("listening", () => {
386
+ listening = true;
387
+ current();
388
+ });
389
+ server.on("close", () => {
390
+ const host = typeof given === "function" ? given() : given;
391
+ host?.close();
392
+ });
393
+ return server;
394
+ }