Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/release-please.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ on:
branches:
- main

concurrency:
group: release-please-${{ github.ref }}
cancel-in-progress: false

permissions:
contents: write
pull-requests: write
Expand Down
8 changes: 6 additions & 2 deletions docs/releasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ This monorepo uses Release Please for independent package releases.

## Release model

Each package under `packages/*` has its own Release Please entry. A change to one package should only release that package.
Release Please maintains one aggregate `chore: release main` PR for all changed packages. More package changes update that open aggregate PR before merge.

Each package under `packages/*` has its own Release Please entry. Packages in the aggregate PR still receive independent versions, changelogs, GitHub releases, and component-prefixed tags (for example, `pi-arc-v0.12.0`). A change to one package should only release that package; aggregation does not link package versions.

### Imported package baselines

Expand Down Expand Up @@ -87,7 +89,9 @@ Current package entries include:

## npm provenance

Publishing uses GitHub Actions and npm provenance through `scripts/npm-publish-workspace-if-needed.mjs`. The release workflow runs the helper for each workspace package on every `main` push. The helper checks whether the exact workspace package version already exists on npm and skips duplicate publishes, which keeps reruns/idempotent release attempts from failing after a GitHub release has already been cut and also repairs cases where a GitHub release exists but npm publish failed.
Publishing uses GitHub Actions and npm provenance through `scripts/npm-publish-workspace-if-needed.mjs`. The release workflow serializes `main` runs using a ref-scoped concurrency group without cancelling in-progress publishing. It runs the helper for every workspace package on every `main` push, not only packages reported by Release Please as newly released. The helper checks whether the exact workspace package version already exists on npm and skips duplicate publishes. This all-package scan is a recovery mechanism when a GitHub release succeeds but npm publication fails.

After a successful real publish, the helper waits for exact-version registry visibility by polling `npm view <package-name>@<package-version> version --json`. It defaults to 24 attempts with a 5000 ms delay between not-found responses. `NPM_PUBLISH_VERIFY_ATTEMPTS` and `NPM_PUBLISH_VERIFY_DELAY_MS` override those defaults; each must be a positive base-10 integer within JavaScript's safe integer range, or the helper fails before publishing. Exhausted attempts fail with the package version and attempt count, while non-not-found errors fail immediately and forward npm's output. Publishes using `--dry-run` skip post-publish visibility checks because they create no registry version.

