@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
@@ -18,6 +18,21 @@ export const PLACEHOLDER_HEIGHT_PX = 96;
18
18
  /** Without a provider: one registry for the page, and no one to confirm (gated calls refused). */
19
19
  const PAGE = { live: createLiveFrames(), heights: new Map() };
20
20
  const Page = createContext(PAGE);
21
+ /** The provider's page state, for the binding's other components (`PortholeView`). */
22
+ export const PortholeContext = Page;
23
+ /** The page's own nonce: `<meta name="csp-nonce" content>`, else the first `script[nonce]`'s. */
24
+ function pageNonce() {
25
+ if (typeof document === "undefined") {
26
+ return undefined;
27
+ }
28
+ const meta = document.querySelector('meta[name="csp-nonce"]')?.content;
29
+ const script = document.querySelector("script[nonce]")?.nonce;
30
+ return meta !== undefined && meta !== ""
31
+ ? meta
32
+ : script !== undefined && script !== ""
33
+ ? script
34
+ : undefined;
35
+ }
21
36
  export function PortholeProvider(props) {
22
37
  const live = useMemo(() => createLiveFrames(), []);
23
38
  const heights = useMemo(() => new Map(), []);
@@ -33,9 +48,19 @@ export function PortholeProvider(props) {
33
48
  // The default copyText: the host's page writes the clipboard (in the frame's click, which
34
49
  // activated this page too) and shows the person what went on it, or offers to copy it.
35
50
  const [notice, setNotice] = useState(null);
51
+ const ownNotify = useRef(props.notify);
52
+ useLayoutEffect(() => {
53
+ ownNotify.current = props.notify;
54
+ });
36
55
  const copyText = useCallback(async ({ text }, context) => {
37
56
  const copied = await writeClipboard(text, globalThis.document);
38
- setNotice({ text, copied, title: context.title });
57
+ const said = { text, copied, title: context.title };
58
+ if (ownNotify.current === undefined) {
59
+ setNotice(said);
60
+ }
61
+ else {
62
+ ownNotify.current(said, { copy: () => writeClipboard(text, globalThis.document) });
63
+ }
39
64
  return copied;
40
65
  }, []);
41
66
  const closeNotice = useCallback(() => setNotice(null), []);
@@ -46,11 +71,41 @@ export function PortholeProvider(props) {
46
71
  useLayoutEffect(() => {
47
72
  ownLocator.current = props.locator;
48
73
  });
49
- const locate = useCallback((instance, signal) => ownLocator.current === undefined
50
- ? Promise.reject(new Error("No locator (PortholeProvider.locator)"))
51
- : ownLocator.current.locate(instance, signal), []);
52
- const locates = props.locator !== undefined;
53
- const { nonce } = props;
74
+ const ownClient = useRef(props.client);
75
+ useLayoutEffect(() => {
76
+ ownClient.current = props.client;
77
+ });
78
+ const locate = useCallback((instance, signal) => ownLocator.current !== undefined
79
+ ? ownLocator.current.locate(instance, signal)
80
+ : ownClient.current !== undefined
81
+ ? ownClient.current.locate(instance, signal)
82
+ : Promise.reject(new Error("No locator (PortholeProvider.locator or client)")), []);
83
+ const locates = props.locator !== undefined || props.client !== undefined;
84
+ // `"auto"`: the page's own nonce, read once.
85
+ const [autoNonce] = useState(() => (props.nonce === "auto" ? pageNonce() : undefined));
86
+ const nonce = props.nonce === "auto" ? autoNonce : props.nonce;
87
+ const { client, scheme, theme, themeKey } = props;
88
+ // openLink without a frame handler: the provider's, or a new tab.
89
+ const ownOpen = useRef(props.openLink);
90
+ useLayoutEffect(() => {
91
+ ownOpen.current = props.openLink;
92
+ });
93
+ const handlers = useMemo(() => ({
94
+ openLink: ({ url }) => {
95
+ if (ownOpen.current === undefined) {
96
+ globalThis.open?.(url, "_blank", "noopener");
97
+ }
98
+ else {
99
+ ownOpen.current(url);
100
+ }
101
+ return true;
102
+ },
103
+ }), []);
104
+ const ownHandlers = useRef(props.handlers);
105
+ useLayoutEffect(() => {
106
+ ownHandlers.current = props.handlers;
107
+ });
108
+ const merged = useCallback(() => ({ ...handlers, ...ownHandlers.current }), [handlers]);
54
109
  const value = useMemo(() => ({
55
110
  live,
56
111
  heights,
@@ -59,19 +114,55 @@ export function PortholeProvider(props) {
59
114
  ...(hostInfo === undefined ? {} : { hostInfo }),
60
115
  ...(locates ? { locate } : {}),
61
116
  ...(nonce === undefined ? {} : { nonce }),
62
- }), [live, heights, confirm, copyText, hostInfo, locates, locate, nonce]);
117
+ ...(client === undefined ? {} : { client }),
118
+ ...(scheme === undefined ? {} : { scheme }),
119
+ ...(theme === undefined ? {} : { theme }),
120
+ ...(themeKey === undefined ? {} : { themeKey }),
121
+ handlers: merged,
122
+ }), [
123
+ live,
124
+ heights,
125
+ confirm,
126
+ copyText,
127
+ hostInfo,
128
+ locates,
129
+ locate,
130
+ nonce,
131
+ client,
132
+ scheme,
133
+ theme,
134
+ themeKey,
135
+ merged,
136
+ ]);
63
137
  const current = queue[0] ?? null;
64
- return (_jsxs(Page.Provider, { value: value, children: [props.children, props.confirm === undefined ? (_jsx(ConfirmDialog, { request: current?.request ?? null, ...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName }), onAnswer: (accepted) => {
138
+ return (_jsxs(Page.Provider, { value: value, children: [props.children, props.confirm === undefined && props.renderConfirm !== undefined && current !== null
139
+ ? props.renderConfirm(current.request, {
140
+ accept: () => {
141
+ // Inside the app's own click: the effect is the person's (a window it opens).
142
+ current.proceed();
143
+ current.resolve("accepted");
144
+ setQueue((waiting) => waiting.slice(1));
145
+ },
146
+ decline: () => {
147
+ current.resolve("declined");
148
+ setQueue((waiting) => waiting.slice(1));
149
+ },
150
+ redirect: () => {
151
+ current.resolve("redirected");
152
+ setQueue((waiting) => waiting.slice(1));
153
+ },
154
+ })
155
+ : null, props.confirm === undefined && props.renderConfirm === undefined ? (_jsx(ConfirmDialog, { request: current?.request ?? null, ...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName }), onAnswer: (accepted) => {
65
156
  // A yes runs the effect inside this very click (a window it opens is the person's).
66
157
  if (accepted) {
67
158
  current?.proceed();
68
159
  }
69
160
  current?.resolve(accepted ? "accepted" : "declined");
70
161
  setQueue((waiting) => waiting.slice(1));
71
- } })) : null, _jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
162
+ } })) : null, props.notify !== undefined ? null : (_jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
72
163
  // A click on the host's own page: the write has the gesture it needs now.
73
164
  void writeClipboard(failed.text, globalThis.document).then((copied) => setNotice({ ...failed, copied }));
74
- } })] }));
165
+ } }))] }));
75
166
  }
