@botiverse/porthole 0.2.4 → 0.3.0

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 (75) hide show
  1. package/README.md +14 -9
  2. package/dist/check/check.d.ts +83 -0
  3. package/dist/check/check.js +169 -0
  4. package/dist/check/drivers.d.ts +24 -0
  5. package/dist/check/drivers.js +110 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/lint.d.ts +21 -0
  9. package/dist/check/lint.js +131 -0
  10. package/dist/check/page-source.d.ts +2 -0
  11. package/dist/check/page-source.js +2 -0
  12. package/dist/check/page.d.ts +51 -0
  13. package/dist/check/page.js +150 -0
  14. package/dist/check/tools.d.ts +61 -0
  15. package/dist/check/tools.js +140 -0
  16. package/dist/conformance/host-kit.d.ts +10 -2
  17. package/dist/conformance/host-kit.js +9 -2
  18. package/dist/displays/displays.d.ts +61 -0
  19. package/dist/displays/displays.js +113 -0
  20. package/dist/host/client.d.ts +92 -0
  21. package/dist/host/client.js +259 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.js +6 -0
  24. package/dist/node/index.d.ts +22 -1
  25. package/dist/node/index.js +46 -1
  26. package/dist/react/frame.d.ts +71 -3
  27. package/dist/react/frame.js +120 -19
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.js +1 -0
  30. package/dist/react/view.d.ts +54 -0
  31. package/dist/react/view.js +146 -0
  32. package/dist/server/bootstrap.d.ts +27 -0
  33. package/dist/server/bootstrap.js +63 -0
  34. package/dist/server/host.d.ts +74 -7
  35. package/dist/server/host.js +237 -9
  36. package/dist/server/index.d.ts +4 -2
  37. package/dist/server/index.js +3 -1
  38. package/dist/server/pages.d.ts +19 -0
  39. package/dist/server/pages.js +8 -0
  40. package/dist/server/proxy.d.ts +24 -0
  41. package/dist/server/proxy.js +67 -0
  42. package/dist/server/server.js +14 -1
  43. package/dist/server/types.d.ts +8 -0
  44. package/docs/ADOPTING.md +191 -104
  45. package/docs/DECISIONS.md +146 -0
  46. package/docs/DESIGN.md +58 -0
  47. package/examples/app.mjs +62 -64
  48. package/examples/conformance/page.spec.mjs +23 -0
  49. package/examples/conformance/playwright.config.mjs +1 -1
  50. package/examples/conformance/porthole.spec.mjs +5 -3
  51. package/examples/displays.mjs +19 -0
  52. package/examples/mcp/server.mjs +121 -0
  53. package/package.json +9 -1
  54. package/src/check/check.ts +278 -0
  55. package/src/check/drivers.ts +144 -0
  56. package/src/check/index.ts +15 -0
  57. package/src/check/lint.ts +238 -0
  58. package/src/check/page-source.ts +19 -0
  59. package/src/check/page.ts +204 -0
  60. package/src/check/tools.ts +206 -0
  61. package/src/conformance/host-kit.ts +20 -11
  62. package/src/displays/displays.ts +191 -0
  63. package/src/host/client.ts +364 -0
  64. package/src/index.ts +25 -0
  65. package/src/node/index.ts +66 -2
  66. package/src/react/frame.tsx +191 -33
  67. package/src/react/index.ts +8 -0
  68. package/src/react/view.tsx +232 -0
  69. package/src/server/bootstrap.ts +97 -0
  70. package/src/server/host.ts +331 -15
  71. package/src/server/index.ts +11 -1
  72. package/src/server/pages.ts +28 -0
  73. package/src/server/proxy.ts +86 -0
  74. package/src/server/server.ts +26 -2
  75. package/src/server/types.ts +5 -0
@@ -34,6 +34,7 @@ import type { InstanceLocator, InstanceRef } from "../isolation/types.ts";
34
34
  import { ConfirmDialog } from "./dialog.tsx";
