@anizoptera/publish-clean 0.7.0 → 0.7.2

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 +21 -0
  2. package/dist/cli.js +416 -169
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -61,6 +61,27 @@ supply-chain risk of its own, and this one has no transitive code to audit.
61
61
  `--provenance` additionally needs npm 11.5.1+ and a cloud CI runner. npm will not sign a
62
62
  publish that came from your laptop.
63
63
 
64
+ ### Running it under Bun packs a smaller tarball
65
+
66
+ gzip encoding belongs to whichever runtime executes the CLI, and Bun's (libdeflate) beats
67
+ Node's zlib on tar-shaped data: 0.17% smaller for this package, 0.28% for a sibling one, with
68
+ a byte-identical archive inside. To get it, pass Bun the **file path**:
69
+
70
+ ```sh
71
+ bun ./node_modules/.bin/publish-clean
72
+ ```
73
+
74
+ Naming the bin instead does not work, and does not say so: `bun publish-clean`,
75
+ `bun run publish-clean` and `bunx publish-clean` all hand the file to the OS, which honours
76
+ its `#!/usr/bin/env node` shebang and runs Node. They succeed, and you get Node's bytes.
77
+
78
+ Not `bunx --bun`, which forces Bun onto the `pnpm` this tool spawns as well; pnpm 11 needs
79
+ `node:sqlite`, which Bun does not implement, and that is the error you get.
80
+
81
+ Either runtime produces valid gzip with identical contents, so the choice is free. The one
82
+ rule is not to switch runtimes _within_ a version: if a release is re-run to repair its
83
+ artifacts, the bytes have to come out the same, and the two encoders do not agree.
84
+
64
85
  ## Package managers
65
86
 
66
87
  Why pnpm packs and npm publishes: pnpm is the only packer that resolves every workspace
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
8
  import { execFileSync } from "node:child_process";
9
9
  import { gunzipSync, gzipSync } from "node:zlib";
10
+
10
11
  //#region src/error.ts
11
12
  /**
12
13
  * The one failure type every module here throws, so `cli.ts` can tell a refusal this tool
@@ -15,13 +16,15 @@ import { gunzipSync, gzipSync } from "node:zlib";
15
16
  */
16
17
  var PublishCleanError = class extends Error {
17
18
  constructor(message, options) {
18
- super(message, options), this.name = "PublishCleanError";
19
+ super(message, options);
20
+ this.name = "PublishCleanError";
19
21
  }
20
22
  };
23
+
21
24
  //#endregion
22
25
  //#region src/json.ts
23
26
  function isObject(value) {
24
- return typeof value == "object" && !!value && !Array.isArray(value);
27
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
28
  }
26
29
  /**
27
30
  * The form written into the published tarball: npm's own two-space indentation with a trailing
@@ -39,15 +42,18 @@ function stableJson(value) {
39
42
  return JSON.stringify(stableValue(value));
40
43
  }
41
44
  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;
45
+ if (Array.isArray(value)) return value.map(stableValue);
46
+ if (!isObject(value)) return value;
47
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)]));
43
48
  }
49
+
44
50
  //#endregion
45
51
  //#region src/artifact.ts
46
52
  /**
47
53
  * 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.
54
+ * the archive's entry paths with the `package/` prefix already stripped — never a directory on
55
+ * disk, because that list is what a consumer's installer unpacks and it needs no filesystem to
56
+ * exist.
51
57
  *
52
58
  * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
53
59
  * argv here. `cli.ts` owns the effects.
@@ -72,7 +78,8 @@ const CRITICAL_PATTERNS = [
72
78
  /(?:^|\/)\.npmrc$/i,
73
79
  /\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
74
80
  /(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
75
- ], SUSPICIOUS_PATTERNS = [
81
+ ];
82
+ const SUSPICIOUS_PATTERNS = [
76
83
  /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
77
84
  /(?:^|\/)\.github(?:\/|$)/,
78
85
  /(?:^|\/)tsconfig[^/]*\.json$/,
@@ -80,10 +87,10 @@ const CRITICAL_PATTERNS = [
80
87
  /\.(?:test|spec)\.[cm]?[jt]sx?$/
81
88
  ];
82
89
  function validatePackedFiles(files, skipSuspicious) {
83
- let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
90
+ const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
84
91
  if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
85
92
  if (skipSuspicious) return;
86
- let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
93
+ const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
87
94
  if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
88
95
  }
89
96
  /**
@@ -95,11 +102,15 @@ function validatePackedFiles(files, skipSuspicious) {
95
102
  * dropped file: the leak checks only ask what is present, and a package missing a file installs
96
103
  * fine and then fails at import, on a version the registry keeps forever.
97
104
  *
98
- * Both lists are read out of the archives by `tar`, an instrument that cannot share a mistake
99
- * with the walk being checked.
105
+ * The two lists come from the same reader, so this cannot catch a defect in the reader itself —
106
+ * only one in the rewrite, which is what it is for. Independence from the reader is bought
107
+ * elsewhere, by the case in test/cli.test.ts that compares the list this reader prints against
108
+ * `tar tzf` of the same tarball — an instrument that cannot share a mistake with this one.
100
109
  */
