@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,110 @@
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 type { FrameOutcome } from "./types.ts";
5
+ /**
6
+ * The client half of the host kit (P072): what the app's page needs from its server's Porthole
7
+ * routes (`ContentHost.routes`, under `/porthole`): whether frames are served and so which config
8
+ * each kind shows under, frame locations, clean addresses, and (for an app whose page holds a
9
+ * token rather than a cookie) the viewer handoff.
10
+ *
11
+ * const porthole = portholeClient({ displays }); // base "/porthole"
12
+ * const config = porthole.config("page"); // null until meta is known
13
+ * createHost(config, { locator: porthole }).mount(box, { …, instance });
14
+ */
15
+ /** What `GET <prefix>/meta` answers (`ContentHost.clientMeta`). */
16
+ export interface ContentClientMeta {
17
+ readonly served: boolean;
18
+ readonly contentSource: string | null;
19
+ readonly frameSources: readonly string[];
20
+ readonly health: {
21
+ readonly state: "off" | "checking" | "healthy" | "unhealthy";
22
+ readonly reason?: string;
23
+ } | null;
24
+ }
25
+ export interface PortholeClientOptions<N extends string> {
26
+ readonly displays: Displays<N>;
27
+ /** Where the server's Porthole routes are: a path (`/porthole`) or a URL (a desktop app's). */
28
+ readonly base?: string;
29
+ /** Headers for each request (an `authorization`), or a function giving them now. */
30
+ readonly headers?: HeadersInit | (() => HeadersInit);
31
+ /** Default `same-origin` (the app's own cookies); `include` for a base on another origin. */
32
+ readonly credentials?: RequestCredentials;
33
+ /** Meta the server put in the page, so frames needn't wait for a request. */
34
+ readonly meta?: ContentClientMeta;
35
+ /**
36
+ * Keep the viewer handoff fresh (`entry.handoff`, P072): an app whose page authenticates with
37
+ * a token. Done now, when the page regains focus, and when it becomes visible.
38
+ */
39
+ readonly handoff?: boolean;
40
+ readonly fetch?: typeof fetch;
41
+ }
42
+ /**
43
+ * Every function is declared `this: void` (P074): each may be passed bare
44
+ * (`useSyncExternalStore(porthole.subscribe, porthole.meta)`), and none reads `this`.
45
+ */
46
+ export interface PortholeClient<N extends string = string> extends InstanceLocator {
47
+ readonly displays: Displays<N>;
48
+ /** Locates an instance's frame through `POST <base>/frames` (`InstanceLocator`). */
49
+ locate(this: void, instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation>;
50
+ /** The meta as last fetched, or null before it is known. */
51
+ meta(this: void): ContentClientMeta | null;
52
+ /** Called when the meta changes (frames served or not). */
53
+ subscribe(this: void, listener: () => void): () => void;
54
+ /** Fetches the meta again. */
55
+ refresh(this: void): Promise<ContentClientMeta | null>;
56
+ /**
57
+ * The config a kind shows under now: served while frames are served, else opaque (a url kind:
58
+ * null). Null until the meta is known, so a frame never starts opaque and then restarts served.
59
+ */
60
+ config(this: void, kind: N): PortholeConfig | null;
61
+ /** The same, for an instance's kind. */
62
+ configFor(this: void, instance: InstanceRef): PortholeConfig | null;
63
+ /** An instance's clean address (`entry.pathOf` on the server), or null. */
64
+ link(this: void, instance: InstanceRef): Promise<string | null>;
65
+ /** The clean address if already known (from locating the instance), for rendering. */
66
+ knownLink(this: void, instance: InstanceRef): string | null;
67
+ /**
68
+ * Opens an instance's clean address in a new tab: call it in the click (the tab opens at once,
69
+ * then goes to the address).
70
+ */
71
+ openInTab(this: void, instance: InstanceRef): void;
72
+ /** Hands the signed-in viewer to the authorize route (`entry.handoff`); true if it took. */
73
+ handoff(this: void): Promise<boolean>;
74
+ /**
75
+ * `next` if it is this server's authorize route (after a sign-in), or with `{ app: true }` any
76
+ * address on the app's own origin; else null (`entryTarget`).
77
+ */
78
+ entryTarget(this: void, next: unknown, options?: {
79
+ readonly app?: boolean;
80
+ }): string | null;
81
+ /** Stops refreshing the handoff. */
82
+ close(this: void): void;
83
+ }
84
+ /**
85
+ * Whether a sign-in's `next` is the app's authorize route (P072): the open-redirect guard a
86
+ * single-page app runs before going on to it. Null for anything else; with `{ app: true }`, also
87
+ * any path or address on the app's own origin (P074), so one check serves a sign-in that comes
88
+ * back to redirect entry or to the app's own pages. Never another origin.
89
+ *
90
+ * The authorize route is `<first app origin><prefix>/authorize` unless the server names another
91
+ * (`entry.authorizeUrl`): `https://app.example.com/porthole/authorize` by default.
92
+ */
93
+ export declare function entryTarget(next: unknown, authorizeUrl: string, options?: {
94
+ readonly app?: boolean;
95
+ }): string | null;
96
+ export declare function portholeClient<N extends string>(options: PortholeClientOptions<N>): PortholeClient<N>;
97
+ /** What a frame that showed nothing should offer the person, by its outcome (P072). */
98
+ export interface FrameFallback {
99
+ /** `needs-tab`: open it in a new tab (the browser keeps no cookie in a frame, sign-in, framing). */
100
+ readonly kind: "needs-tab" | "denied" | "expired" | "failed" | "timeout";
101
+ readonly title: string;
102
+ readonly message: string;
103
+ }
104
+ /**
105
+ * The fallback for a frame's outcome, worded as Porthole's own pages word it; null when it loaded.
106
+ * `url`: a url-mode app, where a timeout means it couldn't run in a frame.
107
+ */
108
+ export declare function frameFallback(outcome: FrameOutcome, options?: {
109
+ readonly url?: boolean;
110
+ }): FrameFallback | null;
@@ -0,0 +1,274 @@
1
+ import { LocateError } from "./locator.js";
2
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3
+ /**
4
+ * Whether a sign-in's `next` is the app's authorize route (P072): the open-redirect guard a
5
+ * single-page app runs before going on to it. Null for anything else; with `{ app: true }`, also
6
+ * any path or address on the app's own origin (P074), so one check serves a sign-in that comes
7
+ * back to redirect entry or to the app's own pages. Never another origin.
8
+ *
9
+ * The authorize route is `<first app origin><prefix>/authorize` unless the server names another
10
+ * (`entry.authorizeUrl`): `https://app.example.com/porthole/authorize` by default.
11
+ */
12
+ export function entryTarget(next, authorizeUrl, options = {}) {
13
+ if (typeof next !== "string" || next.length > 8_192) {
14
+ return null;
15
+ }
16
+ let target;
17
+ let route;
18
+ try {
19
+ route = new URL(authorizeUrl);
20
+ target = new URL(next, route);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ if (target.origin === route.origin &&
26
+ target.pathname === route.pathname &&
27
+ target.hash === "" &&
28
+ target.searchParams.has("state")) {
29
+ return target.href;
30
+ }
31
+ // An app path: one leading slash, no backslash (`//evil.example` and `/\evil.example` are
32
+ // other sites to a browser), and still the app's origin once resolved.
33
+ const path = /^\/(?![/\\])/u.test(next) && !next.includes("\\");
34
+ const absolute = /^https?:\/\//iu.test(next);
35
+ return options.app === true && (path || absolute) && target.origin === route.origin
36
+ ? target.href
37
+ : null;
38
+ }
39
+ export function portholeClient(options) {
40
+ const base = (options.base ?? "/porthole").replace(/\/+$/u, "");
41
+ const ask = options.fetch ?? ((input, init) => fetch(input, init));
42
+ const headersNow = () => new Headers(typeof options.headers === "function" ? options.headers() : options.headers);
43
+ const credentials = options.credentials ?? "same-origin";
44
+ const here = () => (typeof location === "undefined" ? "http://localhost/" : location.href);
45
+ const url = (path) => new URL(`${base}${path}`, here()).href;
46
+ let meta = options.meta ?? null;
47
+ const listeners = new Set();
48
+ const links = new Map();
49
+ const keyOf = (instance) => JSON.stringify(instance);
50
+ const set = (next) => {
51
+ if (JSON.stringify(next) !== JSON.stringify(meta)) {
52
+ meta = next;
53
+ for (const listener of listeners) {
54
+ listener();
55
+ }
56
+ }
57
+ };
58
+ let refreshing = null;
59
+ const refresh = () => {
60
+ refreshing ??= (async () => {
61
+ try {
62
+ const answer = await ask(url("/meta"), {
63
+ headers: headersNow(),
64
+ credentials,
65
+ cache: "no-store",
66
+ });
67
+ const data = answer.ok ? await answer.json() : null;
68
+ if (isRecord(data) && typeof data.served === "boolean") {
69
+ set(data);
70
+ }
71
+ }
72
+ catch {
73
+ // Keep what is known; the next refresh tries again.
74
+ }
75
+ finally {
76
+ refreshing = null;
77
+ }
78
+ return meta;
79
+ })();
80
+ return refreshing;
81
+ };
82
+ if (meta === null) {
83
+ void refresh();
84
+ }
85
+ const configOf = (kind) => {
86
+ if (meta === null || kind === null) {
87
+ return null;
88
+ }
89
+ if (meta.served && meta.contentSource !== null) {
90
+ const served = options.displays.served(meta.contentSource);
91
+ if (served !== null) {
92
+ return served[kind];
93
+ }
94
+ }
95
+ try {
96
+ return options.displays.opaque(kind);
97
+ }
98
+ catch {
99
+ // A url kind has no opaque config: not shown while frames aren't served.
100
+ return null;
101
+ }
102
+ };
103
+ const issue = async (instance, signal) => {
104
+ const headers = headersNow();
105
+ headers.set("content-type", "application/json");
106
+ headers.set("accept", "application/json");
107
+ const answer = await ask(url("/frames"), {
108
+ method: "POST",
109
+ headers,
110
+ credentials,
111
+ redirect: "error",
112
+ body: JSON.stringify({ instance }),
113
+ ...(signal === undefined ? {} : { signal }),
114
+ });
115
+ const data = await answer.json().catch(() => null);
116
+ if (!answer.ok) {
117
+ const error = isRecord(data) && isRecord(data.error) ? data.error : {};
118
+ const code = typeof error.code === "string" ? error.code : "failed";
119
+ if (code === "not-served") {
120
+ void refresh();
121
+ }
122
+ throw new LocateError(typeof error.message === "string"
123
+ ? error.message
124
+ : `The app's frame endpoint answered ${answer.status}`, answer.status, code);
125
+ }
126
+ if (!isRecord(data) || typeof data.url !== "string" || typeof data.origin !== "string") {
127
+ throw new LocateError("The app's frame endpoint gave no location", answer.status, "bad-location");
128
+ }
129
+ links.set(keyOf(instance), typeof data.link === "string" ? data.link : null);
130
+ return {
131
+ url: data.url,
132
+ origin: data.origin,
133
+ ...(typeof data.reports === "boolean" ? { reports: data.reports } : {}),
134
+ };
135
+ };
136
+ let lastHandoff = 0;
137
+ const handoff = async () => {
138
+ lastHandoff = Date.now();
139
+ try {
140
+ const answer = await ask(url("/handoff"), {
141
+ method: "POST",
142
+ headers: headersNow(),
143
+ credentials,
144
+ cache: "no-store",
145
+ });
146
+ return answer.ok;
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ };
152
+ // Kept fresh while the page is used: on load, focus and visibility, at most every 30 s.
153
+ const fresh = () => {
154
+ if (Date.now() - lastHandoff > 30_000 &&
155
+ (typeof document === "undefined" || document.visibilityState !== "hidden")) {
156
+ void handoff();
157
+ }
158
+ };
159
+ const watching = options.handoff === true && typeof window !== "undefined";
160
+ if (watching) {
161
+ void handoff();
162
+ window.addEventListener("focus", fresh);
163
+ document.addEventListener("visibilitychange", fresh);
164
+ }
165
+ const link = async (instance) => {
166
+ const key = keyOf(instance);
167
+ if (!links.has(key)) {
168
+ try {
169
+ await issue(instance);
170
+ }
171
+ catch {
172
+ return null;
173
+ }
174
+ }
175
+ return links.get(key) ?? null;
176
+ };
177
+ return {
178
+ displays: options.displays,
179
+ meta: () => meta,
180
+ subscribe: (listener) => {
181
+ listeners.add(listener);
182
+ return () => {
183
+ listeners.delete(listener);
184
+ };
185
+ },
186
+ refresh,
187
+ config: (kind) => configOf(kind),
188
+ configFor: (instance) => configOf(options.displays.kindOf(instance)),
189
+ locate: issue,
190
+ link,
191
+ knownLink: (instance) => links.get(keyOf(instance)) ?? null,
192
+ openInTab: (instance) => {
193
+ // Opened inside the click (a popup blocker lets it), then sent to the address.
194
+ const tab = typeof window === "undefined" ? null : window.open("about:blank", "_blank");
195
+ if (tab === null) {
196
+ return;
197
+ }
198
+ tab.opener = null;
199
+ void (async () => {
200
+ const found = await link(instance);
201
+ if (found === null) {
202
+ tab.close();
203
+ }
204
+ else {
205
+ tab.location.href = found;
206
+ }
207
+ })();
208
+ },
209
+ handoff,
210
+ entryTarget: (next, given) => entryTarget(next, url("/authorize"), given),
211
+ close: () => {
212
+ if (watching) {
213
+ window.removeEventListener("focus", fresh);
214
+ document.removeEventListener("visibilitychange", fresh);
215
+ }
216
+ },
217
+ };
218
+ }
219
+ /**
220
+ * The fallback for a frame's outcome, worded as Porthole's own pages word it; null when it loaded.
221
+ * `url`: a url-mode app, where a timeout means it couldn't run in a frame.
222
+ */
223
+ export function frameFallback(outcome, options = {}) {
224
+ if (outcome.state === "loaded") {
225
+ return null;
226
+ }
227
+ if (outcome.state === "timeout") {
228
+ return options.url === true
229
+ ? {
230
+ kind: "needs-tab",
231
+ title: "Open this in a new tab",
232
+ message: "It didn't load inside the page.",
233
+ }
234
+ : { kind: "timeout", title: "This is taking too long", message: "It didn't finish loading." };
235
+ }
236
+ switch (outcome.reason) {
237
+ case "cookies":
238
+ return {
239
+ kind: "needs-tab",
240
+ title: "Open this in a new tab",
241
+ message: "This browser keeps no sign-in for it inside a frame.",
242
+ };
243
+ case "sign-in":
244
+ return {
245
+ kind: "needs-tab",
246
+ title: "Open this in a new tab to sign in",
247
+ message: "Signing in doesn't work inside a frame.",
248
+ };
249
+ case "framing":
250
+ return {
251
+ kind: "needs-tab",
252
+ title: "Open this in a new tab",
253
+ message: "It can't be shown inside this page.",
254
+ };
255
+ case "denied":
256
+ return {
257
+ kind: "denied",
258
+ title: "You can't open this anymore",
259
+ message: "You no longer have access to it.",
260
+ };
261
+ case "session":
262
+ return { kind: "expired", title: "This has expired", message: "Open it again." };
263
+ case "not-found":
264
+ return { kind: "failed", title: "Not found", message: "There is nothing here." };
265
+ case "upstream":
266
+ return {
267
+ kind: "failed",
268
+ title: "The app didn't answer",
269
+ message: "Its server couldn't be reached.",
270
+ };
271
+ default:
272
+ return { kind: "failed", title: "This couldn't be shown", message: "Something went wrong." };
273
+ }
274
+ }
package/dist/index.d.ts CHANGED
@@ -24,6 +24,10 @@ export type { AdapterConnection, AdapterEvent, AdapterSession, ProtocolAdapter,
24
24
  export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, PORTHOLE_STYLES, type HostContext, } from "./protocol/mcp-apps.ts";
25
25
  export type { CallContext, CallOutcome, CapabilityHandler, CapabilityHandlers, Confirm, ConfirmAnswer, ConfirmRequest, Proceed, HostFunctionBridge, Refusal, } from "./bridge/types.ts";
26
26
  export { createHost } from "./host/create-host.ts";
27
+ export { entryTarget, frameFallback, portholeClient, type ContentClientMeta, type FrameFallback, type PortholeClient, type PortholeClientOptions, } from "./host/client.ts";
28
+ export { defineDisplays, type DisplayKind, type Displays } from "./displays/displays.ts";
29
+ export { fragmentOf, lintContent, type Finding, type LintRule } from "./check/lint.ts";
30
+ export { admitContent, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, type AdmitResult, type JsonSchema, type ToolDefinition, } from "./check/tools.ts";
27
31
  export { writeClipboard } from "./host/clipboard.ts";
28
32
  export { httpLocator, LocateError, servedOrOpaque, type HttpLocatorOptions, type ServedMeta, } from "./host/locator.ts";
29
33
  export type { AnnotationControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
package/dist/index.js CHANGED
@@ -21,6 +21,12 @@ export { GUIDE_EXAMPLES } from "./guide/examples.js";
21
21
  export { CHART_PALETTE, DEFAULT_THEME, DEFAULT_THEME_EVENT, DEFAULT_THEME_VARIABLES, resolveTheme, themeDefault, } from "./theme/variables.js";
22
22
  export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, PORTHOLE_STYLES, } from "./protocol/mcp-apps.js";
23
23
  export { createHost } from "./host/create-host.js";
24
+ // The client half of the host kit, and the display registry (P072).
25
+ export { entryTarget, frameFallback, portholeClient, } from "./host/client.js";
26
+ export { defineDisplays } from "./displays/displays.js";
27
+ // The agent's side: what content can be told without running it, and its tools (P073).
28
+ export { fragmentOf, lintContent } from "./check/lint.js";
29
+ export { admitContent, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, } from "./check/tools.js";
24
30
  export { writeClipboard } from "./host/clipboard.js";
25
31
  export { httpLocator, LocateError, servedOrOpaque, } from "./host/locator.js";
26
32
  // Annotations (P053): anchors, what a frame reports, and the host's checks on both.
@@ -9,7 +9,7 @@
9
9
  * server.on("upgrade", porthole.upgrade);
10
10
  * server.listen(8080, () => content.start());
11
11
  */
12
- import type { IncomingMessage, ServerResponse } from "node:http";
12
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
13
13
  import type { Duplex } from "node:stream";
14
14
  import type { ContentHost, HealthProbe } from "../server/host.ts";
15
15
  import type { Access } from "../server/types.ts";
@@ -46,4 +46,29 @@ export declare function nodeHost<V>(content: ContentHost<V>, app: NodeHostOption
46
46
  * of the answer read.
47
47
  */
48
48
  export declare function nodeProbe(): HealthProbe;
49
+ export interface NodeServerOptions {
50
+ /**
51
+ * The content host, or a function giving it when it exists: a host made after the server listens
52
+ * (its content domain names the port `listen(0)` chose, P074). Until it gives one, every request
53
+ * is the app's; the health gate starts when it first does.
54
+ */
55
+ readonly content: ContentHost<unknown> | (() => ContentHost<unknown> | null);
56
+ /**
57
+ * The app, fetch-style (Hono's `app.fetch`, or the app's own handler): every request that
58
+ * isn't the content domain's. Or `request`, a Node listener (Express).
59
+ */
60
+ readonly app?: (request: Request) => Response | Promise<Response>;
61
+ readonly request?: RequestListener;
62
+ readonly upgrade?: UpgradeListener;
63
+ readonly appSocket?: NodeHostOptions["appSocket"];
64
+ /** Whether the app's own requests came over https (behind a TLS edge): their URL's scheme. */
65
+ readonly scheme?: "https" | "http";
66
+ }
67
+ /**
68
+ * The whole Node server (P072): the content domain to Porthole, everything else to the app, its
69
+ * WebSockets included; the health gate started when it listens and stopped when it closes.
70
+ *
71
+ * nodeServer({ content, app: (request) => app.fetch(request) }).listen(8790);
72
+ */
73
+ export declare function nodeServer(options: NodeServerOptions): Server;
49
74
  export {};
@@ -1,6 +1,7 @@
1
- import { request as httpRequest } from "node:http";
1
+ import { createServer as createHttpServer, request as httpRequest } from "node:http";
2
2
  import { request as httpsRequest } from "node:https";
3
3
  import { Readable } from "node:stream";
4
+ import { withoutPortholeCookies } from "../server/proxy.js";
4
5
  /**
5
6
  * The Node request as a fetch `Request`: an absolute-form target kept as it came (P056). `signal`
6
7
  * (`nodeHost` gives one, aborted when the client goes away) lets an upstream stop its work.
@@ -172,6 +173,14 @@ export function nodeHost(content, app) {
172
173
  refuseSocket(socket);
173
174
  }
174
175
  else {
176
+ // The app's socket never sees Porthole's own cookies, as its HTTP requests don't (P072).
177
+ const cookie = withoutPortholeCookies(request.headers.cookie);
178
+ if (cookie === null) {
179
+ delete request.headers.cookie;
180
+ }
181
+ else {
182
+ request.headers.cookie = cookie;
183
+ }
175
184
  appSocket(access, request, socket, head);
176
185
  }
177
186
  }, () => refuseSocket(socket));
@@ -218,3 +227,84 @@ export function nodeProbe() {
218
227
  asked.end();
219
228
  });
220
229
  }
230
+ /**
231
+ * The whole Node server (P072): the content domain to Porthole, everything else to the app, its
232
+ * WebSockets included; the health gate started when it listens and stopped when it closes.
233
+ *
234
+ * nodeServer({ content, app: (request) => app.fetch(request) }).listen(8790);
235
+ */
236
+ export function nodeServer(options) {
237
+ const scheme = options.scheme ?? "http";
238
+ const fromFetch = options.app;
239
+ const request = options.request ??
240
+ (fromFetch === undefined
241
+ ? undefined
242
+ : (incoming, response) => {
243
+ Promise.resolve(fromFetch(toRequest(incoming, scheme))).then((answer) => sendResponse(response, answer), () => {
244
+ if (response.headersSent) {
245
+ response.destroy();
246
+ return;
247
+ }
248
+ response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
249
+ response.end("Something went wrong.");
250
+ });
251
+ });
252
+ if (request === undefined) {
253
+ throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
254
+ }
255
+ const adapters = new WeakMap();
256
+ const started = new WeakSet();
257
+ let listening = false;
258
+ const given = options.content;
259
+ /** The host now (made once, adapted once), started once the server listens. */
260
+ const current = () => {
261
+ const host = typeof given === "function" ? given() : given;
262
+ if (host === null) {
263
+ return null;
264
+ }
265
+ let adapter = adapters.get(host);
266
+ if (adapter === undefined) {
267
+ adapter = nodeHost(host, {
268
+ request,
269
+ ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
270
+ ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
271
+ });
272
+ adapters.set(host, adapter);
273
+ }
274
+ if (listening && !started.has(host)) {
275
+ started.add(host);
276
+ host.start();
277
+ }
278
+ return adapter;
279
+ };
280
+ const server = createHttpServer((incoming, response) => {
281
+ const adapter = current();
282
+ if (adapter === null) {
283
+ request(incoming, response);
284
+ }
285
+ else {
286
+ adapter.request(incoming, response);
287
+ }
288
+ });
289
+ server.on("upgrade", (incoming, socket, head) => {
290
+ const adapter = current();
291
+ if (adapter !== null) {
292
+ adapter.upgrade(incoming, socket, head);
293
+ }
294
+ else if (options.upgrade !== undefined) {
295
+ options.upgrade(incoming, socket, head);
296
+ }
297
+ else {
298
+ refuseSocket(socket);
299
+ }
300
+ });
301
+ server.on("listening", () => {
302
+ listening = true;
303
+ current();
304
+ });
305
+ server.on("close", () => {
306
+ const host = typeof given === "function" ? given() : given;
307
+ host?.close();
308
+ });
309
+ return server;
310
+ }
@@ -1,13 +1,77 @@
1
1
  import { type CSSProperties, type ReactElement, type ReactNode } from "react";
2
2
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
3
- import type { CapabilityHandlers, Confirm, Refusal } from "../bridge/types.ts";
3
+ import type { CapabilityHandler, CapabilityHandlers, Confirm, ConfirmRequest, Refusal } from "../bridge/types.ts";
4
4
  import type { CapabilityName } from "../config/capabilities.ts";
5
5
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
6
6
  import type { FrameOutcome, HostErrorKind } from "../host/types.ts";
7
7
  import type { InstanceLocator, InstanceRef } from "../isolation/types.ts";
8
+ import { type LiveFrames } from "./live.ts";
9
+ import { type CopyNotice } from "./toast.tsx";
10
+ import type { PortholeClient } from "../host/client.ts";
8
11
  /** The height a display holds before it has reported its own. */
9
12
  export declare const PLACEHOLDER_HEIGHT_PX = 96;
13
+ interface PageState {
14
+ readonly live: LiveFrames;
15
+ /** The host kit's client (P072): the locator, configs by kind, links. */
16
+ readonly client?: PortholeClient;
17
+ /** Defaults every frame below takes unless it says its own (P072). */
18
+ readonly scheme?: ColorScheme;
19
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
20
+ readonly themeKey?: string | number;
21
+ /** The provider's handlers as of now (its own over the default `openLink`). */
22
+ readonly handlers?: () => CapabilityHandlers;
23
+ /** Heights displays reported, by display id: a frame mounting again starts at its last. */
24
+ readonly heights: Map<string, number>;
25
+ readonly confirm?: Confirm;
26
+ readonly hostInfo?: {
27
+ readonly name: string;
28
+ readonly version: string;
29
+ };
30
+ readonly nonce?: string;
31
+ /** The provider's locator, read when a frame locates (so an inline one restarts nothing). */
32
+ readonly locate?: InstanceLocator["locate"];
33
+ /** The default `copyText`: copies on the host's page and shows the toast (P052). */
34
+ readonly copyText?: CapabilityHandler<"copyText">;
35
+ }
36
+ /** The provider's page state, for the binding's other components (`PortholeView`). */
37
+ export declare const PortholeContext: import("react").Context<PageState>;
10
38
  export interface PortholeProviderProps {
39
+ /**
40
+ * The host kit's client (`portholeClient`, P072): it locates served frames (unless `locator` is
41
+ * given), and `PortholeView` takes each kind's config and link from it.
42
+ */
43
+ readonly client?: PortholeClient;
44
+ /** The color scheme every frame below shows in, unless it says its own. */
45
+ readonly scheme?: ColorScheme;
46
+ /**
47
+ * The host's live values for the theme variables, for every frame below (`cssVariableTheme`
48
+ * reads them from the page's own CSS variables). Change `themeKey` when they change.
49
+ */
50
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
51
+ readonly themeKey?: string | number;
52
+ /** Handlers every frame below has, under its own (a frame's own win). */
53
+ readonly handlers?: CapabilityHandlers;
54
+ /**
55
+ * How `openLink` opens a link where a frame has no handler of its own: a desktop app's
56
+ * external browser. Default: a new tab, `noopener`.
57
+ */
58
+ readonly openLink?: (url: string) => void;
59
+ /**
60
+ * Shows what a copy button put on the clipboard, in the app's own toast (the words stay
61
+ * Porthole's: `notice`); `copy` copies it again in a click where the first write failed.
62
+ * Omitted: Porthole's `CopyToast`.
63
+ */
64
+ readonly notify?: (notice: CopyNotice, actions: {
65
+ readonly copy: () => Promise<boolean>;
66
+ }) => void;
67
+ /**
68
+ * Draws the confirmation in the app's own dialog, for the request at the head of the queue:
69
+ * Porthole keeps the queue (one question at a time), runs `accept` inside the click, and counts
70
+ * declines. `redirect`: the person took it elsewhere (edited a prompt first, P074): the call
71
+ * doesn't go, and it neither counts toward muting the display nor resets the count. Omitted:
72
+ * Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
73
+ */
74
+ readonly renderConfirm?: (request: ConfirmRequest, answer: ConfirmActions) => ReactNode;
11
75
  /**
12
76
  * Who confirms gated calls for every frame below. Omitted: the default dialog (`ConfirmDialog`).
13
77
  * Pass your own function to replace it.
@@ -26,11 +90,21 @@ export interface PortholeProviderProps {
26
90
  readonly toastClassName?: string;
27
91
  /**
28
92
  * The page's CSP nonce, where its `script-src` is nonce-based: opaque frames inherit the page's
29
- * policy, so their shell carries it (P054).
93
+ * policy, so their shell carries it (P054). `"auto"`: read from the page (a `<meta
94
+ * name="csp-nonce">`, else its first script's nonce).
30
95
  */
31
96
  readonly nonce?: string;
32
97
  readonly children?: ReactNode;
33
98
  }
99
+ /** What an app's own confirmation dialog answers with (`renderConfirm`). */
100
+ export interface ConfirmActions {
101
+ /** Yes: the call goes, run inside this click. */
102
+ readonly accept: () => void;
103
+ /** No: the call doesn't go, and it counts toward muting the display. */
104
+ readonly decline: () => void;
105
+ /** Elsewhere (the person edits the prompt first): the call doesn't go, and doesn't count. */
106
+ readonly redirect: () => void;
107
+ }
34
108
  export declare function PortholeProvider(props: PortholeProviderProps): ReactElement;
35
109
  /** What a placeholder shows: a display not yet running, loading, or stopped for others. */
36
110
  export interface PlaceholderProps {
@@ -54,7 +128,8 @@ export interface PortholeFrameProps {
54
128
  readonly document?: string;
55
129
  /** Domain and external isolation: the instance to show. */
56
130
  readonly instance?: InstanceRef;
57
- readonly scheme: ColorScheme;
131
+ /** The color scheme it shows in. Default: the provider's `scheme`, else light. */
132
+ readonly scheme?: ColorScheme;
58
133
  /** The host's live values for the config's theme variables (from its design tokens). */
59
134
  readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
60
135
  /** Handlers for the declared capabilities (the latest ones are called). */
@@ -140,3 +215,4 @@ export interface PortholeFrameProps {
140
215
  readonly style?: CSSProperties;
141
216
  }
142
217
  export declare function PortholeFrame(props: PortholeFrameProps): ReactElement;
218
+ export {};