@anizoptera/publish-clean 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +147 -212
  2. package/dist/cli.js +443 -305
  3. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -1,21 +1,183 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync } from "node:child_process";
3
- import { readFileSync, statSync } from "node:fs";
4
- import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
3
+ import { readFileSync } from "node:fs";
4
+ import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
7
8
  import { parseArgs } from "node:util";
8
9
  import { gunzipSync, gzipSync } from "node:zlib";
9
- //#region src/rules.ts
10
+ //#region src/error.ts
10
11
  /**
11
- * Every decision this tool makes about what a published package carries, with no process,
12
- * filesystem or argv in reach. The split is not cosmetic: these are the rules that say what
13
- * ships, and each is worth exercising directly, one input to one output, rather than through
14
- * two package managers and a tarball. cli.ts owns the effects and wires them to these.
12
+ * The one failure type every module here throws, so `cli.ts` can tell a refusal this tool
13
+ * decided on — which is already phrased for the operator and needs no decoration — from a
14
+ * crash, whose message would otherwise reach them raw.
15
+ */
16
+ var PublishCleanError = class extends Error {
17
+ constructor(message, options) {
18
+ super(message, options), this.name = "PublishCleanError";
19
+ }
20
+ };
21
+ //#endregion
22
+ //#region src/json.ts
23
+ function isObject(value) {
24
+ return typeof value == "object" && !!value && !Array.isArray(value);
25
+ }
26
+ /**
27
+ * The form written into the published tarball: npm's own two-space indentation with a trailing
28
+ * newline, and key order left exactly as the packer emitted it. Preserving order is what makes
29
+ * the artifact byte-reproducible across runs, since cleaning only ever deletes keys.
30
+ */
31
+ function stringifyJson(value) {
32
+ return `${JSON.stringify(value, null, 2)}\n`;
33
+ }
34
+ /**
35
+ * The form used only to compare two manifests for equality. Key order carries no meaning to a
36
+ * consumer, so comparing the written form would report a difference where none exists.
37
+ */
38
+ function stableJson(value) {
39
+ return JSON.stringify(stableValue(value));
40
+ }
41
+ function stableValue(value) {
42
+ return Array.isArray(value) ? value.map(stableValue) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)])) : value;
43
+ }
44
+ //#endregion
45
+ //#region src/artifact.ts
46
+ /**
47
+ * What the published tarball may carry, and what it must. Every rule here judges a file list —
48
+ * the paths `tar` reads out of the archive, with the `package/` prefix already stripped — never
49
+ * a directory on disk, because that list is what a consumer's installer unpacks and it needs no
50
+ * filesystem to exist.
15
51
  *
16
- * Ambient inputs arrive as parameters, never by reaching for them: reading `process.env` from
17
- * here would make these cases depend on state a test can only set process-wide, which is both
18
- * a mock and a race against every case running beside it.
52
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
53
+ * argv here. `cli.ts` owns the effects.
54
+ */
55
+ /**
56
+ * Content that must never reach a registry. `^` means the package root.
57
+ *
58
+ * Case-insensitive throughout, because the filesystems most packages are built on are
59
+ * too. On macOS and Windows `Server.PEM` and `server.pem` are the same file, so a
60
+ * case-sensitive guard refuses one and publishes the other, which is worse than no guard:
61
+ * it reads as coverage.
62
+ *
63
+ * Private keys are matched by extension and, separately, by exact filename. SSH keys carry
64
+ * no extension at all, and `id_rsa` is the most common private-key filename there is. The
65
+ * exact-name form deliberately does not match `id_rsa.pub`, which is public by design and
66
+ * legitimate to ship.
67
+ */
68
+ const CRITICAL_PATTERNS = [
69
+ /(?:^|\/)node_modules(?:\/|$)/i,
70
+ /(?:^|\/)\.git(?:\/|$)/i,
71
+ /(?:^|\/)\.env(?:\.|$)/i,
72
+ /(?:^|\/)\.npmrc$/i,
73
+ /\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
74
+ /(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
75
+ ], SUSPICIOUS_PATTERNS = [
76
+ /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
77
+ /(?:^|\/)\.github(?:\/|$)/,
78
+ /(?:^|\/)tsconfig[^/]*\.json$/,
79
+ /(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
80
+ /\.(?:test|spec)\.[cm]?[jt]sx?$/
81
+ ];
82
+ function validatePackedFiles(files, skipSuspicious) {
83
+ let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
84
+ if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
85
+ if (skipSuspicious) return;
86
+ let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
87
+ if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
88
+ }
89
+ /**
90
+ * Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
91
+ *
92
+ * Replacing a member is supposed to change one member, and the rewriter copies every other
93
+ * entry as opaque bytes — so this can only fail through a defect in that code, which is exactly
94
+ * why it is worth asserting on the step that cannot be taken back. Nothing else would notice a
95
+ * dropped file: the leak checks only ask what is present, and a package missing a file installs
96
+ * fine and then fails at import, on a version the registry keeps forever.
97
+ *
98
+ * Both lists are read out of the archives by `tar`, an instrument that cannot share a mistake
99
+ * with the walk being checked.
100
+ */
101
+ function assertSameEntries(packed, published) {
102
+ let before = new Set(packed), after = new Set(published), changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
103
+ if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
104
+ }
105
+ /**
106
+ * Walks a manifest value of any shape and collects the strings that name a file inside
107
+ * the package, so the caller can prove each one exists in the tarball.
108
+ *
109
+ * `mode` exists because the two families of path-bearing fields disagree about what a
110
+ * bare string means, and reading one by the other's rules produces wrong answers in both
111
+ * directions:
112
+ *
113
+ * - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
114
+ * where every string is a path into this package.
115
+ * - `"relative-only"` for `exports`, `imports`, `sideEffects` and the object form of
116
+ * `browser`, where a string may just as well be an external package name, a condition
117
+ * target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
118
+ * rest would report a missing file for something that was never a file.
119
+ *
120
+ * Booleans are skipped rather than ignored by accident: `sideEffects: false` and
121
+ * `exports` condition values legitimately hold them.
122
+ */
123
+ function collectDeclaredPaths(value, out, mode) {
124
+ if (typeof value == "string") {
125
+ (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
126
+ return;
127
+ }
128
+ if (typeof value != "boolean") {
129
+ if (Array.isArray(value)) {
130
+ for (let item of value) collectDeclaredPaths(item, out, mode);
131
+ return;
132
+ }
133
+ if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out, mode);
134
+ }
135
+ }
136
+ function normalizeDeclaredPath(declared) {
137
+ let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
138
+ if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
139
+ let normalized = path.posix.normalize(withoutDot);
140
+ return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
141
+ }
142
+ /**
143
+ * Refuses a manifest whose declared entry points are not in the tarball.
144
+ *
145
+ * A path containing `*` is skipped: `exports` subpath patterns and `typesVersions` globs stand
146
+ * for a set of files, and resolving them here would mean reimplementing npm's own matcher to
147
+ * answer a question npm answers at install time.
148
+ */
149
+ function assertDeclaredFiles(pkg, published) {
150
+ let declared = [];
151
+ for (let field of [
152
+ "main",
153
+ "module",
154
+ "types",
155
+ "typings",
156
+ "bin"
157
+ ]) collectDeclaredPaths(pkg[field], declared, "every-string");
158
+ typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, declared, "every-string") : collectDeclaredPaths(pkg.browser, declared, "relative-only");
159
+ for (let field of [
160
+ "exports",
161
+ "imports",
162
+ "sideEffects"
163
+ ]) collectDeclaredPaths(pkg[field], declared, "relative-only");
164
+ collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
165
+ let resolved = declared.map((declaredPath) => ({
166
+ path: declaredPath,
167
+ normalized: normalizeDeclaredPath(declaredPath)
168
+ })), invalid = resolved.filter((item) => item.normalized === null);
169
+ if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.path).join("\n")}`);
170
+ let shipped = new Set(published), missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
171
+ if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
172
+ }
173
+ //#endregion
174
+ //#region src/manifest.ts
175
+ /**
176
+ * What the published `package.json` carries: which fields survive cleaning, which are refused,
177
+ * and what the author may add to either list.
178
+ *
179
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
180
+ * argv here — so every rule is one input to one output. `cli.ts` owns the effects.
19
181
  */
20
182
  const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.catalogs.patchedDependencies.private.files.stylelint.trustedDependencies.wireit.devDependencies.overrides.resolutions.ava.c8.jest.mocha.nyc.tap.vitest.babel.biome.browserslist.eslintConfig.eslintIgnore.prettier.remarkConfig.xo.commitlint.husky.lint-staged.simple-git-hooks.clean-publish.publish-clean.semantic-release.packageManager.pnpm.volta.workspaces.nx.turbo".split(".")), CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
21
183
  "preinstall",
@@ -83,7 +245,37 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
83
245
  "styleModule",
84
246
  "svelte",
85
247
  "unpkg"
86
- ]);
248
+ ]), PUBLISH_ADVISORY = "publish-clean packs with pnpm: it resolves workspace: and catalog: specs from the packing package's own node_modules, so a Bun workspace works as-is and a Yarn one needs a pnpm-workspace.yaml plus one pnpm install. npm packs those specs unresolved.";
249
+ function stripManifest(pkg, extraDevFields) {
250
+ let stripped = { ...pkg };
251
+ for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
252
+ let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
253
+ if (scripts) {
254
+ let kept = {};
255
+ for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
256
+ Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
257
+ }
258
+ return stripped;
259
+ }
260
+ /**
261
+ * Pins the published manifest to a registry, when one was chosen.
262
+ *
263
+ * Written into `publishConfig` rather than passed only on the command line, because that is
264
+ * where npm looks when someone later republishes the same tarball by hand — the artifact then
265
+ * carries its own destination instead of depending on whoever runs the command. Any other
266
+ * `publishConfig` keys the author set are consumer-facing and survive untouched.
267
+ *
268
+ * Returns the manifest unchanged when no registry was chosen, so the caller has no branch and
269
+ * cannot forget one.
270
+ */
271
+ function withRegistry(pkg, registry) {
272
+ if (registry === null) return pkg;
273
+ let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
274
+ return publishConfig.registry = registry, {
275
+ ...pkg,
276
+ publishConfig
277
+ };
278
+ }
87
279
  /**
88
280
  * Refuses a published manifest that lost a field the source declared and consumers read.
89
281
  *
@@ -93,8 +285,8 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
93
285
  * `exports` makes the package unimportable, and neither leaves any trace in the artifact
94
286
  * to notice later. The registry keeps the version forever either way.
95
287
  *
96
- * Compared against the *final* tarball rather than the cleaned directory, so a loss
97
- * introduced by the re-pack is caught as well as one introduced by stripping.
288
+ * Read out of the published tarball rather than from the cleaned value in memory, so a loss
289
+ * introduced while rewriting the archive is caught as well as one introduced by stripping.
98
290
  *
99
291
  * `devFields` entries are exempt: removing those was the request. `scripts` is exempt
100
292
  * because it is rewritten rather than removed, down to the install lifecycle hooks a
@@ -129,146 +321,63 @@ function unrecognizedFieldsReport(pkg, kept) {
129
321
  return unrecognized.length === 0 ? null : `publish-clean: these manifest fields are not recognised and were published as-is:\n${unrecognized.map((field) => ` ${field}`).join("\n")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }\n "publish-clean": { "keepFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }`;
130
322
  }