101
110
  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}`)];
111
+ const before = new Set(packed);
112
+ const after = new Set(published);
113
+ const changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
103
114
  if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
104
115
  }
105
116
  /**
@@ -121,23 +132,24 @@ function assertSameEntries(packed, published) {
121
132
  * `exports` condition values legitimately hold them.
122
133
  */
123
134
  function collectDeclaredPaths(value, out, mode) {
124
- if (typeof value == "string") {
125
- (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
135
+ if (typeof value === "string") {
136
+ if (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) out.push(value);
126
137
  return;
127
138
  }
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);
139
+ if (typeof value === "boolean") return;
140
+ if (Array.isArray(value)) {
141
+ for (const item of value) collectDeclaredPaths(item, out, mode);
142
+ return;
134
143
  }
144
+ if (!isObject(value)) return;
145
+ for (const item of Object.values(value)) collectDeclaredPaths(item, out, mode);
135
146
  }
136
147
  function normalizeDeclaredPath(declared) {
137
- let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
148
+ const withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
138
149
  if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
139
- let normalized = path.posix.normalize(withoutDot);
140
- return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
150
+ const normalized = path.posix.normalize(withoutDot);
151
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
152
+ return normalized;
141
153
  }
142
154
  /**
143
155
  * Refuses a manifest whose declared entry points are not in the tarball.
@@ -147,29 +159,33 @@ function normalizeDeclaredPath(declared) {
147
159
  * answer a question npm answers at install time.
148
160
  */
149
161
  function assertDeclaredFiles(pkg, published) {
150
- let declared = [];
151
- for (let field of [
162
+ const declared = [];
163
+ for (const field of [
152
164
  "main",
153
165
  "module",
154
166
  "types",
155
167
  "typings",
156
168
  "bin"
157
169
  ]) 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 [
170
+ if (typeof pkg.browser === "string") collectDeclaredPaths(pkg.browser, declared, "every-string");
171
+ else collectDeclaredPaths(pkg.browser, declared, "relative-only");
172
+ for (const field of [
160
173
  "exports",
161
174
  "imports",
162
175
  "sideEffects"
163
176
  ]) collectDeclaredPaths(pkg[field], declared, "relative-only");
164
177
  collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
165
- let resolved = declared.map((declaredPath) => ({
178
+ const resolved = declared.map((declaredPath) => ({
166
179
  path: declaredPath,
167
180
  normalized: normalizeDeclaredPath(declaredPath)
168
- })), invalid = resolved.filter((item) => item.normalized === null);
181
+ }));
182
+ const invalid = resolved.filter((item) => item.normalized === null);
169
183
  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)));
184
+ const shipped = new Set(published);
185
+ const missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
171
186
  if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
172
187
  }
188
+
173
189
  //#endregion
174
190
  //#region src/command.ts
175
191
  /**
@@ -196,20 +212,22 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
196
212
  *
197
213
  * `/d` skips registry AutoRun commands, which would otherwise execute inside a publish. Neither
198
214
  * `/s` nor `windowsVerbatimArguments` is used: without them Node applies its ordinary C-runtime
199
- * quoting to every argument, exactly as on any other platform, and there is no second escaping
200
- * layer to get wrong. The one residual is cmd's `%VAR%` expansion inside an argument, which no
201
- * argument this tool generates contains; a caller writing one after `--` gets it expanded.
215
+ * quoting to every argument, exactly as on any other platform, so this file owns no escaping.
216
+ * What it owns instead is the refusal below, which is what keeps that true.
202
217
  */
203
- function spawnArgs(command, args) {
204
- return process.platform === "win32" ? ["cmd.exe", [
218
+ function spawnArgs(command, args, platform) {
219
+ if (platform !== "win32") return [command, [...args]];
220
+ const unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
221
+ if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.join("\n")}\nMove the package to a path without & | < > ^ % ( ), or publish from Linux or macOS.`);
222
+ return ["cmd.exe", [
205
223
  "/d",
206
224
  "/c",
207
225
  command,
208
226
  ...args
209
- ]] : [command, [...args]];
227
+ ]];
210
228
  }
