Files
vibemake/scripts/build-cad.mjs
T
2026-11-09 18:43:21 +08:00

95 lines
6.9 KiB
JavaScript

// Publish a self-contained directory mounted at /cad/, separate from the main site.
import { build } from 'esbuild';
import { cpSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { basename, dirname, join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import { readCadEngine, copyCadEngine } from './cad-engine.mjs';
import { versionSiteAssets } from './lib/version-site-assets.mjs';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const DIST = resolve(process.env.VIBEMAKE_CAD_PACKAGE_DIR || join(ROOT, 'dist-cad'));
const ARCHIVE = resolve(process.env.VIBEMAKE_CAD_PACKAGE_ZIP || join(ROOT, 'dist-cad.zip'));
// A CAD build supplies its fresh engine directly instead of using an older local install.
const engine = readCadEngine(process.env.VIBEMAKE_CAD_ENGINE_DIST || join(ROOT, 'cad'));
const contains = (directory, path) => path === directory || path.startsWith(directory + sep);
if (contains(DIST, ROOT) || contains(DIST, engine.root)
|| ['cad', 'js', 'css', 'scripts'].some(path => contains(join(ROOT, path), DIST))) {
throw new Error('CAD package output must not replace the site sources or engine input.');
}
const archiveName = basename(ARCHIVE);
const buildId = Date.now().toString(36);
const pages = [
{ source: 'cad.html', target: 'index.html' },
{ source: 'cad/editor/index.html', target: 'editor/index.html' },
].map(page => ({ ...page, html: readFileSync(join(ROOT, page.source), 'utf8') }));
if (pages.some(page => !/<\/head>/i.test(page.html))) throw new Error('CAD HTML must contain a document head for its import map.');
const importMapSource = readFileSync(join(ROOT, 'index.html'), 'utf8').match(/<script\b[^>]*type=["']importmap["'][^>]*>([\s\S]*?)<\/script>/i);
if (!importMapSource) throw new Error('The site import map is required for the CAD dependencies.');
const importMap = JSON.parse(importMapSource[1]);
// Copy the actual module closure, including lazy imports, without publishing unrelated site pages.
const entryPoints = [...new Set(pages.flatMap(page => [...page.html.matchAll(/<script\b[^>]*src=["']\/(js\/[^"'?#]+\.js)(?:[^"']*)["']/gi)].map(match => match[1])))];
if (!entryPoints.includes('js/cad/app.js')) throw new Error('The CAD application entry is missing from its HTML.');
const graph = await build({
absWorkingDir: ROOT, entryPoints, outdir: join(DIST, 'js'),
bundle: true, format: 'esm', platform: 'browser', packages: 'external',
external: ['/vendor/*'], write: false, metafile: true, logLevel: 'silent',
});
const modules = Object.keys(graph.metafile.inputs);
if (modules.some(path => !path.startsWith('js/') || !path.endsWith('.js') || path.split('/').includes('..'))) {
throw new Error('A CAD application dependency is outside the site JavaScript directory.');
}
// Change static assets only; navigation, API endpoints and existing /cad/ engine URLs stay intact.
const localize = text => text
.replace(/(?<![\w/.])\/(js|css|vendor|assets|data)\//g, '/cad/$1/')
.replace(/(?<![\w/.])\/(favicon\.(?:ico|svg)|apple-touch-icon\.png|icon-\d+\.png)\b/g, '/cad/$1')
.replace(/(["'])((?:robots\/robots|data\/community)\.json)\1/g, '$1/cad/$2$1');
for (const [name, url] of Object.entries(importMap.imports || {})) importMap.imports[name] = localize(url);
const importMapTag = `<script type="importmap">${JSON.stringify(importMap, null, 2)}</script>`;
rmSync(DIST, { recursive: true, force: true });
mkdirSync(DIST, { recursive: true });
const put = (path, text) => {
mkdirSync(dirname(join(DIST, path)), { recursive: true });
writeFileSync(join(DIST, path), text);
};
const copy = path => {
mkdirSync(dirname(join(DIST, path)), { recursive: true });
cpSync(join(ROOT, path), join(DIST, path), { recursive: true, filter: source => !/(^|\/)\.DS_Store$/.test(source) });
};
for (const page of pages) put(page.target, localize(page.html).replace(/<\/head>/i, `${importMapTag}\n</head>`));
for (const file of ['manifest.webmanifest', 'worker.js']) put(file, localize(readFileSync(join(ROOT, 'cad', file), 'utf8')));
for (const file of modules) put(file, localize(readFileSync(join(ROOT, file), 'utf8')));
for (const file of ['css/fonts.css', 'css/style.css', 'css/cad.css']) put(file, localize(readFileSync(join(ROOT, file), 'utf8')));
for (const path of ['vendor', 'assets/brand', 'assets/environments', 'data', 'robots/robots.json', 'favicon.svg', 'favicon.ico', 'apple-touch-icon.png', 'icon-192.png', 'icon-512.png']) copy(path);
copyCadEngine(engine, DIST, { directory: '' });
await versionSiteAssets(DIST, buildId, pages.map(page => page.target), { publicPath: '/cad/' });
writeFileSync(join(DIST, 'build-info.json'), JSON.stringify({
scope: 'cad', buildId, engineBuildId: engine.manifest.buildId,
builtAt: new Date().toISOString(), archive: archiveName, mountPath: '/cad/',
}, null, 2) + '\n');
writeFileSync(join(DIST, 'DEPLOY.md'), `# CAD independent deployment
Extract the contents of ${archiveName} directly into <website-root>/cad/:
mkdir -p /path/to/vibemake/cad
unzip -o /path/to/${archiveName} -d /path/to/vibemake/cad
The ZIP root contains index.html, editor/, js/, css/, vendor/, assets/, icons and the verified engine. It has no enclosing cad/ directory. Do not extract this complete package into the website root.
The result must be <website-root>/cad/index.html and <website-root>/cad/editor/index.html, never cad/cad/. Both directory URLs must serve index.html (configure the static server's directory index). Use HTTP(S), not file://.
All CAD scripts, common styles, fonts and vendor dependencies are included inside cad/. No main-site build or deployment is required. Navigation still links to the main site; authentication and project storage use the existing backend and vm.auth login.
Keep existing cad/_assets/<buildId>/ directories for open editors. Do not delete the website or unrelated modules before extraction.
Check /cad/build-info.json after deployment: buildId=${buildId}, engineBuildId=${engine.manifest.buildId}.
Serve CAD HTML, engine.json, sw.js, worker.js, js/, css/ and vendor/ with Cache-Control: no-cache. Only cad/_assets/<buildId>/ uses immutable caching. Serve WASM as application/wasm.
To update only the engine of an already deployed CAD frontend, merge SolidCraft's dist/vibemake-cad-engine.zip into the website root instead. That engine-only archive has an enclosing cad/ directory, no HTML and cannot provide an initial CAD deployment. Use the complete package when publishing CAD.
`);
mkdirSync(dirname(ARCHIVE), { recursive: true });
const temporaryArchive = join(dirname(ARCHIVE), `.${archiveName}.${buildId}.tmp.zip`);
try {
execFileSync('zip', ['-qr', temporaryArchive, '.'], { cwd: DIST });
execFileSync('unzip', ['-tq', temporaryArchive], { stdio: 'pipe' });
renameSync(temporaryArchive, ARCHIVE);
} finally {
rmSync(temporaryArchive, { force: true });
}
console.log(`CAD package: ${ARCHIVE} (pages ${buildId}, engine ${engine.manifest.buildId})`);