Remove the 996-line fork of the Tauri 2.11.4 template and the custom
comparator. src-tauri/windows/hooks.nsh now adds the RuneStone behavior
through bundle.windows.nsis.installerHooks:
- RuneStoneGuiInit (MUI_CUSTOMFUNCTION_GUIINIT) runs before the first
page in interactive and passive setup. It stops a downgrade with exit
code 2. It makes the stock maintenance page skip itself, so that setup
never starts the uninstaller for an upgrade or a reinstall.
- The hidden section RuneStoneVersionCheck runs before the Tauri sections
in all modes. Silent setup shows no pages, so it needs this check.
- NSIS_HOOK_POSTINSTALL writes the release version to DisplayVersion and
RuneStoneReleaseVersion, and the Windows version to
RuneStoneWindowsVersion. Installed apps now show 0.1.23a, not 0.1.23+1.
Setup compares the four-number Windows encoding with ${VersionCompare}.
An unknown installed version stops setup.
buildInstaller.mjs gives the toolchain version to Tauri through a
--config override. It writes tauri.conf.json, Cargo.toml, and Cargo.lock
only after the installer is complete. package.json changes during the
build because the Settings dialog imports its version. A failed build
restores it. Add --dry-run, which prints the plan and changes no file.
The tests compile NSIS programs with the real makensis. They simulate the
installed version in a test-only HKCU key and check /S, /P, /UPDATE, and
interactive setup. A drift check reads the template from the installed
Tauri CLI. The first real installer needs the installer checks in
docs/builds.md.
160 lines
9.9 KiB
JavaScript
160 lines
9.9 KiB
JavaScript
// Builds the Windows installer. See docs/builds.md#build-the-windows-installer.
|
|
// Usage: node scripts/buildInstaller.mjs [--version <version>] [--dry-run]
|
|
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
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 versionFiles = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'];
|
|
|
|
export function parseArguments(args) {
|
|
const options = { version: 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 throw Error('Use --version followed by the release version, and optionally --dry-run.');
|
|
}
|
|
return options;
|
|
}
|
|
|
|
// Reads the version fields, checks the build preconditions, and returns the build plan. Changes no file.
|
|
export async function planInstallerBuild(root, requestedVersion) {
|
|
const files = versionFiles.map(file => path.join(root, file));
|
|
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
|
|
const current = releaseVersion(JSON.parse(before[0]).version);
|
|
const next = releaseVersion(requestedVersion ?? current.version);
|
|
const config = JSON.parse(before[1]);
|
|
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
|
|
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
|
|
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
|
|
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
|
|
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
|
|
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
|
|
const windowsConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8')).bundle?.windows;
|
|
if (windowsConfig?.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
|
const hooks = windowsConfig?.nsis?.installerHooks;
|
|
if (!hooks || !(await exists(path.join(root, 'src-tauri', hooks)))) throw Error('The installer hooks file is not configured. See src-tauri/tauri.windows.conf.json.');
|
|
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
|
throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.');
|
|
}
|
|
const bundleDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
|
const releaseDir = path.join(root, 'releases', next.version);
|
|
const artifacts = {
|
|
bundled: path.join(bundleDir, `RuneStone_${next.toolchain}_x64-setup.exe`),
|
|
renamed: path.join(bundleDir, `RuneStone_${next.version}_x64-setup.exe`),
|
|
release: path.join(releaseDir, `RuneStone_${next.version}_x64-setup.exe`),
|
|
metadata: path.join(releaseDir, 'host.json'),
|
|
};
|
|
for (const file of new Set(Object.values(artifacts))) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
|
|
|
const packageJson = JSON.parse(before[0]);
|
|
packageJson.version = next.version;
|
|
config.version = next.toolchain;
|
|
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
|
|
if (cargoRelease) cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
|
|
else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
|
|
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
|
|
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
|
|
// Tauri merges this override into tauri.conf.json for the build script, the app, and the bundler.
|
|
const override = { version: next.toolchain };
|
|
return { root, files, before, updated, current, next, override, releaseDir, artifacts };
|
|
}
|
|
|
|
// The commands of a build, in order. overridePath is the file with plan.override.
|
|
export function buildCommands(plan, overridePath) {
|
|
const cli = path.join(plan.root, 'node_modules/@tauri-apps/cli/tauri.js');
|
|
return [
|
|
{ step: 'compile', command: process.execPath, args: [cli, 'build', '--no-bundle', '--config', overridePath, '--', '--locked'] },
|
|
{ step: 'version-resource', command: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
|
path.join(plan.root, 'scripts/setWindowsVersion.ps1'), '-Path', path.join(plan.root, 'src-tauri/target/release/runestone.exe'),
|
|
'-Version', plan.next.version, '-NumericVersion', plan.next.windows] },
|
|
{ step: 'bundle', command: process.execPath, args: [cli, 'bundle', '--bundles', 'nsis', '--config', overridePath] },
|
|
];
|
|
}
|
|
|
|
export function describePlan(plan, overridePath = '<attempt folder>/tauri.version.json') {
|
|
const relative = file => path.relative(plan.root, file);
|
|
return [
|
|
`Release version: ${plan.next.version} (current ${plan.current.version})`,
|
|
`Toolchain version: ${plan.next.toolchain}. Windows version: ${plan.next.windows}.`,
|
|
`Configuration override: ${JSON.stringify(plan.override)}`,
|
|
`1. Write version ${plan.next.version} to package.json. The front-end build reads it. A failed build restores it.`,
|
|
...buildCommands(plan, overridePath).map((entry, index) => `${index + 2}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
|
|
`5. Move the setup file to ${relative(plan.artifacts.release)} and write ${relative(plan.artifacts.metadata)}.`,
|
|
`6. Write the new version to ${versionFiles.slice(1).join(', ')}.`,
|
|
].join('\n');
|
|
}
|
|
|
|
// Runs the build. run(command, args) must reject when a command fails.
|
|
// The tracked version files change only when the build completes, except package.json during the build.
|
|
export async function runInstallerBuild(plan, run, staging) {
|
|
const { files, before, updated, 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]);
|
|
const overridePath = path.join(staging, 'tauri.version.json');
|
|
await fs.writeFile(overridePath, JSON.stringify(plan.override, null, 2) + '\n');
|
|
let complete = false;
|
|
try {
|
|
// src/lib/layout/SettingsDialog.svelte imports the version from package.json.
|
|
await fs.writeFile(files[0], updated[0]);
|
|
for (const { command, args } of buildCommands(plan, overridePath)) await run(command, args);
|
|
await fs.access(artifacts.bundled);
|
|
if (artifacts.bundled !== artifacts.renamed) await fs.rename(artifacts.bundled, artifacts.renamed);
|
|
await fs.mkdir(plan.releaseDir, { recursive: true });
|
|
await fs.copyFile(artifacts.renamed, artifacts.release, fs.constants.COPYFILE_EXCL);
|
|
const bytes = await fs.readFile(artifacts.release);
|
|
const metadata = { version: plan.next.version, toolchainVersion: plan.next.toolchain, windowsVersion: plan.next.windows,
|
|
file: path.basename(artifacts.release), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
await fs.writeFile(artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
|
await fs.unlink(artifacts.renamed);
|
|
for (let i = 1; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
|
|
complete = true;
|
|
return artifacts.release;
|
|
} 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 new Set(Object.values(artifacts))) {
|
|
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
|
}
|
|
console.error('The build did not complete. The version fields 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 planInstallerBuild(root, options.version);
|
|
if (options.dryRun) {
|
|
console.log(describePlan(plan));
|
|
return;
|
|
}
|
|
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
|
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
|
|
// Ctrl+C also stops the child build. Keep this process alive so that package.json is restored.
|
|
let interrupted = false;
|
|
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; });
|
|
async function run(command, parameters) {
|
|
if (interrupted) throw Error('The build was interrupted.');
|
|
console.log(command + ' ' + parameters.join(' '));
|
|
const code = await new Promise((resolve, reject) => {
|
|
const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true });
|
|
child.on('error', reject); child.on('exit', resolve);
|
|
});
|
|
if (interrupted) throw Error('The build was interrupted.');
|
|
if (code !== 0) throw Error('The build command failed with exit code ' + code);
|
|
}
|
|
// Each attempt keeps its own backups, so a later attempt cannot replace them.
|
|
const staging = path.join(root, 'output/installer-build', plan.next.version, new Date().toISOString().replaceAll(':', '-'));
|
|
const installer = await runInstallerBuild(plan, run, staging);
|
|
console.log('Installer available: ' + installer);
|
|
}
|
|
|
|
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) await main();
|