mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 05:51:06 +00:00
* feat(build): add non-turbo source-build path for freebsd * test(build): keep direct-build coverage runnable without turbo and reap build children * test(build): use processTest fixture and long-running tag for build tests --------- Co-authored-by: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
460 lines
15 KiB
TypeScript
460 lines
15 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import {
|
|
copyFile,
|
|
mkdir,
|
|
readFile,
|
|
readdir,
|
|
rm,
|
|
symlink,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { createRequire } from "node:module";
|
|
import { dirname, join, relative, sep } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { describe, expect, it } from "vitest";
|
|
import { z } from "zod";
|
|
|
|
import { isTurboPlatformSupported } from "../../../scripts/run-turbo.mjs";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import {
|
|
processTest,
|
|
type TestProcesses,
|
|
} from "../../support/process/processFixture.js";
|
|
import { copyScriptsWithImports } from "../../support/scriptImportClosure.js";
|
|
|
|
const repository = fileURLToPath(new URL("../../../", import.meta.url));
|
|
const turboLauncher = join(repository, "scripts/run-turbo.mjs");
|
|
const require = createRequire(import.meta.url);
|
|
|
|
const turboPackageSchema = z.object({
|
|
version: z.string(),
|
|
optionalDependencies: z.record(z.string(), z.string()),
|
|
});
|
|
const packageJsonSchema = z.object({
|
|
name: z.string(),
|
|
version: z.string(),
|
|
packageManager: z.string(),
|
|
scripts: z.record(z.string(), z.string()),
|
|
});
|
|
const turboConfigSchema = z.object({
|
|
tasks: z.record(
|
|
z.string(),
|
|
z.object({
|
|
dependsOn: z.array(z.string()).optional(),
|
|
}),
|
|
),
|
|
});
|
|
|
|
const pinnedTurboPackage = turboPackageSchema.parse(
|
|
JSON.parse(await readFile(require.resolve("turbo/package.json"), "utf8")),
|
|
);
|
|
|
|
describe("non-Turborepo direct source build", () => {
|
|
it.each([
|
|
["linux", "x64", true],
|
|
["linux", "arm64", true],
|
|
["darwin", "x64", true],
|
|
["darwin", "arm64", true],
|
|
["win32", "x64", true],
|
|
["win32", "arm64", true],
|
|
["android", "x64", true],
|
|
["android", "arm64", true],
|
|
["freebsd", "x64", false],
|
|
["freebsd", "arm64", false],
|
|
["openbsd", "x64", false],
|
|
["netbsd", "x64", false],
|
|
["linux", "riscv64", false],
|
|
])(
|
|
"classifies %s/%s Turborepo binary availability as %s from pinned inventory",
|
|
(platform, arch, expected) => {
|
|
expect(
|
|
isTurboPlatformSupported(
|
|
platform,
|
|
arch,
|
|
pinnedTurboPackage.optionalDependencies,
|
|
),
|
|
).toBe(expected);
|
|
},
|
|
);
|
|
|
|
it("treats missing optionalDependencies as unsupported", () => {
|
|
expect(isTurboPlatformSupported("linux", "x64", undefined)).toBe(false);
|
|
});
|
|
|
|
it("directs unsupported hosts to build:direct unless TURBO_BINARY_PATH is set", async () => {
|
|
const root = await createTestTempDirectory("rea-turbo-unsupported-");
|
|
await mkdir(join(root, "scripts"), { recursive: true });
|
|
await copyFile(turboLauncher, join(root, "scripts/run-turbo.mjs"));
|
|
await copyFile(
|
|
join(repository, "scripts/run-typescript.mjs"),
|
|
join(root, "scripts/run-typescript.mjs"),
|
|
);
|
|
await mkdir(join(root, "node_modules/turbo/bin"), { recursive: true });
|
|
await writeFile(
|
|
join(root, "node_modules/turbo/package.json"),
|
|
JSON.stringify({
|
|
name: "turbo",
|
|
version: "2.11.13",
|
|
optionalDependencies: {},
|
|
}),
|
|
);
|
|
await writeFile(
|
|
join(root, "node_modules/turbo/bin/turbo"),
|
|
'console.log("stub-turbo-ran:" + (process.env.TURBO_BINARY_PATH ?? ""));\n',
|
|
);
|
|
for (const name of ["tsrs", "typescript"])
|
|
await symlink(
|
|
dirname(require.resolve(`${name}/package.json`)),
|
|
join(root, "node_modules", name),
|
|
process.platform === "win32" ? "junction" : undefined,
|
|
);
|
|
|
|
const refused = spawnSync(
|
|
process.execPath,
|
|
[join(root, "scripts/run-turbo.mjs"), "run", "artifacts:skills"],
|
|
{
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
env: { ...process.env, TURBO_BINARY_PATH: undefined },
|
|
},
|
|
);
|
|
expect(refused.error).toBeUndefined();
|
|
expect(refused.status).toBe(1);
|
|
expect(refused.stderr).toContain(
|
|
`does not ship a binary for ${process.platform}/${process.arch}`,
|
|
);
|
|
expect(refused.stderr).toContain("npm run build:direct");
|
|
expect(refused.stdout).not.toContain("stub-turbo-ran");
|
|
|
|
const overridden = spawnSync(
|
|
process.execPath,
|
|
[join(root, "scripts/run-turbo.mjs"), "run", "artifacts:skills"],
|
|
{
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
env: { ...process.env, TURBO_BINARY_PATH: "/custom/turbo" },
|
|
},
|
|
);
|
|
expect(overridden.error).toBeUndefined();
|
|
expect(overridden.status, overridden.stderr).toBe(0);
|
|
expect(overridden.stdout).toContain("stub-turbo-ran:/custom/turbo");
|
|
});
|
|
|
|
it("mirrors turbo.json's artifacts:skills dependency chain without invoking Turborepo", async () => {
|
|
const packageJson = packageJsonSchema.parse(
|
|
JSON.parse(await readFile(join(repository, "package.json"), "utf8")),
|
|
);
|
|
const turboConfig = turboConfigSchema.parse(
|
|
JSON.parse(await readFile(join(repository, "turbo.json"), "utf8")),
|
|
);
|
|
|
|
const buildDirect = packageJson.scripts["build:direct"];
|
|
const buildDirectRun = packageJson.scripts["build:direct:run"];
|
|
expect(buildDirect).toBeDefined();
|
|
expect(buildDirectRun).toBeDefined();
|
|
expect(buildDirect).not.toMatch(/\bturbo\b|run-turbo\.mjs/u);
|
|
expect(buildDirectRun).not.toMatch(/\bturbo\b|run-turbo\.mjs/u);
|
|
expect(buildDirect).toContain("scripts/check-dependency-install.mjs");
|
|
expect(buildDirect).toContain("scripts/run-exclusive.mjs artifacts");
|
|
expect(buildDirect).toContain("npm run build:direct:run");
|
|
|
|
// Walk turbo.json's dependsOn graph for artifacts:skills in topological order.
|
|
const chain: string[] = [];
|
|
const visit = (task: string) => {
|
|
for (const dependency of turboConfig.tasks[task]?.dependsOn ?? [])
|
|
visit(dependency);
|
|
if (!chain.includes(task)) chain.push(task);
|
|
};
|
|
visit("artifacts:skills");
|
|
expect(chain).toEqual(["metadata:check", "compile", "artifacts:skills"]);
|
|
expect(buildDirectRun).toBe(
|
|
chain.map((task) => `npm run ${task}`).join(" && "),
|
|
);
|
|
});
|
|
|
|
processTest(
|
|
"enforces dependency and metadata checks and builds without invoking turbo",
|
|
{ tags: ["long-running"] },
|
|
async ({ processes }) => {
|
|
const directRoot = await createDirectBuildFixture({ poisonTurbo: true });
|
|
|
|
// Stale installed dependency lockfile must fail before compiling.
|
|
const rootLock = z
|
|
.object({
|
|
packages: z.object({
|
|
"": z.object({
|
|
dependencies: z.record(z.string(), z.string()).optional(),
|
|
devDependencies: z.record(z.string(), z.string()).optional(),
|
|
}),
|
|
}),
|
|
})
|
|
.parse(
|
|
JSON.parse(
|
|
await readFile(join(directRoot, "package-lock.json"), "utf8"),
|
|
),
|
|
);
|
|
const directDependency = Object.keys({
|
|
...rootLock.packages[""].dependencies,
|
|
...rootLock.packages[""].devDependencies,
|
|
}).sort()[0];
|
|
if (directDependency === undefined)
|
|
throw new Error("Fixture lockfile has no direct dependencies");
|
|
const lockPath = join(directRoot, "node_modules/.package-lock.json");
|
|
const originalLock = await readFile(lockPath, "utf8");
|
|
const brokenLock = z
|
|
.object({
|
|
packages: z.record(z.string(), z.record(z.string(), z.unknown())),
|
|
})
|
|
.parse(JSON.parse(originalLock));
|
|
const staleEntry =
|
|
brokenLock.packages[`node_modules/${directDependency}`];
|
|
if (staleEntry === undefined)
|
|
throw new Error(`Missing installed ${directDependency}`);
|
|
staleEntry.version = "0.0.0";
|
|
await writeFile(lockPath, JSON.stringify(brokenLock));
|
|
|
|
const staleDeps = await runNpm(processes, directRoot, [
|
|
"run",
|
|
"build:direct",
|
|
]);
|
|
expect(staleDeps.status).toBe(1);
|
|
expect(staleDeps.stderr).toContain(
|
|
"Direct dependency installation is stale",
|
|
);
|
|
await writeFile(lockPath, originalLock);
|
|
|
|
// Stale generated package metadata must fail before compiling.
|
|
const metadataPath = join(directRoot, "src/generatedPackageMetadata.ts");
|
|
const originalMetadata = await readFile(metadataPath, "utf8");
|
|
await writeFile(
|
|
metadataPath,
|
|
"export const PACKAGE_METADATA = {} as const;\n",
|
|
);
|
|
const staleMetadata = await runNpm(processes, directRoot, [
|
|
"run",
|
|
"build:direct",
|
|
]);
|
|
expect(staleMetadata.status).toBe(1);
|
|
expect(`${staleMetadata.stdout}${staleMetadata.stderr}`).toContain(
|
|
"metadata:generate",
|
|
);
|
|
await writeFile(metadataPath, originalMetadata);
|
|
|
|
// Direct build succeeds even with turbo poisoned, and passes skill verification.
|
|
const directResult = await runNpm(processes, directRoot, [
|
|
"run",
|
|
"build:direct",
|
|
]);
|
|
expect(
|
|
directResult.status,
|
|
`${directResult.stdout}${directResult.stderr}`,
|
|
).toBe(0);
|
|
const skillCheck = spawnSync(
|
|
process.execPath,
|
|
[join(directRoot, "scripts/generate-skill-metadata.mjs"), "--check"],
|
|
{ cwd: directRoot, encoding: "utf8" },
|
|
);
|
|
expect(skillCheck.status, skillCheck.stderr).toBe(0);
|
|
},
|
|
);
|
|
|
|
processTest.skipIf(
|
|
!isTurboPlatformSupported(
|
|
process.platform,
|
|
process.arch,
|
|
pinnedTurboPackage.optionalDependencies,
|
|
),
|
|
)(
|
|
"matches build:cached dist and skills outputs on hosts with a Turborepo binary",
|
|
{ tags: ["long-running"] },
|
|
async ({ processes }) => {
|
|
const directRoot = await createDirectBuildFixture({ poisonTurbo: true });
|
|
const directResult = await runNpm(processes, directRoot, [
|
|
"run",
|
|
"build:direct",
|
|
]);
|
|
expect(
|
|
directResult.status,
|
|
`${directResult.stdout}${directResult.stderr}`,
|
|
).toBe(0);
|
|
|
|
const cachedRoot = await createDirectBuildFixture({ poisonTurbo: false });
|
|
const cachedResult = await runNpm(processes, cachedRoot, [
|
|
"run",
|
|
"build:cached",
|
|
]);
|
|
expect(
|
|
cachedResult.status,
|
|
`${cachedResult.stdout}${cachedResult.stderr}`,
|
|
).toBe(0);
|
|
|
|
expect(await treeDigests(join(directRoot, "dist"))).toEqual(
|
|
await treeDigests(join(cachedRoot, "dist")),
|
|
);
|
|
expect(await treeDigests(join(directRoot, "skills"))).toEqual(
|
|
await treeDigests(join(cachedRoot, "skills")),
|
|
);
|
|
},
|
|
);
|
|
});
|
|
|
|
const createDirectBuildFixture = async ({
|
|
poisonTurbo,
|
|
}: {
|
|
readonly poisonTurbo: boolean;
|
|
}): Promise<string> => {
|
|
const root = await createTestTempDirectory("rea-direct-build-");
|
|
const packageJson = packageJsonSchema.parse(
|
|
JSON.parse(await readFile(join(repository, "package.json"), "utf8")),
|
|
);
|
|
const paths = [
|
|
".nvmrc",
|
|
"package-lock.json",
|
|
"turbo.json",
|
|
"tsconfig.json",
|
|
"tsconfig.build.json",
|
|
".agents/skills/reverse-engineer-anything/SKILL.md",
|
|
"src/generatedPackageMetadata.ts",
|
|
];
|
|
await Promise.all(
|
|
paths.map(async (path) => {
|
|
const destination = join(root, path);
|
|
await mkdir(dirname(destination), { recursive: true });
|
|
await copyFile(join(repository, path), destination);
|
|
}),
|
|
);
|
|
await copyScriptsWithImports(
|
|
[
|
|
"scripts/check-dependency-install.mjs",
|
|
"scripts/run-turbo.mjs",
|
|
"scripts/run-typescript.mjs",
|
|
"scripts/run-exclusive.mjs",
|
|
"scripts/run-exclusive-command.mjs",
|
|
"scripts/generate-skill-metadata.mjs",
|
|
"scripts/clean-build-output.mjs",
|
|
"scripts/generate-package-metadata.mjs",
|
|
],
|
|
root,
|
|
repository,
|
|
);
|
|
await writeFile(
|
|
join(root, "package.json"),
|
|
JSON.stringify({
|
|
...packageJson,
|
|
type: "module",
|
|
scripts: {
|
|
...packageJson.scripts,
|
|
compile: "node scripts/direct-fixture-compile.mjs",
|
|
},
|
|
}),
|
|
);
|
|
await writeFile(
|
|
join(root, "scripts/direct-fixture-compile.mjs"),
|
|
`import { mkdir, writeFile } from "node:fs/promises";
|
|
await mkdir("dist/contracts/catalog", { recursive: true });
|
|
await writeFile("dist/main.js", "export const ok = true;\\n");
|
|
await writeFile("dist/contracts/catalog/catalogIdentity.js", "export const DEFAULT_CATALOG_IDENTITY = { counts: { mcp_tools: 3 } };\\n");
|
|
await writeFile("dist/identity.js", ${JSON.stringify(`export const PRODUCT_IDENTITY = ${JSON.stringify({ packageSpecifier: `${packageJson.name}@latest`, registrationPackageSpecifier: `${packageJson.name}@${packageJson.version}` })};\n`)});
|
|
`,
|
|
);
|
|
await createNodeModulesLinks(root, poisonTurbo);
|
|
await writeFile(
|
|
join(root, "node_modules/.package-lock.json"),
|
|
await readFile(join(repository, "node_modules/.package-lock.json")),
|
|
);
|
|
if (poisonTurbo) {
|
|
const turboDir = join(root, "node_modules/turbo");
|
|
await rm(turboDir, { recursive: true, force: true });
|
|
await mkdir(join(turboDir, "bin"), { recursive: true });
|
|
await writeFile(
|
|
join(turboDir, "package.json"),
|
|
JSON.stringify({
|
|
name: "turbo",
|
|
version: "0.0.0",
|
|
optionalDependencies: {},
|
|
}),
|
|
);
|
|
await writeFile(
|
|
join(turboDir, "bin/turbo"),
|
|
'throw new Error("build:direct must not invoke turbo");\n',
|
|
);
|
|
}
|
|
return root;
|
|
};
|
|
|
|
const createNodeModulesLinks = async (
|
|
root: string,
|
|
skipTurbo: boolean,
|
|
): Promise<void> => {
|
|
const source = join(repository, "node_modules");
|
|
const destination = join(root, "node_modules");
|
|
await mkdir(destination);
|
|
for (const entry of await readdir(source, { withFileTypes: true })) {
|
|
if (entry.name === ".package-lock.json") continue;
|
|
if (skipTurbo && entry.name === "turbo") continue;
|
|
const sourcePath = join(source, entry.name);
|
|
const destinationPath = join(destination, entry.name);
|
|
if (entry.name.startsWith("@") && entry.isDirectory()) {
|
|
await mkdir(destinationPath);
|
|
for (const packageName of await readdir(sourcePath))
|
|
await symlink(
|
|
join(sourcePath, packageName),
|
|
join(destinationPath, packageName),
|
|
process.platform === "win32" ? "junction" : undefined,
|
|
);
|
|
} else {
|
|
await symlink(
|
|
sourcePath,
|
|
destinationPath,
|
|
process.platform === "win32" ? "junction" : undefined,
|
|
);
|
|
}
|
|
}
|
|
};
|
|
|
|
const treeDigests = async (
|
|
root: string,
|
|
): Promise<Readonly<Record<string, string>>> => {
|
|
const entries: [string, string][] = [];
|
|
const walk = async (directory: string): Promise<void> => {
|
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
const fullPath = join(directory, entry.name);
|
|
if (entry.isDirectory()) {
|
|
await walk(fullPath);
|
|
} else if (entry.isFile()) {
|
|
const rel = relative(root, fullPath).split(sep).join("/");
|
|
const digest = createHash("sha256")
|
|
.update(await readFile(fullPath))
|
|
.digest("hex");
|
|
entries.push([rel, digest]);
|
|
}
|
|
}
|
|
};
|
|
await walk(root);
|
|
entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
return Object.fromEntries(entries);
|
|
};
|
|
|
|
const runNpm = async (
|
|
processes: TestProcesses,
|
|
cwd: string,
|
|
arguments_: readonly string[],
|
|
): Promise<{
|
|
readonly status: number;
|
|
readonly stdout: string;
|
|
readonly stderr: string;
|
|
}> => {
|
|
const result = await processes.run("npm", arguments_, {
|
|
cwd,
|
|
env: process.env,
|
|
shell: process.platform === "win32",
|
|
});
|
|
return {
|
|
status: result.exitCode ?? 1,
|
|
stdout: result.stdout,
|
|
stderr: result.stderr,
|
|
};
|
|
};
|