131
323
  /**
132
- * Content that must never reach a registry. Matched against tarball paths with the
133
- * `package/` prefix already stripped, so `^` means the package root.
134
- *
135
- * Case-insensitive throughout, because the filesystems most packages are built on are
136
- * too. On macOS and Windows `Server.PEM` and `server.pem` are the same file, so a
137
- * case-sensitive guard refuses one and publishes the other, which is worse than no guard:
138
- * it reads as coverage.
324
+ * Refuses a manifest that still carries a spec only a workspace can resolve. Published
325
+ * with one, the package is uninstallable for everyone, and the version cannot be taken
326
+ * back.
139
327
  *
140
- * Private keys are matched by extension and, separately, by exact filename. SSH keys carry
141
- * no extension at all, and `id_rsa` is the most common private-key filename there is. The
142
- * exact-name form deliberately does not match `id_rsa.pub`, which is public by design and
143
- * legitimate to ship.
328
+ * The caller passes an already-stripped manifest, so the dev-only members of DEP_FIELDS are
329
+ * absent by construction. They are still checked, because a guard whose correctness depends on
330
+ * the order it happens to be called in fails silently the day someone reorders it.
144
331
  */
145
- const CRITICAL_PATTERNS = [
146
- /(?:^|\/)node_modules(?:\/|$)/i,
147
- /(?:^|\/)\.git(?:\/|$)/i,
148
- /(?:^|\/)\.env(?:\.|$)/i,
149
- /(?:^|\/)\.npmrc$/i,
150
- /\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
151
- /(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
152
- ], SUSPICIOUS_PATTERNS = [
153
- /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
154
- /(?:^|\/)\.github(?:\/|$)/,
155
- /(?:^|\/)tsconfig[^/]*\.json$/,
156
- /(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
157
- /\.(?:test|spec)\.[cm]?[jt]sx?$/
158
- ], PUBLISH_ADVISORY = "publish-clean packs with pnpm: it resolves workspace: and catalog: specs from the packing package's own node_modules, so a Bun workspace works as-is and a Yarn one needs a pnpm-workspace.yaml plus one pnpm install. npm packs those specs unresolved.", MIN_TRUSTED_NPM_VERSION = [
159
- 11,
160
- 5,
161
- 1
162
- ];
163
- var PublishCleanError = class extends Error {
164
- constructor(message, options) {
165
- super(message, options), this.name = "PublishCleanError";
166
- }
167
- };
168
- function isObject(value) {
169
- return typeof value == "object" && !!value && !Array.isArray(value);
170
- }
171
- function stringifyJson(value) {
172
- return `${JSON.stringify(value, null, 2)}\n`;
173
- }
174
- function stableJson(value) {
175
- return JSON.stringify(stableValue(value));
176
- }
177
- function stableValue(value) {
178
- return Array.isArray(value) ? value.map(stableValue) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)])) : value;
179
- }
180
- function isAtLeast(actual, minimum) {
181
- for (let index of [
182
- 0,
183
- 1,
184
- 2
185
- ]) {
186
- if (actual[index] > minimum[index]) return !0;
187
- if (actual[index] < minimum[index]) return !1;
332
+ function assertNoMonorepoProtocols(pkg) {
333
+ let failures = [];
334
+ for (let field of DEP_FIELDS) {
335
+ let map = pkg[field];
336
+ if (isObject(map)) for (let [name, spec] of Object.entries(map)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`${field}.${name}: ${spec}`);
188
337
  }
189
- return !0;
190
- }
191
- function wantsTrustedPublish(pkg, publishArgs, env) {
192
- return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
338
+ if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
193
339
  }
194
340
  function assertPublicPackage(pkg) {
195
341
  if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
196
342
  }
197
- function repositoryUrl(pkg) {
198
- return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
199
- }
200
- function githubRepositorySlug(url) {
201
- let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
202
- if (withoutGitPrefix.startsWith("git@github.com:")) {
203
- let slug = withoutGitPrefix.slice(15);
204
- return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
205
- }
206
- try {
207
- let parsed = new URL(withoutGitPrefix);
208
- if (parsed.hostname !== "github.com") return null;
209
- let slug = parsed.pathname.replace(/^\/+/, "");
210
- return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
211
- } catch {
212
- return null;
213
- }
214
- }
215
- function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
216
- if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
217
- let repoUrl = repositoryUrl(pkg);
218
- if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
219
- if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
220
- }
221
- function stripManifest(pkg, extraDevFields) {
222
- let stripped = { ...pkg };
223
- for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
224
- let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
225
- if (scripts) {
226
- let kept = {};
227
- for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
228
- Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
229
- }
230
- return stripped;
343
+ function assertFilesField(pkg, skip) {
344
+ if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
231
345
  }
232
346
  /**
233
- * Pins the published manifest to a registry, when one was chosen.
234
- *
235
- * Written into `publishConfig` rather than passed only on the command line, because that is
236
- * where npm looks when someone later republishes the same tarball by hand — the artifact then
237
- * carries its own destination instead of depending on whoever runs the command. Any other
238
- * `publishConfig` keys the author set are consumer-facing and survive untouched.
239
- *
240
- * Returns the manifest unchanged when no registry was chosen, so the caller has no branch and
241
- * cannot forget one.
347
+ * Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
348
+ * makes a typo an error instead of a silent no-op — and a silent no-op here is not cosmetic:
349
+ * `devFeilds` publishes the field the author meant to strip, and nothing in the output says so.
242
350
  */
243
- function withRegistry(pkg, registry) {
244
- if (registry === null) return pkg;
245
- let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
246
- return publishConfig.registry = registry, {
247
- ...pkg,
248
- publishConfig
249
- };
351
+ const CONFIG_KEYS = /* @__PURE__ */ new Set([
352
+ "allowSuspicious",
353
+ "devFields",
354
+ "keepFields",
355
+ "noGitChecks",
356
+ "registry",
357
+ "skipFileCheck"
358
+ ]);
359
+ function packageConfig(pkg) {
360
+ let config = pkg["publish-clean"];
361
+ if (!isObject(config)) return {};
362
+ let unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
363
+ if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
364
+ return config;
250
365
  }
251
366
  /**
252
- * Refuses a manifest that still carries a spec only a workspace can resolve. Published
253
- * with one, the package is uninstallable for everyone, and the version cannot be taken
254
- * back.
255
- *
256
- * Both call sites pass an already-stripped manifest, so the dev-only members of
257
- * DEP_FIELDS are absent by construction. They are still checked, because a guard whose
258
- * correctness depends on the order it happens to be called in fails silently the day
259
- * someone reorders it.
367
+ * Reads a string-list option, refusing anything else outright rather than filtering it out.
368
+ * A number or a nested object in this list is a mistake in the manifest, and skipping it
369
+ * silently means the author's intent is lost with no signal anywhere.
260
370
  */
261
- function assertNoMonorepoProtocols(pkg) {
262
- let failures = [];
263
- for (let field of DEP_FIELDS) {
264
- let map = pkg[field];
265
- if (isObject(map)) for (let [name, spec] of Object.entries(map)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`${field}.${name}: ${spec}`);
266
- }
267
- if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
371
+ function stringList(config, key) {
372
+ let value = config[key];
373
+ if (value === void 0) return [];
374
+ if (!Array.isArray(value) || value.some((entry) => typeof entry != "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
375
+ return value;
268
376
  }
269
377
  function customDevFields(config) {
270
- if (!Array.isArray(config.devFields)) return [];
271
- let fields = config.devFields.filter((field) => typeof field == "string"), unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
378
+ let fields = stringList(config, "devFields"), kept = new Set(stringList(config, "keepFields")), contradictory = fields.filter((field) => kept.has(field));
379
+ if (contradictory.length > 0) throw new PublishCleanError(`These fields are listed as both devFields and keepFields, which asks to strip and to publish the same key:\n${contradictory.join("\n")}`);
380
+ let unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
272
381
  if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
273
382
  return fields;
274
383
  }
@@ -284,63 +393,13 @@ function customDevFields(config) {
284
393
  * next one, including a real leak.
285
394
  */
286
395
  function keptFields(config) {
287
- return Array.isArray(config.keepFields) ? config.keepFields.filter((field) => typeof field == "string") : [];
288
- }
289
- function assertFilesField(pkg, skip) {
290
- if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
291
- }
292
- function validatePackedFiles(files, skipSuspicious) {
293
- let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
294
- if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
295
- if (skipSuspicious) return;
296
- let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
297
- if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
298
- }
299
- /**
300
- * Walks a manifest value of any shape and collects the strings that name a file inside
301
- * the package, so the caller can prove each one exists in the tarball.
302
- *
303
- * `mode` exists because the two families of path-bearing fields disagree about what a
304
- * bare string means, and reading one by the other's rules produces wrong answers in both
305
- * directions:
306
- *
307
- * - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
308
- * where every string is a path into this package.
309
- * - `"relative-only"` for `exports`, `imports`, `sideEffects` and the object form of
310
- * `browser`, where a string may just as well be an external package name, a condition
311
- * target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
312
- * rest would report a missing file for something that was never a file.
313
- *
314
- * Booleans are skipped rather than ignored by accident: `sideEffects: false` and
315
- * `exports` condition values legitimately hold them.
316
- */
317
- function collectDeclaredPaths(value, out, mode) {
318
- if (typeof value == "string") {
319
- (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
320
- return;
321
- }
322
- if (typeof value != "boolean") {
323
- if (Array.isArray(value)) {
324
- for (let item of value) collectDeclaredPaths(item, out, mode);
325
- return;
326
- }
327
- if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out, mode);
328
- }
329
- }
330
- function normalizeDeclaredPath(declared) {
331
- let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
332
- if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
333
- let normalized = path.posix.normalize(withoutDot);
334
- return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
335
- }
336
- function packageConfig(pkg) {
337
- let config = pkg["publish-clean"];
338
- return isObject(config) ? config : {};
396
+ return stringList(config, "keepFields");
339
397
  }
340
398
  //#endregion
341
399
  //#region src/tarball.ts
342
400
  /**
343
- * Replaces the manifest inside a packed tarball without repacking it.
401
+ * Reads and rewrites a packed npm tarball. The only place this tool decodes or authors
402
+ * archive bytes, and the only reader every guard consults.
344
403
  *
345
404
  * The pipeline packs once, with pnpm, because that packer decides the file set. Cleaning the
346
405
  * manifest by unpacking and packing again hands that decision to a second packer, which
@@ -350,9 +409,15 @@ function packageConfig(pkg) {
350
409
  * into.
351
410
  *
352
411
  * Every entry other than the manifest is copied as opaque bytes and never decoded, so entry
353
- * shapes this code does not model — pax extended headers, ustar prefix splitting, GNU long
354
- * names — survive untouched. Only walking is universal: an entry's length is always its
355
- * header block plus its size rounded up to a block, whatever the type.
412
+ * shapes this code does not model — pax extended headers, ustar prefix splitting — survive
413
+ * untouched. Only walking is universal: an entry's length is always its header block plus its
414
+ * size rounded up to a block, whatever the type.
415
+ *
416
+ * Reading here rather than through the `tar` binary is what makes the whole tool depend on
417
+ * nothing but Node: one archive is decompressed once and answers every question about it
418
+ * (file list, manifest bytes, rewrite), instead of one spawn and one decompression per
419
+ * question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
420
+ * containing a newline arrives as two entries there and as itself here.
356
421
  */
357
422
  const MANIFEST_PATH = "package/package.json", PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
358
423
  function field(block, offset, length) {
@@ -384,35 +449,146 @@ function reheader(original, size) {
384
449
  return header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii"), header;
385
450
  }
386
451
  /**
387
- * Returns the gzipped tarball with `package/package.json` replaced by `manifest`.
452
+ * Decodes a gzipped tarball into its entries, refusing every shape whose meaning this tool
453
+ * cannot state unambiguously.
388
454
  *
389
- * Refuses anything it cannot rewrite unambiguously. Duplicate manifest entries are a refusal
390
- * rather than a last-one-wins guess, because extractors disagree about which survives and the
391
- * published manifest would then depend on the extractor rather than on this tool.
455
+ * A duplicate manifest is a refusal rather than a last-one-wins guess, because extractors
456
+ * disagree about which survives and the published manifest would then depend on the extractor
457
+ * rather than on this tool. A short final block is a truncation: an archive that ends
458
+ * mid-entry would otherwise read as a valid one that simply stops, which is exactly how a
459
+ * partial write becomes a published package.
392
460
  */
393
- function replaceTarballManifest(archive, manifest) {
394
- let tar = gunzipSync(archive), parts = [], replaced = !1;
461
+ function readArchive(gzipped) {
462
+ let tar = gunzipSync(gzipped), entries = [], tail = tar.subarray(tar.length);
395
463
  for (let offset = 0; offset < tar.length;) {
396
- let header = tar.subarray(offset, offset + 512), name = field(header, 0, 100);
464
+ let header = tar.subarray(offset, offset + 512);
465
+ if (header.length < 512) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
466
+ let name = field(header, 0, 100);
397
467
  if (name === "") {
398
- parts.push(tar.subarray(offset));
468
+ tail = tar.subarray(offset);
399
469
  break;
400
470
  }
401
- let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512), type = field(header, 156, 1);
402
- if (PAX_TYPES.has(type) && assertNoManifestOverride(tar.subarray(offset + 512, offset + 512 + size)), name === MANIFEST_PATH) {
403
- if (replaced) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
471
+ let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512);
472
+ if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
473
+ let type = field(header, 156, 1), body = tar.subarray(offset + 512, offset + 512 + size);
474
+ if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
475
+ if (PAX_TYPES.has(type) && assertNoManifestOverride(body), name === MANIFEST_PATH) {
404
476
  if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
405
- let body = Buffer.from(manifest, "utf8");
406
- parts.push(reheader(header, body.length), body, Buffer.alloc(512 * Math.ceil(body.length / 512) - body.length)), replaced = !0;
407
- } else parts.push(tar.subarray(offset, end));
408
- offset = end;
477
+ if (entries.some((entry) => entry.name === MANIFEST_PATH)) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
478
+ }
479
+ entries.push({
480
+ name,
481
+ type,
482
+ header,
483
+ body,
484
+ raw: tar.subarray(offset, end)
485
+ }), offset = end;
486
+ }
487
+ return {
488
+ entries,
489
+ tail
490
+ };
491
+ }
492
+ /**
493
+ * The paths a consumer's installer writes, with the `package/` prefix stripped — the list every
494
+ * content guard judges. Directories and pax headers are dropped: neither is a file anyone
495
+ * imports, and a pax header's own name (`PaxHeader`) names no file at all.
496
+ */
497
+ function packageFiles(archive) {
498
+ return archive.entries.filter((entry) => entry.type !== "5" && !PAX_TYPES.has(entry.type)).map((entry) => entry.name.startsWith("package/") ? entry.name.slice(8) : entry.name).filter((name) => name.length > 0 && !name.endsWith("/")).sort();
499
+ }
500
+ function manifestEntry(archive) {
501
+ let entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
502
+ if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
503
+ return entry;
504
+ }
505
+ /** The manifest exactly as the archive carries it, for parsing by the caller. */
506
+ function manifestText(archive) {
507
+ return manifestEntry(archive).body.toString("utf8");
508
+ }
509
+ /** Returns the gzipped tarball with `package/package.json` replaced by `manifest`. */
510
+ function replaceManifest(archive, manifest) {
511
+ let target = manifestEntry(archive), body = Buffer.from(manifest, "utf8"), parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
512
+ reheader(entry.header, body.length),
513
+ body,
514
+ Buffer.alloc(512 * Math.ceil(body.length / 512) - body.length)
515
+ ]) : entry.raw);
516
+ return parts.push(archive.tail), gzipSync(Buffer.concat(parts), { level: 9 });
517
+ }
518
+ //#endregion
519
+ //#region src/trusted-publish.ts
520
+ /**
521
+ * Who npm will believe is publishing, and what the toolchain must be for it to sign anything.
522
+ *
523
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
524
+ * argv here. `cli.ts` owns the effects.
525
+ */
526
+ /**
527
+ * The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
528
+ * message so the version a reader is told to install is the version the comparison made.
529
+ *
530
+ * The Node floor is also the package's declared `engines.node`, since a publisher that cannot
531
+ * produce provenance cannot do this tool's job; a test asserts the two agree.
532
+ */
533
+ const MIN_TRUSTED_NPM_VERSION = [
534
+ 11,
535
+ 5,
536
+ 1
537
+ ], MIN_TRUSTED_NODE_VERSION = [
538
+ 22,
539
+ 14,
540
+ 0
541
+ ];
542
+ function isAtLeast(actual, minimum) {
543
+ for (let index of [
544
+ 0,
545
+ 1,
546
+ 2
547
+ ]) {
548
+ if (actual[index] > minimum[index]) return !0;
549
+ if (actual[index] < minimum[index]) return !1;
550
+ }
551
+ return !0;
552
+ }
553
+ function wantsTrustedPublish(pkg, publishArgs, env) {
554
+ return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
555
+ }
556
+ function repositoryUrl(pkg) {
557
+ return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
558
+ }
559
+ function githubRepositorySlug(url) {
560
+ let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
561
+ if (withoutGitPrefix.startsWith("git@github.com:")) {
562
+ let slug = withoutGitPrefix.slice(15);
563
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
564
+ }
565
+ try {
566
+ let parsed = new URL(withoutGitPrefix);
567
+ if (parsed.hostname !== "github.com") return null;
568
+ let slug = parsed.pathname.replace(/^\/+/, "");
569
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
570
+ } catch {
571
+ return null;
409
572
  }
410
- if (!replaced) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
411
- return gzipSync(Buffer.concat(parts));
573
+ }
574
+ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
575
+ if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
576
+ let repoUrl = repositoryUrl(pkg);
577
+ if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
578
+ if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
412
579
  }
413
580
  //#endregion
414
581
  //#region src/cli.ts
415
582
  const TOOL_PROBE_TIMEOUT_MS = 1e4;
583
+ /**
584
+ * Read from the installed manifest rather than baked in at build time, so the number cannot
585
+ * drift from the package a user actually has — which is the only reason anyone asks a tool
586
+ * for its version.
587
+ */
588
+ function ownVersion() {
589
+ let manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
590
+ return typeof manifest.version == "string" ? manifest.version : "unknown";
591
+ }
416
592
  function readJson(file) {
417
593
  let parsed;
418
594
  try {
@@ -525,11 +701,7 @@ function assertTrustedPublishingRuntime(pkg, publishArgs) {
525
701
  node[0] ?? 0,
526
702
  node[1] ?? 0,
527
703
  node[2] ?? 0
528
- ], [
529
- 22,
530
- 14,
531
- 0
532
- ])) throw new PublishCleanError(`Trusted npm publishing requires Node.js 22.14.0 or newer; found ${process.versions.node}.`);
704
+ ], MIN_TRUSTED_NODE_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${process.versions.node}.`);
533
705
  }
534
706
  function warnIfNonPnpmLifecycle() {
535
707
  let userAgent = process.env.npm_config_user_agent;
@@ -545,130 +717,82 @@ function assertCleanGit(packageDir, skip) {
545
717
  ], packageDir).trim();
546
718
  if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
547
719
  } catch (error) {
548
- throw error instanceof PublishCleanError ? error : new PublishCleanError("Unable to verify source git status.", { cause: error });
549
- }
550
- }
551
- async function walkFiles(dir, root, files) {
552
- let entries = await readdir(dir, { withFileTypes: !0 });
553
- for (let entry of entries) {
554
- let absolute = path.join(dir, entry.name), relative = path.relative(root, absolute).replaceAll(path.sep, "/");
555
- if (entry.isDirectory()) {
556
- await walkFiles(absolute, root, files);
557
- continue;
558
- }
559
- entry.isFile() && files.push(relative);
720
+ if (error instanceof PublishCleanError) throw error;
721
+ let stderr = outputFromError(error, "stderr");
722
+ throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
560
723
  }
561
724
  }
562
- function listTarballFiles(tarball, cwd) {
563
- return run("tar", ["tzf", tarball], cwd).trim().split("\n").filter(Boolean).map((file) => file.replaceAll(path.sep, "/")).map((file) => file.startsWith("package/") ? file.slice(8) : file).filter((file) => file.length > 0 && !file.endsWith("/")).sort();
725
+ /**
726
+ * Reads an archive from disk, so every judgement is made about bytes that exist as a file
727
+ * rather than about a buffer this process is holding. The final artifact is read back this
728
+ * way after it is written, which also proves the write itself landed whole.
729
+ */
730
+ async function readTarball(tarball) {
731
+ return readArchive(await readFile(tarball));
564
732
  }
565
- function readTarballJson(tarball, file, cwd) {
733
+ function manifestOf(archive, label) {
566
734
  let parsed;
567
735
  try {
568
- parsed = JSON.parse(run("tar", [
569
- "xOzf",
570
- tarball,
571
- `package/${file}`
572
- ], cwd));
736
+ parsed = JSON.parse(manifestText(archive));
573
737
  } catch (cause) {
574
- throw new PublishCleanError(`Unable to read JSON from final npm tarball: ${file}`, { cause });
738
+ throw new PublishCleanError(`Unable to parse package.json inside ${label}.`, { cause });
575
739
  }
576
- if (!isObject(parsed)) throw new PublishCleanError(`Final npm tarball ${file} must contain a JSON object.`);
740
+ if (!isObject(parsed)) throw new PublishCleanError(`package.json inside ${label} must contain a JSON object.`);
577
741
  return parsed;
578
742
  }
579
743
  /**
580
- * Locates the tarball a packer just produced by reading its destination directory.
744
+ * Locates the tarball `pnpm pack` just produced by reading its destination directory.
581
745
  *
582
- * Every pack here targets a directory this process created and owns exclusively, so
583
- * the result is discoverable without interpreting the packer's output at all. That
584
- * matters because `pack` runs the package's `prepare`/`prepack` lifecycle scripts and
585
- * forwards their stdout: any build tool that logs — most of them — lands ahead of the
586
- * `--json` payload and breaks a parse of that stream. Reading the directory is immune
587
- * to whatever a foreign package's scripts choose to print.
746
+ * The pack targets a directory this process created and owns exclusively, so the result is
747
+ * discoverable without interpreting the packer's output at all. That matters because `pack`
748
+ * runs the package's `prepare`/`prepack` lifecycle scripts and forwards their stdout: any
749
+ * build tool that logs — most of them — lands ahead of a `--json` payload and breaks a parse
750
+ * of that stream. Reading the directory is immune to whatever a foreign package's scripts
751
+ * choose to print.
588
752
  *
589
753
  * Exactly one tarball is the invariant, not a convenience: more than one means the
590
754
  * destination was not exclusive and the wrong artifact could be published.
591
755
  */
592
- async function soleTarball(packRoot, packer) {
756
+ async function soleTarball(packRoot) {
593
757
  let tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz")), [tarball] = tarballs;
594
- if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`${packer} left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
758
+ if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
595
759
  return path.join(packRoot, tarball);
596
760
  }
597
- function assertDeclaredFiles(pkg, packageDir) {
598
- let paths = [];
599
- for (let field of [
600
- "main",
601
- "module",
602
- "types",
603
- "typings",
604
- "bin"
605
- ]) collectDeclaredPaths(pkg[field], paths, "every-string");
606
- typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, paths, "every-string") : collectDeclaredPaths(pkg.browser, paths, "relative-only");
607
- for (let field of [
608
- "exports",
609
- "imports",
610
- "sideEffects"
611
- ]) collectDeclaredPaths(pkg[field], paths, "relative-only");
612
- collectDeclaredPaths(pkg.typesVersions, paths, "every-string");
613
- let normalized = paths.map((declared) => ({
614
- declared,
615
- normalized: normalizeDeclaredPath(declared)
616
- })), invalid = normalized.filter((item) => item.normalized === null);
617
- if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.declared).join("\n")}`);
618
- let missing = normalized.filter((declared) => !declared.declared.includes("*") && !exists(path.join(packageDir, String(declared.normalized))));
619
- if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.declared).join("\n")}`);
620
- }
621
- function exists(file) {
622
- try {
623
- return !!statSync(file).isFile();
624
- } catch {
625
- return !1;
626
- }
627
- }
628
761
  async function packAndClean(packageDir, opts) {
629
- requireTool("pnpm"), requireTool("npm"), requireTool("tar"), warnIfNonPnpmLifecycle();
762
+ requireTool("pnpm"), requireTool("npm"), warnIfNonPnpmLifecycle();
630
763
  let sourcePkg = readJson(path.join(packageDir, "package.json"));
631
764
  !opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
632
- let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config), keepFields = keptFields(config);
765
+ let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, allowSuspicious = opts.allowSuspicious || config.allowSuspicious === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config), keepFields = keptFields(config);
633
766
  assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