```bash
node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-arc
Expand Down
3 changes: 2 additions & 1 deletion packages/pi-git-spice/tests/package.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ test("migration implementation and focused tests stay within their complete-area
test("package exposes the exact Pi git-spice runtime and publishable metadata", () => {
const pkg = readJson("package.json");
assert.equal(pkg.name, "@sentiolabs/pi-git-spice");
assert.equal(pkg.version, "0.1.0");
assert.match(pkg.version,
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);
assert.equal(pkg.license, "MIT");
assert.equal(pkg.repository.directory, "packages/pi-git-spice");
assert.deepEqual(pkg.pi, {
Expand Down
4 changes: 3 additions & 1 deletion release-please-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"release-type": "node",
"include-component-in-tag": true,
"separate-pull-requests": true,
"separate-pull-requests": false,
"always-update": true,
"group-pull-request-title-pattern": "chore: release ${branch}",
"packages": {
"packages/pi-arc": {
"component": "pi-arc",
Expand Down
48 changes: 47 additions & 1 deletion scripts/npm-publish-workspace-if-needed.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,29 @@ if (!packageName) {

const rootDir = process.cwd();
const npmCommand = process.env.NPM_PUBLISH_IF_NEEDED_NPM ?? "npm";
const verifyAttempts = positiveIntegerEnv("NPM_PUBLISH_VERIFY_ATTEMPTS", 24);
const verifyDelayMs = positiveIntegerEnv("NPM_PUBLISH_VERIFY_DELAY_MS", 5000);

function positiveIntegerEnv(name, defaultValue) {
const raw = process.env[name];
if (raw === undefined) return defaultValue;

const value = Number(raw);
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value <= 0) {
console.error(`${name} must be a positive base-10 integer within the safe integer range.`);
process.exit(1);
}
return value;
}

async function sleep(delayMs) {
// Node clamps oversized timers to 1 ms; split long configured delays instead.
for (let remaining = delayMs; remaining > 0;) {
const interval = Math.min(remaining, 2_147_483_647);
await new Promise((resolve) => setTimeout(resolve, interval));
remaining -= interval;
}
}

function readJson(path) {
return JSON.parse(readFileSync(path, "utf8"));
Expand Down Expand Up @@ -212,4 +235,27 @@ const publishResult = spawnSync(
},
);

process.exit(publishResult.status ?? 1);
if (publishResult.status !== 0 || publishExtraArgs.includes("--dry-run")) {
process.exit(publishResult.status ?? 1);
}

for (let attempt = 1; attempt <= verifyAttempts; attempt += 1) {
const visibilityResult = runNpm(["view", versionSpecifier, "version", "--json"]);
if (visibilityResult.status === 0) {
console.log(`${versionSpecifier} is visible on npm (attempt ${attempt}/${verifyAttempts}).`);
process.exit(0);
}

if (!isNpmNotFound(visibilityResult)) {
process.stdout.write(visibilityResult.stdout ?? "");
process.stderr.write(visibilityResult.stderr ?? "");
process.exit(visibilityResult.status ?? 1);
}

if (attempt === verifyAttempts) {
console.error(`${versionSpecifier} is still not visible on npm after ${verifyAttempts} attempts; registry visibility verification timed out.`);
process.exit(1);
}

await sleep(verifyDelayMs);
}
192 changes: 188 additions & 4 deletions tests/npm-publish-workspace-if-needed.test.mjs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import assert from "node:assert/strict";
import { chmodSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import test from "node:test";
import test, { after } from "node:test";

const scriptPath = new URL("../scripts/npm-publish-workspace-if-needed.mjs", import.meta.url).pathname;
const packageName = "@sentiolabs/example";

function setupWorkspace(version = "1.2.3") {
const dir = mkdtempSync(join(tmpdir(), "pi-nexus-publish-test-"));
after(() => rmSync(dir, { recursive: true, force: true }));
mkdirSync(join(dir, "packages", "example"), { recursive: true });
writeFileSync(
join(dir, "package.json"),
Expand All @@ -24,7 +25,55 @@ function setupWorkspace(version = "1.2.3") {
const fakeNpmPath = join(dir, "fake-npm.mjs");
writeFileSync(
fakeNpmPath,
`#!/usr/bin/env node\nimport { appendFileSync } from 'node:fs';\nconst callsPath = process.env.FAKE_NPM_CALLS;\nconst packageName = process.env.FAKE_NPM_PACKAGE_NAME;\nconst packageVersion = process.env.FAKE_NPM_PACKAGE_VERSION;\nconst args = process.argv.slice(2);\nappendFileSync(callsPath, JSON.stringify(args) + '\\n');\nif (args[0] === 'view' && args[1] === packageName + '@' + packageVersion) {\n if (process.env.FAKE_NPM_EXACT_EXISTS === '1') {\n console.log(JSON.stringify(packageVersion));\n process.exit(0);\n }\n console.error('npm error code E404');\n console.error('npm error 404 No match found for version ' + packageVersion);\n process.exit(1);\n}\nif (args[0] === 'view' && args[1] === packageName) {\n const latest = process.env.FAKE_NPM_LATEST_VERSION;\n if (latest) {\n console.log(JSON.stringify(latest));\n process.exit(0);\n }\n console.error('npm error code E404');\n console.error('npm error 404 package not found');\n process.exit(1);\n}\nif (args[0] === 'publish') {\n process.exit(0);\n}\nprocess.exit(99);\n`,
`#!/usr/bin/env node
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
const callsPath = process.env.FAKE_NPM_CALLS;
const packageName = process.env.FAKE_NPM_PACKAGE_NAME;
const packageVersion = process.env.FAKE_NPM_PACKAGE_VERSION;
const args = process.argv.slice(2);
const calls = existsSync(callsPath)
? readFileSync(callsPath, 'utf8').trim().split('\\n').filter(Boolean).map((line) => JSON.parse(line))
: [];
appendFileSync(callsPath, JSON.stringify(args) + '\\n');
if (args[0] === 'view' && args[1] === packageName + '@' + packageVersion) {
const publishIndex = calls.findLastIndex((call) => call[0] === 'publish');
if (publishIndex !== -1) {
if (process.env.FAKE_NPM_VISIBILITY_ERROR) {
console.log('visibility error stdout');
console.error('npm error code ' + process.env.FAKE_NPM_VISIBILITY_ERROR);
process.exit(7);
}
const previousChecks = calls.slice(publishIndex + 1).filter((call) => call[0] === 'view').length;
if (previousChecks >= Number(process.env.FAKE_NPM_VISIBILITY_MISSES)) {
console.log(JSON.stringify(packageVersion));
process.exit(0);
}
console.error(process.env.FAKE_NPM_VISIBILITY_NOT_FOUND);
process.exit(1);
}
if (process.env.FAKE_NPM_EXACT_EXISTS === '1') {
console.log(JSON.stringify(packageVersion));
process.exit(0);
}
console.error('npm error code E404');
console.error('npm error 404 No match found for version ' + packageVersion);
process.exit(1);
}
if (args[0] === 'view' && args[1] === packageName) {
const latest = process.env.FAKE_NPM_LATEST_VERSION;
if (latest) {
console.log(JSON.stringify(latest));
process.exit(0);
}
console.error('npm error code E404');
console.error('npm error 404 package not found');
process.exit(1);
}
if (args[0] === 'publish') {
process.exit(Number(process.env.FAKE_NPM_PUBLISH_EXIT));
}
process.exit(99);
`,
);
chmodSync(fakeNpmPath, 0o755);