35
35
  import { createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
36
36
  import { CopyToast, type CopyNotice } from "./toast.tsx";
37
+ import type { PortholeClient } from "../host/client.ts";
37
38
 
38
39
  /**
39
40
  * The React binding: a `<PortholeProvider>` near the root owns what is per page (which frames
@@ -49,6 +50,14 @@ export const PLACEHOLDER_HEIGHT_PX = 96;
49
50
 
50
51
  interface PageState {
51
52
  readonly live: LiveFrames;
53
+ /** The host kit's client (P072): the locator, configs by kind, links. */
54
+ readonly client?: PortholeClient;
55
+ /** Defaults every frame below takes unless it says its own (P072). */
56
+ readonly scheme?: ColorScheme;
57
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
58
+ readonly themeKey?: string | number;
59
+ /** The provider's handlers as of now (its own over the default `openLink`). */
60
+ readonly handlers?: () => CapabilityHandlers;
52
61
  /** Heights displays reported, by display id: a frame mounting again starts at its last. */
53
62
  readonly heights: Map<string, number>;
54
63
  readonly confirm?: Confirm;
@@ -65,7 +74,48 @@ const PAGE: PageState = { live: createLiveFrames(), heights: new Map() };
65
74
 
66
75
  const Page = createContext<PageState>(PAGE);
67
76
 
77
+ /** The provider's page state, for the binding's other components (`PortholeView`). */
78
+ export const PortholeContext = Page;
79
+
68
80
  export interface PortholeProviderProps {
81
+ /**
82
+ * The host kit's client (`portholeClient`, P072): it locates served frames (unless `locator` is
83
+ * given), and `PortholeView` takes each kind's config and link from it.
84
+ */
85
+ readonly client?: PortholeClient;
86
+ /** The color scheme every frame below shows in, unless it says its own. */
87
+ readonly scheme?: ColorScheme;
88
+ /**
89
+ * The host's live values for the theme variables, for every frame below (`cssVariableTheme`
90
+ * reads them from the page's own CSS variables). Change `themeKey` when they change.
91
+ */
92
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
93
+ readonly themeKey?: string | number;
94
+ /** Handlers every frame below has, under its own (a frame's own win). */
95
+ readonly handlers?: CapabilityHandlers;
96
+ /**
97
+ * How `openLink` opens a link where a frame has no handler of its own: a desktop app's
98
+ * external browser. Default: a new tab, `noopener`.
99
+ */
100
+ readonly openLink?: (url: string) => void;
101
+ /**
102
+ * Shows what a copy button put on the clipboard, in the app's own toast (the words stay
103
+ * Porthole's: `notice`); `copy` copies it again in a click where the first write failed.
104
+ * Omitted: Porthole's `CopyToast`.
105
+ */
106
+ readonly notify?: (
107
+ notice: CopyNotice,
108
+ actions: { readonly copy: () => Promise<boolean> },
109
+ ) => void;
110
+ /**
111
+ * Draws the confirmation in the app's own dialog, for the request at the head of the queue:
112
+ * Porthole keeps the queue (one question at a time), runs `accept` inside the click, and counts
113
+ * declines. Omitted: Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
114
+ */
115
+ readonly renderConfirm?: (
116
+ request: ConfirmRequest,
117
+ answer: { readonly accept: () => void; readonly decline: () => void },
118
+ ) => ReactNode;
69
119
  /**
70
120
  * Who confirms gated calls for every frame below. Omitted: the default dialog (`ConfirmDialog`).
71
121
  * Pass your own function to replace it.
@@ -81,12 +131,27 @@ export interface PortholeProviderProps {
81
131
  readonly toastClassName?: string;
82
132
  /**
83
133
  * The page's CSP nonce, where its `script-src` is nonce-based: opaque frames inherit the page's
84
- * policy, so their shell carries it (P054).
134
+ * policy, so their shell carries it (P054). `"auto"`: read from the page (a `<meta
135
+ * name="csp-nonce">`, else its first script's nonce).
85
136
  */
86
137
  readonly nonce?: string;
87
138
  readonly children?: ReactNode;
88
139
  }
89
140
 
141
+ /** The page's own nonce: `<meta name="csp-nonce" content>`, else the first `script[nonce]`'s. */
142
+ function pageNonce(): string | undefined {
143
+ if (typeof document === "undefined") {
144
+ return undefined;
145
+ }
146
+ const meta = document.querySelector<HTMLMetaElement>('meta[name="csp-nonce"]')?.content;
147
+ const script = document.querySelector<HTMLScriptElement>("script[nonce]")?.nonce;
148
+ return meta !== undefined && meta !== ""
149
+ ? meta
150
+ : script !== undefined && script !== ""
151
+ ? script
152
+ : undefined;
153
+ }
154
+
90
155
  interface Pending {
91
156
  readonly request: ConfirmRequest;
92
157
  readonly resolve: (answer: ConfirmAnswer) => void;
@@ -114,9 +179,18 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
114
179
  // The default copyText: the host's page writes the clipboard (in the frame's click, which
115
180
  // activated this page too) and shows the person what went on it, or offers to copy it.
116
181
  const [notice, setNotice] = useState<CopyNotice | null>(null);
182
+ const ownNotify = useRef(props.notify);
183
+ useLayoutEffect(() => {
184
+ ownNotify.current = props.notify;
185
+ });
117
186
  const copyText = useCallback<CapabilityHandler<"copyText">>(async ({ text }, context) => {
118
187
  const copied = await writeClipboard(text, globalThis.document);
119
- setNotice({ text, copied, title: context.title });
188
+ const said = { text, copied, title: context.title };
189
+ if (ownNotify.current === undefined) {
190
+ setNotice(said);
191
+ } else {
192
+ ownNotify.current(said, { copy: () => writeClipboard(text, globalThis.document) });
193
+ }
120
194
  return copied;
121
195
  }, []);
122
196
  const closeNotice = useCallback(() => setNotice(null), []);
@@ -127,15 +201,50 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
127
201
  useLayoutEffect(() => {
128
202
  ownLocator.current = props.locator;
129
203
  });
204
+ const ownClient = useRef(props.client);
205
+ useLayoutEffect(() => {
206
+ ownClient.current = props.client;
207
+ });
130
208
  const locate = useCallback<InstanceLocator["locate"]>(
131
209
  (instance, signal) =>
132
- ownLocator.current === undefined
133
- ? Promise.reject(new Error("No locator (PortholeProvider.locator)"))
134
- : ownLocator.current.locate(instance, signal),
210
+ ownLocator.current !== undefined
211
+ ? ownLocator.current.locate(instance, signal)
212
+ : ownClient.current !== undefined
213
+ ? ownClient.current.locate(instance, signal)
214
+ : Promise.reject(new Error("No locator (PortholeProvider.locator or client)")),
135
215
  [],
136
216
  );
137
- const locates = props.locator !== undefined;
138
- const { nonce } = props;
217
+ const locates = props.locator !== undefined || props.client !== undefined;
218
+ // `"auto"`: the page's own nonce, read once.
219
+ const [autoNonce] = useState(() => (props.nonce === "auto" ? pageNonce() : undefined));
220
+ const nonce = props.nonce === "auto" ? autoNonce : props.nonce;
221
+ const { client, scheme, theme, themeKey } = props;
222
+ // openLink without a frame handler: the provider's, or a new tab.
223
+ const ownOpen = useRef(props.openLink);
224
+ useLayoutEffect(() => {
225
+ ownOpen.current = props.openLink;
226
+ });
227
+ const handlers = useMemo<CapabilityHandlers>(
228
+ () => ({
229
+ openLink: ({ url }) => {
230
+ if (ownOpen.current === undefined) {
231
+ globalThis.open?.(url, "_blank", "noopener");
232
+ } else {
233
+ ownOpen.current(url);
234
+ }
235
+ return true;
236
+ },
237
+ }),
238
+ [],
239
+ );
240
+ const ownHandlers = useRef(props.handlers);
241
+ useLayoutEffect(() => {
242
+ ownHandlers.current = props.handlers;
243
+ });
244
+ const merged = useCallback<() => CapabilityHandlers>(
245
+ () => ({ ...handlers, ...ownHandlers.current }),
246
+ [handlers],
247
+ );
139
248
  const value = useMemo<PageState>(
140
249
  () => ({
141
250
  live,
@@ -145,14 +254,47 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
145
254
  ...(hostInfo === undefined ? {} : { hostInfo }),
146
255
  ...(locates ? { locate } : {}),
147
256
  ...(nonce === undefined ? {} : { nonce }),
257
+ ...(client === undefined ? {} : { client }),
258
+ ...(scheme === undefined ? {} : { scheme }),
259
+ ...(theme === undefined ? {} : { theme }),
260
+ ...(themeKey === undefined ? {} : { themeKey }),
261
+ handlers: merged,
148
262
  }),
149
- [live, heights, confirm, copyText, hostInfo, locates, locate, nonce],
263
+ [
264
+ live,
265
+ heights,
266
+ confirm,
267
+ copyText,
268
+ hostInfo,
269
+ locates,
270
+ locate,
271
+ nonce,
272
+ client,
273
+ scheme,
274
+ theme,
275
+ themeKey,
276
+ merged,
277
+ ],
150
278
  );
151
279
  const current = queue[0] ?? null;
152
280
  return (
153
281
  <Page.Provider value={value}>
154
282
  {props.children}
155
- {props.confirm === undefined ? (
283
+ {props.confirm === undefined && props.renderConfirm !== undefined && current !== null
284
+ ? props.renderConfirm(current.request, {
285
+ accept: () => {
286
+ // Inside the app's own click: the effect is the person's (a window it opens).
287
+ current.proceed();
288
+ current.resolve("accepted");
289
+ setQueue((waiting) => waiting.slice(1));
290
+ },
291
+ decline: () => {
292
+ current.resolve("declined");
293
+ setQueue((waiting) => waiting.slice(1));
294
+ },
295
+ })
296
+ : null}
297
+ {props.confirm === undefined && props.renderConfirm === undefined ? (
156
298
  <ConfirmDialog
157
299
  request={current?.request ?? null}
158
300
  {...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName })}
@@ -166,17 +308,19 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
166
308
  }}
167
309
  />
168
310
  ) : null}
169
- <CopyToast
170
- notice={notice}
171
- {...(props.toastClassName === undefined ? {} : { className: props.toastClassName })}
172
- onClose={closeNotice}
173
- onCopy={(failed) => {
174
- // A click on the host's own page: the write has the gesture it needs now.
175
- void writeClipboard(failed.text, globalThis.document).then((copied) =>
176
- setNotice({ ...failed, copied }),
177
- );
178
- }}
179
- />
311
+ {props.notify !== undefined ? null : (
312
+ <CopyToast
313
+ notice={notice}
314
+ {...(props.toastClassName === undefined ? {} : { className: props.toastClassName })}
315
+ onClose={closeNotice}
316
+ onCopy={(failed) => {
317
+ // A click on the host's own page: the write has the gesture it needs now.
318
+ void writeClipboard(failed.text, globalThis.document).then((copied) =>
319
+ setNotice({ ...failed, copied }),
320
+ );
321
+ }}
322
+ />
323
+ )}
180
324
  </Page.Provider>
181
325
  );
