@botiverse/porthole 0.3.0 → 0.3.2

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 (56) hide show
  1. package/README.md +3 -2
  2. package/dist/check/check.d.ts +20 -3
  3. package/dist/check/check.js +88 -25
  4. package/dist/check/drivers.d.ts +25 -6
  5. package/dist/check/drivers.js +99 -28
  6. package/dist/check/index.d.ts +2 -2
  7. package/dist/check/index.js +1 -1
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.d.ts +2 -40
  12. package/dist/check/page.js +63 -43
  13. package/dist/conformance/harness-source.d.ts +2 -0
  14. package/dist/conformance/harness-source.js +2 -0
  15. package/dist/conformance/host-kit.d.ts +20 -7
  16. package/dist/conformance/host-kit.js +42 -48
  17. package/dist/conformance/index.d.ts +1 -1
  18. package/dist/conformance/reporter.d.ts +14 -0
  19. package/dist/conformance/reporter.js +28 -0
  20. package/dist/host/client.d.ts +33 -15
  21. package/dist/host/client.js +39 -24
  22. package/dist/node/index.d.ts +6 -2
  23. package/dist/node/index.js +53 -8
  24. package/dist/react/frame.d.ts +13 -5
  25. package/dist/react/frame.js +67 -27
  26. package/dist/react/index.d.ts +1 -1
  27. package/dist/react/view.js +6 -1
  28. package/dist/server/host.d.ts +5 -3
  29. package/dist/server/host.js +41 -12
  30. package/docs/ADOPTING.md +115 -26
  31. package/docs/DECISIONS.md +167 -0
  32. package/docs/DESIGN.md +38 -13
  33. package/examples/app.mjs +23 -17
  34. package/examples/conformance/playwright.config.mjs +2 -1
  35. package/examples/conformance/porthole.spec.mjs +2 -1
  36. package/examples/displays.mjs +2 -0
  37. package/examples/node/server.mjs +16 -34
  38. package/examples/workers/worker.mjs +19 -7
  39. package/package.json +9 -3
  40. package/src/check/check.ts +122 -25
  41. package/src/check/drivers.ts +137 -39
  42. package/src/check/index.ts +8 -1
  43. package/src/check/instrument.ts +138 -0
  44. package/src/check/page-source.ts +4 -3
  45. package/src/check/page.ts +94 -68
  46. package/src/conformance/harness-source.ts +23 -0
  47. package/src/conformance/host-kit.ts +69 -46
  48. package/src/conformance/index.ts +1 -0
  49. package/src/conformance/reporter.ts +38 -0
  50. package/src/host/client.ts +65 -34
  51. package/src/node/index.ts +56 -10
  52. package/src/react/frame.tsx +89 -33
  53. package/src/react/index.ts +1 -0
  54. package/src/react/view.tsx +6 -1
  55. package/src/server/host.ts +53 -15
  56. package/dist/conformance/harness.js +0 -1662
@@ -1,4 +1,3 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { fileURLToPath } from "node:url";
3
2
  import { runInThisContext } from "node:vm";
4
3
  import { expect, type Frame, type Page, type TestInfo, type TestType } from "@playwright/test";
@@ -6,6 +5,7 @@ import type { PortholeConfig } from "../config/schema.ts";
6
5
  import type { Displays } from "../displays/displays.ts";
7
6
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
8
7
  import { entryTests, type EntryConformanceHost } from "./entry.ts";
8
+ import HARNESS from "./harness-source.ts";
9
9
  export { conformancePage } from "./page.ts";
10
10
  import type { ConformanceHarness } from "./harness/page.ts";
11
11
  import type { FrameOutcome } from "../host/types.ts";
