@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,92 @@
1
+ import { init, parse as lex } from "es-module-lexer";
2
+ import { transform, type Transform } from "sucrase";
3
+ import { defineNodeEnv } from "./module-transform.ts";
4
+ import { insertSourceMarkers } from "./markers.ts";
5
+ import { completeCompositeSources } from "./compiler-columns.ts";
6
+ import { sourceHash } from "./source-hash.ts";
7
+ import type { CommonJsSource } from "../link/types.ts";
8
+
9
+ // The service worker's page compiler: Sucrase for TS, TSX and JSX; the MDX compiler for MDX. Both run in the worker
10
+ // and in Node unchanged.
11
+
12
+ /** Where page modules import the development JSX runtime from: a shim that marks host elements. */
13
+ export const DEV_SHIM_URL = "/__runtime/jsx-dev-runtime.js";
14
+ export const COMPILER_REVISION = "editable-boundaries-live-v2";
15
+
16
+ /**
17
+ * Adds `data-source` to host elements from jsxDEV's source argument. MDX's development output passes a full
18
+ * `{fileName, lineNumber, columnNumber}`; TS, TSX and JSX modules already carry the attribute (see markers.ts).
19
+ */
20
+ export const DEV_SHIM = [
21
+ 'import { jsxDEV as base } from "react/jsx-dev-runtime";',
22
+ 'import { editableElement } from "/__runtime/editing.js";',
23
+ 'export { Fragment } from "react/jsx-dev-runtime";',
24
+ "export function jsxDEV(type, props, key, isStatic, source, self) {",
25
+ ' if (typeof type === "string" && source && source.columnNumber !== undefined && !(props && "data-source" in props)) {',
26
+ ' props = { ...props, "data-source": `${source.fileName}:${source.lineNumber}:${source.columnNumber}` };',
27
+ " }",
28
+ " return editableElement(base(type, props, key, isStatic, source, self));",
29
+ "}",
30
+ "",
31
+ ].join("\n");
32
+
33
+ /** The MDX plugins every page compiles with, in facet's build order (the reference and the worker load their own copies). */
34
+ export type MdxPlugins = { remarkFrontmatter: unknown; remarkGfm: unknown; remarkAlert: unknown; rehypeRaw: unknown };
35
+
36
+ /** `remark` appends library-declared plugins, as `[plugin, options]` pairs, after the base set; only exports pass them. */
37
+ export function mdxOptions(plugins: MdxPlugins, remark: unknown[] = []): { remarkPlugins: unknown[]; rehypePlugins: unknown[] } {
38
+ return {
39
+ remarkPlugins: [plugins.remarkFrontmatter, plugins.remarkGfm, [plugins.remarkAlert, { tagName: "blockquote" }], ...remark],
40
+ rehypePlugins: [[plugins.rehypeRaw, { passThrough: ["mdxFlowExpression", "mdxJsxFlowElement", "mdxJsxTextElement", "mdxTextExpression", "mdxjsEsm"] }]],
41
+ };
42
+ }
43
+
44
+ export type MdxCompile = (file: { value: string; path: string }, options: Record<string, unknown>) => Promise<{ toString(): string }>;
45
+
46
+ export type PageSourceInput = { path: string; extension: string; code: string; sourcePath?: string; commonjs?: CommonJsSource };
47
+
48
+ export function compileCommonJsSource(options: { path: string; code: string; conversion: CommonJsSource }): string {
49
+ if (sourceHash(options.code) !== options.conversion.hash) throw new Error(`${options.path}: CommonJS source changed; rebuild its runtime conversion and named-export metadata`);
50
+ if (!options.conversion.target.startsWith("/link/") && !options.conversion.target.startsWith("/src/")) throw new Error(`${options.path}: CommonJS conversion requires a declared source module URL`);
51
+ return `export { default } from ${JSON.stringify(options.conversion.target)};\nexport * from ${JSON.stringify(options.conversion.target)};\n`;
52
+ }
53
+
54
+ /** Compiles one TS, TSX or JSX module with source markers and React's development runtime. */
55
+ export function compileScript({ path, extension, code, sourcePath = path }: PageSourceInput): string {
56
+ const typescript = extension === ".ts" || extension === ".tsx";
57
+ const jsx = extension !== ".ts";
58
+ const marked = jsx ? insertSourceMarkers(code, sourcePath, typescript) : undefined;
59
+ const transforms: Transform[] = [...(typescript ? (["typescript"] as const) : []), ...(jsx ? (["jsx"] as const) : [])];
60
+ const { code: compiled } = transform(marked?.code ?? code, {
61
+ transforms,
62
+ jsxRuntime: "automatic",
63
+ filePath: sourcePath,
64
+ disableESTransforms: true,
65
+ });
66
+ return defineNodeEnv(marked ? completeCompositeSources({ code: compiled, sourceProperty: marked.sourceProperty }) : compiled).code;
67
+ }
68
+
69
+ /** Points a module's `react/jsx-dev-runtime` imports at the marker shim. */
70
+ export async function useDevShim(code: string): Promise<string> {
71
+ await init();
72
+ const [imports] = lex(code);
73
+ let rewritten = code;
74
+ for (const item of [...imports].reverse()) {
75
+ if (item.specifier === "react/jsx-dev-runtime") rewritten = `${rewritten.slice(0, item.start)}${DEV_SHIM_URL}${rewritten.slice(item.end)}`;
76
+ }
77
+ return rewritten;
78
+ }
79
+
80
+ /** Compiles an MDX page with the base plugins (plus `remark`, for exports) and routes jsxDEV calls through the marker shim. */
81
+ export async function compileMdx({ path, code, sourcePath = path }: PageSourceInput, compile: MdxCompile, plugins: MdxPlugins, remark: unknown[] = []): Promise<string> {
82
+ const output = await compile({ value: code, path: sourcePath }, { ...mdxOptions(plugins, remark), development: true });
83
+ return useDevShim(defineNodeEnv(String(output)).code);
84
+ }
85
+
86
+ /** The compiler's entry: TS, TSX, JSX and MDX page sources to ESM. */
87
+ export async function compileSource(input: PageSourceInput, mdx: { compile: MdxCompile; plugins: MdxPlugins }): Promise<string> {
88
+ if (input.commonjs) return compileCommonJsSource({ path: input.path, code: input.code, conversion: input.commonjs });
89
+ if (input.extension === ".mdx" || input.extension === ".md") return compileMdx(input, mdx.compile, mdx.plugins);
90
+ if ([".ts", ".tsx", ".jsx"].includes(input.extension)) return useDevShim(compileScript(input));
91
+ throw new Error(`${input.path}: the compiler takes .ts, .tsx, .jsx, .md and .mdx sources, not ${input.extension}`);
92
+ }
@@ -0,0 +1,44 @@
1
+ import { parse } from "sucrase/dist/parser";
2
+ import { TokenType } from "sucrase/dist/parser/tokenizer/types";
3
+
4
+ // Carry original component positions through Sucrase's prop/key reordering, then move them into
5
+ // React's source argument. The temporary property never reaches a component or the DOM.
6
+ export function completeCompositeSources(options: { code: string; sourceProperty: string }): string {
7
+ const { code, sourceProperty } = options;
8
+ const { tokens } = parse(code, false, false, false);
9
+ const stack: number[] = [];
10
+ const parents = new Map<number, number>();
11
+ const ends = new Map<number, number>();
12
+ tokens.forEach((token, index) => {
13
+ if (stack.length) parents.set(index, stack.at(-1)!);
14
+ if ([TokenType.parenL, TokenType.braceL, TokenType.bracketL, TokenType.dollarBraceL].includes(token.type)) stack.push(index);
15
+ else if ([TokenType.parenR, TokenType.braceR, TokenType.bracketR].includes(token.type)) {
16
+ const start = stack.pop();
17
+ if (start === undefined) throw new Error("unbalanced compiled JSX delimiters");
18
+ ends.set(start, index);
19
+ }
20
+ });
21
+ const edits: Array<{ start: number; end: number; text: string }> = [];
22
+ tokens.forEach((token, index) => {
23
+ if (code.slice(token.start, token.end) !== sourceProperty || tokens[index + 1]?.type !== TokenType.colon) return;
24
+ const props = parents.get(index);
25
+ const call = props === undefined ? undefined : parents.get(props);
26
+ const sourceStart = tokens[index + 2];
27
+ const sourceEnd = ends.get(index + 2);
28
+ const callEnd = call === undefined ? undefined : ends.get(call);
29
+ if (props === undefined || call === undefined || callEnd === undefined || sourceStart?.type !== TokenType.braceL || sourceEnd === undefined) throw new Error("compiled JSX lost its component source property");
30
+ const sources = tokens.slice(index + 3, callEnd).flatMap((candidate, offset) => {
31
+ const at = index + 3 + offset;
32
+ const end = ends.get(at);
33
+ if (candidate.type !== TokenType.braceL || end === undefined || (parents.get(at) !== call && parents.get(at) !== props)) return [];
34
+ if (!/^\{fileName: [\w$]+, lineNumber: \d+\}$/.test(code.slice(candidate.start, tokens[end]!.end))) return [];
35
+ return [{ start: candidate.start, end: tokens[end]!.end }];
36
+ });
37
+ if (sources.length !== 1) throw new Error(`expected one generated JSX source, received ${sources.length}`);
38
+ edits.push({ ...sources[0]!, text: code.slice(sourceStart.start, tokens[sourceEnd]!.end) });
39
+ const comma = tokens[sourceEnd + 1];
40
+ if (comma?.type !== TokenType.comma) throw new Error("compiled JSX source property has no separator");
41
+ edits.push({ start: token.start, end: comma.end, text: "" });
42
+ });
43
+ return edits.sort((a, b) => b.start - a.start).reduce((output, edit) => `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`, code);
44
+ }
@@ -0,0 +1,8 @@
1
+ declare module "sucrase/dist/parser" {
2
+ export * from "sucrase/dist/types/parser/index";
3
+ }
4
+
5
+ declare module "sucrase/dist/parser/tokenizer/types" {
6
+ export * from "sucrase/dist/types/parser/tokenizer/types";
7
+ }
8
+
@@ -0,0 +1,18 @@
1
+ import type { CompilerPlugins } from "../schema.ts";
2
+ import { validateJson } from "../host/message-values.ts";
3
+ import { keys, record } from "./profile.ts";
4
+
5
+ /** Validates a library's compiler plugin declaration; a library may only contribute modules it exports itself. */
6
+ export function validateCompilerPlugins(value: unknown, options: { library: string; path: string }): CompilerPlugins {
7
+ const declared = record(value, options.path);
8
+ keys(declared, ["remark"], options.path);
9
+ if (!Array.isArray(declared.remark) || !declared.remark.length) throw new Error(`${options.path}.remark: expected a non-empty array of plugins`);
10
+ for (const [index, entry] of declared.remark.entries()) {
11
+ const path = `${options.path}.remark[${index}]`;
12
+ const plugin = record(entry, path);
13
+ keys(plugin, ["module", "options"], path);
14
+ if (typeof plugin.module !== "string" || !plugin.module.startsWith(`${options.library}/`)) throw new Error(`${path}.module: expected a ${options.library}/… module the library exports, got ${String(plugin.module)}`);
15
+ if (plugin.options !== undefined) validateJson(plugin.options);
16
+ }
17
+ return declared as CompilerPlugins;
18
+ }
@@ -0,0 +1,93 @@
1
+ import { compile } from "@mdx-js/mdx";
2
+ import { init, parse } from "es-module-lexer";
3
+ import rehypeRaw from "rehype-raw";
4
+ import remarkFrontmatter from "remark-frontmatter";
5
+ import remarkGfm from "remark-gfm";
6
+ import { remarkAlert } from "remark-github-blockquote-alert";
7
+ import type { PageLock } from "../schema.ts";
8
+ import { compileMdx, compileSource, DEV_SHIM_URL, type MdxPlugins } from "./compile.ts";
9
+ import { CANONICAL_CANDIDATES, defineNodeEnv, specifierKind, stylesheetModule, transformModule } from "./module-transform.ts";
10
+ import { resolveSpecifier } from "./composition.ts";
11
+ import { RuntimeFailure } from "./errors.ts";
12
+ import { sourceCandidates } from "./candidates.ts";
13
+ import type { WorkerActivity } from "../activity-schema.ts";
14
+ import { RUNTIME_MODULES } from "./runtime-module.ts";
15
+
16
+ export type CompilerOptions = { path: string; code: string; lock: PageLock; sources: string[]; plugins: MdxPlugins; remark?: unknown[]; activity?: WorkerActivity; transpile?: (compile: () => Promise<string>) => Promise<string> };
17
+ export const BASE_PLUGINS: MdxPlugins = { remarkFrontmatter, remarkGfm, remarkAlert, rehypeRaw };
18
+ export const moduleUrl = (url: string): string => {
19
+ const parsed = new URL(url, "https://runtime.invalid");
20
+ return `${parsed.pathname}${parsed.search}`;
21
+ };
22
+
23
+ // The URL a module is imported by: the page and link context the worker added from the requesting client are removed.
24
+ export const requestModuleUrl = (url: URL): string => {
25
+ const module = new URL(url);
26
+ module.searchParams.delete("page"); module.searchParams.delete("link-context");
27
+ return `${module.pathname}${module.search}`;
28
+ };
29
+
30
+ function canonical(specifier: string, options: { path: string; lock: PageLock; sources: string[]; line: number }): string {
31
+ const kind = specifierKind(specifier);
32
+ let target = kind === "bare" ? resolveSpecifier(options.lock.map, specifier, options.path) : new URL(specifier, `https://runtime.invalid${options.path}`).pathname;
33
+ if (kind === "builtin" || kind === "url" || !target) throw new RuntimeFailure({ phase: "link", file: options.path, line: options.line, message: `${options.path}:${options.line}: import ${specifier} is outside the library set; allowed packages: ${Object.keys(options.lock.versions).join(", ")}` });
34
+ const parsed = new URL(target, "https://runtime.invalid");
35
+ const source = parsed.pathname.startsWith("/src/");
36
+ const converted = parsed.pathname.startsWith("/esm/");
37
+ const prefix = source ? "/src/" : converted ? "/esm/" : "/npm/";
38
+ if (parsed.pathname === DEV_SHIM_URL || Object.hasOwn(RUNTIME_MODULES, parsed.pathname)) return target;
39
+ if (!parsed.pathname.startsWith(prefix)) throw new Error(`${options.path}: unsupported module URL ${target}`);
40
+ const relative = parsed.pathname.slice(prefix.length);
41
+ const listing = source ? options.sources : Object.keys(options.lock.integrity);
42
+ const candidates = source ? ["", ".tsx", ".ts", ".jsx", ".js", ".mdx", ".md", "/index.tsx", "/index.ts", "/index.jsx", "/index.js"] : CANONICAL_CANDIDATES;
43
+ const found = candidates.map((suffix) => `${relative}${suffix}`).find((file) => listing.includes(converted ? `esm/${file}` : file) || (!source && !converted && options.lock.remaps[file] !== undefined));
44
+ if (!found) throw new RuntimeFailure({ phase: "link", file: options.path, line: options.line, message: `${options.path}:${options.line}: cannot resolve ${specifier} to a canonical file` });
45
+ target = `${prefix}${source || converted ? found : options.lock.remaps[found] ?? found}`;
46
+ const query = new URL(specifier, "https://runtime.invalid").searchParams;
47
+ if (query.has("raw")) target += "?raw";
48
+ else if (query.has("url")) target += "?url";
49
+ else if (/\.(css|json)$/.test(found)) target += "?module";
50
+ return target;
51
+ }
52
+
53
+ export async function rewriteImports(options: { code: string; path: string; lock: PageLock; sources: string[]; activity?: WorkerActivity }): Promise<string> {
54
+ const started = performance.now();
55
+ try {
56
+ await init();
57
+ let code = transformModule(options.code, { url: options.path, known: (p) => Object.hasOwn(options.lock.integrity, p), resolveBare: (s, r) => resolveSpecifier(options.lock.map, s, r), barrels: options.path.startsWith("/esm/") ? null : options.lock.barrels }).code;
58
+ const [imports] = parse(code);
59
+ for (const item of [...imports].reverse()) {
60
+ if (item.type === "import-meta") continue;
61
+ if (item.specifier === undefined) throw new RuntimeFailure({ phase: "link", file: options.path, line: code.slice(0, item.start).split("\n").length, message: `${options.path}: dynamic imports must name a literal module` });
62
+ const target = canonical(item.specifier, { ...options, line: code.slice(0, item.start).split("\n").length });
63
+ const quoted = /^['"`]/.test(code.slice(item.start, item.end));
64
+ const revision = new URL(options.path, "https://runtime.invalid").searchParams.get("revision");
65
+ const revised = new URL(target, "https://runtime.invalid");
66
+ if (revision && (revised.pathname.startsWith("/src/") || (revised.pathname.endsWith(".css") && revised.searchParams.has("module")))) revised.searchParams.set("revision", revision);
67
+ const text = moduleUrl(revised.href);
68
+ code = `${code.slice(0, item.start)}${quoted ? JSON.stringify(text) : text}${code.slice(item.end)}`;
69
+ }
70
+ return defineNodeEnv(code).code;
71
+ } finally { if (options.activity) options.activity.rewriteMs += performance.now() - started; }
72
+ }
73
+
74
+ export async function compilePage(options: CompilerOptions): Promise<{ code: string; candidates: string[] }> {
75
+ const url = new URL(options.path, "https://runtime.invalid");
76
+ const extension = url.pathname.slice(url.pathname.lastIndexOf("."));
77
+ let code: string;
78
+ if (url.searchParams.has("raw")) code = `export default ${JSON.stringify(options.code)};`;
79
+ else if (url.searchParams.has("url")) code = `export default ${JSON.stringify(moduleUrl(url.pathname))};`;
80
+ else if (extension === ".json") code = `export default ${JSON.stringify(JSON.parse(options.code))};`;
81
+ else if (extension === ".css") { const stylesheet = new URL(url); stylesheet.searchParams.delete("module"); code = stylesheetModule(options.code, moduleUrl(stylesheet.href)); }
82
+ else if ([".ts", ".tsx", ".jsx", ".mdx", ".md"].includes(extension)) {
83
+ const started = performance.now();
84
+ const input = { path: url.pathname.slice("/src/".length), extension, code: options.code };
85
+ const transpile = () => options.remark && /^\.mdx?$/.test(extension)
86
+ ? compileMdx(input, compile, options.plugins, options.remark)
87
+ : compileSource(input, { compile, plugins: options.plugins });
88
+ try { code = await (options.transpile ? options.transpile(transpile) : transpile()); }
89
+ finally { if (options.activity) options.activity.compileMs += performance.now() - started; }
90
+ } else if ([".js", ".mjs"].includes(extension)) code = options.code;
91
+ else throw new Error(`${options.path}: unsupported source extension ${extension}`);
92
+ return { code: await rewriteImports({ code, path: options.path, lock: options.lock, sources: options.sources, ...(options.activity ? { activity: options.activity } : {}) }), candidates: sourceCandidates({ path: url.pathname, code: options.code }) };
93
+ }
@@ -0,0 +1,86 @@
1
+ import type { CompilerPlugins, Fragment, ImportMap, PageLock, BarrelIndex } from "../schema.ts";
2
+ import { validateCompilerPlugins } from "./compiler-plugins.ts";
3
+
4
+ export const BASE_PACKAGES = ["react", "react-dom", "scheduler", "@tanstack/react-query", "jotai"];
5
+ export const packageName = (specifier: string): string => specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0]!;
6
+ const base = (specifier: string) => BASE_PACKAGES.includes(packageName(specifier));
7
+
8
+ function lookup(table: Record<string, string>, specifier: string): string | null {
9
+ if (Object.hasOwn(table, specifier)) return table[specifier]!;
10
+ const key = Object.keys(table).filter((k) => k.endsWith("/") && specifier.startsWith(k)).sort((a, b) => b.length - a.length)[0];
11
+ return key ? `${table[key]}${specifier.slice(key.length)}` : null;
12
+ }
13
+
14
+ export function resolveSpecifier(map: ImportMap, specifier: string, referrer: string): string | null {
15
+ for (const scope of Object.keys(map.scopes).filter((s) => referrer.startsWith(s)).sort((a, b) => b.length - a.length)) {
16
+ const found = lookup(map.scopes[scope]!, specifier);
17
+ if (found) return found;
18
+ }
19
+ return lookup(map.imports, specifier);
20
+ }
21
+
22
+ function assign(table: Record<string, string>, key: string, value: string, context: string): void {
23
+ if (table[key] && table[key] !== value) throw new Error(`${context}: remaps ${key}: ${table[key]} versus ${value}`);
24
+ table[key] = value;
25
+ }
26
+
27
+ export function composeFragments(options: { fragments: Fragment[] }): Pick<PageLock, "map" | "integrity" | "remaps" | "compiler"> {
28
+ const map: ImportMap = { imports: {}, scopes: {} }; const integrity: Record<string, string> = {}; const remaps: Record<string, string> = {}; const compiler: Record<string, CompilerPlugins> = {};
29
+ const url = (s: string) => `/npm/${s}`;
30
+ for (const fragment of options.fragments) {
31
+ const owned = (s: string) => s === fragment.name || s.startsWith(`${fragment.name}/`);
32
+ for (const [specifier, target] of Object.entries(fragment.imports)) {
33
+ if (base(specifier)) {
34
+ if (fragment.name !== "@flanksource/clicky-ui" && map.imports[specifier] !== url(target)) throw new Error(`${fragment.name}: remaps base-set ${specifier} from ${map.imports[specifier]} to ${url(target)}`);
35
+ assign(map.imports, specifier, url(target), fragment.name);
36
+ } else if (owned(specifier)) assign(map.imports, specifier, url(target), fragment.name);
37
+ }
38
+ for (const [scope, table] of Object.entries(fragment.scopes)) {
39
+ const scoped = map.scopes[url(scope)] ??= {};
40
+ for (const [specifier, target] of Object.entries({ ...fragment.imports, ...table })) {
41
+ if (base(specifier)) {
42
+ if (map.imports[specifier] !== url(target)) throw new Error(`${fragment.name} scope ${scope}: remaps base-set ${specifier}`);
43
+ } else assign(scoped, specifier, url(target), `${fragment.name} scope ${scope}`);
44
+ }
45
+ }
46
+ for (const [alias, prefix] of Object.entries(fragment.aliases)) for (const [specifier, target] of Object.entries(map.imports)) {
47
+ if (specifier === prefix || specifier.startsWith(`${prefix}/`)) assign(map.imports, `${alias}${specifier.slice(prefix.length)}`, target, fragment.name);
48
+ }
49
+ for (const [from, to] of Object.entries(fragment.remaps)) {
50
+ assign(remaps, from, to, fragment.name);
51
+ assign(map.imports, url(from), url(to), fragment.name);
52
+ }
53
+ for (const [file, digest] of Object.entries(fragment.integrity)) assign(integrity, file, digest, fragment.name);
54
+ if (fragment.compiler !== undefined) compiler[fragment.name] = validateCompilerPlugins(fragment.compiler, { library: fragment.name, path: `${fragment.name} fragment compiler` });
55
+ }
56
+ for (const fragment of options.fragments) for (const specifier of fragment.inherits) if (!lookup(map.imports, specifier)) throw new Error(`${fragment.name}: inherited ${specifier} has no base-set mapping`);
57
+ for (const [library, plugins] of Object.entries(compiler)) for (const plugin of plugins.remark) if (!lookup(map.imports, plugin.module)) throw new Error(`${library}: compiler plugin ${plugin.module} is not in its runtime fragment; rebuild the library runtime`);
58
+ return { map, integrity, remaps, ...(Object.keys(compiler).length ? { compiler } : {}) };
59
+ }
60
+
61
+ // Libraries that share a dependency version both index its barrels; identical indices coalesce, divergent ones fail.
62
+ export function mergeBarrels(indices: BarrelIndex[]): BarrelIndex {
63
+ const result: BarrelIndex = { modules: [], barrels: {} };
64
+ const positions = new Map<string, number>();
65
+ const position = (module: string) => {
66
+ const existing = positions.get(module);
67
+ if (existing !== undefined) return existing;
68
+ positions.set(module, result.modules.push(module) - 1);
69
+ return result.modules.length - 1;
70
+ };
71
+ const describe = (entries: BarrelIndex["barrels"][string], modules: string[]) =>
72
+ JSON.stringify(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)).map(([name, at]) => [name, typeof at === "number" ? modules[at] : [modules[at[0]], at[1]]]));
73
+ for (const index of indices) {
74
+ for (const [path, entries] of Object.entries(index.barrels)) {
75
+ const remapped = Object.fromEntries(Object.entries(entries).map(([name, at]): [string, number | [number, string]] => {
76
+ const module = index.modules[typeof at === "number" ? at : at[0]];
77
+ if (module === undefined) throw new Error(`barrel ${path}: ${name} points outside its module list`);
78
+ return [name, typeof at === "number" ? position(module) : [position(module), at[1]]];
79
+ }));
80
+ const existing = result.barrels[path];
81
+ if (existing && describe(existing, result.modules) !== describe(remapped, result.modules)) throw new Error(`barrel ${path} is indexed differently by two libraries`);
82
+ result.barrels[path] = remapped;
83
+ }
84
+ }
85
+ return result;
86
+ }
@@ -0,0 +1,28 @@
1
+ /** Content types by file extension, shared by the Node servers and the service worker. */
2
+ export const CONTENT_TYPES: Record<string, string> = {
3
+ ".js": "text/javascript; charset=utf-8",
4
+ ".mjs": "text/javascript; charset=utf-8",
5
+ ".cjs": "text/javascript; charset=utf-8",
6
+ ".css": "text/css; charset=utf-8",
7
+ ".html": "text/html; charset=utf-8",
8
+ ".json": "application/json; charset=utf-8",
9
+ ".map": "application/json; charset=utf-8",
10
+ ".svg": "image/svg+xml",
11
+ ".png": "image/png",
12
+ ".jpg": "image/jpeg",
13
+ ".gif": "image/gif",
14
+ ".webp": "image/webp",
15
+ ".woff": "font/woff",
16
+ ".woff2": "font/woff2",
17
+ ".ttf": "font/ttf",
18
+ ".otf": "font/otf",
19
+ ".wasm": "application/wasm",
20
+ ".txt": "text/plain; charset=utf-8",
21
+ ".md": "text/markdown; charset=utf-8",
22
+ };
23
+
24
+ export function extensionOf(path: string): string {
25
+ const name = path.slice(path.lastIndexOf("/") + 1);
26
+ const dot = name.lastIndexOf(".");
27
+ return dot > 0 ? name.slice(dot) : "";
28
+ }
@@ -0,0 +1,31 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { afterAll, beforeAll, expect, it } from "vitest";
4
+ import { startConvertedBrowserServer } from "./esm-sh-fixtures/browser-server.ts";
5
+
6
+ const exec = promisify(execFile);
7
+ const session = `esm-sh-${process.pid}`;
8
+ let server: Awaited<ReturnType<typeof startConvertedBrowserServer>> | undefined;
9
+ let launched = false;
10
+ async function browser(...args: string[]): Promise<string> {
11
+ return (await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 2_000_000 })).stdout.trim();
12
+ }
13
+ beforeAll(async () => { server = await startConvertedBrowserServer(); });
14
+ afterAll(async () => { try { if (launched) await browser("close"); } finally { await server?.close(); } });
15
+
16
+ it("renders recorded CommonJS conversion in Chromium with the managed React singleton and a local-only converter", async () => {
17
+ if (!server) throw new Error("converter fixture server was not started");
18
+ launched = true;
19
+ await browser("open", `${server.origin}/?page=report.js`);
20
+ await browser("wait", "--fn", 'document.title === "CONVERTED-DONE" || document.title === "CONVERTED-ERROR"');
21
+ expect(await browser("get", "text", "#result")).toBe("");
22
+ expect(await browser("get", "text", "#converted")).toBe("Copy fixture");
23
+ expect(await browser("get", "attr", "#converted", "data-one-react")).toBe("true");
24
+ expect(new Set(server.converterRequests)).toEqual(new Set([
25
+ "/*react-copy-to-clipboard@5.1.1?dev&target=es2022", "/*react-copy-to-clipboard@5.1.1/es2022/react-copy-to-clipboard.development.mjs",
26
+ "/*copy-to-clipboard@3.3.3?dev&target=es2022", "/*copy-to-clipboard@3.3.3/es2022/copy-to-clipboard.development.mjs",
27
+ "/*toggle-selection@1.0.6?dev&target=es2022", "/*toggle-selection@1.0.6/es2022/toggle-selection.development.mjs",
28
+ ]));
29
+ expect(server.packageRequests.filter((path) => path.endsWith("/react.js"))).toHaveLength(1);
30
+ expect(server.packageRequests.some((path) => path.startsWith("react@"))).toBe(false);
31
+ });
@@ -0,0 +1,64 @@
1
+ import { init, parse } from "es-module-lexer";
2
+ import { digest } from "./integrity.ts";
3
+ import { specifierKind } from "./module-transform.ts";
4
+
5
+ export const CONVERTED_ENTRY = "__entry.mjs";
6
+
7
+ export function convertedFile(path: string): { root: string; path: string } {
8
+ const match = /^esm\/((?:@[^/]+\/)?[^/@]+@[^/]+)\/(.+)$/.exec(path);
9
+ if (!match || /[?#\\]/.test(path) || Array.from(path).some((character) => character.charCodeAt(0) <= 0x20) || path.split("/").some((segment) => ["", ".", ".."].includes(segment))) throw new Error(`invalid converted package file ${path}`);
10
+ return { root: match[1]!, path: match[2]! };
11
+ }
12
+
13
+ export function converterUrl(options: { origin: string; root: string; path: string }): string {
14
+ return `${options.origin.replace(/\/$/, "")}/*${options.root}${options.path === CONVERTED_ENTRY ? "?dev&target=es2022" : `/${options.path}`}`;
15
+ }
16
+
17
+ function internalPath(options: { root: string; path: string; specifier: string }): string | null {
18
+ const { root, path, specifier } = options;
19
+ if (specifier.startsWith("/node/") || specifier.startsWith("node:")) throw new Error(`${root}: converter module ${path} imports Node polyfill ${specifier}`);
20
+ if (specifierKind(specifier) === "bare") return null;
21
+ if (specifierKind(specifier) !== "relative") throw new Error(`${root}: converter import ${specifier} in ${path} is outside the package's own /*${root}/ path`);
22
+ const url = new URL(specifier, `https://converter.invalid/*${root}/${path}`);
23
+ const prefix = `/*${root}/`;
24
+ const decoded = decodeURIComponent(url.pathname);
25
+ if (url.origin !== "https://converter.invalid" || !decoded.startsWith(prefix) || url.search || url.hash || decoded.includes("\\")) throw new Error(`${root}: converter import ${specifier} in ${path} is outside the package's own ${prefix} path`);
26
+ const result = decoded.slice(prefix.length);
27
+ if (!result || result === CONVERTED_ENTRY || result.split("/").some((part) => ["", ".", ".."].includes(part))) throw new Error(`${root}: invalid converter module path ${specifier}`);
28
+ return result;
29
+ }
30
+
31
+ export async function crawlConvertedPackage(options: { origin: string; root: string; fetcher: typeof fetch }): Promise<{ integrity: Record<string, string>; listing: string }> {
32
+ await init();
33
+ const pending = [CONVERTED_ENTRY]; const integrity: Record<string, string> = {};
34
+ const { fetcher } = options;
35
+ for (let index = 0; index < pending.length; index++) {
36
+ const path = pending[index]!;
37
+ const url = converterUrl({ ...options, path });
38
+ const response = await fetcher(url, { mode: "cors", credentials: "omit", redirect: "error" });
39
+ if (!response.ok) throw new Error(`${options.root}: converter returned HTTP ${response.status} for ${url}`);
40
+ const bytes = new Uint8Array(await response.arrayBuffer());
41
+ integrity[`esm/${options.root}/${path}`] = await digest(bytes);
42
+ for (const item of parse(new TextDecoder().decode(bytes))[0]) {
43
+ if (item.type === "import-meta") continue;
44
+ if (item.specifier === undefined) throw new Error(`${options.root}: converter module ${path} has a non-literal dynamic import`);
45
+ const internal = internalPath({ root: options.root, path, specifier: item.specifier });
46
+ if (internal !== null && !pending.includes(internal)) pending.push(internal);
47
+ }
48
+ }
49
+ return { integrity, listing: await digest(new TextEncoder().encode(JSON.stringify(Object.entries(integrity).sort(([a], [b]) => a.localeCompare(b))))) };
50
+ }
51
+
52
+ export async function rewriteConvertedImports(options: { code: string; root: string; path: string }): Promise<string> {
53
+ await init();
54
+ let code = options.code;
55
+ for (const item of [...parse(code)[0]].reverse()) {
56
+ if (item.type === "import-meta") continue;
57
+ if (item.specifier === undefined) throw new Error(`${options.root}: converter module ${options.path} has a non-literal dynamic import`);
58
+ const path = internalPath({ ...options, specifier: item.specifier });
59
+ if (path === null) continue;
60
+ const target = `/esm/${options.root}/${path}`;
61
+ code = `${code.slice(0, item.start)}${/^['"`]/.test(code.slice(item.start, item.end)) ? JSON.stringify(target) : target}${code.slice(item.end)}`;
62
+ }
63
+ return code;
64
+ }
@@ -0,0 +1,42 @@
1
+ import type { parse } from "sucrase/dist/parser";
2
+ import { TokenType } from "sucrase/dist/parser/tokenizer/types";
3
+
4
+ type Tokens = ReturnType<typeof parse>["tokens"];
5
+ const COMPONENTS = new Set(["BoxNode", "ContainerNode", "BrandBox", "BrandContainer", "Tile", "Zone"]);
6
+ const SVG = new Set(["rect", "circle", "ellipse", "line", "polyline", "polygon", "path", "text", "tspan", "g"]);
7
+
8
+ // The write server counts facet imports (including aliases/namespaces) and intrinsic SVG in one source-order sequence.
9
+ export function editableTags(code: string, tokens: Tokens): Set<string> {
10
+ const tags = new Set(SVG);
11
+ tokens.forEach((token, index) => {
12
+ if (token.type !== TokenType._import || token.isType) return;
13
+ let end = index + 1;
14
+ while (tokens[end] && tokens[end]!.type !== TokenType.string && tokens[end]!.type !== TokenType.semi) end++;
15
+ const module = tokens[end];
16
+ if (!module || !/^@flanksource\/facet(?:\/.*)?$/.test(code.slice(module.start + 1, module.end - 1))) return;
17
+ for (let at = index + 1; at < end; at++) {
18
+ const item = tokens[at]!;
19
+ if (item.isType) continue;
20
+ if (item.type === TokenType.star && tokens[at + 2]) {
21
+ const namespace = code.slice(tokens[at + 2]!.start, tokens[at + 2]!.end);
22
+ for (const component of COMPONENTS) tags.add(`${namespace}.${component}`);
23
+ }
24
+ if (tokens[at - 1]?.type !== TokenType.braceL && tokens[at - 1]?.type !== TokenType.comma) continue;
25
+ const name = code.slice(item.start, item.end).replace(/^["']|["']$/g, "");
26
+ if (!COMPONENTS.has(name)) continue;
27
+ const next = tokens[at + 1];
28
+ const alias = next && code.slice(next.start, next.end) === "as" ? tokens[at + 2] : item;
29
+ if (alias) tags.add(code.slice(alias.start, alias.end));
30
+ }
31
+ });
32
+ return tags;
33
+ }
34
+
35
+ export function openingEnd(tokens: Tokens, index: number): number {
36
+ let depth = 1;
37
+ for (let at = index + 1; at < tokens.length; at++) {
38
+ if (tokens[at]!.type === TokenType.jsxTagStart) depth++;
39
+ if (tokens[at]!.type === TokenType.jsxTagEnd && --depth === 0) return tokens[at - 1]!.type === TokenType.slash ? tokens[at - 1]!.start : tokens[at]!.start;
40
+ }
41
+ throw new Error("JSX opening tag has no end");
42
+ }
@@ -0,0 +1,30 @@
1
+ import type { RuntimeError, RuntimePhase } from "../schema.ts";
2
+ import type { LinkActivity } from "./link-activity.ts";
3
+
4
+ export class RuntimeFailure extends Error {
5
+ readonly detail: RuntimeError;
6
+ activity?: LinkActivity;
7
+ constructor(options: RuntimeError) { super(options.message); this.name = "RuntimeFailure"; this.detail = options; }
8
+ }
9
+
10
+ export function runtimeError(options: { error: unknown; phase: RuntimePhase; file: string }): RuntimeError {
11
+ if (options.error instanceof RuntimeFailure) return options.error.detail;
12
+ const message = options.error instanceof Error ? options.error.message : String(options.error);
13
+ if (options.error instanceof Error) {
14
+ for (const token of (options.error.stack ?? "").split(/\s+/)) {
15
+ const start = token.search(/\/(?:src|npm)\//);
16
+ if (start === -1) continue;
17
+ const frame = token.slice(start + 5).replace(/\)$/, "");
18
+ const columnAt = frame.lastIndexOf(":");
19
+ const lineAt = frame.lastIndexOf(":", columnAt - 1);
20
+ if (lineAt < 0) continue;
21
+ const line = frame.slice(lineAt + 1, columnAt);
22
+ const column = frame.slice(columnAt + 1);
23
+ if (!/^\d+$/.test(line) || !/^\d+$/.test(column)) continue;
24
+ const file = frame.slice(0, lineAt).split("?")[0]!;
25
+ return { phase: options.phase, file: decodeURIComponent(file), message, line: Number(line), column: Number(column) };
26
+ }
27
+ }
28
+ const location = /(?:\(|:)(\d+):(\d+)\)?/.exec(message);
29
+ return { phase: options.phase, file: options.file, message, ...(location ? { line: Number(location[1]), column: Number(location[2]) } : {}) };
30
+ }
@@ -0,0 +1,18 @@
1
+ async function run(): Promise<void> {
2
+ await navigator.serviceWorker.register("/sw.js", { scope: "/" });
3
+ await navigator.serviceWorker.ready;
4
+ if (!navigator.serviceWorker.controller) await new Promise<void>((resolve) => navigator.serviceWorker.addEventListener("controllerchange", () => resolve(), { once: true }));
5
+ const response = await fetch("/open.json");
6
+ if (!response.ok) throw new Error(`fixture open: HTTP ${response.status}`);
7
+ const channel = new MessageChannel();
8
+ const opened = new Promise<void>((resolve, reject) => { channel.port1.onmessage = (event: MessageEvent<{ ok: boolean; error?: { message: string } }>) => { channel.port1.close(); if (event.data.ok) resolve(); else reject(new Error(event.data.error?.message ?? "worker open failed")); }; });
9
+ navigator.serviceWorker.controller!.postMessage({ message: await response.json() }, [channel.port2]);
10
+ await opened;
11
+ const entry = "/src/report.js?page=report.js";
12
+ await import(/* @vite-ignore */ entry);
13
+ }
14
+
15
+ void run().catch((error: unknown) => {
16
+ document.querySelector("#result")!.textContent = error instanceof Error ? error.message : String(error);
17
+ document.title = "CONVERTED-ERROR";
18
+ });