@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,61 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import type { CompilerPlugin, FrameConfig, PageLock } from "../schema.ts";
3
+ import { EXPORT_COMPILER_URL } from "../sw/runtime-module.ts";
4
+ import { waitForReadiness } from "./readiness.ts";
5
+
6
+ type ExportModule = { default: unknown; ready?: (() => Promise<void>) | Promise<void> };
7
+ type Mounted = { mounted: Promise<void>; unmount: () => void };
8
+
9
+ /** The remark plugins a page's libraries declare for exports, in library order. */
10
+ export function exportPlugins(lock: PageLock): CompilerPlugin[] {
11
+ return Object.values(lock.compiler ?? {}).flatMap((plugins) => plugins.remark);
12
+ }
13
+
14
+ /**
15
+ * Compiles a Markdown page with its libraries' export plugins, registers the result with the worker, and imports it.
16
+ * Returns null when the live render already is the export: the page is not Markdown, or no library declares plugins.
17
+ */
18
+ export async function exportPageModule<T extends ExportModule>(options: { config: FrameConfig; request: (message: unknown) => Promise<void> }): Promise<T | null> {
19
+ const { config } = options;
20
+ const plugins = exportPlugins(config.lock);
21
+ if (!/\.mdx?$/.test(config.page) || !plugins.length) return null;
22
+ const entry = new URL(config.entry, location.href);
23
+ const raw = new URL(entry); raw.searchParams.set("raw", "");
24
+ const [{ default: source }, { compileExportMdx }, ...loaded] = await Promise.all([
25
+ import(raw.href) as Promise<{ default: string }>,
26
+ import(EXPORT_COMPILER_URL) as Promise<typeof import("./export-compiler.ts")>,
27
+ ...plugins.map((plugin) => import(plugin.module) as Promise<{ default: unknown }>),
28
+ ]);
29
+ const remark = plugins.map((plugin, index) => {
30
+ const module = loaded[index]!;
31
+ if (typeof module.default !== "function") throw new Error(`${plugin.module}: compiler plugin must default-export a function`);
32
+ return plugin.options === undefined ? module.default : [module.default, plugin.options];
33
+ });
34
+ const code = await compileExportMdx({ path: config.page, code: source, remark });
35
+ await options.request({ page: config.page, message: { type: "export-module", path: config.page, code } });
36
+ const url = new URL(entry); url.searchParams.set("export", randomUUID());
37
+ return await import(url.href) as T;
38
+ }
39
+
40
+ /**
41
+ * Prepares export-only markup offscreen while the live page stays visible, then exposes it for snapshot/print.
42
+ */
43
+ export async function withExportRender<T, M extends ExportModule>(options: { config: FrameConfig; root: HTMLElement; request: (message: unknown) => Promise<void>; mount: (module: M, root: HTMLElement) => Mounted; run: () => Promise<T> }): Promise<T> {
44
+ const module = await exportPageModule<M>(options);
45
+ if (!module) return options.run();
46
+ const container = document.createElement("div");
47
+ container.dataset.pageRuntimeExport = "";
48
+ container.style.cssText = `position:fixed;left:-100000px;top:0;width:${options.root.getBoundingClientRect().width}px;pointer-events:none`;
49
+ options.root.after(container);
50
+ let mounted: Mounted | undefined;
51
+ try {
52
+ mounted = options.mount(module, container);
53
+ await waitForReadiness({ root: container, mounted: mounted.mounted, ...(module.ready ? { hook: module.ready } : {}), timeoutMs: options.config.profile.readinessTimeoutMs, status: () => undefined });
54
+ options.root.hidden = true; options.root.dataset.pageRuntimeLive = "";
55
+ container.removeAttribute("style");
56
+ return await options.run();
57
+ } finally {
58
+ mounted?.unmount(); container.remove();
59
+ options.root.hidden = false; delete options.root.dataset.pageRuntimeLive;
60
+ }
61
+ }
@@ -0,0 +1,89 @@
1
+ import postcss from "postcss";
2
+
3
+ function importConditions(css: string, suffix: string): string {
4
+ let rest = suffix.trim();
5
+ const layer = /^layer(?:\(([^)]+)\))?(?:\s+|$)/.exec(rest);
6
+ if (layer) rest = rest.slice(layer[0].length);
7
+ let supports = "";
8
+ if (rest.startsWith("supports(")) {
9
+ let depth = 1; let index = "supports(".length;
10
+ for (; index < rest.length && depth > 0; index++) {
11
+ if (rest[index] === "(") depth++; else if (rest[index] === ")") depth--;
12
+ }
13
+ if (depth) throw new Error(`HTML export invalid @import supports condition: ${rest}`);
14
+ supports = rest.slice("supports".length, index); rest = rest.slice(index).trim();
15
+ }
16
+ let result = rest ? `@media ${rest} {${css}}` : css;
17
+ if (supports) result = `@supports ${supports} {${result}}`;
18
+ if (layer) result = `@layer ${layer[1] ?? ""} {${result}}`;
19
+ return result;
20
+ }
21
+
22
+ async function assetUrl(url: string): Promise<string> {
23
+ if (url.startsWith("data:")) return url;
24
+ const response = await fetch(url);
25
+ if (!response.ok) throw new Error(`HTML export asset ${url}: HTTP ${response.status}`);
26
+ const bytes = new Uint8Array(await response.arrayBuffer());
27
+ let binary = "";
28
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
29
+ return `data:${response.headers.get("content-type") ?? "application/octet-stream"};base64,${btoa(binary)}`;
30
+ }
31
+
32
+ async function inlineCss(options: { css: string; url: string; parents: string[] }): Promise<string> {
33
+ if (options.parents.includes(options.url)) throw new Error(`HTML export cyclic stylesheet import: ${options.url}`);
34
+ const ast = postcss.parse(options.css, { from: options.url });
35
+ const imports: Promise<void>[] = [];
36
+ ast.walkAtRules("import", (rule) => {
37
+ imports.push((async () => {
38
+ const match = /^(?:url\(\s*["']?([^"')]+)["']?\s*\)|["']([^"']+)["'])\s*(.*)$/.exec(rule.params);
39
+ if (!match) throw new Error(`HTML export unsupported @import: ${rule.params}`);
40
+ const url = new URL(match[1] ?? match[2]!, options.url).href;
41
+ const response = await fetch(url);
42
+ if (!response.ok) throw new Error(`HTML export stylesheet ${url}: HTTP ${response.status}`);
43
+ const css = await inlineCss({ css: await response.text(), url, parents: [...options.parents, options.url] });
44
+ rule.replaceWith(postcss.parse(importConditions(css, match[3]!)));
45
+ })());
46
+ });
47
+ await Promise.all(imports);
48
+ const assets: Promise<void>[] = [];
49
+ ast.walkDecls((decl) => {
50
+ const urls = [...decl.value.matchAll(/url\(\s*(["']?)([^"')]+)\1\s*\)/g)];
51
+ if (!urls.length) return;
52
+ assets.push((async () => {
53
+ for (const match of urls.reverse()) {
54
+ const target = match[2]!;
55
+ if (target.startsWith("data:") || target.startsWith("#")) continue;
56
+ const data = await assetUrl(new URL(target, options.url).href);
57
+ decl.value = `${decl.value.slice(0, match.index)}url(${JSON.stringify(data)})${decl.value.slice(match.index! + match[0].length)}`;
58
+ }
59
+ })());
60
+ });
61
+ await Promise.all(assets);
62
+ return ast.toString();
63
+ }
64
+
65
+ export async function exportHtml(): Promise<string> {
66
+ const clone = document.documentElement.cloneNode(true) as HTMLElement;
67
+ clone.querySelectorAll("script").forEach((node) => node.remove());
68
+ clone.querySelectorAll("[data-page-agent], [data-react-grab]").forEach((node) => node.remove());
69
+ // During an export render (export-page.ts) the live root is hidden and the export compile renders after it.
70
+ const exportRender = clone.querySelector<HTMLElement>("[data-page-runtime-export]");
71
+ if (exportRender) { clone.querySelector("[data-page-runtime-live]")?.remove(); exportRender.removeAttribute("data-page-runtime-export"); exportRender.id = "root"; }
72
+ for (const link of clone.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')) {
73
+ const response = await fetch(link.href);
74
+ if (!response.ok) throw new Error(`HTML export stylesheet ${link.href}: HTTP ${response.status}`);
75
+ const style = document.createElement("style"); style.textContent = await inlineCss({ css: await response.text(), url: link.href, parents: [] }); link.replaceWith(style);
76
+ }
77
+ for (const sheet of document.adoptedStyleSheets) {
78
+ const style = document.createElement("style"); style.textContent = [...sheet.cssRules].map((rule) => rule.cssText).join("\n"); clone.querySelector("head")!.append(style);
79
+ }
80
+ for (const style of clone.querySelectorAll("style")) style.textContent = await inlineCss({ css: style.textContent, url: location.href, parents: [] });
81
+ const originals = [...document.images].filter((image) => !image.closest("[data-page-agent], [data-react-grab]") && !(exportRender && image.closest("[data-page-runtime-live]")));
82
+ for (const [index, image] of [...clone.querySelectorAll<HTMLImageElement>("img")].entries()) {
83
+ const original = originals[index];
84
+ if (!original) throw new Error("HTML export image disappeared from source document");
85
+ image.src = await assetUrl(original.currentSrc); image.removeAttribute("srcset"); image.removeAttribute("sizes");
86
+ }
87
+ clone.querySelectorAll("picture source").forEach((source) => source.remove());
88
+ return `<!doctype html>\n${clone.outerHTML}`;
89
+ }
@@ -0,0 +1,8 @@
1
+ export { bootFrame, ensureController, type PageStyles } from "./boot.ts";
2
+ export type { PageModule } from "./mount-page.ts";
3
+ export { waitForReadiness, type ReadinessOptions } from "./readiness.ts";
4
+ export { createFrameBridge, workerRequest } from "./bridge.ts";
5
+ export { validateHostMessage } from "../host/validation.ts";
6
+ export { exportHtml } from "./export.ts";
7
+ export { startPageAgent, type PageAgent, type PageAgentOptions } from "./agent/index.ts";
8
+ export { PageAgentProvider } from "./agent/provider.tsx";
@@ -0,0 +1,36 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { afterAll, beforeAll, expect, it } from "vitest";
4
+ import { startRuntimeTestServer } from "./testing/server.ts";
5
+
6
+ const exec = promisify(execFile);
7
+ const session = `page-runtime-P-local-${process.pid}`;
8
+ let server: Awaited<ReturnType<typeof startRuntimeTestServer>>;
9
+ let launched = false;
10
+ async function browser(...args: string[]) {
11
+ return (await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2000000 })).stdout.trim();
12
+ }
13
+ beforeAll(async () => { server = await startRuntimeTestServer({ local: true }); });
14
+ afterAll(async () => { try { if (launched) await browser("close"); } finally { await server?.close(); } });
15
+ it.each([{ width: 1920, height: 1080 }, { width: 2560, height: 1440 }])("keeps the local host outside worker scope and executes Design in its frame at $width x $height", async (viewport) => {
16
+ await browser("open", server.hostOrigin); launched = true;
17
+ await browser("set", "viewport", String(viewport.width), String(viewport.height));
18
+ await browser("wait", "--fn", 'document.title === "LOCAL-READY" || Boolean(document.querySelector("#error")?.textContent)').catch(async (error: unknown) => { throw new Error(`${String(error)}\nBrowser errors: ${await browser("errors")}\nEvents: ${await browser("get", "text", "body")}`); });
19
+ expect(await browser("get", "text", "#error")).toBe("");
20
+ await browser("click", "#inspect");
21
+ await browser("wait", "--fn", 'document.querySelector("#inspection").textContent.includes("target")');
22
+ const { target } = JSON.parse(await browser("get", "text", "#inspection")) as { target: { x: number; y: number } };
23
+ await browser("click", "#design");
24
+ await browser("mouse", "move", String(target.x), String(target.y));
25
+ await browser("mouse", "down"); await browser("mouse", "up");
26
+ await browser("wait", "--fn", 'document.querySelector("#events").textContent.includes("design-selection")');
27
+ await browser("click", "#preview");
28
+ await browser("wait", "--fn", 'document.querySelector("#events").textContent.includes("design-override-result")');
29
+ await browser("click", "#write");
30
+ await browser("wait", "--fn", 'document.querySelector("#events").textContent.includes("design-write-result")');
31
+ await browser("click", "#inspect");
32
+ await browser("wait", "--fn", 'document.querySelector("#inspection").textContent.includes(\'"fill":"blue"\')');
33
+ expect(JSON.parse(await browser("get", "text", "#inspection"))).toMatchObject({ hostControlled: false, frameControlled: true, scopes: ["/frame/"], probe: "host-route", hostSource: "host-route", fill: "blue", width: "180", write: { page: "report", source: expect.stringMatching(/^report\.tsx:1:\d+#0@[0-9a-f]{12}$/), edit: { kind: "attributes", values: { fill: "blue", width: 180 } } } });
34
+ expect(await browser("get", "text", "#error")).toBe("");
35
+ expect(await browser("get", "text", "#events")).toContain('"ok":true');
36
+ });
@@ -0,0 +1,36 @@
1
+ import type { ComponentType, ReactNode } from "react";
2
+ import type { FrameMessage, JsonValue, PageHost } from "../schema.ts";
3
+ import { RuntimeFailure, runtimeError } from "../sw/errors.ts";
4
+ import { validateFrameMessage } from "../host/validation.ts";
5
+
6
+ export type PageModule = { default: ComponentType<{ data: JsonValue; host: PageHost }>; ready?: (() => Promise<void>) | Promise<void>; meta?: unknown };
7
+ export type PageLayout = { default: ComponentType<{ data: JsonValue; children: ReactNode }>; meta?: unknown };
8
+ export type ReactRuntime = [typeof import("react"), typeof import("react-dom/client"), typeof import("react-dom")];
9
+
10
+ export function mountPage(options: { module: PageModule; layout?: PageLayout; runtime: ReactRuntime; data: JsonValue; file: string; root: HTMLElement; wrap: (children: ReactNode) => ReactNode; send: (message: FrameMessage) => void }) {
11
+ const [React, { createRoot }, { flushSync }] = options.runtime;
12
+ const host: PageHost = { emit: (event, payload) => options.send(validateFrameMessage({ type: "emit", event, payload })) };
13
+ const renderer = createRoot(options.root);
14
+ let revision = 0;
15
+ const failures: unknown[] = [];
16
+ class Boundary extends React.Component<{ revision: number; children: ReactNode }, { revision: number; failed: boolean }> {
17
+ override state = { revision: 0, failed: false };
18
+ static getDerivedStateFromProps(props: { revision: number }, state: { revision: number }) { return props.revision !== state.revision ? { revision: props.revision, failed: false } : null; }
19
+ static getDerivedStateFromError() { return { failed: true }; }
20
+ override componentDidCatch(error: Error) { failures.push(error); }
21
+ override render() { return this.state.failed ? null : this.props.children; }
22
+ }
23
+ async function update(data: JsonValue) {
24
+ failures.length = 0;
25
+ const page = React.createElement(options.module.default, { data, host });
26
+ const content = options.layout ? React.createElement(options.layout.default, { data, children: page }) : page;
27
+ flushSync(() => renderer.render(options.wrap(React.createElement(Boundary, { revision: ++revision, children: content }))));
28
+ if (failures.length) throw new RuntimeFailure(runtimeError({ error: failures[0], phase: "render", file: options.file }));
29
+ }
30
+ return { mounted: update(options.data), update, replace: async (next: { module: PageModule; layout?: PageLayout; data: JsonValue }) => {
31
+ options.module = next.module;
32
+ if (next.layout) options.layout = next.layout;
33
+ else delete options.layout;
34
+ await update(next.data);
35
+ }, unmount: () => renderer.unmount() };
36
+ }
@@ -0,0 +1,2 @@
1
+ export { startPageAgent } from "./agent/index.ts";
2
+ export { PageAgentProvider } from "./agent/provider.tsx";
@@ -0,0 +1,51 @@
1
+ import type { FrameMessage } from "../schema.ts";
2
+
3
+ export type ReadinessOptions = { root: HTMLElement; mounted: Promise<void>; hook?: (() => Promise<void>) | Promise<void>; timeoutMs: number; status: (state: Extract<FrameMessage, { type: "status" }>["state"]) => void };
4
+ const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
5
+
6
+ function diagramsReady(root: HTMLElement): boolean {
7
+ for (const element of root.querySelectorAll("[data-facet-error]")) throw new Error(element.getAttribute("data-facet-error")!);
8
+ return [...root.querySelectorAll("[data-facet-diagram]")].every((d) => d.getAttribute("data-facet-ready") === "true") && [...root.querySelectorAll("[data-facet-arrow]")].every((d) => d.getAttribute("data-facet-arrow-ready") === "true");
9
+ }
10
+
11
+ async function stylesheetsReady(stopped: () => boolean): Promise<void> {
12
+ while (!stopped()) {
13
+ const links = [...document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')];
14
+ const failed = links.find((link) => link.dataset.pageRuntime === "error");
15
+ if (failed) throw new Error(`stylesheet failed: ${failed.href}`);
16
+ if (links.every((link) => link.dataset.pageRuntime === "loaded" || (link.dataset.pageRuntime === undefined && link.sheet !== null))) return;
17
+ await frame();
18
+ }
19
+ }
20
+
21
+ export async function waitForReadiness(options: ReadinessOptions): Promise<void> {
22
+ let lastActivity = performance.now(); let stopped = false;
23
+ const mutation = new MutationObserver(() => { lastActivity = performance.now(); });
24
+ const resize = new ResizeObserver(() => { lastActivity = performance.now(); });
25
+ mutation.observe(options.root, { childList: true, subtree: true, attributes: true, characterData: true });
26
+ resize.observe(options.root);
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ const ready = async () => {
29
+ await options.mounted; if (stopped) return; options.status("mounted");
30
+ await stylesheetsReady(() => stopped); if (stopped) return; options.status("stylesheets");
31
+ await document.fonts.ready; if (stopped) return; options.status("fonts");
32
+ await Promise.all([...document.images].map(async (image) => { await image.decode(); if (!image.naturalWidth) throw new Error(`image failed: ${image.src}`); }));
33
+ if (stopped) return; options.status("images");
34
+ if (options.hook) await (typeof options.hook === "function" ? options.hook() : options.hook);
35
+ if (stopped) return; options.status("hook");
36
+ while (!stopped && !diagramsReady(options.root)) await frame();
37
+ if (stopped) return; options.status("diagrams");
38
+ options.status("quiescence");
39
+ while (!stopped) {
40
+ await stylesheetsReady(() => stopped);
41
+ await document.fonts.ready;
42
+ await Promise.all([...document.images].map((image) => image.decode()));
43
+ if (diagramsReady(options.root) && document.fonts.status === "loaded" && performance.now() - lastActivity >= 200) break;
44
+ await frame();
45
+ }
46
+ if (!stopped) options.status("ready");
47
+ };
48
+ try {
49
+ await Promise.race([ready(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`readiness timeout after ${options.timeoutMs}ms`)), options.timeoutMs); })]);
50
+ } finally { stopped = true; clearTimeout(timer); mutation.disconnect(); resize.disconnect(); }
51
+ }
@@ -0,0 +1,101 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import type { BridgeEnvelope, FrameConfig, FrameMessage, JsonValue, PageLock, RuntimePhase } from "../schema.ts";
3
+ import { workerRequest } from "./bridge.ts";
4
+ import { exportHtml } from "./export.ts";
5
+ import { exportPageModule } from "./export-page.ts";
6
+ import { loadPageStyles, preparePageStyles } from "./boot-styles.ts";
7
+ import { mountPage, type PageModule, type PageLayout, type ReactRuntime } from "./mount-page.ts";
8
+ import { waitForReadiness } from "./readiness.ts";
9
+ import { RuntimeFailure, runtimeError } from "../sw/errors.ts";
10
+
11
+ export function renderLibraryKey(lock: PageLock): string {
12
+ const { page: _page, ...libraries } = lock;
13
+ return JSON.stringify(libraries, (_key, value: unknown) => {
14
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
15
+ const entries = Object.entries(value);
16
+ return Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b)));
17
+ });
18
+ }
19
+
20
+ export function frameRenderJobs(initial: FrameConfig | undefined) {
21
+ let prepared: FrameConfig | undefined;
22
+ const libraryKey = initial ? renderLibraryKey(initial.lock) : undefined;
23
+ let runtime: Promise<ReactRuntime> | undefined;
24
+ let busy = false;
25
+
26
+ return async (envelope: BridgeEnvelope): Promise<FrameMessage> => {
27
+ if (busy) throw new Error("a render is already running");
28
+ busy = true;
29
+ try {
30
+ const message = envelope.message;
31
+ if (message.type === "prepare-render") {
32
+ prepared = undefined;
33
+ const candidate = await workerRequest<FrameConfig>({ message: { type: "open", ...message.open } }, 30000);
34
+ const key = renderLibraryKey(candidate.lock);
35
+ const navigate = libraryKey !== key;
36
+ if (!navigate) prepared = candidate;
37
+ return { type: "prepared-render", lock: candidate.lock, navigate, runtimeVersion: candidate.runtimeVersion };
38
+ }
39
+ if (message.type !== "render" || !prepared) throw new Error("prepare a compatible page before rendering");
40
+ const config = prepared;
41
+ prepared = undefined;
42
+ runtime ??= Promise.all([import("react"), import("react-dom/client"), import("react-dom")]);
43
+ return await renderDocument({ config, runtime, data: message.data });
44
+ } finally {
45
+ busy = false;
46
+ }
47
+ };
48
+ }
49
+
50
+ async function renderDocument(options: { config: FrameConfig; runtime: Promise<ReactRuntime>; data: JsonValue }): Promise<FrameMessage> {
51
+ const { config, data } = options;
52
+ const revision = randomUUID();
53
+ const revised = (path: string) => {
54
+ const module = new URL(path, location.href);
55
+ module.searchParams.set("revision", revision);
56
+ return module.href;
57
+ };
58
+ const root = document.getElementById("root");
59
+ if (!root) throw new Error("render frame is missing its root");
60
+ const base = document.createElement("base");
61
+ base.href = new URL(".", revised(config.entry)).href;
62
+ const head = new Set(document.head.children);
63
+ const sheets = document.adoptedStyleSheets;
64
+ document.head.prepend(base);
65
+ let mounted: ReturnType<typeof mountPage> | undefined;
66
+ let styles: Awaited<ReturnType<typeof preparePageStyles>> | undefined;
67
+ let styleError: unknown;
68
+ let phase: RuntimePhase = "link";
69
+ try {
70
+ const started = performance.now();
71
+ const entry = revised(config.entry);
72
+ const exportConfig = { ...config, entry };
73
+ const layoutUrl = config.layout ? revised(config.layout) : undefined;
74
+ const page = exportPageModule<PageModule>({ config: exportConfig, request: message => workerRequest(message, 15000) })
75
+ .then(module => module ?? import(entry) as Promise<PageModule>);
76
+ const [module, layout, runtime] = await Promise.all([
77
+ page,
78
+ layoutUrl ? import(layoutUrl) as Promise<PageLayout> : undefined,
79
+ options.runtime,
80
+ ]);
81
+ const modulesMs = performance.now() - started;
82
+ phase = "render";
83
+ styles = await preparePageStyles({ config, styles: await loadPageStyles(config), module: { meta: { ...layout?.meta as object, ...module.meta as object } }, onError: error => { styleError = error; } });
84
+ const mount = (page: PageModule, target: HTMLElement) => mountPage({ module: page, ...(layout ? { layout } : {}), runtime, data, file: config.page, root: target, wrap: children => children, send: () => undefined });
85
+ mounted = mount(module, root);
86
+ await mounted.mounted;
87
+ phase = "readiness";
88
+ await waitForReadiness({ root, mounted: mounted.mounted.then(() => styles!.ready()), ...(module.ready ? { hook: module.ready } : {}), timeoutMs: config.profile.readinessTimeoutMs, status: () => undefined });
89
+ if (styleError) throw styleError;
90
+ const ready = performance.now();
91
+ const html = await exportHtml();
92
+ return { type: "rendered", html, modulesMs, readinessMs: ready - started - modulesMs, snapshotMs: performance.now() - ready };
93
+ } catch (error) {
94
+ throw new RuntimeFailure(runtimeError({ error, phase, file: config.page }));
95
+ } finally {
96
+ mounted?.unmount();
97
+ styles?.stop();
98
+ for (const element of document.head.querySelectorAll(":scope > *")) if (!head.has(element)) element.remove();
99
+ document.adoptedStyleSheets = sheets;
100
+ }
101
+ }
@@ -0,0 +1,48 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { afterAll, beforeAll, expect, it } from "vitest";
4
+ import { startRuntimeTestServer } from "./testing/server.ts";
5
+ import type { ReviewFrameMessage } from "../host/index.ts";
6
+ import type { ActivityMessage } from "../activity-schema.ts";
7
+
8
+ const execute = promisify(execFile);
9
+ const session = `runtime-review-integration-${process.pid}`;
10
+ let server: Awaited<ReturnType<typeof startRuntimeTestServer>>;
11
+ let opened = false;
12
+ async function browser(...args: string[]) {
13
+ return (await execute("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2_000_000 })).stdout.trim();
14
+ }
15
+ beforeAll(async () => { server = await startRuntimeTestServer(); });
16
+ afterAll(async () => { try { if (opened) await browser("close"); } finally { await server?.close(); } });
17
+
18
+ it("uses the host review adapter through the authenticated bridge and actual frame boot to enumerate, select and export review elements", async () => {
19
+ await browser("open", `${server.hostOrigin}/?case=review`); opened = true;
20
+ await browser("wait", "--fn", 'document.title === "CASE-DONE"');
21
+ const result = JSON.parse(await browser("get", "text", "#result")) as { errors: unknown[]; failure?: string };
22
+ expect(result.failure).toBeUndefined(); expect(result.errors).toEqual([]);
23
+ await browser("click", "#review-show");
24
+ await browser("wait", "--fn", 'JSON.parse(document.querySelector("#events").textContent).some(m => m.type === "review-state" && m.visible)');
25
+ await browser("click", "#review-list");
26
+ await browser("click", "#review-select");
27
+ await browser("wait", "--fn", 'JSON.parse(document.querySelector("#events").textContent).some(m => m.type === "review-state" && m.selected === "summary")');
28
+ await browser("click", "#review-export");
29
+ await browser("wait", "--fn", 'document.querySelector("#events").textContent.includes("review-action-request")');
30
+ const events = JSON.parse(await browser("get", "text", "#events")) as ReviewFrameMessage[];
31
+ expect(events.find((message) => message.type === "review-state" && message.visible)).toMatchObject({ elements: [{ id: "summary", selection: { element: { source: expect.stringMatching(/^report\.tsx:1:/) } } }] });
32
+ expect(events.find((message) => message.type === "review-action-request")).toMatchObject({ action: "export", element: { id: "summary" }, content: { html: expect.stringContaining("Review summary") } });
33
+ });
34
+
35
+ it.each(["compile", "fetch", "link"])("retains failed request diagnostics when %s fails before the first paint", async (phase) => {
36
+ await browser("open", `${server.hostOrigin}/?case=${phase}`); opened = true;
37
+ await browser("wait", "--fn", 'document.title === "CASE-DONE" && JSON.parse(document.querySelector("#activity").textContent || "[]").some(m => m.records.some(r => r.error))');
38
+ const result = JSON.parse(await browser("get", "text", "#result")) as { errors: Array<{ phase: string }>; failure?: string };
39
+ expect(result.failure).toBeUndefined(); expect(result.errors[0]?.phase).toBe(phase);
40
+ const messages = JSON.parse(await browser("get", "text", "#activity")) as ActivityMessage[];
41
+ const failed = messages.flatMap((message) => message.records).find((record) => record.error?.phase === phase);
42
+ expect(failed).toBeDefined(); expect(failed!.totalMs).toBeGreaterThan(0);
43
+ if (phase === "compile") expect(failed!.compileMs).toBeGreaterThan(0);
44
+ if (phase === "fetch") {
45
+ expect(failed!.error?.message).toContain("integrity mismatch");
46
+ expect(failed!.unavailable).not.toContain("integrity");
47
+ }
48
+ });
@@ -0,0 +1,90 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
4
+ import { startRuntimeTestServer } from "./testing/server.ts";
5
+
6
+ const exec = promisify(execFile);
7
+ const session = `page-runtime-B-${process.pid}`;
8
+ let server: Awaited<ReturnType<typeof startRuntimeTestServer>>;
9
+ let launched = false;
10
+ async function browser(...args: string[]): Promise<string> {
11
+ const { stdout } = await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2_000_000 });
12
+ return stdout.trim();
13
+ }
14
+ async function run(name: string) {
15
+ await browser("open", `${server.hostOrigin}/?case=${name}`);
16
+ launched = true;
17
+ await browser("wait", "--fn", 'document.title === "CASE-DONE"');
18
+ return JSON.parse(await browser("get", "text", "#result")) as { states: string[]; errors: Array<{ phase: string; message: string; file: string }>; elapsed?: number; snapshot?: { html: string }; before?: { html: string }; data?: { html: string }; css?: { html: string }; helper?: { html: string }; failure?: string };
19
+ }
20
+ beforeAll(async () => { server = await startRuntimeTestServer(); });
21
+ afterAll(async () => { try { if (launched) await browser("close"); } finally { await server?.close(); } });
22
+
23
+ describe("worker + frame + boot in real Chromium", () => {
24
+ it("loads library base styles in their recipe layer so custom CSS overrides library utility classes", async () => {
25
+ const result = await run("cascade");
26
+ expect({ failure: result.failure, errors: result.errors }).toEqual({ failure: undefined, errors: [] });
27
+ expect(result.snapshot?.html).toContain('data-color="rgb(91, 33, 182)"');
28
+ expect(result.snapshot?.html).toContain('@layer components');
29
+ });
30
+ it("reconciles data and changed source graphs in one document while retaining unchanged layout DOM", async () => {
31
+ const result = await run("updates");
32
+ expect({ failure: result.failure, errors: result.errors, boots: result.states.filter(state => state === "booting").length }).toEqual({ failure: undefined, errors: [], boots: 1 });
33
+ const attribute = (html: string | undefined, name: string) => html?.match(new RegExp(`${name}="([^"]+)"`))?.[1];
34
+ expect(attribute(result.data?.html, "data-instance")).toBe(attribute(result.before?.html, "data-instance"));
35
+ expect(attribute(result.css?.html, "data-instance")).toBe(attribute(result.data?.html, "data-instance"));
36
+ expect(result.css?.html).toContain("outline-color: rgb(12, 34, 56)");
37
+ expect(attribute(result.snapshot?.html, "data-document")).toBe(attribute(result.before?.html, "data-document"));
38
+ expect(attribute(result.snapshot?.html, "data-layout")).toBe(attribute(result.helper?.html, "data-layout"));
39
+ expect(result.snapshot?.html).toContain("Updated helper:Source data:Edited page");
40
+ });
41
+ it("uses one React, installs the hook first, and waits for every readiness state", async () => {
42
+ const result = await run("ready");
43
+ expect(result.failure).toBeUndefined();
44
+ expect(result.errors).toEqual([]);
45
+ expect(result.states).toEqual(["connecting", "booting", "mounted", "stylesheets", "fonts", "images", "hook", "diagrams", "quiescence", "ready"]);
46
+ expect(result.snapshot?.html).toContain('data-one-react="true"');
47
+ expect(result.snapshot?.html).toContain('data-hook="true"');
48
+ expect(result.snapshot?.html).toContain('data-theme="dark"');
49
+ expect(result.snapshot?.html).toContain('data-source="report.tsx:8:10"');
50
+ expect(result.snapshot?.html).toContain("rgb(1, 2, 3)");
51
+ expect(result.snapshot?.html).not.toContain("@import");
52
+ expect(result.snapshot?.html).not.toContain("<script");
53
+ expect(result.snapshot?.html).toContain("data:image/svg+xml;base64,");
54
+ expect(result.elapsed).toBeGreaterThan(400);
55
+ expect(server.counts().registryRequests).toBe(0);
56
+ });
57
+ it("exports a Markdown page through its libraries' declared remark plugins", async () => {
58
+ const result = await run("markdown-export");
59
+ expect({ failure: result.failure, errors: result.errors, ready: result.states.at(-1) }).toEqual({ failure: undefined, errors: [], ready: "ready" });
60
+ expect({ kept: result.snapshot?.html.includes("Public summary."), removed: result.snapshot?.html.includes("Internal margin figures."), liveRootHidden: result.snapshot?.html.includes("data-page-runtime-live") }).toEqual({ kept: true, removed: false, liveRootHidden: false });
61
+ expect(result.snapshot?.html).toContain('data-report-layout');
62
+ expect(result.snapshot?.html).toContain('Report frame');
63
+ });
64
+ it.each(["resolve", "fetch", "compile", "link", "render", "readiness"])("reports the %s error phase with a source location", async (phase) => {
65
+ const result = await run(phase);
66
+ expect(result.failure).toBeUndefined();
67
+ expect(result.errors[0]).toMatchObject({ phase });
68
+ expect(result.errors[0]?.file).toBeTruthy();
69
+ expect(result.states).not.toContain("ready");
70
+ if (phase === "link") expect(result.errors[0]?.message).toMatch(/report.tsx:\d+:.*forbidden-package.*allowed packages:.*react/);
71
+ });
72
+ // WORKAROUND(agent-browser-oopif): agent-browser 0.38.1 cannot click or read CSS inside a cross-origin frame
73
+ // (`frame iframe` → "Frame not found"); the frame itself mounts, renders and activates Pick (.tmp/N/verification.md).
74
+ // Correct fix: agent-browser targets out-of-process frames, then remove the skip.
75
+ // Ref: user decision 2026-11-06 to skip these two cases.
76
+ it.skip.each([{ width: 1920, height: 1080 }, { width: 2560, height: 1440 }])("boots the agent and picks an unmarked library element at its original page call site in $width x $height", async (viewport) => {
77
+ await browser("set", "viewport", String(viewport.width), String(viewport.height));
78
+ const result = await run("agent");
79
+ expect(result.errors).toEqual([]);
80
+ expect(result.states.at(-1)).toBe("ready");
81
+ await browser("click", "#pick");
82
+ await browser("frame", "iframe");
83
+ await browser("click", "#library-heading");
84
+ await browser("frame", "main");
85
+ await browser("wait", "--fn", 'document.querySelector("#events").textContent.includes("selection")');
86
+ const events = JSON.parse(await browser("get", "text", "#events")) as Array<{ type: string; selection?: unknown }>;
87
+ expect(events.find((event) => event.type === "selection")).toMatchObject({ selection: { element: { source: "report.tsx:3:10", componentName: "StatCard" } } });
88
+ expect(result.snapshot?.html).not.toMatch(/data-page-agent|data-react-grab|<script/);
89
+ });
90
+ });
@@ -0,0 +1,49 @@
1
+ # Frame styles and runtime Tailwind
2
+
3
+ Every page loads its libraries' published stylesheets. A page that opts in also builds Tailwind utilities in the browser.
4
+
5
+ ## Library recipes
6
+
7
+ A managed library publishes `<name>/page-styles`, a `PageStylesRecipe` (see `schema.ts`):
8
+
9
+ - `base`: published precompiled stylesheet specifiers (clicky-ui: `@flanksource/clicky-ui/styles.css`). The frame links them with `<link rel="stylesheet">` on every page, in library order, through `resolveStyleImport`, which enforces the integrity-checked package route. The frame awaits every link's load before mounting, and a failed or timed-out stylesheet is an error naming it.
10
+ - `entry`: compiler inputs only (`tailwindcss/theme.css` in `layer(theme)`, `tailwindcss/utilities.css` in `layer(utilities)` with `source(none)`, `@config`, `@plugin`, `@theme`). `validateRecipe` rejects an `entry` that mentions any `base` stylesheet, so generated CSS never repeats the base.
11
+ - `extends`: managed libraries whose preset this library's preset extends (facet extends clicky-ui). Only the most-derived recipe goes into `compile()`; every library's `base` is still linked.
12
+ - `transform`: optional post-processing of generated CSS, applied for every library in library order.
13
+
14
+ Library order is deterministic and independent of `profile.managed` key order: a library that is extended comes before its extender, and ties are sorted by name. An `extends` naming an unmanaged library, or a cycle, is an error.
15
+
16
+ ## Opting in
17
+
18
+ A page module opts in to runtime Tailwind with:
19
+
20
+ ```tsx
21
+ export const meta = { tailwind: "dynamic" };
22
+ ```
23
+
24
+ Only a page that opts in loads the compiler, fetches `/__runtime/candidates`, opens storage and runs the `MutationObserver`. Any other `meta.tailwind` value, or a `meta` that is not an object, throws an error naming the page. A page that does not opt in is styled by the base links alone.
25
+
26
+ ## Cache identity and storage
27
+
28
+ - `libraryKey` is `[runtimeVersion, ...libraries.map(name, version, integrity)]`. The integrity is the recipe module's entry in `lock.integrity`. It is independent of the page: the recipe URL's `?page=` parameter, stylesheet bodies and the `transform` function are not part of it. A recipe module without a lock integrity (a linked module) cannot be cached and fails when the page opts in.
29
+ - `cssKey` is `sha256(libraryKey, sorted unique source candidates)`. Classes the DOM adds later do not change the key; they are recorded in the stored record's `domClasses`, and a warm load restores them so a remount rebuilds nothing.
30
+
31
+ | Where | What |
32
+ |---|---|
33
+ | IndexedDB `page-runtime` (`storage/db.ts`, shared by the worker and the frame) | `candidates` store: key `[page, module]`, value `{ sourceHash, candidates }`, index `page`. `tailwind` store: key `cssKey`, value `{ libraryKey, candidates, domClasses, bytes, url, createdAt, lastUsedAt }`, index `[libraryKey, lastUsedAt]`. |
34
+ | Cache Storage `page-runtime-<version>-tailwind` | The generated CSS as a plain `text/css` response at `/__runtime/tailwind/<cssKey>.css`. The worker serves that URL from this cache; a miss is a 404 with `x-page-runtime-error`. |
35
+
36
+ Write order: `cache.put`, then the IndexedDB record, which is the commit point. A record whose cached response is missing is an invariant violation: the read throws with the key and URL, with no silent rebuild. A warm read is an IndexedDB `get`, a `fetch` of the record's URL, and an insert into the `#runtime-tailwind` `<style>` before the first render. DOM-driven rebuilds are inserted synchronously before paint, but persisted once per idle period; `ready()` and `stop()` flush a pending write.
37
+
38
+ Eviction runs in the write transaction: it keeps the newest `TAILWIND_ENTRIES_PER_LIBRARY` (32) records per library key, and clears every record of other library keys the first time a new library key writes. The evicted responses are deleted from Cache Storage after the transaction commits. A read counts as a use.
39
+
40
+ The worker writes each compiled module's candidates to the `candidates` store, and `/__runtime/candidates?page=` is `index("page").getAll(page)`. On `activate` the worker deletes `page-runtime-tailwind-v2`, other versions' `-tailwind` caches and the old `/__runtime/candidates/` Cache Storage entries.
41
+
42
+ ## Partitioning
43
+
44
+ The frame runs on the runtime origin inside the host's page, so browsers partition its IndexedDB and Cache Storage by top-level site. The cache is shared per (embedder site, runtime origin), not across embedders, and `link/storage.ts` keeps its own host-origin `page-runtime-links` database because it lives on a different origin.
45
+
46
+ ## Tests
47
+
48
+ - `pnpm --filter @flanksource/page-runtime test tailwind` runs the recipe, key, store, runtime and bootstrap unit tests against `fake-indexeddb`.
49
+ - `pnpm --filter @flanksource/page-runtime test:browser src/frame/tailwind/tailwind.browser.ts` renders the facet example pages in Chrome through `agent-browser` and compares them with a reference build, and checks the storage layout cold and warm. It needs the clicky-ui and facet builds (`packages/ui/dist`, facet `dist`).
@@ -0,0 +1,18 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { expect, it } from "vitest";
4
+ import { startRuntimeTestServer } from "../testing/server.ts";
5
+
6
+ const exec = promisify(execFile);
7
+ it("tailwind boot preserves the frame's readiness sequence", async () => {
8
+ const server = await startRuntimeTestServer();
9
+ const session = `tailwind-boot-${process.pid}`;
10
+ const browser = async (...args: string[]) => (await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2_000_000 })).stdout.trim();
11
+ try {
12
+ await browser("open", `${server.hostOrigin}/?case=ready`);
13
+ await browser("wait", "--fn", 'document.title === "CASE-DONE"');
14
+ const result = JSON.parse(await browser("get", "text", "#result"));
15
+ expect(result.errors, JSON.stringify(result)).toEqual([]);
16
+ expect(result.states).toEqual(["connecting", "booting", "mounted", "stylesheets", "fonts", "images", "hook", "diagrams", "quiescence", "ready"]);
17
+ } finally { await browser("close"); await server.close(); }
18
+ });
@@ -0,0 +1,20 @@
1
+ import type { LibraryStyles } from "./recipe.ts";
2
+ import { TAILWIND_ROUTE } from "../../storage/db.ts";
3
+
4
+ /** Page-independent: the runtime version and each library's name, version and recipe-module integrity, in the order given. */
5
+ export function libraryKey(options: { libraries: LibraryStyles[]; runtimeVersion: string }): string {
6
+ return JSON.stringify([options.runtimeVersion, ...options.libraries.map(({ name, version, integrity }) => {
7
+ if (!integrity) throw new Error(`${name}: recipe module has no lock integrity, so its Tailwind output cannot be cached`);
8
+ return [name, version, integrity];
9
+ })]);
10
+ }
11
+
12
+ export async function cssCacheKey(options: { libraryKey: string; candidates: Iterable<string> }): Promise<string> {
13
+ const bytes = new TextEncoder().encode(JSON.stringify([options.libraryKey, [...new Set(options.candidates)].sort()]));
14
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
15
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
16
+ }
17
+
18
+ export function tailwindCssUrl(options: { key: string; origin: string }): string {
19
+ return new URL(`${TAILWIND_ROUTE}${options.key}.css`, options.origin).href;
20
+ }