142 lines
6.8 KiB
JavaScript
142 lines
6.8 KiB
JavaScript
#!/usr/bin/env node
|
|
// Generic course episode recorder. Usage:
|
|
// DISPLAY=:2 node .../record.mjs --episode E01 [--smoke]
|
|
// The episode driver performs the real UI actions; this file owns browser,
|
|
// OPFS seeding, X11 capture, markers and session evidence.
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
import { createCourseRecording } from "../carrier-course/lib/recording.mjs";
|
|
import { seedOpfsFromBytes, listOpfsFiles } from "../carrier-course/lib/opfs.mjs";
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const webRoot = path.resolve(here, "../..");
|
|
const args = process.argv.slice(2);
|
|
const option = (name, fallback = "") => {
|
|
const index = args.indexOf(name);
|
|
return index < 0 ? fallback : args[index + 1] ?? fallback;
|
|
};
|
|
const smoke = args.includes("--smoke");
|
|
const episodeId = option("--episode");
|
|
if (!episodeId) throw new Error("--episode is required (for example --episode E01)");
|
|
|
|
const course = JSON.parse(fs.readFileSync(path.join(here, "course.json"), "utf8"));
|
|
const episode = course.episodes.find(item => item.id === episodeId);
|
|
if (!episode) throw new Error(`unknown episode ${episodeId}`);
|
|
const driverPath = path.join(here, "episodes", episodeId, "driver.mjs");
|
|
if (!fs.existsSync(driverPath)) throw new Error(`missing driver ${driverPath}`);
|
|
const script = JSON.parse(fs.readFileSync(path.join(here, "episodes", episodeId, "script.zh.json"), "utf8"));
|
|
// A scene must stay on screen at least as long as its narration; otherwise the
|
|
// assembler trims the tail of the voice-over. Run generate-tts before recording.
|
|
const durationsFile = path.join(here, "episodes", episodeId, "audio-durations.json");
|
|
if (fs.existsSync(durationsFile)) {
|
|
const durations = JSON.parse(fs.readFileSync(durationsFile, "utf8")).scenes ?? {};
|
|
for (const scene of script.scenes) {
|
|
const audio = durations[scene.id]?.duration;
|
|
if (typeof audio === "number") scene.target = Math.max(scene.target ?? 0, Math.ceil(audio + 1.5));
|
|
}
|
|
}
|
|
const rawDir = path.join(here, "raw", episodeId);
|
|
const stillsDir = path.join(here, "stills", episodeId);
|
|
fs.mkdirSync(rawDir, { recursive: true });
|
|
fs.mkdirSync(stillsDir, { recursive: true });
|
|
|
|
const appOrigin = course.appOrigin;
|
|
const projectUrl = `${appOrigin}/project.html?workbench=${encodeURIComponent(episode.workbench)}`;
|
|
const pageForEpisode = () => {
|
|
if (episode.page === "project") return projectUrl;
|
|
if (episode.page === "assembly") return `${appOrigin}/workbench.html?module=Assembly&command=Assembly_CreateAssembly`;
|
|
if (episode.page === "techdraw") return `${appOrigin}/workbench.html?module=TechDraw&command=TechDraw_PageDefault`;
|
|
if (episode.page === "fem") return `${appOrigin}/workbench.html?module=Fem&document=FemDeck`;
|
|
return projectUrl;
|
|
};
|
|
const checkpointName = episode.checkpointIn ? `line-course-${episode.checkpointIn}.FCStd` : null;
|
|
const referenceGlbDir = "/home/mes123456/FreeCADWasmDev/working/GLTFmodel";
|
|
const targetUrl = checkpointName
|
|
? `${pageForEpisode()}&fcstd=${encodeURIComponent(checkpointName)}`
|
|
: pageForEpisode();
|
|
|
|
const rec = createCourseRecording({
|
|
rawDir,
|
|
schema: `freecad-web-line-course/${episodeId}`,
|
|
url: `${appOrigin}/project.html`,
|
|
smoke,
|
|
});
|
|
const page = await rec.open();
|
|
// Reference GLBs stay in working/GLTFmodel and are fulfilled per request, so
|
|
// the 197 MB set is never copied into public/ or dist/.
|
|
await page.route("**/line-glb/*.glb", route => {
|
|
const name = decodeURIComponent(new URL(route.request().url()).pathname.split("/").pop() ?? "");
|
|
const file = path.join(referenceGlbDir, name);
|
|
if (!fs.existsSync(file)) return route.fulfill({ status: 404, body: "missing" });
|
|
return route.fulfill({ status: 200, contentType: "model/gltf-binary", body: fs.readFileSync(file) });
|
|
});
|
|
const driver = await import(pathToFileURL(driverPath).href);
|
|
if (typeof driver.run !== "function") throw new Error(`${driverPath} must export run(context)`);
|
|
|
|
async function waitForProjectReady() {
|
|
if (episode.page && episode.page !== "project") {
|
|
await page.waitForFunction(() => Boolean(window.__freecadWorkbenchState), null, { timeout: 180000 });
|
|
await page.waitForTimeout(800);
|
|
return;
|
|
}
|
|
await page.waitForSelector('select[aria-label="Workbench"]', { timeout: 180000 });
|
|
await page.waitForSelector('[aria-label="Imported native 3D view"]', { timeout: 180000 });
|
|
await page.waitForTimeout(800);
|
|
}
|
|
|
|
try {
|
|
await page.waitForLoadState("domcontentloaded", { timeout: 180000 });
|
|
await page.waitForTimeout(600);
|
|
if (checkpointName) {
|
|
const checkpointPath = path.join(here, "checkpoints", `${episodeId}-in.FCStd`);
|
|
const fallback = path.join(here, "checkpoints", `${episode.checkpointIn}.FCStd`);
|
|
const file = fs.existsSync(checkpointPath) ? checkpointPath : fallback;
|
|
if (!fs.existsSync(file)) throw new Error(`missing checkpoint for ${episodeId}: ${file}`);
|
|
await seedOpfsFromBytes(page, checkpointName, fs.readFileSync(file));
|
|
console.log(JSON.stringify({ seeded: checkpointName, bytes: fs.statSync(file).size }));
|
|
}
|
|
await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 180000 });
|
|
await waitForProjectReady();
|
|
if (!smoke) await rec.startCapture();
|
|
|
|
const context = { page, rec, episode, course, script, stillsDir, rawDir, webRoot, appOrigin, smoke };
|
|
rec.mark("episode-start", { episode: episodeId, url: targetUrl });
|
|
await driver.run(context);
|
|
rec.mark("end", { episode: episodeId });
|
|
|
|
const opfsDocs = await listOpfsFiles(page, "freecad-documents").catch(() => []);
|
|
fs.writeFileSync(path.join(rawDir, "session.json"), `${JSON.stringify({
|
|
schema: `freecad-web-line-course/${episodeId}/session/v1`,
|
|
generatedAt: new Date().toISOString(),
|
|
episode: episodeId,
|
|
title: episode.title,
|
|
url: targetUrl,
|
|
smoke,
|
|
markers: rec.state.markers.length,
|
|
pageErrors: rec.state.pageErrors,
|
|
consoleErrors: rec.state.consoleErrors,
|
|
failedResponses: rec.state.failedResponses,
|
|
opfsDocuments: opfsDocs,
|
|
}, null, 2)}\n`);
|
|
await rec.close();
|
|
console.log(JSON.stringify({
|
|
ok: true,
|
|
episode: episodeId,
|
|
markers: rec.state.markers.length,
|
|
pageErrors: rec.state.pageErrors.length,
|
|
consoleErrors: rec.state.consoleErrors.length,
|
|
opfsDocuments: opfsDocs,
|
|
capture: rec.state.capturePath,
|
|
}));
|
|
process.exitCode = rec.state.pageErrors.length ? 1 : 0;
|
|
} catch (error) {
|
|
rec.mark("failure", { message: String(error?.message ?? error).slice(0, 400) });
|
|
await page.screenshot({ path: path.join(rawDir, "failure.png"), fullPage: false }).catch(() => {});
|
|
const labels = await page.locator(".fc-tree-text").allTextContents().catch(() => []);
|
|
const status = await page.locator("p.status").first().textContent().catch(() => "");
|
|
console.error(JSON.stringify({ ok: false, episode: episodeId, error: String(error?.stack ?? error), labels, status }));
|
|
await rec.close().catch(() => {});
|
|
process.exitCode = 1;
|
|
}
|