76
167
  const PLACEHOLDER_STYLE = {
77
168
  position: "absolute",
@@ -99,10 +190,13 @@ function rememberedHeight(heights, displayId, aliases) {
99
190
  }
100
191
  export function PortholeFrame(props) {
101
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;
102
196
  const key = useId();
103
197
  const box = useRef(null);
104
198
  const max = props.config.limits.maxLiveFrames;
105
- 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");
106
200
  const { eager } = props;
107
201
  useEffect(() => {
108
202
  const element = box.current;
@@ -110,38 +204,38 @@ export function PortholeFrame(props) {
110
204
  return;
111
205
  }
112
206
  if (eager === true || typeof IntersectionObserver !== "function") {
113
- page.live.near(key, true);
114
- page.live.admit(key, max);
115
- return () => page.live.release(key);
207
+ live.near(key, true);
208
+ live.admit(key, max);
209
+ return () => live.release(key);
116
210
  }
117
211
  const observer = new IntersectionObserver((entries) => {
118
212
  const entry = entries.at(-1);
119
213
  if (entry === undefined) {
120
214
  return;
121
215
  }
122
- page.live.near(key, entry.isIntersecting);
216
+ live.near(key, entry.isIntersecting);
123
217
  if (entry.isIntersecting) {
124
- page.live.admit(key, max);
218
+ live.admit(key, max);
125
219
  }
126
220
  }, { rootMargin: NEAR_SCREEN });
127
221
  observer.observe(element);
128
222
  return () => {
129
223
  observer.disconnect();
130
- page.live.release(key);
224
+ live.release(key);
131
225
  };
132
- }, [page, key, max, eager]);
133
- const height = rememberedHeight(page.heights, props.displayId, props.aliases);
226
+ }, [live, key, max, eager]);
227
+ const height = rememberedHeight(heights, props.displayId, props.aliases);
134
228
  // A display renamed while it runs (its id settled) keeps its height under its new id.
