Files
RuneStone/tests/unit/release/buildBrowserEngine.spec.ts
T
2026-11-16 04:21:21 -07:00

128 lines
8.3 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm, access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { createHash } from 'node:crypto';
import { buildCommands, describePlan, engineFiles, parseArguments, planEngineBuild, platformKey, runEngineBuild, zipFolder } from '../../../scripts/buildBrowserEngine.mjs';
const repository = path.resolve('.');
const exists = (file: string) => access(file).then(() => true, () => false);
const releaseUrl = 'https://example.com/releases/download/browser-engine';
const windows = { platform: 'win32', arch: 'x64' };
// A copy of the files that the engine script reads.
async function withFixture(body: (root: string, before: string[]) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-engine-build-'));
try {
for (const file of [...engineFiles, 'src-tauri/src/browser_engine.rs', 'browser-runtime/src/engine-main.mjs']) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await copyFile(path.join(repository, file), path.join(root, file));
}
await body(root, await Promise.all(engineFiles.map(file => readFile(path.join(root, file), 'utf8'))));
} finally { await rm(root, { recursive: true, force: true }); }
}
const contents = (root: string) => Promise.all(engineFiles.map(file => readFile(path.join(root, file), 'utf8')));
/** The names and contents of a ZIP, read from its central directory. */
function unzip(archive: Buffer) {
const end = archive.length - 22;
assert.equal(archive.readUInt32LE(end), 0x06054b50);
const count = archive.readUInt16LE(end + 10);
let at = archive.readUInt32LE(end + 16);
const entries: { name: string, data: Buffer, mode: number }[] = [];
for (let i = 0; i < count; i++) {
assert.equal(archive.readUInt32LE(at), 0x02014b50);
const method = archive.readUInt16LE(at + 10), crc = archive.readUInt32LE(at + 16), size = archive.readUInt32LE(at + 20);
const nameLength = archive.readUInt16LE(at + 28), mode = archive.readUInt32LE(at + 38) >>> 16, offset = archive.readUInt32LE(at + 42);
const name = archive.subarray(at + 46, at + 46 + nameLength).toString('utf8');
const start = offset + 30 + archive.readUInt16LE(offset + 26) + archive.readUInt16LE(offset + 28);
const body = archive.subarray(start, start + size);
const data = method === 8 ? zlib.inflateRawSync(body) : Buffer.from(body);
assert.equal(zlib.crc32(data), crc, name);
entries.push({ name, data, mode });
at += 46 + nameLength;
}
return entries;
}
test('the engine script reads its options and maps platform keys', () => {
assert.deepEqual(parseArguments(['--release-url', releaseUrl]), { version: undefined, releaseUrl, dryRun: false });
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.8', '--release-url', releaseUrl]), { version: '0.1.8', releaseUrl, dryRun: true });
for (const args of [[], ['--version', '0.1.8'], ['--release-url'], ['--release-url', releaseUrl, '--release-url', releaseUrl], ['--force']]) assert.throws(() => parseArguments(args));
assert.equal(platformKey('win32', 'x64'), 'windows-x86_64');
assert.equal(platformKey('linux', 'arm64'), 'linux-aarch64');
assert.equal(platformKey('darwin', 'arm64'), 'macos-aarch64');
assert.throws(() => platformKey('aix', 'x64'));
});
test('planning checks the URL, the protocol, and existing releases, and changes no file', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
assert.deepEqual(await contents(root), before);
assert.equal(plan.file, 'RuneStone-Browser_0.1.8_win32-x64.zip');
assert.equal(plan.url, `${releaseUrl}/RuneStone-Browser_0.1.8_win32-x64.zip`);
assert.equal(plan.key, 'windows-x86_64');
assert.match(describePlan(plan), /Pin https:\/\/example\.com\/.*0\.1\.8_win32-x64\.zip in src-tauri\/browser-engine\.json/);
assert.match(buildCommands(plan)[0].args.join(' '), /browser-runtime[\\/]scripts[\\/]package\.mjs --platform=win32 --arch=x64/);
for (const url of ['http://example.com/engine', 'https://user:[email protected]/engine', 'https://example.com/engine?token=1']) {
await assert.rejects(planEngineBuild(root, { version: '0.1.8', releaseUrl: url }, windows), /HTTPS/);
}
await assert.rejects(planEngineBuild(root, { version: '0.1', releaseUrl }, windows), /release version/);
await mkdir(path.dirname(plan.artifacts.archive), { recursive: true });
await writeFile(plan.artifacts.archive, 'old');
await assert.rejects(planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows), /already exists/);
const main = path.join(root, 'browser-runtime/src/engine-main.mjs');
await writeFile(main, (await readFile(main, 'utf8')).replace("event: 'ready', protocol: 1", "event: 'ready', protocol: 2"));
await assert.rejects(planEngineBuild(root, { version: '0.1.9', releaseUrl }, windows), /protocol/);
}));
test('the engine ZIP holds the files at its root, in name order, with the same bytes each time', async () => {
const folder = await mkdtemp(path.join(tmpdir(), 'runestone-engine-zip-'));
try {
await mkdir(path.join(folder, 'locales'), { recursive: true });
await mkdir(path.join(folder, 'resources'), { recursive: true });
await writeFile(path.join(folder, 'RuneStone-Browser.exe'), Buffer.alloc(4096, 7));
await writeFile(path.join(folder, 'locales', 'en-US.pak'), 'strings '.repeat(200));
await writeFile(path.join(folder, 'resources', 'app.asar'), createHash('sha256').update('random').digest());
const first = await zipFolder(folder);
assert.deepEqual(first, await zipFolder(folder));
const entries = unzip(first);
assert.deepEqual(entries.map(entry => entry.name), ['RuneStone-Browser.exe', 'locales/en-US.pak', 'resources/app.asar']);
assert.deepEqual(entries[1].data, Buffer.from('strings '.repeat(200)));
assert.equal(entries[0].mode & 0o170000, 0o100000, 'Each entry is a regular file.');
} finally { await rm(folder, { recursive: true, force: true }); }
});
test('a completed build writes the ZIP, its record, and the pin', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
const versions: string[] = [];
const result = await runEngineBuild(plan, async () => {
versions.push(JSON.parse(await readFile(path.join(root, engineFiles[0]), 'utf8')).version);
await mkdir(plan.dist, { recursive: true });
await writeFile(path.join(plan.dist, 'RuneStone-Browser.exe'), 'engine');
}, path.join(root, 'output/attempt'));
assert.deepEqual(versions, ['0.1.8'], 'The package step sees the new version.');
const archive = await readFile(plan.artifacts.archive);
const sha256 = createHash('sha256').update(archive).digest('hex');
assert.equal(result.sha256, sha256);
assert.deepEqual(JSON.parse(await readFile(plan.artifacts.metadata, 'utf8')), { version: '0.1.8', protocol: plan.protocol, platform: 'windows-x86_64', file: plan.file, url: plan.url, bytes: archive.length, sha256 });
assert.deepEqual(JSON.parse(await readFile(path.join(root, engineFiles[2]), 'utf8')), { version: '0.1.8', protocol: plan.protocol, platforms: { 'windows-x86_64': { url: plan.url, bytes: archive.length, sha256 } } });
const lock = JSON.parse(await readFile(path.join(root, engineFiles[1]), 'utf8'));
assert.equal(lock.version, '0.1.8');
assert.equal(lock.packages[''].version, '0.1.8');
assert.notDeepEqual(await contents(root), before);
}));
test('a failed build restores the version fields and the pin', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
const staging = path.join(root, 'output/attempt');
await assert.rejects(runEngineBuild(plan, async () => { throw Error('packager failed'); }, staging), /packager failed/);
assert.deepEqual(await contents(root), before);
assert.equal(await exists(plan.artifacts.archive), false);
// The package step completes, but the program is missing.
await assert.rejects(runEngineBuild(plan, async () => { await mkdir(plan.dist, { recursive: true }); }, staging), /no engine program/);
assert.deepEqual(await contents(root), before);
assert.equal(await exists(plan.artifacts.metadata), false);
}));