@@ -51,8 +51,12 @@ export interface HostConformanceOptions {
51
51
  readonly config?: (instance: InstanceRef) => PortholeConfig;
52
52
  /** The app's display kinds (`defineDisplays`), in place of `config`. */
53
53
  readonly displays?: Displays;
54
- /** The content source `displays` serve from (`http://*.content.localhost:8790`). */
55
- readonly contentSource?: string;
54
+ /**
55
+ * The content source `displays` serve from (`http://*.content.localhost:8790`). A function is
56
+ * asked when a case needs it (P074): a test server's port that isn't known when the spec file
57
+ * loads.
58
+ */
59
+ readonly contentSource?: string | (() => string);
56
60
  /**
57
61
  * The instances the served cases ask for, each for the scope a case names (may be async: a
58
62
  * page published on demand, `onDemand`). Give what the app serves; the cases for the rest are
@@ -99,35 +103,12 @@ const FOREIGN = "http://porthole-foreign.example";
99
103
  /** Where the harness loads from, on the app's own origin (routed by the test, never the app's). */
100
104
  const HARNESS_PATH = "/__porthole/conformance/harness.js";
101
105
 
102
- let built: Promise<string> | null = null;
103
-
104
106
  /**
105
- * The harness as one script: from the package (`dist/conformance/harness.js`), or, run from the
106
- * sources, bundled now (esbuild, a development dependency of Porthole's).
107
+ * The harness as one script, imported with this module (`harness-source`), so a bundle has it too
108
+ * (P075).
107
109
  */
108
110
  export function harnessScript(): Promise<string> {
109
- built ??= (async () => {
110
- try {
111
- return await readFile(new URL("./harness.js", import.meta.url), "utf8");
112
- } catch {
113
- const { build } = await import("esbuild");
114
- const result = await build({
115
- entryPoints: [fileURLToPath(new URL("./harness/page.ts", import.meta.url))],
116
- bundle: true,
117
- format: "iife",
118
- platform: "browser",
119
- target: "es2022",
120
- write: false,
121
- logLevel: "silent",
122
- });
123
- const text = result.outputFiles[0]?.text;
124
- if (text === undefined) {
125
- throw new Error("the conformance harness didn't build");
126
- }
127
- return text;
128
- }
129
- })();
130
- return built;
111
+ return Promise.resolve(HARNESS);
131
112
  }
132
113
 
133
114
  type Harness = Record<string, ((...args: unknown[]) => unknown) | undefined>;
@@ -182,7 +163,11 @@ export function hostConformance(options: HostConformanceOptions): HostConformanc
182
163
  const configOf =
183
164
  options.config ??
184
165
  (displays !== undefined && contentSource !== undefined
185
- ? (instance: InstanceRef) => displays.configFor(instance, contentSource)
166
+ ? (instance: InstanceRef) =>
167
+ displays.configFor(
168
+ instance,
169
+ typeof contentSource === "function" ? contentSource() : contentSource,
170
+ )
186
171
  : () => {
187
172
  throw new TypeError("hostConformance needs config, or displays with contentSource");
188
173
  });
@@ -501,28 +486,66 @@ export interface ConformanceProject {
501
486
  * preferences its WebRTC probe needs (loopback ICE). Pass `devices` from `@playwright/test`
502
487
  * (P071).
503
488
  */
489
+ export interface ConformanceProjectsOptions {
490
+ readonly engines?: readonly ConformanceProject["name"][];
491
+ /** Added to every project's `use` (a trace setting, `ignoreHTTPSErrors`, a `baseURL`). */
492
+ readonly use?: Readonly<Record<string, unknown>>;
493
+ /**
494
+ * Each engine's launch options, merged with Porthole's own (P074): a system browser's
495
+ * `executablePath` and `args` (`{ chromium: { executablePath: "/usr/bin/chromium" } }`, on a box
496
+ * Playwright has no Chromium build for). Firefox's preferences add to the ones its probes need.
497
+ */
498
+ readonly launchOptions?: Partial<
499
+ Readonly<Record<ConformanceProject["name"], Readonly<Record<string, unknown>>>>
500
+ >;
501
+ }
502
+
503
+ const recordOf = (value: unknown): Record<string, unknown> =>
504
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {};
505
+
504
506
  export function conformanceProjects(
505
507
  devices: Readonly<Record<string, Record<string, unknown>>>,
506
- options: { readonly engines?: readonly ("chromium" | "webkit" | "firefox")[] } = {},
508
+ options: ConformanceProjectsOptions = {},
507
509
  ): ConformanceProject[] {
508
- const all: ConformanceProject[] = [
509
- { name: "chromium", use: { ...devices["Desktop Chrome"] } },
510
- { name: "webkit", use: { ...devices["Desktop Safari"] } },
511
- {
512
- name: "firefox",
513
- use: {
514
- ...devices["Desktop Firefox"],
515
- launchOptions: {
516
- firefoxUserPrefs: {
517
- "media.peerconnection.ice.loopback": true,
518
- "media.peerconnection.ice.obfuscate_host_addresses": false,
519
- },
520
- },
510
+ const DEVICE = {
511
+ chromium: "Desktop Chrome",
512
+ webkit: "Desktop Safari",
513
+ firefox: "Desktop Firefox",
514
+ } as const;
515
+ /** Porthole's own launch options: Firefox's WebRTC probe needs loopback ICE. */
516
+ const OWN: Readonly<Record<ConformanceProject["name"], Record<string, unknown>>> = {
517
+ chromium: {},
518
+ webkit: {},
519
+ firefox: {
520
+ firefoxUserPrefs: {
521
+ "media.peerconnection.ice.loopback": true,
522
+ "media.peerconnection.ice.obfuscate_host_addresses": false,
521
523
  },
522
524
  },
523
- ];
525
+ };
524
526
  const engines = options.engines ?? ["chromium", "webkit", "firefox"];
525
- return all.filter((project) => engines.includes(project.name));
527
+ return (["chromium", "webkit", "firefox"] as const)
528
+ .filter((name) => engines.includes(name))
529
+ .map((name) => {
530
+ const given = { ...recordOf(options.use?.launchOptions), ...options.launchOptions?.[name] };
531
+ const prefs = {
532
+ ...recordOf(OWN[name].firefoxUserPrefs),
533
+ ...recordOf(given.firefoxUserPrefs),
534
+ };
535
+ const launchOptions = {
536
+ ...OWN[name],
537
+ ...given,
538
+ ...(Object.keys(prefs).length === 0 ? {} : { firefoxUserPrefs: prefs }),
539
+ };
540
+ return {
541
+ name,
542
+ use: {
543
+ ...devices[DEVICE[name]],
544
+ ...options.use,
545
+ ...(Object.keys(launchOptions).length === 0 ? {} : { launchOptions }),
546
+ },
547
+ };
548
+ });
526
549
  }
527
550
 
528
551
  /**
@@ -129,6 +129,7 @@ export {
129
129
  hostConformance,
130
130
  onDemand,
131
131
  type ConformanceProject,
132
+ type ConformanceProjectsOptions,
132
133
  type HostConformance,
133
134
  type HostConformanceOptions,
134
135
  } from "./host-kit.ts";
@@ -0,0 +1,38 @@
1
+ import type { FullResult, Reporter, TestCase, TestResult } from "@playwright/test/reporter";
2
+
3
+ /**
4
+ * A Playwright reporter that says why each conformance case was skipped (P074): the list and line
5
+ * reporters show a skipped case as "-" with no reason, and an inapplicable probe ("the page's own
6
+ * CSP, which an opaque frame inherits, blocks … (connect-src)") is a fact worth reading.
7
+ *
8
+ * reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
9
+ */
10
+ export default class SkipReasons implements Reporter {
11
+ readonly #skipped = new Map<string, string>();
12
+
13
+ printsToStdio(): boolean {
14
+ return true;
15
+ }
16
+
17
+ onTestEnd(test: TestCase, result: TestResult): void {
18
+ if (result.status !== "skipped") {
19
+ return;
20
+ }
21
+ const reason =
22
+ [...result.annotations, ...test.annotations].find(
23
+ (each) => each.type === "skip" && each.description !== undefined && each.description !== "",
24
+ )?.description ?? "skipped";
25
+ const title = test.title.length > 90 ? `${test.title.slice(0, 89)}…` : test.title;
26
+ this.#skipped.set(`${title}\u0000${reason}`, `${title}: ${reason}`);
27
+ }
28
+
29
+ onEnd(_result: FullResult): void {
30
+ if (this.#skipped.size === 0) {
31
+ return;
32
+ }
33
+ const lines = [...this.#skipped.values()].toSorted();
34
+ process.stdout.write(
35
+ `\nSkipped (${lines.length}), and why:\n${lines.map((each) => ` - ${each}`).join("\n")}\n`,
36
+ );
37
+ }
38
+ }
@@ -44,36 +44,45 @@ export interface PortholeClientOptions<N extends string> {
44
44
  readonly fetch?: typeof fetch;
45
45
  }
46
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
+ */
47
51
  export interface PortholeClient<N extends string = string> extends InstanceLocator {
48
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>;
49
55
  /** The meta as last fetched, or null before it is known. */
50
- meta(): ContentClientMeta | null;
56
+ meta(this: void): ContentClientMeta | null;
51
57
  /** Called when the meta changes (frames served or not). */
52
- subscribe(listener: () => void): () => void;
58
+ subscribe(this: void, listener: () => void): () => void;
53
59
  /** Fetches the meta again. */
54
- refresh(): Promise<ContentClientMeta | null>;
60
+ refresh(this: void): Promise<ContentClientMeta | null>;
55
61
  /**
56
62
  * The config a kind shows under now: served while frames are served, else opaque (a url kind:
57
63
  * null). Null until the meta is known, so a frame never starts opaque and then restarts served.
58
64
  */
59
- config(kind: N): PortholeConfig | null;
65
+ config(this: void, kind: N): PortholeConfig | null;
60
66
  /** The same, for an instance's kind. */
61
- configFor(instance: InstanceRef): PortholeConfig | null;
67
+ configFor(this: void, instance: InstanceRef): PortholeConfig | null;
62
68
  /** An instance's clean address (`entry.pathOf` on the server), or null. */
63
- link(instance: InstanceRef): Promise<string | null>;
69
+ link(this: void, instance: InstanceRef): Promise<string | null>;
64
70
  /** The clean address if already known (from locating the instance), for rendering. */
65
- knownLink(instance: InstanceRef): string | null;
71
+ knownLink(this: void, instance: InstanceRef): string | null;
66
72
  /**
67
73
  * Opens an instance's clean address in a new tab: call it in the click (the tab opens at once,
68
74
  * then goes to the address).
69
75
  */
70
- openInTab(instance: InstanceRef): void;
76
+ openInTab(this: void, instance: InstanceRef): void;
71
77
  /** Hands the signed-in viewer to the authorize route (`entry.handoff`); true if it took. */
72
- handoff(): Promise<boolean>;
73
- /** `next` if it is this server's authorize route (after a sign-in), else null (`entryTarget`). */
74
- entryTarget(next: unknown): string | null;
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;
75
84
  /** Stops refreshing the handoff. */
76
- close(): void;
85
+ close(this: void): void;
77
86
  }
78
87
 
79
88
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -81,9 +90,18 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
81
90
 
82
91
  /**
83
92
  * Whether a sign-in's `next` is the app's authorize route (P072): the open-redirect guard a
84
- * single-page app runs before going on to it. Null for anything else.
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.
85
99
  */
86
- export function entryTarget(next: unknown, authorizeUrl: string): string | null {
100
+ export function entryTarget(
101
+ next: unknown,
102
+ authorizeUrl: string,
103
+ options: { readonly app?: boolean } = {},
104
+ ): string | null {
87
105
  if (typeof next !== "string" || next.length > 8_192) {
88
106
  return null;
89
107
  }
@@ -95,10 +113,19 @@ export function entryTarget(next: unknown, authorizeUrl: string): string | null
95
113
  } catch {
96
114
  return null;
97
115
  }
98
- return target.origin === route.origin &&
116
+ if (
117
+ target.origin === route.origin &&
99
118
  target.pathname === route.pathname &&
100
119
  target.hash === "" &&
101
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
102
129
  ? target.href
103
130
  : null;
104
131
  }
@@ -245,30 +272,34 @@ export function portholeClient<N extends string>(
245
272
  document.addEventListener("visibilitychange", fresh);
246
273
  }
247
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
+
248
287
  return {
249
288
  displays: options.displays,
250
289
  meta: () => meta,
251
- subscribe(listener) {
290
+ subscribe: (listener) => {
252
291
  listeners.add(listener);
253
- return () => listeners.delete(listener);
292
+ return () => {
293
+ listeners.delete(listener);
294
+ };
254
295
  },
255
296
  refresh,
256
297
  config: (kind) => configOf(kind),
257
298
  configFor: (instance) => configOf(options.displays.kindOf(instance)),
258
299
  locate: issue,
259
- async link(instance) {
260
- const key = keyOf(instance);
261
- if (!links.has(key)) {
262
- try {
263
- await issue(instance);
264
- } catch {
265
- return null;
266
- }
267
- }
268
- return links.get(key) ?? null;
269
- },
300
+ link,
270
301
  knownLink: (instance) => links.get(keyOf(instance)) ?? null,
271
- openInTab(instance) {
302
+ openInTab: (instance) => {
272
303
  // Opened inside the click (a popup blocker lets it), then sent to the address.
273
304
  const tab = typeof window === "undefined" ? null : window.open("about:blank", "_blank");
274
305
  if (tab === null) {
@@ -276,17 +307,17 @@ export function portholeClient<N extends string>(
276
307
  }
277
308
  tab.opener = null;
278
309
  void (async () => {
279
- const link = await this.link(instance);
280
- if (link === null) {
310
+ const found = await link(instance);
311
+ if (found === null) {
281
312
  tab.close();
282
313
  } else {
283
- tab.location.href = link;
314
+ tab.location.href = found;
284
315
  }
285
316
  })();
286
317
  },
287
318
  handoff,
288
- entryTarget: (next) => entryTarget(next, url("/authorize")),
289
- close() {
319
+ entryTarget: (next, given) => entryTarget(next, url("/authorize"), given),
320
+ close: () => {
290
321
  if (watching) {
291
322
  window.removeEventListener("focus", fresh);
292
323
  document.removeEventListener("visibilitychange", fresh);
package/src/node/index.ts CHANGED
@@ -292,8 +292,12 @@ export function nodeProbe(): HealthProbe {
292
292
  }
293
293
 
294
294
  export interface NodeServerOptions {
295
- /** The content host. */
296
- readonly content: ContentHost<unknown>;
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);
297
301
  /**
298
302
  * The app, fetch-style (Hono's `app.fetch`, or the app's own handler): every request that
299
303
  * isn't the content domain's. Or `request`, a Node listener (Express).
@@ -335,14 +339,56 @@ export function nodeServer(options: NodeServerOptions): Server {
335
339
  if (request === undefined) {
336
340
  throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
337
341
  }
338
- const porthole = nodeHost(options.content, {
339
- request,
340
- ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
341
- ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
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();
342
392
  });
343
- const server = createHttpServer(porthole.request);
344
- server.on("upgrade", porthole.upgrade);
345
- server.on("listening", () => options.content.start());
346
- server.on("close", () => options.content.close());
347
393
  return server;
348
394
  }