182
326
  }
@@ -204,7 +348,8 @@ export interface PortholeFrameProps {
204
348
  readonly document?: string;
205
349
  /** Domain and external isolation: the instance to show. */
206
350
  readonly instance?: InstanceRef;
207
- readonly scheme: ColorScheme;
351
+ /** The color scheme it shows in. Default: the provider's `scheme`, else light. */
352
+ readonly scheme?: ColorScheme;
208
353
  /** The host's live values for the config's theme variables (from its design tokens). */
209
354
  readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
210
355
  /** Handlers for the declared capabilities (the latest ones are called). */
@@ -437,7 +582,10 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
437
582
  const [ready, setReady] = useState(false);
438
583
  // The height this display started at: later reports don't make it start again.
439
584
  const [startHeight] = useState(initialHeightPx);
440
- const { document: view, content, partial, scheme } = frame;
585
+ const { document: view, content, partial } = frame;
586
+ const scheme = frame.scheme ?? page.scheme ?? "light";
587
+ // A run's content errors, told once each (a loop throwing the same error says it once).
588
+ const told = useRef(new Set<string>());
441
589
  // By value: a config or instance made inline (each render) is the same display.
442
590
  const config = useByValue(frame.config);
443
591
  const instance = useByValue(frame.instance);
@@ -458,9 +606,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
458
606
  frame.onResize?.(size);
459
607
  return;
460
608
  }
