RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
@@ -0,0 +1,127 @@
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);
}));
+131
View File
@@ -0,0 +1,131 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, readdir, rm, access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { buildCommands, describePlan, parseArguments, planInstallerBuild, runInstallerBuild, versionFiles } from '../../../scripts/buildInstaller.mjs';
import { nextHotfix, releaseVersion } from '../../../scripts/releaseVersion.mjs';
const repository = path.resolve('.');
const exists = (file: string) => access(file).then(() => true, () => false);
// A copy of the files that the installer script reads.
async function fixture() {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-build-'));
for (const file of [...versionFiles, 'src-tauri/tauri.windows.conf.json', 'src-tauri/windows/hooks.nsh']) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await copyFile(path.join(repository, file), path.join(root, file));
}
const before = await Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
const current = releaseVersion(JSON.parse(before[0]).version);
return { root, before, current, next: releaseVersion(nextHotfix(current.version)) };
}
const contents = (root: string) => Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
async function withFixture(body: (setup: Awaited<ReturnType<typeof fixture>>) => Promise<void>) {
const setup = await fixture();
try { await body(setup); } finally { await rm(setup.root, { recursive: true, force: true }); }
}
test('the installer script reads --version and --dry-run', () => {
assert.deepEqual(parseArguments([]), { version: undefined, dryRun: false });
assert.deepEqual(parseArguments(['--version', '0.1.44a', '--dry-run']), { version: '0.1.44a', dryRun: true });
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.45']), { version: '0.1.45', dryRun: true });
for (const args of [['--version'], ['0.1.45'], ['--version', '0.1.45', '--version', '0.1.46'], ['--force']]) assert.throws(() => parseArguments(args));
});
test('a completed build sets the version fields only after the installer exists', () => withFixture(async ({ root, before, next }) => {
const plan = await planInstallerBuild(root, next.version);
assert.deepEqual(await contents(root), before, 'Planning must not change a file.');
assert.deepEqual(plan.override, { version: next.toolchain });
const plain = describePlan(plan);
assert.match(plain, new RegExp(`Configuration override: \\{"version":"${next.toolchain.replace('+', '\\+')}"\\}`));
assert.match(plain, /compile: .* build --no-bundle --config .* -- --locked/);
const staging = path.join(root, 'output/attempt');
const overridePath = path.join(staging, 'tauri.version.json');
const calls: { command: string, args: string[], files: string[] }[] = [];
const installer = await runInstallerBuild(plan, async (command: string, args: string[]) => {
calls.push({ command, args, files: await contents(root) });
if (args.includes('bundle')) {
assert.deepEqual(JSON.parse(await readFile(overridePath, 'utf8')), { version: next.toolchain });
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
await writeFile(plan.artifacts.bundled, 'setup');
}
}, staging);
assert.deepEqual(calls.map(({ command, args }) => ({ command, args })),
buildCommands(plan, overridePath).map(({ command, args }) => ({ command, args })));
for (const call of calls) {
// Tauri, Cargo, and the bundler get the version from the override. The front end gets it from plan.env.
assert.deepEqual(call.files, before, 'No version file changes during the build.');
assert.deepEqual(plan.env, { RUNESTONE_VERSION: next.version });
}
assert.equal(installer, path.join(root, 'releases', next.version, `RuneStone_${next.version}_x64-setup.exe`));
assert.equal(await readFile(installer, 'utf8'), 'setup');
assert.equal(await exists(plan.artifacts.bundled), false);
assert.equal(await exists(plan.artifacts.renamed), false);
const metadata = JSON.parse(await readFile(plan.artifacts.metadata, 'utf8'));
assert.deepEqual([metadata.version, metadata.toolchainVersion, metadata.windowsVersion, metadata.bytes], [next.version, next.toolchain, next.windows, 5]);
const after = await contents(root);
assert.deepEqual(after, plan.updated);
assert.equal(JSON.parse(after[0]).version, next.version);
assert.equal(JSON.parse(after[1]).version, next.toolchain);
assert.match(after[2], new RegExp(`^version = "${next.toolchain.replace('+', '\\+')}"`, 'm'));
assert.match(after[2], new RegExp(`\\[package\\.metadata\\.runestone\\]\\r?\\nversion = "${next.version}"`));
assert.match(after[3], new RegExp(`name = "runestone"\\r?\\nversion = "${next.toolchain.replace('+', '\\+')}"`));
}));
test('a failed build leaves the version fields unchanged', () => withFixture(async ({ root, before, next }) => {
for (const failure of ['compile', 'version-resource', 'bundle', 'missing setup file', 'oversized setup file']) {
const plan = await planInstallerBuild(root, next.version);
if (failure === 'oversized setup file') plan.maxSetupBytes = 4;
const staging = path.join(root, 'output', failure.replaceAll(' ', '-'));
const steps = buildCommands(plan, path.join(staging, 'tauri.version.json'));
let index = 0;
const attempt = runInstallerBuild(plan, async () => {
const step = steps[index++].step;
if (step === failure) throw Error('The build command failed with exit code 1');
// A setup file over the size limit, as with a bundled browser engine.
if (step === 'bundle' && failure === 'oversized setup file') {
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
await writeFile(plan.artifacts.bundled, 'setup');
}
}, staging);
await assert.rejects(attempt, failure === 'oversized setup file' ? /more than the limit/ : Error);
assert.deepEqual(await contents(root), before, 'A failure during ' + failure + ' must restore the version fields.');
assert.equal(await exists(plan.artifacts.release), false);
assert.equal(await exists(plan.artifacts.metadata), false);
assert.ok((await readdir(staging)).includes('package.json.before'));
}
}));
test('the plan stops before a build that breaks the release rules', () => withFixture(async ({ root, before, current, next }) => {
const tauriConfig = path.join(root, 'src-tauri/tauri.conf.json');
const windowsConfig = path.join(root, 'src-tauri/tauri.windows.conf.json');
const windowsBefore = await readFile(windowsConfig, 'utf8');
await assert.rejects(planInstallerBuild(root, '0.1.44-rc1'), /release version such as/);
await writeFile(tauriConfig, before[1].replace(`"version": "${current.toolchain}"`, '"version": "9.9.9"'));
await assert.rejects(planInstallerBuild(root, next.version), /do not match/);
await writeFile(tauriConfig, before[1]);
const windows = JSON.parse(windowsBefore);
windows.bundle.windows.allowDowngrades = true;
await writeFile(windowsConfig, JSON.stringify(windows));
await assert.rejects(planInstallerBuild(root, next.version), /Downgrade protection/);
windows.bundle.windows.allowDowngrades = false;
delete windows.bundle.windows.nsis.installerHooks;
await writeFile(windowsConfig, JSON.stringify(windows));
await assert.rejects(planInstallerBuild(root, next.version), /installer hooks/);
await writeFile(windowsConfig, windowsBefore);
const plan = await planInstallerBuild(root, next.version);
await mkdir(plan.releaseDir, { recursive: true });
await writeFile(plan.artifacts.release, 'existing');
await assert.rejects(planInstallerBuild(root, next.version), /already exists/);
await rm(plan.releaseDir, { recursive: true });
// The browser engine is a separate download. The installer must not bundle it.
const config = JSON.parse(before[1]);
config.bundle.resources = { 'browser-engine/': 'browser-engine/' };
await writeFile(tauriConfig, JSON.stringify(config));
await assert.rejects(planInstallerBuild(root, next.version), /must not bundle the browser engine/);
await writeFile(tauriConfig, before[1]);
assert.deepEqual(await contents(root), before);
}));
+41
View File
@@ -0,0 +1,41 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { checkChunks, featureModule, staticClosure } from "../../../scripts/featureChunks.mjs";
const root = "D:/RuneStone/";
const chunk = (fileName: string, fields: Record<string, unknown> = {}) => ({ fileName, isEntry: false, isDynamicEntry: false, facadeModuleId: null, imports: [], moduleIds: [], size: 10, ...fields });
test("the static closure follows imports from each entry, and not dynamic imports", () => {
const chunks = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("node.js", { isEntry: true }),
chunk("shared.js", { imports: ["deep.js"] }),
chunk("deep.js"),
chunk("git.js", { isDynamicEntry: true, imports: ["shared.js"] }),
];
assert.deepEqual([...staticClosure(chunks)].sort(), ["app.js", "deep.js", "node.js", "shared.js"]);
});
test("feature folders and feature libraries count as feature modules, and the runtime does not", () => {
assert.equal(featureModule(`${root}src/lib/features/git/index.ts`), true);
assert.equal(featureModule("D:\\RuneStone\\src\\lib\\features\\git\\model.ts"), true);
assert.equal(featureModule(`${root}src/lib/features/catalog.ts`), false);
assert.equal(featureModule(`${root}node_modules/.pnpm/@[email protected]/node_modules/@xterm/xterm/lib/xterm.mjs`), true);
assert.equal(featureModule(`${root}node_modules/pdfjs-dist/build/pdf.mjs`), true);
assert.equal(featureModule(`${root}node_modules/svelte/src/index.js`), false);
});
test("a feature module in a start chunk fails, and a separate dynamic chunk passes", () => {
const good = [
chunk("app.js", { isEntry: true, moduleIds: [`${root}src/lib/features/catalog.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts`, moduleIds: [`${root}src/lib/features/git/index.ts`], size: 2048 }),
];
assert.deepEqual(checkChunks(good, ["git"]), { problems: [], sizes: { git: 2048 } });
const bad = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("shared.js", { moduleIds: [`${root}src/lib/features/git/model.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts` }),
];
assert.deepEqual(checkChunks(bad, ["git"]).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })], ["git"]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
});
+309
View File
@@ -0,0 +1,309 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from 'node:fs/promises';
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { releaseVersion, nextHotfix, compareReleases } from '../../../scripts/releaseVersion.mjs';
const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24'];
const hooks = path.resolve('src-tauri/windows/hooks.nsh');
test('hotfix versions retain their release identity and advance in letter order', () => {
assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' });
for (const [before, after] of [['0.1.23', '0.1.23a'], ['0.1.23a', '0.1.23b'], ['0.1.23b', '0.1.23c'], ['0.1.23z', '0.1.23aa'], ['0.1.23aa', '0.1.23ab'], ['0.1.23zz', '0.1.23aaa']]) assert.equal(nextHotfix(before), after);
for (const version of ['0.1.23A', '0.1.23a1', '0.1.23-a', '0.1.23+1', '0.1', '0.1.23aaaaa', '0.1.65536']) assert.throws(() => releaseVersion(version));
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j));
});
test('the Windows configuration uses the RuneStone hooks with the stock template', async () => {
const config = JSON.parse(await readFile('src-tauri/tauri.conf.json', 'utf8'));
const windows = JSON.parse(await readFile('src-tauri/tauri.windows.conf.json', 'utf8')).bundle.windows;
assert.equal(windows.allowDowngrades, false);
assert.equal(windows.nsis.template, undefined, 'Use the stock Tauri template. Put RuneStone behavior in the hooks.');
assert.equal(path.resolve('src-tauri', windows.nsis.installerHooks), hooks);
// The hooks read SHCTX as HKCU and use the uninstall key of the product name.
assert.equal(windows.nsis.installMode, 'currentUser');
const source = await readFile(hooks, 'utf8');
assert.ok(source.includes(`!define /ifndef RUNESTONE_UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${config.productName}"`));
});
// The Tauri CLI embeds its NSIS template. These checks fail when a Tauri update changes what the hooks rely on.
function stockTemplate() {
const cli = createRequire(realpathSync('node_modules/@tauri-apps/cli/package.json'));
let binary: string;
try { binary = cli.resolve('@tauri-apps/cli-win32-x64-msvc'); } catch { return null; }
const bytes = readFileSync(binary);
const start = bytes.indexOf('Unicode true\r\nManifestDPIAware true');
assert.ok(start >= 0, 'The Tauri CLI no longer contains the expected NSIS template.');
let end = start;
while (end < bytes.length && (bytes[end] === 9 || bytes[end] === 10 || bytes[end] === 13 || (bytes[end] >= 32 && bytes[end] < 127))) end++;
return bytes.subarray(start, end).toString('latin1').replaceAll('\r\n', '\n');
}
const template = process.platform === 'win32' ? stockTemplate() : null;
test('the stock Tauri template still provides what the hooks rely on', { skip: template ? false : 'needs the Windows Tauri CLI' }, () => {
const text = template!;
const at = (fragment: string) => {
const index = text.indexOf(fragment);
assert.ok(index >= 0, 'The stock template no longer contains: ' + fragment);
return index;
};
// NSIS_HOOK_POSTUNINSTALL removes the downloaded engine. It needs ${BUNDLEID}, $UpdateMode, and its place after the app data step.
const removal = at('RmDir /r "$LOCALAPPDATA\\${BUNDLEID}"');
assert.ok(text.indexOf('${AndIf} $UpdateMode <> 1') < removal);
assert.ok(removal < at('!insertmacro NSIS_HOOK_POSTUNINSTALL'), 'The uninstall hook must run after the app data step.');
const include = at('!include "{{installer_hooks}}"');
assert.ok(include < at('!insertmacro MUI_PAGE_WELCOME'), 'Tauri must include the hooks before the first page.');
assert.ok(include < at('\nSection EarlyChecks'), 'Tauri must include the hooks before its first section.');
assert.ok(include < at('\nVar '), 'The hooks file cannot use the template variables.');
at('!define UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${PRODUCTNAME}"');
// RuneStoneInstallerVersion reads the version resource.
at('VIProductVersion "${VERSIONWITHBUILD}"');
assert.ok(!text.includes('VIFileVersion'));
assert.ok(!text.includes('MUI_CUSTOMFUNCTION_GUIINIT') && !text.includes('.onGUIInit'), 'The hooks define the GUI initialization function.');
// RuneStoneGuiInit makes the maintenance page skip itself. That page must look for the installation in SHCTX.
const page = text.slice(at('Function PageReinstall\n'), at('Function PageReinstallUpdateSelection'));
for (const line of ['ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""', 'ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"', '${IfThen} "$R0$R1" == "" ${|} Abort ${|}']) {
assert.ok(page.includes(line), 'PageReinstall no longer contains: ' + line);
}
// No installer code may change the context between RuneStoneGuiInit and the RuneStoneVersionCheck section.
const install = text.slice(0, at('Function un.onInit'));
assert.ok(!install.includes('SetShellVarContext'), 'The installer part of the template now changes the shell context.');
assert.ok(text.slice(at('Function .onInit'), at('Section EarlyChecks')).includes('!insertmacro SetContext'));
const section = text.slice(at('Section Install\n'), at('Function .onInstSuccess'));
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') >= 0);
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') < section.indexOf('!insertmacro NSIS_HOOK_POSTINSTALL'), 'The hook must write DisplayVersion after the template.');
});
const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe');
const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; Tauri downloads it during the first installer build';
function compile(script: string, source: string) {
const built = spawnSync(makensis, ['/V2', script], { input: undefined, encoding: 'utf8', windowsHide: true });
assert.equal(built.status, 0, source + '\n' + built.stdout + built.stderr);
}
test('the hook functions convert versions in release order', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
try {
const results = path.join(root, 'results.txt');
const valid = new Map<string, string>([['65535.0.0.65535', '65535.0.0.65535'], ['0.1.23', '0.1.23.0']]);
for (const version of ordering) {
const { toolchain, windows } = releaseVersion(version);
valid.set(toolchain, windows);
valid.set(windows, windows);
}
const invalid = ['', '0.1.23a', '0.1.23A', '0.1.23-rc', '0.1', '0.1.', '.1.2', '1..2.3', '0.1.23+', '0.1.23+1.2', '1.2+3',
'0.1.23.1.0', '0.1.65536', '0.1.23+65536', '0.1.23.65536', 'garbage', ' 0.1.23', '0.1.23 ', '0x1.2.3'];
const lines = ['FileOpen $9 "' + results + '" w'];
for (const input of [...valid.keys(), ...invalid]) lines.push(`Push "${input}"`, 'Call RuneStoneNumericVersion', 'Pop $0', `FileWrite $9 "numeric|${input}|$0$\\n"`);
for (const version of ordering) lines.push(`Push "${releaseVersion(version).windows}"`, 'Call RuneStoneReleaseName', 'Pop $0', `FileWrite $9 "release|${version}|$0$\\n"`);
for (const left of ordering) for (const right of ordering) {
lines.push(`\${VersionCompare} "${releaseVersion(left).windows}" "${releaseVersion(right).windows}" $0`, `FileWrite $9 "compare|${left}|${right}|$0$\\n"`);
}
lines.push('FileClose $9');
const executable = path.join(root, 'functions.exe');
const script = path.join(root, 'functions.nsi');
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone hook functions"\nOutFile "${executable}"\n` +
`!define RUNESTONE_UNINSTKEY "Software\\RuneStoneInstallerTest-${path.basename(root)}"\n!include "${hooks}"\nSection\n${lines.join('\n')}\nSectionEnd\n`;
await writeFile(script, source);
compile(script, source);
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(checked.status, 0);
const output = (await readFile(results, 'utf8')).trim().split('\n').map(line => line.split('|'));
const numeric = new Map(output.filter(row => row[0] === 'numeric').map(row => [row[1], row[2]]));
for (const [input, expected] of valid) assert.equal(numeric.get(input), expected, 'RuneStoneNumericVersion ' + input);
for (const input of invalid) assert.equal(numeric.get(input), '', 'RuneStoneNumericVersion must reject ' + JSON.stringify(input));
for (const row of output.filter(row => row[0] === 'release')) assert.equal(row[2], row[1], 'RuneStoneReleaseName ' + row[1]);
for (const [, left, right, result] of output.filter(row => row[0] === 'compare')) {
// VersionCompare returns 0 for equal versions, 1 when the first is newer, and 2 when the second is newer.
assert.equal(result, String([0, 1, 2].at(compareReleases(left, right))), `VersionCompare ${left} ${right}`);
}
assert.equal(output.filter(row => row[0] === 'compare').length, ordering.length ** 2);
// Tauri cannot write a letter suffix into the version strings of the app executable.
const patchedExe = path.join(root, 'patched.exe');
await copyFile(executable, patchedExe);
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', patchedExe, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
assert.equal(patched.status, 0, patched.stdout + patched.stderr);
assert.match(patched.stdout, /0\.1\.23a/);
} finally {
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
await rm(root, { recursive: true, force: true });
}
});
// Each test installer has the version resource that Tauri writes for its version, and the stock template
// layout: Modern UI, then the hooks, then the pages and an Install section that ends with NSIS_HOOK_POSTINSTALL.
// The installed version comes from a test-only registry key. Nothing forces an internal variable.
test('the hooks block downgrades in every installer mode', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-hooks-'));
const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root);
const reg = (...args: string[]) => spawnSync('reg', args, { encoding: 'utf8', windowsHide: true });
const installed = () => {
const result = reg('query', 'HKCU\\' + key);
const values: Record<string, string> = {};
if (result.status === 0) for (const match of result.stdout.matchAll(/^\s+(\S+)\s+REG_SZ\s+(.*?)\s*$/gm)) values[match[1]] = match[2];
return values;
};
const setInstalled = (values: Record<string, string>) => {
reg('delete', 'HKCU\\' + key, '/f');
for (const [name, value] of Object.entries(values)) assert.equal(reg('add', 'HKCU\\' + key, '/v', name, '/d', value, '/f').status, 0);
};
const installers = new Map<string, string>();
const installer = async (version: string) => {
if (installers.has(version)) return installers.get(version)!;
const { toolchain, windows } = releaseVersion(version);
const executable = path.join(root, `setup-${version}.exe`);
const script = path.join(root, `setup-${version}.nsi`);
const source = `Unicode true
RequestExecutionLevel user
Name "RuneStone hook test"
OutFile "${executable}"
InstallDir "${path.join(root, 'install')}"
AutoCloseWindow true
VIProductVersion "${windows}"
VIAddVersionKey "ProductName" "RuneStone hook test"
VIAddVersionKey "FileDescription" "RuneStone hook test"
VIAddVersionKey "LegalCopyright" "Test"
VIAddVersionKey "FileVersion" "${toolchain}"
VIAddVersionKey "ProductVersion" "${toolchain}"
!define RUNESTONE_UNINSTKEY "${key}"
; Record the notice instead of opening a message box.
!macro RUNESTONE_DOWNGRADE_NOTICE
\${IfNot} \${Silent}
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestNotice" "shown"
\${EndIf}
!macroend
!include MUI2.nsh
!include "${hooks}"
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipPage
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
; In the stock template, the maintenance page that can start the uninstaller follows the first page.
; That page skips itself when it cannot find the installation in SHCTX.
Function SkipPage
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestFirstPage" "shown"
ReadRegStr $0 SHCTX "\${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion"
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestPageFound" "[$0]"
Abort
FunctionEnd
Section Install
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "DisplayVersion" "${toolchain}"
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "TestLocalAppData" "$LOCALAPPDATA"
!insertmacro NSIS_HOOK_POSTINSTALL
SectionEnd
`;
await writeFile(script, source);
compile(script, source);
installers.set(version, executable);
return executable;
};
const install = async (version: string, flags: string[]) =>
spawnSync(await installer(version), flags, { encoding: 'utf8', windowsHide: true, timeout: 60000 }).status;
const silent = (flags: readonly string[]) => flags.includes('/S');
try {
// Installer 0.1.23a over 0.1.23b. Without /S, the check runs before the first page.
for (const flags of [['/S'], ['/S', '/UPDATE'], ['/S', '/P'], ['/P'], ['/P', '/UPDATE'], []]) {
setInstalled({ RuneStoneWindowsVersion: '0.1.23.2', DisplayVersion: '0.1.23b' });
assert.equal(await install('0.1.23a', flags), 2, 'A downgrade must stop with exit code 2: ' + (flags.join(' ') || 'interactive'));
const values = installed();
assert.equal(values.DisplayVersion, '0.1.23b', 'A blocked setup must not install.');
assert.equal(values.TestNotice, silent(flags) ? undefined : 'shown');
assert.equal(values.TestFirstPage, undefined, 'Setup must stop before the first page.');
}
// Earlier installers wrote only the toolchain version to DisplayVersion.
for (const [previous, version, code] of [['0.1.24', '0.1.23z', 2], ['0.1.23+1', '0.1.23', 2], ['0.1.23+1', '0.1.23a', 0], ['0.1.23+1', '0.1.23b', 0]] as const) {
setInstalled({ DisplayVersion: previous });
assert.equal(await install(version, ['/S']), code, `${version} over ${previous}`);
}
// An unknown installed version blocks setup.
for (const values of [{ RuneStoneWindowsVersion: '0.1.23b' }, { DisplayVersion: '0.1.23b' }, { DisplayVersion: '0.1.23-beta' }, { DisplayVersion: 'garbage' }] as Record<string, string>[]) {
setInstalled(values);
assert.equal(await install('0.1.24', ['/S']), 2, 'Unknown installed version ' + JSON.stringify(values));
}
// Same version, upgrade, and first installation. Each writes the literal release version.
for (const [previous, version, flags] of [['0.1.23.1', '0.1.23a', ['/S']], ['0.1.23.1', '0.1.23a', []], ['0.1.23.26', '0.1.23aa', ['/P', '/UPDATE']], [null, '0.1.24', ['/S']]] as const) {
setInstalled(previous ? { RuneStoneWindowsVersion: previous } : {});
assert.equal(await install(version, [...flags]), 0, `${version} over ${previous ?? 'no installation'} with ${flags.join(' ') || 'interactive'}`);
const values = installed();
assert.equal(values.DisplayVersion, version, 'Installed apps must show the release version.');
assert.equal(values.RuneStoneReleaseVersion, version);
assert.equal(values.RuneStoneWindowsVersion, releaseVersion(version).windows);
assert.equal(values.TestNotice, undefined);
// Without /S, the pages must not find the installation, so that setup replaces it in place.
assert.equal(values.TestPageFound, silent(flags) ? undefined : '[]');
// RuneStoneGuiInit switches to the "all" context. The sections must run in the current-user context again.
assert.equal(values.TestLocalAppData?.toLowerCase(), process.env.LOCALAPPDATA!.toLowerCase());
}
} finally {
reg('delete', 'HKCU\\' + key, '/f');
assert.equal(reg('query', 'HKCU\\' + key).status, 1, 'The test registry key must be removed.');
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-hooks-')), true);
await rm(root, { recursive: true, force: true });
}
});
// NSIS_HOOK_POSTINSTALL removes the engine folder that releases up to 0.1.48 put in the installation folder.
// NSIS_HOOK_POSTUNINSTALL removes the downloaded engine, keeps the browser profiles, and keeps everything during an update.
test('the hooks remove old and downloaded browser engines but keep the profiles', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-engine-'));
const bundle = 'com.runestone.hook-test-' + path.basename(root);
const local = path.join(process.env.LOCALAPPDATA!, bundle);
const install = path.join(root, 'install');
const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root);
const program = async (name: string, updateMode: number) => {
const executable = path.join(root, name + '.exe'), script = path.join(root, name + '.nsi');
const source = `Unicode true
SilentInstall silent
RequestExecutionLevel user
Name "RuneStone engine hook test"
OutFile "${executable}"
InstallDir "${install}"
VIProductVersion "0.1.49.0"
VIAddVersionKey "ProductName" "RuneStone engine hook test"
VIAddVersionKey "FileVersion" "0.1.49"
VIAddVersionKey "ProductVersion" "0.1.49"
!define RUNESTONE_UNINSTKEY "${key}"
!define BUNDLEID "${bundle}"
!include "${hooks}"
Var UpdateMode
Section Install
StrCpy $UpdateMode ${updateMode}
!insertmacro NSIS_HOOK_POSTINSTALL
!insertmacro NSIS_HOOK_POSTUNINSTALL
SectionEnd
`;
await writeFile(script, source);
compile(script, source);
return executable;
};
const seed = async () => {
await mkdir(path.join(install, 'browser-engine', 'locales'), { recursive: true });
await writeFile(path.join(install, 'browser-engine', 'RuneStone-Browser.exe'), 'old engine');
await writeFile(path.join(install, 'runestone.exe'), 'app');
await mkdir(path.join(local, 'browser-engine', '0.1.8'), { recursive: true });
await writeFile(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe'), 'engine');
await mkdir(path.join(local, 'browser'), { recursive: true });
await writeFile(path.join(local, 'browser', 'browser.json'), '{}');
};
try {
await seed();
assert.equal(spawnSync(await program('remove', 0), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0);
assert.equal(existsSync(path.join(install, 'browser-engine')), false, 'Setup removes the old engine folder.');
assert.equal(existsSync(path.join(install, 'runestone.exe')), true);
assert.equal(existsSync(path.join(local, 'browser-engine')), false, 'Uninstall removes the downloaded engine.');
assert.equal(existsSync(path.join(local, 'browser', 'browser.json')), true, 'The profiles stay.');
await seed();
assert.equal(spawnSync(await program('update', 1), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0);
assert.equal(existsSync(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe')), true, 'An update keeps the downloaded engine.');
} finally {
spawnSync('reg', ['delete', 'HKCU\\' + key, '/f'], { windowsHide: true });
assert.equal(local.startsWith(process.env.LOCALAPPDATA!) && path.basename(local).startsWith('com.runestone.hook-test-'), true);
await rm(local, { recursive: true, force: true });
await rm(root, { recursive: true, force: true });
}
});
+167
View File
@@ -0,0 +1,167 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { inflateSync } from 'node:zlib';
import { checkTarget, INSTALLED_EXE, markdownTable, median, parseArguments, processTree, summarize } from '../../../scripts/measure/core.mjs';
import { crc32, encodePng, gradientPixel, PNG_SIGNATURE, readPngChunks } from '../../../scripts/measure/png.mjs';
import { readPdfXref, writePdf } from '../../../scripts/measure/pdf.mjs';
import { cardFileName, pmFiles, seededUuid } from '../../../scripts/measure/fixture.mjs';
const required = ['--exe', 'build/runestone.exe', '--identifier', 'com.runestone.phase7-ram', '--stage', 'reference', '--mode', 'plugin', '--features', 'git,pdf'];
const env = { APPDATA: 'C:\\Users\\Test\\AppData\\Roaming', LOCALAPPDATA: 'C:\\Users\\Test\\AppData\\Local' };
test('the measurement tool reads its arguments and their defaults', () => {
const options = parseArguments(required);
assert.equal(options.exe, 'build/runestone.exe');
assert.equal(options.identifier, 'com.runestone.phase7-ram');
assert.deepEqual(options.features, ['git', 'pdf']);
assert.equal(options.runs, 3);
assert.equal(options.port, 9241);
assert.equal(options.freshFixture, false);
const custom = parseArguments([...required, '--runs', '5', '--port', '9300', '--fresh-fixture', '--only', 'base,git:in-use']);
assert.equal(custom.runs, 5);
assert.equal(custom.port, 9300);
assert.equal(custom.freshFixture, true);
assert.deepEqual(custom.only, ['base', 'git:in-use']);
assert.deepEqual(parseArguments([...required.slice(0, 8), '--features', 'git,git, pm']).features, ['git', 'pm']);
});
test('the measurement tool rejects missing, repeated, and unknown arguments', () => {
for (const args of [
[],
required.slice(0, -2),
[...required, '--runs'],
[...required, '--runs', 'three'],
[...required, '--runs', '0'],
[...required, '--port', '80'],
[...required, '--mode', 'native'],
[...required, '--force'],
[...required.slice(0, 6), '--mode', 'hybrid', '--features', 'git'],
[...required.slice(0, 8), '--features', 'git,editor'],
[...required.slice(0, 4), '--stage', '../escape', '--mode', 'plugin', '--features', 'git'],
[...required, '--only', 'pm:in-use'],
[...required, '--only', 'git:busy'],
]) assert.throws(() => parseArguments(args), Error, args.join(' '));
});
test('the measurement tool refuses the installed app and its identifier', () => {
assert.throws(() => checkTarget({ exe: INSTALLED_EXE, identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: INSTALLED_EXE.toUpperCase(), identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\other.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
for (const identifier of ['com.runestone.app', 'COM.RUNESTONE.APP', 'com.example.test', 'com.runestone.', 'com.runestone.../x', 'com.runestone.Test', undefined])
assert.throws(() => checkTarget({ exe: 'D:\\build\\runestone.exe', identifier }, env), /Refusing the identifier/, String(identifier));
assert.deepEqual(checkTarget({ exe: 'D:\\build\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), {
roaming: 'C:\\Users\\Test\\AppData\\Roaming\\com.runestone.phase7-ram',
local: 'C:\\Users\\Test\\AppData\\Local\\com.runestone.phase7-ram',
});
});
test('the median ignores missing values and averages the two middle values', () => {
assert.equal(median([]), null);
assert.equal(median([null, undefined, Number.NaN]), null);
assert.equal(median([3, 1, 2]), 2);
assert.equal(median([4, 1, 3, 2]), 2.5);
assert.equal(median([5, null, 1]), 3);
const summary: Record<string, number | null> = summarize([{ privateMB: 100, startMs: 900 }, { privateMB: 120, startMs: 1100 }, { error: 'failed', privateMB: 999 }]);
assert.equal(summary.runs, 3);
assert.equal(summary.failed, 1);
assert.equal(summary.privateMB, 110);
assert.equal(summary.startMs, 1000);
});
test('the process tree walk sums only the descendants of the started process', () => {
const list = [
{ ProcessId: 4, ParentProcessId: 0, Name: 'System', PrivatePageCount: 1, WorkingSetSize: 1, Created: 1 },
{ ProcessId: 100, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 10, WorkingSetSize: 20, Created: 10 },
{ ProcessId: 101, ParentProcessId: 100, Name: 'msedgewebview2.exe', PrivatePageCount: 30, WorkingSetSize: 40, Created: 11 },
{ ProcessId: 102, ParentProcessId: 101, Name: 'msedgewebview2.exe', PrivatePageCount: 50, WorkingSetSize: 60, Created: 12 },
{ ProcessId: 103, ParentProcessId: 100, Name: 'pwsh.exe', PrivatePageCount: 5, WorkingSetSize: 6, Created: 13 },
// The installed app, a sibling tree that the walk must not count.
{ ProcessId: 200, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 },
{ ProcessId: 201, ParentProcessId: 200, Name: 'msedgewebview2.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 },
// A process whose parent ID was reused: it started before the process with that ID.
{ ProcessId: 104, ParentProcessId: 100, Name: 'stale.exe', PrivatePageCount: 7, WorkingSetSize: 7, Created: 5 },
];
const tree = processTree(list, 100);
assert.deepEqual(tree.processes.map(item => item.ProcessId), [100, 101, 103, 102]);
assert.equal(tree.privateBytes, 95);
assert.equal(tree.workingSet, 126);
assert.equal(tree.count, 4);
assert.deepEqual(tree.names, { 'runestone.exe': 1, 'msedgewebview2.exe': 2, 'pwsh.exe': 1 });
assert.equal(processTree(list, 999).count, 0);
// A cycle in a stale process list does not loop.
assert.equal(processTree([{ ProcessId: 1, ParentProcessId: 2, Name: 'a' }, { ProcessId: 2, ParentProcessId: 1, Name: 'b' }], 1).count, 2);
});
test('the PNG writer gives a valid signature, chunk CRCs, and pixel data', () => {
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926);
const png = encodePng(4, 3, gradientPixel(4, 3, [0, 0, 0], [255, 255, 255], 0));
assert.ok(png.subarray(0, 8).equals(PNG_SIGNATURE));
const chunks = readPngChunks(png);
assert.deepEqual(chunks.map(chunk => chunk.type), ['IHDR', 'IDAT', 'IEND']);
for (const chunk of chunks) assert.equal(chunk.stored, chunk.computed, chunk.type);
assert.equal(chunks[0].data.readUInt32BE(0), 4);
assert.equal(chunks[0].data.readUInt32BE(4), 3);
assert.equal(chunks[0].data[8], 8);
assert.equal(chunks[0].data[9], 2);
const raw = inflateSync(chunks[1].data);
assert.equal(raw.length, 3 * (1 + 4 * 3));
assert.equal(raw[0], 0);
assert.deepEqual([...raw.subarray(1, 4)], [0, 0, 0]);
assert.deepEqual([...raw.subarray(10, 13)], [191, 191, 191]);
assert.throws(() => encodePng(0, 1, () => [0, 0, 0]));
});
test('the PDF writer gives a header, a trailer, and xref offsets that point to their objects', () => {
const pdf = writePdf(Array.from({ length: 50 }, (_, index) => `Page ${index + 1}`));
const text = pdf.toString('latin1');
assert.ok(text.startsWith('%PDF-1.4\n'));
assert.ok(text.endsWith('%%EOF\n'));
const xref = readPdfXref(pdf);
assert.equal(xref.count, 3 + 50 * 2 + 1);
assert.equal(xref.entries[0].line, '0000000000 65535 f ');
for (const [index, entry] of xref.entries.slice(1).entries()) {
assert.equal(entry.line.length + 1, 20, 'Each xref entry is 20 bytes.');
assert.ok(entry.used);
assert.ok(text.startsWith(`${index + 1} 0 obj\n`, entry.offset), `Object ${index + 1} is at ${entry.offset}.`);
}
assert.match(text, /\/Type \/Pages \/Kids \[[^\]]+\] \/Count 50 >>/);
assert.match(text, /\(Page 25\) Tj/);
assert.match(text, new RegExp(`/Size ${xref.count} /Root 1 0 R`));
// Stream lengths match the stream bytes.
for (const match of text.matchAll(/<< \/Length (\d+) >>\nstream\n/g)) {
const start = match.index + match[0].length;
assert.ok(text.startsWith('endstream', start + Number(match[1])));
}
assert.match(writePdf(['A (b) \\ c']).toString('latin1'), /\(A \\\(b\\\) \\\\ c\) Tj/);
});
test('the Project Management fixture uses the card file names and ignore files of the real store', () => {
const files = pmFiles();
assert.equal(files.get('.runestone/pm/cards/.gitignore'), '*\n');
assert.match(files.get('.runestone/pm/.gitignore')!, /^\*$/m);
const catalog = JSON.parse(files.get('.runestone/pm/workspace.json')!);
assert.equal(catalog.schema, 1);
assert.equal(catalog.boards.length, 8);
const cards = [...files.keys()].filter(name => name.startsWith('.runestone/pm/cards/') && name.endsWith('.md'));
assert.equal(cards.length, 400);
const id = seededUuid('card-0-0');
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
assert.equal(cardFileName(id), `${Buffer.from(id).toString('hex')}.md`);
assert.match(files.get(`.runestone/pm/cards/${cardFileName(id)}`)!, new RegExp(`^---\\nrunestone_pm:\\n schema: 1\\n id: ${id}\\n kind: task\\n`));
});
test('the report table has one row for each scenario and marks failures', () => {
const report = {
stage: 'reference', build: 'x.exe', identifier: 'com.runestone.phase7-ram', mode: 'plugin', runs: 3, date: '2026-10-29',
machine: { cpu: 'CPU', ramGB: 32, windows: 'Windows 11' },
rows: [
{ feature: 'base', scenario: 'base', median: { runs: 3, failed: 0, privateMB: 200.04, workingSetMB: 300, heapMB: 20, startMs: 1500.4, firstNeedMs: null, longTaskCount: 1, longTaskMaxMs: 80 } },
{ feature: 'pdf', scenario: 'in-use', median: { runs: 3, failed: 3 }, reason: 'timeout | x' },
],
};
const table = markdownTable(report);
assert.match(table, /\| base \| base \| 200\.0 \| 300\.0 \| 20\.0 \| 1500 \| – \| 1 \/ 80 \|/);
assert.match(table, /\| pdf \| in-use \| failed \|/);
assert.doesNotMatch(table, /timeout \| x/);
});
+189
View File
@@ -0,0 +1,189 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm, access, readdir } 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 { describePlan, git, integrity, packEntries, packageFileName, packageTime, parseArguments, planSdkRelease, releasePackageJson, runSdkRelease } from "../../../scripts/releaseSdk.mjs";
// These tests use a temporary Git repository. They need no network and upload nothing.
const repository = path.resolve(".");
const sdk = "packages/plugin-sdk";
const releaseUrl = "https://example.com/releases/download/plugin-sdk-v0.1.0";
const exists = (file: string) => access(file).then(() => true, () => false);
type Setup = { base: string; root: string };
// A host repository with the SDK package files at version 0.0.0.
async function fixture(): Promise<Setup> {
const base = await mkdtemp(path.join(tmpdir(), "runestone-sdk-release-"));
const root = path.join(base, "RuneStone");
await mkdir(path.join(root, sdk), { recursive: true });
for (const file of ["package.json", "README.md", "LICENSE", "NOTICE"]) await copyFile(path.join(repository, sdk, file), path.join(root, sdk, file));
const source = JSON.parse(await readFile(path.join(root, sdk, "package.json"), "utf8"));
await writeFile(path.join(root, sdk, "package.json"), JSON.stringify({ ...source, version: "0.0.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } }, null, 2) + "\n");
await writeFile(path.join(root, ".gitignore"), "dist/\nreleases/\n");
await git(root, ["init", "-q", "-b", "master"]);
await git(root, ["config", "user.name", "SDK test"]);
await git(root, ["config", "user.email", "[email protected]"]);
await git(root, ["add", "-A"]);
await git(root, ["commit", "-q", "-m", "host"]);
return { base, root };
}
async function withFixture(body: (setup: Setup) => Promise<void>) {
const setup = await fixture();
try { await body(setup); } finally { await rm(setup.base, { recursive: true, force: true }); }
}
// A build that writes a small dist/ folder in place of the TypeScript compiler.
const fakeBuild = async (root: string) => {
const dist = path.join(root, sdk, "dist");
await mkdir(path.join(dist, "nested"), { recursive: true });
await writeFile(path.join(dist, "index.js"), "export const API_VERSION = 1;\n");
await writeFile(path.join(dist, "index.d.ts"), "export declare const API_VERSION = 1;\n");
await writeFile(path.join(dist, "nested", "extra.js"), "export {};\n");
return dist;
};
const failingBuild = async () => { throw Error("The compiler failed."); };
// Reads the files of a gzip tar: the name, mode, time, and contents of each entry.
function unpack(archive: Buffer) {
const tar = zlib.gunzipSync(archive);
const entries: { name: string; mode: number; time: number; type: string; data: string }[] = [];
for (let offset = 0; offset + 512 <= tar.length; ) {
const header = tar.subarray(offset, offset + 512);
if (header.every(byte => byte === 0)) break;
const field = (start: number, size: number) => header.subarray(start, start + size).toString("ascii").replace(/\0.*$/s, "").trim();
let sum = 0;
for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
assert.equal(parseInt(field(148, 8), 8), sum, "The header checksum must match.");
assert.equal(field(257, 6), "ustar");
const size = parseInt(field(124, 12), 8);
entries.push({ name: field(0, 100), mode: parseInt(field(100, 8), 8), time: parseInt(field(136, 12), 8), type: field(156, 1),
data: tar.subarray(offset + 512, offset + 512 + size).toString("utf8") });
offset += 512 + Math.ceil(size / 512) * 512;
}
return entries;
}
const quiet = async <T>(work: () => Promise<T>) => {
const error = console.error;
console.error = () => {};
try { return await work(); } finally { console.error = error; }
};
test("the SDK release script reads --release-url, --version, and --dry-run", () => {
assert.deepEqual(parseArguments(["--release-url", releaseUrl, "--version", "0.1.0"]), { version: "0.1.0", releaseUrl, dryRun: false });
assert.deepEqual(parseArguments(["--dry-run", "--version", "0.1.0a", "--release-url", releaseUrl]), { version: "0.1.0a", releaseUrl, dryRun: true });
for (const args of [[], ["--version", "0.1.0"], ["--release-url", releaseUrl], ["--version"], ["0.1.0"], ["--release-url", releaseUrl, "--version", "0.1.0", "--version", "0.1.1"], ["--push"]]) {
assert.throws(() => parseArguments(args));
}
});
test("the release package.json has the version and no build scripts or development dependencies", () => {
const source = { name: "@runestone/plugin-sdk", version: "0.0.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } };
assert.deepEqual(releasePackageJson(source, "0.1.0"), { name: "@runestone/plugin-sdk", version: "0.1.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0" });
assert.throws(() => releasePackageJson({ ...source, license: undefined }, "0.1.0"), /license/);
});
test("the package file has the npm pack name", () => {
assert.equal(packageFileName("@runestone/plugin-sdk", "0.1.0"), "runestone-plugin-sdk-0.1.0.tgz");
assert.equal(packageFileName("plain", "1.0.0a"), "plain-1.0.0a.tgz");
});
test("the package is a tar under package/ in name order, with a fixed time, and the same entries give the same bytes", () => {
const entries = [
{ name: "package.json", data: Buffer.from('{"name":"x"}\n') },
{ name: "dist/index.js", data: Buffer.alloc(700, 97) },
{ name: "README.md", data: Buffer.from("") },
];
const archive = packEntries(entries);
assert.deepEqual(archive, packEntries([...entries].reverse()));
const files = unpack(archive);
assert.deepEqual(files.map(file => file.name), ["package/README.md", "package/dist/index.js", "package/package.json"]);
for (const file of files) {
assert.equal(file.mode, 0o644);
assert.equal(file.time, packageTime);
assert.equal(file.type, "0");
}
assert.equal(files[1].data, "a".repeat(700));
assert.equal(integrity(archive), "sha512-" + createHash("sha512").update(archive).digest("base64"));
assert.throws(() => packEntries([{ name: "x".repeat(93), data: Buffer.from("") }]), /too long/);
assert.throws(() => packEntries([{ name: "a", data: Buffer.from("1") }, { name: "a", data: Buffer.from("2") }]), /two files/);
});
test("a dry run plans the release, gives the plugin dependency line, and changes no file", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
const text = describePlan(plan);
assert.match(text, /SDK version: 0\.1\.0 \(current 0\.0\.0\)/);
assert.match(text, /with dist, package\.json, README\.md, LICENSE, NOTICE, and/);
assert.equal(plan.url, `${releaseUrl}/runestone-plugin-sdk-0.1.0.tgz`);
assert.match(text, /Plugins then use: "@runestone\/plugin-sdk": "https:\/\/example\.com\/releases\/download\/plugin-sdk-v0\.1\.0\/runestone-plugin-sdk-0\.1\.0\.tgz"/);
assert.equal(plan.packageJson.version, "0.1.0");
assert.equal(plan.packageJson.scripts, undefined);
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(path.join(setup.root, "releases")), false);
}));
test("the release refuses an HTTP URL, a URL with credentials, an earlier version, and an existing release file", () => withFixture(async setup => {
for (const url of ["http://example.com/r", "https://user:[email protected]/r", "https://example.com/r?x=1", "https://example.com/r#x"]) {
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl: url }), /HTTPS release URL/);
}
await assert.rejects(planSdkRelease(setup.root, { version: "0.0.0", releaseUrl }), /greater than the current version 0\.0\.0/);
await assert.rejects(planSdkRelease(setup.root, { version: "1.0", releaseUrl }), /release version/);
await mkdir(path.join(setup.root, "releases/plugin-sdk/0.1.0"), { recursive: true });
await writeFile(path.join(setup.root, "releases/plugin-sdk/0.1.0/sdk.json"), "{}");
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /already exists/);
}));
test("the release refuses a package without a license file or with source changes that are not committed", () => withFixture(async setup => {
await rm(path.join(setup.root, sdk, "LICENSE"));
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /no LICENSE file/);
await git(setup.root, ["checkout", "-q", "--", sdk]);
await writeFile(path.join(setup.root, sdk, "README.md"), "changed");
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /not committed/);
}));
test("a completed release writes the package and its record, then sets the source version", () => withFixture(async setup => {
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
const result = await runSdkRelease(plan, fakeBuild);
const folder = path.join(setup.root, "releases/plugin-sdk/0.1.0");
assert.deepEqual((await readdir(folder)).sort(), ["runestone-plugin-sdk-0.1.0.tgz", "sdk.json"]);
const archive = await readFile(path.join(folder, "runestone-plugin-sdk-0.1.0.tgz"));
const files = unpack(archive);
assert.deepEqual(files.map(file => file.name), ["package/LICENSE", "package/NOTICE", "package/README.md", "package/dist/index.d.ts", "package/dist/index.js", "package/dist/nested/extra.js", "package/package.json"]);
const packed = JSON.parse(files.find(file => file.name === "package/package.json")!.data);
assert.equal(packed.version, "0.1.0");
assert.equal(packed.scripts, undefined);
assert.equal(files.find(file => file.name === "package/LICENSE")!.data, await readFile(path.join(setup.root, sdk, "LICENSE"), "utf8"));
const record = JSON.parse(await readFile(path.join(folder, "sdk.json"), "utf8"));
assert.deepEqual(record, {
name: "@runestone/plugin-sdk", version: "0.1.0", file: "runestone-plugin-sdk-0.1.0.tgz", url: plan.url, bytes: archive.length,
sha256: createHash("sha256").update(archive).digest("hex"), integrity: integrity(archive), source: plan.hostCommit,
});
assert.equal(result.sha256, record.sha256);
assert.equal(JSON.parse(await readFile(path.join(setup.root, sdk, "package.json"), "utf8")).version, "0.1.0");
}));
test("a failed build restores the version and writes no release file", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
await quiet(() => assert.rejects(runSdkRelease(plan, failingBuild), /compiler failed/));
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(path.join(setup.root, "releases/plugin-sdk/0.1.0")), false);
}));
test("a failure after the package is written removes the files of that attempt only", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
// A record that appears after the plan makes the record write fail.
await mkdir(plan.releaseDir, { recursive: true });
await writeFile(plan.artifacts.metadata, "kept");
await quiet(() => assert.rejects(runSdkRelease(plan, fakeBuild), /EEXIST/));
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(plan.artifacts.archive), false);
assert.equal(await readFile(plan.artifacts.metadata, "utf8"), "kept");
}));