@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,75 @@
|
|
|
1
|
+
import type { FrameConfig } from "../../schema.ts";
|
|
2
|
+
import { orderLibraries, validateRecipe, type CompilerLoaders, type LibraryStyles } from "./recipe.ts";
|
|
3
|
+
|
|
4
|
+
export type ImportModule = (url: string) => Promise<Record<string, unknown>>;
|
|
5
|
+
type StyleResolver = typeof resolveStyleImport;
|
|
6
|
+
const importModule: ImportModule = (url) => import(/* @vite-ignore */ url) as Promise<Record<string, unknown>>;
|
|
7
|
+
|
|
8
|
+
export function resolveStyleImport(options: { id: string; base: string; config: FrameConfig }): string {
|
|
9
|
+
const { id, config } = options;
|
|
10
|
+
let target: string | undefined;
|
|
11
|
+
if (/^(?:[./]|https?:)/.test(id)) target = new URL(id, options.base).href;
|
|
12
|
+
else {
|
|
13
|
+
const scopes = Object.entries(config.lock.map.scopes).filter(([scope]) => options.base.startsWith(new URL(scope, location.origin).href)).sort(([a], [b]) => b.length - a.length);
|
|
14
|
+
for (const table of [...scopes.map(([, table]) => table), config.lock.map.imports]) {
|
|
15
|
+
target = table[id];
|
|
16
|
+
if (!target) {
|
|
17
|
+
const prefix = Object.keys(table).filter((key) => key.endsWith("/") && id.startsWith(key)).sort((a, b) => b.length - a.length)[0];
|
|
18
|
+
if (prefix) target = table[prefix]! + id.slice(prefix.length);
|
|
19
|
+
}
|
|
20
|
+
if (target) break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (!target) throw new Error(`${options.base}: unmapped page-style import ${id}`);
|
|
24
|
+
const url = new URL(target, location.origin);
|
|
25
|
+
const packageRoute = url.pathname.startsWith("/npm/") || (config.profile.links === "allow" && url.pathname.startsWith("/link/"));
|
|
26
|
+
if (url.origin !== location.origin || !packageRoute) throw new Error(`${id}: page styles must load through the runtime package route: ${url.href}`);
|
|
27
|
+
url.searchParams.set("page", config.page);
|
|
28
|
+
return url.href;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The lock's integrity entry for a package-route URL, which is absent for linked modules. */
|
|
32
|
+
function lockedIntegrity(url: string, config: FrameConfig): string | undefined {
|
|
33
|
+
const { pathname } = new URL(url);
|
|
34
|
+
const path = pathname.startsWith("/npm/") ? decodeURIComponent(pathname.slice("/npm/".length)) : pathname.startsWith("/esm/") ? decodeURIComponent(pathname.slice(1)) : undefined;
|
|
35
|
+
return path === undefined ? undefined : config.lock.integrity[path];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Every library's published base stylesheets, in library order, resolved through the integrity-checked package route. */
|
|
39
|
+
export function baseStylesheets(options: { libraries: LibraryStyles[]; config: FrameConfig; resolve?: StyleResolver }): Array<{ url: string; layer: string }> {
|
|
40
|
+
const sheets = new Map<string, { url: string; layer: string }>();
|
|
41
|
+
for (const library of options.libraries) for (const id of library.recipe.base) {
|
|
42
|
+
const url = (options.resolve ?? resolveStyleImport)({ id, base: library.base, config: options.config });
|
|
43
|
+
const previous = sheets.get(url);
|
|
44
|
+
if (previous && previous.layer !== library.recipe.layer) throw new Error(`${url}: base stylesheet declared in conflicting layers ${previous.layer} and ${library.recipe.layer}`);
|
|
45
|
+
sheets.set(url, { url, layer: library.recipe.layer });
|
|
46
|
+
}
|
|
47
|
+
return [...sheets.values()];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function loadLibraries(options: { config: FrameConfig; importModule?: ImportModule; resolve?: StyleResolver; fetch?: typeof fetch }): Promise<{ libraries: LibraryStyles[]; loaders: CompilerLoaders }> {
|
|
51
|
+
const importer = options.importModule ?? importModule;
|
|
52
|
+
const resolve = options.resolve ?? resolveStyleImport;
|
|
53
|
+
const libraries: LibraryStyles[] = await Promise.all(Object.keys(options.config.profile.managed).map(async (name) => {
|
|
54
|
+
const version = options.config.lock.versions[name];
|
|
55
|
+
if (!version) throw new Error(`${name}: managed library has no version in the page lock`);
|
|
56
|
+
const url = resolve({ id: `${name}/page-styles`, base: location.href, config: options.config });
|
|
57
|
+
const loaded = await importer(url);
|
|
58
|
+
const recipe = validateRecipe(loaded.pageStyles ?? loaded.default, name);
|
|
59
|
+
const integrity = lockedIntegrity(url, options.config);
|
|
60
|
+
return { id: url, name, version, ...(integrity ? { integrity } : {}), base: new URL(".", url).href, recipe };
|
|
61
|
+
}));
|
|
62
|
+
return { libraries: orderLibraries(libraries), loaders: {
|
|
63
|
+
loadStylesheet: async (id, base) => {
|
|
64
|
+
const url = resolve({ id, base, config: options.config });
|
|
65
|
+
const response = await (options.fetch ?? fetch)(url);
|
|
66
|
+
if (!response.ok || response.headers.has("x-page-runtime-error")) throw new Error(`${url}: stylesheet fetch failed (HTTP ${response.status})`);
|
|
67
|
+
return { path: url, base: new URL(".", url).href, content: await response.text() };
|
|
68
|
+
},
|
|
69
|
+
loadModule: async (id, base) => {
|
|
70
|
+
const url = resolve({ id, base, config: options.config });
|
|
71
|
+
const loaded = await importer(url);
|
|
72
|
+
return { path: url, base: new URL(".", url).href, module: loaded.default ?? loaded };
|
|
73
|
+
},
|
|
74
|
+
} };
|
|
75
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { compile } from "tailwindcss";
|
|
2
|
+
import autoprefixer from "autoprefixer";
|
|
3
|
+
import postcss from "postcss";
|
|
4
|
+
import type { PageStylesRecipe } from "../../schema.ts";
|
|
5
|
+
import { cascadeOrder } from "../../styles.ts";
|
|
6
|
+
export { layerOrder } from "../../styles.ts";
|
|
7
|
+
|
|
8
|
+
export type { PageStylesRecipe };
|
|
9
|
+
export type LibraryStyles = {
|
|
10
|
+
/** The recipe module's URL, used for loading only: it carries the requesting page and is not part of any cache key. */
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
version: string;
|
|
14
|
+
/** The recipe module's `lock.integrity` entry; absent for linked modules, which cannot key a cache. */
|
|
15
|
+
integrity?: string;
|
|
16
|
+
base: string;
|
|
17
|
+
recipe: PageStylesRecipe;
|
|
18
|
+
};
|
|
19
|
+
export type CompilerLoaders = Required<Pick<NonNullable<Parameters<typeof compile>[1]>, "loadStylesheet" | "loadModule">>;
|
|
20
|
+
|
|
21
|
+
/** Deterministic library order: a library that is extended comes before its extender, and ties are sorted by name. */
|
|
22
|
+
export function orderLibraries(libraries: LibraryStyles[]): LibraryStyles[] {
|
|
23
|
+
const byName = new Map(libraries.map((library) => [library.name, library]));
|
|
24
|
+
const waiting = new Map<string, Set<string>>();
|
|
25
|
+
for (const library of libraries) {
|
|
26
|
+
const needs = new Set(library.recipe.extends ?? []);
|
|
27
|
+
for (const name of needs) if (!byName.has(name)) throw new Error(`${library.name}/page-styles: extends ${name}, which is not a managed library`);
|
|
28
|
+
waiting.set(library.name, needs);
|
|
29
|
+
}
|
|
30
|
+
const ordered: LibraryStyles[] = [];
|
|
31
|
+
while (waiting.size) {
|
|
32
|
+
const ready = [...waiting].filter(([, needs]) => needs.size === 0).map(([name]) => name).sort();
|
|
33
|
+
if (!ready.length) throw new Error(`page-styles: libraries extend each other in a cycle: ${[...waiting.keys()].sort().join(", ")}`);
|
|
34
|
+
const next = ready[0]!;
|
|
35
|
+
ordered.push(byName.get(next)!);
|
|
36
|
+
waiting.delete(next);
|
|
37
|
+
for (const needs of waiting.values()) needs.delete(next);
|
|
38
|
+
}
|
|
39
|
+
return ordered;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function compileLibraries(options: { libraries: LibraryStyles[]; loaders: CompilerLoaders }) {
|
|
43
|
+
const entries: Record<string, LibraryStyles> = {};
|
|
44
|
+
const entry = orderLibraries(options.libraries).map((library, index) => {
|
|
45
|
+
const id = `page-runtime:recipe-${index}`;
|
|
46
|
+
entries[id] = library;
|
|
47
|
+
return `@import "${id}";`;
|
|
48
|
+
});
|
|
49
|
+
return compile([cascadeOrder(orderLibraries(options.libraries).map(library => library.recipe.layer)), ...entry].join("\n"), {
|
|
50
|
+
loadStylesheet: async (id, base) => {
|
|
51
|
+
const library = entries[id];
|
|
52
|
+
if (library) return { path: id, base: library.base, content: library.recipe.entry };
|
|
53
|
+
return options.loaders.loadStylesheet(id, base);
|
|
54
|
+
},
|
|
55
|
+
loadModule: options.loaders.loadModule,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function transformCss(options: { css: string; libraries: LibraryStyles[] }): string {
|
|
60
|
+
options.css = postcss([autoprefixer({ grid: false })]).process(options.css, { from: undefined }).css;
|
|
61
|
+
for (const { recipe } of options.libraries) {
|
|
62
|
+
if (recipe.transform) options.css = recipe.transform(options.css);
|
|
63
|
+
}
|
|
64
|
+
return options.css;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
68
|
+
|
|
69
|
+
export function validateRecipe(value: unknown, name: string): PageStylesRecipe {
|
|
70
|
+
if (!value || typeof value !== "object") throw new Error(`${name}/page-styles: expected a recipe`);
|
|
71
|
+
const recipe = value as PageStylesRecipe;
|
|
72
|
+
if (recipe.name !== name || typeof recipe.layer !== "string" || !recipe.layer || typeof recipe.entry !== "string" || typeof recipe.theme !== "string" || !strings(recipe.base) || !recipe.base.length || recipe.base.some((specifier) => !specifier) || !strings(recipe.runtimeDependencies) || (recipe.extends !== undefined && !strings(recipe.extends)) || (recipe.transform !== undefined && typeof recipe.transform !== "function")) throw new Error(`${name}/page-styles: invalid recipe`);
|
|
73
|
+
const imported = recipe.base.find((specifier) => recipe.entry.includes(specifier));
|
|
74
|
+
if (imported) throw new Error(`${name}/page-styles: entry must not import the base stylesheet ${imported}`);
|
|
75
|
+
return recipe;
|
|
76
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { compileLibraries, transformCss, type CompilerLoaders, type LibraryStyles } from "./recipe.ts";
|
|
2
|
+
import { cssCacheKey, libraryKey } from "./cache.ts";
|
|
3
|
+
import { insertCss } from "./stylesheets.ts";
|
|
4
|
+
import type { TailwindStore } from "./store.ts";
|
|
5
|
+
import type { TailwindActivity } from "../../activity-schema.ts";
|
|
6
|
+
|
|
7
|
+
type Compiled = { compiler: Awaited<ReturnType<typeof compileLibraries>>; candidates: Set<string> };
|
|
8
|
+
const compilers = new Map<string, Promise<Compiled>>();
|
|
9
|
+
const IDLE_PERSIST_MS = 1000;
|
|
10
|
+
export type TailwindOptions = { libraries: LibraryStyles[]; loaders: CompilerLoaders; runtimeVersion: string; root: HTMLElement; candidates: string[]; store?: TailwindStore; timeoutMs: number; onError: (error: unknown) => void; onActivity?: (activity: TailwindActivity) => void };
|
|
11
|
+
|
|
12
|
+
export function loadTailwind(options: Pick<TailwindOptions, "libraries" | "loaders" | "runtimeVersion" | "onActivity">): Promise<Compiled> {
|
|
13
|
+
const key = libraryKey(options);
|
|
14
|
+
let compiling = compilers.get(key);
|
|
15
|
+
if (!compiling) {
|
|
16
|
+
const startMs = performance.now();
|
|
17
|
+
compiling = compileLibraries(options).then((compiler) => { options.onActivity?.({ kind: "libraries", startMs, durationMs: performance.now() - startMs, candidates: 0, cssBytes: 0, cacheHit: false }); return { compiler, candidates: new Set<string>() }; });
|
|
18
|
+
compilers.set(key, compiling);
|
|
19
|
+
} else options.onActivity?.({ kind: "libraries", startMs: performance.now(), durationMs: 0, candidates: 0, cssBytes: 0, cacheHit: true });
|
|
20
|
+
return compiling;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function classesUnder(options: { node: Element; root: HTMLElement; candidates: Set<string> }): boolean {
|
|
24
|
+
if (!options.root.contains(options.node)) return false;
|
|
25
|
+
let fresh = false;
|
|
26
|
+
for (const element of [options.node, ...options.node.querySelectorAll("[class]")]) {
|
|
27
|
+
for (const name of element.classList) {
|
|
28
|
+
if (!options.candidates.has(name)) { options.candidates.add(name); fresh = true; }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return fresh;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function whenIdle(callback: () => void): () => void {
|
|
35
|
+
if (typeof requestIdleCallback === "function") {
|
|
36
|
+
const id = requestIdleCallback(callback, { timeout: IDLE_PERSIST_MS });
|
|
37
|
+
return () => cancelIdleCallback(id);
|
|
38
|
+
}
|
|
39
|
+
const id = setTimeout(callback, IDLE_PERSIST_MS);
|
|
40
|
+
return () => clearTimeout(id);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function prepareTailwind(options: TailwindOptions) {
|
|
44
|
+
if (options.candidates.some((candidate) => typeof candidate !== "string")) throw new Error("runtime Tailwind: source candidates must be strings");
|
|
45
|
+
const library = libraryKey(options);
|
|
46
|
+
const source = new Set(options.candidates);
|
|
47
|
+
const candidates = new Set(source);
|
|
48
|
+
const key = await cssCacheKey({ libraryKey: library, candidates: source });
|
|
49
|
+
const cached = await options.store?.read(key);
|
|
50
|
+
if (cached) for (const candidate of cached.record.domClasses) candidates.add(candidate);
|
|
51
|
+
const fresh = classesUnder({ node: options.root, root: options.root, candidates });
|
|
52
|
+
performance.mark("page-runtime:css-cache");
|
|
53
|
+
let style: HTMLStyleElement | undefined;
|
|
54
|
+
let imports = Promise.resolve();
|
|
55
|
+
let failure: unknown;
|
|
56
|
+
let observing = false;
|
|
57
|
+
const report = (error: unknown) => { failure = error; if (observing) options.onError(error); };
|
|
58
|
+
const insert = (css: string) => {
|
|
59
|
+
const output = insertCss({ document: options.root.ownerDocument, ...(style ? { previous: style } : {}), css, timeoutMs: options.timeoutMs });
|
|
60
|
+
style = output.style; imports = output.ready;
|
|
61
|
+
void imports.catch(report);
|
|
62
|
+
};
|
|
63
|
+
if (cached) { insert(cached.css); options.onActivity?.({ kind: "candidates", startMs: performance.now(), durationMs: 0, candidates: candidates.size, cssBytes: new TextEncoder().encode(cached.css).byteLength, cacheHit: true }); }
|
|
64
|
+
const compiled = await loadTailwind(options);
|
|
65
|
+
let current = cached?.css ?? "";
|
|
66
|
+
const build = () => {
|
|
67
|
+
for (const candidate of candidates) compiled.candidates.add(candidate);
|
|
68
|
+
return transformCss({ css: compiled.compiler.build([...compiled.candidates]), libraries: options.libraries });
|
|
69
|
+
};
|
|
70
|
+
let persisted = Promise.resolve();
|
|
71
|
+
let pending: (() => void) | undefined;
|
|
72
|
+
const flush = (): Promise<void> => {
|
|
73
|
+
if (pending) {
|
|
74
|
+
pending(); pending = undefined;
|
|
75
|
+
const write = { key, libraryKey: library, candidates: [...source].sort(), domClasses: [...candidates].filter((name) => !source.has(name)).sort(), css: current };
|
|
76
|
+
persisted = persisted.then(() => options.store?.write(write));
|
|
77
|
+
void persisted.catch(report);
|
|
78
|
+
}
|
|
79
|
+
return persisted;
|
|
80
|
+
};
|
|
81
|
+
const persist = () => { if (options.store) pending ??= whenIdle(() => { void flush(); }); };
|
|
82
|
+
const update = () => {
|
|
83
|
+
const startMs = performance.now();
|
|
84
|
+
current = build();
|
|
85
|
+
options.onActivity?.({ kind: "candidates", startMs, durationMs: performance.now() - startMs, candidates: compiled.candidates.size, cssBytes: new TextEncoder().encode(current).byteLength, cacheHit: false });
|
|
86
|
+
insert(current);
|
|
87
|
+
for (const candidate of compiled.candidates) candidates.add(candidate);
|
|
88
|
+
persist();
|
|
89
|
+
};
|
|
90
|
+
if (!cached || fresh) update();
|
|
91
|
+
else for (const candidate of candidates) compiled.candidates.add(candidate);
|
|
92
|
+
performance.mark("page-runtime:css-built");
|
|
93
|
+
if (!cached) await flush();
|
|
94
|
+
await imports;
|
|
95
|
+
performance.mark("page-runtime:css-imports");
|
|
96
|
+
const observer = new MutationObserver((records) => {
|
|
97
|
+
try {
|
|
98
|
+
let changed = false;
|
|
99
|
+
for (const record of records) {
|
|
100
|
+
const nodes = record.type === "attributes" ? [record.target] : [...record.addedNodes];
|
|
101
|
+
for (const node of nodes) if (node instanceof Element && classesUnder({ node, root: options.root, candidates })) changed = true;
|
|
102
|
+
}
|
|
103
|
+
if (changed) update();
|
|
104
|
+
} catch (error) { observer.disconnect(); report(error); }
|
|
105
|
+
});
|
|
106
|
+
observer.observe(options.root, { subtree: true, childList: true, attributes: true, attributeFilter: ["class"] });
|
|
107
|
+
observing = true;
|
|
108
|
+
return {
|
|
109
|
+
warm: Boolean(cached), get style() { return style!; }, candidates,
|
|
110
|
+
ready: async () => { await imports; await flush(); if (failure) throw failure; },
|
|
111
|
+
stop: () => { observer.disconnect(); style?.remove(); if (pending) void flush().catch(report); },
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { committed, result, type TailwindRecord } from "../../storage/db.ts";
|
|
2
|
+
import { tailwindCssUrl } from "./cache.ts";
|
|
3
|
+
|
|
4
|
+
/** Generated stylesheets kept per library key; the least recently used beyond this are evicted. */
|
|
5
|
+
export const TAILWIND_ENTRIES_PER_LIBRARY = 32;
|
|
6
|
+
export type TailwindWrite = { key: string; libraryKey: string; candidates: string[]; domClasses: string[]; css: string };
|
|
7
|
+
export type TailwindStoreOptions = { db: () => Promise<IDBDatabase>; cache: Cache; origin: string; fetch: typeof fetch; keep?: number; now?: () => number };
|
|
8
|
+
export type TailwindStore = ReturnType<typeof createTailwindStore>;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generated CSS is a plain `text/css` response in Cache Storage, served by the worker at `/__runtime/tailwind/<key>.css`.
|
|
12
|
+
* The IndexedDB record is the commit point: it is written after the response, and a record whose response is missing
|
|
13
|
+
* is an invariant violation, not a miss.
|
|
14
|
+
*/
|
|
15
|
+
export function createTailwindStore(options: TailwindStoreOptions) {
|
|
16
|
+
const keep = options.keep ?? TAILWIND_ENTRIES_PER_LIBRARY;
|
|
17
|
+
let last = 0;
|
|
18
|
+
// Strictly increasing, so records written within one millisecond still order by recency.
|
|
19
|
+
const now = options.now ?? (() => last = Math.max(Date.now(), last + 1));
|
|
20
|
+
|
|
21
|
+
/** The record and its CSS, or undefined when nothing was stored for the key. Counts as a use for eviction. */
|
|
22
|
+
async function read(key: string): Promise<{ record: TailwindRecord; css: string } | undefined> {
|
|
23
|
+
const tx = (await options.db()).transaction("tailwind", "readwrite");
|
|
24
|
+
const store = tx.objectStore("tailwind");
|
|
25
|
+
const record = await result<TailwindRecord | undefined>(store.get(key));
|
|
26
|
+
if (record) store.put({ ...record, lastUsedAt: now() });
|
|
27
|
+
await committed(tx);
|
|
28
|
+
if (!record) return undefined;
|
|
29
|
+
const response = await options.fetch(record.url);
|
|
30
|
+
if (!response.ok || response.headers.has("x-page-runtime-error")) throw new Error(`runtime Tailwind: record ${key} has no cached stylesheet at ${record.url} (HTTP ${response.status}); its Cache Storage entry was removed while the IndexedDB record remained`);
|
|
31
|
+
return { record, css: await response.text() };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function write(input: TailwindWrite): Promise<void> {
|
|
35
|
+
const url = tailwindCssUrl({ key: input.key, origin: options.origin });
|
|
36
|
+
const bytes = new TextEncoder().encode(input.css).byteLength;
|
|
37
|
+
await options.cache.put(url, new Response(input.css, { headers: { "content-type": "text/css; charset=utf-8", "content-length": String(bytes), "x-tailwind-library-key": encodeURIComponent(input.libraryKey) } }));
|
|
38
|
+
const tx = (await options.db()).transaction("tailwind", "readwrite");
|
|
39
|
+
const store = tx.objectStore("tailwind");
|
|
40
|
+
const own = IDBKeyRange.bound([input.libraryKey, 0], [input.libraryKey, Infinity]);
|
|
41
|
+
const index = store.index("libraryKey+lastUsedAt");
|
|
42
|
+
const [previous, known] = await Promise.all([result<TailwindRecord | undefined>(store.get(input.key)), result(index.count(own))]);
|
|
43
|
+
const time = now();
|
|
44
|
+
store.put({ key: input.key, libraryKey: input.libraryKey, candidates: input.candidates, domClasses: input.domClasses, bytes, url, createdAt: previous?.createdAt ?? time, lastUsedAt: time } satisfies TailwindRecord);
|
|
45
|
+
const evicted: TailwindRecord[] = [];
|
|
46
|
+
if (known === 0) evicted.push(...(await result<TailwindRecord[]>(store.getAll())).filter((record) => record.libraryKey !== input.libraryKey));
|
|
47
|
+
const others = (await result<TailwindRecord[]>(index.getAll(own))).filter((record) => record.key !== input.key);
|
|
48
|
+
evicted.push(...others.slice(0, Math.max(0, others.length - (keep - 1))));
|
|
49
|
+
for (const record of evicted) store.delete(record.key);
|
|
50
|
+
await committed(tx);
|
|
51
|
+
await Promise.all(evicted.map((record) => options.cache.delete(record.url)));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { read, write };
|
|
55
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { cascadeOrder } from "../../styles.ts";
|
|
2
|
+
|
|
3
|
+
/** Imports base stylesheets in their declared cascade layers and waits for every import to load. */
|
|
4
|
+
export function insertBaseStyles(options: { document: Document; stylesheets: Array<{ url: string; layer: string }>; timeoutMs: number }): { links: HTMLStyleElement[]; ready: Promise<void> } {
|
|
5
|
+
const layerOrder = cascadeOrder(options.stylesheets.map(sheet => sheet.layer));
|
|
6
|
+
const links = options.stylesheets.map(({ url, layer }) => {
|
|
7
|
+
const link = options.document.createElement("style");
|
|
8
|
+
link.textContent = `${layerOrder}\n@import url(${JSON.stringify(url)}) layer(${layer});`;
|
|
9
|
+
link.dataset["pageRuntimeBase"] = url;
|
|
10
|
+
return link;
|
|
11
|
+
});
|
|
12
|
+
const ready = Promise.all(links.map((link) => new Promise<void>((resolve, reject) => {
|
|
13
|
+
const url = link.dataset["pageRuntimeBase"];
|
|
14
|
+
const timer = setTimeout(() => reject(new Error(`${url}: base stylesheet timeout after ${options.timeoutMs}ms`)), options.timeoutMs);
|
|
15
|
+
link.addEventListener("load", () => { clearTimeout(timer); resolve(); }, { once: true });
|
|
16
|
+
link.addEventListener("error", () => { clearTimeout(timer); reject(new Error(`${url}: base stylesheet failed to load`)); }, { once: true });
|
|
17
|
+
}))).then(() => undefined);
|
|
18
|
+
options.document.head.append(...links);
|
|
19
|
+
return { links, ready };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function insertCss(options: { document: Document; previous?: HTMLStyleElement; css: string; timeoutMs: number }) {
|
|
23
|
+
const style = options.document.createElement("style");
|
|
24
|
+
style.id = "runtime-tailwind";
|
|
25
|
+
const ready = /@import\s/.test(options.css) ? new Promise<void>((resolve, reject) => {
|
|
26
|
+
const done = (error?: Error) => {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
style.removeEventListener("load", loaded);
|
|
29
|
+
style.removeEventListener("error", failed);
|
|
30
|
+
if (error) reject(error); else resolve();
|
|
31
|
+
};
|
|
32
|
+
const loaded = () => done();
|
|
33
|
+
const failed = () => done(new Error("runtime Tailwind stylesheet import failed"));
|
|
34
|
+
const timer = setTimeout(() => done(new Error(`runtime Tailwind stylesheet imports timeout after ${options.timeoutMs}ms`)), options.timeoutMs);
|
|
35
|
+
style.addEventListener("load", loaded);
|
|
36
|
+
style.addEventListener("error", failed);
|
|
37
|
+
}) : Promise.resolve();
|
|
38
|
+
style.textContent = options.css;
|
|
39
|
+
if (options.previous) options.previous.replaceWith(style);
|
|
40
|
+
else options.document.head.append(style);
|
|
41
|
+
return { style, ready };
|
|
42
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
4
|
+
import { startTailwindServer } from "./testing/server.ts";
|
|
5
|
+
import { compare, type Snapshot } from "./testing/compare.ts";
|
|
6
|
+
import { parityPages } from "./testing/pages.ts";
|
|
7
|
+
|
|
8
|
+
const exec = promisify(execFile);
|
|
9
|
+
const session = `page-runtime-E-${process.pid}`;
|
|
10
|
+
let server: Awaited<ReturnType<typeof startTailwindServer>>;
|
|
11
|
+
let opened = false;
|
|
12
|
+
async function browser(...args: string[]) {
|
|
13
|
+
const { stdout } = await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 128_000_000 });
|
|
14
|
+
return stdout.trim();
|
|
15
|
+
}
|
|
16
|
+
async function run(path: string) {
|
|
17
|
+
await browser("open", `${server.url}/${path}`); opened = true;
|
|
18
|
+
await browser("wait", "--fn", 'document.title === "DONE"');
|
|
19
|
+
const result = JSON.parse(await browser("get", "text", "#result"));
|
|
20
|
+
if (result.error) throw new Error(`${result.error}\n${result.stack}`);
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
beforeAll(async () => {
|
|
24
|
+
server = await startTailwindServer();
|
|
25
|
+
await browser("open", "about:blank"); opened = true;
|
|
26
|
+
await browser("set", "viewport", "1920", "1080");
|
|
27
|
+
});
|
|
28
|
+
afterAll(async () => { try { if (opened) await browser("close"); } finally { await server?.close(); } });
|
|
29
|
+
|
|
30
|
+
describe("tailwind Chromium", () => {
|
|
31
|
+
it("styles source candidates before layout effects, runtime classes before paint, excludes overlays and warms from Cache Storage", async () => {
|
|
32
|
+
const result = await run("?probe=1");
|
|
33
|
+
expect(result, JSON.stringify(result)).toMatchObject({ sourceWidth: 137, dynamicWidth: 237, changedWidth: 319, excluded: true, warm: true, layoutWidth: 137, importFailed: true, errors: [] });
|
|
34
|
+
expect(result.imported).toBeGreaterThanOrEqual(180);
|
|
35
|
+
});
|
|
36
|
+
it("keeps base rules out of the generated stylesheet and stores it as a few-KB text/css response with agreeing IndexedDB metadata", async () => {
|
|
37
|
+
const result = await run("?probe=1");
|
|
38
|
+
expect(result.baseInGenerated).toBe(false);
|
|
39
|
+
expect(result.generatedKilobytes).toBeLessThan(20);
|
|
40
|
+
expect(result.cold).toMatchObject({ records: 1, candidateRecords: 0, legacyCandidateEntries: 0, contentType: "text/css; charset=utf-8" });
|
|
41
|
+
expect(result.cold.cachedBytes).toBe(result.cold.recordBytes);
|
|
42
|
+
expect(result.cold.kilobytes).toBeLessThan(20);
|
|
43
|
+
});
|
|
44
|
+
it("warms from the stored record, adding the DOM classes the cold load discovered without a second entry", async () => {
|
|
45
|
+
const result = await run("?probe=1");
|
|
46
|
+
expect(result.warm).toBe(true);
|
|
47
|
+
expect(result.warmStorage).toMatchObject({ records: 1, legacyCandidateEntries: 0 });
|
|
48
|
+
expect(result.cold.domClasses).toEqual(expect.arrayContaining(["w-[237px]", "w-[319px]"]));
|
|
49
|
+
});
|
|
50
|
+
it("styles a page that does not opt in from the base links alone, with no runtime style element", async () => {
|
|
51
|
+
const result = await run("?plain=1");
|
|
52
|
+
expect(result).toMatchObject({ runtimeStyle: false, styled: true });
|
|
53
|
+
expect(result.baseLinks).toBeGreaterThanOrEqual(1);
|
|
54
|
+
});
|
|
55
|
+
it.each(parityPages)("matches facet's v4 build in two fresh renders: %s", async (name) => {
|
|
56
|
+
const runtime = await run(`?page=${name}&mode=runtime`) as Snapshot;
|
|
57
|
+
const reference = await run(`?page=${name}&mode=reference`) as Snapshot;
|
|
58
|
+
const differences = compare(runtime, reference).differences;
|
|
59
|
+
expect(differences, JSON.stringify(differences.slice(0, 12))).toEqual([]);
|
|
60
|
+
expect(runtime.selectors.length).toBeGreaterThan(10);
|
|
61
|
+
});
|
|
62
|
+
it.each(["LiveDiagram", "DataFlowDiagram"])("keeps styled diagram measurements at 2560x1440: %s", async (name) => {
|
|
63
|
+
await browser("set", "viewport", "2560", "1440");
|
|
64
|
+
try {
|
|
65
|
+
const runtime = await run(`?page=${name}&mode=runtime`) as Snapshot;
|
|
66
|
+
const reference = await run(`?page=${name}&mode=reference`) as Snapshot;
|
|
67
|
+
const differences = compare(runtime, reference).differences;
|
|
68
|
+
expect(differences, JSON.stringify(differences.slice(0, 12))).toEqual([]);
|
|
69
|
+
} finally { await browser("set", "viewport", "1920", "1080"); }
|
|
70
|
+
});
|
|
71
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { createRoot } from "react-dom/client";
|
|
3
|
+
import { prepareTailwind, type TailwindOptions } from "../runtime.ts";
|
|
4
|
+
import { waitForReadiness } from "../../readiness.ts";
|
|
5
|
+
import { insertBaseStyles, insertCss } from "../stylesheets.ts";
|
|
6
|
+
import { createTailwindStore } from "../store.ts";
|
|
7
|
+
import { openRuntimeDb, result, tailwindCacheName } from "../../../storage/db.ts";
|
|
8
|
+
import type { Snapshot } from "./compare.ts";
|
|
9
|
+
|
|
10
|
+
const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
|
11
|
+
type Options = Pick<TailwindOptions, "libraries" | "loaders" | "candidates"> & { base: Array<{ url: string; layer: string }>; pages: Record<string, () => Promise<{ default: React.ComponentType<{ data: unknown }> }>>; data: unknown };
|
|
12
|
+
|
|
13
|
+
async function snapshot(root: HTMLElement): Promise<Snapshot> {
|
|
14
|
+
await frame(); await document.fonts.ready;
|
|
15
|
+
for (const animation of document.getAnimations()) {
|
|
16
|
+
if (animation instanceof CSSTransition) animation.finish();
|
|
17
|
+
else { animation.pause(); animation.currentTime = 0; }
|
|
18
|
+
}
|
|
19
|
+
for (const svg of root.querySelectorAll("svg")) { svg.pauseAnimations(); svg.setCurrentTime(0); }
|
|
20
|
+
await frame();
|
|
21
|
+
const elements = [document.body, root, ...root.querySelectorAll("*")];
|
|
22
|
+
return {
|
|
23
|
+
selectors: elements.map((element) => `${element.tagName}.${element.getAttribute("class") ?? ""}`),
|
|
24
|
+
styles: elements.map((element) => { const style = getComputedStyle(element); return Array.from(style, (property) => `${property}:${style.getPropertyValue(property)}`); }),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The harness has no service worker, so the store reads generated CSS straight from the cache the worker would serve it from.
|
|
29
|
+
async function freshStorage(runtimeVersion: string) {
|
|
30
|
+
await new Promise<void>((resolve, reject) => { const request = indexedDB.deleteDatabase("page-runtime"); request.onsuccess = () => resolve(); request.onerror = () => reject(request.error); });
|
|
31
|
+
await caches.delete(tailwindCacheName(runtimeVersion));
|
|
32
|
+
const cache = await caches.open(tailwindCacheName(runtimeVersion));
|
|
33
|
+
const db = openRuntimeDb();
|
|
34
|
+
const store = createTailwindStore({ db: () => db, cache, origin: location.origin, fetch: async (url) => (await cache.match(String(url))) ?? new Response("missing", { status: 404, headers: { "x-page-runtime-error": "fetch" } }) });
|
|
35
|
+
return { store, db, cache };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function storageState(storage: Awaited<ReturnType<typeof freshStorage>>) {
|
|
39
|
+
const records = await result((await storage.db).transaction("tailwind").objectStore("tailwind").getAll());
|
|
40
|
+
const candidateRecords = await result((await storage.db).transaction("candidates").objectStore("candidates").getAll());
|
|
41
|
+
const response = records[0] ? await storage.cache.match(records[0].url) : undefined;
|
|
42
|
+
const body = response ? await response.text() : "";
|
|
43
|
+
const legacy = (await Promise.all((await caches.keys()).map(async (name) => (await (await caches.open(name)).keys()).filter((request) => request.url.includes("/__runtime/candidates/")).length))).reduce((sum, count) => sum + count, 0);
|
|
44
|
+
return {
|
|
45
|
+
records: records.length, candidateRecords: candidateRecords.length, legacyCandidateEntries: legacy,
|
|
46
|
+
contentType: response?.headers.get("content-type") ?? null, cachedBytes: new TextEncoder().encode(body).byteLength, recordBytes: records[0]?.bytes ?? null, kilobytes: Math.round(body.length / 1024),
|
|
47
|
+
domClasses: records[0]?.domClasses ?? [],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function probes(options: Options & { root: HTMLElement }) {
|
|
52
|
+
const runtimeVersion = "probe";
|
|
53
|
+
const storage = await freshStorage(runtimeVersion);
|
|
54
|
+
await insertBaseStyles({ document, stylesheets: options.base, timeoutMs: 15000 }).ready;
|
|
55
|
+
const errors: string[] = [];
|
|
56
|
+
const prepare = () => prepareTailwind({ ...options, candidates: ["w-[137px]"], runtimeVersion, store: storage.store, timeoutMs: 5000, onError: (error) => errors.push(String(error)) });
|
|
57
|
+
let runtime = await prepare();
|
|
58
|
+
const source = document.createElement("div"); source.className = "w-[137px]"; options.root.append(source);
|
|
59
|
+
const sourceWidth = source.getBoundingClientRect().width;
|
|
60
|
+
const dynamic = document.createElement("div"); dynamic.className = `w-[${Math.floor(200 + 37)}px]`; options.root.append(dynamic);
|
|
61
|
+
await frame(); const dynamicWidth = dynamic.getBoundingClientRect().width;
|
|
62
|
+
dynamic.className = `w-[${Math.floor(300 + 19)}px]`;
|
|
63
|
+
await frame(); const changedWidth = dynamic.getBoundingClientRect().width;
|
|
64
|
+
const overlay = document.createElement("aside"); overlay.className = "w-[991px]"; document.body.append(overlay);
|
|
65
|
+
const host = document.createElement("div"); options.root.append(host);
|
|
66
|
+
const shadow = host.attachShadow({ mode: "open" });
|
|
67
|
+
const shadowProbe = document.createElement("div"); shadowProbe.className = "w-[992px]"; shadow.append(shadowProbe);
|
|
68
|
+
await frame(); await runtime.ready();
|
|
69
|
+
const excluded = !runtime.candidates.has("w-[991px]") && !runtime.candidates.has("w-[992px]");
|
|
70
|
+
const generated = document.getElementById("runtime-tailwind")!.textContent!;
|
|
71
|
+
const baseInGenerated = /box-sizing|--color-red-500|\.bg-red-500|@import/.test(generated);
|
|
72
|
+
const cold = await storageState(storage);
|
|
73
|
+
runtime.stop(); options.root.replaceChildren(); overlay.remove();
|
|
74
|
+
runtime = await prepare();
|
|
75
|
+
const warm = runtime.warm;
|
|
76
|
+
let layoutWidth = 0;
|
|
77
|
+
const mounted = new Promise<void>((resolve) => {
|
|
78
|
+
function Page() { React.useLayoutEffect(() => { layoutWidth = options.root.firstElementChild!.getBoundingClientRect().width; resolve(); }, []); return React.createElement("div", { className: "w-[137px]" }); }
|
|
79
|
+
createRoot(options.root).render(React.createElement(Page));
|
|
80
|
+
});
|
|
81
|
+
await mounted; await runtime.ready();
|
|
82
|
+
const warmStorage = await storageState(storage);
|
|
83
|
+
runtime.stop();
|
|
84
|
+
const began = performance.now();
|
|
85
|
+
const importedSheet = insertCss({ document, css: '@import "/delayed.css";', timeoutMs: 5000 });
|
|
86
|
+
await importedSheet.ready;
|
|
87
|
+
const imported = performance.now() - began;
|
|
88
|
+
let importFailed = false;
|
|
89
|
+
try { await insertCss({ document, previous: importedSheet.style, css: '@import "/missing.css";', timeoutMs: 5000 }).ready; } catch { importFailed = true; }
|
|
90
|
+
return { sourceWidth, dynamicWidth, changedWidth, excluded, warm, layoutWidth, imported, importFailed, errors, baseInGenerated, generatedKilobytes: Math.round(generated.length / 1024), cold, warmStorage };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// A page that never opts in: the base links alone style it and no runtime style element exists.
|
|
94
|
+
async function plainProbe(options: Options & { root: HTMLElement }) {
|
|
95
|
+
await insertBaseStyles({ document, stylesheets: options.base, timeoutMs: 15000 }).ready;
|
|
96
|
+
const safelisted = document.createElement("div"); safelisted.className = "bg-red-500"; options.root.append(safelisted);
|
|
97
|
+
await frame();
|
|
98
|
+
const color = getComputedStyle(safelisted).backgroundColor;
|
|
99
|
+
return { runtimeStyle: document.getElementById("runtime-tailwind") !== null, baseLinks: document.querySelectorAll("[data-page-runtime-base]").length, color, styled: color !== "rgba(0, 0, 0, 0)" && color !== "" };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function run(options: Options): Promise<unknown> {
|
|
103
|
+
const root = document.getElementById("root")!;
|
|
104
|
+
const params = new URLSearchParams(location.search);
|
|
105
|
+
if (params.has("probe")) return probes({ ...options, root });
|
|
106
|
+
if (params.has("plain")) return plainProbe({ ...options, root });
|
|
107
|
+
const name = params.get("page");
|
|
108
|
+
if (name === null || !Object.hasOwn(options.pages, name)) throw new Error(`unknown page ${name}`);
|
|
109
|
+
const load = options.pages[name]; if (!load) throw new Error(`unknown page ${name}`);
|
|
110
|
+
const module = await load();
|
|
111
|
+
let runtime: Awaited<ReturnType<typeof prepareTailwind>> | undefined;
|
|
112
|
+
await insertBaseStyles({ document, stylesheets: options.base, timeoutMs: 15000 }).ready;
|
|
113
|
+
if (params.get("mode") === "reference") {
|
|
114
|
+
const response = await fetch(`/reference/${name}`);
|
|
115
|
+
if (!response.ok) throw new Error(await response.text());
|
|
116
|
+
await insertCss({ document, css: await response.text(), timeoutMs: 15000 }).ready;
|
|
117
|
+
} else {
|
|
118
|
+
const storage = await freshStorage("parity");
|
|
119
|
+
runtime = await prepareTailwind({ ...options, root, runtimeVersion: "parity", store: storage.store, timeoutMs: 15000, onError: (error) => { throw error; } });
|
|
120
|
+
}
|
|
121
|
+
const mounted = new Promise<void>((resolve) => {
|
|
122
|
+
function Page() { React.useLayoutEffect(resolve, []); return React.createElement(module.default, { data: options.data }); }
|
|
123
|
+
createRoot(root).render(React.createElement(Page));
|
|
124
|
+
});
|
|
125
|
+
await waitForReadiness({ root, mounted, timeoutMs: 15000, status: () => {} });
|
|
126
|
+
await runtime?.ready();
|
|
127
|
+
const rendered = await snapshot(root);
|
|
128
|
+
if (runtime) {
|
|
129
|
+
const response = await fetch(`/reference/${name}`, { method: "POST", body: root.outerHTML });
|
|
130
|
+
if (!response.ok) throw new Error(await response.text());
|
|
131
|
+
}
|
|
132
|
+
return rendered;
|
|
133
|
+
}
|