@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
package/README.md CHANGED
@@ -9,7 +9,7 @@ npm install @botiverse/porthole
9
9
  ```
10
10
 
11
11
  Node 24 or later, or Cloudflare Workers. The browser part is plain ES modules with no
12
- dependencies (bundle it, or serve `dist/`).
12
+ dependencies (bundle it, or serve `dist/` with an import map: docs/ADOPTING.md § 4).
13
13
 
14
14
  ## Two ways to show content
15
15
 
@@ -30,8 +30,10 @@ PORTHOLE_SECRET=$(npx porthole secret) node node_modules/@botiverse/porthole/exa
30
30
  ```
31
31
 
32
32
  - `examples/app.mjs`: the app (policy, routes, page), runtime-agnostic.
33
- - `examples/node/server.mjs`, `examples/workers/` (with its D1 migration and `wrangler.jsonc`).
33
+ - `examples/node/server.mjs` (`nodeServer`), `examples/workers/` (`contentHostFor`, with its D1
34
+ migration and `wrangler.jsonc`).
34
35
  - `examples/conformance/`: Porthole's conformance suite run against it, on three engines.
36
+ - `examples/mcp/server.mjs`: the agent's tools (show, guide, check) as an MCP server.
35
37
 
36
38
  ## The smallest opaque display
37
39
 
@@ -50,16 +52,19 @@ display.setContent("<p>Hello from an agent</p>");
50
52
  In React: `<PortholeProvider>` around `<PortholeFrame config displayId title scheme content />` from
51
53
  `@botiverse/porthole/react`.
52
54
 
53
- ## What the agent reads
55
+ ## What the agent gets
54
56
 
55
57
  ```js
56
- import { compile } from "@botiverse/porthole";
58
+ import { admitContent, checkTool, guideTool, showTool } from "@botiverse/porthole";
57
59
 
58
- const compiled = compile(config);
59
- compiled.toolDescription(); // the show tool's description: what it may write, and where it runs
60
- compiled.guide(); // the manual: the sandbox's limits, sizes, colors, examples
60
+ const tools = [showTool(config), guideTool(config), checkTool(config)]; // name, description, JSON Schema
61
+ const admitted = admitContent(config, html); // refuses only what certainly fails, saying what to change
61
62
  ```
62
63
 
64
+ `checkPage` (`@botiverse/porthole/check`) runs a page in the real sandbox at phone and desktop
65
+ width, light and dark, before anyone sees it, and tells the agent what broke in a few lines.
66
+ `examples/mcp/server.mjs` wires the tools as an MCP server.
67
+
63
68
  ## Read next
64
69
 
65
70
  - [docs/ADOPTING.md](docs/ADOPTING.md): getting started, step by step: the server, the page, its
@@ -71,11 +76,12 @@ compiled.guide(); // the manual: the sandbox's limits, sizes, colors,
71
76
 
72
77
  | Import | What |
73
78
  | --- | --- |
74
- | `@botiverse/porthole` | `createHost`, `presets`, `compile`, `httpLocator`, `servedOrOpaque` (browser and server) |
75
- | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame` |
76
- | `@botiverse/porthole/server` | `createContentHost`, `prefixedName`, `d1TicketStore` (any runtime) |
77
- | `@botiverse/porthole/node` | `nodeHost`, `nodeProbe` (Node's http server) |
79
+ | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `lintContent`, the tools (browser and server) |
80
+ | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView` |
81
+ | `@botiverse/porthole/server` | `createContentHost` (`routes`), `contentHostFor`, `prefixedName`, `d1TicketStore` (any runtime) |
82
+ | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe` (Node's http server) |
78
83
  | `@botiverse/porthole/mcp` | the MCP Apps adapter |
84
+ | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver`: the agent's pre-show check |
79
85
  | `@botiverse/porthole/conformance` | `defineHostConformance`: the suite, against your app (Playwright) |
80
86
 
81
87
  `npx porthole secret` makes a secret; `npx porthole d1-schema` prints the D1 migration.