135
229
  const previousId = useRef(props.displayId);
136
230
  useLayoutEffect(() => {
137
231
  const before = previousId.current;
138
232
  previousId.current = props.displayId;
139
- const kept = page.heights.get(before);
140
- if (before !== props.displayId && kept !== undefined && !page.heights.has(props.displayId)) {
141
- 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);
142
236
  }
143
- }, [page, props.displayId]);
144
- const run = () => page.live.admit(key, max);
237
+ }, [heights, props.displayId]);
238
+ const run = () => live.admit(key, max);
145
239
  const placeholder = props.renderPlaceholder ?? DefaultPlaceholder;
146
240
  return (_jsx("div", { ref: box, className: props.className, "data-porthole-display": props.displayId, "data-porthole-state": state, style: {
147
241
  position: "relative",
@@ -163,13 +257,21 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
163
257
  const [ready, setReady] = useState(false);
164
258
  // The height this display started at: later reports don't make it start again.
165
259
  const [startHeight] = useState(initialHeightPx);
166
- const { document: view, content, partial, scheme } = frame;
260
+ const { document: view, content, partial } = frame;
261
+ const scheme = frame.scheme ?? page.scheme ?? "light";
262
+ // A run's content errors, told once each (a loop throwing the same error says it once).
263
+ const told = useRef(new Set());
167
264
  // By value: a config or instance made inline (each render) is the same display.
168
265
  const config = useByValue(frame.config);
169
266
  const instance = useByValue(frame.instance);
170
267
  const fills = config.mode === "url" || frame.fill === true || config.layout.kind === "fill";
171
268
  // The latest props, read when the display calls back (never during render).
172
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;
173
275
  const notify = useEffectEvent((event, detail) => {
174
276
  switch (event) {
175
277
  case "initialized":
@@ -182,9 +284,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
182
284
  frame.onResize?.(size);
183
285
  return;
184
286
  }
185
- case "contentError":
186
- frame.onContentError?.(detail.message);
287
+ case "contentError": {
288
+ const { message } = detail;
289
+ if (!told.current.has(message)) {
290
+ told.current.add(message);
291
+ frame.onContentError?.(message);
292
+ }
187
293
  return;
294
+ }
188
295
  case "hostError":
189
296
  frame.onHostError?.(detail);
190
297
  return;
@@ -225,36 +332,42 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
225
332
  displayId: latest().displayId,
226
333
  title: latest().title,
227
334
  });
228
- // The handlers present now (a declared one must be), each calling the latest prop's.
335
+ // The handlers present now (a declared one must be), each calling the latest prop's, else
336
+ // the provider's (P072).
229
337
  const handlers = {};
230
- for (const name of Object.keys(first.handlers ?? {})) {
231
- handlers[name] = (args, context) => latest().handlers?.[name]?.(args, named(context));
338
+ const declared = new Set(Object.keys(config.capabilities));
339
+ for (const name of new Set([
340
+ ...Object.keys(first.handlers ?? {}),
341
+ ...Object.keys(pageHandlers?.() ?? {}).filter((each) => declared.has(each)),
342
+ ])) {
343
+ handlers[name] = (args, context) => (latest().handlers?.[name] ??
344
+ pageHandlers?.()?.[name])?.(args, named(context));
232
345
  }
233
346
  // Copy buttons without a handler of the host's: the provider's, which shows a toast.
234
347
  if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
235
- const fallback = page.copyText;
348
+ const fallback = pageCopyText;
236
349
  if (fallback !== undefined) {
237
350
  handlers.copyText = (args, context) => fallback(args, named(context));
238
351
  }
239
352
  }
240
- const asks = first.confirm !== undefined || page.confirm !== undefined;
353
+ const asks = first.confirm !== undefined || pageConfirm !== undefined;
241
354
  let display;
242
355
  try {
243
356
  display = createHost(config, {
244
357
  handlers,
245
358
  ...(asks
246
359
  ? {
247
- 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),
248
361
  }
249
362
  : {}),
250
- theme: (each) => latest().theme?.(each) ?? {},
251
- ...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
252
- ...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
253
- ...(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 }),
254
367
  }).mount(container, {
255
368
  displayId: first.displayId,
256
369
  title: first.title,
257
- scheme: first.scheme,
370
+ scheme: first.scheme ?? latestPage().scheme ?? "light",
258
371
  initialHeightPx: startHeight,
259
372
  ...(view === undefined ? {} : { document: view }),
260
373
  ...(instance === undefined ? {} : { instance }),
@@ -291,9 +404,22 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
291
404
  display.destroy();
292
405
  handle.current = null;
293
406
  };
294
- // A new display only for a new config, document, instance or page (or generation, by key);
295
- // content, theme, handlers, id and title are fed to the running one.
296
- }, [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
+ ]);
297
423
  useEffect(() => {
298
424
  if (content !== undefined) {
299
425
  handle.current?.setContent(content, { partial: partial === true });
@@ -345,13 +471,28 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
345
471
  handle.current?.setTheme(scheme);
346
472
  }
347
473
  }, [scheme, mountScheme]);
348
- const { themeKey } = frame;
474
+ const themeKey = frame.themeKey ?? page.themeKey;
349
475
  const [mountThemeKey] = useState(themeKey);
350
476
  useEffect(() => {
351
477
  if (themeKey !== undefined && themeKey !== mountThemeKey) {
352
478
  handle.current?.refreshTheme();
353
479
  }
354
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]);
355
496
  return (_jsxs("div", { "data-porthole-ready": String(ready), style: {
356
497
  position: "relative",
357
498
  // A url-mode app fills the frame's box (give PortholeFrame a height); the rest size to content.
@@ -8,7 +8,8 @@
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
+ export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, type PortholeFallbackProps, type PortholeViewProps, } from "./view.tsx";
13
14
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, type CopyNotice, type CopyToastProps, } from "./toast.tsx";
14
15
  export { admitFrame, createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
@@ -10,5 +10,6 @@
10
10
  */
11
11
  export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, } from "./frame.js";
12
12
  export { ARM_DELAY_MS, ConfirmDialog } from "./dialog.js";
13
+ export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, } from "./view.js";
13
14
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, } from "./toast.js";
14
15
  export { admitFrame, createLiveFrames } from "./live.js";
@@ -0,0 +1,54 @@
1
+ import { type ReactElement, type ReactNode } from "react";
2
+ import type { ColorScheme } from "../config/schema.ts";
3
+ import { type FrameFallback } from "../host/client.ts";
4
+ import type { InstanceRef } from "../isolation/types.ts";
5
+ import { type PortholeFrameProps } from "./frame.tsx";
6
+ /**
7
+ * The host kit's React side (P072): a display by its kind, served or opaque as the server says
8
+ * now, located through the provider's client, with a fallback when its frame shows nothing.
9
+ *
10
+ * <PortholeProvider client={porthole} scheme={mode}>
11
+ * <PortholeView display="page" instance={instance} content={opaqueCopy}
12
+ * fallback={({ title, message, link, retry }) => <Fallback … />} />
13
+ * </PortholeProvider>
14
+ */
15
+ /** What a fallback is drawn from: why the frame showed nothing, its clean address, a retry. */
16
+ export interface PortholeFallbackProps extends FrameFallback {
17
+ /** The instance's clean address (its "open in a new tab"), or null. */
18
+ readonly link: string | null;
19
+ /** Shows the display again. */
20
+ readonly retry: () => void;
21
+ }
22
+ export interface PortholeViewProps extends Omit<PortholeFrameProps, "config" | "instance" | "content" | "fill"> {
23
+ /** The display kind (`defineDisplays`). */
24
+ readonly display: string;
25
+ /** The instance to show while frames are served. */
26
+ readonly instance?: InstanceRef;
27
+ /**
28
+ * The content: a served shell's to draw, and what an opaque frame shows while frames aren't
29
+ * served (a stored page's HTML). Without it, a served-only display shows the fallback then.
30
+ */
31
+ readonly content?: string;
32
+ /** Drawn instead of the frame when it showed nothing. Default: a line and a link. */
33
+ readonly fallback?: (props: PortholeFallbackProps) => ReactNode;
34
+ /** Drawn while the server's meta isn't known yet. */
35
+ readonly pending?: ReactNode;
36
+ }
37
+ export declare function PortholeView(props: PortholeViewProps): ReactElement | null;
38
+ /** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
39
+ export declare function usePortholeLink(instance: InstanceRef | null): {
40
+ readonly link: string | null;
41
+ readonly open: () => void;
42
+ readonly copy: () => Promise<boolean>;
43
+ };
44
+ /**
45
+ * Theme values read from the page's own CSS variables (P072): `tokens` maps each of Porthole's
46
+ * theme variables to the app's (`{ "--color-text-primary": "--app-fg" }`). Read when a frame asks,
47
+ * so pass `themeKey` to re-read after the app's theme changes.
48
+ */
49
+ export declare function cssVariableTheme(tokens: Readonly<Record<string, string>>, root?: () => Element): (scheme: ColorScheme) => Record<string, string>;
50
+ /** A display's "run again": pass `generation` to the frame, call `runAgain` from a button. */
51
+ export declare function useRunAgain(): {
52
+ readonly generation: number;
53
+ readonly runAgain: () => void;
54
+ };
@@ -0,0 +1,151 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useContext, useEffect, useState, useSyncExternalStore, } from "react";
3
+ import { frameFallback } from "../host/client.js";
4
+ import { PortholeFrame, PortholeContext } from "./frame.js";
5
+ function useClient() {
6
+ const client = useContext(PortholeContext).client;
7
+ if (client === undefined) {
8
+ throw new Error("PortholeView needs a PortholeProvider with a client (portholeClient)");
9
+ }
10
+ return client;
11
+ }
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
+ */
18
+ function useMeta(client) {
19
+ return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => client.meta());
20
+ }
21
+ function DefaultFallback({ title, message, link }) {
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" }))] }));
23
+ }
24
+ export function PortholeView(props) {
25
+ const client = useClient();
26
+ const meta = useMeta(client);
27
+ const { display, instance, content, fallback, pending, onOutcome, ...frame } = props;
28
+ const [failed, setFailed] = useState(null);
29
+ const [generation, setGeneration] = useState(0);
30
+ const [link, setLink] = useState(null);
31
+ const kind = display;
32
+ const config = client.config(kind);
33
+ const served = meta?.served === true && config?.isolation !== "opaque";
34
+ const url = config?.mode === "url";
35
+ const retry = useCallback(() => {
36
+ setFailed(null);
37
+ setGeneration((each) => each + 1);
38
+ }, []);
39
+ useEffect(() => {
40
+ if (failed === null || instance === undefined) {
41
+ return;
42
+ }
43
+ let live = true;
44
+ void client.link(instance).then((found) => {
45
+ if (live) {
46
+ setLink(found);
47
+ }
48
+ });
49
+ return () => {
50
+ live = false;
51
+ };
52
+ }, [client, failed, instance]);
53
+ if (meta === null || config === null) {
54
+ // Not known yet; or a url kind while frames aren't served.
55
+ if (meta !== null && config === null) {
56
+ const said = {
57
+ kind: "failed",
58
+ title: "This can't be shown now",
59
+ message: "Its content isn't being served.",
60
+ };
61
+ return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...said, link: null, retry }) });
62
+ }
63
+ return _jsx(_Fragment, { children: pending ?? null });
64
+ }
65
+ if (!served && content === undefined) {
66
+ const said = {
67
+ kind: "failed",
68
+ title: "This can't be shown now",
69
+ message: "Its content isn't being served.",
70
+ };
71
+ return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...said, link: null, retry }) });
72
+ }
73
+ if (failed !== null) {
74
+ return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...failed, link, retry }) });
75
+ }
76
+ return (_jsx(PortholeFrame, { ...frame, config: config, generation: (frame.generation ?? 0) + generation, ...(served && instance !== undefined ? { instance } : {}), ...(content === undefined ? {} : { content }), onOutcome: (outcome) => {
77
+ onOutcome?.(outcome);
78
+ const said = frameFallback(outcome, { url });
79
+ if (said !== null) {
80
+ setFailed(said);
81
+ }
82
+ } }));
83
+ }
84
+ /** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
85
+ export function usePortholeLink(instance) {
86
+ const client = useClient();
87
+ const key = instance === null ? "" : JSON.stringify(instance);
88
+ // The address found for the instance it was found for: another instance shows none until its own.
89
+ const [found, setFound] = useState(() => ({ key, link: instance === null ? null : client.knownLink(instance) }));
90
+ useEffect(() => {
91
+ if (key === "") {
92
+ return;
93
+ }
94
+ let live = true;
95
+ void client.link(JSON.parse(key)).then((each) => {
96
+ if (live) {
97
+ setFound({ key, link: each });
98
+ }
99
+ });
100
+ return () => {
101
+ live = false;
102
+ };
103
+ }, [client, key]);
104
+ const link = found.key === key ? found.link : null;
105
+ const open = useCallback(() => {
106
+ if (key !== "") {
107
+ client.openInTab(JSON.parse(key));
108
+ }
109
+ }, [client, key]);
110
+ const copy = useCallback(async () => {
111
+ if (link === null) {
112
+ return false;
113
+ }
114
+ try {
115
+ await navigator.clipboard.writeText(link);
116
+ return true;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ }, [link]);
122
+ return { link, open, copy };
123
+ }
124
+ /**
125
+ * Theme values read from the page's own CSS variables (P072): `tokens` maps each of Porthole's
126
+ * theme variables to the app's (`{ "--color-text-primary": "--app-fg" }`). Read when a frame asks,
127
+ * so pass `themeKey` to re-read after the app's theme changes.
128
+ */
129
+ export function cssVariableTheme(tokens, root) {
130
+ return () => {
131
+ const element = root?.() ?? globalThis.document?.documentElement;
132
+ if (element === undefined) {
133
+ return {};
134
+ }
135
+ const style = getComputedStyle(element);
136
+ const values = {};
137
+ for (const [ours, theirs] of Object.entries(tokens)) {
138
+ const value = style.getPropertyValue(theirs).trim();
139
+ if (value !== "") {
140
+ values[ours] = value;
141
+ }
142
+ }
143
+ return values;
144
+ };
145
+ }
146
+ /** A display's "run again": pass `generation` to the frame, call `runAgain` from a button. */
147
+ export function useRunAgain() {
148
+ const [generation, setGeneration] = useState(0);
149
+ const runAgain = useCallback(() => setGeneration((each) => each + 1), []);
150
+ return { generation, runAgain };
151
+ }
@@ -0,0 +1,27 @@
1
+ import { type ContentHost, type ContentHostOptions } from "./host.ts";
2
+ /**
3
+ * The host kit on a runtime that hands each request its settings (Cloudflare Workers' `env`)
4
+ * (P072): one content host per settings object, made on first use. Settings that can't be served
5
+ * fail closed: every request is a plain 503 naming why, told to the log once.
6
+ *
7
+ * const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, secret: env.PORTHOLE_SECRET, … }));
8
+ * export default {
9
+ * async fetch(request, env) {
10
+ * return (await porthole.fetch(request, env)) ?? app.fetch(request, env);
11
+ * },
12
+ * };
13
+ */
14
+ export interface ContentHostFor<E extends object, V> {
15
+ /** The content host for these settings; throws, naming why, where they can't be served. */
16
+ host(env: E): ContentHost<V>;
17
+ /**
18
+ * The content domain's answer for a request (`ContentHost.fetch`), or null for the app's own;
19
+ * a plain 503 for every request while the settings can't be served.
20
+ */
21
+ fetch(request: Request, env: E): Promise<Response | null>;
22
+ /** `ContentHost.routes`, for these settings. */
23
+ routes(request: Request, env: E, viewerOf: (request: Request) => V | null | Promise<V | null>): Promise<Response | null>;
24
+ }
25
+ export declare function contentHostFor<E extends object, V>(build: (env: E) => ContentHostOptions<V>, options?: {
26
+ readonly log?: (problem: string) => void;
27
+ }): ContentHostFor<E, V>;