461
- case "contentError":
462
- frame.onContentError?.((detail as DisplayEvents["contentError"]).message);
609
+ case "contentError": {
610
+ const { message } = detail as DisplayEvents["contentError"];
611
+ if (!told.current.has(message)) {
612
+ told.current.add(message);
613
+ frame.onContentError?.(message);
614
+ }
463
615
  return;
616
+ }
464
617
  case "hostError":
465
618
  frame.onHostError?.(detail as DisplayEvents["hostError"]);
466
619
  return;
@@ -503,14 +656,19 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
503
656
  displayId: latest().displayId,
504
657
  title: latest().title,
505
658
  });
506
- // The handlers present now (a declared one must be), each calling the latest prop's.
659
+ // The handlers present now (a declared one must be), each calling the latest prop's, else
660
+ // the provider's (P072).
507
661
  const handlers: Record<string, AnyHandler> = {};
508
- for (const name of Object.keys(first.handlers ?? {})) {
662
+ const declared = new Set(Object.keys(config.capabilities));
663
+ for (const name of new Set([
664
+ ...Object.keys(first.handlers ?? {}),
665
+ ...Object.keys(page.handlers?.() ?? {}).filter((each) => declared.has(each)),
666
+ ])) {
509
667
  handlers[name] = (args, context) =>
510
- (latest().handlers as Record<string, AnyHandler | undefined> | undefined)?.[name]?.(
511
- args,
512
- named(context),
513
- );
668
+ (
669
+ (latest().handlers as Record<string, AnyHandler | undefined> | undefined)?.[name] ??
670
+ (page.handlers?.() as Record<string, AnyHandler | undefined> | undefined)?.[name]
671
+ )?.(args, named(context));
514
672
  }
515
673
  // Copy buttons without a handler of the host's: the provider's, which shows a toast.
516
674
  if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
@@ -534,14 +692,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
534
692
  ),