@@ -0,0 +1,100 @@
1
+ import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
+ import { type Finding } from "./lint.ts";
3
+ import { type CheckCall } from "./instrument.ts";
4
+ export type { CheckCall } from "./instrument.ts";
5
+ /**
6
+ * Checks content before people see it (P073): runs it in the real sandbox at each width and
7
+ * scheme, through a driver (a browser the host has: Playwright, or any CDP session, Cloudflare
8
+ * Browser Rendering's included), and says what went wrong, briefly, for the agent.
9
+ *
10
+ * const report = await checkPage({ config, content: html, driver: playwrightDriver(browser) });
11
+ * report.ok; report.text; // "At 320 px, dark: TypeError: … (line 12). …"
12
+ */
13
+ /** A page the check drives: one at a time, sequentially. */
14
+ export interface CheckSession {
15
+ setViewport(width: number, height: number): Promise<void>;
16
+ /** Loads a whole HTML document into the page. */
17
+ load(html: string): Promise<void>;
18
+ /**
19
+ * Answers every request to the check page's origin and the check's content domain with
20
+ * `handler`, and opens the page (`/`): a served config's content then runs on an origin of its
21
+ * own, as people's browsers run it (P074). Without it, the check runs content opaque.
22
+ */
23
+ serve?(handler: (request: Request) => Promise<Response>): Promise<void>;
24
+ /** Evaluates a JavaScript expression in the page (a promise is awaited); JSON back. */
25
+ evaluate<T>(expression: string): Promise<T>;
26
+ /** A PNG of the element `selector` names, where the driver can. */
27
+ screenshot?(selector: string): Promise<Uint8Array>;
28
+ close(): Promise<void>;
29
+ }
30
+ /** How the check gets a page: `playwrightDriver(browser)`, `cdpDriver(session)`. */
31
+ export interface CheckDriver {
32
+ open(): Promise<CheckSession>;
33
+ }
34
+ export interface CheckOptions {
35
+ readonly config: PortholeConfig;
36
+ /** The content as the agent would send it: a fragment, or a whole document. */
37
+ readonly content: string;
38
+ readonly driver: CheckDriver;
39
+ /** Widths, px. Default: the manual's phone and desktop widths (`config.layout`). */
40
+ readonly widths?: readonly number[];
41
+ /** Default: light and dark, or light alone where the app doesn't theme it. */
42
+ readonly schemes?: readonly ColorScheme[];
43
+ /** The host's live theme values per scheme, as `HostOptions.theme` answers. */
44
+ readonly hostTheme?: {
45
+ readonly light?: Readonly<Record<string, string>>;
46
+ readonly dark?: Readonly<Record<string, string>>;
47
+ };
48
+ /** How long content settles before it is measured, ms. Default 1500. */
49
+ readonly settleMs?: number;
50
+ /** A PNG of each run, for an agent that sees. */
51
+ readonly screenshots?: boolean;
52
+ /** The most distinct problems `text` names (default 8): the rest are counted. */
53
+ readonly maxProblems?: number;
54
+ /**
55
+ * The check page's script (`import page from "@botiverse/porthole/check/page"`). Node finds it
56
+ * itself; a bundled runtime (a Worker) passes it.
57
+ */
58
+ readonly page?: string;
59
+ }
60
+ export interface CheckRun {
61
+ readonly width: number;
62
+ readonly scheme: ColorScheme;
63
+ /** The height the content reported, px, and whether the config's limit cuts it. */
64
+ readonly height: number | null;
65
+ readonly clipped: boolean;
66
+ /** Wider than its frame: it scrolls sideways (or is cut). */
67
+ readonly overflowX: boolean;
68
+ readonly errors: readonly string[];
69
+ readonly blocked: readonly {
70
+ readonly url: string;
71
+ readonly directive: string;
72
+ }[];
73
+ readonly failedLoads: readonly {
74
+ readonly url: string;
75
+ readonly tag: string;
76
+ }[];
77
+ readonly console: readonly {
78
+ readonly level: "error" | "warning";
79
+ readonly text: string;
80
+ }[];
81
+ /**
82
+ * The host functions it called (P074), each answered as a host that declines would. One a
83
+ * host's gates refuse whatever the person says (no click, bad arguments, not offered, too
84
+ * often) is a problem; one a person or host may decline is a note.
85
+ */
86
+ readonly calls: readonly CheckCall[];
87
+ readonly screenshot?: Uint8Array;
88
+ }
89
+ export interface CheckReport {
90
+ /**
91
+ * Nothing failed: no errors, blocks, failed loads, console errors, host-function calls a host
92
+ * refuses, overflow or cut, no lint error.
93
+ */
94
+ readonly ok: boolean;
95
+ readonly lint: readonly Finding[];
96
+ readonly runs: readonly CheckRun[];
97
+ /** One short summary for the agent: each problem once, with where it happened. */
98
+ readonly text: string;
99
+ }
100
+ export declare function checkPage(options: CheckOptions): Promise<CheckReport>;
@@ -0,0 +1,247 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { presets } from "../presets/presets.js";
10
+ import { createServer } from "../server/server.js";
11
+ import { CHECK_CONTENT_DOMAIN, CHECK_ORIGIN } from "./drivers.js";
12
+ import { lintContent } from "./lint.js";
13
+ import { instrumented, namedScripts, } from "./instrument.js";
14
+ /** The content source the check's served origins match. */
15
+ const CHECK_SOURCE = `https://*.${CHECK_CONTENT_DOMAIN}`;
16
+ const noun = (config) => config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
17
+ /**
18
+ * The config the check runs content under where it can't serve it (a driver without `serve`):
19
+ * opaque (a served config's content with the same CSP); an MCP Apps view as a page with the view's
20
+ * egress (its protocol is its host's).
21
+ */
22
+ function checkedAs(config) {
23
+ const opaque = config.isolation === "opaque" ? config : { ...config, isolation: "opaque", contentOrigins: [] };
24
+ return opaque.mode === "mcp-app"
25
+ ? presets.artifact({ egress: opaque.egress, limits: opaque.limits })
26
+ : opaque;
27
+ }
28
+ /** The check page's script: given, or (Node) the package's own. */
29
+ async function pageScript(given) {
30
+ if (given !== undefined) {
31
+ return given;
32
+ }
33
+ // Not a literal: a bundler for a Worker leaves it alone (a Worker passes `page`).
34
+ const where = new URL(import.meta.url.endsWith(".ts") ? "./page-source.ts" : "./page-source.js", import.meta.url).href;
35
+ const loaded = (await import(__rewriteRelativeImportExtension(where)));
36
+ return loaded.default;
37
+ }
38
+ const escapeScript = (code) => code.replace(/<\/script/giu, "<\\/script");
39
+ export async function checkPage(options) {
40
+ const { config } = options;
41
+ const lint = lintContent(config, options.content);
42
+ if (config.mode === "url") {
43
+ return {
44
+ ok: true,
45
+ lint,
46
+ runs: [],
47
+ text: "A url-mode app runs its own page: nothing to check here.",
48
+ };
49
+ }
50
+ const widths = options.widths ?? [config.layout.narrowWidthPx, config.layout.wideWidthPx];
51
+ const unthemed = config.theme.documents === "never";
52
+ const schemes = options.schemes ?? (unthemed ? ["light"] : ["light", "dark"]);
53
+ const settle = options.settleMs ?? 1_500;
54
+ const fills = config.layout.kind === "fill";
55
+ const script = await pageScript(options.page);
56
+ const html = `<!doctype html><html><head><meta charset="utf-8"><title>Porthole check</title><style>body{margin:0;padding:8px}section{margin-bottom:16px}</style></head><body><script>${escapeScript(script)}</script></body></html>`;
57
+ // Its inline scripts named, so an error says the line in the content as written (P074).
58
+ const { content, scriptLines } = namedScripts(options.content);
59
+ const session = await options.driver.open();
60
+ // A served config runs served, on a content origin the driver answers, under Porthole's own
61
+ // server: its CSP in headers, its shell, its storage and cookies (P074). Else opaque.
62
+ const servedHere = config.isolation === "domain" && config.mode !== "mcp-app" && session.serve !== undefined;
63
+ const servedConfig = { ...config, contentOrigins: [CHECK_SOURCE] };
64
+ const server = servedHere
65
+ ? createServer({
66
+ content: { domain: CHECK_CONTENT_DOMAIN, scheme: "https" },
67
+ secret: crypto.getRandomValues(new Uint8Array(32)),
68
+ hostOrigins: [CHECK_ORIGIN],
69
+ configs: { check: servedConfig },
70
+ artifacts: { get: () => Promise.resolve({ html: instrumented(content) }) },
71
+ })
72
+ : null;
73
+ const handler = async (request) => {
74
+ const url = new URL(request.url);
75
+ if (url.origin === CHECK_ORIGIN) {
76
+ if (url.pathname === "/") {
77
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
78
+ }
79
+ if (url.pathname === "/issue" && server !== null) {
80
+ const asked = (await request.json());
81
+ return Response.json(await server.issue(asked.instance, { viewer: "check" }));
82
+ }
83
+ return new Response("not found", { status: 404 });
84
+ }
85
+ return (await server?.handle(request)) ?? new Response("not found", { status: 404 });
86
+ };
87
+ const shown = servedHere ? servedConfig : checkedAs(config);
88
+ let runIndex = 0;
89
+ const runs = [];
90
+ try {
91
+ for (const width of widths) {
92
+ await session.setViewport(width + 40, fills ? 760 : 900);
93
+ if (servedHere && session.serve !== undefined) {
94
+ await session.serve(handler);
95
+ }
96
+ else {
97
+ await session.load(html);
98
+ }
99
+ for (const scheme of schemes) {
100
+ runIndex += 1;
101
+ // Each run on an origin of its own: its storage starts empty, as a new page's does.
102
+ const instance = servedHere
103
+ ? {
104
+ scope: `check-${runIndex}`,
105
+ document: config.mode === "inline"
106
+ ? { kind: "shell", preset: "check" }
107
+ : { kind: "artifact", id: "check", version: "1", preset: "check" },
108
+ }
109
+ : undefined;
110
+ const spec = {
111
+ config: shown,
112
+ content,
113
+ scriptLines,
114
+ ...(instance === undefined ? {} : { instance }),
115
+ widthPx: width,
116
+ ...(fills ? { heightPx: 700 } : {}),
117
+ scheme,
118
+ ...(options.hostTheme?.[scheme] === undefined
119
+ ? {}
120
+ : { hostTheme: options.hostTheme[scheme] }),
121
+ };
122
+ const id = await session.evaluate(`window.portholeCheck.run(${JSON.stringify(spec)})`);
123
+ await session.evaluate(`new Promise((resolve) => setTimeout(resolve, ${settle}))`);
124
+ await session.evaluate(`window.portholeCheck.measure(${id})`);
125
+ const data = await session.evaluate(`window.portholeCheck.result(${id})`);
126
+ const screenshot = options.screenshots === true && session.screenshot !== undefined
127
+ ? await session.screenshot(`#porthole-check-${id}`)
128
+ : undefined;
129
+ await session.evaluate(`window.portholeCheck.end(${id})`);
130
+ const height = data?.height ?? null;
131
+ runs.push({
132
+ width,
133
+ scheme,
134
+ height,
135
+ clipped: !fills && height !== null && height >= config.limits.maxHeightPx,
136
+ overflowX: data?.scrollWidth !== null &&
137
+ data?.scrollWidth !== undefined &&
138
+ data.clientWidth !== null &&
139
+ data.scrollWidth > data.clientWidth + 1,
140
+ errors: unique(data?.errors ?? []),
141
+ blocked: uniqueBy(data?.blocked ?? [], (each) => `${each.url} ${each.directive}`),
142
+ failedLoads: uniqueBy(data?.failedLoads ?? [], (each) => each.url),
143
+ console: uniqueBy(data?.console ?? [], (each) => `${each.level} ${each.text}`),
144
+ calls: uniqueBy(data?.calls ?? [], (each) => `${each.capability} ${each.outcome}`),
145
+ ...(screenshot === undefined ? {} : { screenshot }),
146
+ });
147
+ }
148
+ }
149
+ }
150
+ finally {
151
+ await session.close();
152
+ }
153
+ const failed = (run) => run.errors.length > 0 ||
154
+ run.blocked.length > 0 ||
155
+ run.failedLoads.length > 0 ||
156
+ run.console.some((each) => each.level === "error") ||
157
+ run.calls.some((each) => REFUSED[each.outcome] !== undefined) ||
158
+ run.overflowX ||
159
+ run.clipped;
160
+ const ok = !lint.some((each) => each.severity === "error") && !runs.some(failed);
161
+ return { ok, lint, runs, text: summary(config, lint, runs, options.maxProblems ?? 8) };
162
+ }
163
+ /** Calls a host refuses whatever the person says: problems, worded for the agent. */
164
+ const REFUSED = {
165
+ "no-user-activation": (name) => `It called ${name} at load, with no click: hosts refuse that. Call ${name} from a click`,
166
+ invalid: (name) => `It called ${name} with arguments hosts refuse: see what the manual says ${name} takes`,
167
+ "not-declared": (name) => `It called ${name}, which this host doesn't offer: leave it out`,
168
+ "rate-limited": (name) => `It called ${name} more often than hosts allow, and was refused`,
169
+ "no-confirm": (name) => `It called ${name}, which this host can't confirm, and was refused`,
170
+ };
171
+ const unique = (values) => [...new Set(values)];
172
+ function uniqueBy(values, key) {
173
+ const seen = new Set();
174
+ return values.filter((each) => {
175
+ const k = key(each);
176
+ if (seen.has(k)) {
177
+ return false;
178
+ }
179
+ seen.add(k);
180
+ return true;
181
+ });
182
+ }
183
+ const clip = (text, most = 200) => text.length > most ? `${text.slice(0, most - 1)}…` : text;
184
+ /**
185
+ * The report in a few lines for the agent: each problem once, with the runs it happened in, at
186
+ * most `most` of them.
187
+ */
188
+ function summary(config, lint, runs, most) {
189
+ const it = noun(config);
190
+ const where = new Map();
191
+ const add = (problem, run) => {
192
+ const list = where.get(problem) ?? [];
193
+ list.push(`${run.width} px ${run.scheme}`);
194
+ where.set(problem, list);
195
+ };
196
+ // Calls a person or host may decline: the content should still work when they do.
197
+ const notes = new Set();
198
+ for (const run of runs) {
199
+ for (const call of run.calls) {
200
+ const refused = REFUSED[call.outcome];
201
+ if (refused === undefined) {
202
+ notes.add(`Note: it called ${call.capability} at load; the check answered no, as a host or a person may. Make sure the ${it} still works then.`);
203
+ }
204
+ else {
205
+ add(refused(call.capability), run);
206
+ }
207
+ }
208
+ for (const error of run.errors) {
209
+ add(`It threw: ${clip(error)}`, run);
210
+ }
211
+ for (const block of run.blocked) {
212
+ add(`The sandbox blocked ${clip(block.url, 120)} (${block.directive}): nothing loads from there here`, run);
213
+ }
214
+ const blockedUrls = new Set(run.blocked.map((each) => each.url));
215
+ for (const load of run.failedLoads.filter((each) => !blockedUrls.has(each.url))) {
216
+ add(`Failed to load ${clip(load.url, 120)} (<${load.tag}>)`, run);
217
+ }
218
+ for (const line of run.console.filter((each) => each.level === "error")) {
219
+ add(`console.error: ${clip(line.text)}`, run);
220
+ }
221
+ if (run.overflowX) {
222
+ add(`It is wider than its frame and scrolls sideways: nothing fixed wider than ${config.layout.minWidthPx} px; let it wrap`, run);
223
+ }
224
+ if (run.clipped) {
225
+ add(`It is taller than ${config.limits.maxHeightPx} px and is cut: make it shorter`, run);
226
+ }
227
+ }
228
+ const lines = [
229
+ ...lint.map((each) => `${each.severity === "error" ? "Error" : "Warning"}${each.line === undefined ? "" : ` (line ${each.line})`}: ${each.message}`),
230
+ ...[...where].map(([problem, at]) => `${problem} (at ${at.length === runs.length ? "every width and scheme" : at.join(", ")}).`),
231
+ ];
232
+ const ran = `${[...new Set(runs.map((run) => `${run.width} px`))].join(" and ")}, ${[...new Set(runs.map((run) => run.scheme))].join(" and ")}`;
233
+ if (lines.length === 0) {
234
+ return [
235
+ `OK: the ${it} ran at ${ran} with no errors, blocks, failed loads or overflow.`,
236
+ ...notes,
237
+ ].join("\n");
238
+ }
239
+ const shown = lines.slice(0, most);
240
+ const more = lines.length - shown.length;
241
+ return [
242
+ `The ${it} has ${lines.length} problem${lines.length === 1 ? "" : "s"} (ran at ${ran}):`,
243
+ ...shown.map((line) => `- ${line}`),
244
+ ...(more > 0 ? [`- and ${more} more.`] : []),
245
+ ...notes,
246
+ ].join("\n");
247
+ }
@@ -0,0 +1,43 @@
1
+ import type { Browser } from "@playwright/test";
2
+ import type { CheckDriver } from "./check.ts";
3
+ /**
4
+ * Drivers for `checkPage` (P073): Playwright's browser on Node, or any Chrome DevTools Protocol
5
+ * session (Puppeteer's `page.createCDPSession()`, `@cloudflare/puppeteer` on Cloudflare Browser
6
+ * Rendering from a Worker).
7
+ *
8
+ * A driver answers two names no network has itself: the check page's origin (a host's), and a
9
+ * content domain, where a served config's content runs on an origin of its own as people's
10
+ * browsers run it (P074).
11
+ */
12
+ /** Where the check page is served from. */
13
+ export declare const CHECK_ORIGIN = "https://porthole-check.invalid";
14
+ /** The content domain a served config's content runs under in the check: another site. */
15
+ export declare const CHECK_CONTENT_DOMAIN = "porthole-check-content.invalid";
16
+ /** Checks in a page of a Playwright browser (`chromium.launch()`), one page per check. */
17
+ export declare function playwrightDriver(browser: Browser): CheckDriver;
18
+ /**
19
+ * A Chrome DevTools Protocol session: its commands and its events. The least the driver uses, so
20
+ * Puppeteer's `CDPSession` (`@cloudflare/puppeteer`'s too) and Playwright's fit as they are, with
21
+ * no cast (P074).
22
+ */
23
+ export interface CdpSession {
24
+ send(method: string, params?: Record<string, unknown>): Promise<unknown>;
25
+ on(event: "Fetch.requestPaused", listener: (params: PausedRequest) => void): unknown;
26
+ }
27
+ /** What CDP says of a request it paused. */
28
+ interface PausedRequest {
29
+ readonly requestId: string;
30
+ readonly request?: {
31
+ readonly url: string;
32
+ readonly method: string;
33
+ readonly headers?: Readonly<Record<string, string>>;
34
+ readonly postData?: string;
35
+ };
36
+ }
37
+ /**
38
+ * Checks over a CDP session to a page (P073): `cdpDriver(() => page.createCDPSession())` with
39
+ * Puppeteer, or `@cloudflare/puppeteer` in a Worker with a Browser Rendering binding. `open` is
40
+ * asked for a session per check; the caller closes its page.
41
+ */
42
+ export declare function cdpDriver(open: () => Promise<CdpSession>): CheckDriver;
43
+ export {};
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Drivers for `checkPage` (P073): Playwright's browser on Node, or any Chrome DevTools Protocol
3
+ * session (Puppeteer's `page.createCDPSession()`, `@cloudflare/puppeteer` on Cloudflare Browser
4
+ * Rendering from a Worker).
5
+ *
6
+ * A driver answers two names no network has itself: the check page's origin (a host's), and a
7
+ * content domain, where a served config's content runs on an origin of its own as people's
8
+ * browsers run it (P074).
9
+ */
10
+ /** Where the check page is served from. */
11
+ export const CHECK_ORIGIN = "https://porthole-check.invalid";
12
+ /** The content domain a served config's content runs under in the check: another site. */
13
+ export const CHECK_CONTENT_DOMAIN = "porthole-check-content.invalid";
14
+ const CHECK_HOST = new URL(CHECK_ORIGIN).hostname;
15
+ /** Whether the driver answers a URL itself. */
16
+ const answered = (url) => url.hostname === CHECK_HOST || url.hostname.endsWith(`.${CHECK_CONTENT_DOMAIN}`);
17
+ /** A page that answers the check's own names: `/` the given document, the rest 404. */
18
+ const pageOnly = (html) => (request) => Promise.resolve(new URL(request.url).hostname === CHECK_HOST && new URL(request.url).pathname === "/"
19
+ ? new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } })
20
+ : new Response("not found", { status: 404 }));
21
+ /** Checks in a page of a Playwright browser (`chromium.launch()`), one page per check. */
22
+ export function playwrightDriver(browser) {
23
+ return {
24
+ async open() {
25
+ const page = await browser.newPage();
26
+ let handler = pageOnly("");
27
+ await page.route(answered, async (route) => {
28
+ const asked = route.request();
29
+ const headers = Object.entries(await asked.allHeaders()).filter(([name]) => !name.startsWith(":"));
30
+ const method = asked.method();
31
+ const body = method === "GET" || method === "HEAD" ? null : asked.postDataBuffer();
32
+ const answer = await handler(new Request(asked.url(), {
33
+ method,
34
+ headers,
35
+ ...(body === null ? {} : { body: new Uint8Array(body) }),
36
+ }));
37
+ const out = {};
38
+ for (const [name, value] of answer.headers) {
39
+ if (name !== "set-cookie") {
40
+ out[name] = value;
41
+ }
42
+ }
43
+ const cookies = answer.headers.getSetCookie();
44
+ if (cookies.length > 0) {
45
+ out["set-cookie"] = cookies.join("\n");
46
+ }
47
+ await route.fulfill({
48
+ status: answer.status,
49
+ headers: out,
50
+ body: Buffer.from(await answer.arrayBuffer()),
51
+ });
52
+ });
53
+ return {
54
+ setViewport: (width, height) => page.setViewportSize({ width, height }),
55
+ async load(document) {
56
+ handler = pageOnly(document);
57
+ await page.goto(`${CHECK_ORIGIN}/`, { waitUntil: "load" });
58
+ },
59
+ async serve(given) {
60
+ handler = given;
61
+ await page.goto(`${CHECK_ORIGIN}/`, { waitUntil: "load" });
62
+ },
63
+ evaluate: (expression) => page.evaluate(expression),
64
+ screenshot: async (selector) => new Uint8Array(await page.locator(selector).screenshot()),
65
+ close: () => page.close(),
66
+ };
67
+ },
68
+ };
69
+ }
70
+ const bytesToBase64 = (bytes) => {
71
+ let binary = "";
72
+ for (const byte of bytes) {
73
+ binary += String.fromCharCode(byte);
74
+ }
75
+ return btoa(binary);
76
+ };
77
+ const base64 = (text) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
78
+ /**
79
+ * Checks over a CDP session to a page (P073): `cdpDriver(() => page.createCDPSession())` with
80
+ * Puppeteer, or `@cloudflare/puppeteer` in a Worker with a Browser Rendering binding. `open` is
81
+ * asked for a session per check; the caller closes its page.
82
+ */
83
+ export function cdpDriver(open) {
84
+ return {
85
+ async open() {
86
+ const session = await open();
87
+ await session.send("Page.enable");
88
+ await session.send("Runtime.enable");
89
+ let handler = pageOnly("");
90
+ // The check's own names are answered here; everything else goes on.
91
+ await session.send("Fetch.enable", {
92
+ patterns: [
93
+ { urlPattern: `${CHECK_ORIGIN}/*` },
94
+ { urlPattern: `https://*.${CHECK_CONTENT_DOMAIN}/*` },
95
+ ],
96
+ });
97
+ session.on("Fetch.requestPaused", (event) => {
98
+ void (async () => {
99
+ const asked = event.request;
100
+ if (asked === undefined || !answered(new URL(asked.url))) {
101
+ await session.send("Fetch.continueRequest", { requestId: event.requestId });
102
+ return;
103
+ }
104
+ const body = asked.method === "GET" || asked.method === "HEAD" ? null : (asked.postData ?? null);
105
+ const answer = await handler(new Request(asked.url, {
106
+ method: asked.method,
107
+ headers: Object.entries(asked.headers ?? {}),
108
+ ...(body === null ? {} : { body }),
109
+ }));
110
+ await session.send("Fetch.fulfillRequest", {
111
+ requestId: event.requestId,
112
+ responseCode: answer.status,
113
+ responseHeaders: [
114
+ ...[...answer.headers]
115
+ .filter(([name]) => name !== "set-cookie")
116
+ .map(([name, value]) => ({ name, value })),
117
+ ...answer.headers.getSetCookie().map((value) => ({ name: "set-cookie", value })),
118
+ ],
119
+ body: bytesToBase64(new Uint8Array(await answer.arrayBuffer())),
120
+ });
121
+ })();
122
+ });
123
+ const evaluate = async (expression) => {
124
+ const answer = (await session.send("Runtime.evaluate", {
125
+ expression,
126
+ awaitPromise: true,
127
+ returnByValue: true,
128
+ }));
129
+ if (answer.exceptionDetails !== undefined) {
130
+ throw new Error(answer.exceptionDetails.exception?.description ??
131
+ answer.exceptionDetails.text ??
132
+ "Evaluation failed");
133
+ }
134
+ return answer.result?.value;
135
+ };
136
+ const goto = async () => {
137
+ await session.send("Page.navigate", { url: `${CHECK_ORIGIN}/` });
138
+ // The page's script runs when it loads: wait until it says so.
139
+ for (let tries = 0; tries < 100; tries += 1) {
140
+ const ready = await evaluate('document.documentElement?.dataset.portholeCheck === "ready"').catch(() => false);
141
+ if (ready) {
142
+ return;
143
+ }
144
+ await new Promise((resolve) => setTimeout(resolve, 50));
145
+ }
146
+ throw new Error("The check page didn't start");
147
+ };
148
+ return {
149
+ async setViewport(width, height) {
150
+ await session.send("Emulation.setDeviceMetricsOverride", {
151
+ width,
152
+ height,
153
+ deviceScaleFactor: 1,
154
+ mobile: false,
155
+ });
156
+ },
157
+ async load(document) {
158
+ handler = pageOnly(document);
159
+ await goto();
160
+ },
161
+ async serve(given) {
162
+ handler = given;
163
+ await goto();
164
+ },
165
+ evaluate,
166
+ async screenshot(selector) {
167
+ const box = await evaluate(`(() => { const r = document.querySelector(${JSON.stringify(selector)})?.getBoundingClientRect(); return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null; })()`);
168
+ if (box === null) {
169
+ return new Uint8Array();
170
+ }
171
+ const shot = (await session.send("Page.captureScreenshot", {
172
+ format: "png",
173
+ clip: { ...box, scale: 1 },
174
+ }));
175
+ return base64(shot.data);
176
+ },
177
+ close: () => Promise.resolve(),
178
+ };
179
+ },
180
+ };
181
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@botiverse/porthole/check`: check content before people see it (P073). `checkPage` runs it in
3
+ * the real sandbox through a driver (`playwrightDriver`, `cdpDriver`); `lintContent` and the tool
4
+ * definitions are in the core (`@botiverse/porthole`), since they need no browser.
5
+ */
6
+ export { checkPage, type CheckCall, type CheckDriver, type CheckOptions, type CheckReport, type CheckRun, type CheckSession, } from "./check.ts";
7
+ export { CHECK_CONTENT_DOMAIN, CHECK_ORIGIN, cdpDriver, playwrightDriver, type CdpSession, } from "./drivers.ts";
8
+ export { lintContent, type Finding, type LintRule } from "./lint.ts";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@botiverse/porthole/check`: check content before people see it (P073). `checkPage` runs it in
3
+ * the real sandbox through a driver (`playwrightDriver`, `cdpDriver`); `lintContent` and the tool
4
+ * definitions are in the core (`@botiverse/porthole`), since they need no browser.
5
+ */
6
+ export { checkPage, } from "./check.js";
7
+ export { CHECK_CONTENT_DOMAIN, CHECK_ORIGIN, cdpDriver, playwrightDriver, } from "./drivers.js";
8
+ export { lintContent } from "./lint.js";