Expand All @@ -35,19 +84,28 @@ function runScript({ dir, callsPath, fakeNpmPath, version }, options = {}) {
return spawnSync(process.execPath, [scriptPath, packageName, ...(options.extraArgs ?? [])], {
cwd: dir,
encoding: "utf8",
timeout: options.timeout ?? 10_000,
env: {
...process.env,
FAKE_NPM_CALLS: callsPath,
FAKE_NPM_EXACT_EXISTS: options.exactExists ? "1" : "0",
FAKE_NPM_LATEST_VERSION: options.latestVersion ?? "",
FAKE_NPM_PACKAGE_NAME: packageName,
FAKE_NPM_PACKAGE_VERSION: version,
FAKE_NPM_VISIBILITY_MISSES: String(options.visibilityMisses ?? 0),
FAKE_NPM_VISIBILITY_ERROR: options.visibilityError ?? "",
FAKE_NPM_VISIBILITY_NOT_FOUND: options.visibilityNotFound ?? "npm error code E404",
FAKE_NPM_PUBLISH_EXIT: String(options.publishExit ?? 0),
NPM_PUBLISH_VERIFY_ATTEMPTS: "3",
NPM_PUBLISH_VERIFY_DELAY_MS: "1",
...options.verifyEnv,
NPM_PUBLISH_IF_NEEDED_NPM: fakeNpmPath,
},
});
}

function readCalls(callsPath) {
if (!existsSync(callsPath)) return [];
return readFileSync(callsPath, "utf8")
.trim()
.split("\n")
Expand All @@ -67,7 +125,7 @@ test("publish helper skips workspace package versions already on npm", () => {
]);
});

test("publish helper publishes workspace package versions missing from npm", () => {
test("publish helper dry-run skips post-publish visibility checks", () => {
const workspace = setupWorkspace();

const result = runScript(workspace, { latestVersion: "1.2.2", extraArgs: ["--dry-run"] });
Expand Down Expand Up @@ -118,3 +176,129 @@ test("publish helper allows prereleases with an explicit non-latest dist-tag", (
["publish", "--workspace", "@sentiolabs/example", "--access", "public", "--provenance", "--tag", "next", "--dry-run"],
]);
});

function expectedPublishCalls(version = "1.2.3", extraArgs = []) {
return [
["view", `${packageName}@${version}`, "version", "--json"],
["view", packageName, "version", "--json"],
["publish", "--workspace", packageName, "--access", "public", "--provenance", ...extraArgs],
];
}

for (const visibilityMisses of [0, 1, 2]) {
test(`publish helper confirms visibility after ${visibilityMisses} exact-version misses`, () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { latestVersion: "1.2.2", visibilityMisses });

assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /@sentiolabs\/example@1\.2\.3.*visible/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
...Array.from({ length: visibilityMisses + 1 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]),
]);
});
}

