Files
RuneStone/scripts/buildBrowserEngine.mjs
T
2026-11-03 00:23:07 -07:00

194 lines
12 KiB
JavaScript

// Builds the browser engine ZIP and pins it in the host. See docs/builds.md#build-the-browser-engine.
// Usage: node scripts/buildBrowserEngine.mjs --release-url <folder URL> [--version <version>] [--dry-run]
import fs from 'node:fs/promises';
import path from 'node:path';
import zlib from 'node:zlib';
import { spawn } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { releaseVersion } from './releaseVersion.mjs';
const exists = file => fs.access(file).then(() => true, () => false);
export const engineFiles = ['browser-runtime/package.json', 'browser-runtime/package-lock.json', 'src-tauri/browser-engine.json'];
export function parseArguments(args) {
const options = { version: undefined, releaseUrl: undefined, dryRun: false };
for (let i = 0; i < args.length; i++) {
if (args[i] === '--dry-run') options.dryRun = true;
else if (args[i] === '--version' && args[i + 1] && !options.version) options.version = args[++i];
else if (args[i] === '--release-url' && args[i + 1] && !options.releaseUrl) options.releaseUrl = args[++i];
else throw Error('Use --release-url followed by the release folder URL, optionally --version followed by the engine version, and optionally --dry-run.');
}
if (!options.releaseUrl) throw Error('Use --release-url followed by the URL of the folder that will hold the engine ZIP.');
return options;
}
/** The platform key of the host manifest, as `browser_engine::platform()` in Rust writes it. */
export function platformKey(platform, arch) {
const system = { win32: 'windows', linux: 'linux', darwin: 'macos' }[platform];
const processor = { x64: 'x86_64', arm64: 'aarch64' }[arch];
if (!system || !processor) throw Error(`Unsupported engine platform: ${platform}-${arch}`);
return `${system}-${processor}`;
}
// Reads the version fields, checks the preconditions, and returns the build plan. Changes no file.
/** @param {string} root @param {{ version?: string, releaseUrl: string }} options @param {{ platform: string, arch: string }} [target] */
export async function planEngineBuild(root, { version, releaseUrl }, target = process) {
const files = engineFiles.map(file => path.join(root, file));
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
const [packageJson, lock, manifest] = before.map(text => JSON.parse(text));
const current = releaseVersion(packageJson.version).version;
const next = releaseVersion(version ?? current).version;
if (lock.version !== current || lock.packages?.['']?.version !== current) throw Error('The engine version fields do not match.');
const protocol = Number(/pub const PROTOCOL: u64 = (\d+);/.exec(await fs.readFile(path.join(root, 'src-tauri/src/browser_engine.rs'), 'utf8'))?.[1]);
const sent = Number(/event: 'ready', protocol: (\d+)/.exec(await fs.readFile(path.join(root, 'browser-runtime/src/engine-main.mjs'), 'utf8'))?.[1]);
if (!protocol || protocol !== sent) throw Error('The engine protocol in browser_engine.rs and engine-main.mjs differs.');
const folder = new URL(releaseUrl.endsWith('/') ? releaseUrl : releaseUrl + '/');
if (folder.protocol !== 'https:' || folder.username || folder.password || folder.search || folder.hash) {
throw Error('Use an HTTPS release URL without credentials, a query, or a fragment.');
}
const { platform, arch } = target;
const file = `RuneStone-Browser_${next}_${platform}-${arch}.zip`;
const releaseDir = path.join(root, 'releases', 'browser-engine', next);
const artifacts = { archive: path.join(releaseDir, file), metadata: path.join(releaseDir, 'engine.json') };
for (const artifact of Object.values(artifacts)) if (await exists(artifact)) throw Error('The release file already exists: ' + artifact);
const dist = path.join(root, 'browser-runtime', 'dist', `RuneStone-Browser-${platform}-${arch}`);
return { root, files, before, current, next, protocol, platform, arch, key: platformKey(platform, arch), file,
url: new URL(file, folder).href, dist, releaseDir, artifacts };
}
export function buildCommands(plan) {
// The same script as `npm --prefix browser-runtime run package`, without a shell.
return [{ step: 'package', command: process.execPath,
args: [path.join(plan.root, 'browser-runtime/scripts/package.mjs'), `--platform=${plan.platform}`, `--arch=${plan.arch}`] }];
}
export function describePlan(plan) {
const relative = file => path.relative(plan.root, file);
return [
`Engine version: ${plan.next} (current ${plan.current}). Protocol: ${plan.protocol}. Platform: ${plan.key}.`,
`1. Write ${plan.next} to ${engineFiles.slice(0, 2).join(' and ')}.`,
...buildCommands(plan).map((entry, index) => `${index + 2}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
`3. Write ${relative(plan.artifacts.archive)} from ${relative(plan.dist)}, and ${relative(plan.artifacts.metadata)}.`,
`4. Pin ${plan.url} in ${engineFiles[2]}.`,
].join('\n');
}
async function listFiles(folder, prefix = '') {
const result = [];
const entries = (await fs.readdir(path.join(folder, prefix), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
for (const entry of entries) {
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) result.push(...await listFiles(folder, name));
else if (entry.isFile()) result.push(name);
else throw Error(`The engine folder contains a link or a special file: ${name}`);
}
return result;
}
/** A ZIP of the files in `folder`, at the archive root, in name order, with a fixed time. The same files give the same bytes. */
export async function zipFolder(folder) {
const chunks = [], central = [];
let offset = 0;
const names = await listFiles(folder);
if (names.length > 65535) throw Error('The engine has too many files for a ZIP without ZIP64.');
for (const name of names) {
const full = path.join(folder, ...name.split('/'));
const [data, stat] = await Promise.all([fs.readFile(full), fs.stat(full)]);
const deflated = zlib.deflateRawSync(data, { level: 9 });
const stored = deflated.length >= data.length;
const body = stored ? data : deflated;
const crc = zlib.crc32(data);
const nameBytes = Buffer.from(name, 'utf8');
if (data.length >= 0xffffffff || offset + 30 + nameBytes.length + body.length >= 0xffffffff) throw Error('The engine is too large for a ZIP without ZIP64.');
// Version 2.0, UTF-8 names, no data descriptor, and the DOS date 1980-01-01 00:00.
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(stored ? 0 : 8, 8);
local.writeUInt16LE(0, 10); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc, 14); local.writeUInt32LE(body.length, 18);
local.writeUInt32LE(data.length, 22); local.writeUInt16LE(nameBytes.length, 26); local.writeUInt16LE(0, 28);
const mode = 0o100000 | (process.platform === 'win32' ? 0o644 : stat.mode & 0o755);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0); entry.writeUInt16LE((3 << 8) | 20, 4); entry.writeUInt16LE(20, 6); entry.writeUInt16LE(0x0800, 8);
entry.writeUInt16LE(stored ? 0 : 8, 10); entry.writeUInt16LE(0, 12); entry.writeUInt16LE(0x21, 14); entry.writeUInt32LE(crc, 16);
entry.writeUInt32LE(body.length, 20); entry.writeUInt32LE(data.length, 24); entry.writeUInt16LE(nameBytes.length, 28);
entry.writeUInt32LE(mode * 0x10000, 38); entry.writeUInt32LE(offset, 42);
chunks.push(local, nameBytes, body);
central.push(entry, nameBytes);
offset += local.length + nameBytes.length + body.length;
}
const directory = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(names.length, 8); end.writeUInt16LE(names.length, 10);
end.writeUInt32LE(directory.length, 12); end.writeUInt32LE(offset, 16);
return Buffer.concat([...chunks, directory, end]);
}
// Runs the build. run(command, args) must reject when a command fails.
// On failure, the version fields and the pin get their previous contents back.
export async function runEngineBuild(plan, run, staging) {
const { files, before, artifacts } = plan;
await fs.mkdir(staging, { recursive: true });
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
let complete = false;
try {
// Electron reports this version with app.getVersion(), so it goes into the package first.
const packageJson = JSON.parse(before[0]);
packageJson.version = plan.next;
const lock = JSON.parse(before[1]);
lock.version = plan.next; lock.packages[''].version = plan.next;
await fs.writeFile(files[0], JSON.stringify(packageJson, null, 2) + '\n');
await fs.writeFile(files[1], JSON.stringify(lock, null, 2) + '\n');
for (const { command, args } of buildCommands(plan)) await run(command, args);
const executable = plan.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser';
if (!(await exists(path.join(plan.dist, executable)))) throw Error('The packaged engine has no engine program: ' + plan.dist);
const archive = await zipFolder(plan.dist);
await fs.mkdir(plan.releaseDir, { recursive: true });
await fs.writeFile(artifacts.archive, archive, { flag: 'wx' });
const sha256 = createHash('sha256').update(archive).digest('hex');
const metadata = { version: plan.next, protocol: plan.protocol, platform: plan.key, file: plan.file, url: plan.url, bytes: archive.length, sha256 };
await fs.writeFile(artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
const previous = JSON.parse(before[2]);
// The packages of other platforms stay only when they have the same engine version.
const platforms = previous.version === plan.next ? { ...previous.platforms } : {};
platforms[plan.key] = { url: plan.url, bytes: archive.length, sha256 };
await fs.writeFile(files[2], JSON.stringify({ version: plan.next, protocol: plan.protocol, platforms }, null, 2) + '\n');
complete = true;
return { archive: artifacts.archive, ...metadata };
} finally {
if (!complete) {
for (let i = 0; i < files.length; i++) {
if ((await fs.readFile(files[i], 'utf8').catch(() => null)) !== before[i]) await fs.writeFile(files[i], before[i]);
}
for (const file of Object.values(artifacts)) {
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
}
console.error('The engine build did not complete. The version fields and the pin are restored. Backups: ' + staging);
}
}
}
async function main() {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const options = parseArguments(process.argv.slice(2));
const plan = await planEngineBuild(root, options);
if (options.dryRun) {
console.log(describePlan(plan));
return;
}
if (process.platform !== 'win32') throw Error('Build the browser engine on Windows. The other platforms have no published engine yet.');
async function run(command, parameters) {
console.log(command + ' ' + parameters.join(' '));
const code = await new Promise((resolve, reject) => {
const child = spawn(command, parameters, { cwd: root, stdio: 'inherit', windowsHide: true });
child.on('error', reject); child.on('exit', resolve);
});
if (code !== 0) throw Error('The engine build command failed with exit code ' + code);
}
const staging = path.join(root, 'output/browser-engine-build', plan.next, new Date().toISOString().replaceAll(':', '-'));
const result = await runEngineBuild(plan, run, staging);
console.log(`Engine available: ${result.archive}\n${result.bytes} bytes, SHA-256 ${result.sha256}\nUpload it to ${result.url}`);
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) await main();