Files
2026-11-09 18:43:21 +08:00

31 lines
2.9 KiB
JavaScript

import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, resolve, sep } from 'node:path';
export function readCadEngine(source) {
if (!source) throw new Error('A CAD engine directory is required. Extract the SolidCraft Web package into the VibeMake project root first.');
const root = resolve(source), manifest = JSON.parse(readFileSync(join(root, 'engine.json'), 'utf8'));
if (manifest.bridgeVersion !== 1 || manifest.engineKind !== 'solidcraft' || manifest.kernel !== 'smlib' || !/^[a-zA-Z0-9_-]+$/.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error('Incompatible CAD engine manifest');
const prefix = `/cad/_assets/${manifest.buildId}/`, names = new Set();
for (const entry of manifest.files) {
if (!entry.path?.startsWith(prefix) || /[?#\\]|(?:^|\/)\.{1,2}(?:\/|$)/.test(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256)) throw new Error('Unsafe CAD engine asset path');
const path = resolve(root, entry.path.slice('/cad/'.length));
if (!path.startsWith(root + sep) || !existsSync(path) || lstatSync(path).isSymbolicLink()) throw new Error('CAD engine asset missing or unsafe');
const bytes = readFileSync(path);
if (bytes.length !== entry.size || createHash('sha256').update(bytes).digest('hex') !== entry.sha256 || names.has(entry.path)) throw new Error('CAD engine asset checksum mismatch');
names.add(entry.path);
}
for (const key of ['js', 'wasm', 'chineseFont']) if (!names.has(manifest[key])) throw new Error(`CAD engine ${key} missing from manifest`);
return { root, manifest };
}
export function copyCadEngine(engine, destination, { directory = 'cad' } = {}) {
const target = join(destination, directory); mkdirSync(join(target, '_assets'), { recursive: true });
cpSync(join(engine.root, '_assets', engine.manifest.buildId), join(target, '_assets', engine.manifest.buildId), { recursive: true });
writeFileSync(join(target, 'engine.json'), JSON.stringify(engine.manifest, null, 2) + '\n');
// This worker only intercepts an exact public asset allowlist; never API, auth or signed URLs.
writeFileSync(join(target, 'sw.js'), cadWorker(engine.manifest));
}
export function cadWorker(manifest) {
const publicFiles = manifest.files.map((f) => f.path);
return `const FILES=new Set(${JSON.stringify(publicFiles)});\nconst CACHE='vm.cad.static.${manifest.buildId}';\nself.addEventListener('install',()=>{});\nself.addEventListener('activate',()=>{});\nself.addEventListener('fetch',event=>{const u=new URL(event.request.url);if(event.request.method!=='GET'||u.origin!==self.location.origin||u.search||!FILES.has(u.pathname))return;event.respondWith((async()=>{const cache=await caches.open(CACHE);const hit=await cache.match(event.request);if(hit)return hit;const response=await fetch(event.request);if(response.ok)await cache.put(event.request,response.clone());return response;})());});\n`;
}