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
11 changes: 11 additions & 0 deletions .changeset/multipublish-jsr-gitignored-dist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@stephansama/multipublish": patch
---

Fix JSR publishing of gitignored build output, and fail the run when a publish fails

- Directories that `exports` point into (e.g. `dist`) are added to the JSR config's `publish.exclude` as negated globs, so gitignored build output is published instead of failing with `excluded-module`
- `defaultInclude` / `defaultExclude` now go to `publish.include` / `publish.exclude`, where JSR honors negated globs like `!config`, and a user's own `publish` block is kept
- A failed publish no longer exits `0`: the remaining platforms and packages are still attempted, then the CLI lists what failed and exits `1`
- Publish errors no longer repeat the publish command, which contained the JSR auth token
- An unscoped package with the `.npmrc` strategy now fails instead of being skipped silently
8 changes: 7 additions & 1 deletion core/multipublish/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ You can configure `multipublish` by creating a configuration file (or object) in
{
"$schema": "./node_modules/@stephansama/multipublish/dist/schema.json",
"platforms": [
["jsr", { "experimentalGenerateJSR": true, "defaultExclude": ["!dist"] }],
["jsr", { "experimentalGenerateJSR": true }],
[
"npm",
{
Expand All @@ -118,6 +118,12 @@ permissions:

When publishing to JSR, you must either have a valid `jsr.json` or `deno.json`, or allow `experimentalGenerateJSR` using the config option.

JSR leaves out gitignored files, which usually includes your build output. multipublish adds a negated `publish.exclude` glob for every directory your `exports` point into (`!dist` for `./dist/index.mjs`), so build output is published without any config.

`defaultInclude` and `defaultExclude` are added to the JSR config's `publish.include` and `publish.exclude`. Use them for anything else, e.g. `"defaultExclude": ["!config"]` to publish a gitignored `config` directory. JSR only honors negated globs there, not in the top-level `exclude`.

If any publish fails, multipublish still tries the remaining platforms and packages, then exits with code `1` and lists what failed.

### Changesets

If you are using jsr this with changesets, please update your version script with a preversion script that calls the `multipublish` CLI in order to update your existing jsr configurations.
Expand Down
7 changes: 7 additions & 0 deletions core/multipublish/__snapshots__/tsnapi/index.snapshot.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
/**
* Generated by tsnapi — public API snapshot of `@stephansama/multipublish`
*/
// #region Classes
export declare class PublishError extends Error {
readonly failures: string[];
constructor(_: string[]);
}
// #endregion

// #region Functions
export declare function run(): Promise<void>;
// #endregion
6 changes: 6 additions & 0 deletions core/multipublish/__snapshots__/tsnapi/index.snapshot.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
/**
* Generated by tsnapi — public API snapshot of `@stephansama/multipublish`
*/
// #region Classes
export class PublishError extends Error {
constructor(_) {}
}
// #endregion

// #region Functions
export async function run() {}
// #endregion
50 changes: 50 additions & 0 deletions core/multipublish/src/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const mocks = vi.hoisted(() => ({ run: vi.fn() }));

vi.mock("./index", async (importOriginal) => ({
...(await importOriginal<typeof import("./index")>()),
run: mocks.run,
}));

describe("cli", () => {
beforeEach(() => {
vi.resetModules();
process.exitCode = undefined;
});

afterEach(() => {
vi.restoreAllMocks();
process.exitCode = undefined;
});

it("should exit 0 when every publish succeeds", async () => {
mocks.run.mockImplementation(() => Promise.resolve());

await import("./cli");

expect(mocks.run).toHaveBeenCalledOnce();
expect(process.exitCode).toBeUndefined();
});

it("should print the summary and exit 1 when a publish fails", async () => {
const { PublishError } = await import("./index");
mocks.run.mockRejectedValue(new PublishError(["pkg (jsr)"]));
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => {});

await import("./cli");

expect(consoleError).toHaveBeenCalledWith(
"1 publish failed: pkg (jsr)",
);
expect(process.exitCode).toBe(1);
});

it("should rethrow errors that aren't publish failures", async () => {
mocks.run.mockRejectedValue(new Error("bad config"));

await expect(import("./cli")).rejects.toThrow("bad config");
});
});
11 changes: 9 additions & 2 deletions core/multipublish/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
#!/usr/bin/env node

import { run } from "./index";
import { PublishError, run } from "./index";

await run();
try {
await run();
} catch (error) {
// failed platforms were already logged, so print the summary without a stack
if (!(error instanceof PublishError)) throw error;
console.error(error.message);
process.exitCode = 1;
}
24 changes: 23 additions & 1 deletion core/multipublish/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";

import { run } from "./index";
import { PublishError, run } from "./index";

const mocks = vi.hoisted(() => ({
findRoot: vi.fn(() => Promise.resolve({ rootDir: "/mock/root" })),
Expand Down Expand Up @@ -86,4 +86,26 @@ describe("run", () => {
expect(mocks.updateJsrConfigVersion).toHaveBeenCalledOnce();
expect(mocks.publishPlatform).not.toHaveBeenCalled();
});

it("should publish the remaining packages after a failure, then throw", async () => {
mocks.publishPlatform.mockRejectedValueOnce(
new Error("npm publish failed for pkg1"),
);
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => {});

const error = await run().catch((error_: unknown) => error_);

expect(mocks.publishPlatform).toHaveBeenCalledTimes(2);
expect(error).toBeInstanceOf(PublishError);
expect((error as PublishError).failures).toEqual(["pkg1 (npm)"]);
expect((error as PublishError).message).toBe(
"1 publish failed: pkg1 (npm)",
);
expect(consoleError).toHaveBeenCalledWith(
"✖ pkg1 (npm): npm publish failed for pkg1",
);
consoleError.mockRestore();
});
});
31 changes: 30 additions & 1 deletion core/multipublish/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ import { updateJsrConfigVersion } from "./jsr";
import { publishPlatform } from "./publish";
import { loadReleases } from "./release";

/** Thrown by {@link run} after every platform was attempted, if any failed */
export class PublishError extends Error {
constructor(readonly failures: string[]) {
super(
`${failures.length} publish${failures.length === 1 ? "" : "es"} failed: ${failures.join(", ")}`,
);
this.name = "PublishError";
}
}

export async function run() {
const root = await findRoot(process.cwd());
const arguments_ = await getArguments();
Expand All @@ -27,6 +37,8 @@ export async function run() {
return { ...pkg, version: release.version || pkg.packageJson.version };
});

const failures: string[] = [];

for (const pkg of releasedPackages) {
if (arguments_.versionJsr) {
if (!pkg.packageJson.name.includes("/")) {
Expand All @@ -41,8 +53,25 @@ export async function run() {
continue;
}

// keep publishing the other platforms and packages when one fails, so a
// registry outage doesn't block the rest, then fail the run at the end
for (const platform of config.platforms) {
await publishPlatform(pkg, platform);
try {
await publishPlatform(pkg, platform);
} catch (error) {
const name =
typeof platform === "string" ? platform : platform[0];
const message =
error instanceof Error ? error.message : String(error);
console.error(
`✖ ${pkg.packageJson.name} (${name}): ${message}`,
);
failures.push(`${pkg.packageJson.name} (${name})`);
}
}
}

if (failures.length > 0) {
throw new PublishError(failures);
}
}
135 changes: 122 additions & 13 deletions core/multipublish/src/jsr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import { describe, expect, it } from "vitest";
import type { JsrSchema } from "./jsr";
import type { JsrPlatformOptionsSchema } from "./schema";

import { jsrTransformer, updateIncludeExcludeList } from "./jsr";
import {
includeExportDirectories,
jsrSchema,
jsrTransformer,
updateIncludeExcludeList,
} from "./jsr";

describe("jsr", () => {
describe("jsrTransformer", () => {
Expand Down Expand Up @@ -164,21 +169,28 @@ describe("jsr", () => {

updateIncludeExcludeList(jsrConfig, appConfig);

expect(jsrConfig.include).toEqual(["src"]);
expect(jsrConfig.exclude).toEqual(["test"]);
expect(jsrConfig.publish).toEqual({
exclude: ["test"],
include: ["src"],
});
expect(jsrConfig.include).toBeUndefined();
expect(jsrConfig.exclude).toBeUndefined();
});

it("should merge with existing include/exclude", () => {
it("should merge with existing publish include/exclude", () => {
const jsrConfig: JsrSchema = {
exclude: ["existing-exclude"],
exclude: ["top-level-exclude"],
exports: "./index.ts",
include: ["existing-include"],
name: "@scope/pkg",
publish: {
exclude: ["existing-exclude"],
include: ["existing-include"],
},
version: "1.0.0",
};
const appConfig: JsrPlatformOptionsSchema = {
allowSlowTypes: true,
defaultExclude: ["new-exclude"],
defaultExclude: ["new-exclude", "existing-exclude"],
defaultInclude: ["new-include"],
experimentalGenerateJSR: false,
experimentalUpdateCatalogs: false,
Expand All @@ -187,14 +199,111 @@ describe("jsr", () => {

updateIncludeExcludeList(jsrConfig, appConfig);

expect(jsrConfig.include).toEqual([
"existing-include",
"new-include",
expect(jsrConfig.publish).toEqual({
exclude: ["existing-exclude", "new-exclude"],
include: ["existing-include", "new-include"],
});
expect(jsrConfig.exclude).toEqual(["top-level-exclude"]);
});

it("should not add a publish block when there is nothing to add", () => {
const jsrConfig: JsrSchema = {
exports: "./index.ts",
name: "@scope/pkg",
version: "1.0.0",
};

updateIncludeExcludeList(jsrConfig, {
allowSlowTypes: true,
experimentalGenerateJSR: false,
experimentalUpdateCatalogs: false,
tokenEnvironmentKey: "test",
});

expect(jsrConfig.publish).toBeUndefined();
});
});

describe("includeExportDirectories", () => {
const base = { name: "@scope/pkg", version: "1.0.0" };

it("should un-exclude the directory of a string export", () => {
const jsrConfig: JsrSchema = {
...base,
exports: "./dist/index.mjs",
};
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish?.exclude).toEqual(["!dist"]);
});

it("should un-exclude each directory of a record export once", () => {
const jsrConfig: JsrSchema = {
...base,
exports: {
".": "./dist/index.mjs",
"./cli": "./dist/cli.mjs",
"./schema.json": "./schema/schema.json",
},
};
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish?.exclude).toEqual(["!dist", "!schema"]);
});

it("should only use the top-level directory of nested paths", () => {
const jsrConfig: JsrSchema = {
...base,
exports: { ".": "dist/esm/index.mjs" },
};
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish?.exclude).toEqual(["!dist"]);
});

it("should skip exports at the package root", () => {
const jsrConfig: JsrSchema = { ...base, exports: "./index.ts" };
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish).toBeUndefined();
});

it("should put the directories before existing excludes, which jsr matches last-wins", () => {
const jsrConfig: JsrSchema = {
...base,
exports: "./dist/index.mjs",
publish: { exclude: ["dist/**/*.map", "!config"] },
};
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish?.exclude).toEqual([
"!dist",
"dist/**/*.map",
"!config",
]);
expect(jsrConfig.exclude).toEqual([
"existing-exclude",
"new-exclude",
});

it("should keep a directory that's already listed where it is", () => {
const jsrConfig: JsrSchema = {
...base,
exports: "./dist/index.mjs",
publish: { exclude: ["dist/internal", "!dist"] },
};
includeExportDirectories(jsrConfig);
expect(jsrConfig.publish?.exclude).toEqual([
"dist/internal",
"!dist",
]);
});
});

describe("jsrSchema", () => {
it("should keep a user's publish block", () => {
const config = jsrSchema.parse({
exports: "./dist/index.mjs",
name: "@scope/pkg",
publish: { exclude: ["!dist"], include: ["dist", "README.md"] },
version: "1.0.0",
});
expect(config.publish).toEqual({
exclude: ["!dist"],
include: ["dist", "README.md"],
});
});
});
});
Loading
Loading