Files
RuneStone/scripts/releaseSdk.mjs
T
Knotty Wyvern a950edfb13 Release the plugin SDK as a package file
pnpm release:sdk now packs runestone-plugin-sdk-<version>.tgz and sdk.json
into releases/plugin-sdk/<version>/. Plugins install the SDK from the URL
of that file on the RuneStone releases page. The script no longer uses a
clone of a separate SDK repository.

Installers, browser engine ZIPs, and SDK packages now share the RuneStone
releases page.
2026-10-29 13:05:10 -07:00

199 lines
11 KiB
JavaScript

// Packs the plugin SDK into a release file that plugins install from its URL. See docs/releases.md#sdk-releases.
// Usage: node scripts/releaseSdk.mjs --release-url <folder URL> --version <version> [--dry-run]
// The script writes releases/plugin-sdk/<version>/. It never uploads. It prints the dependency line for plugins.
import fs from 'node:fs/promises';
import path from 'node:path';
import zlib from 'node:zlib';
import { execFile } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { compareReleases, releaseVersion } from './releaseVersion.mjs';
import { buildSdk, sdkFolder } from './buildSdk.mjs';
const exists = file => fs.access(file).then(() => true, () => false);
export const packageName = '@runestone/plugin-sdk';
// The files beside dist/ and package.json in the package. LICENSE and README.md are required. NOTICE is optional.
export const packageFiles = ['README.md', 'LICENSE', 'NOTICE'];
// The fixed file time of npm packages, 1985-10-26 08:15 UTC, in seconds.
export const packageTime = 499162500;
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, --version followed by the SDK version, and optionally --dry-run.');
}
if (!options.releaseUrl) throw Error('Use --release-url followed by the URL of the folder that will hold the SDK package.');
if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.2.');
return options;
}
// Runs git in a folder and returns its output without the final line break. Rejects when git fails.
export function git(cwd, args) {
return new Promise((resolve, reject) => {
execFile('git', ['-C', cwd, ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) reject(Error(`git ${args.join(' ')} failed in ${cwd}: ${String(stderr || error.message).trim()}`));
else resolve(stdout.replace(/\r?\n$/, ''));
});
});
}
// The package.json of the release: the source fields with the new version, without build scripts or development dependencies.
export function releasePackageJson(source, version) {
const { scripts, devDependencies, ...rest } = source;
const result = { ...rest, version };
for (const field of ['types', 'exports', 'files', 'license']) if (!result[field]) throw Error(`The SDK package.json has no "${field}" field.`);
return result;
}
/** The file name that `npm pack` gives a package: `@scope/name` becomes `scope-name-<version>.tgz`. */
export function packageFileName(name, version) {
return `${name.replace(/^@/, '').replace('/', '-')}-${version}.tgz`;
}
/** A gzip tar of the entries under `package/`, in name order, with a fixed time and mode. The same entries give the same bytes. */
export function packEntries(entries) {
const blocks = [];
const sorted = [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
for (let i = 1; i < sorted.length; i++) if (sorted[i].name === sorted[i - 1].name) throw Error('The SDK package has two files with the name ' + sorted[i].name);
for (const { name, data } of sorted) {
const full = Buffer.from('package/' + name, 'utf8');
if (full.length > 100) throw Error('The SDK has a file name that is too long for the package: ' + name);
if (data.length >= 8 ** 11) throw Error('The SDK has a file that is too large for the package: ' + name);
// A ustar header: name, mode, owner, group, size, time, checksum, type, and the magic value.
const header = Buffer.alloc(512);
full.copy(header, 0);
const octal = (value, offset, size) => header.write(value.toString(8).padStart(size - 1, '0') + '\0', offset, size, 'ascii');
octal(0o644, 100, 8); octal(0, 108, 8); octal(0, 116, 8); octal(data.length, 124, 12); octal(packageTime, 136, 12);
header.write(' ', 148, 8, 'ascii');
header.write('0', 156, 1, 'ascii');
header.write('ustar\0' + '00', 257, 8, 'ascii');
let sum = 0;
for (const byte of header) sum += byte;
header.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'ascii');
blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
}
blocks.push(Buffer.alloc(1024));
return zlib.gzipSync(Buffer.concat(blocks), { level: 9 });
}
/** The SHA-512 value that npm and pnpm record in a lock file. */
export const integrity = data => 'sha512-' + createHash('sha512').update(data).digest('base64');
async function listFiles(folder, prefix = '') {
const result = [];
for (const entry of await fs.readdir(path.join(folder, prefix), { withFileTypes: true })) {
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 SDK build contains a link or a special file: ' + name);
}
return result;
}
// Checks the preconditions and returns the release plan. Changes no file.
/** @param {string} root @param {{ version: string, releaseUrl: string }} options */
export async function planSdkRelease(root, { version, releaseUrl }) {
const next = releaseVersion(version);
const packageDir = path.join(root, sdkFolder);
const sourceFile = path.join(packageDir, 'package.json');
const source = JSON.parse(await fs.readFile(sourceFile, 'utf8'));
if (source.name !== packageName) throw Error(`${sourceFile} is not the ${packageName} package.`);
const current = releaseVersion(source.version);
if (compareReleases(next.version, current.version) <= 0) throw Error(`The SDK version must be greater than the current version ${current.version}.`);
for (const file of ['README.md', 'LICENSE']) {
if (!(await exists(path.join(packageDir, file)))) throw Error(`The SDK package has no ${file} file. Add ${path.join(sdkFolder, file)} before a release.`);
}
const copies = [];
for (const file of packageFiles) if (await exists(path.join(packageDir, file))) copies.push(file);
if ((await git(root, ['status', '--porcelain', '--untracked-files=all', '--', sdkFolder])) !== '') {
throw Error(`${sdkFolder} has changes that are not committed. Commit them first, so that the release has a source commit.`);
}
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 file = packageFileName(packageName, next.version);
const releaseDir = path.join(root, 'releases', 'plugin-sdk', next.version);
const artifacts = { archive: path.join(releaseDir, file), metadata: path.join(releaseDir, 'sdk.json') };
for (const artifact of Object.values(artifacts)) if (await exists(artifact)) throw Error('The release file already exists: ' + artifact);
return {
root, packageDir, sourceFile, source, current, next, copies, file, releaseDir, artifacts,
url: new URL(file, folder).href,
hostCommit: await git(root, ['rev-parse', 'HEAD']),
packageJson: releasePackageJson(source, next.version),
};
}
export function describePlan(plan) {
const relative = file => path.relative(plan.root, file);
return [
`SDK version: ${plan.next.version} (current ${plan.current.version})`,
`Source: ${relative(plan.packageDir) || '.'} at RuneStone ${plan.hostCommit}`,
`1. Build ${sdkFolder}/dist.`,
`2. Write ${relative(plan.artifacts.archive)} with dist, package.json, ${plan.copies.join(', ')}, and ${relative(plan.artifacts.metadata)}.`,
`3. Write the version ${plan.next.version} to ${sdkFolder}/package.json.`,
`Plugins then use: "${packageName}": "${plan.url}"`,
'The script does not upload the file.',
].join('\n');
}
// Runs the release. build(root) returns the dist folder. The source version changes only when the release files exist.
export async function runSdkRelease(plan, build = buildSdk) {
const before = await fs.readFile(plan.sourceFile, 'utf8');
const written = [];
let complete = false;
try {
const dist = await build(plan.root);
for (const file of ['index.js', 'index.d.ts']) await fs.access(path.join(dist, file));
const entries = [{ name: 'package.json', data: Buffer.from(JSON.stringify(plan.packageJson, null, 2) + '\n') }];
for (const file of plan.copies) entries.push({ name: file, data: await fs.readFile(path.join(plan.packageDir, file)) });
for (const file of await listFiles(dist)) entries.push({ name: 'dist/' + file, data: await fs.readFile(path.join(dist, ...file.split('/'))) });
const archive = packEntries(entries);
await fs.mkdir(plan.releaseDir, { recursive: true });
await fs.writeFile(plan.artifacts.archive, archive, { flag: 'wx' });
written.push(plan.artifacts.archive);
const metadata = {
name: packageName, version: plan.next.version, file: plan.file, url: plan.url, bytes: archive.length,
sha256: createHash('sha256').update(archive).digest('hex'), integrity: integrity(archive), source: plan.hostCommit,
};
await fs.writeFile(plan.artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
written.push(plan.artifacts.metadata);
await fs.writeFile(plan.sourceFile, before.replace(/("version":\s*")[^"]+(")/, `$1${plan.next.version}$2`));
if (JSON.parse(await fs.readFile(plan.sourceFile, 'utf8')).version !== plan.next.version) throw Error('The SDK version field did not change.');
complete = true;
return { archive: plan.artifacts.archive, ...metadata };
} finally {
if (!complete) {
if ((await fs.readFile(plan.sourceFile, 'utf8').catch(() => null)) !== before) await fs.writeFile(plan.sourceFile, before);
// Only the files of this attempt go. A failed attempt does not use up the version.
for (const file of written) await fs.rm(file, { force: true });
await fs.rmdir(plan.releaseDir).catch(() => {});
console.error('The SDK release did not complete. The version is restored, and the files of this attempt are removed.');
}
}
}
async function main() {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const options = parseArguments(process.argv.slice(2));
const plan = await planSdkRelease(root, options);
console.log(describePlan(plan));
if (options.dryRun) {
console.log('Dry run: no file changed.');
return;
}
const result = await runSdkRelease(plan);
console.log(`\nSDK package: ${result.archive}\n${result.bytes} bytes, SHA-256 ${result.sha256}\nIntegrity: ${result.integrity}`);
console.log(`Upload it to ${result.url}`);
console.log(`Plugins use: "${packageName}": "${result.url}"`);
console.log(`Then commit the new version in ${sdkFolder}/package.json in RuneStone.`);
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
try { await main(); } catch (error) { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; }
}