@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,115 @@
1
+ # Developer library links
2
+
3
+ A link replaces a managed library's published entries with checkout source and uses that checkout's runtime fragment, converted CommonJS modules, constants, and generated files. Both `profile.links: "allow"` and the host's `developerOverrides: true` are required. Overrides are session state: keep the published lock and pass a composed copy to `PageFrame.open.lock`.
4
+
5
+ ## Build a checkout
6
+
7
+ Build the library normally first. For clicky-ui, generate icons with `pnpm --filter @flanksource/clicky-ui build:icons`. Link preparation calls the existing `buildLibraryRuntime` and writes `dist/runtime/link.json` alongside its fragment, barrels, and the development runtime.
8
+
9
+ Provide an entrypoints JSON file mapping published specifiers to checkout source paths. For example:
10
+
11
+ ```json
12
+ {
13
+ "@flanksource/clicky-ui/data": "src/data.ts",
14
+ "@flanksource/clicky-ui/icons": "src/icons.ts"
15
+ }
16
+ ```
17
+
18
+ Provide a build-inputs JSON file containing the checkout's actual constants (`__CLICKY_COMMIT__`, `__CLICKY_TAG__`, `__CLICKY_DATE__`, and `__CLICKY_DIRTY__` for clicky-ui). They are injected into linked source modules. Values must be strings, booleans, or numbers. Missing generated icons fail with the icon-generation command.
19
+
20
+ From the repository root:
21
+
22
+ ```sh
23
+ pnpm --filter @flanksource/page-runtime exec tsx src/link/build-cli.ts --library /absolute/checkout --entries /absolute/entrypoints.json --defines /absolute/build-inputs.json
24
+ pnpm --filter @flanksource/page-runtime exec tsx src/link/examples/server.ts /absolute/checkout 8790
25
+ ```
26
+
27
+ For facet, add `--base /absolute/clicky-ui/dist/runtime/importmap.json` so preparation inherits clicky-ui's singletons. The source server binds to loopback, supports CORS, and serves unchanged checkout files. Both transports use the same link manifest. Source edits within the existing import graph need no build; adding imports, changing exports, or changing dependencies requires running the link build again and reinstalling the link.
28
+
29
+ The Node API is `buildLinkRuntime({ libraryDir, outDir, entries, defines, base?, generated? })` from `src/link/build.ts`. `generated` maps additional required checkout paths to the commands that create them. `base` is the base library's fragment. `entries` explicitly names the source entry points to expose; `defines` comes from the checkout, and `outDir` should be its `dist/runtime` directory.
30
+
31
+ ## Host API
32
+
33
+ The typed host entry point is `src/host/link/index.ts`, exported as `@flanksource/page-runtime/host/link`.
34
+
35
+ ```ts
36
+ import { connectLinkRuntime, createLinkHost } from "@flanksource/page-runtime/host/link";
37
+
38
+ const connection = await connectLinkRuntime({ runtimeOrigin, profile, developerOverrides: true });
39
+ const links = createLinkHost({ profile, developerOverrides: true, transport: connection.request });
40
+ await links.restore();
41
+ await links.server({ id: "ui", url: "http://127.0.0.1:8790/" });
42
+ const lock = links.override({ lock: publishedLock, ids: ["ui"] });
43
+ const unregister = links.registerFrame({ id: pageId, links: ["ui"], reload: reloadPreviewUntilReady });
44
+ const watcher = links.watch("ui");
45
+ await watcher.start({ onError: showLinkError });
46
+ ```
47
+
48
+ Activate the runtime service worker with a runtime frame before calling `connectLinkRuntime`. The connection opens a hidden runtime-origin relay and validates the parent origin, source window, session, and deployment policy. Pass `lock` into the existing open message or `PageFrame.open`. Reinstalling a checkout clears its compiled pointers. `restore()` reloads descriptors and directory handles from host-origin IndexedDB and reconnects their worker state; invoke it on host startup. `list()` returns installed links.
49
+
50
+ For a folder button, call `links.pickFolder({ id: "ui" })` directly from the click handler. An existing granted handle can be passed to `links.folder({ id: "ui", directory })`. Directory handles stay in host-origin IndexedDB. The worker asks for file bytes over a session-bound relay; no cross-origin handle transfer is attempted. Revoked permissions and disconnected hosts produce errors. Chromium's native `FileSystemObserver` is used when available; otherwise the same content-hash polling path is used. Servers always use polling, at 25 ms by default. Change detection watches source modules actually served by the worker and compares against their served hashes, including edits before the first scan.
51
+
52
+ `invalidate(id, paths)` invalidates only those modules before reloading registered frames using that link. The `reload` callback should send the existing bridge reload message and return a promise that resolves on the frame's ready status; polling then waits for rendering to finish. Unrelated frames retain their documents. Runtime-version and content hashes key compiled cache entries. Canonical URLs name no page: the worker takes each request's page and link context from the frame (or page-spawned worker) that made it, so the frame import map and rewritten imports use the same singleton URLs in every page. Library modules are cached compiled but not yet rewritten, keyed by their source and link build, and shared by every page; each page rewrites the module's imports through its own import map once, and that rewrite is cached by page context and source hash. Page modules are cached whole per page context. Page candidates feed the existing runtime CSS candidate endpoint.
53
+
54
+ Linked responses carry per-request `x-link-activity` metadata, which the outer router validates and projects into `Server-Timing` and the host activity stream. Fetch, integrity, compile and rewrite timings include work completed before a failure. Cache entries persist source/output sizes, never elapsed timings: the first persistent read reports `storage`, later reads report `memory`, and a content hit after invalidation preserves the fresh source-read cost. Server/package origins use their actual URLs and expose encoded transfer bytes when `Content-Length` is available; native folder reads have no network origin and transfer zero bytes. Generated agent and JSX shim modules report their generation and rewrite work separately.
55
+
56
+ Generated agent/shim output is cached by the link context and original source hash. The agent source is still fetched and hashed on each request, so changed runtime files invalidate the transform; a cache hit retains that fetch/transfer cost and reports zero rewrite work. Installed context links are reused for policy checks rather than rescanning the complete import map for every cached module.
57
+
58
+ On teardown, call `await watcher.stop()`, `unregister()`, `await links.close()`, and `connection.close()`. To unlink, stop its watcher, call `await links.remove(id)`, and reopen affected frames with their published lock.
59
+
60
+ ## Verification
61
+
62
+ Focused unit checks:
63
+
64
+ ```sh
65
+ gavel test --work-dir ./packages/page-runtime --framework vitest --recursive=false -- src/link/overrides.test.ts src/sw/link-route.test.ts
66
+ ```
67
+
68
+ Chromium checks (agent-browser owns the browser and Gavel holds the test slot):
69
+
70
+ ```sh
71
+ gavel test --work-dir ./packages/page-runtime --framework vitest --recursive=false -- --config src/link/vitest.browser.config.ts src/link/link.browser.ts
72
+ ```
73
+
74
+ The browser fixture copies the real clicky-ui source, builds its runtime set, renders DataTable and Version, checks a cold and warm load, edits Version twelve times, checks exact recompile sets and the unlinked control, and then verifies folder reads using an IndexedDB-persisted OPFS directory handle. It writes `.tmp/H-link/browser-results.json` and a screenshot. This does not automate the native folder picker.
75
+
76
+ For the manual Chromium check, start the standalone fixture:
77
+
78
+ ```sh
79
+ pnpm --filter @flanksource/page-runtime exec tsx src/link/testing/server.ts
80
+ ```
81
+
82
+ 1. Open the printed **Link verification host** URL in desktop Chromium.
83
+ 2. Click **Link folder**.
84
+ 3. Select the printed **Folder to select** directory, click **Open**, and grant read access if Chromium asks.
85
+ 4. Confirm the **Folder linked** status and the DataTable and Version preview.
86
+ 5. In that copied directory, edit `src/data/Version.tsx`, changing `revision-0` to another visible value. Confirm the linked preview changes and the **Unlinked control** frame stays loaded.
87
+ 6. Reload the host and grant read access again if Chromium requires it. Confirm the persisted directory can be reconnected. Cancel or deny the picker once and confirm the error is visible.
88
+
89
+ The historical spike reported an occasional approximately three-second warm/early-edit stall. The product fixture guards warm reload and the first two edits below one second in addition to the 300 ms edit p50 and 15 s cold budget. A passing guard demonstrates its absence in that run; it does not establish the cause of the historical spike's stall.
90
+
91
+ ## Reference host
92
+
93
+ The reference host's library controls use this API. See [the page-host link documentation](../../../../apps/page-host/README.md#developer-library-links) for setup and usage. Its P6 fixture writes `e2e/results/page-host-link.json`; the standalone fixture writes independent measurements under `.tmp/H-link/`.
94
+
95
+ ## Frame-scoped local relay and page roots
96
+
97
+ For a same-origin-local host, pass `relayPath: "/frame/_link-relay"` to `connectLinkRuntime`. The default remains `/frame/__runtime-link-relay`, matching the runtime's `/frame/` worker scope for existing hosts. Relay documents are dispatched before generic frames; the local relay never requires widening the service-worker scope beyond `/frame/`.
98
+
99
+ A source link declares `build.pageSources`, an array of `{ root, prefix, editable }`. `root` is a checkout-relative directory, `prefix` is its page-relative mount (empty for the primary pages directory), and `editable` grants editable marker projection. `composeLinkOverrides` adds the link ID to each declaration in `lock.pageSources`; worker compilation checks these against the installed link. `pageSourceModule({ page, roots })` selects the linked entry without a host-buffer snapshot. `pageSourcePath({ path, roots })` projects only editable roots; library links and read-only roots keep their noneditable locations. Noncanonical paths and overlapping declarations fail. Compiler markers retain the hash of the original UTF-8 bytes.
100
+
101
+ `buildLinkRuntime` accepts `pageSources` and prepares CommonJS source entries with the published runtime-set converter and its evaluated named-export analysis. The manifest's `commonjs[path]` stores `{ hash, target }`; the worker forwards the original source to that converted ESM entry only while the original hash matches. Rebuild the link metadata/runtime set after a CommonJS source edit. TypeScript/JSX source edits continue compiling in the worker normally.
102
+
103
+ For a declared library alias without a `dist` build, use `prepareCommonJsSources` from `@flanksource/page-runtime/link/build`:
104
+
105
+ ```ts
106
+ const prepared = await prepareCommonJsSources({
107
+ libraryDir: iconsDirectory,
108
+ outDir: conversionDirectory,
109
+ runtimePath: "dist/runtime/source-commonjs",
110
+ paths: ["mi/index.js"],
111
+ base: clickyFragment,
112
+ });
113
+ ```
114
+
115
+ `prepared.fragment` supplies the converted closure, `prepared.commonjs` supplies source-to-ESM metadata, and `prepared.files` maps checkout-relative generated URLs to physical output files. Merge these into the declared library link and serve the generated files at those exact URLs. The alias still targets `/link/<id>/mi/index.js`; user imports stay intact. This prepares library artifacts with the existing Node build tool, never page TSX compilation on the server. `compileCommonJsSource` in the worker validates original bytes and emits the forwarding module; missing or stale artifacts fail.
@@ -0,0 +1,5 @@
1
+ import type { BarrelIndex } from "../schema.ts";
2
+
3
+ export function mapBarrels(options: { index: BarrelIndex; map: (path: string) => string }): BarrelIndex {
4
+ return { modules: options.index.modules.map(options.map), barrels: Object.fromEntries(Object.entries(options.index.barrels).map(([path, entries]) => [options.map(path), entries])) };
5
+ }
@@ -0,0 +1,12 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve, join } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import type { Fragment } from "../schema.ts";
5
+ import type { LinkBuild } from "./types.ts";
6
+ import { buildLinkRuntime } from "./build.ts";
7
+
8
+ const { values } = parseArgs({ options: { library: { type: "string" }, entries: { type: "string" }, defines: { type: "string" }, base: { type: "string" } } });
9
+ if (!values.library || !values.entries || !values.defines) throw new Error("Usage: build-cli.ts --library /checkout --entries /entrypoints.json --defines /build-inputs.json [--base /base/importmap.json]");
10
+ const libraryDir = resolve(values.library);
11
+ const result = await buildLinkRuntime({ libraryDir, outDir: join(libraryDir, "dist/runtime"), entries: JSON.parse(await readFile(resolve(values.entries), "utf8")) as Record<string, string>, defines: JSON.parse(await readFile(resolve(values.defines), "utf8")) as LinkBuild["defines"], ...(values.base ? { base: JSON.parse(await readFile(resolve(values.base), "utf8")) as Fragment } : {}) });
12
+ process.stdout.write(`Built ${result.library}@${result.version}: ${Object.keys(result.modules).length} source modules; ${join(libraryDir, "dist/runtime/link.json")}\n`);
@@ -0,0 +1,99 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { writeFile } from "node:fs/promises";
3
+ import { dirname, extname, join, relative, sep } from "node:path";
4
+ import { init, parse } from "es-module-lexer";
5
+ import { ResolverFactory } from "rolldown/experimental";
6
+ import { parseSync } from "rolldown/utils";
7
+ import type { Fragment } from "../schema.ts";
8
+ import { buildLibraryRuntime } from "../build/library-runtime.ts";
9
+ import { buildBarrelIndex, shapeOf, sideEffectsRule } from "../build/barrels.ts";
10
+ import { resolveSpecifier } from "../sw/composition.ts";
11
+ import { composeFragments, mergeBarrels } from "../sw/composition.ts";
12
+ import { compileScript } from "../sw/compile.ts";
13
+ import type { LinkBuild } from "./types.ts";
14
+ import { validateLink, missingLinkFile } from "./validation.ts";
15
+ import { validateSourcePath } from "../host/validation.ts";
16
+ import { mapBarrels } from "./barrels.ts";
17
+ import { prepareCommonJsSources } from "./commonjs.ts";
18
+ import { moduleFormat } from "../build/trace.ts";
19
+ export { prepareCommonJsSources } from "./commonjs.ts";
20
+ export type { CommonJsSourcesOptions } from "./commonjs.ts";
21
+
22
+ export type LinkBuildOptions = { libraryDir: string; outDir: string; entries: Record<string, string>; base?: Fragment; defines: LinkBuild["defines"]; generated?: Record<string, string>; pageSources?: LinkBuild["pageSources"] };
23
+
24
+ export async function buildLinkRuntime(options: LinkBuildOptions): Promise<LinkBuild> {
25
+ const directory = realpathSync(options.libraryDir);
26
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as { name: string; version: string; sideEffects: unknown; dependencies?: Record<string, string>; peerDependencies?: Record<string, string> };
27
+ for (const [name, path] of Object.entries(options.entries)) {
28
+ if (name !== manifest.name && !name.startsWith(`${manifest.name}/`)) throw new Error(`Source entry ${name} is outside ${manifest.name}`);
29
+ validateSourcePath(path);
30
+ }
31
+ const generated = { ...(manifest.name === "@flanksource/clicky-ui" ? { "src/icons/components/UiClose.tsx": "pnpm --filter @flanksource/clicky-ui build:icons" } : {}), ...options.generated };
32
+ for (const [path, command] of Object.entries(generated)) {
33
+ try { readFileSync(join(directory, path)); } catch (error) { throw new Error(`${manifest.name}: missing generated file ${path}; run \`${command}\``, { cause: error }); }
34
+ }
35
+ const { fragment, barrels } = await buildLibraryRuntime(options);
36
+ const build: LinkBuild = { link: 1, library: manifest.name, version: manifest.version, fragment, entries: options.entries, modules: {}, barrels: { modules: [], barrels: {} }, defines: options.defines, generated };
37
+ build.package = { ...(manifest.dependencies ? { dependencies: manifest.dependencies } : {}), ...(manifest.peerDependencies ? { peerDependencies: manifest.peerDependencies } : {}) };
38
+ if (options.pageSources) build.pageSources = options.pageSources;
39
+ const link = { id: "build", source: { kind: "folder" as const }, build };
40
+ const resolver = new ResolverFactory({ conditionNames: ["browser", "import", "module", "default"], extensions: [".tsx", ".ts", ".jsx", ".js", ".cjs", ".json"], symlinks: true });
41
+ const map = composeFragments({ fragments: options.base ? [options.base, fragment] : [fragment] }).map;
42
+ const compiled = new Map<string, string>();
43
+ const source = (path: string): string => {
44
+ let code = compiled.get(path);
45
+ if (code === undefined) {
46
+ const file = realpathSync(join(directory, path));
47
+ if (relative(directory, file).startsWith("../")) throw new Error(`Source ${path} escapes the checkout`);
48
+ const text = readFileSync(file, "utf8");
49
+ code = [".ts", ".tsx", ".jsx"].includes(extname(path)) ? compileScript({ path, extension: extname(path), code: text }) : text;
50
+ compiled.set(path, code);
51
+ }
52
+ return code;
53
+ };
54
+ const resolve = (path: string, specifier: string): string => {
55
+ const entry = options.entries[specifier];
56
+ if (entry) return entry;
57
+ if (!specifier.startsWith(".")) {
58
+ const target = resolveSpecifier(map, specifier, `/npm/${manifest.name}@${manifest.version}/dist/${path.slice(4).replace(/\.tsx?$/, ".js")}`);
59
+ if (!target) throw new Error(`${path}: ${specifier} is missing from the checkout runtime fragment; rebuildLibraryRuntime with this dependency`);
60
+ return target;
61
+ }
62
+ const resolved = resolver.sync(dirname(join(directory, path)), specifier.split("?")[0]!);
63
+ if (!resolved.path) throw missingLinkFile(link, relative(directory, join(dirname(join(directory, path)), specifier)));
64
+ const local = relative(directory, realpathSync(resolved.path));
65
+ if (local.startsWith("../") || local.startsWith("/")) throw new Error(`${path}: import ${specifier} escapes the checkout`);
66
+ return local;
67
+ };
68
+ await init();
69
+ const pending = Object.values(options.entries);
70
+ const commonjs: string[] = [];
71
+ for (let path = pending.shift(); path; path = pending.shift()) {
72
+ if (build.modules[path]) continue;
73
+ const resolutions: Record<string, string> = {};
74
+ build.modules[path] = { resolutions };
75
+ if (/\.(?:js|cjs)$/.test(path) && moduleFormat(join(directory, path)).format === "commonjs") { commonjs.push(path); continue; }
76
+ if (!/\.(tsx?|jsx?|mjs)$/.test(path)) continue;
77
+ for (const item of parse(source(path))[0]) {
78
+ if (item.type === "import-meta") continue;
79
+ if (!item.specifier) throw new Error(`${path}: dynamic imports must name a literal module`);
80
+ resolutions[item.specifier] = resolve(path, item.specifier);
81
+ if (!resolutions[item.specifier]!.startsWith("/npm/")) pending.push(resolutions[item.specifier]!);
82
+ }
83
+ }
84
+ const sideEffects = sideEffectsRule(manifest.sideEffects, manifest.name);
85
+ if (commonjs.length) {
86
+ const runtimePath = relative(directory, join(realpathSync(options.outDir), "source-commonjs")).split(sep).join("/");
87
+ validateSourcePath(runtimePath);
88
+ const prepared = await prepareCommonJsSources({ libraryDir: directory, outDir: join(options.outDir, "source-commonjs"), runtimePath, paths: commonjs, base: options.base ?? fragment });
89
+ const merged = composeFragments({ fragments: [fragment, prepared.fragment] });
90
+ build.fragment = { ...fragment, imports: Object.fromEntries(Object.entries(merged.map.imports).map(([key, value]) => [key, value.replace(/^\/npm\//, "")])), scopes: Object.fromEntries(Object.entries(merged.map.scopes).map(([scope, table]) => [scope.replace(/^\/npm\//, ""), Object.fromEntries(Object.entries(table).map(([key, value]) => [key, value.replace(/^\/npm\//, "")]))])), integrity: merged.integrity, remaps: merged.remaps, inherits: [...new Set([...fragment.inherits, ...prepared.fragment.inherits])] };
91
+ build.commonjs = prepared.commonjs;
92
+ }
93
+ build.barrels = buildBarrelIndex({ urls: Object.keys(build.modules).filter((path) => /\.(tsx?|jsx?|mjs)$/.test(path)), shape: (path) => Object.hasOwn(build.modules, path) && /\.(tsx?|jsx?|mjs)$/.test(path) ? shapeOf(parseSync("module.js", source(path)).module) : null, resolve, sideEffectFree: (path) => !path.startsWith("/npm/") && sideEffects(path) }).index;
94
+ const prefix = `${manifest.name}@${manifest.version}/`;
95
+ build.barrels = mergeBarrels([mapBarrels({ index: barrels, map: (path) => path.startsWith(prefix) ? path.slice(prefix.length) : `/npm/${path}` }), build.barrels]);
96
+ validateLink(link);
97
+ await writeFile(join(options.outDir, "link.json"), `${JSON.stringify(build, null, 2)}\n`);
98
+ return build;
99
+ }
@@ -0,0 +1,39 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { resolve, relative, sep } from "node:path";
4
+ import type { Fragment } from "../schema.ts";
5
+ import { ClosureTracer, packageName } from "../build/trace.ts";
6
+ import { convertCommonJs } from "../build/convert-commonjs.ts";
7
+ import { fragmentOf } from "../build/fragment.ts";
8
+ import { assertTrace } from "../build/library-runtime.ts";
9
+ import { sourceHash } from "../sw/source-hash.ts";
10
+ import { validateSourcePath } from "../host/validation.ts";
11
+ import type { CommonJsSource } from "./types.ts";
12
+
13
+ export type CommonJsSourcesOptions = { libraryDir: string; outDir: string; runtimePath: string; paths: string[]; base: Fragment };
14
+
15
+ /** Library-source CommonJS uses the same converter and evaluated named exports as published runtime sets. */
16
+ export async function prepareCommonJsSources(options: CommonJsSourcesOptions): Promise<{ fragment: Fragment; commonjs: Record<string, CommonJsSource>; files: Record<string, string> }> {
17
+ const root = realpathSync(options.libraryDir);
18
+ const manifest = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")) as { name: string; version: string };
19
+ if (!manifest.name || !manifest.version) throw new Error("CommonJS library requires name and version");
20
+ validateSourcePath(options.runtimePath);
21
+ const entries = options.paths.map((path) => {
22
+ validateSourcePath(path);
23
+ const absolute = realpathSync(resolve(root, path));
24
+ if (relative(root, absolute).startsWith(`..${sep}`)) throw new Error(`CommonJS source ${path} escapes the library`);
25
+ return { specifier: `${manifest.name}/${path}`, path: absolute };
26
+ });
27
+ const prefix = `${manifest.name}@${manifest.version}/`;
28
+ const tracer = new ClosureTracer({ name: manifest.name, resolveFrom: root, runtimeBase: `${prefix}${options.runtimePath}/`, entries, topLevel: [], inherits: [...new Set(Object.keys(options.base.imports).map(packageName))].filter((name) => name !== manifest.name) }).trace();
29
+ assertTrace(tracer);
30
+ await mkdir(options.outDir, { recursive: true });
31
+ await convertCommonJs(tracer, options.outDir);
32
+ assertTrace(tracer);
33
+ const commonjs = Object.fromEntries(options.paths.map((path) => {
34
+ const target = tracer.imports[`${manifest.name}/${path}`];
35
+ if (!target?.startsWith(`${prefix}${options.runtimePath}/`)) throw new Error(`${path} was not converted from CommonJS`);
36
+ return [path, { hash: sourceHash(readFileSync(resolve(root, path), "utf8")), target: target.slice(prefix.length) }];
37
+ }));
38
+ return { fragment: fragmentOf(tracer), commonjs, files: Object.fromEntries([...tracer.files.values()].filter((file) => file.url.startsWith(`${prefix}${options.runtimePath}/`)).map((file) => [file.url.slice(prefix.length), file.path])) };
39
+ }
@@ -0,0 +1,18 @@
1
+ import { createServer } from "node:http";
2
+ import { readFile } from "node:fs/promises";
3
+ import { resolve, sep } from "node:path";
4
+
5
+ if (!process.argv[2]) throw new Error("Usage: server.ts /absolute/checkout [port]");
6
+ const directory = resolve(process.argv[2]);
7
+ const port = Number(process.argv[3] ?? 8790);
8
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Port must be an integer from 1 to 65535");
9
+ const server = createServer((request, response) => {
10
+ void (async () => {
11
+ response.setHeader("access-control-allow-origin", "*");
12
+ response.setHeader("cache-control", "no-store");
13
+ const path = resolve(directory, "." + decodeURIComponent(new URL(request.url!, "http://localhost").pathname));
14
+ if (!path.startsWith(directory + sep)) { response.statusCode = 403; response.end("Outside checkout"); return; }
15
+ response.end(await readFile(path));
16
+ })().catch((error: unknown) => { response.statusCode = error instanceof Error && "code" in error && error.code === "ENOENT" ? 404 : 500; response.end(String(error)); });
17
+ });
18
+ server.listen(port, "127.0.0.1", () => process.stdout.write(`CORS checkout: http://127.0.0.1:${port}/ (${directory})\n`));
@@ -0,0 +1,6 @@
1
+ export * from "./types.ts";
2
+ export { assertLinksAllowed, validateLink, linkUrl, missingLinkFile } from "./validation.ts";
3
+ export { composeLinkOverrides, linksInLock } from "./overrides.ts";
4
+ export { createLinkStore } from "./storage.ts";
5
+ export { pageSourcePath, pageSourceModule, validatePageSources, validatePageSourceLinks } from "./page-sources.ts";
6
+ export type { PageSourceRoot, PageSourceLock, PageSourceContext } from "./page-sources.ts";
@@ -0,0 +1,66 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { resolve } from "node:path";
5
+ import { describe, expect, it } from "vitest";
6
+ import { startLinkTestServer } from "./testing/server.ts";
7
+
8
+ const execute = promisify(execFile);
9
+
10
+ describe("file-server library link in Chromium", () => {
11
+ it("keeps source imports on the development checkout's React runtime", async () => {
12
+ const server = await startLinkTestServer();
13
+ const session = `page-runtime-link-dev-${process.pid}`;
14
+ let launched = false;
15
+ const browser = (...args: string[]) => execute("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2000000 });
16
+ try {
17
+ await browser("open", server.hostOrigin); launched = true;
18
+ expect(await server.next()).toMatchObject({ marker: "revision-0", reactInstances: 1, reactEvaluations: 1, controlLoads: 1 });
19
+ expect((await server.next()).compiled).toEqual([]);
20
+ } finally { try { if (launched) await browser("close"); } finally { await server.close(); } }
21
+ });
22
+ it("renders checkout React, persists links, reloads only linked frames and recompiles exactly one edited source module", async () => {
23
+ const server = await startLinkTestServer();
24
+ const session = `page-runtime-link-${process.pid}`;
25
+ let launched = false;
26
+ const browser = (...args: string[]) => execute("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2000000 });
27
+ try {
28
+ await browser("open", server.hostOrigin);
29
+ launched = true;
30
+ const cold = await server.next();
31
+ const warm = await server.next();
32
+ const edits = [];
33
+ for (let revision = 1; revision <= 12; revision++) {
34
+ const at = performance.timeOrigin + performance.now();
35
+ await server.edit(revision);
36
+ const result = await server.next();
37
+ expect(result.marker).toBe(`revision-${revision}`);
38
+ edits.push({ ...result, editMs: result.at - at });
39
+ }
40
+ expect(cold.reactInstances).toBe(1);
41
+ expect(cold.reactEvaluations).toBe(1);
42
+ expect(cold.compiled.length).toBeGreaterThan(0);
43
+ expect(warm.compiled).toEqual([]);
44
+ expect(edits.map((edit) => edit.compiled)).toEqual(Array.from({ length: 12 }, () => ["/link/checkout/src/data/Version.tsx"]));
45
+ expect(edits.map(({ controlLoads, reactInstances, reactEvaluations, restored, deniedWithoutOverrides }) => ({ controlLoads, reactInstances, reactEvaluations, restored, deniedWithoutOverrides }))).toEqual(Array.from({ length: 12 }, () => ({ controlLoads: 1, reactInstances: 1, reactEvaluations: 1, restored: true, deniedWithoutOverrides: true })));
46
+ const times = edits.map((edit) => edit.editMs).sort((a, b) => a - b);
47
+ const results = { coldMs: cold.elapsed, coldModules: cold.compiled.length, warmMs: warm.elapsed, editP50Ms: times[5]!, editP95Ms: times[11]!, deniedWithoutOverrides: cold.deniedWithoutOverrides, oneModulePerEdit: true, reactInstances: cold.reactInstances, reactEvaluations: cold.reactEvaluations, edits };
48
+ await mkdir(resolve("../../.tmp/H-link"), { recursive: true });
49
+ await writeFile(resolve("../../.tmp/H-link/browser-results.json"), JSON.stringify(results, null, 2));
50
+ const folder = await server.next();
51
+ expect(folder).toMatchObject({ folderTransport: true, marker: "revision-12", restored: true, reactInstances: 1, reactEvaluations: 1, controlLoads: 1 });
52
+ await writeFile(resolve("../../.tmp/H-link/browser-results.json"), JSON.stringify({ ...results, folder }, null, 2));
53
+ expect(results.coldMs).toBeLessThanOrEqual(15000);
54
+ expect(results.editP50Ms).toBeLessThanOrEqual(300);
55
+ expect(Math.max(warm.elapsed, edits[0]!.elapsed, edits[1]!.elapsed)).toBeLessThan(1000);
56
+ await browser("screenshot", resolve("../../.tmp/H-link/linked-frame.png"));
57
+ } catch (error) {
58
+ if (launched) {
59
+ await writeFile(resolve("../../.tmp/H-link/browser-errors.json"), (await browser("errors", "--json")).stdout);
60
+ await writeFile(resolve("../../.tmp/H-link/browser-console.json"), (await browser("console", "--json")).stdout);
61
+ await writeFile(resolve("../../.tmp/H-link/browser-body.html"), (await browser("get", "html", "body")).stdout);
62
+ }
63
+ throw error;
64
+ } finally { try { if (launched) await browser("close"); } finally { await server.close(); } }
65
+ });
66
+ });
@@ -0,0 +1,22 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { expect, it } from "vitest";
4
+ import { startLocalLinkServer } from "./testing/local-server.ts";
5
+
6
+ it("installs, caches and invalidates through a local relay while only /frame/ is controlled", async () => {
7
+ const server = await startLocalLinkServer();
8
+ const execute = promisify(execFile);
9
+ const session = `page-runtime-V-link-${process.pid}`;
10
+ let launched = false;
11
+ const browser = async (...args: string[]) => (await execute("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2000000 })).stdout.trim();
12
+ try {
13
+ await browser("open", server.url); launched = true;
14
+ await browser("wait", "--fn", 'document.title === "LINK-READY" || document.title === "LINK-ERROR"');
15
+ expect(await browser("get", "text", "#error")).toBe("");
16
+ expect(JSON.parse(await browser("get", "text", "#result"))).toEqual({ shellControlled: false, scopes: ["/frame/"], reads: [
17
+ { code: expect.stringContaining('"revision-0"'), compiled: "1" },
18
+ { code: expect.stringContaining('"revision-0"'), compiled: "0" },
19
+ { code: expect.stringContaining('"revision-1"'), compiled: "1" },
20
+ ] });
21
+ } finally { try { if (launched) await browser("close"); } finally { await server.close(); } }
22
+ });
@@ -0,0 +1,69 @@
1
+ import type { Fragment, RuntimeProfile } from "../schema.ts";
2
+ import { BASE_PACKAGES, composeFragments, mergeBarrels, packageName } from "../sw/composition.ts";
3
+ import type { LibraryLink } from "./types.ts";
4
+ import { assertLinksAllowed, linkUrl, validateLink } from "./validation.ts";
5
+ import { mapBarrels } from "./barrels.ts";
6
+ import { validatePageSources, type PageSourceLock } from "./page-sources.ts";
7
+ import { validateCompilerPlugins } from "../sw/compiler-plugins.ts";
8
+
9
+ export function mountLinkTarget(link: LibraryLink, target: string): string {
10
+ const path = target.replace(/^\/npm\//, "");
11
+ const prefix = `${link.build.library}@${link.build.version}/`;
12
+ if (path === prefix.slice(0, -1)) return `/link/${link.id}`;
13
+ if (path.startsWith(prefix)) return linkUrl(link.id, path.slice(prefix.length));
14
+ return target.startsWith("/") ? target : `/npm/${path}`;
15
+ }
16
+
17
+ export function composeLinkOverrides(options: { lock: PageSourceLock; links: LibraryLink[]; profile: Pick<RuntimeProfile, "links">; developerOverrides: boolean }): PageSourceLock {
18
+ assertLinksAllowed(options);
19
+ const links = [...options.links].sort((a, b) => Number(b.build.library === "@flanksource/clicky-ui") - Number(a.build.library === "@flanksource/clicky-ui"));
20
+ const names = new Set<string>();
21
+ const ids = new Set<string>();
22
+ for (const link of links) {
23
+ validateLink(link);
24
+ if (names.has(link.build.library) || ids.has(link.id)) throw new Error(`Duplicate linked library or id ${link.build.library}: ${link.id}`);
25
+ names.add(link.build.library);
26
+ ids.add(link.id);
27
+ }
28
+ const lock = structuredClone(options.lock);
29
+ const pageSources = [...(lock.pageSources ?? []).filter((root) => !ids.has(root.link)), ...links.flatMap((link) => (link.build.pageSources ?? []).map((root) => ({ ...root, link: link.id })))];
30
+ if (pageSources.length) { validatePageSources(pageSources); lock.pageSources = pageSources; }
31
+ const linkedBase = links.find((link) => link.build.library === "@flanksource/clicky-ui");
32
+ const inheritedBase: Fragment = { fragment: 1, name: "@flanksource/clicky-ui", imports: Object.fromEntries(Object.entries(lock.map.imports).map(([name, target]) => [name, target.replace(/^\/npm\//, "")])), scopes: {}, remaps: {}, integrity: {}, inherits: [], aliases: {} };
33
+ if (linkedBase) {
34
+ const base = composeFragments({ fragments: [linkedBase.build.fragment] }).map.imports;
35
+ for (const specifier of Object.keys(lock.map.imports).filter((name) => BASE_PACKAGES.includes(packageName(name)))) {
36
+ if (!base[specifier]) throw new Error(`Linked base set is missing ${specifier}`);
37
+ for (const table of Object.values(lock.map.scopes)) {
38
+ if (table[specifier] && table[specifier] !== lock.map.imports[specifier]) throw new Error(`Scope remaps base-set ${specifier}`);
39
+ delete table[specifier];
40
+ }
41
+ delete lock.map.imports[specifier];
42
+ }
43
+ }
44
+ for (const link of links) {
45
+ const base = linkedBase?.build.fragment ?? inheritedBase;
46
+ const composed = composeFragments({ fragments: link === linkedBase ? [link.build.fragment] : [base, link.build.fragment] });
47
+ const mount = (target: string) => mountLinkTarget(links.find((candidate) => target.startsWith(`/npm/${candidate.build.library}@${candidate.build.version}/`) || target === `/npm/${candidate.build.library}@${candidate.build.version}`) ?? link, target);
48
+ for (const key of Object.keys(lock.map.imports)) if (key === link.build.library || key.startsWith(`${link.build.library}/`)) delete lock.map.imports[key];
49
+ for (const scope of Object.keys(lock.map.scopes)) if (scope.startsWith(`/npm/${link.build.library}@`)) delete lock.map.scopes[scope];
50
+ for (const [name, target] of Object.entries(composed.map.imports)) {
51
+ const owner = linkedBase && target.startsWith(`/npm/${linkedBase.build.library}@`) ? linkedBase : link;
52
+ if (BASE_PACKAGES.includes(packageName(name)) && !linkedBase && lock.map.imports[name] !== target) throw new Error(`${link.build.library}: remaps base-set ${name}`);
53
+ lock.map.imports[name] = mountLinkTarget(owner, target);
54
+ }
55
+ for (const [scope, table] of Object.entries(composed.map.scopes)) lock.map.scopes[mount(scope.slice(0, -1)) + "/"] = Object.fromEntries(Object.entries(table).map(([name, target]) => [name, mount(target)]));
56
+ for (const [name, path] of Object.entries(link.build.entries)) lock.map.imports[name] = linkUrl(link.id, path);
57
+ Object.assign(lock.integrity, composed.integrity);
58
+ Object.assign(lock.remaps, composed.remaps);
59
+ lock.versions[link.build.library] = link.build.version;
60
+ if (link.build.fragment.compiler) lock.compiler = { ...lock.compiler, [link.build.library]: validateCompilerPlugins(link.build.fragment.compiler, { library: link.build.library, path: `${link.build.library} checkout fragment compiler` }) };
61
+ else if (lock.compiler?.[link.build.library]) lock.compiler = Object.fromEntries(Object.entries(lock.compiler).filter(([library]) => library !== link.build.library));
62
+ lock.barrels = mergeBarrels([lock.barrels, mapBarrels({ index: link.build.barrels, map: (path) => path.startsWith("/npm/") ? mount(path) : linkUrl(link.id, path) })]);
63
+ }
64
+ return lock;
65
+ }
66
+
67
+ export function linksInLock(lock: PageSourceLock): string[] {
68
+ return [...new Set([...(lock.pageSources ?? []).map((root) => root.link), ...[Object.keys(lock.map.scopes), Object.values(lock.map.imports), ...Object.values(lock.map.scopes).map(Object.values)].flat().flatMap((target) => /^\/link\/([^/]+)\//.exec(target)?.[1] ?? [])])];
69
+ }
@@ -0,0 +1,69 @@
1
+ import type { PageLock } from "../schema.ts";
2
+ import { validateSourcePath } from "../host/validation.ts";
3
+ import { isPageSource } from "../host/agent-source.ts";
4
+ import type { LibraryLink } from "./types.ts";
5
+ import { linkUrl } from "./validation.ts";
6
+
7
+ export type PageSourceRoot = { link: string; root: string; prefix: string; editable: boolean };
8
+ export type PageSourceLock = PageLock & { pageSources?: PageSourceRoot[] };
9
+ export type PageSourceContext = { pageSources?: PageSourceRoot[] };
10
+
11
+ export function isPageModule(options: { path: string; lock: PageSourceContext }): boolean {
12
+ if (options.path.startsWith("/src/")) return true;
13
+ const link = /^\/link\/([^/]+)\//.exec(options.path)?.[1];
14
+ return link !== undefined && (options.lock.pageSources ?? []).some((root) => root.link === link);
15
+ }
16
+
17
+ export function pageSourceModule(options: { page: string; roots: PageSourceRoot[] }): string | undefined {
18
+ path(options.page); validatePageSources(options.roots);
19
+ const root = options.roots.filter((root) => !root.prefix || options.page.startsWith(`${root.prefix}/`)).sort((a, b) => b.prefix.length - a.prefix.length)[0];
20
+ return root ? linkUrl(root.link, `${root.root}/${root.prefix ? options.page.slice(root.prefix.length + 1) : options.page}`) : undefined;
21
+ }
22
+
23
+ function path(value: string, empty = false): void {
24
+ if (empty && value === "") return;
25
+ validateSourcePath(value);
26
+ if (/%|:/.test(value)) throw new Error(`Noncanonical page source path ${value}`);
27
+ }
28
+
29
+ export function validatePageSources(value: unknown): asserts value is PageSourceRoot[] {
30
+ if (!Array.isArray(value) || value.length > 1000) throw new Error("Invalid page source roots");
31
+ const roots: PageSourceRoot[] = [];
32
+ for (const item of value) {
33
+ if (!item || typeof item !== "object" || Object.keys(item).some((key) => !["link", "root", "prefix", "editable"].includes(key))) throw new Error("Invalid page source root");
34
+ const root = item as PageSourceRoot;
35
+ if (typeof root.link !== "string" || !/^[A-Za-z0-9_-]+$/.test(root.link) || typeof root.root !== "string" || typeof root.prefix !== "string" || typeof root.editable !== "boolean") throw new Error("Invalid page source declaration");
36
+ path(root.root); path(root.prefix, true);
37
+ if (!isPageSource(`${root.root}/page.tsx:1:1`) || !isPageSource(`${root.prefix ? `${root.prefix}/` : ""}page.tsx:1:1`)) throw new Error("Page source root or destination is a library or runtime path");
38
+ for (const previous of roots) {
39
+ if ((previous.link === root.link && overlaps(previous.root, root.root)) || previous.prefix === root.prefix) throw new Error("Page source roots overlap");
40
+ }
41
+ roots.push(root);
42
+ }
43
+ }
44
+
45
+ function overlaps(a: string, b: string): boolean {
46
+ return !a || !b || a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
47
+ }
48
+
49
+ export function pageSourcePath(options: { path: string; roots: PageSourceRoot[] }): string | undefined {
50
+ validatePageSources(options.roots);
51
+ const match = /^\/link\/([^/]+)\/(.+)$/.exec(options.path);
52
+ if (!match) return undefined;
53
+ const relative = decodeURIComponent(match[2]!); path(relative);
54
+ const root = options.roots.find((root) => root.link === match[1] && relative.startsWith(`${root.root}/`));
55
+ if (!root?.editable) return undefined;
56
+ const projected = `${root.prefix ? `${root.prefix}/` : ""}${relative.slice(root.root.length + 1)}`;
57
+ path(projected);
58
+ if (!isPageSource(`${projected}:1:1`)) throw new Error("Projected source is a library or runtime path");
59
+ return projected;
60
+ }
61
+
62
+ export function validatePageSourceLinks(options: { lock: PageSourceLock; links: LibraryLink[] }): void {
63
+ if (options.lock.pageSources === undefined) return;
64
+ validatePageSources(options.lock.pageSources);
65
+ for (const root of options.lock.pageSources) {
66
+ const link = options.links.find((link) => link.id === root.link);
67
+ if (!link?.build.pageSources?.some((declared) => declared.root === root.root && declared.prefix === root.prefix && declared.editable === root.editable)) throw new Error(`Page source ${root.link}/${root.root} has no matching installed link declaration`);
68
+ }
69
+ }
@@ -0,0 +1,25 @@
1
+ import type { StoredLink } from "./types.ts";
2
+ import { missingLinkFile } from "./validation.ts";
3
+ import { validateSourcePath } from "../host/validation.ts";
4
+
5
+ export async function readLinkFile(options: { link: StoredLink; path: string; fetch?: typeof fetch; signal?: AbortSignal }): Promise<Uint8Array> {
6
+ const { link, path } = options;
7
+ validateSourcePath(path);
8
+ if (link.source.kind === "server") {
9
+ const url = new URL(path.split("/").map(encodeURIComponent).join("/"), link.source.url.replace(/\/?$/, "/"));
10
+ const response = await (options.fetch ?? fetch)(url, { mode: "cors", credentials: "omit", redirect: "error", cache: "no-store", ...(options.signal ? { signal: options.signal } : {}) });
11
+ if (response.status === 404) throw missingLinkFile(link, path);
12
+ if (!response.ok) throw new Error(`${link.build.library}: ${path}: HTTP ${response.status}`);
13
+ return new Uint8Array(await response.arrayBuffer());
14
+ }
15
+ if (!link.directory) throw new Error(`${link.id}: folder handle is missing; select the checkout again`);
16
+ try {
17
+ const segments = path.split("/");
18
+ let directory = link.directory;
19
+ for (const segment of segments.slice(0, -1)) directory = await directory.getDirectoryHandle(segment);
20
+ return new Uint8Array(await (await (await directory.getFileHandle(segments.at(-1)!)).getFile()).arrayBuffer());
21
+ } catch (error) {
22
+ if (error instanceof DOMException && error.name === "NotFoundError") throw missingLinkFile(link, path);
23
+ throw new Error(`${link.id}: cannot read ${path}; verify folder read permission: ${String(error)}`, { cause: error });
24
+ }
25
+ }
@@ -0,0 +1,32 @@
1
+ import type { StoredLink } from "./types.ts";
2
+ import { validateLink } from "./validation.ts";
3
+
4
+ export function createLinkStore(factory?: IDBFactory) {
5
+ let opened: Promise<IDBDatabase> | undefined;
6
+ function database(): Promise<IDBDatabase> {
7
+ return opened ??= new Promise((resolve, reject) => {
8
+ const request = (factory ?? indexedDB).open("page-runtime-links", 1);
9
+ request.onupgradeneeded = () => request.result.createObjectStore("links", { keyPath: "id" });
10
+ request.onsuccess = () => resolve(request.result);
11
+ request.onerror = () => reject(request.error);
12
+ request.onblocked = () => reject(new Error("Link database upgrade is blocked"));
13
+ });
14
+ }
15
+ async function transaction<T>(mode: IDBTransactionMode, action: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
16
+ const db = await database();
17
+ return new Promise((resolve, reject) => {
18
+ const tx = db.transaction("links", mode);
19
+ const request = action(tx.objectStore("links"));
20
+ tx.oncomplete = () => resolve(request.result);
21
+ tx.onerror = () => reject(tx.error);
22
+ tx.onabort = () => reject(tx.error ?? new Error("Link transaction aborted"));
23
+ });
24
+ }
25
+ return {
26
+ async put(link: StoredLink) { validateLink(link); await transaction("readwrite", (store) => store.put(link)); },
27
+ async get(id: string): Promise<StoredLink> { const link = await transaction<StoredLink | undefined>("readonly", (store) => store.get(id)); if (!link) throw new Error(`Unknown library link ${id}`); validateLink(link); return link; },
28
+ async list(): Promise<StoredLink[]> { const links = await transaction<StoredLink[]>("readonly", (store) => store.getAll()); links.forEach(validateLink); return links; },
29
+ async remove(id: string) { await transaction("readwrite", (store) => store.delete(id)); },
30
+ async close() { if (opened) (await opened).close(); opened = undefined; },
31
+ };
32
+ }