535
693
  }
536
694
  : {}),
537
- theme: (each) => latest().theme?.(each) ?? {},
695
+ theme: (each) => (latest().theme ?? page.theme)?.(each) ?? {},
538
696
  ...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
539
697
  ...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
540
698
  ...(page.nonce === undefined ? {} : { nonce: page.nonce }),
541
699
  }).mount(container, {
542
700
  displayId: first.displayId,
543
701
  title: first.title,
544
- scheme: first.scheme,
702
+ scheme: first.scheme ?? page.scheme ?? "light",
545
703
  initialHeightPx: startHeight,
546
704
  ...(view === undefined ? {} : { document: view }),
547
705
  ...(instance === undefined ? {} : { instance }),
@@ -638,7 +796,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
638
796
  handle.current?.setTheme(scheme);
639
797
  }
640
798
  }, [scheme, mountScheme]);
641
- const { themeKey } = frame;
799
+ const themeKey = frame.themeKey ?? page.themeKey;
642
800
  const [mountThemeKey] = useState(themeKey);
643
801
  useEffect(() => {
644
802
  if (themeKey !== undefined && themeKey !== mountThemeKey) {
@@ -17,6 +17,14 @@ export {
17
17
  type PortholeProviderProps,
18
18
  } from "./frame.tsx";
19
19
  export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
20
+ export {
21
+ cssVariableTheme,
22
+ PortholeView,
23
+ usePortholeLink,
24
+ useRunAgain,
25
+ type PortholeFallbackProps,
26
+ type PortholeViewProps,
27
+ } from "./view.tsx";
20
28
  export {
21
29
  CopyToast,
22
30
  TOAST_CHARS,
@@ -0,0 +1,232 @@
1
+ import {
2
+ useCallback,
3
+ useContext,
4
+ useEffect,
5
+ useState,
6
+ useSyncExternalStore,
7
+ type ReactElement,
8
+ type ReactNode,
9
+ } from "react";
10
+ import type { ColorScheme } from "../config/schema.ts";
11
+ import { frameFallback, type FrameFallback, type PortholeClient } from "../host/client.ts";
12
+ import type { FrameOutcome } from "../host/types.ts";
13
+ import type { InstanceRef } from "../isolation/types.ts";
14
+ import { PortholeFrame, PortholeContext, type PortholeFrameProps } from "./frame.tsx";
15
+
16
+ /**
17
+ * The host kit's React side (P072): a display by its kind, served or opaque as the server says
18
+ * now, located through the provider's client, with a fallback when its frame shows nothing.
19
+ *
20
+ * <PortholeProvider client={porthole} scheme={mode}>
21
+ * <PortholeView display="page" instance={instance} content={opaqueCopy}
22
+ * fallback={({ title, message, link, retry }) => <Fallback … />} />
23
+ * </PortholeProvider>
24
+ */
25
+
26
+ /** What a fallback is drawn from: why the frame showed nothing, its clean address, a retry. */
27
+ export interface PortholeFallbackProps extends FrameFallback {
28
+ /** The instance's clean address (its "open in a new tab"), or null. */
29
+ readonly link: string | null;
30
+ /** Shows the display again. */
31
+ readonly retry: () => void;
32
+ }
33
+
34
+ export interface PortholeViewProps extends Omit<
35
+ PortholeFrameProps,
36
+ "config" | "instance" | "content" | "fill"
37
+ > {
38
+ /** The display kind (`defineDisplays`). */
39
+ readonly display: string;
40
+ /** The instance to show while frames are served. */
41
+ readonly instance?: InstanceRef;
42
+ /**
43
+ * The content: a served shell's to draw, and what an opaque frame shows while frames aren't
44
+ * served (a stored page's HTML). Without it, a served-only display shows the fallback then.
45
+ */
46
+ readonly content?: string;
47
+ /** Drawn instead of the frame when it showed nothing. Default: a line and a link. */
48
+ readonly fallback?: (props: PortholeFallbackProps) => ReactNode;
49
+ /** Drawn while the server's meta isn't known yet. */
50
+ readonly pending?: ReactNode;
51
+ }
52
+
53
+ function useClient(): PortholeClient {
54
+ const client = useContext(PortholeContext).client;
55
+ if (client === undefined) {
56
+ throw new Error("PortholeView needs a PortholeProvider with a client (portholeClient)");
57
+ }
58
+ return client;
59
+ }
60
+
61
+ /** The client's meta, as a React value (re-renders when frames start or stop being served). */
62
+ function useMeta(client: PortholeClient) {
63
+ return useSyncExternalStore(
64
+ (listener) => client.subscribe(listener),
65
+ () => client.meta(),
66
+ () => null,
67
+ );
68
+ }
69
+
70
+ function DefaultFallback({ title, message, link }: PortholeFallbackProps): ReactElement {
71
+ return (
72
+ <div data-porthole-fallback="" role="status" style={{ padding: 16 }}>
73
+ <strong>{title}</strong> <span>{message}</span>{" "}
74
+ {link === null ? null : (
75
+ <a href={link} target="_blank" rel="noopener">
76
+ Open in a new tab
77
+ </a>
78
+ )}
79
+ </div>
80
+ );
81
+ }
82
+
83
+ export function PortholeView(props: PortholeViewProps): ReactElement | null {
84
+ const client = useClient();
85
+ const meta = useMeta(client);
86
+ const { display, instance, content, fallback, pending, onOutcome, ...frame } = props;
87
+ const [failed, setFailed] = useState<FrameFallback | null>(null);
88
+ const [generation, setGeneration] = useState(0);
89
+ const [link, setLink] = useState<string | null>(null);
90
+ const kind = display;
91
+ const config = client.config(kind);
92
+ const served = meta?.served === true && config?.isolation !== "opaque";
93
+ const url = config?.mode === "url";
94
+
95
+ const retry = useCallback(() => {
96
+ setFailed(null);
97
+ setGeneration((each) => each + 1);
98
+ }, []);
99
+ useEffect(() => {
100
+ if (failed === null || instance === undefined) {
101
+ return;
102
+ }
103
+ let live = true;
104
+ void client.link(instance).then((found) => {
105
+ if (live) {
106
+ setLink(found);
107
+ }
108
+ });
109
+ return () => {
110
+ live = false;
111
+ };
112
+ }, [client, failed, instance]);
113
+
114
+ if (meta === null || config === null) {
115
+ // Not known yet; or a url kind while frames aren't served.
116
+ if (meta !== null && config === null) {
117
+ const said: FrameFallback = {
118
+ kind: "failed",
119
+ title: "This can't be shown now",
120
+ message: "Its content isn't being served.",
121
+ };
122
+ return <>{(fallback ?? DefaultFallback)({ ...said, link: null, retry })}</>;
123
+ }
124
+ return <>{pending ?? null}</>;
125
+ }
126
+ if (!served && content === undefined) {
127
+ const said: FrameFallback = {
128
+ kind: "failed",
129
+ title: "This can't be shown now",
130
+ message: "Its content isn't being served.",
131
+ };
132
+ return <>{(fallback ?? DefaultFallback)({ ...said, link: null, retry })}</>;
133
+ }
134
+ if (failed !== null) {
135
+ return <>{(fallback ?? DefaultFallback)({ ...failed, link, retry })}</>;
136
+ }
137
+ return (
138
+ <PortholeFrame
139
+ {...frame}
140
+ config={config}
141
+ generation={(frame.generation ?? 0) + generation}
142
+ {...(served && instance !== undefined ? { instance } : {})}
143
+ {...(content === undefined ? {} : { content })}
144
+ onOutcome={(outcome: FrameOutcome) => {
145
+ onOutcome?.(outcome);
146
+ const said = frameFallback(outcome, { url });
147
+ if (said !== null) {
148
+ setFailed(said);
149
+ }
150
+ }}
151
+ />
152
+ );
153
+ }
154
+
155
+ /** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
156
+ export function usePortholeLink(instance: InstanceRef | null): {
157
+ readonly link: string | null;
158
+ readonly open: () => void;
159
+ readonly copy: () => Promise<boolean>;
160
+ } {
161
+ const client = useClient();
162
+ const key = instance === null ? "" : JSON.stringify(instance);
163
+ // The address found for the instance it was found for: another instance shows none until its own.
164
+ const [found, setFound] = useState<{ readonly key: string; readonly link: string | null }>(
165
+ () => ({ key, link: instance === null ? null : client.knownLink(instance) }),
166
+ );
167
+ useEffect(() => {
168
+ if (key === "") {
169
+ return;
170
+ }
171
+ let live = true;
172
+ void client.link(JSON.parse(key) as InstanceRef).then((each) => {
173
+ if (live) {
174
+ setFound({ key, link: each });
175
+ }
176
+ });
177
+ return () => {
178
+ live = false;
179
+ };
180
+ }, [client, key]);
181
+ const link = found.key === key ? found.link : null;
182
+ const open = useCallback(() => {
183
+ if (key !== "") {
184
+ client.openInTab(JSON.parse(key) as InstanceRef);
185
+ }
186
+ }, [client, key]);
187
+ const copy = useCallback(async () => {
188
+ if (link === null) {
189
+ return false;
190
+ }
191
+ try {
192
+ await navigator.clipboard.writeText(link);
193
+ return true;
194
+ } catch {
195
+ return false;
196
+ }
197
+ }, [link]);
198
+ return { link, open, copy };
199
+ }
200
+
201
+ /**
202
+ * Theme values read from the page's own CSS variables (P072): `tokens` maps each of Porthole's
203
+ * theme variables to the app's (`{ "--color-text-primary": "--app-fg" }`). Read when a frame asks,
204
+ * so pass `themeKey` to re-read after the app's theme changes.
205
+ */
206
+ export function cssVariableTheme(
207
+ tokens: Readonly<Record<string, string>>,
208
+ root?: () => Element,
209
+ ): (scheme: ColorScheme) => Record<string, string> {
210
+ return () => {
211
+ const element = root?.() ?? globalThis.document?.documentElement;
212
+ if (element === undefined) {
213
+ return {};
214
+ }
215
+ const style = getComputedStyle(element);
216
+ const values: Record<string, string> = {};
217
+ for (const [ours, theirs] of Object.entries(tokens)) {
218
+ const value = style.getPropertyValue(theirs).trim();
219
+ if (value !== "") {
220
+ values[ours] = value;
221
+ }
222
+ }
223
+ return values;
224
+ };
225
+ }
226
+
227
+ /** A display's "run again": pass `generation` to the frame, call `runAgain` from a button. */
228
+ export function useRunAgain(): { readonly generation: number; readonly runAgain: () => void } {
229
+ const [generation, setGeneration] = useState(0);
230
+ const runAgain = useCallback(() => setGeneration((each) => each + 1), []);
231
+ return { generation, runAgain };
232
+ }
@@ -0,0 +1,97 @@
1
+ import { createContentHost, type ContentHost, type ContentHostOptions } from "./host.ts";
2
+
3
+ /**
4
+ * The host kit on a runtime that hands each request its settings (Cloudflare Workers' `env`)
5
+ * (P072): one content host per settings object, made on first use. Settings that can't be served
6
+ * fail closed: every request is a plain 503 naming why, told to the log once.
7
+ *
8
+ * const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, secret: env.PORTHOLE_SECRET, … }));
9
+ * export default {
10
+ * async fetch(request, env) {
11
+ * return (await porthole.fetch(request, env)) ?? app.fetch(request, env);
12
+ * },
13
+ * };
14
+ */
15
+
16
+ export interface ContentHostFor<E extends object, V> {
17
+ /** The content host for these settings; throws, naming why, where they can't be served. */
18
+ host(env: E): ContentHost<V>;
19
+ /**
20
+ * The content domain's answer for a request (`ContentHost.fetch`), or null for the app's own;
21
+ * a plain 503 for every request while the settings can't be served.
22
+ */
23
+ fetch(request: Request, env: E): Promise<Response | null>;
24
+ /** `ContentHost.routes`, for these settings. */
25
+ routes(
26
+ request: Request,
27
+ env: E,
28
+ viewerOf: (request: Request) => V | null | Promise<V | null>,
29
+ ): Promise<Response | null>;
30
+ }
31
+
32
+ /** Why the content host can't be made for some settings. */
33
+ class Unservable extends Error {
34
+ override readonly name = "ContentHostUnservable";
35
+ }
36
+
37
+ export function contentHostFor<E extends object, V>(
38
+ build: (env: E) => ContentHostOptions<V>,
39
+ options: { readonly log?: (problem: string) => void } = {},
40
+ ): ContentHostFor<E, V> {
41
+ const made = new WeakMap<E, ContentHost<V> | Unservable>();
42
+ const hostOf = (env: E): ContentHost<V> => {
43
+ let found = made.get(env);
44
+ if (found === undefined) {
45
+ try {
46
+ found = createContentHost(build(env));
47
+ } catch (error) {
48
+ found = new Unservable(
49
+ `the content domain can't be served: ${error instanceof Error ? error.message : String(error)}`,
50
+ );
51
+ (options.log ?? (() => {}))(found.message);
52
+ }
53
+ made.set(env, found);
54
+ }
55
+ if (found instanceof Unservable) {
56
+ throw found;
57
+ }
58
+ return found;
59
+ };
60
+ const unavailable = (error: Unservable) =>
61
+ new Response(`Unavailable: ${error.message}.`, {
62
+ status: 503,
63
+ headers: {
64
+ "content-type": "text/plain; charset=utf-8",
65
+ "cache-control": "no-store",
66
+ "x-content-type-options": "nosniff",
67
+ "x-robots-tag": "noindex, nofollow",
68
+ },
69
+ });
70
+ return {
71
+ host: hostOf,
72
+ async fetch(request, env) {
73
+ let host: ContentHost<V>;
74
+ try {
75
+ host = hostOf(env);
76
+ } catch (error) {
77
+ if (error instanceof Unservable) {
78
+ return unavailable(error);
79
+ }
80
+ throw error;
81
+ }
82
+ return host.fetch(request);
83
+ },
84
+ async routes(request, env, viewerOf) {
85
+ let host: ContentHost<V>;
86
+ try {
87
+ host = hostOf(env);
88
+ } catch (error) {
89
+ if (error instanceof Unservable) {
90
+ return unavailable(error);
91
+ }
92
+ throw error;
93
+ }
94
+ return host.routes(viewerOf)(request);
95
+ },
96
+ };
97
+ }