kernel / .github / npm-publish.mjsmain at 949894f
// npm-publish.mjs — THE `iterate` PACKAGE ON NPM, FROM THIS REPOSITORY. `core/lib` is the package.
// The jobs of .github/workflows/npm-publish.yml are this file's four commands:
//
// node .github/npm-publish.mjs pack --dist-tag main --out out
// node .github/npm-publish.mjs install --tarball out/iterate-<version>.tgz
// node .github/npm-publish.mjs publish --tarball out/iterate-<version>.tgz --dist-tag main
// node .github/npm-publish.mjs check
//
// `pack` packs `core/lib` of this checkout as pnpm packs it (its `prepack` builds it; `catalog:`
// and `workspace:` become versions, and publishConfig applies). The manifest gets the version
// (`versionAt`) and `gitHead` and loses `devDependencies`, which no consumer installs. It is the
// only command that runs the package's code, and its job has no token of npm's. `install` installs
// that tarball where nothing of ours is. `publish` hands npm the same file, with no script of it
// run. A package whose files equal those of the version that its dist-tag names now is not
// published again. Under `main`, `latest` then names what `main` names: it is what npmjs.com shows
// and what `npx iterate` gets.
//
// The job that publishes authenticates by npm's trusted publishing (the job's OIDC token; npm
// 11.5.1 or later): the package's settings on npmjs.com name github.com/iterate/kernel, the
// workflow's file and the environment `npm`. `check` says what the package still lacks there. By
// hand, `npm login` first.
//
// No dependency: the job that holds npm's token runs this file, Node and npm, and nothing else.
import { execFileSync } from "node:child_process";
import {
appendFileSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join, relative, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
/** The package, and its folder in this repository. */
const NAME = "iterate";
const FOLDER = "core/lib";
/** What `install` runs once the package is installed: the CLI starts, and finds a command. */
const SMOKE = [
["iterate", "--version"],
["iterate", "git", "setup", "--help"],
];
/** This repository's root: this file is in `.github`. */
const ROOT = fileURLToPath(new URL("..", import.meta.url));
/** The workflow's file: what a package's trusted publisher on npmjs.com names. */
const WORKFLOW = "npm-publish.yml";
const DIST_TAGS = ["main", "canary"];
/**
* The npm version of a package at a commit: `<package.json version>-<dist-tag>.<committer date>-<sha>`,
* such as `0.1.0-main.20261002T164000Z-3202ce3`. The date is the commit's own, to the second, never
* the clock's, so the version is the same whenever it is worked out. The sha is its first seven
* digits, to tell the commit by eye; the manifest's `gitHead` holds all forty. semver compares a
* prerelease identifier as ASCII text, and the fixed-width date leads it, so a later commit's
* version sorts higher.
*/
export function versionAt({ version, distTag, committedAt, sha }) {
const stamp = new Date(committedAt).toISOString().slice(0, 19).replace(/\W/g, "");
return `${version}-${distTag}.${stamp}Z-${sha.slice(0, 7)}`;
}
/** Whether a consumer would get anything new from `packed` over `published`, two packages as
* their files (path to bytes): their files differ, or their manifests do in more than `version`
* and `gitHead`, which name the build and not what it holds, and `devDependencies`. A dependency
* map's order is no difference: pnpm writes the ones it resolves in whichever order they settle. */
export function differs(packed, published) {
const content = (files) =>
[...files]
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([path, bytes]) => {
if (path !== "package.json") return [path, bytes.toString("base64")];
const { version: _v, gitHead: _g, devDependencies: _d, ...manifest } = JSON.parse(bytes);
for (const field of ["dependencies", "peerDependencies", "optionalDependencies"])
if (manifest[field])
manifest[field] = Object.fromEntries(
Object.entries(manifest[field]).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
);
return [path, JSON.stringify(manifest)];
});
return JSON.stringify(content(packed)) !== JSON.stringify(content(published));
}
/**
* Packs the package at this checkout's commit into the folder `out`, and says what it packed: the
* commit, the version, how it compares with what `distTag` names on npm, and the tarball's file
* count and npm's `integrity` of it. Publishes nothing.
*/
export async function pack({ distTag, out }) {
const name = NAME;
const folder = FOLDER;
const work = mkdtempSync(join(tmpdir(), "npm-publish-"));
try {
const checkout = ROOT;
const git = (...args) => execFileSync("git", args, { cwd: checkout, encoding: "utf8" }).trim();
const sha = git("rev-parse", "HEAD");
// the version and `gitHead` name the commit, so the package's files must be that commit's
const changed = git("status", "--porcelain", "--", folder);
if (changed) throw new Error(`${folder} differs from ${sha}:\n${changed}`);
const committedAt = git("log", "-1", "--format=%cI", sha);
// what the pack's build needs, by this repository's lockfile and its pnpm
const run = (cwd, command, ...args) =>
execFileSync(command, args, { cwd, stdio: ["ignore", process.stderr, "inherit"] });
run(checkout, "pnpm", "install", "--frozen-lockfile", "--filter", `${name}...`);
run(join(checkout, folder), "pnpm", "pack", "--pack-destination", join(work, "pnpm"));
const [tarball, ...more] = readdirSync(join(work, "pnpm"));
if (!tarball || more.length)
throw new Error(`pnpm pack of ${folder} wrote ${[tarball, ...more]}`);
unpack(join(work, "pnpm", tarball), join(work, "packed"));
const manifestPath = join(work, "packed/package/package.json");
const { devDependencies: _d, ...manifest } = JSON.parse(readFileSync(manifestPath, "utf8"));
if (manifest.name !== name) throw new Error(`${folder} holds ${manifest.name}, not ${name}`);
const version = versionAt({ version: manifest.version, distTag, committedAt, sha });
writeFileSync(
manifestPath,
`${JSON.stringify({ ...manifest, version, gitHead: sha }, null, 2)}\n`,
);
mkdirSync(out, { recursive: true });
const [packed] = JSON.parse(
execFileSync(
"npm",
[
"pack",
join(work, "packed/package"),
"--pack-destination",
out,
"--ignore-scripts",
"--json",
],
{ encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] },
),
);
const last = await publishedAt(name, distTag, work);
const compared = !last
? `npm has no \`${distTag}\` of it`
: differs(filesOf(join(work, "packed/package")), last.files)
? `differs from ${last.version}`
: `the same files as ${last.version}: a publish would skip it`;
await say(
[
`${name}@${version}`,
`- source: ${folder} at ${sha}`,
`- tarball: ${packed.filename}, ${packed.entryCount} files, ${packed.integrity}`,
`- npm \`${distTag}\`: ${compared}`,
].join("\n"),
);
} finally {
rmSync(work, { recursive: true, force: true });
}
}
/** Installs `tarball` in an empty folder, with its dependencies from npm, and runs SMOKE there. */
export function install({ tarball }) {
const work = mkdtempSync(join(tmpdir(), "npm-publish-install-"));
try {
unpack(resolve(tarball), work);
const { name } = JSON.parse(readFileSync(join(work, "package/package.json"), "utf8"));
if (name !== NAME) throw new Error(`${tarball} holds ${name}, not ${NAME}`);
const at = join(work, "install");
mkdirSync(at);
writeFileSync(join(at, "package.json"), "{}\n");
const run = (command, ...args) => {
console.log(`$ ${[command, ...args].join(" ")}`);
execFileSync(command, args, { cwd: at, stdio: "inherit" });
};
run("npm", "install", resolve(tarball));
for (const command of SMOKE) run("npx", "--no-install", ...command);
} finally {
rmSync(work, { recursive: true, force: true });
}
}
/**
* Publishes one tarball that `pack` made, as it is, under `distTag`, and waits until npm serves
* it; under `main`, `latest` then names what `main` names. No script of the package runs. Nothing
* is published when the tarball's files equal those of the version that `distTag` names now, or
* when npm has the version already, so a second run only moves the tags it can.
*/
export async function publish({ tarball, distTag, dryRun }) {
const work = mkdtempSync(join(tmpdir(), "npm-publish-publish-"));
try {
unpack(resolve(tarball), join(work, "packed"));
const { name, version } = JSON.parse(
readFileSync(join(work, "packed/package/package.json"), "utf8"),
);
if (name !== NAME) throw new Error(`${tarball} holds ${name}, not ${NAME}`);
if (!version.includes(`-${distTag}.`))
throw new Error(`${name}@${version} was not packed for the dist-tag ${distTag}`);
const npm = await packumentOf(name);
const last = await publishedAt(name, distTag, work);
// a run that was held back: the dist-tag names a later commit's version already. The date
// leads the version, so text order is commit order.
if (
last &&
last.version.startsWith(`${version.split("-")[0]}-${distTag}.`) &&
last.version > version
)
return await say(
`npm \`${distTag}\` names ${last.version}, which is later than ${version}: not published`,
);
const unchanged = last && !differs(filesOf(join(work, "packed/package")), last.files);
const has = Boolean(npm?.versions[version]);
const names = unchanged ? last.version : version;
let line = unchanged
? `${name}: the same files as ${last.version}, not published`
: has
? `${name}@${version}: npm has it already`
: `${name}@${version}${dryRun ? " (dry run)" : ""}`;
if (!unchanged && !has) {
// npm makes the provenance statement by itself: the job is of a public repository, and the
// manifest's `repository.url` names it.
execFileSync(
"npm",
[
"publish",
resolve(tarball),
"--tag",
distTag,
"--access",
"public",
"--ignore-scripts",
...(dryRun ? ["--dry-run"] : []),
],
{ stdio: "inherit" },
);
if (!dryRun) await untilNpmServes({ name, distTag, version });
}
const latest = npm?.["dist-tags"].latest;
let refused = false;
if (distTag === "main" && latest !== names) {
const moved = dryRun ? undefined : await pointLatestAt(name, names);
refused = Boolean(moved);
line += moved
? `; \`latest\` stays ${latest || "unset"}: ${moved}`
: `; \`latest\` is now ${names}, was ${latest || "unset"}${dryRun ? " (dry run)" : ""}`;
}
await say(`npm \`${distTag}\`: ${line}`);
if (refused) throw new Error(`npm would not move \`latest\` of ${name}`);
} finally {
rmSync(work, { recursive: true, force: true });
}
}
/** Fails unless npm is ready for this repository's workflow to publish the package, and says
* what sets it up when it is not (`missingOnNpm`). */
export async function check() {
const oidc = jobOidc();
if (!oidc) throw new Error(`check asks npm as a job of ${WORKFLOW}, which this is not`);
const missing = await missingOnNpm(NAME, oidc);
if (!missing) return await say(`npm is ready for this workflow to publish ${NAME}.`);
await say(
[`${missing.said}. As someone who may publish it:`, "", "```sh", ...missing.setup, "```"].join(
"\n",
),
);
throw new Error(`npm is not ready for ${NAME}`);
}
/** What a package needs on npmjs.com before the workflow can publish it, in the order it gets
* them. */
const NPM_SETUP = ["package", "trusted publisher", "dist-tag"];
/** The tag `missingOnNpm` adds to a package and removes again. Nothing reads it. */
const CHECK_TAG = "npm-publish-check";
/**
* WHAT `name` STILL NEEDS ON NPMJS.COM BEFORE THE WORKFLOW CAN PUBLISH IT: the first of NPM_SETUP
* it lacks, with npm's answer and the commands for it and each step after (`setup`), or undefined
* when it has them all. Asked as a job of the workflow that the package is to trust:
*
* - `package`: npm has no such package, and sets a trusted publisher only on one that exists.
* - `trusted publisher`: npm trades the job no token for the package.
* - `dist-tag`: npm refuses the traded token a tag. npm shows a trusted publisher's permissions to
* no token, so the test is a write: CHECK_TAG, added at the version `latest` names and removed
* again, each with a token of its own. `latest` and `main` are never written.
*
* "Allow npm publish" is not checked: only a publish would show it.
*/
async function missingOnNpm(name, oidc) {
const repository = process.env.GITHUB_REPOSITORY;
const commands = {
package: `cd "$(mktemp -d)" && echo '${JSON.stringify({ name, version: "0.0.0" })}' > package.json && npm publish --access public`,
"trusted publisher": `open https://www.npmjs.com/package/${name}/access && echo 'Add a trusted publisher: GitHub Actions, ${repository}, ${WORKFLOW}, environment npm, "Allow npm publish"'`,
"dist-tag": `open https://www.npmjs.com/package/${name}/access && echo 'On the trusted publisher of ${repository}, tick "Allow npm dist-tag", save'`,
};
const lacks = (step, said) => ({
said,
setup: NPM_SETUP.slice(NPM_SETUP.indexOf(step)).map((each) => commands[each]),
});
const tags = `https://registry.npmjs.org/-/package/${name.replace("/", "%2f")}/dist-tags`;
const read = await fetchRepeated(tags);
if (!read.ok)
return lacks(
"package",
`${name} is not on npm (npm answered ${read.status}: ${await read.text()})`,
);
const { latest } = await read.json();
const toAdd = await tradedToken(name, oidc);
if (toAdd.refused)
return lacks(
"trusted publisher",
`${name} does not trust this workflow to publish it (${toAdd.refused})`,
);
// a write is sent once: npm takes its token for one request to this route
const added = await fetch(`${tags}/${CHECK_TAG}`, {
method: "PUT",
headers: { authorization: `Bearer ${toAdd.token}`, "content-type": "application/json" },
body: JSON.stringify(latest),
});
if (!added.ok)
return lacks(
"dist-tag",
`${name} does not let this workflow move its dist-tags (npm answered ${added.status}: ${await added.text()})`,
);
const toRemove = await tradedToken(name, oidc);
if (toRemove.refused)
throw new Error(
`${name} keeps the tag ${CHECK_TAG}: no token to remove it, ${toRemove.refused}`,
);
const removed = await fetch(`${tags}/${CHECK_TAG}`, {
method: "DELETE",
headers: { authorization: `Bearer ${toRemove.token}` },
});
if (!removed.ok)
throw new Error(
`${name} keeps the tag ${CHECK_TAG}: npm answered its removal ${removed.status}: ${await removed.text()}`,
);
return undefined;
}
/**
* Makes `latest` of `name` name `version`; answers npm's reason when npm refuses, else undefined.
* `npm dist-tag add`, as whoever npm is logged in as. In CI that is no one: trusted publishing logs
* in `npm publish` alone. So the same trade is made here (`tradedToken`), and npm is handed the
* token in a config file of its own. npm moves a tag for that token only where the package's
* trusted publisher has "Allow npm dist-tag".
*/
async function pointLatestAt(name, version) {
const config = mkdtempSync(join(tmpdir(), "npm-publish-latest-"));
try {
const oidc = jobOidc();
const traded = oidc && (await tradedToken(name, oidc));
if (traded?.refused) return `no token for ${name}: ${traded.refused}`;
if (traded)
writeFileSync(join(config, "npmrc"), `//registry.npmjs.org/:_authToken=${traded.token}\n`);
execFileSync("npm", ["dist-tag", "add", `${name}@${version}`, "latest"], {
stdio: ["inherit", "inherit", "pipe"],
encoding: "utf8",
env: traded ? { ...process.env, NPM_CONFIG_USERCONFIG: join(config, "npmrc") } : process.env,
});
return undefined;
} catch (error) {
const output = String(error.stderr || error.message);
process.stderr.write(`${output}\n`);
// npm's own sentence when it has one: `npm error 403 403 Forbidden - PUT … - <why>`
return output.match(/^npm error \d{3} (.+)$/m)?.[1] || output.trim().split("\n")[0];
} finally {
rmSync(config, { recursive: true, force: true });
}
}
/** How this job asks GitHub for its OIDC token (a GitHub Actions job with `id-token: write`), or
* undefined anywhere else. */
function jobOidc() {
const { ACTIONS_ID_TOKEN_REQUEST_URL: url, ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer } = process.env;
return url && bearer ? { url, bearer } : undefined;
}
/**
* npm's token for `name` in a GitHub Actions job whose workflow the package trusts, as `npm
* publish` gets one (npm/cli lib/utils/oidc.js): the job's OIDC token, for npm's audience, traded
* at the registry. npm takes a token for one request to a route. `refused` is npm's answer when it
* trades none: the same 404, "package not found", for a package that it does not have and for one
* whose trusted publishers do not name the job's workflow.
*/
async function tradedToken(name, oidc) {
const identity = await fetchRepeated(`${oidc.url}&audience=npm:registry.npmjs.org`, {
headers: { authorization: `Bearer ${oidc.bearer}` },
});
if (!identity.ok)
throw new Error(
`GET the job's OIDC token answered ${identity.status}: ${await identity.text()}`,
);
const { value } = await identity.json();
const traded = await fetchRepeated(
`https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/${name.replace("/", "%2f")}`,
{ method: "POST", headers: { authorization: `Bearer ${value}` } },
);
if (!traded.ok) return { refused: `npm answered ${traded.status}: ${await traded.text()}` };
return { token: (await traded.json()).token };
}
/** Prints `text`, and adds it to the job's summary in GitHub Actions. */
async function say(text) {
console.log(text);
if (process.env.GITHUB_STEP_SUMMARY)
appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n\n`);
}
/** Extracts `tarball` into the new folder `into`, whose `package/` it fills. */
function unpack(tarball, into) {
mkdirSync(into, { recursive: true });
execFileSync("tar", ["-xzf", tarball, "-C", into]);
}
/** Every file under `folder`, by its path there. */
function filesOf(folder) {
return new Map(
readdirSync(folder, { recursive: true, withFileTypes: true })
.filter((entry) => entry.isFile())
.map((entry) => {
const file = join(entry.parentPath, entry.name);
return [relative(folder, file), readFileSync(file)];
}),
);
}
/** How often a read is asked again when the connection fails or the server answers 429 or 5xx. */
const HTTP_DELAYS_MS = [1_000, 5_000, 15_000];
/** `fetch`, asked again after each of `delaysMs` while the connection fails or `again` says so of
* the answer. Only for a request that may be sent twice. */
async function fetchRepeated(url, init = {}, options = {}) {
const { delaysMs = HTTP_DELAYS_MS, again = (r) => r.status === 429 || r.status >= 500 } = options;
for (let attempt = 0; ; attempt++) {
const last = attempt === delaysMs.length;
try {
const response = await fetch(url, { ...init, signal: AbortSignal.timeout(120_000) });
if (last || !(await again(response.clone()))) return response;
await response.arrayBuffer().catch(() => undefined);
} catch (error) {
if (last) throw error;
}
await sleep(delaysMs[attempt]);
}
}
/** What npm has of `name` (its dist-tags, and each version's tarball), or undefined before the
* first publish. `?write=true` asks for the packument uncached, as npm does before it writes one:
* the cached copy lags by up to five minutes. */
async function packumentOf(name, options) {
const url = `https://registry.npmjs.org/${name.replace("/", "%2f")}?write=true`;
const answer = await fetchRepeated(url, {}, options);
if (answer.status === 404) return undefined;
if (!answer.ok) throw new Error(`GET ${url} answered ${answer.status}`);
return await answer.json();
}
/** npm serves a fresh version in its packument minutes before its tarball. A tarball that the
* packument names is asked for again on this schedule, about eight minutes in all. */
const NPM_PROCESSING_MS = [10_000, 20_000, 30_000, ...Array.from({ length: 6 }, () => 60_000)];
/** The version that `distTag` of `name` names on npm, with its files, or undefined when nothing
* has that tag yet. `work` is a folder to unpack in. */
async function publishedAt(name, distTag, work) {
const npm = await packumentOf(name);
const version = npm?.["dist-tags"][distTag];
if (!version) return undefined;
const url = npm.versions[version].dist.tarball;
const answer = await fetchRepeated(
url,
{},
{
delaysMs: NPM_PROCESSING_MS,
again: (r) => r.status === 404 || r.status === 429 || r.status >= 500,
},
);
if (!answer.ok) throw new Error(`GET ${url} answered ${answer.status}`);
const into = mkdtempSync(join(work, "published-"));
writeFileSync(join(into, "tarball.tgz"), Buffer.from(await answer.arrayBuffer()));
unpack(join(into, "tarball.tgz"), into);
return { version, files: filesOf(join(into, "package")) };
}
/** How long a publish waits for npm to serve its version: about thirteen minutes in all, twice
* the longest wait measured. */
const NPM_SERVES_MS = [10_000, 20_000, 30_000, ...Array.from({ length: 12 }, () => 60_000)];
/**
* Waits until npm's packument names `version` under `distTag`, and throws what the dist-tag still
* names when it never does. `npm publish` returns once npm has taken a version; its packument holds
* it later (100 seconds to six minutes, measured 2026-11-12). Until then the dist-tag names the
* version before, and npm can drop a `latest` move to the new version.
*/
async function untilNpmServes({ name, distTag, version }) {
let names;
await packumentOf(name, {
delaysMs: NPM_SERVES_MS,
again: async (r) => {
if (r.status === 429 || r.status >= 500) return true;
// a 404 is a package's first publish: npm has no packument for it yet
names = r.ok ? (await r.json())["dist-tags"][distTag] : undefined;
return names !== version;
},
});
if (names !== version)
throw new Error(
`npm has yet to serve ${name}@${version}: \`${distTag}\` names ${names || "nothing"}`,
);
}
// `install` runs on Node 22, which has no `import.meta.main`
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [command, ...rest] = process.argv.slice(2);
const { values } = parseArgs({
args: rest,
options: {
"dist-tag": { type: "string", default: "main" },
out: { type: "string", default: "out" },
tarball: { type: "string" },
"dry-run": { type: "boolean", default: false },
},
});
const distTag = values["dist-tag"];
if (!DIST_TAGS.includes(distTag)) throw new Error(`--dist-tag is one of ${DIST_TAGS.join(", ")}`);
const one = (what, value) => {
if (!value) throw new Error(`${command} needs --${what}`);
return value;
};
if (command === "pack") await pack({ distTag, out: resolve(values.out) });
else if (command === "install") install({ tarball: one("tarball", values.tarball) });
else if (command === "publish")
await publish({ tarball: one("tarball", values.tarball), distTag, dryRun: values["dry-run"] });
else if (command === "check") await check();
else throw new Error("usage: node .github/npm-publish.mjs <pack | install | publish | check> …");
}