@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.
- package/LICENSE +17 -0
- package/README.md +494 -2
- package/dist/build/README.md +96 -0
- package/dist/build/cjs-export-names.mjs +24 -0
- package/dist/build/dependencies.mjs +279 -0
- package/dist/build/dependencies.mjs.map +1 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs +2130 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs.map +1 -0
- package/dist/build/index.mjs +42 -0
- package/dist/build/index.mjs.map +1 -0
- package/dist/build/package.json +19 -0
- package/dist/build/types/activity-schema.d.ts +62 -0
- package/dist/build/types/build/barrels.d.ts +70 -0
- package/dist/build/types/build/base.d.ts +2 -0
- package/dist/build/types/build/browser-runtime-exports.d.ts +19 -0
- package/dist/build/types/build/check-fragment.d.ts +5 -0
- package/dist/build/types/build/commonjs-exports.d.ts +5 -0
- package/dist/build/types/build/convert-commonjs.d.ts +12 -0
- package/dist/build/types/build/dependencies.d.ts +6 -0
- package/dist/build/types/build/dependency-barrel-index.d.ts +5 -0
- package/dist/build/types/build/dependency-barrels.d.ts +7 -0
- package/dist/build/types/build/dependency-cache.d.ts +7 -0
- package/dist/build/types/build/dependency-optional.d.ts +4 -0
- package/dist/build/types/build/dependency-plugin.d.ts +8 -0
- package/dist/build/types/build/dependency-runtime.d.ts +20 -0
- package/dist/build/types/build/dependency-workers.d.ts +8 -0
- package/dist/build/types/build/errors.d.ts +9 -0
- package/dist/build/types/build/fragment.d.ts +13 -0
- package/dist/build/types/build/index.d.ts +7 -0
- package/dist/build/types/build/library-runtime.d.ts +21 -0
- package/dist/build/types/build/module-utils.d.ts +3 -0
- package/dist/build/types/build/recipe-dependencies.d.ts +2 -0
- package/dist/build/types/build/runtime-entries.d.ts +4 -0
- package/dist/build/types/build/runtime-layer.d.ts +17 -0
- package/dist/build/types/build/trace.d.ts +140 -0
- package/dist/build/types/design-schema.d.ts +98 -0
- package/dist/build/types/host/agent-source.d.ts +2 -0
- package/dist/build/types/host/agent-validation.d.ts +3 -0
- package/dist/build/types/host/design-validation.d.ts +2 -0
- package/dist/build/types/host/message-values.d.ts +8 -0
- package/dist/build/types/host/review/validation.d.ts +5 -0
- package/dist/build/types/host/validation.d.ts +6 -0
- package/dist/build/types/link/page-sources.d.ts +31 -0
- package/dist/build/types/link/types.d.ts +62 -0
- package/dist/build/types/link/validation.d.ts +9 -0
- package/dist/build/types/markers.d.ts +10 -0
- package/dist/build/types/review-schema.d.ts +60 -0
- package/dist/build/types/schema.d.ts +319 -0
- package/dist/build/types/sw/barrels.d.ts +9 -0
- package/dist/build/types/sw/compiler-plugins.d.ts +6 -0
- package/dist/build/types/sw/composition.d.ts +8 -0
- package/dist/build/types/sw/module-transform.d.ts +68 -0
- package/dist/build/types/sw/profile.d.ts +7 -0
- package/dist/build/types/sw/source-provider.d.ts +7 -0
- package/dist/build/types/sw/versions.d.ts +10 -0
- package/dist/node/catalog.mjs +1 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs +229 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs.map +1 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs +12 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs.map +1 -0
- package/dist/node/dev.mjs +410 -0
- package/dist/node/dev.mjs.map +1 -0
- package/dist/node/publication/cli.mjs +13 -0
- package/dist/node/publication/cli.mjs.map +1 -0
- package/dist/node/publication.mjs +1 -0
- package/dist/node/schema.mjs +1 -0
- package/dist/node/styles.mjs +49 -0
- package/dist/node/styles.mjs.map +1 -0
- package/dist/static/boot.js +40938 -0
- package/dist/static/boot.js.map +1 -0
- package/dist/static/bootstrap.html +1 -0
- package/dist/static/devtools-hook.js +118 -0
- package/dist/static/document-bundle.js +1 -0
- package/dist/static/document.js +2621 -0
- package/dist/static/editing.js +37 -0
- package/dist/static/export-compiler.js +81521 -0
- package/dist/static/export-compiler.js.map +1 -0
- package/dist/static/page-agent.js +17193 -0
- package/dist/static/page-agent.js.map +1 -0
- package/dist/static/sw.js +86112 -0
- package/dist/static/sw.js.map +1 -0
- package/package.json +110 -3
- package/scripts/build-builder.ts +27 -0
- package/scripts/build-library-runtime.ts +9 -0
- package/scripts/build-node.ts +26 -0
- package/scripts/build-static.ts +86 -0
- package/scripts/build.ts +7 -0
- package/scripts/check-fragment.ts +12 -0
- package/scripts/local-workspaces.ts +55 -0
- package/scripts/react-externals.ts +18 -0
- package/scripts/release-version.ts +47 -0
- package/scripts/run-package-build.ts +8 -0
- package/scripts/serve-packages.ts +8 -0
- package/src/activity-schema.ts +92 -0
- package/src/build/README.md +96 -0
- package/src/build/barrels.ts +306 -0
- package/src/build/base.ts +2 -0
- package/src/build/browser-runtime-exports.ts +52 -0
- package/src/build/check-fragment.ts +45 -0
- package/src/build/cjs-export-names.mjs +24 -0
- package/src/build/commonjs-exports.ts +24 -0
- package/src/build/convert-commonjs.ts +183 -0
- package/src/build/dependencies.ts +6 -0
- package/src/build/dependency-barrel-index.ts +48 -0
- package/src/build/dependency-barrels.ts +80 -0
- package/src/build/dependency-cache.ts +40 -0
- package/src/build/dependency-optional.ts +15 -0
- package/src/build/dependency-plugin.ts +58 -0
- package/src/build/dependency-runtime.ts +182 -0
- package/src/build/dependency-workers.ts +41 -0
- package/src/build/errors.ts +9 -0
- package/src/build/fragment.ts +89 -0
- package/src/build/index.ts +7 -0
- package/src/build/library-runtime.ts +101 -0
- package/src/build/module-utils.ts +11 -0
- package/src/build/recipe-dependencies.ts +14 -0
- package/src/build/runtime-entries.ts +10 -0
- package/src/build/runtime-layer.ts +99 -0
- package/src/build/trace.ts +431 -0
- package/src/design-schema.ts +25 -0
- package/src/dev/README.md +78 -0
- package/src/dev/catalog.ts +79 -0
- package/src/dev/cli.ts +25 -0
- package/src/dev/index.ts +118 -0
- package/src/dev/runtime-origin.ts +63 -0
- package/src/editing.ts +25 -0
- package/src/form/entry-source.ts +68 -0
- package/src/form/form-page.ts +63 -0
- package/src/form/index.ts +2 -0
- package/src/form/source-update.ts +17 -0
- package/src/frame/activity.browser.ts +34 -0
- package/src/frame/activity.ts +52 -0
- package/src/frame/agent/README.md +47 -0
- package/src/frame/agent/agent.browser.ts +127 -0
- package/src/frame/agent/design.ts +62 -0
- package/src/frame/agent/frame-layout.ts +54 -0
- package/src/frame/agent/index.ts +151 -0
- package/src/frame/agent/overlay.ts +104 -0
- package/src/frame/agent/owner.ts +61 -0
- package/src/frame/agent/provider.tsx +14 -0
- package/src/frame/agent/react-override.ts +55 -0
- package/src/frame/agent/review.browser.ts +65 -0
- package/src/frame/agent/review.ts +108 -0
- package/src/frame/agent/testing/callsite.tsx +5 -0
- package/src/frame/agent/testing/client.ts +99 -0
- package/src/frame/agent/testing/library.ts +3 -0
- package/src/frame/agent/testing/modal.tsx +5 -0
- package/src/frame/agent/testing/review-client.ts +43 -0
- package/src/frame/agent/testing/review-server.ts +31 -0
- package/src/frame/agent/testing/server.ts +72 -0
- package/src/frame/agent/testing/vocabulary-host.ts +20 -0
- package/src/frame/agent/testing/vocabulary.tsx +10 -0
- package/src/frame/agent/vitest.browser.config.ts +6 -0
- package/src/frame/agent/vocabulary.browser.ts +30 -0
- package/src/frame/agent/vocabulary.ts +13 -0
- package/src/frame/agent.ts +3 -0
- package/src/frame/boot-styles.ts +50 -0
- package/src/frame/boot.ts +269 -0
- package/src/frame/bridge.ts +27 -0
- package/src/frame/devtools-hook.ts +1 -0
- package/src/frame/document-assets.ts +76 -0
- package/src/frame/document-entry.ts +68 -0
- package/src/frame/document-modules.ts +113 -0
- package/src/frame/document-mount.ts +32 -0
- package/src/frame/entry.ts +4 -0
- package/src/frame/export-compiler.ts +18 -0
- package/src/frame/export-page.ts +61 -0
- package/src/frame/export.ts +89 -0
- package/src/frame/index.ts +8 -0
- package/src/frame/local-runtime.browser.ts +36 -0
- package/src/frame/mount-page.ts +36 -0
- package/src/frame/page-agent.ts +2 -0
- package/src/frame/readiness.ts +51 -0
- package/src/frame/render-job.ts +101 -0
- package/src/frame/review-integration.browser.ts +48 -0
- package/src/frame/runtime.browser.ts +90 -0
- package/src/frame/tailwind/README.md +49 -0
- package/src/frame/tailwind/boot-styles.browser.ts +18 -0
- package/src/frame/tailwind/cache.ts +20 -0
- package/src/frame/tailwind/load.ts +75 -0
- package/src/frame/tailwind/recipe.ts +76 -0
- package/src/frame/tailwind/runtime.ts +113 -0
- package/src/frame/tailwind/store.ts +55 -0
- package/src/frame/tailwind/stylesheets.ts +42 -0
- package/src/frame/tailwind/tailwind.browser.ts +71 -0
- package/src/frame/tailwind/testing/client.ts +133 -0
- package/src/frame/tailwind/testing/compare.ts +91 -0
- package/src/frame/tailwind/testing/pages.ts +14 -0
- package/src/frame/tailwind/testing/server.ts +89 -0
- package/src/frame/tailwind/vitest.browser.config.ts +7 -0
- package/src/frame/testing/boot-layout.ts +3 -0
- package/src/frame/testing/boot-page.ts +3 -0
- package/src/frame/testing/host.ts +78 -0
- package/src/frame/testing/local-host.tsx +33 -0
- package/src/frame/testing/server.ts +135 -0
- package/src/host/BuildLog.tsx +28 -0
- package/src/host/DEBUG_CONSOLE.md +13 -0
- package/src/host/PageForm.tsx +63 -0
- package/src/host/PageFrame.tsx +49 -0
- package/src/host/RuntimeActivity.tsx +77 -0
- package/src/host/RuntimeDebugPanel.tsx +18 -0
- package/src/host/activity-state.ts +69 -0
- package/src/host/agent-source.ts +14 -0
- package/src/host/agent-validation.ts +73 -0
- package/src/host/bridge.ts +56 -0
- package/src/host/build-log.ts +29 -0
- package/src/host/clear-cache.ts +66 -0
- package/src/host/debug-runtime.tsx +17 -0
- package/src/host/design-validation.ts +96 -0
- package/src/host/index.ts +12 -0
- package/src/host/link/index.ts +66 -0
- package/src/host/link/transport.ts +68 -0
- package/src/host/link/watch.ts +62 -0
- package/src/host/message-values.ts +55 -0
- package/src/host/origin.ts +7 -0
- package/src/host/review/README.md +32 -0
- package/src/host/review/index.ts +43 -0
- package/src/host/review/validation.ts +55 -0
- package/src/host/runtime-diagnostics.ts +41 -0
- package/src/host/validation.ts +148 -0
- package/src/link/README.md +115 -0
- package/src/link/barrels.ts +5 -0
- package/src/link/build-cli.ts +12 -0
- package/src/link/build.ts +99 -0
- package/src/link/commonjs.ts +39 -0
- package/src/link/examples/server.ts +18 -0
- package/src/link/index.ts +6 -0
- package/src/link/link.browser.ts +66 -0
- package/src/link/local-relay.browser.ts +22 -0
- package/src/link/overrides.ts +69 -0
- package/src/link/page-sources.ts +69 -0
- package/src/link/source.ts +25 -0
- package/src/link/storage.ts +32 -0
- package/src/link/testing/client.ts +96 -0
- package/src/link/testing/folder.ts +19 -0
- package/src/link/testing/local-client.ts +30 -0
- package/src/link/testing/local-server.ts +26 -0
- package/src/link/testing/local-worker.ts +17 -0
- package/src/link/testing/server.ts +131 -0
- package/src/link/testing/worker.ts +32 -0
- package/src/link/testing-cache.ts +20 -0
- package/src/link/testing-fixtures.ts +16 -0
- package/src/link/types.ts +27 -0
- package/src/link/validation.ts +44 -0
- package/src/link/vitest.browser.config.ts +3 -0
- package/src/markers.ts +18 -0
- package/src/publication/build.ts +27 -0
- package/src/publication/fixtures/build.mjs +2 -0
- package/src/publication/index.ts +3 -0
- package/src/publication/lock.ts +32 -0
- package/src/publication/manifest.ts +14 -0
- package/src/publication/publish.ts +80 -0
- package/src/publication/runtime.ts +28 -0
- package/src/publication/schema.ts +13 -0
- package/src/review-schema.ts +17 -0
- package/src/schema.ts +175 -0
- package/src/storage/db.ts +64 -0
- package/src/styles.ts +40 -0
- package/src/sw/activity.ts +66 -0
- package/src/sw/barrels.ts +44 -0
- package/src/sw/candidates.ts +14 -0
- package/src/sw/compile.ts +92 -0
- package/src/sw/compiler-columns.ts +44 -0
- package/src/sw/compiler-internals.d.ts +8 -0
- package/src/sw/compiler-plugins.ts +18 -0
- package/src/sw/compiler.ts +93 -0
- package/src/sw/composition.ts +86 -0
- package/src/sw/content-types.ts +28 -0
- package/src/sw/converted.browser.ts +31 -0
- package/src/sw/converted.ts +64 -0
- package/src/sw/editable-sites.ts +42 -0
- package/src/sw/errors.ts +30 -0
- package/src/sw/esm-sh-fixtures/browser-client.ts +18 -0
- package/src/sw/esm-sh-fixtures/browser-server.ts +104 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.headers +13 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.mjs.txt +142 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.mjs.txt +222 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.headers +14 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.mjs.txt +76 -0
- package/src/sw/esm-sh-fixtures/fixtures.ts +54 -0
- package/src/sw/esm-sh-fixtures/redact.ts +1 -0
- package/src/sw/index.ts +7 -0
- package/src/sw/integrity.ts +10 -0
- package/src/sw/legacy-storage.ts +18 -0
- package/src/sw/link-activity.ts +21 -0
- package/src/sw/link-cache.ts +19 -0
- package/src/sw/link-compiler.ts +120 -0
- package/src/sw/link-folder.ts +29 -0
- package/src/sw/link-relay.ts +40 -0
- package/src/sw/link-route.ts +239 -0
- package/src/sw/link-source.ts +41 -0
- package/src/sw/markers.ts +128 -0
- package/src/sw/module-transform.ts +364 -0
- package/src/sw/page-clients.ts +45 -0
- package/src/sw/profile.ts +90 -0
- package/src/sw/resolver.ts +224 -0
- package/src/sw/router.ts +360 -0
- package/src/sw/runtime-exports.ts +39 -0
- package/src/sw/runtime-module.ts +13 -0
- package/src/sw/source-hash.ts +37 -0
- package/src/sw/source-provider.ts +20 -0
- package/src/sw/versions.ts +96 -0
- package/src/sw/worker.ts +91 -0
- package/static/README.md +15 -0
- package/static/profile.example.json +15 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Computed-style comparison between two renders of the same page.
|
|
2
|
+
|
|
3
|
+
export type Snapshot = { selectors: string[]; styles: string[][] };
|
|
4
|
+
export type Difference = { element: string; property: string; runtime: string; reference: string; count: number };
|
|
5
|
+
export type Comparison = { elements: number; differingElements: number; customPropertyDiffs: number; reorderedTransitions: number; differences: Difference[] };
|
|
6
|
+
|
|
7
|
+
/** Splits a computed list value at its top-level commas (`cubic-bezier(…, …)` stays one entry). */
|
|
8
|
+
export function listEntries(value: string): string[] {
|
|
9
|
+
const entries: string[] = [];
|
|
10
|
+
let depth = 0;
|
|
11
|
+
let current = "";
|
|
12
|
+
for (const character of value) {
|
|
13
|
+
if (character === "(") depth += 1;
|
|
14
|
+
if (character === ")") depth -= 1;
|
|
15
|
+
if (character === "," && depth === 0) {
|
|
16
|
+
entries.push(current.trim());
|
|
17
|
+
current = "";
|
|
18
|
+
} else current += character;
|
|
19
|
+
}
|
|
20
|
+
entries.push(current.trim());
|
|
21
|
+
return entries;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const TRANSITION_LISTS = ["transition-duration", "transition-timing-function", "transition-delay", "transition-behavior"];
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Each transitioned property with the duration, timing function, delay and behavior it gets: a shorter list repeats
|
|
28
|
+
* to the length of `transition-property`, as CSS Transitions specifies.
|
|
29
|
+
*/
|
|
30
|
+
function transitions(style: Map<string, string>): string[] {
|
|
31
|
+
const lists = TRANSITION_LISTS.map((property) => listEntries(style.get(property) ?? ""));
|
|
32
|
+
return listEntries(style.get("transition-property") ?? "")
|
|
33
|
+
.map((property, index) => [property, ...lists.map((list) => list[index % list.length])].join(" "))
|
|
34
|
+
.sort();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Two transition declarations are equivalent when they give every property the same transition, whatever the order.
|
|
39
|
+
* Lightning CSS emits prefixed declarations ahead of the standard one, so the reference lists
|
|
40
|
+
* `-webkit-text-decoration` before `text-decoration`.
|
|
41
|
+
*/
|
|
42
|
+
export function equivalentTransition(ours: Map<string, string>, theirs: Map<string, string>): boolean {
|
|
43
|
+
return transitions(ours).join(",") === transitions(theirs).join(",");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function styleMap(values: string[]): Map<string, string> {
|
|
47
|
+
return new Map(values.map((entry) => [entry.slice(0, entry.indexOf(":")), entry.slice(entry.indexOf(":") + 1)]));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Compares two snapshots of the same page element by element. Custom properties compute to their token text, so a
|
|
52
|
+
* minifier's respelling (`rgb(59 130 246 / 0.5)` as `#3b82f680`) differs there without changing any rendered style;
|
|
53
|
+
* they are counted apart, and their effect is compared through the standard properties that read them.
|
|
54
|
+
*/
|
|
55
|
+
export function compare(runtime: Snapshot, reference: Snapshot): Comparison {
|
|
56
|
+
if (runtime.selectors.join("\n") !== reference.selectors.join("\n")) {
|
|
57
|
+
throw new Error(`the two renders differ in their elements (${runtime.selectors.length} and ${reference.selectors.length})`);
|
|
58
|
+
}
|
|
59
|
+
// Grouped by element selector, property and both values, so repeated rows report one entry with a count.
|
|
60
|
+
const differences = new Map<string, Difference>();
|
|
61
|
+
let differingElements = 0;
|
|
62
|
+
let customPropertyDiffs = 0;
|
|
63
|
+
let reorderedTransitions = 0;
|
|
64
|
+
runtime.styles.forEach((values, index) => {
|
|
65
|
+
const ours = styleMap(values);
|
|
66
|
+
const theirs = styleMap(reference.styles[index] ?? []);
|
|
67
|
+
const element = runtime.selectors[index] ?? "";
|
|
68
|
+
let differs = false;
|
|
69
|
+
for (const property of new Set([...ours.keys(), ...theirs.keys()])) {
|
|
70
|
+
const value = ours.get(property) ?? "";
|
|
71
|
+
const other = theirs.get(property) ?? "";
|
|
72
|
+
if (value === other) continue;
|
|
73
|
+
if (property.startsWith("--")) {
|
|
74
|
+
customPropertyDiffs += 1;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (property === "transition-property" && equivalentTransition(ours, theirs)) {
|
|
78
|
+
reorderedTransitions += 1;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
differs = true;
|
|
82
|
+
const key = [element, property, value, other].join("\u0000");
|
|
83
|
+
const entry = differences.get(key);
|
|
84
|
+
if (entry) entry.count += 1;
|
|
85
|
+
else differences.set(key, { element, property, runtime: value, reference: other, count: 1 });
|
|
86
|
+
}
|
|
87
|
+
if (differs) differingElements += 1;
|
|
88
|
+
});
|
|
89
|
+
const sorted = [...differences.values()].sort((a, b) => b.count - a.count).slice(0, 200);
|
|
90
|
+
return { elements: runtime.styles.length, differingElements, customPropertyDiffs, reorderedTransitions, differences: sorted };
|
|
91
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const parityPages = [
|
|
2
|
+
"BadgeExamples", "BleedTest", "CompactTableExample", "DataFlowDiagram", "FindingsReport",
|
|
3
|
+
"HeaderDefault", "HeaderMinimal", "HeaderNone", "HeaderSolid", "ListTableExample", "LogoGridTableExample",
|
|
4
|
+
"MetricExamples", "PageSizeTest", "SecurityChecksTableExample", "SpecificationTableExample", "StatCardExamples",
|
|
5
|
+
"TableExamples", "TypographyTest", "OfficeContents", "LiveDiagram", "OfficeReport",
|
|
6
|
+
];
|
|
7
|
+
|
|
8
|
+
export function pageFile(name: string): string {
|
|
9
|
+
if (name === "OfficeContents") return "office/Contents.tsx";
|
|
10
|
+
if (name === "LiveDiagram") return "office/LiveDiagram.tsx";
|
|
11
|
+
if (name === "OfficeReport") return "office/Report.tsx";
|
|
12
|
+
if (!parityPages.includes(name)) throw new Error(`unknown Tailwind parity page ${name}`);
|
|
13
|
+
return `kitchen-sink/${name}.tsx`;
|
|
14
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { readFile, readdir, mkdir } from "node:fs/promises";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { build } from "rolldown";
|
|
7
|
+
import { compile, optimize } from "@tailwindcss/node";
|
|
8
|
+
import { Scanner } from "@tailwindcss/oxide";
|
|
9
|
+
import autoprefixer from "autoprefixer";
|
|
10
|
+
import postcss from "postcss";
|
|
11
|
+
import { layerOrder, type PageStylesRecipe } from "../recipe.ts";
|
|
12
|
+
import { parityPages, pageFile } from "./pages.ts";
|
|
13
|
+
|
|
14
|
+
const pkg = fileURLToPath(new URL("../../../..", import.meta.url));
|
|
15
|
+
const facetRoot = resolve(pkg, "../../../facet");
|
|
16
|
+
const repo = resolve(pkg, "../..");
|
|
17
|
+
const require = createRequire(import.meta.url);
|
|
18
|
+
const facetRequire = createRequire(resolve(facetRoot, "package.json"));
|
|
19
|
+
|
|
20
|
+
async function fixtures() {
|
|
21
|
+
const recipePath = resolve(facetRoot, "dist/page-styles/index.mjs");
|
|
22
|
+
const { default: facet } = facetRequire("./dist/page-styles/index.mjs") as { default: PageStylesRecipe };
|
|
23
|
+
const sources: string[] = [];
|
|
24
|
+
for (const dir of ["kitchen-sink", "office"]) {
|
|
25
|
+
for (const name of await readdir(resolve(facetRoot, "examples", dir))) if (/\.(tsx?|json)$/.test(name)) sources.push(await readFile(resolve(facetRoot, "examples", dir, name), "utf8"));
|
|
26
|
+
}
|
|
27
|
+
const stylesheets = Object.fromEntries(await Promise.all(["theme.css", "utilities.css"].map(async (file) => [`tailwindcss/${file}`, await readFile(require.resolve(`tailwindcss/${file}`), "utf8")])));
|
|
28
|
+
const baseSheets = new Map([
|
|
29
|
+
["/base/clicky.css", await readFile(resolve(repo, "packages/ui/dist/styles.css"), "utf8")],
|
|
30
|
+
["/base/facet.css", await readFile(resolve(facetRoot, "dist/styles.css"), "utf8")],
|
|
31
|
+
]);
|
|
32
|
+
return { recipePath, facet, sources, stylesheets, baseSheets };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function bundle(data: Awaited<ReturnType<typeof fixtures>>) {
|
|
36
|
+
const pages = parityPages.map((name) => `${JSON.stringify(name)}: () => import(${JSON.stringify(resolve(facetRoot, "examples", pageFile(name)))})`).join(",");
|
|
37
|
+
const source = [
|
|
38
|
+
`import { run } from ${JSON.stringify(resolve(pkg, "src/frame/tailwind/testing/client.ts"))};`,
|
|
39
|
+
`import facet from ${JSON.stringify(data.recipePath)};`,
|
|
40
|
+
`import clicky from ${JSON.stringify(resolve(repo, "packages/ui/src/page-styles.ts"))};`,
|
|
41
|
+
`import preset from ${JSON.stringify(resolve(repo, "packages/ui/src/tailwind-preset.ts"))};`,
|
|
42
|
+
`import facetPreset from ${JSON.stringify(resolve(facetRoot, "dist/page-styles/preset.mjs"))};`,
|
|
43
|
+
`import typography from ${JSON.stringify(facetRequire.resolve("@tailwindcss/typography"))};`,
|
|
44
|
+
`import officeData from ${JSON.stringify(resolve(facetRoot, "examples/office/data.json"))};`,
|
|
45
|
+
`const sheets = ${JSON.stringify(data.stylesheets)};`,
|
|
46
|
+
`const loaders = { loadStylesheet: async (id, base) => { if (!(id in sheets)) throw new Error('missing stylesheet '+id); return {path:id,base,content:sheets[id]}; }, loadModule: async (id,base) => { const modules = {'@tailwindcss/typography': typography, '@flanksource/clicky-ui/tailwind-preset':preset, '@flanksource/facet/tailwind-preset':facetPreset}; if (!(id in modules)) throw new Error('missing module '+id); return {path:id,base,module:modules[id]}; } };`,
|
|
47
|
+
`const options = {libraries:[{id:'clicky',name:clicky.name,version:'parity',integrity:'sha384-parity-clicky',base:location.origin+'/clicky/',recipe:clicky},{id:'facet',name:facet.name,version:'parity',integrity:'sha384-parity-facet',base:location.origin+'/facet/',recipe:facet}],base:${JSON.stringify([...data.baseSheets.keys()])}.map((url,index)=>({url,layer:[clicky.layer,facet.layer][index]})),loaders,candidates:${JSON.stringify([...new Set(data.sources.flatMap((text) => text.match(/[^<>"'`\s]*[^<>"'`\s:]/g) ?? []))])},pages:{${pages}},data:officeData};`,
|
|
48
|
+
`run(options).then(value => {document.getElementById('result').textContent=JSON.stringify(value);document.title='DONE';},error => {document.getElementById('result').textContent=JSON.stringify({error:String(error),stack:error.stack});document.title='DONE';});`,
|
|
49
|
+
].join("\n");
|
|
50
|
+
const output = await build({ input: "tailwind:fixture", platform: "browser", resolve: { alias: { "@flanksource/clicky-ui/tailwind-preset": resolve(repo, "packages/ui/src/tailwind-preset.ts"), "@facet":resolve(facetRoot, "dist/components/index.js"), "@flanksource/facet": resolve(facetRoot, "dist/components/index.js"), react: require.resolve("react"), "react-dom/client": require.resolve("react-dom/client") } }, transform: { jsx: { runtime: "automatic" }, define: { "process.env.NODE_ENV": '"development"', "process.env": "{}" } }, plugins: [{ name: "fixture", resolveId: (id) => id === "tailwind:fixture" ? id : null, load: (id) => id === "tailwind:fixture" ? source : null }], output: { format: "es", dir: resolve(repo, ".tmp/E/browser"), entryFileNames: "entry.js", chunkFileNames: "[name]-[hash].js" }, write: false });
|
|
51
|
+
return new Map(output.output.map((file) => [file.fileName, file.type === "chunk" ? file.code : file.source]));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function reference(data: Awaited<ReturnType<typeof fixtures>>) {
|
|
55
|
+
const dir = resolve(repo, ".tmp/E/reference"); await mkdir(dir, { recursive: true });
|
|
56
|
+
const entry = [layerOrder, data.facet.entry].join("\n");
|
|
57
|
+
const compiler = await compile(entry, { base: dir, onDependency: () => {}, customCssResolver: async (id) => require.resolve(id), customJsResolver: async (id) => id === "@flanksource/facet/tailwind-preset" ? resolve(facetRoot, "dist/page-styles/preset.mjs") : id === "@flanksource/clicky-ui/tailwind-preset" ? resolve(repo, "packages/ui/dist/tailwind-preset.js") : facetRequire.resolve(id) });
|
|
58
|
+
return (html: string) => {
|
|
59
|
+
const candidates = new Scanner({}).scanFiles([...data.sources.map((content) => ({ content, extension: "tsx" })), { content: html, extension: "html" }]);
|
|
60
|
+
const css = postcss([autoprefixer()]).process(optimize(compiler.build(candidates)).code, { from: undefined }).css;
|
|
61
|
+
return data.facet.transform!(css);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function startTailwindServer() {
|
|
66
|
+
const data = await fixtures();
|
|
67
|
+
const files = await bundle(data);
|
|
68
|
+
const buildReference = await reference(data);
|
|
69
|
+
const references = new Map<string, string>();
|
|
70
|
+
const server = createServer((req, res) => { void (async () => {
|
|
71
|
+
const url = new URL(req.url!, "http://localhost");
|
|
72
|
+
if (url.pathname.startsWith("/reference/")) {
|
|
73
|
+
const name = url.pathname.slice(11);
|
|
74
|
+
if (req.method === "POST") { const chunks = []; for await (const chunk of req) chunks.push(chunk); references.set(name, buildReference(Buffer.concat(chunks).toString())); }
|
|
75
|
+
if (!references.has(name)) throw new Error(`reference missing for ${name}`);
|
|
76
|
+
res.setHeader("content-type", "text/css"); res.end(references.get(name)); return;
|
|
77
|
+
}
|
|
78
|
+
const base = data.baseSheets.get(url.pathname);
|
|
79
|
+
if (base !== undefined) { res.setHeader("content-type", "text/css"); res.end(base); return; }
|
|
80
|
+
if (url.pathname === "/delayed.css") { await new Promise((resolve) => setTimeout(resolve, 200)); res.setHeader("content-type", "text/css"); res.end("body { --imported: yes; }"); return; }
|
|
81
|
+
if (url.pathname === "/missing.css") { res.statusCode = 404; res.end("missing"); return; }
|
|
82
|
+
const file = files.get(url.pathname.slice(1));
|
|
83
|
+
if (file !== undefined) { res.setHeader("content-type", "text/javascript"); res.end(file); return; }
|
|
84
|
+
res.setHeader("content-type", "text/html"); res.end('<!doctype html><html><head><title>RUNNING</title></head><body><div id="root"></div><output id="result" hidden></output><script type="module" src="/entry.js"></script></body></html>');
|
|
85
|
+
})().catch((error: unknown) => { res.statusCode = 500; res.end(String(error)); }); });
|
|
86
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
87
|
+
const address = server.address(); if (!address || typeof address === "string") throw new Error("no test server port");
|
|
88
|
+
return { url: `http://127.0.0.1:${address.port}`, close: () => new Promise<void>((resolve, reject) => { server.closeAllConnections(); server.close((error) => error ? reject(error) : resolve()); }) };
|
|
89
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { defineConfig } from "vitest/config";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
|
|
4
|
+
export default defineConfig({ cacheDir: fileURLToPath(new URL("../../../../../.tmp/E/vite", import.meta.url)), test: {
|
|
5
|
+
environment: "node", include: ["src/frame/tailwind/*.browser.ts"],
|
|
6
|
+
testTimeout: 120_000, hookTimeout: 120_000, fileParallelism: false,
|
|
7
|
+
} });
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createBridge } from "../../host/bridge.ts";
|
|
2
|
+
import type { FrameMessage, HostMessage, RuntimeError } from "../../schema.ts";
|
|
3
|
+
import { createRemoteReview } from "../../host/review/index.ts";
|
|
4
|
+
|
|
5
|
+
type CaseConfig = { origin: string; open: Extract<HostMessage, { type: "open" }>; name: string };
|
|
6
|
+
const config = await (await fetch(`/case.json${location.search}`)).json() as CaseConfig;
|
|
7
|
+
const frame = document.createElement("iframe"); frame.sandbox.add("allow-scripts", "allow-same-origin", "allow-modals"); document.body.append(frame);
|
|
8
|
+
const states: string[] = [];
|
|
9
|
+
const errors: RuntimeError[] = [];
|
|
10
|
+
const started = performance.now();
|
|
11
|
+
const result = document.createElement("pre"); result.id = "result"; document.body.append(result);
|
|
12
|
+
const session = crypto.randomUUID();
|
|
13
|
+
const agentEvents: FrameMessage[] = [];
|
|
14
|
+
const activityEvents: FrameMessage[] = [];
|
|
15
|
+
const activityOutput = document.createElement("pre"); activityOutput.id = "activity"; activityOutput.hidden = true; document.body.append(activityOutput);
|
|
16
|
+
const reload = document.createElement("button"); reload.id = "reload"; reload.textContent = "Reload page"; reload.onclick = () => bridge.send({ type: "reload" }); document.body.append(reload);
|
|
17
|
+
let opened = false;
|
|
18
|
+
let updating = false;
|
|
19
|
+
const bridge = createBridge({ target: frame.contentWindow!, origin: config.origin, session, direction: "host", onMessage: (envelope) => { void receive(envelope.message as FrameMessage); }, onError: (error) => { result.textContent = JSON.stringify({ failure: error.message }); document.title = "CASE-DONE"; } });
|
|
20
|
+
const review = createRemoteReview({ send: (message) => bridge.send(message), onState: () => undefined, onAction: () => undefined });
|
|
21
|
+
async function receive(message: FrameMessage) {
|
|
22
|
+
if (message.type.startsWith("review-")) review.receive(message);
|
|
23
|
+
if (message.type === "activity") { activityEvents.push(message); activityOutput.textContent = JSON.stringify(activityEvents); }
|
|
24
|
+
agentEvents.push(message);
|
|
25
|
+
const events = document.getElementById("events");
|
|
26
|
+
if (events) events.textContent = JSON.stringify(agentEvents);
|
|
27
|
+
if (message.type === "status") {
|
|
28
|
+
states.push(message.state);
|
|
29
|
+
if (message.state === "connecting" || (message.state === "booting" && !opened)) { opened = true; bridge.send(config.open); return; }
|
|
30
|
+
if (message.state === "booting") { bridge.send({ type: "theme", theme: "dark", density: "compact" }); bridge.send({ type: "data", data: "Report" }); }
|
|
31
|
+
if (message.state === "ready") {
|
|
32
|
+
if (config.name === "updates") {
|
|
33
|
+
if (updating) return;
|
|
34
|
+
updating = true;
|
|
35
|
+
try {
|
|
36
|
+
const snapshot = async () => (await bridge.request({ type: "export", format: "html" })).message;
|
|
37
|
+
const before = await snapshot();
|
|
38
|
+
await bridge.request({ type: "data", data: "Data update" });
|
|
39
|
+
const data = await snapshot();
|
|
40
|
+
await bridge.request({ type: "sources", files: { "custom.css": 'main { outline-color: rgb(12, 34, 56); }' } });
|
|
41
|
+
const css = await snapshot();
|
|
42
|
+
await bridge.request({ type: "sources", files: { "helper.ts": 'export const text = "Updated helper";' }, data: "Source data" });
|
|
43
|
+
const helper = await snapshot();
|
|
44
|
+
await bridge.request({ type: "sources", files: { "report.tsx": config.open.files["report.tsx"]!.replace("{text}:{data}", "{text}:{data}:Edited page") } });
|
|
45
|
+
result.textContent = JSON.stringify({ states, errors, before, data, css, helper, snapshot: await snapshot() });
|
|
46
|
+
} catch (error) { result.textContent = JSON.stringify({ states, errors, failure: String(error) }); }
|
|
47
|
+
document.title = "CASE-DONE"; return;
|
|
48
|
+
}
|
|
49
|
+
// A rejected export is the case result; otherwise the host would wait for CASE-DONE until the test times out.
|
|
50
|
+
try {
|
|
51
|
+
const snapshot = await bridge.request({ type: "export", format: "html" });
|
|
52
|
+
result.textContent = JSON.stringify({ states, errors, elapsed: performance.now() - started, snapshot: snapshot.message });
|
|
53
|
+
} catch (error) { result.textContent = JSON.stringify({ states, errors, failure: String(error) }); }
|
|
54
|
+
document.title = "CASE-DONE";
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (message.type === "error") {
|
|
58
|
+
errors.push(message.error); result.textContent = JSON.stringify({ states, errors }); document.title = "CASE-DONE";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (config.name === "agent" || config.name === "review") {
|
|
62
|
+
const button = document.createElement("button"); button.id = "pick"; button.textContent = "Pick";
|
|
63
|
+
button.onclick = () => bridge.send({ type: "pick" }); document.body.append(button);
|
|
64
|
+
const events = document.createElement("pre"); events.id = "events"; document.body.append(events);
|
|
65
|
+
}
|
|
66
|
+
if (config.name === "review") {
|
|
67
|
+
for (const [id, action] of Object.entries({
|
|
68
|
+
"review-show": () => review.setVisibility({ visible: true, showRejected: false }),
|
|
69
|
+
"review-list": () => review.list(),
|
|
70
|
+
"review-select": () => review.select("summary"),
|
|
71
|
+
"review-export": () => review.action({ id: "summary", action: "export" }),
|
|
72
|
+
})) {
|
|
73
|
+
const button = document.createElement("button"); button.id = id; button.textContent = id;
|
|
74
|
+
button.onclick = () => { void action().catch((error: unknown) => { result.textContent = JSON.stringify({ failure: String(error) }); }); };
|
|
75
|
+
document.body.append(button);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
frame.src = `${config.origin}/frame/${config.open.page}?case=${encodeURIComponent(config.name)}#${new URLSearchParams({ host: location.origin, session })}`;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createElement } from "react";
|
|
2
|
+
import { createRoot } from "react-dom/client";
|
|
3
|
+
import { PageFrame } from "../../host/PageFrame.tsx";
|
|
4
|
+
import type { PageBridge } from "../../host/bridge.ts";
|
|
5
|
+
import type { FrameMessage, HostMessage } from "../../schema.ts";
|
|
6
|
+
|
|
7
|
+
const config = await (await fetch("/case.json?case=ready")).json() as { origin: string; open: Extract<HostMessage, { type: "open" }> };
|
|
8
|
+
const events: FrameMessage[] = [];
|
|
9
|
+
let bridge: PageBridge | null = null;
|
|
10
|
+
let source = "";
|
|
11
|
+
document.body.innerHTML = '<div id="frame"></div><button id="design">Design</button><button id="preview">Preview</button><button id="write">Write</button><button id="inspect">Inspect</button><pre id="events"></pre><pre id="inspection"></pre><pre id="error"></pre>';
|
|
12
|
+
function send(message: FrameMessage) {
|
|
13
|
+
events.push(message);
|
|
14
|
+
document.getElementById("events")!.textContent = JSON.stringify(events);
|
|
15
|
+
if (message.type === "status" && message.state === "ready") document.title = "LOCAL-READY";
|
|
16
|
+
if (message.type === "error") document.getElementById("error")!.textContent = JSON.stringify(message.error);
|
|
17
|
+
if (message.type === "design-selection") source = message.source;
|
|
18
|
+
if (message.type === "design-write-request") {
|
|
19
|
+
document.body.dataset.write = JSON.stringify(message.request);
|
|
20
|
+
bridge!.send({ type: "design-write-result", requestId: message.requestId, result: { status: "applied", file: "report.tsx", path: "/pages/report.tsx", line: 1, hash: "012345abcdef" } });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
createRoot(document.getElementById("frame")!).render(createElement(PageFrame, { id: "runtime-frame", runtimeOrigin: location.origin, origin: "same-origin-local", open: config.open, theme: { theme: "light", density: "compact" }, data: null, style: { width: "100%", height: 300 }, onMessage: send, onBridge(value) { bridge = value; }, onError(error) { document.getElementById("error")!.textContent = error.message; } }));
|
|
24
|
+
document.getElementById("design")!.onclick = () => bridge!.send({ type: "mode", mode: "design" });
|
|
25
|
+
document.getElementById("preview")!.onclick = () => bridge!.send({ type: "design-override", requestId: "preview", source, props: { fill: "blue", width: 180 } });
|
|
26
|
+
document.getElementById("write")!.onclick = () => bridge!.send({ type: "design-write", requestId: "write", page: "report", source, edit: { kind: "attributes", values: { fill: "blue", width: 180 } } });
|
|
27
|
+
document.getElementById("inspect")!.onclick = () => { void (async () => {
|
|
28
|
+
const frame = document.querySelector("iframe")!;
|
|
29
|
+
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
30
|
+
const element = frame.contentDocument!.getElementById("target")!;
|
|
31
|
+
const target = element.getBoundingClientRect(); const outer = frame.getBoundingClientRect();
|
|
32
|
+
document.getElementById("inspection")!.textContent = JSON.stringify({ hostControlled: navigator.serviceWorker.controller !== null, scopes: registrations.map((r) => new URL(r.scope).pathname), probe: await (await fetch("/__playground/probe")).text(), hostSource: await (await fetch("/src/host-module.js")).text(), frameControlled: frame.contentWindow!.navigator.serviceWorker.controller !== null, fill: element.getAttribute("fill"), width: element.getAttribute("width"), write: document.body.dataset.write ? JSON.parse(document.body.dataset.write) as unknown : null, target: { x: outer.left + frame.clientLeft + target.left + target.width / 2, y: outer.top + frame.clientTop + target.top + target.height / 2 } });
|
|
33
|
+
})().catch((error: unknown) => { document.getElementById("error")!.textContent = String(error); }); };
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createServer, type Server, type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { readFile, mkdir } from "node:fs/promises";
|
|
4
|
+
import { resolve, dirname } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { build } from "rolldown";
|
|
7
|
+
import type { HostMessage, PageLock, RuntimeProfile } from "../../schema.ts";
|
|
8
|
+
import { digest } from "../../sw/router.ts";
|
|
9
|
+
import { buildStatic } from "../../../scripts/build-static.ts";
|
|
10
|
+
|
|
11
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
const runtime = "@acme/runtime@1.0.0/";
|
|
14
|
+
const REACT_NAMES = ["Children", "Component", "Fragment", "PureComponent", "StrictMode", "Suspense", "cloneElement", "createContext", "createElement", "createRef", "forwardRef", "isValidElement", "lazy", "memo", "startTransition", "useCallback", "useContext", "useDebugValue", "useDeferredValue", "useEffect", "useId", "useImperativeHandle", "useInsertionEffect", "useLayoutEffect", "useMemo", "useReducer", "useRef", "useState", "useSyncExternalStore", "useTransition", "version", "__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"];
|
|
15
|
+
|
|
16
|
+
async function runtimeFiles(): Promise<Map<string, string>> {
|
|
17
|
+
const bundles = await build({
|
|
18
|
+
input: { react: "runtime:react", "react-dom": "runtime:react-dom", "react-dom-client": "runtime:react-dom/client", "jsx-runtime": "runtime:react/jsx-runtime", "jsx-dev-runtime": "runtime:react/jsx-dev-runtime", comments: resolve(root, "../ui/src/comments.ts") },
|
|
19
|
+
platform: "browser",
|
|
20
|
+
transform: { define: { "process.env.NODE_ENV": JSON.stringify("development") } },
|
|
21
|
+
plugins: [{ name: "test-runtime-set", resolveId(source, importer, options) {
|
|
22
|
+
if (source.startsWith("runtime:") || source === "external:react") return source;
|
|
23
|
+
if (source === "react" && importer !== "runtime:react") return options.kind === "require-call" ? "external:react" : { id: "react", external: true };
|
|
24
|
+
return null;
|
|
25
|
+
}, load(id) {
|
|
26
|
+
if (id === "external:react") return 'import * as React from "react"; export * from "react"; export default React.default;';
|
|
27
|
+
if (id.startsWith("runtime:")) {
|
|
28
|
+
const specifier = id.slice(8);
|
|
29
|
+
const path = require.resolve(specifier);
|
|
30
|
+
const names = specifier === "react" ? REACT_NAMES : specifier === "react-dom/client" ? ["createRoot", "hydrateRoot"] : specifier === "react-dom" ? ["flushSync", "version"] : specifier.endsWith("jsx-dev-runtime") ? ["jsxDEV", "Fragment"] : ["jsx", "jsxs", "Fragment"];
|
|
31
|
+
return `import ns from ${JSON.stringify(path)}; export default ns; ${names.map((name) => `export const ${name} = ns.${name};`).join("\n")}`;
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
} }],
|
|
35
|
+
output: { format: "es", dir: resolve(root, ".tmp/browser-fixture"), entryFileNames: "[name].js", chunkFileNames: "shared-[hash].js" }, write: false,
|
|
36
|
+
});
|
|
37
|
+
return new Map(bundles.output.filter((file) => file.type === "chunk").map((file) => [runtime + file.fileName, file.code]));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const PAGE = `import React, { useLayoutEffect } from "react";
|
|
41
|
+
import { shared as one } from "@acme/library-one";
|
|
42
|
+
import { shared as two } from "@acme/library-two";
|
|
43
|
+
import "./page.css";
|
|
44
|
+
export const ready = () => new Promise(resolve => setTimeout(resolve, 250));
|
|
45
|
+
export default function Page({data}: {data: string}) {
|
|
46
|
+
useLayoutEffect(() => { setTimeout(() => { document.querySelector('[data-facet-diagram]').setAttribute('data-facet-ready','true'); document.querySelector('[data-facet-arrow]').setAttribute('data-facet-arrow-ready','true'); }, 200); }, []);
|
|
47
|
+
return <main data-facet-diagram data-facet-ready="false" data-one-react={React === one && one === two} data-hook={Boolean(window.__REACT_DEVTOOLS_GLOBAL_HOOK__)}><h1>{data}</h1><img src="/image.svg" /><svg data-facet-arrow data-facet-arrow-ready="false" /></main>;
|
|
48
|
+
}`;
|
|
49
|
+
const SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" /></svg>';
|
|
50
|
+
type Case = "ready" | "cascade" | "updates" | "agent" | "review" | "resolve" | "fetch" | "compile" | "link" | "render" | "readiness" | "markdown-export";
|
|
51
|
+
async function listen(server: Server): Promise<string> {
|
|
52
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
53
|
+
const address = server.address(); if (!address || typeof address === "string") throw new Error("server has no port");
|
|
54
|
+
return `http://127.0.0.1:${address.port}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function startRuntimeTestServer(options: { local?: boolean } = {}) {
|
|
58
|
+
const output = resolve(root, ".tmp/B-core/static"); await mkdir(output, { recursive: true });
|
|
59
|
+
await buildStatic({ outDir: output, dev: true, version: `browser-${Date.now()}` });
|
|
60
|
+
const hostBuild = await build({ input: resolve(root, options.local ? "src/frame/testing/local-host.tsx" : "src/frame/testing/host.ts"), transform: { define: { "process.env.NODE_ENV": JSON.stringify("development") } }, output: { format: "es" }, write: false });
|
|
61
|
+
const hostCode = hostBuild.output.find((f) => f.type === "chunk"); if (!hostCode || hostCode.type !== "chunk") throw new Error("host fixture did not bundle");
|
|
62
|
+
const hostScript = hostCode.code;
|
|
63
|
+
const files = await runtimeFiles();
|
|
64
|
+
files.set("@acme/library-one@1.0.0/index.js", 'import React from "react"; export const shared = React; export function StatCard() { return React.createElement("h2", {id:"library-heading",style:{padding:"32px",margin:"32px"}}, "Revenue"); }');
|
|
65
|
+
files.set("@acme/library-two@1.0.0/index.js", 'import React from "react"; export const shared = React;');
|
|
66
|
+
files.set("@acme/library-one@1.0.0/styles.css", '.library-heading { color: red; }');
|
|
67
|
+
files.set("@acme/library-one@1.0.0/page-styles.js", 'export default { name: "@acme/library-one", layer: "components", base: ["@acme/library-one/styles.css"], entry: "", theme: "", runtimeDependencies: [] };');
|
|
68
|
+
// A library export plugin: drops paragraphs starting with `options.prefix`, the way facet-redact removes classified regions.
|
|
69
|
+
files.set("@acme/redact@1.0.0/remark.mjs", "export default function drop(options) { return (tree) => { tree.children = tree.children.filter((node) => !(node.type === \"paragraph\" && node.children?.[0]?.value?.startsWith(options.prefix))); }; }");
|
|
70
|
+
const integrity = Object.fromEntries(await Promise.all([...files].map(async ([path, code]) => [path, await digest(new TextEncoder().encode(code))])));
|
|
71
|
+
const lock: PageLock = { lock: 2, packageOrigin: "http://127.0.0.1", page: "report.tsx", versions: { react: "18.3.1", "@acme/library-one": "1.0.0", "@acme/library-two": "1.0.0" }, map: { imports: { react: `/npm/${runtime}react.js`, "react-dom/client": `/npm/${runtime}react-dom-client.js`, "react/jsx-runtime": `/npm/${runtime}jsx-runtime.js`, "react/jsx-dev-runtime": `/npm/${runtime}jsx-dev-runtime.js`, "@acme/library-one": "/npm/@acme/library-one@1.0.0/index.js", "@acme/library-two": "/npm/@acme/library-two@1.0.0/index.js" }, scopes: {} }, integrity, remaps: {}, barrels: { modules: [], barrels: {} } };
|
|
72
|
+
lock.map.imports["@flanksource/clicky-ui/comments"] = `/npm/${runtime}comments.js`;
|
|
73
|
+
lock.map.imports["react-dom"] = `/npm/${runtime}react-dom.js`;
|
|
74
|
+
lock.map.imports["@acme/library-one/styles.css"] = "/npm/@acme/library-one@1.0.0/styles.css";
|
|
75
|
+
lock.map.imports["@acme/library-one/page-styles"] = "/npm/@acme/library-one@1.0.0/page-styles.js";
|
|
76
|
+
let hostOrigin = ""; let runtimeOrigin = ""; let packageRequests = 0; let registryRequests = 0;
|
|
77
|
+
const server = createServer((req, res) => { void (async () => {
|
|
78
|
+
const url = new URL(req.url!, runtimeOrigin);
|
|
79
|
+
if (options.local && ["/", "/host.js", "/case.json"].includes(url.pathname)) { handleHost(req, res); return; }
|
|
80
|
+
if (url.pathname === "/__playground/probe" || url.pathname.startsWith("/src/host-")) { res.end("host-route"); return; }
|
|
81
|
+
if (url.pathname === "/profile.json") {
|
|
82
|
+
const profile: RuntimeProfile = { runtimeDomain: "127.0.0.1", embedders: [hostOrigin], packageOrigin: `${runtimeOrigin}/packages`, registry: `${runtimeOrigin}/registry`, managed: { "@acme/library-one": "*" }, policy: { dependencies: "strict" }, minReleaseAgeDays: 0, network: { allow: [] }, csp: { add: {} }, links: "deny", sources: ["host"], readinessTimeoutMs: 1500 };
|
|
83
|
+
res.setHeader("content-type", "application/json"); res.end(JSON.stringify(profile)); return;
|
|
84
|
+
}
|
|
85
|
+
if (url.pathname.startsWith("/packages/")) { packageRequests++; const file = files.get(decodeURIComponent(url.pathname.slice(10))); if (file === undefined) { res.statusCode = 404; res.end("missing package"); } else res.end(file); return; }
|
|
86
|
+
if (url.pathname.startsWith("/registry")) { registryRequests++; res.statusCode = 500; res.end("registry must not be used"); return; }
|
|
87
|
+
if (url.pathname === "/image.svg" || url.pathname === "/delayed.css") { await new Promise((resolve) => setTimeout(resolve, 180)); res.setHeader("content-type", url.pathname.endsWith("svg") ? "image/svg+xml" : "text/css"); res.end(url.pathname.endsWith("svg") ? SVG : "h1 { color: rgb(1, 2, 3); }"); return; }
|
|
88
|
+
const file = url.pathname.startsWith("/frame/") ? "bootstrap.html" : url.pathname.slice(1);
|
|
89
|
+
if (!["bootstrap.html", "sw.js", "boot.js", "page-agent.js", "editing.js", "export-compiler.js", "devtools-hook.js"].includes(file)) { res.statusCode = 404; res.end("missing"); return; }
|
|
90
|
+
res.setHeader("content-type", file.endsWith("html") ? "text/html" : "text/javascript"); res.end(await readFile(resolve(output, file)));
|
|
91
|
+
})().catch((error: unknown) => { res.statusCode = 500; res.end(String(error)); }); });
|
|
92
|
+
runtimeOrigin = await listen(server);
|
|
93
|
+
lock.packageOrigin = `${runtimeOrigin}/packages`;
|
|
94
|
+
function handleHost(req: IncomingMessage, res: ServerResponse) {
|
|
95
|
+
const url = new URL(req.url!, hostOrigin);
|
|
96
|
+
if (url.pathname === "/host.js") { res.setHeader("content-type", "text/javascript"); res.end(hostScript); return; }
|
|
97
|
+
if (url.pathname === "/case.json") {
|
|
98
|
+
const name = url.searchParams.get("case") as Case;
|
|
99
|
+
const ownLock = structuredClone(lock);
|
|
100
|
+
let source = PAGE;
|
|
101
|
+
if (name === "agent") source = 'import { StatCard } from "@acme/library-one";\nexport default function Page() {\n return <StatCard />;\n}';
|
|
102
|
+
if (name === "review") source = 'export default function Page() { return <article data-review-id="summary"><h1 data-review-content>Review summary</h1></article>; }';
|
|
103
|
+
if (name === "cascade") source = 'import {useLayoutEffect} from "react"; import "./custom.css"; export default function Page() { useLayoutEffect(() => { const heading = document.getElementById("layer-heading"); heading.setAttribute("data-color", getComputedStyle(heading).color); }, []); return <h3 id="layer-heading" className="library-heading">Custom heading</h3>; }';
|
|
104
|
+
if (options.local) source = 'export default function Page() { return <svg width="240" height="120"><rect id="target" width={160} height={80} fill="red" /></svg>; }';
|
|
105
|
+
if (name === "resolve") ownLock.page = "other.tsx";
|
|
106
|
+
if (name === "fetch") ownLock.integrity["@acme/library-one@1.0.0/index.js"] = "sha384-invalid";
|
|
107
|
+
if (name === "compile") source = "export default function Page() { return <div>";
|
|
108
|
+
if (name === "link") source = 'import x from "forbidden-package"; export default function Page() { return <main>{x}</main>; }';
|
|
109
|
+
if (name === "render") source = 'export default function Page() { throw new Error("render failure"); }';
|
|
110
|
+
if (name === "readiness") source = 'export const ready = new Promise(() => {}); export default function Page() { return <main>waiting</main>; }';
|
|
111
|
+
let open: Extract<HostMessage, { type: "open" }> = { type: "open", page: "report.tsx", lock: ownLock, manifest: { dependencies: {} }, files: { "report.tsx": source, "page.css": '@import url("/delayed.css"); main { display: block; }' } };
|
|
112
|
+
if (name === "cascade") open.files["custom.css"] = 'h3 { color: rgb(91, 33, 182); }';
|
|
113
|
+
if (name === "updates") {
|
|
114
|
+
open.layout = "layout.tsx";
|
|
115
|
+
open.files = {
|
|
116
|
+
"report.tsx": 'import {useState} from "react"; import {text} from "./helper"; window.documentId ??= crypto.randomUUID(); export default function Page({data}) { const [id] = useState(() => crypto.randomUUID()); return <main data-document={window.documentId} data-instance={id}>{text}:{data}</main>; }',
|
|
117
|
+
"helper.ts": 'export const text = "Original";',
|
|
118
|
+
"layout.tsx": 'import {useState} from "react"; import "./custom.css"; export default function Layout({children}) { const [id] = useState(() => crypto.randomUUID()); return <section><header data-layout={id}>Stable header</header>{children}</section>; }',
|
|
119
|
+
"custom.css": 'main { outline-color: red; }',
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (name === "markdown-export") {
|
|
123
|
+
ownLock.page = "report.md";
|
|
124
|
+
ownLock.map.imports["@acme/redact/remark"] = "/npm/@acme/redact@1.0.0/remark.mjs";
|
|
125
|
+
ownLock.compiler = { "@acme/redact": { remark: [{ module: "@acme/redact/remark", options: { prefix: "Internal" } }] } };
|
|
126
|
+
open = { type: "open", page: "report.md", layout: "layout.tsx", lock: ownLock, manifest: { dependencies: {} }, files: { "report.md": "# Report\n\nPublic summary.\n\nInternal margin figures.\n", "layout.tsx": 'export default function Layout({children}) { return <section data-report-layout><header>Report frame</header>{children}</section>; }' } };
|
|
127
|
+
}
|
|
128
|
+
res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ origin: runtimeOrigin, open, name })); return;
|
|
129
|
+
}
|
|
130
|
+
res.setHeader("content-type", "text/html"); res.end('<!doctype html><html><head><title>RUNNING</title></head><body><script type="module" src="/host.js"></script></body></html>');
|
|
131
|
+
}
|
|
132
|
+
const host = createServer(handleHost);
|
|
133
|
+
hostOrigin = options.local ? runtimeOrigin : await listen(host);
|
|
134
|
+
return { hostOrigin, runtimeOrigin, counts: () => ({ packageRequests, registryRequests }), close: async () => { await Promise.all((options.local ? [server] : [server, host]).map((s) => new Promise<void>((resolve, reject) => { s.closeAllConnections(); s.close((error) => error ? reject(error) : resolve()); }))); } };
|
|
135
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { useEffect, useState } from "react";
|
|
2
|
+
import { Badge } from "@flanksource/clicky-ui/data";
|
|
3
|
+
import { formatDuration } from "@flanksource/clicky-ui/utils";
|
|
4
|
+
import type { BuildLogEntry } from "./build-log.ts";
|
|
5
|
+
|
|
6
|
+
const elapsed = (ms: number) => `+${(ms / 1000).toFixed(2)}s`;
|
|
7
|
+
|
|
8
|
+
/** A timed page-load log; while `live`, the running step's duration ticks from `startedAt` (epoch ms of the first step). */
|
|
9
|
+
export function BuildLog({ entries, live, startedAt, className = "" }: { entries: BuildLogEntry[]; live: boolean; startedAt?: number; className?: string }) {
|
|
10
|
+
const [now, setNow] = useState(() => Date.now());
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
if (!live) return;
|
|
13
|
+
const timer = setInterval(() => setNow(Date.now()), 100);
|
|
14
|
+
return () => clearInterval(timer);
|
|
15
|
+
}, [live]);
|
|
16
|
+
return <ol role="log" aria-live="polite" aria-label="Build log" className={`space-y-0.5 font-mono text-xs ${className}`}>
|
|
17
|
+
{entries.map((entry, index) => {
|
|
18
|
+
const running = entry.durationMs === null && live && startedAt !== undefined;
|
|
19
|
+
const duration = entry.durationMs ?? (running ? Math.max(0, now - startedAt - entry.offsetMs) : null);
|
|
20
|
+
return <li key={index} className={`grid grid-cols-[4.5rem_5.5rem_1fr_auto] items-baseline gap-2 ${entry.error ? "text-destructive" : ""}`}>
|
|
21
|
+
<span className="tabular-nums text-muted-foreground">{elapsed(entry.offsetMs)}</span>
|
|
22
|
+
<span><Badge>{entry.source}</Badge></span>
|
|
23
|
+
<span className="min-w-0 break-words">{entry.label}{entry.error ? `: ${entry.error}` : ""}</span>
|
|
24
|
+
<span className="tabular-nums text-muted-foreground">{duration === null ? "" : running ? `${formatDuration(duration)}…` : formatDuration(duration)}</span>
|
|
25
|
+
</li>;
|
|
26
|
+
})}
|
|
27
|
+
</ol>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Page runtimes in DebugConsole
|
|
2
|
+
|
|
3
|
+
`PageFrame` automatically registers each active frame with the shared `@flanksource/clicky-ui` DebugConsole. This covers Facet previews and Clicky UI pages without wiring diagnostics in each application. Mount the existing `DebugConsoleDock` and `DebugConsoleButton` in the host application; open the console and select **Runtimes**.
|
|
4
|
+
|
|
5
|
+
Each frame has an independent view of its status, build errors, libraries, requests, timeline, Tailwind builds and load summary. The build log includes frame lifecycle steps. The diagnostics view loads when selected. Unmounting or navigating the frame removes its registration, and **Clear captures** clears runtime diagnostics alongside the other console captures.
|
|
6
|
+
|
|
7
|
+
`DebugConsoleButton` also displays a runtime indicator badge while frames are active. It follows their loading, ready and failed states, prioritizes failures when several frames are open, and opens **Runtimes** when clicked. The tooltip lists each page's state and latest error. `RuntimeIndicatorBadge` is also exported from `@flanksource/clicky-ui/devtools` for a custom toolbar.
|
|
8
|
+
|
|
9
|
+
Request activity is retained only while the console is open with capture enabled. Each frame retains at most 2,000 requests and reports how many older requests were dropped. Status and the latest build error remain available when opening the console after a failure. Diagnostics do not retain template data, source content or export snapshots.
|
|
10
|
+
|
|
11
|
+
For a custom runtime host, `registerDebugRuntime({ id, label, content, clear, state })` from `@flanksource/clicky-ui/data` registers a React diagnostics view. `state` supplies `getSnapshot()` returning `{ status, error }` and `subscribe(listener)` returning an unsubscribe function. The returned registration function unregisters the runtime and its status subscription. IDs must be unique among active frames. `DebugConsole` subscribes to registrations, so mounting it after a frame still lists that frame. The selected top-level tab persists in `__debug_tab=runtimes`.
|
|
12
|
+
|
|
13
|
+
The **Devtools / Page runtimes / FacetAndClicky** Storybook story demonstrates both runtime views, a failed build and clearing diagnostics.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import type { FormDataProps } from "@flanksource/clicky-ui/components";
|
|
3
|
+
import type { FolderManifest, FrameMessage, JsonValue, RuntimePolicy, SourceProvider } from "../schema.ts";
|
|
4
|
+
import { formPageOpen, schemaExtensionSources, type FormExtensionSource } from "../form/form-page.ts";
|
|
5
|
+
import { formSourceUpdate } from "../form/source-update.ts";
|
|
6
|
+
import type { PageBridge } from "./bridge.ts";
|
|
7
|
+
import { PageFrame, type PageFrameProps } from "./PageFrame.tsx";
|
|
8
|
+
import { validateJson } from "./message-values.ts";
|
|
9
|
+
|
|
10
|
+
export type PageFormProps = Omit<PageFrameProps, "open" | "data" | "dataUpdates" | "onBridge" | "onMessage" | "onChange"> & {
|
|
11
|
+
schema: JsonValue;
|
|
12
|
+
value: JsonValue;
|
|
13
|
+
/** Called with the whole form value on every edit; feed it back through `value` to keep the form controlled. */
|
|
14
|
+
onChange: (value: JsonValue) => void;
|
|
15
|
+
/** Runtime-compiled `FormExtension` modules: inline TSX, or a path served by `files` or `sourceProvider`. */
|
|
16
|
+
extensions: FormExtensionSource[];
|
|
17
|
+
/** The serializable `JsonSchemaForm` props; function-valued ones come from the extensions inside the frame. */
|
|
18
|
+
formProps?: FormDataProps;
|
|
19
|
+
manifest: FolderManifest;
|
|
20
|
+
files?: Record<string, string>;
|
|
21
|
+
sourceProvider?: SourceProvider;
|
|
22
|
+
policy?: RuntimePolicy;
|
|
23
|
+
/** Every frame message except `size` and the form's `change` event, which `PageForm` consumes. */
|
|
24
|
+
onMessage?: (message: FrameMessage) => void;
|
|
25
|
+
onBridge?: (bridge: PageBridge | null) => void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** Renders a `JsonSchemaForm`, with runtime-compiled extensions, inside a page-runtime frame sized to its content. */
|
|
29
|
+
export function PageForm({ schema, value, onChange, extensions, formProps, manifest, files, sourceProvider, policy, onMessage, onBridge, style, ...frame }: PageFormProps) {
|
|
30
|
+
const sources = JSON.stringify([extensions, schemaExtensionSources(schema), manifest, files, sourceProvider, policy]);
|
|
31
|
+
const open = useMemo(() => formPageOpen({ extensions, schema, manifest, ...(files ? { files } : {}), ...(sourceProvider ? { sourceProvider } : {}), ...(policy ? { policy } : {}) }), [sources]);
|
|
32
|
+
const data = useMemo<JsonValue>(() => {
|
|
33
|
+
const next: unknown = { schema, value, props: formProps ?? {} };
|
|
34
|
+
validateJson(next);
|
|
35
|
+
return next;
|
|
36
|
+
}, [schema, value, formProps]);
|
|
37
|
+
const [applied, setApplied] = useState(open);
|
|
38
|
+
const [ready, setReady] = useState(false);
|
|
39
|
+
const [height, setHeight] = useState<number>();
|
|
40
|
+
const [bridge, setBridge] = useState<PageBridge | null>(null);
|
|
41
|
+
const updating = useRef(false);
|
|
42
|
+
const latest = useRef({ data, onChange, onMessage, onError: frame.onError });
|
|
43
|
+
latest.current = { data, onChange, onMessage, onError: frame.onError };
|
|
44
|
+
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
if (!ready || !bridge || updating.current || applied === open) return;
|
|
47
|
+
const update = formSourceUpdate({ before: applied, after: open, data: latest.current.data });
|
|
48
|
+
if (!update) { setApplied(open); return; }
|
|
49
|
+
if (update.type === "open") { bridge.send(update); setReady(false); setApplied(open); return; }
|
|
50
|
+
updating.current = true;
|
|
51
|
+
void bridge.request(update).then(() => setApplied(open)).catch((error: unknown) => latest.current.onError(error instanceof Error ? error : new Error(String(error)))).finally(() => { updating.current = false; });
|
|
52
|
+
}, [ready, bridge, applied, open]);
|
|
53
|
+
|
|
54
|
+
const receive = (message: FrameMessage) => {
|
|
55
|
+
if (message.type === "size") setHeight(message.height);
|
|
56
|
+
else if (message.type === "emit" && message.event === "change") latest.current.onChange(message.payload);
|
|
57
|
+
else {
|
|
58
|
+
if (message.type === "status" && message.state === "ready") setReady(true);
|
|
59
|
+
latest.current.onMessage?.(message);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
return <PageFrame {...frame} open={applied} data={data} style={{ ...style, ...(height === undefined ? {} : { height }) }} onMessage={receive} onBridge={(next) => { setBridge(next); if (!next) setReady(false); onBridge?.(next); }} />;
|
|
63
|
+
}
|