test(repo): enforce workspace contracts

This commit is contained in:
James
2026-07-11 21:57:45 -07:00
parent 505003e0a6
commit 83db364f81
13 changed files with 420 additions and 86 deletions
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = join(import.meta.dirname, "..");
export const REQUIRED_WORKSPACE_SCRIPTS = ["build", "typecheck", "test"];
function hasExecutableScript(pkg, script) {
return typeof pkg.scripts?.[script] === "string" && pkg.scripts[script].trim().length > 0;
}
function hasSpecificReason(reason) {
return typeof reason === "string" ? reason.trim().length >= 20 : false;
}
function hasDocumentedOptOut(pkg, script) {
const optOut = pkg.hyperframesWorkspaceContract?.[script];
return optOut?.optOut === true && hasSpecificReason(optOut.reason);
}
export function listWorkspaceContractIssues(workspace, pkg) {
return REQUIRED_WORKSPACE_SCRIPTS.flatMap((script) => {
if (hasExecutableScript(pkg, script) || hasDocumentedOptOut(pkg, script)) return [];
return [
`${workspace}: missing executable \`${script}\` script or ` +
`hyperframesWorkspaceContract.${script} opt-out with a specific reason`,
];
});
}
export function listWorkspacePackages(root = ROOT) {
const packagesDir = join(root, "packages");
return readdirSync(packagesDir)
.sort()
.filter((name) => existsSync(join(packagesDir, name, "package.json")))
.map((name) => {
const workspace = `packages/${name}`;
const pkg = JSON.parse(readFileSync(join(root, workspace, "package.json"), "utf8"));
return { workspace, pkg };
});
}
export function checkWorkspaceContracts(root = ROOT) {
return listWorkspacePackages(root).flatMap(({ workspace, pkg }) =>
listWorkspaceContractIssues(workspace, pkg),
);
}
function main() {
const issues = checkWorkspaceContracts();
if (issues.length > 0) {
console.error("Workspace contract violations:");
issues.forEach((issue) => console.error(`- ${issue}`));
process.exitCode = 1;
return;
}
console.log("Workspace contracts verified: build, typecheck, and test are explicit.");
}
if (process.argv[1] === fileURLToPath(import.meta.url)) main();
@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
listWorkspaceContractIssues,
REQUIRED_WORKSPACE_SCRIPTS,
} from "./check-workspace-contracts.mjs";
describe("workspace contract checker", () => {
it("accepts workspaces with all executable lifecycle scripts", () => {
const scripts = Object.fromEntries(REQUIRED_WORKSPACE_SCRIPTS.map((name) => [name, "echo ok"]));
assert.deepEqual(listWorkspaceContractIssues("packages/example", { scripts }), []);
});
it("reports every missing or empty lifecycle script", () => {
assert.deepEqual(
listWorkspaceContractIssues("packages/example", { scripts: { build: " " } }),
REQUIRED_WORKSPACE_SCRIPTS.map(
(script) =>
`packages/example: missing executable \`${script}\` script or ` +
`hyperframesWorkspaceContract.${script} opt-out with a specific reason`,
),
);
});
it("accepts an explicit opt-out only when it has a specific reason", () => {
const pkg = {
scripts: { build: "build", typecheck: "typecheck" },
hyperframesWorkspaceContract: {
test: {
optOut: true,
reason: "Generated fixture validated by the owning package integration suite.",
},
},
};
assert.deepEqual(listWorkspaceContractIssues("packages/example", pkg), []);
pkg.hyperframesWorkspaceContract.test.reason = "no tests";
assert.equal(listWorkspaceContractIssues("packages/example", pkg).length, 1);
});
});
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env node
import { createRequire } from "node:module";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = join(import.meta.dirname, "..");
const PROJECT_ID = "smoke-test";
export const SMOKE_COMPOSITION_HTML =
'<!doctype html><html><body><div data-composition-id="root" data-width="1920" ' +
'data-height="1080" data-duration="1" data-start="0"><div class="clip" ' +
'data-hf-id="title" data-start="0" data-duration="1">Test</div></div></body></html>';
function json(body, status = 200) {
return { status, contentType: "application/json", body: JSON.stringify(body) };
}
function text(body, contentType = "text/plain") {
return { status: 200, contentType, body };
}
const PROJECT_PATH = `/api/projects/${PROJECT_ID}`;
const GET_RESPONSES = new Map([
[
"/api/projects",
json({ projects: [{ id: PROJECT_ID, dir: "/tmp/smoke-test", title: "Smoke test" }] }),
],
[
PROJECT_PATH,
json({
id: PROJECT_ID,
dir: "/tmp/smoke-test",
title: "Smoke test",
files: ["index.html"],
compositions: ["index.html"],
}),
],
[`${PROJECT_PATH}/preview`, text(SMOKE_COMPOSITION_HTML, "text/html")],
[`${PROJECT_PATH}/renders`, json({ renders: [] })],
[`${PROJECT_PATH}/lint`, json({ findings: [] })],
[
`${PROJECT_PATH}/storyboard`,
json({
exists: false,
path: "STORYBOARD.md",
globals: { extra: {} },
frames: [],
warnings: [],
script: { exists: false, path: "SCRIPT.md", content: "" },
}),
],
[`${PROJECT_PATH}/selection`, json({ selection: null, updatedAt: null })],
["/api/registry/blocks", json([])],
["/api/fonts", json({ fonts: [] })],
["/api/fonts/google", json({ fonts: [] })],
["/api/assets/global", json({ assets: [] })],
]);
const MUTATION_RESPONSES = new Map([
[`${PROJECT_PATH}/selection`, json({ ok: true, selection: null, updatedAt: null })],
]);
function projectFileResponse(pathname) {
if (!pathname.startsWith(`${PROJECT_PATH}/files/`)) return undefined;
const filename = decodeURIComponent(pathname.split("/files/")[1] ?? "");
return json({
filename,
content: filename === "index.html" ? SMOKE_COMPOSITION_HTML : "",
});
}
function projectPreviewResponse(pathname) {
if (!pathname.startsWith(`${PROJECT_PATH}/preview/`)) return undefined;
return pathname.endsWith("/.media/manifest.jsonl")
? text("", "application/x-ndjson")
: text(SMOKE_COMPOSITION_HTML, "text/html");
}
function gsapAnimationsResponse(pathname) {
if (!pathname.startsWith(`${PROJECT_PATH}/gsap-animations/`)) return undefined;
return json({ animations: [], timelineVar: "tl", preamble: "", postamble: "" });
}
function getStudioSmokeResponse(pathname) {
return (
GET_RESPONSES.get(pathname) ??
projectFileResponse(pathname) ??
projectPreviewResponse(pathname) ??
gsapAnimationsResponse(pathname)
);
}
function studioSmokeApiPathResponse(method, pathname) {
return method === "GET"
? (getStudioSmokeResponse(pathname) ?? null)
: (MUTATION_RESPONSES.get(pathname) ?? null);
}
export function studioSmokeApiResponse(method, requestUrl) {
const { pathname } = new URL(requestUrl);
return pathname.startsWith("/api/") ? studioSmokeApiPathResponse(method, pathname) : undefined;
}
export function isExpectedStudioSmokeError(message) {
return message.includes("favicon.ico");
}
async function loadPuppeteer() {
const requireFromProducer = createRequire(join(ROOT, "packages", "producer", "package.json"));
return requireFromProducer("puppeteer");
}
export async function runStudioRuntimeSmoke(targetUrl) {
const puppeteer = await loadPuppeteer();
const browser = await puppeteer.launch({
headless: "new",
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
const errors = [];
const unmockedApiRequests = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") errors.push(message.text());
});
await page.setRequestInterception(true);
page.on("request", (request) => {
const response = studioSmokeApiResponse(request.method(), request.url());
if (response === undefined) {
void request.continue();
return;
}
if (response === null) {
unmockedApiRequests.push(`${request.method()} ${new URL(request.url()).pathname}`);
void request.respond(json({ error: "unmocked smoke endpoint" }, 501));
return;
}
void request.respond(response);
});
try {
await page.goto(targetUrl, { waitUntil: "networkidle0", timeout: 30_000 });
await new Promise((resolve) => setTimeout(resolve, 3_000));
const errorBoundary = await page.evaluate(() => {
const textContent = document.body.innerText;
return textContent.includes("Something went wrong") ? textContent : null;
});
if (errorBoundary) errors.push(`React error boundary triggered: ${errorBoundary}`);
} finally {
await browser.close();
}
const fatal = errors.filter((error) => !isExpectedStudioSmokeError(error));
const failures = [
...new Set(unmockedApiRequests.map((request) => `unmocked API request: ${request}`)),
...fatal,
];
if (failures.length > 0) {
throw new Error(
`Studio runtime smoke failed:\n${failures.map((error) => `- ${error}`).join("\n")}`,
);
}
}
async function main() {
const targetUrl = process.argv[2] ?? "http://localhost:5199/#project=smoke-test";
await runStudioRuntimeSmoke(targetUrl);
console.log("PASS: studio loaded with schema-valid API fixtures and no runtime errors");
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}
+58
View File
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
isExpectedStudioSmokeError,
SMOKE_COMPOSITION_HTML,
studioSmokeApiResponse,
} from "./studio-runtime-smoke.mjs";
function bodyOf(method, path) {
const response = studioSmokeApiResponse(method, `http://localhost:5199${path}`);
assert.ok(response && response !== null);
return JSON.parse(response.body);
}
describe("Studio runtime smoke fixtures", () => {
it("matches the collection and project-detail API schemas", () => {
assert.deepEqual(bodyOf("GET", "/api/projects"), {
projects: [{ id: "smoke-test", dir: "/tmp/smoke-test", title: "Smoke test" }],
});
assert.deepEqual(bodyOf("GET", "/api/projects/smoke-test"), {
id: "smoke-test",
dir: "/tmp/smoke-test",
title: "Smoke test",
files: ["index.html"],
compositions: ["index.html"],
});
});
it("returns file content rather than the unrelated file-tree shape", () => {
assert.deepEqual(bodyOf("GET", "/api/projects/smoke-test/files/index.html"), {
filename: "index.html",
content: SMOKE_COMPOSITION_HTML,
});
});
it("returns iterable collections for eager Studio queries", () => {
assert.deepEqual(bodyOf("GET", "/api/projects/smoke-test/renders"), { renders: [] });
assert.deepEqual(bodyOf("GET", "/api/projects/smoke-test/gsap-animations/index.html"), {
animations: [],
timelineVar: "tl",
preamble: "",
postamble: "",
});
assert.deepEqual(bodyOf("GET", "/api/projects/smoke-test/lint"), { findings: [] });
});
it("marks unknown API requests as fixture failures", () => {
assert.equal(studioSmokeApiResponse("GET", "http://localhost:5199/api/new-endpoint"), null);
assert.equal(studioSmokeApiResponse("GET", "http://localhost:5199/src/main.tsx"), undefined);
});
it("does not suppress generic JavaScript or network failures", () => {
assert.equal(isExpectedStudioSmokeError("Cannot read properties of undefined"), false);
assert.equal(isExpectedStudioSmokeError("value is not iterable"), false);
assert.equal(isExpectedStudioSmokeError("Failed to fetch"), false);
assert.equal(isExpectedStudioSmokeError("GET /favicon.ico 404"), true);
});
});