Files
vibemake/js/cad/engine.js
T
2026-11-06 15:54:55 +08:00

84 lines
4.2 KiB
JavaScript

import { CAD } from './config.js';
import { cadError } from './api.js';
import { locale } from './i18n.js';
let engine, workerRegistration;
export function loadEngine() {
return engine ??= start().catch((error) => { engine = null; throw error; });
}
async function start() {
const response = await fetch(CAD.engineManifest, { cache: 'no-store' });
if (!response.ok) throw cadError('ENGINE_MISSING');
const manifest = await response.json();
if (manifest.bridgeVersion !== CAD.bridgeVersion || !/^[a-zA-Z0-9_-]+$/.test(manifest.buildId)) throw cadError('FORMAT_UNSUPPORTED');
const prefix = `/cad/_assets/${manifest.buildId}/`;
for (const key of ['js', 'wasm', 'chineseFont']) if (!manifest[key]?.startsWith(prefix) || /[?#]|\.\./.test(manifest[key])) throw cadError('BAD_RESPONSE');
// Set before WASM starts. Standalone engine builds keep their original behaviour.
window.__VIBEMAKE_CAD__ = { bridgeVersion: 1, buildId: manifest.buildId, locale: locale(), assetBase: prefix, chineseFont: manifest.chineseFont };
const { default: init } = await import(manifest.js);
await init({ module_or_path: manifest.wasm });
const deadline = performance.now() + 90000;
while (!window.vibemakeCad) { if (performance.now() > deadline) throw cadError('ENGINE_TIMEOUT'); await new Promise((r) => setTimeout(r, 30)); }
await window.vibemakeCad.ready();
if ('serviceWorker' in navigator) {
workerRegistration = navigator.serviceWorker.register('/cad/worker.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => {
let notifiedBuild;
const notify = async () => {
try {
const response = await fetch(CAD.engineManifest, { cache: 'no-store' });
if (!response.ok) return;
const latest = await response.json();
// A waiting cache worker does not mean the running engine is outdated.
if (typeof latest.buildId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(latest.buildId) || latest.buildId === manifest.buildId || latest.buildId === notifiedBuild) return;
notifiedBuild = latest.buildId;
window.dispatchEvent(new CustomEvent('vm:cad:update'));
} catch { /* An unavailable update check must not interrupt editing. */ }
};
if (registration.waiting) notify();
const watch = (worker) => {
worker?.addEventListener('statechange', () => { if (worker.state === 'installed' && navigator.serviceWorker.controller) notify(); });
};
watch(registration.installing);
registration.addEventListener('updatefound', () => watch(registration.installing));
return registration;
}).catch(() => null); // Editor remains usable when static caching is unavailable.
}
return window.vibemakeCad;
}
function waitForWorker(worker, states, timeout) {
return new Promise((resolve) => {
const finish = (result) => {
clearTimeout(timer);
worker.removeEventListener('statechange', changed);
resolve(result);
};
const changed = () => {
if (states.includes(worker.state)) finish(true);
else if (worker.state === 'redundant') finish(false);
};
const timer = setTimeout(() => finish(false), timeout);
worker.addEventListener('statechange', changed);
changed();
});
}
// Called only after the editor has completed its unsaved-changes guard.
export async function prepareEngineRefresh() {
if (!('serviceWorker' in navigator)) return;
const registration = await (workerRegistration || navigator.serviceWorker.getRegistration('/cad/'));
if (!registration || registration.scope !== new URL('/cad/', location.href).href) return;
await registration.update();
if (registration.installing && !await waitForWorker(registration.installing, ['installed', 'activated'], 10000)) throw cadError('ENGINE_UPDATE_FAILED');
const worker = registration.waiting;
if (!worker) return;
const activated = waitForWorker(worker, ['activated'], 2000);
worker.postMessage({ type: 'SKIP_WAITING' });
if (!await activated) throw cadError('ENGINE_UPDATE_FAILED');
}
export function downloadBytes(bytes, name) {
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 30000);
}