634
- let root = await mkdtemp(path.join(tmpdir(), "publish-clean-")), keepRoot = !1;
767
+ let root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
635
768
  try {
636
769
  run("pnpm", [
637
770
  "pack",
638
771
  "--pack-destination",
639
772
  root
640
773
  ], packageDir);
641
- let tarball = await soleTarball(root, "pnpm pack");
642
- run("tar", [
643
- "xzf",
644
- tarball,
645
- "-C",
646
- root
647
- ], packageDir);
648
- let extracted = path.join(root, "package");
649
- if (!(await stat(extracted)).isDirectory()) throw new PublishCleanError("Extracted tarball did not contain package/ directory.");
650
- let files = [];
651
- await walkFiles(extracted, extracted, files), validatePackedFiles(files, skipFileCheck);
652
- let packedPkgPath = path.join(extracted, "package.json"), cleanedPkg = withRegistry(stripManifest(readJson(packedPkgPath), extraDevFields), registry);
653
- assertNoMonorepoProtocols(cleanedPkg);
654
- let unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
655
- unrecognized && console.warn(unrecognized), assertDeclaredFiles(cleanedPkg, extracted), await writeFile(packedPkgPath, stringifyJson(cleanedPkg));
774
+ let tarball = await soleTarball(root), packed = await readTarball(tarball), cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry), unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
775
+ unrecognized && console.warn(unrecognized);
656
776
  let publishRoot = path.join(root, "publish");