for (const visibilityNotFound of ["npm error code E404", "404 Not Found", "No match found for version 1.2.3"]) {
test(`publish helper fails after the final visibility attempt for ${visibilityNotFound}`, () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { visibilityMisses: 3, visibilityNotFound });

assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /@sentiolabs\/example@1\.2\.3.*not visible.*3 attempts/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
...Array.from({ length: 3 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]),
]);
});
}

test("publish helper forwards non-404 visibility errors and fails without retrying", () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { visibilityError: "E401" });

assert.equal(result.status, 7, result.stderr);
assert.match(result.stdout, /visibility error stdout/);
assert.match(result.stderr, /npm error code E401/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
["view", `${packageName}@1.2.3`, "version", "--json"],
]);
});

test("publish helper does not check visibility after a failed publish", () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { publishExit: 9 });

assert.equal(result.status, 9, result.stderr);
assert.deepEqual(readCalls(workspace.callsPath), expectedPublishCalls());
});

test("publish helper preserves a failed dry-run exit status without checking visibility", () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { publishExit: 9, extraArgs: ["--dry-run"] });

assert.equal(result.status, 9, result.stderr);
assert.deepEqual(readCalls(workspace.callsPath), expectedPublishCalls("1.2.3", ["--dry-run"]));
});

for (const name of ["NPM_PUBLISH_VERIFY_ATTEMPTS", "NPM_PUBLISH_VERIFY_DELAY_MS"]) {
for (const value of ["", "0", "-1", "1.5", "nope", "2ms", "1e2", "0x10", " 2", "2 ", "2\n", "Infinity", "9007199254740992"]) {
test(`publish helper rejects ${name}=${JSON.stringify(value)} before publishing`, () => {
const workspace = setupWorkspace();
const result = runScript(workspace, { verifyEnv: { [name]: value } });

assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, new RegExp(`${name}.*positive base-10 integer`));
assert.equal(readCalls(workspace.callsPath).some((call) => call[0] === "publish"), false);
});
}
}

test("publish helper accepts positive base-10 verification overrides", () => {
const workspace = setupWorkspace();
const result = runScript(workspace, {
visibilityMisses: 3,
verifyEnv: { NPM_PUBLISH_VERIFY_ATTEMPTS: "04", NPM_PUBLISH_VERIFY_DELAY_MS: "01" },
});

assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /@sentiolabs\/example@1\.2\.3.*visible/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
...Array.from({ length: 4 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]),
]);
});

for (const delayMs of [undefined, "2000", "2147483648"]) {
test(`publish helper waits between visibility attempts with delay ${delayMs ?? "default"} without timer overflow`, () => {
const workspace = setupWorkspace();
const result = runScript(workspace, {
visibilityMisses: 1,
timeout: 1000,
verifyEnv: { NPM_PUBLISH_VERIFY_DELAY_MS: delayMs },
});

assert.equal(result.error?.code, "ETIMEDOUT", result.stderr);
assert.doesNotMatch(result.stderr, /TimeoutOverflowWarning/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
["view", `${packageName}@1.2.3`, "version", "--json"],
]);
});
}

test("publish helper defaults to 24 bounded visibility attempts", () => {
const workspace = setupWorkspace();
const result = runScript(workspace, {
visibilityMisses: 24,
verifyEnv: { NPM_PUBLISH_VERIFY_ATTEMPTS: undefined },
});

assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /@sentiolabs\/example@1\.2\.3.*not visible.*24 attempts/);
assert.deepEqual(readCalls(workspace.callsPath), [
...expectedPublishCalls(),
...Array.from({ length: 24 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]),
]);
});
Loading
Loading