#!/usr/bin/env node // Publishes the slim install refs of one release: a synthetic commit whose tree // holds only the runtime payload (install.js, package.json, version.json and // src/) plus a binding manifest, pushed once as the immutable // `refs/tags/install-vX.Y.Z` and as the new fast-forward tip of // `refs/heads/release`. Dev-only: lives in scripts/ so it never ships inside a // skill or the runtime payload it assembles. // // node scripts/publish-install-refs.mjs --tag v3.2.3 --repo "$GITHUB_WORKSPACE" // // Runs in the full release checkout of .github/workflows/release-app.yml, // after the GitHub release is public. The payload is read from the source // tag's own git tree, never from the working tree, and the commit is built // with a temporary index, so the checkout and its normal index are never // touched. Zero dependencies: Node built-ins and the git on PATH. // // Exit codes: 0 published (or a dry run that would publish), 1 refused or // failed (nothing pushed), 2 bad arguments. import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; export const INSTALL_REF_MANIFEST = ".plan2code-install-ref.json"; // The package scripts that make npm prepare a git dependency with a full dev install (pacote). const GIT_DEP_LIFECYCLE = new Set(["prepare", "build", "install", "preinstall", "postinstall", "prepack"]); export const RELEASE_BRANCH_REF = "refs/heads/release"; export const REMOTE = "origin"; const TAG_SHAPE = /^v(\d+\.\d+\.\d+)$/; /** * The runtime payload, as data: exactly these top-level files plus the * recursive trees under `prefixes`, minus any path with an `excludedSegments` * folder in it. `forbiddenTopLevel` names what must never appear (reported on * its own when it does), and `required` the files an install cannot run * without; the workflow skill sources install.js's SOURCE_PROMPTS names are * required on top of these (`workflowSkillSources()`). */ export const RUNTIME_PAYLOAD = Object.freeze({ files: Object.freeze(["install.js", "package.json", "version.json"]), prefixes: Object.freeze(["src/"]), excludedSegments: Object.freeze(["node_modules", ".git", "fixtures", "__fixtures__"]), forbiddenTopLevel: Object.freeze([ ".git", ".github", "docs", "scripts", "specs", "skills", "plan2code-app", "plan2code-metrics", "plan2code-bot", ]), required: Object.freeze([ "install.js", "package.json", "version.json", "src/launcher/plan2code.js", "src/web-console/update-check.mjs", "src/web-console/console.mjs", "src/installer/timing.js", "src/installer/skills-cli.js", "src/installer/canonical-skills.js", "src/installer/console-stage.js", // Read by install.js at runtime too: the skills' forwarding stub, the status line, the // launcher's model menu, agent list and lookup, and the desktop shortcut's icons. "src/web-console-stub/console.mjs", "src/statusline-claude/statusline.js", "src/launcher/models.json", "src/launcher/agents.json", "src/web-console/agent-lookup.mjs", "src/launcher/plan2code.ico", "src/web-console/public/favicon.png", ]), }); /** The allowlist the payload is assembled and validated against. */ export function runtimePayloadAllowlist() { return RUNTIME_PAYLOAD; } /** Whether a `/`-separated path relative to the payload root belongs in the payload. */ export function isAllowedPayloadPath(rel, allowlist = RUNTIME_PAYLOAD) { if (typeof rel !== "string" || rel === "" || rel.startsWith("/") || rel.includes("\\")) return false; const parts = rel.split("/"); if (parts.some((p) => p === "" || p === "." || p === "..")) return false; if (allowlist.forbiddenTopLevel.includes(parts[0])) return false; if (allowlist.files.includes(rel)) return true; if (!allowlist.prefixes.some((prefix) => rel.startsWith(prefix) && rel.length > prefix.length)) return false; return !parts.slice(0, -1).some((p) => allowlist.excludedSegments.includes(p)); } /** * What install.js builds the skills from, read from its SOURCE_PROMPTS array: * each top-level `source: '.md'` as `src/.md`, each shared script * a `scripts: [...]` list names (plus SHARED_SCRIPTS_ALWAYS) as * `src/skill-scripts/`, and each `additionalReferences` `{ source: ... }` * as `src/` (a file or a folder). An empty list means the array could * not be read, which validation reports. */ export function workflowSkillSources(installJsText) { const start = installJsText.indexOf("const SOURCE_PROMPTS = ["); if (start === -1) return []; const end = installJsText.indexOf("\n];", start); const block = installJsText.slice(start, end === -1 ? undefined : end); const names = (list) => [...list.matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]); const sources = [...block.matchAll(/^ {4}source: ['"]([^'"]+\.md)['"]/gm)].map((m) => `src/${m[1]}`); if (!sources.length) return []; const shared = [...block.matchAll(/^ {4}scripts: \[([^\]]*)\]/gm)].flatMap((m) => names(m[1])); const always = /^const SHARED_SCRIPTS_ALWAYS = \[([^\]]*)\]/m.exec(installJsText); if (shared.length && always) shared.push(...names(always[1])); const references = [...block.matchAll(/\{ source: ['"]([^'"]+)['"]/g)].map((m) => `src/${m[1]}`); return [...new Set([...sources, ...shared.map((name) => `src/skill-scripts/${name}`), ...references])]; } export class PublishError extends Error { constructor(message, details = null) { super(message); this.name = "PublishError"; this.details = details; } } // Credentials can ride in a remote URL (https://user:token@host); git echoes // URLs in its errors, so every message that leaves this script goes through this. const redact = (text) => String(text).replace(/(\/\/)[^/\s@]+@/g, "$1***@"); function git(repo, args, { input, env, allowFail = false, encoding = "utf8" } = {}) { const r = spawnSync("git", ["-C", repo, ...args], { input, env: env || process.env, encoding: encoding === "buffer" ? undefined : encoding, maxBuffer: 1024 * 1024 * 1024, windowsHide: true, }); if (r.error) throw new PublishError(`git ${args[0]} could not run: ${redact(r.error.message)}`); if (r.status !== 0 && !allowFail) { const stderr = Buffer.isBuffer(r.stderr) ? r.stderr.toString("utf8") : r.stderr || ""; throw new PublishError(`git ${args[0]} failed: ${redact(stderr.trim() || `exit ${r.status}`)}`); } return r; } const gitText = (repo, args, options) => git(repo, args, options).stdout.trim(); /** The commit a ref names, or null when it does not exist (annotated tags peel to their commit). */ function commitOf(repo, ref) { const r = git(repo, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFail: true }); return r.status === 0 ? r.stdout.trim() : null; } function readJsonAt(repo, commit, file) { const r = git(repo, ["show", `${commit}:${file}`], { allowFail: true }); if (r.status !== 0) throw new PublishError(`${file} is missing from the source commit ${commit}`); try { return JSON.parse(r.stdout); } catch (err) { throw new PublishError(`${file} in the source commit is not valid JSON: ${err.message}`); } } /** * Resolves the source tag and checks that the tag, its version.json, its root * package.json and the checkout agree before anything is written. The tag may * be annotated or lightweight. `sourceCommit`, when given, stands in for HEAD. */ export function verifySource({ repo, tag, sourceCommit = null }) { const shape = TAG_SHAPE.exec(tag || ""); if (!shape) throw new PublishError(`the source tag must be an exact vX.Y.Z release tag, not "${tag}"`); const version = shape[1]; const tagCommit = commitOf(repo, `refs/tags/${tag}`); if (!tagCommit) throw new PublishError(`the tag ${tag} does not exist in ${repo}; fetch it first`); const checkout = sourceCommit ? commitOf(repo, sourceCommit) : commitOf(repo, "HEAD"); if (!checkout) throw new PublishError(`the source commit ${sourceCommit || "HEAD"} cannot be resolved`); if (checkout !== tagCommit) { throw new PublishError(`${sourceCommit ? "the supplied source commit" : "the checkout's HEAD"} ${checkout} is not the commit ${tag} names (${tagCommit})`); } const versionJson = readJsonAt(repo, tagCommit, "version.json"); const packageJson = readJsonAt(repo, tagCommit, "package.json"); const mismatches = []; if (versionJson.version !== version) mismatches.push(`version.json says ${versionJson.version}`); if (packageJson.version !== version) mismatches.push(`package.json says ${packageJson.version}`); if (mismatches.length) throw new PublishError(`the versions do not match the tag ${tag}: ${mismatches.join(", ")}`); // npm runs a full dev-dependency install for a git package that has one of these scripts, so // every user's npx would download the dev tools (Playwright and the rest) before installing. const lifecycle = Object.keys(packageJson.scripts || {}).filter((name) => GIT_DEP_LIFECYCLE.has(name)); if (lifecycle.length) { throw new PublishError(`package.json has ${lifecycle.join(", ")}: npm would install every dev dependency on each user's machine before the installer runs; remove the script or rename it`); } return { version, sourceTag: tag, sourceCommit: tagCommit }; } /** Every `{ mode, type, sha, path }` in a commit's tree, recursively. */ function treeEntries(repo, commit) { const out = gitText(repo, ["ls-tree", "-r", "-z", "--full-tree", commit]).split("\0"); const entries = []; for (const line of out) { if (!line) continue; const tab = line.indexOf("\t"); const [mode, type, sha] = line.slice(0, tab).split(" "); entries.push({ mode, type, sha, path: line.slice(tab + 1) }); } return entries; } /** The contents of many blobs from one `git cat-file --batch`, in order. */ function readBlobs(repo, shas) { if (!shas.length) return []; const out = git(repo, ["cat-file", "--batch"], { input: `${shas.join("\n")}\n`, encoding: "buffer" }).stdout; const blobs = []; let at = 0; for (const sha of shas) { const nl = out.indexOf(0x0a, at); const header = out.subarray(at, nl).toString("utf8").split(" "); if (header[0] !== sha || header[1] !== "blob") throw new PublishError(`git cat-file could not read blob ${sha}`); const size = Number(header[2]); blobs.push(out.subarray(nl + 1, nl + 1 + size)); at = nl + 1 + size + 1; } return blobs; } function ensureEmptyDir(dir) { if (fs.existsSync(dir)) { if (!fs.statSync(dir).isDirectory()) throw new PublishError(`the output ${dir} is not a folder`); if (fs.readdirSync(dir).length) throw new PublishError(`the output folder ${dir} is not empty`); } else { fs.mkdirSync(dir, { recursive: true }); } } /** * Copies the allowlisted files of `commit`'s tree into the clean folder * `output`, keeping each file's git mode (an executable 100755 stays one). * Returns `{ output, modes, excluded }`: `modes` maps each payload path to its * mode, `excluded` counts the tree's files left out. */ export function assemblePayload({ repo, commit, output, allowlist = RUNTIME_PAYLOAD }) { ensureEmptyDir(output); const picked = []; let excluded = 0; for (const entry of treeEntries(repo, commit)) { if (!isAllowedPayloadPath(entry.path, allowlist)) { excluded++; continue; } if (entry.type !== "blob" || (entry.mode !== "100644" && entry.mode !== "100755")) { throw new PublishError(`${entry.path} is a ${entry.mode === "120000" ? "symlink" : entry.type} (mode ${entry.mode}); the payload holds regular files only`); } picked.push(entry); } const blobs = readBlobs( repo, picked.map((e) => e.sha), ); const modes = {}; picked.forEach((entry, i) => { const dest = path.join(output, ...entry.path.split("/")); fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.writeFileSync(dest, blobs[i]); if (entry.mode === "100755") fs.chmodSync(dest, 0o755); modes[entry.path] = entry.mode; }); return { output, modes, excluded }; } /** Every file under `dir`, as sorted `/`-separated relative paths; symlinks are listed in `links`. */ function walk(dir) { const files = []; const links = []; const visit = (abs, rel) => { for (const name of fs.readdirSync(abs)) { const childAbs = path.join(abs, name); const childRel = rel ? `${rel}/${name}` : name; const st = fs.lstatSync(childAbs); if (st.isSymbolicLink()) links.push(childRel); else if (st.isDirectory()) visit(childAbs, childRel); else files.push(childRel); } }; visit(dir, ""); return { files: files.sort(), links: links.sort() }; } /** * Checks an assembled payload folder: every required file present (including * every skill build input its install.js names), nothing outside the * allowlist and no forbidden top-level entry. `report` is a diff-like list: * `- path` missing, `+ path` unexpected. */ export function validatePayload(dir, { allowlist = RUNTIME_PAYLOAD } = {}) { const { files, links } = walk(dir); const present = new Set(files); const required = [...allowlist.required]; if (present.has("install.js")) { const sources = workflowSkillSources(fs.readFileSync(path.join(dir, "install.js"), "utf8")); if (!sources.length) required.push("install.js SOURCE_PROMPTS (no workflow skill sources found)"); required.push(...sources); } // A required folder (a reference such as src/web-console) is present when it holds a file. const has = (rel) => present.has(rel) || files.some((f) => f.startsWith(`${rel}/`)); const missing = [...new Set(required)].filter((rel) => !has(rel)).sort(); const unexpected = [...files.filter((rel) => rel !== INSTALL_REF_MANIFEST && !isAllowedPayloadPath(rel, allowlist)), ...links.map((rel) => `${rel} (symlink)`)].sort(); const topLevel = new Set([...files, ...links].map((rel) => rel.split("/")[0])); const forbidden = allowlist.forbiddenTopLevel.filter((name) => topLevel.has(name)); const bytes = files.reduce((sum, rel) => sum + fs.statSync(path.join(dir, ...rel.split("/"))).size, 0); const report = [...missing.map((rel) => `- ${rel}`), ...unexpected.map((rel) => `+ ${rel}`), ...forbidden.map((name) => `+ ${name}/ (forbidden top-level entry)`)]; return { ok: !missing.length && !unexpected.length && !forbidden.length, files: files.length, bytes, manifest: present.has(INSTALL_REF_MANIFEST), missing, unexpected, forbidden, report, }; } const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex"); /** * Writes `.plan2code-install-ref.json` at the payload root, binding it to * its release: `{ kind, version, sourceTag, sourceCommit, files }`, `files` * mapping every other payload path to its sha256. Hashed first, written last. */ export function writeInstallRefManifest(dir, { version, sourceTag, sourceCommit }) { const files = {}; for (const rel of walk(dir).files) { if (rel === INSTALL_REF_MANIFEST) continue; files[rel] = sha256(fs.readFileSync(path.join(dir, ...rel.split("/")))); } const manifest = { kind: "install-ref", version, sourceTag, sourceCommit, files }; fs.writeFileSync(path.join(dir, INSTALL_REF_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`); return manifest; } // commit-tree needs an author and committer. A release runner has none // configured, so the GitHub Actions bot stands in unless git or the // environment already names one. const BOT = { name: "github-actions[bot]", email: "41898099+github-actions[bot]@users.noreply.github.com" }; function identityEnv(repo, base) { const env = { ...base }; const configured = (key) => git(repo, ["config", "--get", key], { allowFail: true }).stdout.trim(); const name = configured("user.name"); const email = configured("user.email"); for (const role of ["AUTHOR", "COMMITTER"]) { if (!env[`GIT_${role}_NAME`] && !name) env[`GIT_${role}_NAME`] = BOT.name; if (!env[`GIT_${role}_EMAIL`] && !email) env[`GIT_${role}_EMAIL`] = BOT.email; } return env; } // Windows caps a command line near 32K characters; stay far below it. const MAX_ARGS_CHARS = 8000; /** * Builds the synthetic commit from the payload folder with a temporary * GIT_INDEX_FILE inside the repository's git dir: an empty index, blobs * written with `hash-object -w`, entries added with `update-index --cacheinfo`, * `write-tree`, then `commit-tree` on `parent`. The checkout's working tree * and normal index are never touched. Returns `{ tree, commit }`. */ export function createSyntheticCommit({ repo, dir, modes, parent, message }) { const gitDir = gitText(repo, ["rev-parse", "--absolute-git-dir"]); const indexFile = path.join(gitDir, `p2c-install-index-${process.pid}-${crypto.randomBytes(4).toString("hex")}`); const env = { ...process.env, GIT_INDEX_FILE: indexFile }; const removeIndex = () => { fs.rmSync(indexFile, { force: true }); fs.rmSync(`${indexFile}.lock`, { force: true }); }; removeIndex(); try { const files = walk(dir).files; const abs = files.map((rel) => path.join(dir, ...rel.split("/"))); const shas = gitText(repo, ["hash-object", "-w", "--no-filters", "--stdin-paths"], { input: `${abs.join("\n")}\n`, env }).split(/\r?\n/); if (shas.length !== files.length) throw new PublishError(`git hash-object returned ${shas.length} ids for ${files.length} files`); let batch = []; let chars = 0; const flush = () => { if (!batch.length) return; git(repo, ["update-index", "--add", ...batch], { env }); batch = []; chars = 0; }; files.forEach((rel, i) => { const info = `${modes[rel] || "100644"},${shas[i]},${rel}`; if (chars + info.length > MAX_ARGS_CHARS) flush(); batch.push("--cacheinfo", info); chars += info.length + 13; }); flush(); const tree = gitText(repo, ["write-tree"], { env }); const commit = gitText(repo, ["commit-tree", tree, "-p", parent, "-F", "-"], { input: message, env: identityEnv(repo, env) }); return { tree, commit }; } finally { removeIndex(); } } /** The remote's sha for each ref asked about, from one `git ls-remote`; absent refs are left out. */ function remoteRefs(repo, remote, refs) { const r = git(repo, ["ls-remote", remote, ...refs], { allowFail: true }); if (r.status !== 0) throw new PublishError(`git ls-remote ${remote} failed: ${redact(r.stderr.trim() || `exit ${r.status}`)}`); const found = {}; for (const line of r.stdout.split(/\r?\n/)) { const [sha, ref] = line.split("\t"); if (sha && ref && refs.includes(ref)) found[ref] = sha; } return found; } /** * The parent of the new synthetic commit: the remote release branch's tip when * it exists (the first migration parents the legacy full-source tip only so * the push stays a fast-forward); with no release branch, the source tag's * commit, but only when `allowMissingReleaseBranch` says so. */ export function selectParent({ repo, releaseTip, sourceCommit, allowMissingReleaseBranch }) { if (releaseTip) { if (!commitOf(repo, releaseTip)) { throw new PublishError(`the release branch tip ${releaseTip} is not in this checkout; fetch ${RELEASE_BRANCH_REF} first`); } return { parent: releaseTip, parentKind: "release" }; } if (allowMissingReleaseBranch) return { parent: sourceCommit, parentKind: "source-tag" }; throw new PublishError(`${RELEASE_BRANCH_REF} does not exist on ${REMOTE}; pass --allow-missing-release-branch for a first publication`); } /** Refuses an install tag that already exists here or on the remote: install tags are never overwritten. */ export function checkInstallTagFree({ repo, installTagRef, remoteHas }) { const local = git(repo, ["rev-parse", "--verify", "--quiet", installTagRef], { allowFail: true }).status === 0; if (local || remoteHas) { throw new PublishError(`${installTagRef} already exists ${local && remoteHas ? "here and on the remote" : local ? "in this checkout" : "on the remote"}; install tags are immutable and are never overwritten`); } } /** Negative, zero or positive as `a` (X.Y.Z) is below, equal to or above `b`. */ function compareReleaseVersions(a, b) { const pa = a.split(".").map(Number); const pb = b.split(".").map(Number); for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i]; return 0; } /** readJsonAt, or null when the file is not in that commit or does not parse. */ function readJsonAtOrNull(repo, commit, file) { try { return readJsonAt(repo, commit, file); } catch { return null; } } /** * The version the release branch tip installs: its install-ref manifest's, else its version.json * (a legacy full-source tip), else null when neither can be read. */ export function releaseTipVersion(repo, releaseTip) { if (!releaseTip) return null; const manifest = readJsonAtOrNull(repo, releaseTip, INSTALL_REF_MANIFEST); if (manifest && typeof manifest.version === "string") return manifest.version; const versionJson = readJsonAtOrNull(repo, releaseTip, "version.json"); return versionJson && typeof versionJson.version === "string" ? versionJson.version : null; } /** * Refuses to point the release branch at a version that is not newer than the one it installs * now: a hotfix tagged from a maintenance branch, or two publications finishing out of order, * would otherwise send every README install back to an older release. `allowOlder` is the * explicit override for a deliberate rollback. */ export function checkNewerThanRelease({ repo, releaseTip, version, allowOlder = false }) { if (allowOlder || !releaseTip) return; const current = releaseTipVersion(repo, releaseTip); if (current && compareReleaseVersions(version, current) <= 0) { throw new PublishError(`the release branch already installs ${current}; refusing to move it to ${version}, which is not newer (pass --allow-older for a deliberate rollback)`); } } /** * True when this release is already fully published: the install tag exists on the remote, the * release branch points at it, and its manifest names this release's source commit. A second run * for the same tag (the workflow has more than one trigger) then has nothing to do. */ export function alreadyPublished({ repo, remoteTag, releaseTip, sourceCommit }) { if (!remoteTag || remoteTag !== releaseTip) return false; const manifest = readJsonAtOrNull(repo, remoteTag, INSTALL_REF_MANIFEST); return Boolean(manifest && manifest.sourceCommit === sourceCommit); } /** Refuses a release branch move that would not be a fast-forward. */ export function checkFastForward({ repo, priorTip, commit }) { if (!priorTip) return; const r = git(repo, ["merge-base", "--is-ancestor", priorTip, commit], { allowFail: true }); if (r.status !== 0) throw new PublishError(`the release branch tip ${priorTip} is not an ancestor of ${commit}; refusing a non-fast-forward move`); } /** * Publishes one release's slim install refs: verify the source, assemble and * validate the payload, write the manifest, build one synthetic commit, check * collision and fast-forward, then push that commit to both refs in one * command (unless `dryRun`). Returns the summary the CLI prints as JSON. */ export function publishInstallRefs({ tag, version = null, repo, dryRun = false, output = null, allowMissingReleaseBranch = false, sourceCommit = null, allowOlder = false }) { repo = path.resolve(repo || process.cwd()); const source = verifySource({ repo, tag, sourceCommit }); if (version && version !== source.version) throw new PublishError(`the version ${version} does not match the tag ${tag}`); const installTagRef = `refs/tags/install-${tag}`; const remote = remoteRefs(repo, REMOTE, [installTagRef, RELEASE_BRANCH_REF]); const releaseTip = remote[RELEASE_BRANCH_REF] || null; if (alreadyPublished({ repo, remoteTag: remote[installTagRef] || null, releaseTip, sourceCommit: source.sourceCommit })) { return { ok: true, dryRun, pushed: false, alreadyPublished: true, tag, version: source.version, sourceCommit: source.sourceCommit, commit: releaseTip, refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF } }; } checkInstallTagFree({ repo, installTagRef, remoteHas: Boolean(remote[installTagRef]) }); checkNewerThanRelease({ repo, releaseTip, version: source.version, allowOlder }); const { parent, parentKind } = selectParent({ repo, releaseTip, sourceCommit: source.sourceCommit, allowMissingReleaseBranch }); const keep = Boolean(output); const dir = keep ? path.resolve(output) : fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-payload-")); try { const { modes, excluded } = assemblePayload({ repo, commit: source.sourceCommit, output: dir }); const before = validatePayload(dir); if (!before.ok) throw new PublishError(`the runtime payload of ${tag} is not valid`, before.report); writeInstallRefManifest(dir, source); const validation = validatePayload(dir); if (!validation.ok || !validation.manifest) throw new PublishError(`the runtime payload of ${tag} is not valid after the manifest was written`, validation.report); const message = `Install payload for ${tag}\n\nSource commit: ${source.sourceCommit}\n`; const { tree, commit } = createSyntheticCommit({ repo, dir, modes, parent, message }); checkFastForward({ repo, priorTip: releaseTip, commit }); if (!dryRun) git(repo, ["push", "--atomic", REMOTE, `${commit}:${installTagRef}`, `${commit}:${RELEASE_BRANCH_REF}`]); return { ok: true, dryRun, pushed: !dryRun, tag, version: source.version, sourceCommit: source.sourceCommit, commit, tree, parent, parentKind, files: validation.files, bytes: validation.bytes, excluded, manifest: INSTALL_REF_MANIFEST, refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF }, payload: keep ? dir : null, validation: { missing: validation.missing, unexpected: validation.unexpected, forbidden: validation.forbidden }, }; } finally { if (!keep) fs.rmSync(dir, { recursive: true, force: true }); } } export const USAGE = `Usage: node scripts/publish-install-refs.mjs --tag vX.Y.Z [options] Publishes the slim runtime payload of a release as refs/tags/install-vX.Y.Z and the new fast-forward tip of refs/heads/release, in one push to origin. --tag the release tag (required, exact vX.Y.Z) --repo the full release checkout (default: the current folder) --output assemble the payload into this empty folder and keep it --dry-run build and check everything, push nothing --json also write the result as JSON to this file --allow-missing-release-branch first publication: parent the source tag's commit when refs/heads/release does not exist yet --allow-older move refs/heads/release even when it already installs this version or a newer one (a deliberate rollback) `; /** `{ options }` from argv, or `{ error }` for anything unknown, missing or malformed. */ export function parseArgs(argv) { const options = { tag: null, repo: null, output: null, dryRun: false, json: null, allowMissingReleaseBranch: false, allowOlder: false }; const valued = { "--tag": "tag", "--repo": "repo", "--output": "output", "--json": "json" }; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg in valued) { const value = argv[++i]; if (value === undefined || value.startsWith("--")) return { error: `${arg} needs a value` }; options[valued[arg]] = value; } else if (arg === "--dry-run") options.dryRun = true; else if (arg === "--allow-missing-release-branch") options.allowMissingReleaseBranch = true; else if (arg === "--allow-older") options.allowOlder = true; else return { error: `unknown argument: ${arg}` }; } if (!options.tag) return { error: "--tag is required" }; if (!TAG_SHAPE.test(options.tag)) return { error: `--tag must be an exact vX.Y.Z release tag, not "${options.tag}"` }; return { options }; } function main(argv) { const parsed = parseArgs(argv); if (parsed.error) { process.stderr.write(`${parsed.error}\n\n${USAGE}`); return 2; } const { options } = parsed; const writeJson = (value) => { if (options.json) fs.writeFileSync(options.json, `${JSON.stringify(value, null, 2)}\n`); }; try { const result = publishInstallRefs({ tag: options.tag, repo: options.repo || process.cwd(), dryRun: options.dryRun, output: options.output, allowMissingReleaseBranch: options.allowMissingReleaseBranch, allowOlder: options.allowOlder, }); writeJson(result); if (result.alreadyPublished) { process.stdout.write(`${result.tag} is already published: ${result.refs.tag} and ${result.refs.branch} point at ${result.commit}\n`); return 0; } const verb = result.dryRun ? "Would publish" : "Published"; process.stdout.write( `${verb} ${result.commit} (tree ${result.tree}) to ${result.refs.tag} and ${result.refs.branch}\n` + ` parent ${result.parent} (${result.parentKind}), ${result.files} files, ${result.bytes} bytes, ${result.excluded} source files left out\n`, ); return 0; } catch (err) { if (!(err instanceof PublishError)) throw err; writeJson({ ok: false, error: err.message, details: err.details }); process.stderr.write(`publish-install-refs: ${err.message}\n${err.details ? `${err.details.join("\n")}\n` : ""}Nothing was pushed.\n`); return 1; } } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { process.exitCode = main(process.argv.slice(2)); }