@flanksource/page-runtime 0.0.0-stage → 0.1.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 (312) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +494 -2
  3. package/dist/build/README.md +96 -0
  4. package/dist/build/cjs-export-names.mjs +24 -0
  5. package/dist/build/dependencies.mjs +279 -0
  6. package/dist/build/dependencies.mjs.map +1 -0
  7. package/dist/build/dependency-cache-Zg-FGasE.mjs +2130 -0
  8. package/dist/build/dependency-cache-Zg-FGasE.mjs.map +1 -0
  9. package/dist/build/index.mjs +42 -0
  10. package/dist/build/index.mjs.map +1 -0
  11. package/dist/build/package.json +19 -0
  12. package/dist/build/types/activity-schema.d.ts +62 -0
  13. package/dist/build/types/build/barrels.d.ts +70 -0
  14. package/dist/build/types/build/base.d.ts +2 -0
  15. package/dist/build/types/build/browser-runtime-exports.d.ts +19 -0
  16. package/dist/build/types/build/check-fragment.d.ts +5 -0
  17. package/dist/build/types/build/commonjs-exports.d.ts +5 -0
  18. package/dist/build/types/build/convert-commonjs.d.ts +12 -0
  19. package/dist/build/types/build/dependencies.d.ts +6 -0
  20. package/dist/build/types/build/dependency-barrel-index.d.ts +5 -0
  21. package/dist/build/types/build/dependency-barrels.d.ts +7 -0
  22. package/dist/build/types/build/dependency-cache.d.ts +7 -0
  23. package/dist/build/types/build/dependency-optional.d.ts +4 -0
  24. package/dist/build/types/build/dependency-plugin.d.ts +8 -0
  25. package/dist/build/types/build/dependency-runtime.d.ts +20 -0
  26. package/dist/build/types/build/dependency-workers.d.ts +8 -0
  27. package/dist/build/types/build/errors.d.ts +9 -0
  28. package/dist/build/types/build/fragment.d.ts +13 -0
  29. package/dist/build/types/build/index.d.ts +7 -0
  30. package/dist/build/types/build/library-runtime.d.ts +21 -0
  31. package/dist/build/types/build/module-utils.d.ts +3 -0
  32. package/dist/build/types/build/recipe-dependencies.d.ts +2 -0
  33. package/dist/build/types/build/runtime-entries.d.ts +4 -0
  34. package/dist/build/types/build/runtime-layer.d.ts +17 -0
  35. package/dist/build/types/build/trace.d.ts +140 -0
  36. package/dist/build/types/design-schema.d.ts +98 -0
  37. package/dist/build/types/host/agent-source.d.ts +2 -0
  38. package/dist/build/types/host/agent-validation.d.ts +3 -0
  39. package/dist/build/types/host/design-validation.d.ts +2 -0
  40. package/dist/build/types/host/message-values.d.ts +8 -0
  41. package/dist/build/types/host/review/validation.d.ts +5 -0
  42. package/dist/build/types/host/validation.d.ts +6 -0
  43. package/dist/build/types/link/page-sources.d.ts +31 -0
  44. package/dist/build/types/link/types.d.ts +62 -0
  45. package/dist/build/types/link/validation.d.ts +9 -0
  46. package/dist/build/types/markers.d.ts +10 -0
  47. package/dist/build/types/review-schema.d.ts +60 -0
  48. package/dist/build/types/schema.d.ts +319 -0
  49. package/dist/build/types/sw/barrels.d.ts +9 -0
  50. package/dist/build/types/sw/compiler-plugins.d.ts +6 -0
  51. package/dist/build/types/sw/composition.d.ts +8 -0
  52. package/dist/build/types/sw/module-transform.d.ts +68 -0
  53. package/dist/build/types/sw/profile.d.ts +7 -0
  54. package/dist/build/types/sw/source-provider.d.ts +7 -0
  55. package/dist/build/types/sw/versions.d.ts +10 -0
  56. package/dist/node/catalog.mjs +1 -0
  57. package/dist/node/chunks/publication-RchcQvxD.mjs +229 -0
  58. package/dist/node/chunks/publication-RchcQvxD.mjs.map +1 -0
  59. package/dist/node/chunks/schema-CaRTfg2x.mjs +12 -0
  60. package/dist/node/chunks/schema-CaRTfg2x.mjs.map +1 -0
  61. package/dist/node/dev.mjs +410 -0
  62. package/dist/node/dev.mjs.map +1 -0
  63. package/dist/node/publication/cli.mjs +13 -0
  64. package/dist/node/publication/cli.mjs.map +1 -0
  65. package/dist/node/publication.mjs +1 -0
  66. package/dist/node/schema.mjs +1 -0
  67. package/dist/node/styles.mjs +49 -0
  68. package/dist/node/styles.mjs.map +1 -0
  69. package/dist/static/boot.js +40938 -0
  70. package/dist/static/boot.js.map +1 -0
  71. package/dist/static/bootstrap.html +1 -0
  72. package/dist/static/devtools-hook.js +118 -0
  73. package/dist/static/document-bundle.js +1 -0
  74. package/dist/static/document.js +2621 -0
  75. package/dist/static/editing.js +37 -0
  76. package/dist/static/export-compiler.js +81521 -0
  77. package/dist/static/export-compiler.js.map +1 -0
  78. package/dist/static/page-agent.js +17193 -0
  79. package/dist/static/page-agent.js.map +1 -0
  80. package/dist/static/sw.js +86112 -0
  81. package/dist/static/sw.js.map +1 -0
  82. package/package.json +110 -3
  83. package/scripts/build-builder.ts +27 -0
  84. package/scripts/build-library-runtime.ts +9 -0
  85. package/scripts/build-node.ts +26 -0
  86. package/scripts/build-static.ts +86 -0
  87. package/scripts/build.ts +7 -0
  88. package/scripts/check-fragment.ts +12 -0
  89. package/scripts/local-workspaces.ts +55 -0
  90. package/scripts/react-externals.ts +18 -0
  91. package/scripts/release-version.ts +47 -0
  92. package/scripts/run-package-build.ts +8 -0
  93. package/scripts/serve-packages.ts +8 -0
  94. package/src/activity-schema.ts +92 -0
  95. package/src/build/README.md +96 -0
  96. package/src/build/barrels.ts +306 -0
  97. package/src/build/base.ts +2 -0
  98. package/src/build/browser-runtime-exports.ts +52 -0
  99. package/src/build/check-fragment.ts +45 -0
  100. package/src/build/cjs-export-names.mjs +24 -0
  101. package/src/build/commonjs-exports.ts +24 -0
  102. package/src/build/convert-commonjs.ts +183 -0
  103. package/src/build/dependencies.ts +6 -0
  104. package/src/build/dependency-barrel-index.ts +48 -0
  105. package/src/build/dependency-barrels.ts +80 -0
  106. package/src/build/dependency-cache.ts +40 -0
  107. package/src/build/dependency-optional.ts +15 -0
  108. package/src/build/dependency-plugin.ts +58 -0
  109. package/src/build/dependency-runtime.ts +182 -0
  110. package/src/build/dependency-workers.ts +41 -0
  111. package/src/build/errors.ts +9 -0
  112. package/src/build/fragment.ts +89 -0
  113. package/src/build/index.ts +7 -0
  114. package/src/build/library-runtime.ts +101 -0
  115. package/src/build/module-utils.ts +11 -0
  116. package/src/build/recipe-dependencies.ts +14 -0
  117. package/src/build/runtime-entries.ts +10 -0
  118. package/src/build/runtime-layer.ts +99 -0
  119. package/src/build/trace.ts +431 -0
  120. package/src/design-schema.ts +25 -0
  121. package/src/dev/README.md +78 -0
  122. package/src/dev/catalog.ts +79 -0
  123. package/src/dev/cli.ts +25 -0
  124. package/src/dev/index.ts +118 -0
  125. package/src/dev/runtime-origin.ts +63 -0
  126. package/src/editing.ts +25 -0
  127. package/src/form/entry-source.ts +68 -0
  128. package/src/form/form-page.ts +63 -0
  129. package/src/form/index.ts +2 -0
  130. package/src/form/source-update.ts +17 -0
  131. package/src/frame/activity.browser.ts +34 -0
  132. package/src/frame/activity.ts +52 -0
  133. package/src/frame/agent/README.md +47 -0
  134. package/src/frame/agent/agent.browser.ts +127 -0
  135. package/src/frame/agent/design.ts +62 -0
  136. package/src/frame/agent/frame-layout.ts +54 -0
  137. package/src/frame/agent/index.ts +151 -0
  138. package/src/frame/agent/overlay.ts +104 -0
  139. package/src/frame/agent/owner.ts +61 -0
  140. package/src/frame/agent/provider.tsx +14 -0
  141. package/src/frame/agent/react-override.ts +55 -0
  142. package/src/frame/agent/review.browser.ts +65 -0
  143. package/src/frame/agent/review.ts +108 -0
  144. package/src/frame/agent/testing/callsite.tsx +5 -0
  145. package/src/frame/agent/testing/client.ts +99 -0
  146. package/src/frame/agent/testing/library.ts +3 -0
  147. package/src/frame/agent/testing/modal.tsx +5 -0
  148. package/src/frame/agent/testing/review-client.ts +43 -0
  149. package/src/frame/agent/testing/review-server.ts +31 -0
  150. package/src/frame/agent/testing/server.ts +72 -0
  151. package/src/frame/agent/testing/vocabulary-host.ts +20 -0
  152. package/src/frame/agent/testing/vocabulary.tsx +10 -0
  153. package/src/frame/agent/vitest.browser.config.ts +6 -0
  154. package/src/frame/agent/vocabulary.browser.ts +30 -0
  155. package/src/frame/agent/vocabulary.ts +13 -0
  156. package/src/frame/agent.ts +3 -0
  157. package/src/frame/boot-styles.ts +50 -0
  158. package/src/frame/boot.ts +269 -0
  159. package/src/frame/bridge.ts +27 -0
  160. package/src/frame/devtools-hook.ts +1 -0
  161. package/src/frame/document-assets.ts +76 -0
  162. package/src/frame/document-entry.ts +68 -0
  163. package/src/frame/document-modules.ts +113 -0
  164. package/src/frame/document-mount.ts +32 -0
  165. package/src/frame/entry.ts +4 -0
  166. package/src/frame/export-compiler.ts +18 -0
  167. package/src/frame/export-page.ts +61 -0
  168. package/src/frame/export.ts +89 -0
  169. package/src/frame/index.ts +8 -0
  170. package/src/frame/local-runtime.browser.ts +36 -0
  171. package/src/frame/mount-page.ts +36 -0
  172. package/src/frame/page-agent.ts +2 -0
  173. package/src/frame/readiness.ts +51 -0
  174. package/src/frame/render-job.ts +101 -0
  175. package/src/frame/review-integration.browser.ts +48 -0
  176. package/src/frame/runtime.browser.ts +90 -0
  177. package/src/frame/tailwind/README.md +49 -0
  178. package/src/frame/tailwind/boot-styles.browser.ts +18 -0
  179. package/src/frame/tailwind/cache.ts +20 -0
  180. package/src/frame/tailwind/load.ts +75 -0
  181. package/src/frame/tailwind/recipe.ts +76 -0
  182. package/src/frame/tailwind/runtime.ts +113 -0
  183. package/src/frame/tailwind/store.ts +55 -0
  184. package/src/frame/tailwind/stylesheets.ts +42 -0
  185. package/src/frame/tailwind/tailwind.browser.ts +71 -0
  186. package/src/frame/tailwind/testing/client.ts +133 -0
  187. package/src/frame/tailwind/testing/compare.ts +91 -0
  188. package/src/frame/tailwind/testing/pages.ts +14 -0
  189. package/src/frame/tailwind/testing/server.ts +89 -0
  190. package/src/frame/tailwind/vitest.browser.config.ts +7 -0
  191. package/src/frame/testing/boot-layout.ts +3 -0
  192. package/src/frame/testing/boot-page.ts +3 -0
  193. package/src/frame/testing/host.ts +78 -0
  194. package/src/frame/testing/local-host.tsx +33 -0
  195. package/src/frame/testing/server.ts +135 -0
  196. package/src/host/BuildLog.tsx +28 -0
  197. package/src/host/DEBUG_CONSOLE.md +13 -0
  198. package/src/host/PageForm.tsx +63 -0
  199. package/src/host/PageFrame.tsx +49 -0
  200. package/src/host/RuntimeActivity.tsx +77 -0
  201. package/src/host/RuntimeDebugPanel.tsx +18 -0
  202. package/src/host/activity-state.ts +69 -0
  203. package/src/host/agent-source.ts +14 -0
  204. package/src/host/agent-validation.ts +73 -0
  205. package/src/host/bridge.ts +56 -0
  206. package/src/host/build-log.ts +29 -0
  207. package/src/host/clear-cache.ts +66 -0
  208. package/src/host/debug-runtime.tsx +17 -0
  209. package/src/host/design-validation.ts +96 -0
  210. package/src/host/index.ts +12 -0
  211. package/src/host/link/index.ts +66 -0
  212. package/src/host/link/transport.ts +68 -0
  213. package/src/host/link/watch.ts +62 -0
  214. package/src/host/message-values.ts +55 -0
  215. package/src/host/origin.ts +7 -0
  216. package/src/host/review/README.md +32 -0
  217. package/src/host/review/index.ts +43 -0
  218. package/src/host/review/validation.ts +55 -0
  219. package/src/host/runtime-diagnostics.ts +41 -0
  220. package/src/host/validation.ts +148 -0
  221. package/src/link/README.md +115 -0
  222. package/src/link/barrels.ts +5 -0
  223. package/src/link/build-cli.ts +12 -0
  224. package/src/link/build.ts +99 -0
  225. package/src/link/commonjs.ts +39 -0
  226. package/src/link/examples/server.ts +18 -0
  227. package/src/link/index.ts +6 -0
  228. package/src/link/link.browser.ts +66 -0
  229. package/src/link/local-relay.browser.ts +22 -0
  230. package/src/link/overrides.ts +69 -0
  231. package/src/link/page-sources.ts +69 -0
  232. package/src/link/source.ts +25 -0
  233. package/src/link/storage.ts +32 -0
  234. package/src/link/testing/client.ts +96 -0
  235. package/src/link/testing/folder.ts +19 -0
  236. package/src/link/testing/local-client.ts +30 -0
  237. package/src/link/testing/local-server.ts +26 -0
  238. package/src/link/testing/local-worker.ts +17 -0
  239. package/src/link/testing/server.ts +131 -0
  240. package/src/link/testing/worker.ts +32 -0
  241. package/src/link/testing-cache.ts +20 -0
  242. package/src/link/testing-fixtures.ts +16 -0
  243. package/src/link/types.ts +27 -0
  244. package/src/link/validation.ts +44 -0
  245. package/src/link/vitest.browser.config.ts +3 -0
  246. package/src/markers.ts +18 -0
  247. package/src/publication/build.ts +27 -0
  248. package/src/publication/fixtures/build.mjs +2 -0
  249. package/src/publication/index.ts +3 -0
  250. package/src/publication/lock.ts +32 -0
  251. package/src/publication/manifest.ts +14 -0
  252. package/src/publication/publish.ts +80 -0
  253. package/src/publication/runtime.ts +28 -0
  254. package/src/publication/schema.ts +13 -0
  255. package/src/review-schema.ts +17 -0
  256. package/src/schema.ts +175 -0
  257. package/src/storage/db.ts +64 -0
  258. package/src/styles.ts +40 -0
  259. package/src/sw/activity.ts +66 -0
  260. package/src/sw/barrels.ts +44 -0
  261. package/src/sw/candidates.ts +14 -0
  262. package/src/sw/compile.ts +92 -0
  263. package/src/sw/compiler-columns.ts +44 -0
  264. package/src/sw/compiler-internals.d.ts +8 -0
  265. package/src/sw/compiler-plugins.ts +18 -0
  266. package/src/sw/compiler.ts +93 -0
  267. package/src/sw/composition.ts +86 -0
  268. package/src/sw/content-types.ts +28 -0
  269. package/src/sw/converted.browser.ts +31 -0
  270. package/src/sw/converted.ts +64 -0
  271. package/src/sw/editable-sites.ts +42 -0
  272. package/src/sw/errors.ts +30 -0
  273. package/src/sw/esm-sh-fixtures/browser-client.ts +18 -0
  274. package/src/sw/esm-sh-fixtures/browser-server.ts +104 -0
  275. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.headers +15 -0
  276. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.mjs.txt +3 -0
  277. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.headers +13 -0
  278. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.mjs.txt +142 -0
  279. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.headers +15 -0
  280. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.mjs.txt +3 -0
  281. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.headers +11 -0
  282. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.mjs.txt +222 -0
  283. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.headers +14 -0
  284. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.mjs.txt +3 -0
  285. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.headers +11 -0
  286. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.mjs.txt +76 -0
  287. package/src/sw/esm-sh-fixtures/fixtures.ts +54 -0
  288. package/src/sw/esm-sh-fixtures/redact.ts +1 -0
  289. package/src/sw/index.ts +7 -0
  290. package/src/sw/integrity.ts +10 -0
  291. package/src/sw/legacy-storage.ts +18 -0
  292. package/src/sw/link-activity.ts +21 -0
  293. package/src/sw/link-cache.ts +19 -0
  294. package/src/sw/link-compiler.ts +120 -0
  295. package/src/sw/link-folder.ts +29 -0
  296. package/src/sw/link-relay.ts +40 -0
  297. package/src/sw/link-route.ts +239 -0
  298. package/src/sw/link-source.ts +41 -0
  299. package/src/sw/markers.ts +128 -0
  300. package/src/sw/module-transform.ts +364 -0
  301. package/src/sw/page-clients.ts +45 -0
  302. package/src/sw/profile.ts +90 -0
  303. package/src/sw/resolver.ts +224 -0
  304. package/src/sw/router.ts +360 -0
  305. package/src/sw/runtime-exports.ts +39 -0
  306. package/src/sw/runtime-module.ts +13 -0
  307. package/src/sw/source-hash.ts +37 -0
  308. package/src/sw/source-provider.ts +20 -0
  309. package/src/sw/versions.ts +96 -0
  310. package/src/sw/worker.ts +91 -0
  311. package/static/README.md +15 -0
  312. package/static/profile.example.json +15 -0