657
777
  await mkdir(publishRoot);
658
778
  let finalTarball = path.join(publishRoot, path.basename(tarball));
659
- await writeFile(finalTarball, replaceTarballManifest(await readFile(tarball), stringifyJson(cleanedPkg))), validatePackedFiles(listTarballFiles(finalTarball, root), skipFileCheck);
660
- let finalPkg = readTarballJson(finalTarball, "package.json", root);
661
- if (assertNoMonorepoProtocols(finalPkg), assertNoLostConsumerFields(sourcePkg, finalPkg, extraDevFields), stableJson(finalPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
779
+ await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
780
+ let published = await readTarball(finalTarball), finalFiles = packageFiles(published);
781
+ assertSameEntries(packageFiles(packed), finalFiles), validatePackedFiles(finalFiles, allowSuspicious), assertDeclaredFiles(cleanedPkg, finalFiles);
782
+ let shippedPkg = manifestOf(published, "the published tarball");
783
+ if (assertNoMonorepoProtocols(shippedPkg), assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields), stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
662
784
  if (opts.tarballOut !== null) {
663
785
  await mkdir(opts.tarballOut, { recursive: !0 });
664
786
  let kept = path.join(opts.tarballOut, path.basename(finalTarball));
665
787
  await copyFile(finalTarball, kept), console.log(`Final tarball kept at: ${kept}`);
666
788
  }
667
- if (opts.guardOnly || opts.dryRun) {
668
- if (!opts.dryRun) return;
669
- keepRoot = !0, console.log(`[dry-run] Extracted package at: ${extracted}`), console.log(`[dry-run] Final tarball at: ${finalTarball}`);
789
+ if (opts.dryRun) {
790
+ console.log(`[dry-run] ${finalFiles.length} files:`);
791
+ for (let file of finalFiles) console.log(` ${file}`);
792
+ console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
670
793
  return;
671
794
  }
795
+ if (opts.guardOnly) return;
672
796
  assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv()), runAttached("npm", registry ? [
673
797
  "publish",
674
798
  finalTarball,
@@ -679,9 +803,9 @@ async function packAndClean(packageDir, opts) {
679
803
  "publish",
680
804
  finalTarball,
681
805
  ...opts.publishArgs
682
- ], extracted);
806
+ ], packageDir);
683
807
  } finally {
684
- keepRoot || await rm(root, {
808
+ await rm(root, {
685
809
  recursive: !0,
686
810
  force: !0
687
811
  });
@@ -692,6 +816,10 @@ async function main() {
692
816
  args: cliArgs,
693
817
  allowPositionals: !0,
694
818
  options: {
819
+ "allow-suspicious": {
820
+ type: "boolean",
821
+ default: !1
822
+ },
695
823
  "dry-run": {
696
824
  type: "boolean",
697
825
  default: !1
@@ -720,16 +848,26 @@ async function main() {
720
848
  "tarball-out": {
721
849
  type: "string",
722
850
  default: void 0
851
+ },
852
+ version: {
853
+ type: "boolean",
854
+ short: "v",
855
+ default: !1
723
856
  }
724
857
  },
725
858
  strict: !0
726
859
  });
860
+ if (parsed.values.version) {
861
+ console.log(ownVersion());
862
+ return;
863
+ }
727
864
  if (parsed.values.help) {
728
- console.log("publish-clean [--dry-run] [--guard-only] [--no-git-checks] [--registry URL] [--skip-file-check] [--tarball-out DIR] [package-dir] [-- npm-publish-args]");
865
+ console.log("publish-clean [options] [package-dir] [-- npm publish args]\n\nPacks with pnpm, strips developer-only fields from the packed manifest, validates the\nartifact, and publishes that exact tarball with npm. Arguments after `--` go to\n`npm publish` untouched (e.g. --access public --tag next --provenance).\n\nOptions:\n --dry-run Pack, clean and validate; print the file list and manifest, publish nothing.\n --guard-only Same checks, no output and no publish. For a pre-publish gate.\n --tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.\n --registry URL Publish to URL, and record it in the artifact's publishConfig.\n --no-git-checks Publish from a working tree with uncommitted changes.\n --skip-file-check Allow a manifest with no \"files\" array.\n --allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.\n -h, --help Show this help.\n -v, --version Show the publish-clean version.\n\nManifest configuration, under a \"publish-clean\" key in package.json:\n devFields string[] Extra fields to strip. Refused for fields consumers resolve.\n keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.\n registry string Default for --registry.\n noGitChecks boolean Default for --no-git-checks.\n skipFileCheck boolean Default for --skip-file-check.\n allowSuspicious boolean Default for --allow-suspicious.\n\nRequires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and\nnpm 11.5.1+, and only a cloud CI runner can produce it.");
729
866
  return;
730
867
  }
731
868
  if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
732
869
  await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
870
+ allowSuspicious: parsed.values["allow-suspicious"] === !0,
733
871
  dryRun: parsed.values["dry-run"] === !0,
734
872
  guardOnly: parsed.values["guard-only"] === !0,
735
873
  noGitChecks: parsed.values["no-git-checks"] === !0,