@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
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A Playwright reporter that says why each conformance case was skipped (P074): the list and line
3
+ * reporters show a skipped case as "-" with no reason, and an inapplicable probe ("the page's own
4
+ * CSP, which an opaque frame inherits, blocks … (connect-src)") is a fact worth reading.
5
+ *
6
+ * reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
7
+ */
8
+ export default class SkipReasons {
9
+ #skipped = new Map();
10
+ printsToStdio() {
11
+ return true;
12
+ }
13
+ onTestEnd(test, result) {
14
+ if (result.status !== "skipped") {
15
+ return;
16
+ }
17
+ const reason = [...result.annotations, ...test.annotations].find((each) => each.type === "skip" && each.description !== undefined && each.description !== "")?.description ?? "skipped";
18
+ const title = test.title.length > 90 ? `${test.title.slice(0, 89)}…` : test.title;
19
+ this.#skipped.set(`${title}\u0000${reason}`, `${title}: ${reason}`);
20
+ }
21
+ onEnd(_result) {
22
+ if (this.#skipped.size === 0) {
23
+ return;
24
+ }
25
+ const lines = [...this.#skipped.values()].toSorted();
26
+ process.stdout.write(`\nSkipped (${lines.length}), and why:\n${lines.map((each) => ` - ${each}`).join("\n")}\n`);
27
+ }
28
+ }
@@ -1,6 +1,6 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
2
  import type { Displays } from "../displays/displays.ts";
3
- import type { InstanceLocator, InstanceRef } from "../isolation/types.ts";
3
+ import type { FrameLocation, InstanceLocator, InstanceRef } from "../isolation/types.ts";
4
4
  import type { FrameOutcome } from "./types.ts";
5
5
  /**
6
6
  * The client half of the host kit (P072): what the app's page needs from its server's Porthole
@@ -39,42 +39,60 @@ export interface PortholeClientOptions<N extends string> {
39
39
  readonly handoff?: boolean;
40
40
  readonly fetch?: typeof fetch;
41
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
+ */
42
46
  export interface PortholeClient<N extends string = string> extends InstanceLocator {
43
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>;
44
50
  /** The meta as last fetched, or null before it is known. */
45
- meta(): ContentClientMeta | null;
51
+ meta(this: void): ContentClientMeta | null;
46
52
  /** Called when the meta changes (frames served or not). */
47
- subscribe(listener: () => void): () => void;
53
+ subscribe(this: void, listener: () => void): () => void;
48
54
  /** Fetches the meta again. */
49
- refresh(): Promise<ContentClientMeta | null>;
55
+ refresh(this: void): Promise<ContentClientMeta | null>;
50
56
  /**
51
57
  * The config a kind shows under now: served while frames are served, else opaque (a url kind:
52
58
  * null). Null until the meta is known, so a frame never starts opaque and then restarts served.
53
59
  */
54
- config(kind: N): PortholeConfig | null;
60
+ config(this: void, kind: N): PortholeConfig | null;
55
61
  /** The same, for an instance's kind. */
56
- configFor(instance: InstanceRef): PortholeConfig | null;
62
+ configFor(this: void, instance: InstanceRef): PortholeConfig | null;
57
63
  /** An instance's clean address (`entry.pathOf` on the server), or null. */
58
- link(instance: InstanceRef): Promise<string | null>;
64
+ link(this: void, instance: InstanceRef): Promise<string | null>;
59
65
  /** The clean address if already known (from locating the instance), for rendering. */
60
- knownLink(instance: InstanceRef): string | null;
66
+ knownLink(this: void, instance: InstanceRef): string | null;
61
67
  /**
62
68
  * Opens an instance's clean address in a new tab: call it in the click (the tab opens at once,
63
69
  * then goes to the address).
64
70
  */
65
- openInTab(instance: InstanceRef): void;
71
+ openInTab(this: void, instance: InstanceRef): void;
66
72
  /** Hands the signed-in viewer to the authorize route (`entry.handoff`); true if it took. */
67
- handoff(): Promise<boolean>;
68
- /** `next` if it is this server's authorize route (after a sign-in), else null (`entryTarget`). */
69
- entryTarget(next: unknown): string | null;
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;
70
81
  /** Stops refreshing the handoff. */
71
- close(): void;
82
+ close(this: void): void;
72
83
  }
73
84
  /**
74
85
  * Whether a sign-in's `next` is the app's authorize route (P072): the open-redirect guard a
75
- * single-page app runs before going on to it. Null for anything else.
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.
76
92
  */
77
- export declare function entryTarget(next: unknown, authorizeUrl: string): string | null;
93
+ export declare function entryTarget(next: unknown, authorizeUrl: string, options?: {
94
+ readonly app?: boolean;
95
+ }): string | null;
78
96
  export declare function portholeClient<N extends string>(options: PortholeClientOptions<N>): PortholeClient<N>;
79
97
  /** What a frame that showed nothing should offer the person, by its outcome (P072). */
80
98
  export interface FrameFallback {
@@ -2,9 +2,14 @@ import { LocateError } from "./locator.js";
2
2
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3
3
  /**
4
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.
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.
6
11
  */
7
- export function entryTarget(next, authorizeUrl) {
12
+ export function entryTarget(next, authorizeUrl, options = {}) {
8
13
  if (typeof next !== "string" || next.length > 8_192) {
9
14
  return null;
10
15
  }
@@ -17,10 +22,17 @@ export function entryTarget(next, authorizeUrl) {
17
22
  catch {
18
23
  return null;
19
24
  }
20
- return target.origin === route.origin &&
25
+ if (target.origin === route.origin &&
21
26
  target.pathname === route.pathname &&
22
27
  target.hash === "" &&
23
- target.searchParams.has("state")
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
24
36
  ? target.href
25
37
  : null;
26
38
  }
@@ -150,31 +162,34 @@ export function portholeClient(options) {
150
162
  window.addEventListener("focus", fresh);
151
163
  document.addEventListener("visibilitychange", fresh);
152
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
+ };
153
177
  return {
154
178
  displays: options.displays,
155
179
  meta: () => meta,
156
- subscribe(listener) {
180
+ subscribe: (listener) => {
157
181
  listeners.add(listener);
158
- return () => listeners.delete(listener);
182
+ return () => {
183
+ listeners.delete(listener);
184
+ };
159
185
  },
160
186
  refresh,
161
187
  config: (kind) => configOf(kind),
162
188
  configFor: (instance) => configOf(options.displays.kindOf(instance)),
163
189
  locate: issue,
164
- async link(instance) {
165
- const key = keyOf(instance);
166
- if (!links.has(key)) {
167
- try {
168
- await issue(instance);
169
- }
170
- catch {
171
- return null;
172
- }
173
- }
174
- return links.get(key) ?? null;
175
- },
190
+ link,
176
191
  knownLink: (instance) => links.get(keyOf(instance)) ?? null,
177
- openInTab(instance) {
192
+ openInTab: (instance) => {
178
193
  // Opened inside the click (a popup blocker lets it), then sent to the address.
179
194
  const tab = typeof window === "undefined" ? null : window.open("about:blank", "_blank");
180
195
  if (tab === null) {
@@ -182,18 +197,18 @@ export function portholeClient(options) {
182
197
  }
183
198
  tab.opener = null;
184
199
  void (async () => {
185
- const link = await this.link(instance);
186
- if (link === null) {
200
+ const found = await link(instance);
201
+ if (found === null) {
187
202
  tab.close();
188
203
  }
189
204
  else {
190
- tab.location.href = link;
205
+ tab.location.href = found;
191
206
  }
192
207
  })();
193
208
  },
194
209
  handoff,
195
- entryTarget: (next) => entryTarget(next, url("/authorize")),
196
- close() {
210
+ entryTarget: (next, given) => entryTarget(next, url("/authorize"), given),
211
+ close: () => {
197
212
  if (watching) {
198
213
  window.removeEventListener("focus", fresh);
199
214
  document.removeEventListener("visibilitychange", fresh);
@@ -47,8 +47,12 @@ export declare function nodeHost<V>(content: ContentHost<V>, app: NodeHostOption
47
47
  */
48
48
  export declare function nodeProbe(): HealthProbe;
49
49
  export interface NodeServerOptions {
50
- /** The content host. */
51
- readonly content: ContentHost<unknown>;
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);
52
56
  /**
53
57
  * The app, fetch-style (Hono's `app.fetch`, or the app's own handler): every request that
54
58
  * isn't the content domain's. Or `request`, a Node listener (Express).
@@ -252,14 +252,59 @@ export function nodeServer(options) {
252
252
  if (request === undefined) {
253
253
  throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
254
254
  }
255
- const porthole = nodeHost(options.content, {
256
- request,
257
- ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
258
- ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
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();
259
308
  });
260
- const server = createHttpServer(porthole.request);
261
- server.on("upgrade", porthole.upgrade);
262
- server.on("listening", () => options.content.start());
263
- server.on("close", () => options.content.close());
264
309
  return server;
265
310
  }
@@ -67,12 +67,11 @@ export interface PortholeProviderProps {
67
67
  /**
68
68
  * Draws the confirmation in the app's own dialog, for the request at the head of the queue:
69
69
  * Porthole keeps the queue (one question at a time), runs `accept` inside the click, and counts
70
- * declines. Omitted: Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
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.)
71
73
  */
72
- readonly renderConfirm?: (request: ConfirmRequest, answer: {
73
- readonly accept: () => void;
74
- readonly decline: () => void;
75
- }) => ReactNode;
74
+ readonly renderConfirm?: (request: ConfirmRequest, answer: ConfirmActions) => ReactNode;
76
75
  /**
77
76
  * Who confirms gated calls for every frame below. Omitted: the default dialog (`ConfirmDialog`).
78
77
  * Pass your own function to replace it.
@@ -97,6 +96,15 @@ export interface PortholeProviderProps {
97
96
  readonly nonce?: string;
98
97
  readonly children?: ReactNode;
99
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
+ }
100
108
  export declare function PortholeProvider(props: PortholeProviderProps): ReactElement;
101
109
  /** What a placeholder shows: a display not yet running, loading, or stopped for others. */
102
110
  export interface PlaceholderProps {
@@ -147,6 +147,10 @@ export function PortholeProvider(props) {
147
147
  current.resolve("declined");
148
148
  setQueue((waiting) => waiting.slice(1));
149
149
  },
150
+ redirect: () => {
151
+ current.resolve("redirected");
152
+ setQueue((waiting) => waiting.slice(1));
153
+ },
150
154
  })
151
155
  : null, props.confirm === undefined && props.renderConfirm === undefined ? (_jsx(ConfirmDialog, { request: current?.request ?? null, ...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName }), onAnswer: (accepted) => {
152
156
  // A yes runs the effect inside this very click (a window it opens is the person's).
@@ -186,10 +190,13 @@ function rememberedHeight(heights, displayId, aliases) {
186
190
  }
187
191
  export function PortholeFrame(props) {
188
192
  const page = useContext(Page);
193
+ // The provider's registry and heights: stable, unlike the context value, which a scheme flip
194
+ // or a new themeKey renews (an effect keyed on it would let the frame go and make it again, #9).
195
+ const { live, heights } = page;
189
196
  const key = useId();
190
197
  const box = useRef(null);
191
198
  const max = props.config.limits.maxLiveFrames;
192
- const state = useSyncExternalStore((listener) => page.live.subscribe(listener), () => page.live.state(key), () => "waiting");
199
+ const state = useSyncExternalStore((listener) => live.subscribe(listener), () => live.state(key), () => "waiting");
193
200
  const { eager } = props;
194
201
  useEffect(() => {
195
202
  const element = box.current;
@@ -197,38 +204,38 @@ export function PortholeFrame(props) {
197
204
  return;
198
205
  }
199
206
  if (eager === true || typeof IntersectionObserver !== "function") {
200
- page.live.near(key, true);
201
- page.live.admit(key, max);
202
- return () => page.live.release(key);
207
+ live.near(key, true);
208
+ live.admit(key, max);
209
+ return () => live.release(key);
203
210
  }
204
211
  const observer = new IntersectionObserver((entries) => {
205
212
  const entry = entries.at(-1);
206
213
  if (entry === undefined) {
207
214
  return;
208
215
  }
209
- page.live.near(key, entry.isIntersecting);
216
+ live.near(key, entry.isIntersecting);
210
217
  if (entry.isIntersecting) {
211
- page.live.admit(key, max);
218
+ live.admit(key, max);
212
219
  }
213
220
  }, { rootMargin: NEAR_SCREEN });
214
221
  observer.observe(element);
215
222
  return () => {
216
223
  observer.disconnect();
217
- page.live.release(key);
224
+ live.release(key);
218
225
  };
219
- }, [page, key, max, eager]);
220
- const height = rememberedHeight(page.heights, props.displayId, props.aliases);
226
+ }, [live, key, max, eager]);
227
+ const height = rememberedHeight(heights, props.displayId, props.aliases);
221
228
  // A display renamed while it runs (its id settled) keeps its height under its new id.
222
229
  const previousId = useRef(props.displayId);
223
230
  useLayoutEffect(() => {
224
231
  const before = previousId.current;
225
232
  previousId.current = props.displayId;
226
- const kept = page.heights.get(before);
227
- if (before !== props.displayId && kept !== undefined && !page.heights.has(props.displayId)) {
228
- page.heights.set(props.displayId, kept);
233
+ const kept = heights.get(before);
234
+ if (before !== props.displayId && kept !== undefined && !heights.has(props.displayId)) {
235
+ heights.set(props.displayId, kept);
229
236
  }
230
- }, [page, props.displayId]);
231
- const run = () => page.live.admit(key, max);
237
+ }, [heights, props.displayId]);
238
+ const run = () => live.admit(key, max);
232
239
  const placeholder = props.renderPlaceholder ?? DefaultPlaceholder;
233
240
  return (_jsx("div", { ref: box, className: props.className, "data-porthole-display": props.displayId, "data-porthole-state": state, style: {
234
241
  position: "relative",
@@ -260,6 +267,11 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
260
267
  const fills = config.mode === "url" || frame.fill === true || config.layout.kind === "fill";
261
268
  // The latest props, read when the display calls back (never during render).
262
269
  const latest = useEffectEvent(() => frame);
270
+ // The provider's scheme and theme, read when used: a flip or a new themeKey (a new context
271
+ // value) re-themes the running display, never makes it again (#9, P074). What a display is
272
+ // made with comes from the provider's stable parts below.
273
+ const latestPage = useEffectEvent(() => page);
274
+ const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, hostInfo, locate, nonce, } = page;
263
275
  const notify = useEffectEvent((event, detail) => {
264
276
  switch (event) {
265
277
  case "initialized":
@@ -326,36 +338,36 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
326
338
  const declared = new Set(Object.keys(config.capabilities));
327
339
  for (const name of new Set([
328
340
  ...Object.keys(first.handlers ?? {}),
329
- ...Object.keys(page.handlers?.() ?? {}).filter((each) => declared.has(each)),
341
+ ...Object.keys(pageHandlers?.() ?? {}).filter((each) => declared.has(each)),
330
342
  ])) {
331
343
  handlers[name] = (args, context) => (latest().handlers?.[name] ??
332
- page.handlers?.()?.[name])?.(args, named(context));
344
+ pageHandlers?.()?.[name])?.(args, named(context));
333
345
  }
334
346
  // Copy buttons without a handler of the host's: the provider's, which shows a toast.
335
347
  if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
336
- const fallback = page.copyText;
348
+ const fallback = pageCopyText;
337
349
  if (fallback !== undefined) {
338
350
  handlers.copyText = (args, context) => fallback(args, named(context));
339
351
  }
340
352
  }
341
- const asks = first.confirm !== undefined || page.confirm !== undefined;
353
+ const asks = first.confirm !== undefined || pageConfirm !== undefined;
342
354
  let display;
343
355
  try {
344
356
  display = createHost(config, {
345
357
  handlers,
346
358
  ...(asks
347
359
  ? {
348
- confirm: (request, proceed) => (latest().confirm ?? page.confirm ?? (() => Promise.resolve(false)))({ ...request, display: { id: latest().displayId, title: latest().title } }, proceed),
360
+ confirm: (request, proceed) => (latest().confirm ?? pageConfirm ?? (() => Promise.resolve(false)))({ ...request, display: { id: latest().displayId, title: latest().title } }, proceed),
349
361
  }
350
362
  : {}),
351
- theme: (each) => (latest().theme ?? page.theme)?.(each) ?? {},
352
- ...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
353
- ...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
354
- ...(page.nonce === undefined ? {} : { nonce: page.nonce }),
363
+ theme: (each) => (latest().theme ?? latestPage().theme)?.(each) ?? {},
364
+ ...(hostInfo === undefined ? {} : { hostInfo }),
365
+ ...(locate === undefined ? {} : { locator: { locate } }),
366
+ ...(nonce === undefined ? {} : { nonce }),
355
367
  }).mount(container, {
356
368
  displayId: first.displayId,
357
369
  title: first.title,
358
- scheme: first.scheme ?? page.scheme ?? "light",
370
+ scheme: first.scheme ?? latestPage().scheme ?? "light",
359
371
  initialHeightPx: startHeight,
360
372
  ...(view === undefined ? {} : { document: view }),
361
373
  ...(instance === undefined ? {} : { instance }),
@@ -392,9 +404,22 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
392
404
  display.destroy();
393
405
  handle.current = null;
394
406
  };
395
- // A new display only for a new config, document, instance or page (or generation, by key);
396
- // content, theme, handlers, id and title are fed to the running one.
397
- }, [config, view, instance, page, startHeight, fills]);
407
+ // A new display only for a new config, document or instance, or what the provider makes
408
+ // displays with (its nonce, hostInfo by value, whether it locates or confirms; generation, by
409
+ // key). Content, scheme, theme, handlers, id and title are fed to the running one.
410
+ }, [
411
+ config,
412
+ view,
413
+ instance,
414
+ startHeight,
415
+ fills,
416
+ pageHandlers,
417
+ pageCopyText,
418
+ pageConfirm,
419
+ hostInfo,
420
+ locate,
421
+ nonce,
422
+ ]);
398
423
  useEffect(() => {
399
424
  if (content !== undefined) {
400
425
  handle.current?.setContent(content, { partial: partial === true });
@@ -453,6 +478,21 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
453
478
  handle.current?.refreshTheme();
454
479
  }
455
480
  }, [themeKey, mountThemeKey]);
481
+ // A new theme function (tokens a host passes inline): its values reach the running display
482
+ // where they changed for the scheme it shows (a flip re-reads them itself), P074.
483
+ const themeOf = frame.theme ?? page.theme;
484
+ const themed = useRef(null);
485
+ useEffect(() => {
486
+ if (themeOf === undefined) {
487
+ return;
488
+ }
489
+ const now = `${scheme}\n${JSON.stringify(themeOf(scheme))}`;
490
+ const before = themed.current;
491
+ themed.current = now;
492
+ if (before !== null && before !== now && before.startsWith(`${scheme}\n`)) {
493
+ handle.current?.refreshTheme();
494
+ }
495
+ }, [themeOf, scheme]);
456
496
  return (_jsxs("div", { "data-porthole-ready": String(ready), style: {
457
497
  position: "relative",
458
498
  // A url-mode app fills the frame's box (give PortholeFrame a height); the rest size to content.
@@ -8,7 +8,7 @@
8
8
  * theme={tokensFor} onError={report} />
9
9
  * </PortholeProvider>
10
10
  */
11
- export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type PortholeProviderProps, } from "./frame.tsx";
11
+ export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type ConfirmActions, type PortholeProviderProps, } from "./frame.tsx";
12
12
  export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
13
13
  export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, type PortholeFallbackProps, type PortholeViewProps, } from "./view.tsx";
14
14
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, type CopyNotice, type CopyToastProps, } from "./toast.tsx";
@@ -10,8 +10,13 @@ function useClient() {
10
10
  return client;
11
11
  }
12
12
  /** The client's meta, as a React value (re-renders when frames start or stop being served). */
13
+ /**
14
+ * The client's meta. On the server too (P074): a client made with the meta it will start with
15
+ * (`portholeClient({ meta })`) renders the frame's placeholder or the fallback there, and the
16
+ * page hydrates from the same.
17
+ */
13
18
  function useMeta(client) {
14
- return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => null);
19
+ return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => client.meta());
15
20
  }
16
21
  function DefaultFallback({ title, message, link }) {
17
22
  return (_jsxs("div", { "data-porthole-fallback": "", role: "status", style: { padding: 16 }, children: [_jsx("strong", { children: title }), " ", _jsx("span", { children: message }), " ", link === null ? null : (_jsx("a", { href: link, target: "_blank", rel: "noopener", children: "Open in a new tab" }))] }));
@@ -154,7 +154,8 @@ export interface EntryOptions<V> {
154
154
  */
155
155
  readonly at: (scope: string, path: string, viewer: V | null, request: Request) => Awaitable<InstanceRef | null | undefined>;
156
156
  /**
157
- * The app's own sign-in, which comes back to `returnTo` (the authorize URL) once signed in.
157
+ * The app's own sign-in, which comes back to `returnTo` (the authorize URL, as `authorizeUrl`
158
+ * names the app, with the entry's state) once signed in.
158
159
  * Only ever on a tab: in a frame, the person is asked to open a new tab instead. `entry` is the
159
160
  * address being opened, decoded (P070).
160
161
  */
@@ -169,9 +170,10 @@ export interface EntryOptions<V> {
169
170
  };
170
171
  /**
171
172
  * The clean path of an instance (the reverse of `at`), or null: `issue` then answers its clean
172
- * address as `link` (P072), for "open in a new tab" and "copy link".
173
+ * address as `link` (P072), for "open in a new tab" and "copy link". It may look it up (a
174
+ * promise, P074); where it fails, the frame comes without a link.
173
175
  */
174
- readonly pathOf?: (instance: InstanceRef) => string | null;
176
+ readonly pathOf?: (instance: InstanceRef, request: Request) => Awaitable<string | null>;
175
177
  /**
176
178
  * A viewer handoff, for an app whose page authenticates with a token rather than a cookie
177
179
  * (P072): `POST <prefix>/handoff`, made with the app's own credential, leaves a short-lived key