211
229
  function run(command, args, cwd) {
212
- return execFileSync(...spawnArgs(command, args), {
230
+ return execFileSync(...spawnArgs(command, args, process.platform), {
213
231
  cwd,
214
232
  encoding: "utf8",
215
233
  stdio: [
@@ -230,7 +248,7 @@ function run(command, args, cwd) {
230
248
  * that says nothing about the one action that cannot be undone.
231
249
  */
232
250
  function runAttached(command, args, cwd) {
233
- execFileSync(...spawnArgs(command, args), {
251
+ execFileSync(...spawnArgs(command, args, process.platform), {
234
252
  cwd,
235
253
  stdio: [
236
254
  "ignore",
@@ -242,8 +260,10 @@ function runAttached(command, args, cwd) {
242
260
  /** Child output survives only on the thrown error, and is lost unless read off it here. */
243
261
  function outputFromError(error, key) {
244
262
  if (!isObject(error)) return "";
245
- let output = error[key];
246
- return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
263
+ const output = error[key];
264
+ if (typeof output === "string") return output.trim();
265
+ if (output instanceof Uint8Array) return Buffer.from(output).toString("utf8").trim();
266
+ return "";
247
267
  }
248
268
  /**
249
269
  * A required tool can fail three ways, and each one asks something different of the
@@ -258,12 +278,12 @@ function toolFailureReason(cause) {
258
278
  if (cause.code === "ENOENT") return "is not available in PATH";
259
279
  if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
260
280
  }
261
- let stderr = outputFromError(cause, "stderr");
281
+ const stderr = outputFromError(cause, "stderr");
262
282
  return `failed to run${stderr ? `: ${stderr}` : ""}`;
263
283
  }
264
284
  function requireTool(name) {
265
285
  try {
266
- execFileSync(...spawnArgs(name, ["--version"]), {
286
+ execFileSync(...spawnArgs(name, ["--version"], process.platform), {
267
287
  stdio: [
268
288
  "ignore",
269
289
  "ignore",
@@ -275,6 +295,7 @@ function requireTool(name) {
275
295
  throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
276
296
  }
277
297
  }
298
+
278
299
  //#endregion
279
300
  //#region src/manifest.ts
280
301
  /**
@@ -284,25 +305,74 @@ function requireTool(name) {
284
305
  * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
285
306
  * argv here — so every rule is one input to one output. `cli.ts` owns the effects.
286
307
  */
287
- 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([
308
+ const DEV_FIELDS = /* @__PURE__ */ new Set([
309
+ "$schema",
310
+ "catalog",
311
+ "catalogs",
312
+ "patchedDependencies",
313
+ "private",
314
+ "files",
315
+ "stylelint",
316
+ "trustedDependencies",
317
+ "wireit",
318
+ "devDependencies",
319
+ "overrides",
320
+ "resolutions",
321
+ "ava",
322
+ "c8",
323
+ "jest",
324
+ "mocha",
325
+ "nyc",
326
+ "tap",
327
+ "vitest",
328
+ "babel",
329
+ "biome",
330
+ "browserslist",
331
+ "eslintConfig",
332
+ "eslintIgnore",
333
+ "prettier",
334
+ "remarkConfig",
335
+ "xo",
336
+ "commitlint",
337
+ "husky",
338
+ "lint-staged",
339
+ "simple-git-hooks",
340
+ "clean-publish",
341
+ "publish-clean",
342
+ "semantic-release",
343
+ "packageManager",
344
+ "pnpm",
345
+ "volta",
346
+ "workspaces",
347
+ "nx",
348
+ "turbo"
349
+ ]);
350
+ const CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
288
351
  "preinstall",
289
352
  "install",
290
353
  "postinstall",
291
354
  "prepare",
292
355
  "uninstall"
293
- ]), DEP_FIELDS = [
356
+ ]);
357
+ const DEP_FIELDS = [
294
358
  "dependencies",
295
359
  "devDependencies",
296
360
  "optionalDependencies",
297
361
  "peerDependencies",
298
362
  "overrides",
299
363
  "resolutions"
300
- ], MONOREPO_PROTOCOLS = [
364
+ ];
365
+ const MONOREPO_PROTOCOLS = [
301
366
  "catalog:",
302
367
  "workspace:",
303
368
  "link:",
304
369
  "portal:"
305
- ], RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
370
+ ];
371
+ /**
372
+ * Fields a consumer's toolchain resolves. Stripping one breaks installs, imports or
373
+ * platform gating, so `devFields` is not allowed to name them.
374
+ */
375
+ const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
306
376
  ...DEP_FIELDS,
307
377
  "bin",
308
378
  "browser",
@@ -326,7 +396,17 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
326
396
  "typesVersions",
327
397
  "typings",
328
398
  "version"
329
- ]), REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
399
+ ]);
400
+ /**
401
+ * Fields npm's registry, website and CLI read, plus the de-facto entry points bundlers
402
+ * and CDNs look for. Recognised, so they raise no report, but a maintainer may legitimately
403
+ * strip any of them through `devFields`: none is load-bearing for an install.
404
+ *
405
+ * Together with RUNTIME_MANIFEST_FIELDS this is the answer to "does anything downstream
406
+ * read this key?". Anything outside both sets is, as far as this tool can tell, project
407
+ * bookkeeping that a consumer downloads and never uses.
408
+ */
409
+ const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
330
410
  "author",
331
411
  "bugs",
332
412
  "config",
@@ -350,15 +430,26 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
350
430
  "styleModule",
351
431
  "svelte",
352
432
  "unpkg"
353
- ]), 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.";
433
+ ]);
434
+ /**
435
+ * Shown when another package manager started this tool, so the pnpm requirement is not a
436
+ * surprise. It names the packer and the consequence for the reader's own layout, rather
437
+ * than claiming the alternatives are broken, because what a reader needs to do next
438
+ * depends on which package manager they came from.
439
+ *
440
+ * The measured comparison behind the choice of packer, and the standing rule against
441
+ * swapping it, live in this repository's AGENTS.md.
442
+ */
443
+ const 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.";
354
444
  function stripManifest(pkg, extraDevFields) {
355
- let stripped = { ...pkg };
356
- for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
357
- let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
445
+ const stripped = { ...pkg };
446
+ for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
447
+ const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
358
448
  if (scripts) {
359
- let kept = {};
360
- for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
361
- Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
449
+ const kept = {};
450
+ for (const [name, value] of Object.entries(scripts)) if (CONSUMER_SCRIPTS.has(name) && typeof value === "string") kept[name] = value;
451
+ if (Object.keys(kept).length > 0) stripped.scripts = kept;
452
+ else delete stripped.scripts;
362
453
  }
363
454
  return stripped;
364
455
  }
@@ -375,8 +466,9 @@ function stripManifest(pkg, extraDevFields) {
375
466
  */
376
467
  function withRegistry(pkg, registry) {
377
468
  if (registry === null) return pkg;
378
- let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
379
- return publishConfig.registry = registry, {
469
+ const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
470
+ publishConfig.registry = registry;
471
+ return {
380
472
  ...pkg,
381
473
  publishConfig
382
474
  };
@@ -399,11 +491,12 @@ function withRegistry(pkg, registry) {
399
491
  * none.
400
492
  */
401
493
  function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
402
- let expected = /* @__PURE__ */ new Set([
494
+ const expected = /* @__PURE__ */ new Set([
403
495
  ...DEV_FIELDS,
404
496
  ...removedOnRequest,
405
497
  "scripts"
406
- ]), lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
498
+ ]);
499
+ const lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
407
500
  if (lost.length > 0) throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${lost.join("\n")}`);
408
501
  }
409
502
  /**
@@ -422,8 +515,10 @@ function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
422
515
  * object, which two cases running side by side can clobber.
423
516
  */
424
517
  function unrecognizedFieldsReport(pkg, kept) {
425
- let acknowledged = new Set(kept), unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
426
- 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(", ")}] }`;
518
+ const acknowledged = new Set(kept);
519
+ const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
520
+ if (unrecognized.length === 0) return null;
521
+ return `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(", ")}] }`;
427
522
  }
428
523
  /**
429
524
  * Refuses a manifest that still carries a spec only a workspace can resolve. Published
@@ -435,18 +530,23 @@ function unrecognizedFieldsReport(pkg, kept) {
435
530
  * the order it happens to be called in fails silently the day someone reorders it.
436
531
  */
437
532
  function assertNoMonorepoProtocols(pkg) {
438
- let failures = [];
439
- for (let field of DEP_FIELDS) {
440
- let map = pkg[field];
441
- 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}`);
533
+ const failures = [];
534
+ for (const field of DEP_FIELDS) {
535
+ const map = pkg[field];
536
+ if (!isObject(map)) continue;
537
+ for (const [name, spec] of Object.entries(map)) {
538
+ if (typeof spec !== "string") continue;
539
+ if (MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix))) failures.push(`${field}.${name}: ${spec}`);
540
+ }
442
541
  }
443
542
  if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
444
543
  }
445
544
  function assertPublicPackage(pkg) {
446
- if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
545
+ if (pkg.private === true) throw new PublishCleanError("Refusing to publish a package with private: true.");
447
546
  }
448
547
  function assertFilesField(pkg, skip) {
449
- if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
548
+ if (skip) return;
549
+ if (!Array.isArray(pkg.files) || pkg.files.length === 0) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
450
550
  }
451
551
  /**
452
552
  * Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
@@ -462,9 +562,9 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
462
562
  "skipFileCheck"
463
563
  ]);
464
564
  function packageConfig(pkg) {
465
- let config = pkg["publish-clean"];
565
+ const config = pkg["publish-clean"];
466
566
  if (!isObject(config)) return {};
467
- let unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
567
+ const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
468
568
  if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
469
569
  return config;
470
570
  }
@@ -474,15 +574,17 @@ function packageConfig(pkg) {
474
574
  * silently means the author's intent is lost with no signal anywhere.
475
575
  */
476
576
  function stringList(config, key) {
477
- let value = config[key];
577
+ const value = config[key];
478
578
  if (value === void 0) return [];
479
- if (!Array.isArray(value) || value.some((entry) => typeof entry != "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
579
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
480
580
  return value;
481
581
  }
482
582
  function customDevFields(config) {
483
- let fields = stringList(config, "devFields"), kept = new Set(stringList(config, "keepFields")), contradictory = fields.filter((field) => kept.has(field));
583
+ const fields = stringList(config, "devFields");
584
+ const kept = new Set(stringList(config, "keepFields"));
585
+ const contradictory = fields.filter((field) => kept.has(field));
484
586
  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")}`);
485
- let unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
587
+ const unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
486
588
  if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
487
589
  return fields;
488
590
  }
@@ -500,6 +602,7 @@ function customDevFields(config) {
500
602
  function keptFields(config) {
501
603
  return stringList(config, "keepFields");
502
604
  }
605
+
503
606
  //#endregion
504
607
  //#region src/tarball.ts
505
608
  /**
@@ -524,17 +627,67 @@ function keptFields(config) {
524
627
  * question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
525
628
  * containing a newline arrives as two entries there and as itself here.
526
629
  */
527
- const MANIFEST_PATH = "package/package.json", PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
630
+ const BLOCK = 512;
631
+ const NAME_LEN = 100;
632
+ const SIZE_OFFSET = 124;
633
+ const CHECKSUM_OFFSET = 148;
634
+ const TYPE_OFFSET = 156;
635
+ /**
636
+ * The manifest is always at this exact path, and at 20 characters it can never be the entry
637
+ * that needs a pax header or a prefix split — so the one entry this code must identify is
638
+ * also the one whose name is guaranteed to be readable straight from the header block.
639
+ */
640
+ const MANIFEST_PATH = "package/package.json";
641
+ /** Extended (`x`) and global (`g`) pax headers carry key/value overrides for other entries. */
642
+ const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
643
+ /** Tar's flag for a directory entry. Directories are not files a consumer imports. */
644
+ const DIRECTORY_TYPE = "5";
645
+ /**
646
+ * GNU's long-name entry, whose payload is the real path of the entry that follows it while
647
+ * that entry's own header reads `././@LongLink`.
648
+ *
649
+ * Refused for the same reason a pax `path=` override is: it renames the following entry, so it
650
+ * can point at `package/package.json` and the archive then extracts a manifest no guard here
651
+ * ever saw. pnpm emits pax and never this, so refusing costs nothing and closes the second way
652
+ * to rename an entry onto the one path this tool authors. `K` (long *link* name) is left alone:
653
+ * it renames a symlink target, which cannot collide with an entry path.
654
+ */
655
+ const GNU_LONG_NAME = "L";
528
656
  function field(block, offset, length) {
529
657
  return block.toString("utf8", offset, offset + length).replace(/\0.*/s, "");
530
658
  }
531
659
  function entrySize(block) {
532
- if ((block[124] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
533
- let size = Number.parseInt(field(block, 124, 12).trim(), 8);
660
+ if ((block[SIZE_OFFSET] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
661
+ const size = Number.parseInt(field(block, SIZE_OFFSET, 12).trim(), 8);
534
662
  if (!Number.isFinite(size) || size < 0) throw new PublishCleanError("Tarball entry has an unreadable size field.");
535
663
  return size;
536
664
  }
537
665
  /**
666
+ * Verifies a header block against the checksum tar stores inside it.
667
+ *
668
+ * This is the format's own integrity check over the 512 bytes that say where an entry starts,
669
+ * how long it is and what it is called — the fields a walk trusts absolutely. The gzip CRC
670
+ * already covers every byte of the archive, so on a packed tarball this is redundant; it is
671
+ * here because the rewrite AUTHORS one of these blocks, and a checksum nothing verifies is a
672
+ * value vouching for itself. Reading the written artifact back runs this over that block.
673
+ *
674
+ * Both sums are accepted because tar has two historical conventions: the standard sums the
675
+ * bytes unsigned, while older implementations summed them as signed chars. The two agree for
676
+ * every all-ASCII header and diverge the moment a name carries a byte above 127, so refusing
677
+ * the signed form would reject valid archives holding non-ASCII filenames.
678
+ */
679
+ function assertChecksum(header, name) {
680
+ const stored = Number.parseInt(field(header, CHECKSUM_OFFSET, 8).trim(), 8);
681
+ let unsigned = 0;
682
+ let signed = 0;
683
+ for (const [index, byte] of header.entries()) {
684
+ const value = index >= CHECKSUM_OFFSET && index < 156 ? 32 : byte;
685
+ unsigned += value;
686
+ signed += value > 127 ? value - 256 : value;
687
+ }
688
+ if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
689
+ }
690
+ /**
538
691
  * Rejects a pax header that renames another entry onto the manifest path.
539
692
  *
540
693
  * Without this the archive could extract a `package.json` that no check ever saw: the guards
@@ -543,15 +696,17 @@ function entrySize(block) {
543
696
  * substitution is visible from the walk alone.
544
697
  */
545
698
  function assertNoManifestOverride(payload) {
546
- for (let record of payload.toString("utf8").split("\n")) if (/^\d+ path=/.test(record) && record.slice(record.indexOf("=") + 1) === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
699
+ for (const record of payload.toString("utf8").split("\n")) if (/^\d+ path=/.test(record) && record.slice(record.indexOf("=") + 1) === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
547
700
  }
548
701
  /** Rebuilds a header for a changed payload size, keeping every other field of the original. */
549
702
  function reheader(original, size) {
550
- let header = Buffer.from(original);
551
- header.write(size.toString(8).padStart(11, "0") + "\0", 124, 12, "ascii"), header.write(" ".repeat(8), 148, 8, "ascii");
703
+ const header = Buffer.from(original);
704
+ header.write(size.toString(8).padStart(11, "0") + "\0", SIZE_OFFSET, 12, "ascii");
705
+ header.write(" ".repeat(8), CHECKSUM_OFFSET, 8, "ascii");
552
706
  let sum = 0;
553
- for (let byte of header) sum += byte;
554
- return header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii"), header;
707
+ for (const byte of header) sum += byte;
708
+ header.write(sum.toString(8).padStart(6, "0") + "\0 ", CHECKSUM_OFFSET, 8, "ascii");
709
+ return header;
555
710
  }
556
711
  /**
557
712
  * Decodes a gzipped tarball into its entries, refusing every shape whose meaning this tool
@@ -564,20 +719,26 @@ function reheader(original, size) {
564
719
  * partial write becomes a published package.
565
720
  */
566
721
  function readArchive(gzipped) {
567
- let tar = gunzipSync(gzipped), entries = [], tail = null;
722
+ const tar = gunzipSync(gzipped);
723
+ const entries = [];
724
+ let tail = null;
568
725
  for (let offset = 0; offset < tar.length;) {
569
- let header = tar.subarray(offset, offset + 512);
570
- if (header.length < 512) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
571
- let name = field(header, 0, 100);
726
+ const header = tar.subarray(offset, offset + BLOCK);
727
+ if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
728
+ const name = field(header, 0, NAME_LEN);
572
729
  if (name === "") {
573
730
  tail = tar.subarray(offset);
574
731
  break;
575
732
  }
576
- let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512);
733
+ assertChecksum(header, name);
734
+ const size = entrySize(header);
735
+ const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
577
736
  if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
578
- let type = field(header, 156, 1), body = tar.subarray(offset + 512, offset + 512 + size);
579
- if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
580
- if (PAX_TYPES.has(type) && assertNoManifestOverride(body), name === MANIFEST_PATH) {
737
+ const type = field(header, TYPE_OFFSET, 1);
738
+ const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
739
+ if (type === GNU_LONG_NAME) throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
740
+ if (PAX_TYPES.has(type)) assertNoManifestOverride(body);
741
+ if (name === MANIFEST_PATH) {
581
742
  if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
582
743
  if (entries.some((entry) => entry.name === MANIFEST_PATH)) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
583
744
  }
@@ -587,7 +748,8 @@ function readArchive(gzipped) {
587
748
  header,
588
749
  body,
589
750
  raw: tar.subarray(offset, end)
590
- }), offset = end;
751
+ });
752
+ offset = end;
591
753
  }
592
754
  if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
593
755
  return {
@@ -601,10 +763,10 @@ function readArchive(gzipped) {
601
763
  * imports, and a pax header's own name (`PaxHeader`) names no file at all.
602
764
  */
603
765
  function packageFiles(archive) {
604
- 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();
766
+ return archive.entries.filter((entry) => entry.type !== DIRECTORY_TYPE && !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();
605
767
  }
606
768
  function manifestEntry(archive) {
607
- let entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
769
+ const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
608
770
  if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
609
771
  return entry;
610
772
  }
@@ -614,13 +776,17 @@ function manifestText(archive) {
614
776
  }
615
777
  /** Returns the gzipped tarball with `package/package.json` replaced by `manifest`. */
616
778
  function replaceManifest(archive, manifest) {
617
- let target = manifestEntry(archive), body = Buffer.from(manifest, "utf8"), parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
779
+ const target = manifestEntry(archive);
780
+ const body = Buffer.from(manifest, "utf8");
781
+ const parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
618
782
  reheader(entry.header, body.length),
619
783
  body,
620
- Buffer.alloc(512 * Math.ceil(body.length / 512) - body.length)
784
+ Buffer.alloc(BLOCK * Math.ceil(body.length / BLOCK) - body.length)
621
785
  ]) : entry.raw);
622
- return parts.push(archive.tail), gzipSync(Buffer.concat(parts), { level: 9 });
786
+ parts.push(archive.tail);
787
+ return gzipSync(Buffer.concat(parts), { level: 9 });
623
788
  }
789
+
624
790
  //#endregion
625
791
  //#region src/trusted-publish.ts
626
792
  /**
@@ -640,57 +806,100 @@ const MIN_TRUSTED_NPM_VERSION = [
640
806
  11,
641
807
  5,
642
808
  1
643
- ], MIN_TRUSTED_NODE_VERSION = [
809
+ ];
810
+ const MIN_TRUSTED_NODE_VERSION = [
644
811
  22,
645
812
  14,
646
813
  0
647
814
  ];
648
815
  function isAtLeast(actual, minimum) {
649
- for (let index of [
816
+ for (const index of [
650
817
  0,
651
818
  1,
652
819
  2
653
820
  ]) {
654
- if (actual[index] > minimum[index]) return !0;
655
- if (actual[index] < minimum[index]) return !1;
821
+ if (actual[index] > minimum[index]) return true;
822
+ if (actual[index] < minimum[index]) return false;
656
823
  }
657
- return !0;
824
+ return true;
658
825
  }
659
826
  function wantsTrustedPublish(pkg, publishArgs, env) {
660
- return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
827
+ if (publishArgs.includes("--provenance")) return true;
828
+ if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance === true) return true;
829
+ return env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string";
661
830
  }
662
831
  function repositoryUrl(pkg) {
663
- return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
832
+ if (typeof pkg.repository === "string") return pkg.repository;
833
+ if (isObject(pkg.repository) && typeof pkg.repository.url === "string") return pkg.repository.url;
834
+ return null;
664
835
  }
665
836
  function githubRepositorySlug(url) {
666
- let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
837
+ const withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
667
838
  if (withoutGitPrefix.startsWith("git@github.com:")) {
668
- let slug = withoutGitPrefix.slice(15);
839
+ const slug = withoutGitPrefix.slice(15);
669
840
  return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
670
841
  }
671
842
  try {
672
- let parsed = new URL(withoutGitPrefix);
843
+ const parsed = new URL(withoutGitPrefix);
673
844
  if (parsed.hostname !== "github.com") return null;
674
- let slug = parsed.pathname.replace(/^\/+/, "");
845
+ const slug = parsed.pathname.replace(/^\/+/, "");
675
846
  return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
676
847
  } catch {
677
848
  return null;
678
849
  }
679
850
  }
680
851
  function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
681
- if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
682
- let repoUrl = repositoryUrl(pkg);
852
+ if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
853
+ if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
854
+ const repoUrl = repositoryUrl(pkg);
683
855
  if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
684
856
  if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
685
857
  }
858
+
859
+ //#endregion
860
+ //#region src/cli.ts
861
+ /**
862
+ * The whole interface in one screen, because this is where an out-of-context reader lands:
863
+ * the flags, the manifest config block that sets the same policies durably, and the `--`
864
+ * convention that decides which arguments this tool reads and which npm does. Anything a
865
+ * user must know to publish correctly belongs here, not only in the README, which is not
866
+ * installed next to the binary.
867
+ */
868
+ const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
869
+
870
+ Packs with pnpm, strips developer-only fields from the packed manifest, validates the
871
+ artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
872
+ \`npm publish\` untouched (e.g. --access public --tag next --provenance).
873
+
874
+ Options:
875
+ --dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
876
+ --guard-only Same checks, no output and no publish. For a pre-publish gate.
877
+ --tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
878
+ --registry URL Publish to URL, and record it in the artifact's publishConfig.
879
+ --no-git-checks Publish from a working tree with uncommitted changes.
880
+ --skip-file-check Allow a manifest with no "files" array.
881
+ --allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
882
+ -h, --help Show this help.
883
+ -v, --version Show the publish-clean version.
884
+
885
+ Manifest configuration, under a "publish-clean" key in package.json:
886
+ devFields string[] Extra fields to strip. Refused for fields consumers resolve.
887
+ keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
888
+ registry string Default for --registry.
889
+ noGitChecks boolean Default for --no-git-checks.
890
+ skipFileCheck boolean Default for --skip-file-check.
891
+ allowSuspicious boolean Default for --allow-suspicious.
892
+
893
+ Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
894
+ npm 11.5.1+, and only a cloud CI runner can produce it.`;
686
895
  /**
687
896
  * Read from the installed manifest rather than baked in at build time, so the number cannot
688
897
  * drift from the package a user actually has — which is the only reason anyone asks a tool
689
898
  * for its version.
690
899
  */
691
900
  function ownVersion() {
692
- let manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
693
- return typeof manifest.version == "string" ? manifest.version : "unknown";
901
+ const manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
902
+ return typeof manifest.version === "string" ? manifest.version : "unknown";
694
903
  }
695
904
  function readJson(file) {
696
905
  let parsed;
@@ -702,9 +911,20 @@ function readJson(file) {
702
911
  if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
703
912
  return parsed;
704
913
  }
705
- function npmVersion() {
706
- let raw = run("npm", ["--version"], process.cwd()).trim(), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
707
- if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse npm version: ${raw}`);
914
+ /**
915
+ * Asks an executable on PATH what version it is, e.g. `24.15.0` from node's `v24.15.0`.
916
+ *
917
+ * Both provenance floors are asked of PATH rather than read from this process, because the
918
+ * process that has to satisfy them is npm's, not this one. `npm` is a `#!/usr/bin/env node`
919
+ * script, so the Node enforcing the floor is whichever one PATH resolves — and that is not
920
+ * necessarily the one executing this file. Under Bun the gap is total: `process.versions.node`
921
+ * is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
922
+ * so reading it would answer a question nobody asked while looking exactly like a check.
923
+ */
924
+ function toolVersion(command) {
925
+ const raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, "");
926
+ const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
927
+ if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
708
928
  return [
709
929
  parts[0] ?? 0,
710
930
  parts[1] ?? 0,
@@ -725,22 +945,21 @@ function publishEnv() {
725
945
  }
726
946
  function assertTrustedPublishingRuntime(pkg, publishArgs) {
727
947
  if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
728
- let actual = npmVersion();
729
- if (!isAtLeast(actual, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${actual.join(".")}.`);
730
- let node = process.versions.node.split(".").map(Number);
731
- if (!isAtLeast([
732
- node[0] ?? 0,
733
- node[1] ?? 0,
734
- node[2] ?? 0
735
- ], MIN_TRUSTED_NODE_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${process.versions.node}.`);
948
+ const npm = toolVersion("npm");
949
+ if (!isAtLeast(npm, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${npm.join(".")}.`);
950
+ const node = toolVersion("node");
951
+ if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
952
+ throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
736
953
  }
737
954
  function warnIfNonPnpmLifecycle() {
738
- let userAgent = process.env.npm_config_user_agent;
739
- !userAgent || userAgent.startsWith("pnpm/") || console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
955
+ const userAgent = process.env.npm_config_user_agent;
956
+ if (!userAgent || userAgent.startsWith("pnpm/")) return;
957
+ console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
740
958
  }
741
959
  function assertCleanGit(packageDir, skip) {
742
- if (!skip) try {
743
- let output = run("git", [
960
+ if (skip) return;
961
+ try {
962
+ const output = run("git", [
744
963
  "status",
745
964
  "--porcelain",
746
965
  "--",
@@ -749,7 +968,7 @@ function assertCleanGit(packageDir, skip) {
749
968
  if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
750
969
  } catch (error) {
751
970
  if (error instanceof PublishCleanError) throw error;
752
- let stderr = outputFromError(error, "stderr");
971
+ const stderr = outputFromError(error, "stderr");
753
972
  throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
754
973
  }
755
974
  }
@@ -785,46 +1004,67 @@ function manifestOf(archive, label) {
785
1004
  * destination was not exclusive and the wrong artifact could be published.
786
1005
  */
787
1006
  async function soleTarball(packRoot) {
788
- let tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz")), [tarball] = tarballs;
1007
+ const tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz"));
1008
+ const [tarball] = tarballs;
789
1009
  if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
790
1010
  return path.join(packRoot, tarball);
791
1011
  }
792
1012
  async function packAndClean(packageDir, opts) {
793
- requireTool("pnpm"), requireTool("npm"), warnIfNonPnpmLifecycle();
794
- let sourcePkg = readJson(path.join(packageDir, "package.json"));
795
- !opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
796
- 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);
797
- assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
798
- let root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
1013
+ requireTool("pnpm");
1014
+ requireTool("npm");
1015
+ warnIfNonPnpmLifecycle();
1016
+ const sourcePkg = readJson(path.join(packageDir, "package.json"));
1017
+ if (!opts.guardOnly && !opts.dryRun) assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
1018
+ const config = packageConfig(sourcePkg);
1019
+ const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
1020
+ const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
1021
+ const noGitChecks = opts.noGitChecks || config.noGitChecks === true;
1022
+ const registry = opts.registry ?? (typeof config.registry === "string" ? config.registry : null);
1023
+ const extraDevFields = customDevFields(config);
1024
+ const keepFields = keptFields(config);
1025
+ assertPublicPackage(sourcePkg);
1026
+ assertCleanGit(packageDir, noGitChecks);
1027
+ assertFilesField(sourcePkg, skipFileCheck);
1028
+ const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
799
1029
  try {
800
1030
  run("pnpm", [
801
1031
  "pack",
802
1032
  "--pack-destination",
803
1033
  root
804
1034
  ], packageDir);
805
- let tarball = await soleTarball(root), packed = await readTarball(tarball), cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry), unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
806
- unrecognized && console.warn(unrecognized);
807
- let publishRoot = path.join(root, "publish");
1035
+ const tarball = await soleTarball(root);
1036
+ const packed = await readTarball(tarball);
1037
+ const cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry);
1038
+ const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
1039
+ if (unrecognized) console.warn(unrecognized);
1040
+ const publishRoot = path.join(root, "publish");
808
1041
  await mkdir(publishRoot);
809
- let finalTarball = path.join(publishRoot, path.basename(tarball));
1042
+ const finalTarball = path.join(publishRoot, path.basename(tarball));
810
1043
  await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
811
- let published = await readTarball(finalTarball), finalFiles = packageFiles(published);
812
- assertSameEntries(packageFiles(packed), finalFiles), validatePackedFiles(finalFiles, allowSuspicious), assertDeclaredFiles(cleanedPkg, finalFiles);
813
- let shippedPkg = manifestOf(published, "the published tarball");
814
- if (assertNoMonorepoProtocols(shippedPkg), assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields), stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
1044
+ const published = await readTarball(finalTarball);
1045
+ const finalFiles = packageFiles(published);
1046
+ assertSameEntries(packageFiles(packed), finalFiles);
1047
+ validatePackedFiles(finalFiles, allowSuspicious);
1048
+ assertDeclaredFiles(cleanedPkg, finalFiles);
1049
+ const shippedPkg = manifestOf(published, "the published tarball");
1050
+ assertNoMonorepoProtocols(shippedPkg);
1051
+ assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields);
1052
+ if (stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
815
1053
  if (opts.tarballOut !== null) {
816
- await mkdir(opts.tarballOut, { recursive: !0 });
817
- let kept = path.join(opts.tarballOut, path.basename(finalTarball));
818
- await copyFile(finalTarball, kept), console.log(`Final tarball kept at: ${kept}`);
1054
+ await mkdir(opts.tarballOut, { recursive: true });
1055
+ const kept = path.join(opts.tarballOut, path.basename(finalTarball));
1056
+ await copyFile(finalTarball, kept);
1057
+ console.log(`Final tarball kept at: ${kept}`);
819
1058
  }
820
1059
  if (opts.dryRun) {
821
1060
  console.log(`[dry-run] ${finalFiles.length} files:`);
822
- for (let file of finalFiles) console.log(` ${file}`);
1061
+ for (const file of finalFiles) console.log(` ${file}`);
823
1062
  console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
824
1063
  return;
825
1064
  }
826
1065
  if (opts.guardOnly) return;
827
- assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv()), runAttached("npm", registry ? [
1066
+ assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv());
1067
+ const publishArgs = registry ? [
828
1068
  "publish",
829
1069
  finalTarball,
830
1070
  "--registry",
@@ -834,39 +1074,44 @@ async function packAndClean(packageDir, opts) {
834
1074
  "publish",
835
1075
  finalTarball,
836
1076
  ...opts.publishArgs
837
- ], packageDir);
1077
+ ];
1078
+ runAttached("npm", publishArgs, packageDir);
838
1079
  } finally {
839
1080
  await rm(root, {
840
- recursive: !0,
841
- force: !0
1081
+ recursive: true,
1082
+ force: true
842
1083
  });
843
1084
  }
844
1085
  }
845
1086
  async function main() {
846
- let rawArgs = process.argv.slice(2), separator = rawArgs.indexOf("--"), cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator), publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1), parsed = parseArgs({
1087
+ const rawArgs = process.argv.slice(2);
1088
+ const separator = rawArgs.indexOf("--");
1089
+ const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
1090
+ const publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1);
1091
+ const parsed = parseArgs({
847
1092
  args: cliArgs,
848
- allowPositionals: !0,
1093
+ allowPositionals: true,
849
1094
  options: {
850
1095
  "allow-suspicious": {
851
1096
  type: "boolean",
852
- default: !1
1097
+ default: false
853
1098
  },
854
1099
  "dry-run": {
855
1100
  type: "boolean",
856
- default: !1
1101
+ default: false
857
1102
  },
858
1103
  "guard-only": {
859
1104
  type: "boolean",
860
- default: !1
1105
+ default: false
861
1106
  },
862
1107
  help: {
863
1108
  type: "boolean",
864
1109
  short: "h",
865
- default: !1
1110
+ default: false
866
1111
  },
867
1112
  "no-git-checks": {
868
1113
  type: "boolean",
869
- default: !1
1114
+ default: false
870
1115
  },
871
1116
  registry: {
872
1117
  type: "string",
@@ -874,7 +1119,7 @@ async function main() {
874
1119
  },
875
1120
  "skip-file-check": {
876
1121
  type: "boolean",
877
- default: !1
1122
+ default: false
878
1123
  },
879
1124
  "tarball-out": {
880
1125
  type: "string",
@@ -883,38 +1128,40 @@ async function main() {
883
1128
  version: {
884
1129
  type: "boolean",
885
1130
  short: "v",
886
- default: !1
1131
+ default: false
887
1132
  }
888
1133
  },
889
- strict: !0
1134
+ strict: true
890
1135
  });
891
1136
  if (parsed.values.version) {
892
1137
  console.log(ownVersion());
893
1138
  return;
894
1139
  }
895
1140
  if (parsed.values.help) {
896
- 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.");
1141
+ console.log(HELP);
897
1142
  return;
898
1143
  }
899
1144
  if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
900
1145
  await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
901
- allowSuspicious: parsed.values["allow-suspicious"] === !0,
902
- dryRun: parsed.values["dry-run"] === !0,
903
- guardOnly: parsed.values["guard-only"] === !0,
904
- noGitChecks: parsed.values["no-git-checks"] === !0,
1146
+ allowSuspicious: parsed.values["allow-suspicious"] === true,
1147
+ dryRun: parsed.values["dry-run"] === true,
1148
+ guardOnly: parsed.values["guard-only"] === true,
1149
+ noGitChecks: parsed.values["no-git-checks"] === true,
905
1150
  publishArgs,
906
- registry: typeof parsed.values.registry == "string" ? parsed.values.registry : null,
907
- skipFileCheck: parsed.values["skip-file-check"] === !0,
908
- tarballOut: typeof parsed.values["tarball-out"] == "string" ? parsed.values["tarball-out"] : null
1151
+ registry: typeof parsed.values.registry === "string" ? parsed.values.registry : null,
1152
+ skipFileCheck: parsed.values["skip-file-check"] === true,
1153
+ tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
909
1154
  });
910
1155
  }
911
1156
  main().catch((error) => {
912
- let details = [
1157
+ const details = [
913
1158
  error instanceof Error ? error.message : String(error),
914
1159
  outputFromError(error, "stdout"),
915
1160
  outputFromError(error, "stderr")
916
1161
  ].filter((detail) => detail.length > 0);
917
- console.error(`publish-clean: ${details.join("\n")}`), process.exitCode = 1;
1162
+ console.error(`publish-clean: ${details.join("\n")}`);
1163
+ process.exitCode = 1;
918
1164
  });
1165
+
919
1166
  //#endregion
920
- export {};
1167
+ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anizoptera/publish-clean",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Pre-publish npm package cleaner that strips common useless noise and crap from package.json; prevents accidental publication of unwanted things and unresolved dependencies. No deps, one JS file.",
5
5
  "keywords": [
6
6
  "bun",