@@ -0,0 +1,49 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import { useLayoutEffect, useRef, type IframeHTMLAttributes } from "react";
3
+ import type { FrameMessage, HostMessage, JsonValue, Theme } from "../schema.ts";
4
+ import { createBridge, type PageBridge } from "./bridge.ts";
5
+ import { validateFrameOrigin, type FrameOrigin } from "./origin.ts";
6
+ import { registerPageRuntimeDebug } from "./debug-runtime.tsx";
7
+
8
+ export type PageFrameProps = Omit<IframeHTMLAttributes<HTMLIFrameElement>, "src" | "sandbox" | "onError"> & {
9
+ runtimeOrigin: string; open: Omit<Extract<HostMessage, { type: "open" }>, "type">; theme: Theme; data: JsonValue;
10
+ onMessage?: (message: FrameMessage) => void; onError: (error: Error) => void;
11
+ onBridge?: (bridge: PageBridge | null) => void;
12
+ /** False when the host sends data updates through the bridge; bootstrap still receives the latest data. */
13
+ dataUpdates?: boolean;
14
+ /** Local development only: embed on the host origin while P7 isolation is deferred. */
15
+ origin?: FrameOrigin;
16
+ };
17
+
18
+ export function PageFrame({ runtimeOrigin, origin = "cross-origin", open, theme, data, dataUpdates = true, onMessage, onError, onBridge, ...props }: PageFrameProps) {
19
+ const frame = useRef<HTMLIFrameElement>(null);
20
+ const latest = useRef({ open, theme, data, onMessage, onError, onBridge });
21
+ const bridge = useRef<PageBridge | null>(null);
22
+ useLayoutEffect(() => {
23
+ latest.current = { open, theme, data, onMessage, onError, onBridge };
24
+ }, [open, theme, data, onMessage, onError, onBridge]);
25
+ useLayoutEffect(() => {
26
+ const target = frame.current?.contentWindow;
27
+ if (!target || !frame.current) throw new Error("PageFrame has no contentWindow");
28
+ validateFrameOrigin({ runtimeOrigin, hostOrigin: location.origin, origin });
29
+ const session = randomUUID();
30
+ const debug = registerPageRuntimeDebug({ session, page: open.page, origin: runtimeOrigin });
31
+ let opened = false;
32
+ bridge.current = createBridge({ target, origin: runtimeOrigin, session, direction: "host", onError: (error) => { debug.fail(error); latest.current.onError(error); }, onMessage: (envelope) => {
33
+ const message = envelope.message as FrameMessage;
34
+ debug.receive(message);
35
+ if (message.type === "lock" && JSON.stringify(message.lock) === JSON.stringify(latest.current.open.lock)) return;
36
+ if (message.type === "status" && (message.state === "connecting" || (message.state === "booting" && !opened))) { opened = true; bridge.current!.send({ type: "open", ...latest.current.open }); return; }
37
+ if (message.type === "status" && message.state === "booting") { bridge.current!.send({ type: "theme", ...latest.current.theme }); bridge.current!.send({ type: "data", data: latest.current.data }); }
38
+ latest.current.onMessage?.(message);
39
+ } });
40
+ latest.current.onBridge?.(bridge.current);
41
+ const params = new URLSearchParams({ session, host: location.origin });
42
+ if (origin === "same-origin-local") params.set("origin", origin);
43
+ frame.current.src = `${runtimeOrigin}/frame/${open.page.split("/").map(encodeURIComponent).join("/")}#${params}`;
44
+ return () => { debug.dispose(); bridge.current?.dispose(); bridge.current = null; latest.current.onBridge?.(null); };
45
+ }, [runtimeOrigin, origin, open.page]);
46
+ useLayoutEffect(() => { bridge.current?.send({ type: "theme", ...theme }); }, [theme]);
47
+ useLayoutEffect(() => { if (dataUpdates) bridge.current?.send({ type: "data", data }); }, [data, dataUpdates]);
48
+ return <iframe {...props} ref={frame} title={props.title ?? open.page} sandbox="allow-scripts allow-same-origin allow-modals" />;
49
+ }
@@ -0,0 +1,77 @@
1
+ import { useMemo, useState } from "react";
2
+ import { FilterBar, Tabs } from "@flanksource/clicky-ui/components";
3
+ import { Badge, DataTable, Properties, type DataTableColumn } from "@flanksource/clicky-ui/data";
4
+ import { formatBytes, formatDuration } from "@flanksource/clicky-ui/utils";
5
+ import type { WorkerActivity } from "../activity-schema.ts";
6
+ import { activityLibraries, summarizeActivity, type ActivityLibrary, type ActivityLoad, type ActivitySummary, type RuntimeActivityState } from "./activity-state.ts";
7
+
8
+ const sizes = (value: number | null) => value === null ? "Unavailable" : formatBytes(value);
9
+ const requestColumns: DataTableColumn<WorkerActivity>[] = [
10
+ { key: "kind", label: "Kind", render: (_, r) => <Badge>{r.kind}</Badge> },
11
+ { key: "url", label: "File", render: (_, r) => <span title={r.url}>{r.package ? `${r.package.name}@${r.package.version}/${r.package.path}` : new URL(r.url).pathname}</span> },
12
+ { key: "source", label: "Source" }, { key: "transferredBytes", label: "Transferred", align: "right", render: (_, r) => sizes(r.transferredBytes) },
13
+ { key: "decodedBytes", label: "Decoded", align: "right", render: (_, r) => sizes(r.decodedBytes) },
14
+ { key: "outputBytes", label: "Output", align: "right", render: (_, r) => sizes(r.outputBytes) },
15
+ { key: "totalMs", label: "Time", align: "right", render: (_, r) => formatDuration(r.totalMs) }, { key: "status", label: "Status", align: "right" },
16
+ ];
17
+ const libraryColumns: DataTableColumn<ActivityLibrary>[] = [
18
+ { key: "id", label: "Package" }, { key: "role", label: "Runtime set", render: (_, r) => <Badge>{r.role}</Badge> },
19
+ { key: "origin", label: "Origin", render: (_, r) => <span title={r.origin}>{r.origin}</span> },
20
+ { key: "files", label: "Files", align: "right" }, { key: "transferredBytes", label: "Transferred", align: "right", render: (_, r) => `${formatBytes(r.transferredBytes)}${r.unknownTransfers ? " + unknown" : ""}` },
21
+ { key: "decodedBytes", label: "Decoded", align: "right", render: (_, r) => formatBytes(r.decodedBytes) }, { key: "cacheRatio", label: "Cache hits", align: "right", render: (_, r) => `${Math.round(r.cacheRatio * 100)}%` },
22
+ ];
23
+
24
+ export function RuntimeActivity({ activity, className = "" }: { activity: RuntimeActivityState; className?: string }) {
25
+ const [tab, setTab] = useState("summary");
26
+ const libraries = useMemo(() => activity.current ? activityLibraries(activity.current) : [], [activity.current]);
27
+ return <section aria-label="Runtime activity" className={`flex min-h-0 flex-col overflow-hidden bg-background text-foreground ${className}`}>
28
+ <Tabs value={tab} onChange={setTab} tabs={[{ id: "libraries", label: "Libraries", count: libraries.length }, { id: "requests", label: "Requests", count: activity.current?.records.length ?? 0 }, { id: "timeline", label: "Timeline" }, { id: "summary", label: "Summary" }]} />
29
+ {!activity.current ? <p className="p-density-3 text-sm text-muted-foreground">Waiting for runtime activity. Open a page to inspect its requests and rendering.</p> : <div role="tabpanel" aria-label={tab} className="flex min-h-0 flex-1 flex-col overflow-hidden">
30
+ {tab === "libraries" && <DataTable data={libraries} columns={libraryColumns} virtualize getRowId={(r) => r.id} className="min-h-0 flex-1" />}
31
+ {tab === "requests" && <Requests key={activity.current.id} load={activity.current} />}
32
+ {tab === "timeline" && <Timeline load={activity.current} />}
33
+ {tab === "summary" && <div className="overflow-auto p-density-3"><Summary title="Current load" summary={summarizeActivity(activity.current)} />
34
+ {activity.current.runtime && <Properties<unknown> items={[{ key: "Import map", value: formatBytes(activity.current.runtime.importMapBytes) }, { key: "Scopes", value: activity.current.runtime.scopes }, { key: "Base set", value: activity.current.runtime.base }]} />}
35
+ {activity.previous && <Summary title="Previous load" summary={activity.previous} />}</div>}
36
+ </div>}
37
+ </section>;
38
+ }
39
+
40
+ function Requests({ load }: { load: ActivityLoad }) {
41
+ const [kind, setKind] = useState(""); const [pkg, setPackage] = useState(""); const [source, setSource] = useState("");
42
+ const [selected, setSelected] = useState<WorkerActivity | null>(null);
43
+ const records = useMemo(() => load.records.filter((r) => (!kind || r.kind === kind) && (!pkg || r.package?.name === pkg) && (!source || r.source === source)), [load.records, kind, pkg, source]);
44
+ return <>
45
+ <FilterBar filters={[
46
+ { kind: "enum", key: "kind", label: "Kind", value: kind, options: ["", "frame", "src", "npm", "link", "static"].map((value) => ({ value, label: value || "All kinds" })), onChange: setKind },
47
+ { kind: "enum", key: "package", label: "Package", value: pkg, options: ["", ...new Set(load.records.flatMap((r) => r.package ? [r.package.name] : []))].map((value) => ({ value, label: value || "All packages" })), onChange: setPackage },
48
+ { kind: "enum", key: "source", label: "Source", value: source, options: ["", "cache", "network", "compiled", "generated"].map((value) => ({ value, label: value || "All sources" })), onChange: setSource },
49
+ ]} className="shrink-0 p-density-2" />
50
+ <div className="flex min-h-0 flex-1 overflow-hidden">
51
+ <DataTable data={records} columns={requestColumns} virtualize getRowId={(r) => r.id} onRowClick={setSelected} className="min-h-0 min-w-0 flex-1" />
52
+ {selected && <aside aria-label="Request details" className="w-80 shrink-0 overflow-auto border-l border-border p-density-3"><Properties items={Object.entries(selected).map(([key, value]) => ({ key, value }))} valueClassName="break-all" /></aside>}
53
+ </div>
54
+ </>;
55
+ }
56
+
57
+ function Timeline({ load }: { load: ActivityLoad }) {
58
+ const marks = load.timeline.map((mark, index) => ({ name: mark.phase, start: load.timeline[index - 1]?.atMs ?? 0, end: mark.atMs, detail: formatDuration(mark.atMs) }));
59
+ const builds = load.tailwind.map((build) => ({ name: `Tailwind ${build.kind}${build.cacheHit ? " (cache)" : ""}`, start: build.startMs, end: build.startMs + build.durationMs, detail: `${build.candidates} candidates · ${formatBytes(build.cssBytes)} · ${formatDuration(build.durationMs)}` }));
60
+ const end = Math.max(1, ...marks.map((mark) => mark.end), ...builds.map((build) => build.end));
61
+ return <div className="overflow-auto p-density-3 text-sm">
62
+ <p className="mb-density-2 text-muted-foreground">Durations from navigation start. Bars show boot phases and Tailwind work.</p>
63
+ {[...marks, ...builds].map((mark, index) => <div key={index} className="grid grid-cols-[10rem_1fr_15rem] items-center gap-density-2 py-1">
64
+ <span>{mark.name}</span><div className="h-3 rounded bg-muted"><div className="h-full min-w-0.5 rounded bg-primary" style={{ marginLeft: `${mark.start / end * 100}%`, width: `${Math.max(0.1, (mark.end - mark.start) / end * 100)}%` }} /></div><span className="text-right tabular-nums">{mark.detail}</span>
65
+ </div>)}
66
+ <p className="mt-density-3">Last edit → visible reload: {load.editToVisibleMs === undefined ? "No edit in this load" : formatDuration(load.editToVisibleMs)}</p>
67
+ </div>;
68
+ }
69
+
70
+ function Summary({ title, summary }: { title: string; summary: ActivitySummary }) {
71
+ return <div className="mb-density-3"><h3 className="mb-density-2 text-sm font-medium">{title}</h3><Properties<unknown> items={[
72
+ { key: "Requests", value: summary.requests }, { key: "Transferred", value: `${formatBytes(summary.transferredBytes)}${summary.unknownTransfers ? ` + ${summary.unknownTransfers} unavailable sizes` : ""}` },
73
+ { key: "Decoded", value: formatBytes(summary.decodedBytes) }, { key: "Output", value: formatBytes(summary.outputBytes) }, { key: "Cache hits", value: `${summary.cacheHits} / ${summary.requests}` },
74
+ { key: "Compile", value: `${formatDuration(summary.compileMs)}${summary.unknownCompiles ? ` + ${summary.unknownCompiles} unavailable timings` : ""}` }, { key: "Time to ready", value: summary.readyMs === null ? "Pending" : formatDuration(summary.readyMs) },
75
+ ...Object.entries(summary.versions).map(([key, value]) => ({ key, value })),
76
+ ]} /></div>;
77
+ }
@@ -0,0 +1,18 @@
1
+ import { useState, useSyncExternalStore } from "react";
2
+ import { Tabs } from "@flanksource/clicky-ui/components";
3
+ import { RuntimeActivity } from "./RuntimeActivity.tsx";
4
+ import { BuildLog } from "./BuildLog.tsx";
5
+ import { buildLog } from "./build-log.ts";
6
+ import type { RuntimeDiagnosticsSource } from "./runtime-diagnostics.ts";
7
+
8
+ export default function RuntimeDebugPanel({ source, page, origin }: { source: RuntimeDiagnosticsSource; page: string; origin: string }) {
9
+ const state = useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);
10
+ const [tab, setTab] = useState("activity");
11
+ return <section aria-label={`Runtime diagnostics: ${page}`} className="flex min-h-0 flex-1 flex-col overflow-hidden">
12
+ <div className="flex flex-wrap items-center gap-density-2 border-b border-border px-density-3 py-density-2 text-xs"><strong>{page}</strong><span>{state.status}</span><span className="break-all text-muted-foreground">{origin}</span></div>
13
+ {state.error && <p role="alert" className="shrink-0 px-density-3 py-density-2 text-sm text-destructive">{state.error}</p>}
14
+ {state.dropped > 0 && <p className="px-density-3 text-xs text-muted-foreground">{state.dropped} older requests dropped from this capture.</p>}
15
+ <Tabs tabs={[{ id: "activity", label: "Activity" }, { id: "build", label: "Build log" }]} value={tab} onChange={setTab} />
16
+ {tab === "activity" ? <RuntimeActivity activity={state.activity} className="min-h-0 flex-1" /> : <div className="min-h-0 flex-1 overflow-auto p-density-3"><BuildLog entries={buildLog({ steps: state.steps, load: state.activity.current })} live={!["ready", "failed"].includes(state.status)} {...(state.steps[0] ? { startedAt: state.steps[0].at } : {})} /></div>}
17
+ </section>;
18
+ }
@@ -0,0 +1,69 @@
1
+ import type { ServerTimingMetric } from "@flanksource/clicky-ui/data";
2
+ import type { ActivityMessage, RuntimeResolution, TailwindActivity, WorkerActivity } from "../activity-schema.ts";
3
+
4
+ export type ActivitySummary = { requests: number; transferredBytes: number; unknownTransfers: number; unknownCompiles: number; decodedBytes: number; outputBytes: number; cacheHits: number; compileMs: number; readyMs: number | null; versions: Record<string, string> };
5
+ export type ActivityLoad = { id: string; navigationStart: number; records: WorkerActivity[]; timeline: ActivityMessage["timeline"]; tailwind: TailwindActivity[]; runtime?: RuntimeResolution; editToVisibleMs?: number };
6
+ export type RuntimeActivityState = { current: ActivityLoad | null; previous: ActivitySummary | null };
7
+ export const emptyActivity = (): RuntimeActivityState => ({ current: null, previous: null });
8
+
9
+ export function summarizeActivity(load: ActivityLoad): ActivitySummary {
10
+ return { requests: load.records.length, transferredBytes: load.records.reduce((n, r) => n + (r.transferredBytes ?? 0), 0), unknownTransfers: load.records.filter((r) => r.transferredBytes === null).length, unknownCompiles: load.records.filter((r) => r.unavailable.includes("compile")).length,
11
+ decodedBytes: load.records.reduce((n, r) => n + (r.decodedBytes ?? 0), 0), outputBytes: load.records.reduce((n, r) => n + (r.outputBytes ?? 0), 0), cacheHits: load.records.filter((r) => r.source === "cache").length,
12
+ compileMs: load.records.reduce((n, r) => n + r.compileMs, 0) + load.tailwind.reduce((n, r) => n + r.durationMs, 0), readyMs: load.timeline.find((mark) => mark.phase === "ready")?.atMs ?? null, versions: load.runtime?.versions ?? {} };
13
+ }
14
+
15
+ /**
16
+ * The load as Server-Timing metrics: `total` is the time to ready, and each phase is that phase's work
17
+ * summed over the requests that did it, so phases can exceed the total when requests overlap.
18
+ * Empty until the load is ready.
19
+ */
20
+ export function activityTimings(load: ActivityLoad): ServerTimingMetric[] {
21
+ const ready = load.timeline.find((mark) => mark.phase === "ready")?.atMs;
22
+ if (ready === undefined) return [];
23
+ const phase = (name: string, counter: string, durations: number[]): ServerTimingMetric[] => {
24
+ const worked = durations.filter((duration) => duration > 0);
25
+ return worked.length ? [{ name, duration: worked.reduce((total, duration) => total + duration, 0), counters: { [counter]: worked.length } }] : [];
26
+ };
27
+ return [
28
+ { name: "total", duration: ready, counters: {} },
29
+ ...phase("fetch", "requests", load.records.map((r) => r.fetchMs)),
30
+ ...phase("integrity", "files", load.records.map((r) => r.integrityMs)),
31
+ ...phase("compile", "modules", load.records.map((r) => r.compileMs)),
32
+ ...phase("rewrite", "modules", load.records.map((r) => r.rewriteMs)),
33
+ ...phase("tailwind", "builds", load.tailwind.map((build) => build.durationMs)),
34
+ ];
35
+ }
36
+
37
+ export function appendActivity(options: { state: RuntimeActivityState; message: ActivityMessage; editStartedAt?: number }): RuntimeActivityState {
38
+ const { message, state } = options;
39
+ if (state.current && message.navigationStart < state.current.navigationStart) return state;
40
+ const same = state.current?.id === message.load;
41
+ const current: ActivityLoad = same ? state.current! : { id: message.load, navigationStart: message.navigationStart, records: [], timeline: [], tailwind: [] };
42
+ const ids = new Set(current.records.map((record) => record.id));
43
+ const next = { ...current, records: [...current.records, ...message.records.filter((record) => !ids.has(record.id))], timeline: message.timeline.length ? message.timeline : current.timeline, tailwind: [...current.tailwind, ...message.tailwind], ...(message.runtime ? { runtime: message.runtime } : {}) };
44
+ const visible = next.timeline.find((mark) => mark.phase === "visible");
45
+ if (visible && options.editStartedAt !== undefined && options.editStartedAt < next.navigationStart) next.editToVisibleMs = next.navigationStart + visible.atMs - options.editStartedAt;
46
+ return { current: next, previous: same ? state.previous : state.current ? summarizeActivity(state.current) : state.previous };
47
+ }
48
+
49
+ export type ActivityLibrary = { id: string; name: string; version: string; origin: string; files: number; transferredBytes: number; unknownTransfers: number; decodedBytes: number; cacheRatio: number; role: "managed library" | "base set" | "additional package" };
50
+ export function activityLibraries(load: ActivityLoad): ActivityLibrary[] {
51
+ const groups = new Map<string, { name: string; version: string; records: WorkerActivity[]; base: boolean }>();
52
+ for (const record of load.records) if (record.package) {
53
+ const baseEntry = Object.entries(load.runtime?.base ?? {}).find(([, url]) => new URL(url, record.url).pathname === new URL(record.url).pathname);
54
+ const baseName = baseEntry?.[0].startsWith("@") ? baseEntry[0].split("/").slice(0, 2).join("/") : baseEntry?.[0].split("/")[0];
55
+ const version = baseName ? load.runtime?.versions[baseName] : undefined;
56
+ const name = version && baseName ? baseName : record.package.name;
57
+ const resolvedVersion = version ?? record.package.version;
58
+ const key = `${name}@${resolvedVersion}`;
59
+ const group = groups.get(key);
60
+ if (group) group.records.push(record);
61
+ else groups.set(key, { name, version: resolvedVersion, records: [record], base: Boolean(baseEntry) });
62
+ }
63
+ return [...groups].map(([id, { name, version, records, base }]) => {
64
+ const first = records[0]!; const pkg = first.package!;
65
+ return { id, name, version, origin: first.origin ? first.origin.slice(0, first.origin.length - pkg.path.length) : "", files: new Set(records.map((r) => r.package!.path)).size,
66
+ transferredBytes: records.reduce((n, r) => n + (r.transferredBytes ?? 0), 0), unknownTransfers: records.filter((r) => r.transferredBytes === null).length, decodedBytes: records.reduce((n, r) => n + (r.decodedBytes ?? 0), 0), cacheRatio: records.filter((r) => r.source === "cache").length / records.length,
67
+ role: load.runtime?.managed.includes(name) ? "managed library" : base ? "base set" : "additional package" };
68
+ });
69
+ }
@@ -0,0 +1,14 @@
1
+ import { parseEditableSource } from "../markers.ts";
2
+
3
+ export function isPageSource(source: string): boolean {
4
+ if (/^(?:file|data|blob|javascript):/i.test(source)) return false;
5
+ if (source.includes("#")) {
6
+ try { parseEditableSource(source); } catch { return false; }
7
+ } else if (!/^.+:[1-9]\d*:[1-9]\d*$/.test(source)) return false;
8
+ return !/(?:^|\/)(?:node_modules|npm|link|entry|__runtime)\/|(?:^|\/)packages\/(?:ui|react-grab|facet)\//.test(source);
9
+ }
10
+
11
+ export function validateDocumentSource(url: string): void {
12
+ const parsed = new URL(url);
13
+ if (!["http:", "https:", "file:"].includes(parsed.protocol) || parsed.href !== url || parsed.username || parsed.password) throw new Error("external-document source requires a canonical credential-free HTTP(S) or file document URL");
14
+ }
@@ -0,0 +1,73 @@
1
+ import type { AgentFrameMessage, AgentHostMessage } from "../schema.ts";
2
+ import { keys, record } from "../sw/profile.ts";
3
+ import { validateDesignMessage } from "./design-validation.ts";
4
+ import { text, number, list, rect, locator, validateAgentSelection } from "./message-values.ts";
5
+
6
+ export function validateAgentFrameMessage(value: unknown): AgentFrameMessage {
7
+ const m = record(value, "agent");
8
+ switch (m.type) {
9
+ case "design-selection": case "design-override-result": case "design-write-request": case "design-write-result": return validateDesignMessage(m, "frame") as AgentFrameMessage;
10
+ case "selection": keys(m, ["type", "selection"], "agent"); validateAgentSelection(m.selection); break;
11
+ case "vocabulary-previews": {
12
+ keys(m, ["type", "images"], "agent");
13
+ if (!Array.isArray(m.images) || m.images.length > 2000) throw new Error("vocabulary-previews.images: expected at most 2000 images");
14
+ const ids = new Set<string>();
15
+ for (const value of m.images) {
16
+ const image = record(value, "vocabulary preview");
17
+ keys(image, ["id", "image", "width", "height"], "vocabulary preview");
18
+ if (typeof image.id !== "string" || !image.id) throw new Error("vocabulary preview.id: expected non-empty string");
19
+ if (typeof image.image !== "string" || !image.image.startsWith("data:image/webp;base64,")) throw new Error(`vocabulary preview ${image.id}.image: expected WebP data URL`);
20
+ for (const dimension of ["width", "height"]) {
21
+ if (typeof image[dimension] !== "number" || !Number.isFinite(image[dimension]) || image[dimension] <= 0) throw new Error(`vocabulary preview ${image.id}.${dimension}: expected positive finite number`);
22
+ }
23
+ if (ids.has(image.id)) throw new Error(`duplicate vocabulary preview id ${image.id}`);
24
+ ids.add(image.id);
25
+ }
26
+ break;
27
+ }
28
+ case "anchors":
29
+ keys(m, ["type", "anchors"], "agent");
30
+ list(m.anchors).forEach((value) => {
31
+ const a = record(value, "anchor"); keys(a, ["anchor", "state", "label", "rect"], "anchor"); text(a.anchor); text(a.label);
32
+ if (a.state === "orphaned") { if (a.rect !== null) throw new Error("orphaned anchor must have null rect"); }
33
+ else if (a.state === "found" || a.state === "moved") rect(a.rect);
34
+ else throw new Error("invalid anchor state");
35
+ }); break;
36
+ case "focus": keys(m, ["type", "anchor"], "agent"); text(m.anchor); break;
37
+ case "keys":
38
+ keys(m, ["type", "key", "ctrlKey", "metaKey", "shiftKey", "altKey"], "agent");
39
+ if (m.key !== "Escape" && m.key !== "c") throw new Error("invalid forwarded key");
40
+ for (const key of ["ctrlKey", "metaKey", "shiftKey", "altKey"]) if (typeof m[key] !== "boolean") throw new Error("invalid key modifier");
41
+ break;
42
+ case "geometry":
43
+ keys(m, ["type", "scrollX", "scrollY", "width", "height"], "agent"); number(m.scrollX); number(m.scrollY); number(m.width, 0); number(m.height, 0); break;
44
+ default: throw new Error("unsupported agent frame message");
45
+ }
46
+ return m as AgentFrameMessage;
47
+ }
48
+
49
+ export function validateAgentHostMessage(value: unknown): AgentHostMessage {
50
+ const m = record(value, "agent");
51
+ switch (m.type) {
52
+ case "design-override": case "design-write": case "design-write-result": return validateDesignMessage(m, "host") as AgentHostMessage;
53
+ case "mode": keys(m, ["type", "mode"], "agent"); if (m.mode !== "off" && m.mode !== "comment" && m.mode !== "design") throw new Error("invalid agent mode"); break;
54
+ case "pick": case "page": case "capture-vocabulary": keys(m, ["type"], "agent"); break;
55
+ case "pins":
56
+ keys(m, ["type", "anchors", "focus"], "agent");
57
+ if (m.focus !== undefined && m.focus !== null) text(m.focus);
58
+ list(m.anchors).forEach((value) => {
59
+ const p = record(value, "pin"); keys(p, ["anchor", "count", "locators"], "pin"); text(p.anchor); number(p.count, 1);
60
+ if (!Number.isInteger(p.count)) throw new Error("invalid pin count");
61
+ list(p.locators).forEach(locator);
62
+ }); break;
63
+ case "highlight": keys(m, ["type", "anchor"], "agent"); if (m.anchor !== null) text(m.anchor); break;
64
+ case "scroll":
65
+ keys(m, ["type", "anchor", "behavior", "block", "offset"], "agent"); text(m.anchor);
66
+ if (m.behavior !== undefined && !["auto", "smooth", "instant"].includes(String(m.behavior))) throw new Error("invalid scroll behavior");
67
+ if (m.block !== undefined && m.block !== "start" && m.block !== "center") throw new Error("invalid scroll block");
68
+ if (m.offset !== undefined) number(m.offset);
69
+ break;
70
+ default: throw new Error("unsupported agent host message");
71
+ }
72
+ return m as AgentHostMessage;
73
+ }
@@ -0,0 +1,56 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import type { BridgeEnvelope, FrameMessage, HostMessage } from "../schema.ts";
3
+ import { validateEnvelope } from "./validation.ts";
4
+
5
+ export type BridgeOptions = {
6
+ target: Window; origin: string; session: string; direction: "host" | "frame";
7
+ onMessage: (envelope: BridgeEnvelope) => void;
8
+ onError: (error: Error) => void;
9
+ window?: Window; timeoutMs?: number;
10
+ };
11
+
12
+ export function createBridge(options: BridgeOptions) {
13
+ if (new URL(options.origin).origin !== options.origin || !options.session) throw new Error("bridge requires an exact origin and session");
14
+ const local = options.window ?? window;
15
+ const pending = new Map<string, { resolve: (m: BridgeEnvelope) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();
16
+ const inbound = options.direction === "host" ? "frame" : "host";
17
+ const receive = (event: MessageEvent<unknown>) => {
18
+ if (event.origin !== options.origin || event.source !== options.target) return;
19
+ try {
20
+ const message = validateEnvelope(event.data, inbound);
21
+ if (message.session !== options.session) return;
22
+ const request = message.re ? pending.get(message.re) : undefined;
23
+ if (request && message.re) {
24
+ clearTimeout(request.timer); pending.delete(message.re);
25
+ if (message.message.type === "error") request.reject(new Error(`${message.message.error.phase}: ${message.message.error.message}`)); else request.resolve(message);
26
+ } else options.onMessage(message);
27
+ } catch (error) { options.onError(error instanceof Error ? error : new Error(String(error))); }
28
+ };
29
+ local.addEventListener("message", receive);
30
+ let disposed = false;
31
+ function send(message: HostMessage | FrameMessage, reference?: { id?: string; re?: string }) {
32
+ if (disposed) throw new Error("bridge is disposed");
33
+ const envelope: BridgeEnvelope = { bridge: "page-runtime-v1", session: options.session, ...reference, message };
34
+ validateEnvelope(envelope, options.direction);
35
+ options.target.postMessage(envelope, options.origin);
36
+ }
37
+ return {
38
+ send,
39
+ request(message: HostMessage | FrameMessage, requestOptions: { timeoutMs?: number } = {}): Promise<BridgeEnvelope> {
40
+ const id = randomUUID();
41
+ return new Promise((resolve, reject) => {
42
+ const timeoutMs = requestOptions.timeoutMs ?? options.timeoutMs ?? 15000;
43
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("bridge request timeout must be a positive finite number");
44
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`bridge request ${id} timed out`)); }, timeoutMs);
45
+ pending.set(id, { resolve, reject, timer });
46
+ try { send(message, { id }); } catch (error) { clearTimeout(timer); pending.delete(id); reject(error); }
47
+ });
48
+ },
49
+ dispose() {
50
+ disposed = true; local.removeEventListener("message", receive);
51
+ for (const request of pending.values()) { clearTimeout(request.timer); request.reject(new Error("bridge disposed")); }
52
+ pending.clear();
53
+ },
54
+ };
55
+ }
56
+ export type PageBridge = ReturnType<typeof createBridge>;
@@ -0,0 +1,29 @@
1
+ import type { ActivityLoad } from "./activity-state.ts";
2
+
3
+ /** A host-observed load step, stamped in epoch milliseconds (`performance.timeOrigin + performance.now()`). */
4
+ export type BuildStep = { label: string; at: number; source: "host" | "frame"; error?: string };
5
+ export type BuildLogEntry = { label: string; source: "host" | "frame" | "timeline" | "tailwind"; offsetMs: number; durationMs: number | null; error?: string };
6
+
7
+ /**
8
+ * One timed log of a page load: host and frame steps offset from the first step, each lasting until the
9
+ * next step (`null` while the last is still running), merged with the frame's timeline marks and Tailwind
10
+ * builds once the frame has reported activity.
11
+ */
12
+ export function buildLog({ steps, load }: { steps: BuildStep[]; load: ActivityLoad | null }): BuildLogEntry[] {
13
+ const start = steps[0]?.at;
14
+ if (start === undefined) {
15
+ if (load) throw new Error(`buildLog: load ${load.id} has activity but no recorded build steps to time it against`);
16
+ return [];
17
+ }
18
+ const entries: BuildLogEntry[] = steps.map((step, index) => {
19
+ const next = steps[index + 1];
20
+ return { label: step.label, source: step.source, offsetMs: step.at - start, durationMs: step.error ? 0 : next ? next.at - step.at : null, ...(step.error ? { error: step.error } : {}) };
21
+ });
22
+ // A frame navigation that began before the first step belongs to the previous load.
23
+ if (load && load.navigationStart >= start) {
24
+ const base = load.navigationStart - start;
25
+ load.timeline.forEach((mark, index) => entries.push({ label: mark.phase, source: "timeline", offsetMs: base + mark.atMs, durationMs: mark.atMs - (load.timeline[index - 1]?.atMs ?? 0) }));
26
+ for (const build of load.tailwind) entries.push({ label: `Tailwind ${build.kind}${build.cacheHit ? " (cache)" : ""}`, source: "tailwind", offsetMs: base + build.startMs, durationMs: build.durationMs });
27
+ }
28
+ return entries.sort((a, b) => a.offsetMs - b.offsetMs);
29
+ }
@@ -0,0 +1,66 @@
1
+ import { RUNTIME_DB } from "../storage/db.ts";
2
+
3
+ /** Every Cache Storage cache the runtime creates (pages, compiled, packages, tailwind, link sizes, legacy tailwind) is named with this prefix. */
4
+ export const PAGE_RUNTIME_CACHE_PREFIX = "page-runtime-";
5
+
6
+ export type ClearPageRuntimeCacheOptions = {
7
+ /** Origin the runtime service worker is registered on. */
8
+ runtimeOrigin: string;
9
+ /** Scope the host registered the runtime worker with, for example `/frame/`. Resolved against `runtimeOrigin`. */
10
+ scope: string;
11
+ /** Defaults to the global `caches`. */
12
+ caches?: CacheStorage;
13
+ /** Defaults to the global `indexedDB`. */
14
+ indexedDB?: IDBFactory;
15
+ /** Defaults to `navigator.serviceWorker`. */
16
+ serviceWorker?: Pick<ServiceWorkerContainer, "getRegistrations">;
17
+ };
18
+
19
+ export type ClearedPageRuntimeCache = {
20
+ /** Names of the deleted Cache Storage caches. */
21
+ caches: string[];
22
+ /** Names of the deleted IndexedDB databases. */
23
+ databases: string[];
24
+ /** Scopes of the unregistered service worker registrations. */
25
+ registrations: string[];
26
+ };
27
+
28
+ function deleteDatabase(options: { factory: IDBFactory; name: string }): Promise<void> {
29
+ return new Promise((resolve, reject) => {
30
+ const request = options.factory.deleteDatabase(options.name);
31
+ request.onsuccess = () => resolve();
32
+ request.onerror = () => reject(new Error(`${options.name} database could not be deleted: ${request.error?.message ?? "unknown IndexedDB error"}`));
33
+ request.onblocked = () => reject(new Error(`${options.name} database deletion is blocked by another open connection; close other tabs of this runtime`));
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Wipes everything the page runtime stored in the browser so the next open resolves, compiles and fetches from scratch:
39
+ * the registrations of the runtime worker for `scope`, every `page-runtime-*` Cache Storage cache, and the `page-runtime`
40
+ * IndexedDB database (candidates and Tailwind records). Host-side state, including `localStorage` overrides and the
41
+ * host-origin `page-runtime-links` store of linked checkouts, is left alone. The host reopens its pages afterwards, which
42
+ * registers the worker again and writes fresh page records. Any browser API that is unavailable or refuses is an error.
43
+ */
44
+ export async function clearPageRuntimeCache(options: ClearPageRuntimeCacheOptions): Promise<ClearedPageRuntimeCache> {
45
+ const storage = options.caches ?? (typeof caches === "undefined" ? undefined : caches);
46
+ if (!storage) throw new Error("Cache Storage is unavailable; the page runtime cache cannot be cleared");
47
+ const factory = options.indexedDB ?? (typeof indexedDB === "undefined" ? undefined : indexedDB);
48
+ if (!factory) throw new Error("IndexedDB is unavailable; the page runtime cache cannot be cleared");
49
+ const workers = options.serviceWorker ?? (typeof navigator === "undefined" ? undefined : navigator.serviceWorker);
50
+ if (!workers) throw new Error("Service workers are unavailable; the page runtime cache cannot be cleared");
51
+ const scope = new URL(options.scope, options.runtimeOrigin).href;
52
+ const registrations: string[] = [];
53
+ for (const registration of await workers.getRegistrations()) {
54
+ if (registration.scope !== scope) continue;
55
+ if (!await registration.unregister()) throw new Error(`The browser could not unregister the runtime service worker for ${registration.scope}`);
56
+ registrations.push(registration.scope);
57
+ }
58
+ const cleared: string[] = [];
59
+ for (const name of await storage.keys()) {
60
+ if (!name.startsWith(PAGE_RUNTIME_CACHE_PREFIX)) continue;
61
+ if (!await storage.delete(name)) throw new Error(`Cache Storage did not delete ${name}`);
62
+ cleared.push(name);
63
+ }
64
+ await deleteDatabase({ factory, name: RUNTIME_DB });
65
+ return { caches: cleared, databases: [RUNTIME_DB], registrations };
66
+ }
@@ -0,0 +1,17 @@
1
+ import { lazy, Suspense } from "react";
2
+ import { debugCaptureHeaders, registerDebugRuntime } from "@flanksource/clicky-ui/data";
3
+ import { createRuntimeDiagnostics } from "./runtime-diagnostics.ts";
4
+
5
+ const RuntimeDebugPanel = lazy(() => import("./RuntimeDebugPanel.tsx"));
6
+
7
+ export function registerPageRuntimeDebug(options: { session: string; page: string; origin: string }) {
8
+ const source = createRuntimeDiagnostics({ capture: () => Boolean(debugCaptureHeaders()["X-Debug-Level"]) });
9
+ const dispose = registerDebugRuntime({
10
+ id: options.session,
11
+ label: options.page,
12
+ state: source,
13
+ clear: source.clear,
14
+ content: <Suspense fallback={<p className="p-density-3 text-sm text-muted-foreground">Loading runtime diagnostics…</p>}><RuntimeDebugPanel source={source} page={options.page} origin={options.origin} /></Suspense>,
15
+ });
16
+ return { ...source, dispose };
17
+ }
@@ -0,0 +1,96 @@
1
+ import type { DesignFrameMessage, DesignHostMessage } from "../schema.ts";
2
+ import { parseEditableSource } from "../markers.ts";
3
+ import { record, keys } from "../sw/profile.ts";
4
+ import { isPageSource } from "./agent-source.ts";
5
+ import { validateAgentSelection, validateJson } from "./message-values.ts";
6
+
7
+ function text(value: unknown, empty = false): asserts value is string {
8
+ if (typeof value !== "string" || (!empty && !value) || value.length > 10000) throw new Error("design: invalid text");
9
+ }
10
+ function position(value: unknown): void {
11
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new Error("design: invalid position");
12
+ }
13
+ function source(value: unknown): void {
14
+ text(value); parseEditableSource(value);
15
+ if (!isPageSource(value)) throw new Error("design: expected editable page source");
16
+ }
17
+ function prop(name: string): void {
18
+ if (!/^[a-zA-Z][\w-]*$/.test(name) || /^(?:on[A-Z]|data-source$|__|ref$|key$|dangerouslySetInnerHTML$)/.test(name)) throw new Error(`design: invalid prop ${name}`);
19
+ }
20
+ function props(value: unknown): void {
21
+ for (const [name, item] of Object.entries(record(value, "design.props"))) { prop(name); validateJson(item); }
22
+ }
23
+ function edit(value: unknown): void {
24
+ const e = record(value, "design.edit");
25
+ switch (e.kind) {
26
+ case "delete": keys(e, ["kind"], "edit"); break;
27
+ case "style":
28
+ keys(e, ["kind", "prop", "value"], "edit");
29
+ if (e.prop !== "variant" && e.prop !== "role") throw new Error("design: invalid style prop");
30
+ text(e.value, true); break;
31
+ case "text":
32
+ keys(e, ["kind", "prop", "from", "to"], "edit"); text(e.prop); prop(e.prop); text(e.from, true); text(e.to, true); break;
33
+ case "attributes":
34
+ keys(e, ["kind", "values", "textFrom"], "edit");
35
+ if (e.textFrom !== undefined) text(e.textFrom, true);
36
+ if (!Object.keys(record(e.values, "attributes")).length) throw new Error("design: attributes are empty");
37
+ for (const [name, item] of Object.entries(record(e.values, "attributes"))) {
38
+ prop(name);
39
+ if (item !== null && typeof item !== "string" && !(typeof item === "number" && Number.isFinite(item))) throw new Error("design: invalid attribute value");
40
+ }
41
+ break;
42
+ default: throw new Error("design: invalid edit kind");
43
+ }
44
+ }
45
+ function result(value: unknown): void {
46
+ const r = record(value, "design.result");
47
+ switch (r.status) {
48
+ case "applied":
49
+ keys(r, ["status", "file", "path", "line", "hash"], "result"); text(r.file); text(r.path); position(r.line); text(r.hash);
50
+ if (!/^[0-9a-f]{12}$/.test(r.hash)) throw new Error("design: invalid result hash");
51
+ break;
52
+ case "stale": keys(r, ["status", "error", "file"], "result"); text(r.error); text(r.file); break;
53
+ case "invalid": keys(r, ["status", "error"], "result"); text(r.error); break;
54
+ case "refused":
55
+ keys(r, ["status", "error", "reason", "file", "line", "column", "attribute"], "result");
56
+ text(r.error); text(r.reason); text(r.file); position(r.line); position(r.column);
57
+ if (r.attribute !== undefined) text(r.attribute);
58
+ break;
59
+ case "ambiguous":
60
+ keys(r, ["status", "error", "candidates"], "result"); text(r.error);
61
+ if (!Array.isArray(r.candidates) || !r.candidates.length || r.candidates.length > 10000) throw new Error("design: invalid candidates");
62
+ for (const value of r.candidates) {
63
+ const c = record(value, "candidate"); keys(c, ["id", "file", "line", "column", "context"], "candidate");
64
+ text(c.id); text(c.file); position(c.line); position(c.column); text(c.context, true);
65
+ }
66
+ break;
67
+ default: throw new Error("design: invalid result status");
68
+ }
69
+ }
70
+
71
+ export function validateDesignMessage(m: Record<string, unknown>, direction: "host" | "frame"): DesignHostMessage | DesignFrameMessage {
72
+ if (m.type === "design-selection" && direction === "frame") {
73
+ keys(m, ["type", "selection", "source", "props"], "design"); validateAgentSelection(m.selection); source(m.source); props(m.props);
74
+ const element = record(record(m.selection, "selection").element, "element");
75
+ if (element.source !== m.source || element.sourceContext !== undefined) throw new Error("design: selection must match the editable page source");
76
+ return m as DesignFrameMessage;
77
+ }
78
+ text(m.requestId);
79
+ if (m.type === "design-write-result") {
80
+ keys(m, ["type", "requestId", "result"], "design"); result(m.result);
81
+ } else if (m.type === "design-override" && direction === "host") {
82
+ keys(m, ["type", "requestId", "source", "props"], "design"); source(m.source); props(m.props);
83
+ if (!Object.keys(m.props as object).length) throw new Error("design: override is empty");
84
+ } else if (m.type === "design-override-result" && direction === "frame") {
85
+ keys(m, m.ok === true ? ["type", "requestId", "source", "ok"] : ["type", "requestId", "source", "ok", "error"], "design"); source(m.source);
86
+ if (m.ok === false) text(m.error); else if (m.ok !== true) throw new Error("design: invalid override result");
87
+ } else if (m.type === "design-write" && direction === "host") {
88
+ keys(m, ["type", "requestId", "page", "source", "edit", "choose"], "design"); text(m.page); source(m.source); edit(m.edit);
89
+ if (m.choose !== undefined) text(m.choose);
90
+ } else if (m.type === "design-write-request" && direction === "frame") {
91
+ keys(m, ["type", "requestId", "request"], "design");
92
+ const r = record(m.request, "request"); keys(r, ["page", "source", "edit", "choose"], "request"); text(r.page); source(r.source); edit(r.edit);
93
+ if (r.choose !== undefined) text(r.choose);
94
+ } else throw new Error("design: unsupported message direction");
95
+ return m as DesignHostMessage | DesignFrameMessage;
96
+ }
@@ -0,0 +1,12 @@
1
+ export { PageFrame, type PageFrameProps } from "./PageFrame.tsx";
2
+ export { PageForm, type PageFormProps } from "./PageForm.tsx";
3
+ export { createBridge, type BridgeOptions, type PageBridge } from "./bridge.ts";
4
+ export { validateEnvelope, validateFrameMessage, validateHostMessage } from "./validation.ts";
5
+ export { RuntimeActivity } from "./RuntimeActivity.tsx";
6
+ export { clearPageRuntimeCache, PAGE_RUNTIME_CACHE_PREFIX, type ClearedPageRuntimeCache, type ClearPageRuntimeCacheOptions } from "./clear-cache.ts";
7
+ export { BuildLog } from "./BuildLog.tsx";
8
+ export { buildLog, type BuildLogEntry, type BuildStep } from "./build-log.ts";
9
+ export { activityTimings, appendActivity, emptyActivity, summarizeActivity, type RuntimeActivityState } from "./activity-state.ts";
10
+ export type { ActivityMessage, WorkerActivity, TailwindActivity } from "../activity-schema.ts";
11
+ export { createRemoteReview, validateReviewFrameMessage, validateReviewHostMessage } from "./review/index.ts";
12
+ export type { RemoteReviewOptions, ReviewAction, ReviewElement, ReviewHostMessage, ReviewFrameMessage, ReviewState, ReviewActionRequest } from "./review/index.ts";