@anizoptera/publish-clean 0.4.0 → 0.5.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 +133 -210
  2. package/dist/cli.js +317 -270
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -1,23 +1,21 @@
1
1
  # @anizoptera/publish-clean
2
2
 
3
- Publish npm packages with a consumer-only `package.json`. Refuses to ship a `.env`, a
4
- private key, or an unresolved workspace dependency.
3
+ Pre-publish npm package cleaner that strips common useless noise and crap from
4
+ `package.json`; prevents accidental publication of unwanted things and unresolved
5
+ dependencies. No deps, one JS file.
5
6
 
6
7
  [![npm version](https://img.shields.io/npm/v/@anizoptera/publish-clean?label=npm)](https://www.npmjs.com/package/@anizoptera/publish-clean)
7
8
  [![Signed provenance](https://img.shields.io/badge/provenance-signed-2ea44f?logo=npm&logoColor=white)](https://www.npmjs.com/package/@anizoptera/publish-clean#provenance)
8
9
  [![CI](https://github.com/Anizoptera/publish-clean/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/Anizoptera/publish-clean/actions/workflows/check.yml)
9
- [![License](https://img.shields.io/github/license/Anizoptera/publish-clean)](LICENSE)
10
-
10
+ [![Node >=22.14](https://img.shields.io/badge/node-%3E%3D22.14-339933?logo=node.js&logoColor=white)](package.json)
11
11
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
12
- [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
13
- [![pnpm pack + npm publish](https://img.shields.io/badge/pnpm_pack%20%2B%20npm_publish-f69220?logo=pnpm&logoColor=white)](https://pnpm.io/cli/pack)
14
- [![Bun checked](https://img.shields.io/badge/Bun-checked-000000?logo=bun&logoColor=white)](https://bun.sh/docs/cli/test)
12
+ [![License](https://img.shields.io/github/license/Anizoptera/publish-clean)](LICENSE)
15
13
 
16
14
  When you run `npm publish`, two things ship that you probably did not mean to ship.
17
15
 
18
- The first is your `package.json`. It is a development manifest. It lists devDependencies,
19
- config blocks for your test runner and linter and formatter, `packageManager`,
20
- `workspaces`, `pnpm` settings, release-tool settings, and every script you run locally.
16
+ The first is your `package.json`. It is a development manifest: devDependencies, config
17
+ blocks for your test runner, linter and formatter, `packageManager`, `workspaces`, `pnpm`
18
+ settings, release-tool settings, and every script you run locally.
21
19
  npm sends all of it, unchanged, to everyone who installs your package. In a pnpm
22
20
  workspace it can also send `workspace:*` and `catalog:` specs that were never resolved,
23
21
  and those break the install for every consumer.
@@ -27,20 +25,29 @@ tests, `.github/`, a lockfile. You do not see the tarball before it goes out, an
27
25
  version is published you cannot edit it. Unpublishing only works for a short window and
28
26
  under conditions npm decides.
29
27
 
30
- `publish-clean` packs the package, rewrites the manifest of the extracted copy down to
31
- what consumers actually use, packs that, and publishes the result. Your working tree is
32
- never modified. If the artifact still has something in it that should not ship, or
33
- declares a `main`, `exports`, or `bin` path that is not in the tarball, it fails instead
34
- of publishing.
28
+ `publish-clean` packs the package once, rewrites the `package.json` inside that tarball
29
+ down to what consumers actually use, checks the result, and publishes those exact bytes.
30
+ Your working tree is never modified. If the artifact still has something in it that should
31
+ not ship, or declares a `main`, `exports`, or `bin` path that is not in the tarball, it
32
+ fails instead of publishing.
35
33
 
36
- It uses pnpm to pack and npm to publish, and cleans the manifest in between. The
37
- reasoning behind that is in [Why it works this way](#why-it-works-this-way).
34
+ It packs with pnpm and publishes with npm, and cleans the manifest in between. Both
35
+ choices are argued, with measurements, in
36
+ [why pnpm packs and npm publishes](docs/why-pnpm-and-npm.md).
38
37
 
39
38
  ## Install
40
39
 
41
- ```bash
42
- pnpm add -D @anizoptera/publish-clean
43
- ```
40
+ | Project | Install | Run |
41
+ | ------- | --------------------------------------- | ------------------------- |
42
+ | pnpm | `pnpm add -D @anizoptera/publish-clean` | `pnpm exec publish-clean` |
43
+ | Bun | `bun add -d @anizoptera/publish-clean` | `bunx publish-clean` |
44
+ | npm | `npm i -D @anizoptera/publish-clean` | `npm exec publish-clean` |
45
+ | Yarn | `yarn add -D @anizoptera/publish-clean` | `yarn publish-clean` |
46
+
47
+ **Whatever you start it with, `pnpm` prepares the package and `npm` uploads it, so both
48
+ must be on `PATH`.** A Bun, npm or Yarn project needs pnpm installed too, including in CI.
49
+
50
+ Also needs `tar` and Node.js 22.14+. Below 22.14 npm cannot mint provenance.
44
51
 
45
52
  That installs one package and nothing else. `publish-clean` has zero runtime
46
53
  dependencies: it is a single file that talks to `pnpm`, `npm` and `tar` through the
@@ -48,29 +55,20 @@ tools you already have. For something that sits on your publish path and handles
48
55
  registry credentials, that matters. A publishing tool with a dependency tree is a
49
56
  supply-chain risk of its own, and this one has no transitive code to audit.
50
57
 
51
- Needs Node.js 20+, and `pnpm`, `npm` and `tar` on `PATH`.
52
-
53
- `--provenance` also needs Node.js 22.14+, npm 11.5.1+, and a cloud CI runner. npm will
54
- not sign a publish that came from your laptop.
58
+ `--provenance` additionally needs npm 11.5.1+ and a cloud CI runner. npm will not sign a
59
+ publish that came from your laptop.
55
60
 
56
61
  ## Package managers
57
62
 
58
- Start `publish-clean` with any package manager and it still packs with `pnpm` and
59
- publishes with `npm`. So both have to be installed even if your project uses neither. The
60
- reasons are in [Why it works this way](#why-it-works-this-way).
61
-
62
- | Your project | How to run it | What to expect |
63
- | ------------ | ------------------------- | --------------------------------------------------------- |
64
- | pnpm | `pnpm exec publish-clean` | Everything works, no warning. |
65
- | npm | `npm exec publish-clean` | Works. Prints an advisory that packing goes through pnpm. |
66
- | Yarn | `yarn publish-clean` | Same as npm. |
67
- | Bun | `bunx publish-clean` | Same as npm. |
63
+ Why pnpm packs and npm publishes: pnpm is the only packer that resolves every workspace
64
+ layout correctly, and npm is the only client that can sign a release. The measurements are
65
+ in [why pnpm packs and npm publishes](docs/why-pnpm-and-npm.md).
68
66
 
69
- The advisory is a warning on stderr, not an error. Nothing behaves differently because of
70
- it and there's no flag to silence it. Worth seeing once if the rest of your pipeline runs
71
- on something other than pnpm.
67
+ Started with anything other than pnpm, it prints an advisory on stderr saying so. That is
68
+ a warning, not an error. Nothing behaves differently because of it, and there is no flag
69
+ to silence it.
72
70
 
73
- For a single package all four behave the same, since nothing in the manifest needs
71
+ For a single package every manager behaves the same, since nothing in the manifest needs
74
72
  resolving before it ships.
75
73
 
76
74
  Monorepos are where it matters. `pnpm pack` resolves `workspace:` and `catalog:` specs by
@@ -159,8 +157,8 @@ publishes its own tarball, so you get the checks and not the cleaned manifest.
159
157
  pnpm exec publish-clean --dry-run
160
158
  ```
161
159
 
162
- Prints the paths of the cleaned package and the exact tarball that would be uploaded, and
163
- leaves both on disk. Run `tar tzf` on the tarball and read the rewritten `package.json`.
160
+ Prints every file that would ship and the cleaned `package.json`, then deletes its temp
161
+ tree. Add `--tarball-out DIR` to keep the tarball itself.
164
162
 
165
163
  ### Publishing a restricted package
166
164
 
@@ -181,98 +179,43 @@ publish-clean packages/my-lib -- --access public --tag next
181
179
 
182
180
  ```mermaid
183
181
  flowchart TD
184
- A[Your package directory] -->|pnpm pack| B[Tarball - pnpm decides the file set]
185
- B --> C[Extract into a temp directory]
186
- C --> D{No leaked files?}
187
- D --> E[Clean package.json for consumers]
188
- E --> F{Every declared main/exports/bin/types path exists?}
189
- F -->|replace the package.json member| G[Same tarball, cleaned manifest]
190
- G --> H{Same files, expected manifest, still no leaks?}
191
- H --> I[npm publish that tarball]
192
- ```
193
-
194
- Any gate that fails exits non-zero and nothing is published. `--dry-run` and
195
- `--guard-only` run the whole pipeline and stop before the publish.
196
-
197
- ## Why it works this way
198
-
199
- ### Why pnpm does the packing
200
-
201
- Not for file selection. pnpm, npm and Bun pick the same files: same `files` field, same
202
- `.npmignore`, same packlist defaults. There are no file rules of this tool's own either,
203
- so that part behaves however your package manager already behaves.
204
-
205
- Workspaces are the reason. A dependency written as `"@acme/utils": "workspace:*"` means
206
- "whatever version of that package is in this repo right now". It has to become a real
207
- version range before it ships, because to a stranger installing from the registry
208
- `workspace:*` means nothing.
209
-
210
- npm never adopted the protocol. It won't even install it:
211
-
182
+ A[Your package directory] -->|pnpm pack| B[Tarball, file set chosen by pnpm]
183
+ B --> C[Copy it, rewriting only the package.json inside]
184
+ C --> D[Final tarball]
185
+ D --> E{Checks, all reading this tarball}
186
+ E -->|any fails| F[Exit non-zero, publish nothing]
187
+ E -->|all pass| G[npm publish this same tarball]
212
188
  ```
213
- npm error code EUNSUPPORTEDPROTOCOL
214
- npm error Unsupported URL Type "workspace:": workspace:*
215
- ```
216
-
217
- `npm pack` on that same package exits 0 and writes `workspace:*` straight into the
218
- tarball. It neither resolves it nor refuses it, and silently publishing something you
219
- can't install is the one behaviour a release tool can't be built on.
220
-
221
- pnpm and Bun both resolve it, and both stop loudly when they can't. Their output matches
222
- down to `workspace:^` and `workspace:~` in `peerDependencies` and `optionalDependencies`,
223
- and `catalog:` entries too. On correctness there is nothing to choose between them.
224
189
 
225
- ### Why pnpm rather than Bun
190
+ The checks are listed under [What it checks](#what-it-checks). The point of the shape is
191
+ that they all read the tarball that gets uploaded, so what passed the checks and what
192
+ reached the registry are the same bytes, not two things that ought to match.
226
193
 
227
- They resolve from different places, and that decides it.
194
+ `--dry-run` and `--guard-only` run the whole pipeline and stop before the publish.
228
195
 
229
- pnpm looks for the dependency in the packing package's own `node_modules` and resolves it
230
- from there. It never asks who put it there, so a Bun workspace, which gives every package
231
- its own `node_modules`, packs as readily as pnpm's own. Yarn hoists to the root instead
232
- and needs the one-time setup above.
233
-
234
- Bun reads `bun.lock`. It resolves the workspaces Bun installed and refuses the others:
235
-
236
- ```
237
- error: Failed to resolve workspace version for "@acme/utils" in `dependencies`.
238
- Run `bun install` and try again.
239
- ```
240
-
241
- That message is accurate and useless, because in a pnpm repo `bun install` is not
242
- something you want to be told to run. A tool that executes in other people's
243
- repositories has to cope with the repository it finds, so it packs with the one that
244
- reads all of them.
245
-
246
- There's a correctness gap too, and it's the quiet kind. An aliased workspace dependency,
247
- `"utils": "workspace:@acme/utils@*"`, has to come out the other side as an npm alias.
248
- pnpm writes `"npm:@acme/utils@1.2.3"`. Bun 1.3.14 writes `"@acme/utils@*"`: the `npm:`
249
- prefix is dropped and the range was never resolved. npm won't take it.
250
-
251
- ```
252
- npm error code EINVALIDTAGNAME
253
- npm error Invalid tag name "is-odd@3.0.1" of package "aliased@is-odd@3.0.1"
254
- ```
196
+ ## Why it works this way
255
197
 
256
- `bun pm pack` exits 0 either way, so nothing tells you until someone tries to install the
257
- release.
198
+ ### Why pnpm packs, and npm publishes
258
199
 
259
- One silent way to publish a broken manifest is one too many for the step you can't take
260
- back.
200
+ pnpm because of workspaces. A dependency written `"@acme/utils": "workspace:*"` has to
201
+ become a real version range before it ships, and pnpm is the only packer that does that
202
+ for every layout it might find, including a Bun one. npm writes `workspace:*` into the
203
+ tarball unchanged and exits 0, publishing a package nobody can install. Bun resolves only
204
+ what Bun installed, and quietly mangles an aliased workspace dependency.
261
205
 
262
- pnpm also applies `publishConfig` field overrides. If your manifest points `main`, `types`
263
- and `exports` at source for local development and overrides them to `dist` for publishing,
264
- pnpm swaps them on the way out and drops `publishConfig` itself. npm and Bun both ignore
265
- those overrides and publish the development paths. That one is a pnpm extension rather
266
- than a bug in the other two, but the effect on the release is the same.
206
+ npm because of provenance. The signed attestation behind the "Built and signed on GitHub
207
+ Actions" badge is minted by the npm CLI talking to Sigstore, and trusted publishing, which
208
+ removes the long-lived token entirely, is npm's own exchange with the registry. No other
209
+ client does either one. `npm publish` also takes a tarball directly, which is what the
210
+ packing step already produced.
267
211
 
268
- Everything else we compared came out identical: file modes including the executable bit on
269
- `bin`, negated `files` patterns, dropped symlinks, prerelease versions, pinned
270
- `workspace:1.2.3` ranges, named catalogs, and refusing a catalog entry that doesn't exist.
212
+ The measurements behind both choices, and the one thing packing with pnpm costs you, are
213
+ in [why pnpm packs and npm publishes](docs/why-pnpm-and-npm.md).
271
214
 
272
215
  ### Why the manifest is cleaned on a copy
273
216
 
274
- The tarball gets extracted into a temp directory and rewritten there. Your working tree
275
- is never touched.
217
+ The manifest is read out of the packed tarball and written back into a copy of it, in a
218
+ temp directory. Your working tree is never touched.
276
219
 
277
220
  The obvious alternative is what a lot of hand-rolled release scripts do: edit
278
221
  `package.json`, publish, edit it back. That's fine until something dies in the middle,
@@ -294,63 +237,51 @@ then has nothing left to select with, falls back to your `.gitignore`/`.npmignor
294
237
  exclusion, and quietly drops files the first pack included. A package shipping a
295
238
  `.gitignore` that excludes any other shipped file loses it.
296
239
 
297
- Editing avoids the whole question. Only the `package/package.json` member is replaced;
298
- every other entry is copied without being decoded, so the file set stays exactly what pnpm
299
- chose and entry shapes this tool does not model (pax headers for long paths, prefix
300
- splitting) pass through untouched. It also keeps pnpm's normalised metadata — owner `0:0`,
301
- a fixed timestamp, mode 644 — which a plain `tar` invocation would replace with the build
302
- machine's own user and group names.
240
+ Editing avoids the question. Only the `package/package.json` member is replaced. Every
241
+ other entry is copied without being decoded, so the file set stays exactly what pnpm chose,
242
+ and entry shapes this tool does not model (pax headers for long paths, prefix splitting)
243
+ pass through untouched. It also keeps pnpm's normalised metadata: owner `0:0`, a fixed
244
+ timestamp, mode 644. A plain `tar` invocation would replace those with whatever the build
245
+ machine happens to have.
303
246
 
304
247
  Lifecycle scripts run once, at the first pack. `pnpm pack` runs your `prepare` and
305
248
  `prepack`, which is how build output reaches the package at all. Nothing runs afterwards:
306
249
  npm skips `prepack`/`postpack` when it is handed a tarball rather than a directory, so
307
250
  nothing can alter the artifact after it was checked.
308
251
 
309
- ### Why npm does the publishing
310
-
311
- Provenance is an npm feature. The signed attestation behind the "Built and signed on
312
- GitHub Actions" badge is minted by the npm CLI talking to Sigstore, and trusted
313
- publishing, which removes the long-lived token entirely, is npm's own OIDC exchange with
314
- the registry.
315
-
316
- No other client mints it. `bun publish` offers `--access`, `--tag`, `--otp` and
317
- `--auth-type`, and nothing at all for provenance or attestation, so publishing through it
318
- would cost both the badge and the tokenless path. That trade isn't on the table here:
319
- verifiable provenance is why this package exists.
320
-
321
- `npm publish` also takes a tarball directly, which is exactly what the previous step
322
- produced.
323
-
324
252
  ## What it checks
325
253
 
326
- `publish-clean` refuses to continue when:
327
-
328
- - the package is `private: true`
329
- - the source package has uncommitted changes, unless disabled
330
- - the package has no non-empty `files` array, unless disabled
331
- - the tarball contains critical leaks like `.env`, `.npmrc`, `.git`,
332
- `node_modules`, or private-key files
333
- - dependency specs still use `catalog:`, `workspace:`, `link:`, or `portal:`
334
- - declared export, type, import, browser, bin, or side-effect paths are missing
335
- from the cleaned package
336
- - the final npm tarball drops files that were present in the cleaned package
337
- - trusted GitHub publication uses `--provenance` but package repository metadata
338
- does not match the workflow repository
339
-
340
- It warns, without stopping, when it was started by npm, Yarn or Bun rather than pnpm.
341
- The packing still goes through pnpm, but the warning is there because the rest of your
342
- release probably should too.
343
-
344
- Leak checks cannot be turned off by any flag or config key.
254
+ `publish-clean` stops, and publishes nothing, when:
255
+
256
+ - the package is marked `private: true`
257
+ - the working tree has uncommitted changes (`--no-git-checks` to allow it)
258
+ - the package has no non-empty `files` array (`--skip-file-check` to allow it)
259
+ - the tarball holds something that should never ship: a `.env`, an `.npmrc`, `.git`,
260
+ `node_modules`, or a private key. This one has no off switch, by any flag or config key
261
+ - a dependency is still written as `catalog:`, `workspace:`, `link:` or `portal:`, which
262
+ nobody outside your repo can install
263
+ - the manifest points `exports`, `types`, `main`, `browser`, `bin` or `sideEffects` at a
264
+ path that is not in the tarball
265
+ - rewriting the manifest changed anything else in the tarball
266
+ - you asked for `--provenance` from GitHub Actions, but the `repository` in your manifest
267
+ is not the repository the workflow is running in
268
+
269
+ It warns, without stopping, when it was started by npm, Yarn or Bun rather than pnpm. The
270
+ packing still goes through pnpm, but the warning is there because the rest of your release
271
+ probably should too.
345
272
 
346
273
  ## What the cleaned manifest keeps
347
274
 
348
275
  Everything a consumer or a registry reads survives: `name`, `version`, `license`,
349
276
  `dependencies`, `peerDependencies` and their meta, `exports`, `main`, `module`, `types`,
350
- `bin`, `files`, `engines`, `os`, `cpu`, `sideEffects`, `publishConfig`, and the rest of
351
- the public surface.
277
+ `bin`, `engines`, `os`, `cpu`, `sideEffects`, `publishConfig`, and the rest of the public
278
+ surface.
279
+
280
+ `files` goes, because it is spent: it told the packer what to include, the tarball already
281
+ exists, nothing re-selects afterwards, and an install extracts every entry unfiltered. npm
282
+ agrees — its registry drops the field from the metadata it serves.
352
283
 
353
- What goes: `devDependencies`, `workspaces`, `pnpm`, `packageManager`, `overrides`,
284
+ What else goes: `devDependencies`, `workspaces`, `pnpm`, `packageManager`, `overrides`,
354
285
  `resolutions`, and the config blocks belonging to test runners, linters, formatters,
355
286
  coverage tools, build systems and release tools. Scripts go too, apart from the install
356
287
  lifecycle ones a consumer actually runs: `preinstall`, `install`, `postinstall`,
@@ -374,34 +305,14 @@ hear about it from a stranger's broken build rather than from your own release.
374
305
  Add your own with `devFields`. Better still, run `--dry-run` and read the manifest that
375
306
  would ship instead of trusting this list.
376
307
 
377
- ## Options
308
+ ## Options and config
378
309
 
379
310
  ```bash
380
311
  publish-clean [options] [package-dir] [-- npm-publish-args]
381
312
  ```
382
313
 
383
- - `--dry-run`: pack, check, clean, and print the cleaned package and final
384
- tarball paths.
385
- - `--guard-only`: run the full pack, clean, and final-tarball guard without
386
- publishing.
387
- - `--registry URL`: set `publishConfig.registry` on the cleaned manifest.
388
- - `--skip-file-check`: skip suspicious-file checks and the required `files`
389
- array check. Critical leak checks still run.
390
- - `--no-git-checks`: skip the source git cleanliness check.
391
- - `--tarball-out DIR`: copy the final tarball into `DIR` before publishing. The bytes
392
- kept are the ones that were published, so a release pipeline can attach them to a
393
- GitHub Release or sign them with build-provenance attestation.
394
- - `-h`, `--help`: print usage.
395
-
396
- Arguments after `--` go to `npm publish`, which publishes the final cleaned
397
- tarball.
398
-
399
- Pass the npm dist-tag explicitly. For normal public releases, use
400
- `--tag latest`.
401
-
402
- ## Package config
403
-
404
- Stable project defaults can live in `package.json`:
314
+ Most settings can be a flag or a `package.json` key. Flags win, so keep per-release
315
+ choices like dist-tags on the command line and stable project policy in the manifest:
405
316
 
406
317
  ```json
407
318
  {
@@ -415,35 +326,49 @@ Stable project defaults can live in `package.json`:
415
326
  }
416
327
  ```
417
328
 
418
- `registry` is written as `publishConfig.registry` on the cleaned manifest and passed to
419
- `npm publish`, so the package cannot end up on whatever registry the machine happens to
420
- be pointed at.
329
+ | Flag | `package.json` | What it does |
330
+ | ------------------- | --------------- | ------------------------------------------------------------------------------------------ |
331
+ | `--dry-run` | - | Run everything up to the publish, then print the file list and the cleaned `package.json`. |
332
+ | `--guard-only` | - | Run everything up to the publish and exit, printing nothing. |
333
+ | `--tarball-out DIR` | - | Copy the final tarball into `DIR` before publishing. |
334
+ | `--registry URL` | `registry` | Set `publishConfig.registry` on the cleaned manifest, and publish to it. |
335
+ | `--skip-file-check` | `skipFileCheck` | Drop the suspicious-file check and the required `files` array. |
336
+ | `--no-git-checks` | `noGitChecks` | Allow publishing from a dirty working tree. |
337
+ | - | `devFields` | Extra manifest fields to strip. |
338
+ | - | `keepFields` | Fields that belong in the published package, so stop reporting them. |
339
+ | `-h`, `--help` | - | Print usage. |
340
+
341
+ Arguments after `--` go to `npm publish`. Pass the dist-tag explicitly: `--tag latest` for
342
+ a normal public release.
343
+
344
+ A few of these deserve a sentence more.
421
345
 
422
- `skipFileCheck` drops the suspicious-file check and the requirement for a `files` array.
423
- Leak checks keep running; those cannot be turned off.
346
+ `--tarball-out` keeps the bytes that were published, so a release pipeline can attach them
347
+ to a GitHub Release or sign them with build-provenance attestation. The copy happens in
348
+ every mode, before the publish, so you get the validated artifact even if the upload fails.
424
349
 
425
- `noGitChecks` allows publishing from a dirty working tree. You need it when you publish
426
- from a build directory or a checkout that is not a git repository.
350
+ `registry` pins where the package goes, so it cannot end up on whatever registry the
351
+ machine happens to be pointed at.
427
352
 
428
- `devFields` lists extra manifest fields to strip, for tooling this package has not heard
429
- of. Fields that npm or your consumers actually use, like `exports`, `bin`, `engines` and
430
- the dependency maps, are rejected here, so a typo cannot quietly break your package.
353
+ `skipFileCheck` does not touch the leak checks.
431
354
 
432
- `keepFields` is the other answer to the same report: the field belongs in the published
433
- package, stop mentioning it. A VS Code extension needs `contributes` and `publisher` in
434
- the artifact to work, and no generic publishing tool is ever going to know that.
355
+ `noGitChecks` is what you need when you publish from a build directory, or from a checkout
356
+ that is not a git repository at all.
435
357
 
436
- Command-line flags override this block. Keep per-release choices such as dist-tags on the
437
- command line.
358
+ `devFields` refuses fields that npm or your consumers actually read, like `exports`, `bin`,
359
+ `engines` and the dependency maps, so a typo cannot quietly break your package.
360
+
361
+ `keepFields` answers the unrecognised-field report the other way: the field belongs in the
362
+ published package, stop mentioning it. A VS Code extension needs `contributes` and
363
+ `publisher` in the artifact to work, and no generic publishing tool is ever going to know
364
+ that.
438
365
 
439
366
  ## What it does not do
440
367
 
441
368
  It isn't a release manager. It won't pick your version number, write a changelog, tag
442
- anything, push a commit, create a GitHub release, or set up trusted publishing for you.
443
- It also doesn't check that your entry points resolve correctly for consumers, which is
444
- what `publint` and `@arethetypeswrong/cli` are for.
445
-
446
- Pick a release manager and a validator to go with it. The next section covers which.
369
+ anything, push a commit, create a GitHub release, or set up trusted publishing for you. It
370
+ also doesn't check that your entry points resolve correctly for consumers. Pair it with a
371
+ release manager and a validator; the next section names them.
447
372
 
448
373
  It can't publish a package that uses `bundleDependencies`. pnpm links dependencies rather
449
374
  than copying them, so it has nothing to bundle and refuses:
@@ -454,9 +379,7 @@ Add "nodeLinker: hoisted" to pnpm-workspace.yaml or delete bundleDependencies
454
379
 
455
380
  Doing what it says makes the package publishable again. This is the one thing you give up
456
381
  by packing with pnpm, and it's a fair trade: `bundleDependencies` is rare, and the failure
457
- is loud and tells you the fix. npm and Bun bundle correctly for a standalone package, and
458
- neither bundles anything for a package inside a workspace, because the dependency hoists
459
- to the workspace root where the package can't see it.
382
+ is loud and tells you the fix.
460
383
 
461
384
  ## How it compares
462
385
 
package/dist/cli.js CHANGED
@@ -1,21 +1,182 @@
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
7
  import { parseArgs } from "node:util";
8
8
  import { gunzipSync, gzipSync } from "node:zlib";
9
- //#region src/rules.ts
9
+ //#region src/error.ts
10
10
  /**
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.
11
+ * The one failure type every module here throws, so `cli.ts` can tell a refusal this tool
12
+ * decided on — which is already phrased for the operator and needs no decoration — from a
13
+ * crash, whose message would otherwise reach them raw.
14
+ */
15
+ var PublishCleanError = class extends Error {
16
+ constructor(message, options) {
17
+ super(message, options), this.name = "PublishCleanError";
18
+ }
19
+ };
20
+ //#endregion
21
+ //#region src/json.ts
22
+ function isObject(value) {
23
+ return typeof value == "object" && !!value && !Array.isArray(value);
24
+ }
25
+ /**
26
+ * The form written into the published tarball: npm's own two-space indentation with a trailing
27
+ * newline, and key order left exactly as the packer emitted it. Preserving order is what makes
28
+ * the artifact byte-reproducible across runs, since cleaning only ever deletes keys.
29
+ */
30
+ function stringifyJson(value) {
31
+ return `${JSON.stringify(value, null, 2)}\n`;
32
+ }
33
+ /**
34
+ * The form used only to compare two manifests for equality. Key order carries no meaning to a
35
+ * consumer, so comparing the written form would report a difference where none exists.
36
+ */
37
+ function stableJson(value) {
38
+ return JSON.stringify(stableValue(value));
39
+ }
40
+ function stableValue(value) {
41
+ 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;
42
+ }
43
+ //#endregion
44
+ //#region src/artifact.ts
45
+ /**
46
+ * What the published tarball may carry, and what it must. Every rule here judges a file list —
47
+ * the paths `tar` reads out of the archive, with the `package/` prefix already stripped — never
48
+ * a directory on disk, because that list is what a consumer's installer unpacks and it needs no
49
+ * filesystem to exist.
50
+ *
51
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
52
+ * argv here. `cli.ts` owns the effects.
53
+ */
54
+ /**
55
+ * Content that must never reach a registry. `^` means the package root.
56
+ *
57
+ * Case-insensitive throughout, because the filesystems most packages are built on are
58
+ * too. On macOS and Windows `Server.PEM` and `server.pem` are the same file, so a
59
+ * case-sensitive guard refuses one and publishes the other, which is worse than no guard:
60
+ * it reads as coverage.
61
+ *
62
+ * Private keys are matched by extension and, separately, by exact filename. SSH keys carry
63
+ * no extension at all, and `id_rsa` is the most common private-key filename there is. The
64
+ * exact-name form deliberately does not match `id_rsa.pub`, which is public by design and
65
+ * legitimate to ship.
66
+ */
67
+ const CRITICAL_PATTERNS = [
68
+ /(?:^|\/)node_modules(?:\/|$)/i,
69
+ /(?:^|\/)\.git(?:\/|$)/i,
70
+ /(?:^|\/)\.env(?:\.|$)/i,
71
+ /(?:^|\/)\.npmrc$/i,
72
+ /\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
73
+ /(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
74
+ ], SUSPICIOUS_PATTERNS = [
75
+ /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
76
+ /(?:^|\/)\.github(?:\/|$)/,
77
+ /(?:^|\/)tsconfig[^/]*\.json$/,
78
+ /(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
79
+ /\.(?:test|spec)\.[cm]?[jt]sx?$/
80
+ ];
81
+ function validatePackedFiles(files, skipSuspicious) {
82
+ let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
83
+ if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
84
+ if (skipSuspicious) return;
85
+ let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
86
+ if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
87
+ }
88
+ /**
89
+ * Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
90
+ *
91
+ * Replacing a member is supposed to change one member, and the rewriter copies every other
92
+ * entry as opaque bytes — so this can only fail through a defect in that code, which is exactly
93
+ * why it is worth asserting on the step that cannot be taken back. Nothing else would notice a
94
+ * dropped file: the leak checks only ask what is present, and a package missing a file installs
95
+ * fine and then fails at import, on a version the registry keeps forever.
96
+ *
97
+ * Both lists are read out of the archives by `tar`, an instrument that cannot share a mistake
98
+ * with the walk being checked.
99
+ */
100
+ function assertSameEntries(packed, published) {
101
+ 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}`)];
102
+ if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
103
+ }
104
+ /**
105
+ * Walks a manifest value of any shape and collects the strings that name a file inside
106
+ * the package, so the caller can prove each one exists in the tarball.
107
+ *
108
+ * `mode` exists because the two families of path-bearing fields disagree about what a
109
+ * bare string means, and reading one by the other's rules produces wrong answers in both
110
+ * directions:
111
+ *
112
+ * - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
113
+ * where every string is a path into this package.
114
+ * - `"relative-only"` for `exports`, `imports`, `sideEffects` and the object form of
115
+ * `browser`, where a string may just as well be an external package name, a condition
116
+ * target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
117
+ * rest would report a missing file for something that was never a file.
118
+ *
119
+ * Booleans are skipped rather than ignored by accident: `sideEffects: false` and
120
+ * `exports` condition values legitimately hold them.
121
+ */
122
+ function collectDeclaredPaths(value, out, mode) {
123
+ if (typeof value == "string") {
124
+ (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
125
+ return;
126
+ }
127
+ if (typeof value != "boolean") {
128
+ if (Array.isArray(value)) {
129
+ for (let item of value) collectDeclaredPaths(item, out, mode);
130
+ return;
131
+ }
132
+ if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out, mode);
133
+ }
134
+ }
135
+ function normalizeDeclaredPath(declared) {
136
+ let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
137
+ if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
138
+ let normalized = path.posix.normalize(withoutDot);
139
+ return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
140
+ }
141
+ /**
142
+ * Refuses a manifest whose declared entry points are not in the tarball.
15
143
  *
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.
144
+ * A path containing `*` is skipped: `exports` subpath patterns and `typesVersions` globs stand
145
+ * for a set of files, and resolving them here would mean reimplementing npm's own matcher to
146
+ * answer a question npm answers at install time.
147
+ */
148
+ function assertDeclaredFiles(pkg, published) {
149
+ let declared = [];
150
+ for (let field of [
151
+ "main",
152
+ "module",
153
+ "types",
154
+ "typings",
155
+ "bin"
156
+ ]) collectDeclaredPaths(pkg[field], declared, "every-string");
157
+ typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, declared, "every-string") : collectDeclaredPaths(pkg.browser, declared, "relative-only");
158
+ for (let field of [
159
+ "exports",
160
+ "imports",
161
+ "sideEffects"
162
+ ]) collectDeclaredPaths(pkg[field], declared, "relative-only");
163
+ collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
164
+ let resolved = declared.map((declaredPath) => ({
165
+ path: declaredPath,
166
+ normalized: normalizeDeclaredPath(declaredPath)
167
+ })), invalid = resolved.filter((item) => item.normalized === null);
168
+ if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.path).join("\n")}`);
169
+ let shipped = new Set(published), missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
170
+ if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
171
+ }
172
+ //#endregion
173
+ //#region src/manifest.ts
174
+ /**
175
+ * What the published `package.json` carries: which fields survive cleaning, which are refused,
176
+ * and what the author may add to either list.
177
+ *
178
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
179
+ * argv here — so every rule is one input to one output. `cli.ts` owns the effects.
19
180
  */
20
181
  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
182
  "preinstall",
@@ -83,7 +244,37 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
83
244
  "styleModule",
84
245
  "svelte",
85
246
  "unpkg"
86
- ]);
247
+ ]), 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.";
248
+ function stripManifest(pkg, extraDevFields) {
249
+ let stripped = { ...pkg };
250
+ for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
251
+ let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
252
+ if (scripts) {
253
+ let kept = {};
254
+ for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
255
+ Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
256
+ }
257
+ return stripped;
258
+ }
259
+ /**
260
+ * Pins the published manifest to a registry, when one was chosen.
261
+ *
262
+ * Written into `publishConfig` rather than passed only on the command line, because that is
263
+ * where npm looks when someone later republishes the same tarball by hand — the artifact then
264
+ * carries its own destination instead of depending on whoever runs the command. Any other
265
+ * `publishConfig` keys the author set are consumer-facing and survive untouched.
266
+ *
267
+ * Returns the manifest unchanged when no registry was chosen, so the caller has no branch and
268
+ * cannot forget one.
269
+ */
270
+ function withRegistry(pkg, registry) {
271
+ if (registry === null) return pkg;
272
+ let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
273
+ return publishConfig.registry = registry, {
274
+ ...pkg,
275
+ publishConfig
276
+ };
277
+ }
87
278
  /**
88
279
  * Refuses a published manifest that lost a field the source declared and consumers read.
89
280
  *
@@ -93,8 +284,8 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
93
284
  * `exports` makes the package unimportable, and neither leaves any trace in the artifact
94
285
  * to notice later. The registry keeps the version forever either way.
95
286
  *
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.
287
+ * Read out of the published tarball rather than from the cleaned value in memory, so a loss
288
+ * introduced while rewriting the archive is caught as well as one introduced by stripping.
98
289
  *
99
290
  * `devFields` entries are exempt: removing those was the request. `scripts` is exempt
100
291
  * because it is rewritten rather than removed, down to the install lifecycle hooks a
@@ -129,134 +320,13 @@ function unrecognizedFieldsReport(pkg, kept) {
129
320
  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
321
  }
131
322
  /**
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.
139
- *
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.
144
- */
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;
188
- }
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";
193
- }
194
- function assertPublicPackage(pkg) {
195
- if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
196
- }
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;
231
- }
232
- /**
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.
242
- */
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
- };
250
- }
251
- /**
252
323
  * Refuses a manifest that still carries a spec only a workspace can resolve. Published
253
324
  * with one, the package is uninstallable for everyone, and the version cannot be taken
254
325
  * back.
255
326
  *
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.
327
+ * The caller passes an already-stripped manifest, so the dev-only members of DEP_FIELDS are
328
+ * absent by construction. They are still checked, because a guard whose correctness depends on
329
+ * the order it happens to be called in fails silently the day someone reorders it.
260
330
  */
261
331
  function assertNoMonorepoProtocols(pkg) {
262
332
  let failures = [];
@@ -266,6 +336,16 @@ function assertNoMonorepoProtocols(pkg) {
266
336
  }
267
337
  if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
268
338
  }
339
+ function assertPublicPackage(pkg) {
340
+ if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
341
+ }
342
+ function assertFilesField(pkg, skip) {
343
+ if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
344
+ }
345
+ function packageConfig(pkg) {
346
+ let config = pkg["publish-clean"];
347
+ return isObject(config) ? config : {};
348
+ }
269
349
  function customDevFields(config) {
270
350
  if (!Array.isArray(config.devFields)) return [];
271
351
  let fields = config.devFields.filter((field) => typeof field == "string"), unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
@@ -286,57 +366,6 @@ function customDevFields(config) {
286
366
  function keptFields(config) {
287
367
  return Array.isArray(config.keepFields) ? config.keepFields.filter((field) => typeof field == "string") : [];
288
368
  }
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 : {};
339
- }
340
369
  //#endregion
341
370
  //#region src/tarball.ts
342
371
  /**
@@ -399,6 +428,7 @@ function replaceTarballManifest(archive, manifest) {
399
428
  break;
400
429
  }
401
430
  let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512), type = field(header, 156, 1);
431
+ if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
402
432
  if (PAX_TYPES.has(type) && assertNoManifestOverride(tar.subarray(offset + 512, offset + 512 + size)), name === MANIFEST_PATH) {
403
433
  if (replaced) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
404
434
  if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
@@ -411,6 +441,68 @@ function replaceTarballManifest(archive, manifest) {
411
441
  return gzipSync(Buffer.concat(parts));
412
442
  }
413
443
  //#endregion
444
+ //#region src/trusted-publish.ts
445
+ /**
446
+ * Who npm will believe is publishing, and what the toolchain must be for it to sign anything.
447
+ *
448
+ * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
449
+ * argv here. `cli.ts` owns the effects.
450
+ */
451
+ /**
452
+ * The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
453
+ * message so the version a reader is told to install is the version the comparison made.
454
+ *
455
+ * The Node floor is also the package's declared `engines.node`, since a publisher that cannot
456
+ * produce provenance cannot do this tool's job; a test asserts the two agree.
457
+ */
458
+ const MIN_TRUSTED_NPM_VERSION = [
459
+ 11,
460
+ 5,
461
+ 1
462
+ ], MIN_TRUSTED_NODE_VERSION = [
463
+ 22,
464
+ 14,
465
+ 0
466
+ ];
467
+ function isAtLeast(actual, minimum) {
468
+ for (let index of [
469
+ 0,
470
+ 1,
471
+ 2
472
+ ]) {
473
+ if (actual[index] > minimum[index]) return !0;
474
+ if (actual[index] < minimum[index]) return !1;
475
+ }
476
+ return !0;
477
+ }
478
+ function wantsTrustedPublish(pkg, publishArgs, env) {
479
+ return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
480
+ }
481
+ function repositoryUrl(pkg) {
482
+ return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
483
+ }
484
+ function githubRepositorySlug(url) {
485
+ let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
486
+ if (withoutGitPrefix.startsWith("git@github.com:")) {
487
+ let slug = withoutGitPrefix.slice(15);
488
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
489
+ }
490
+ try {
491
+ let parsed = new URL(withoutGitPrefix);
492
+ if (parsed.hostname !== "github.com") return null;
493
+ let slug = parsed.pathname.replace(/^\/+/, "");
494
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
495
+ } catch {
496
+ return null;
497
+ }
498
+ }
499
+ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
500
+ if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
501
+ let repoUrl = repositoryUrl(pkg);
502
+ if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
503
+ if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
504
+ }
505
+ //#endregion
414
506
  //#region src/cli.ts
415
507
  const TOOL_PROBE_TIMEOUT_MS = 1e4;
416
508
  function readJson(file) {
@@ -525,11 +617,7 @@ function assertTrustedPublishingRuntime(pkg, publishArgs) {
525
617
  node[0] ?? 0,
526
618
  node[1] ?? 0,
527
619
  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}.`);
620
+ ], 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
621
  }
534
622
  function warnIfNonPnpmLifecycle() {
535
623
  let userAgent = process.env.npm_config_user_agent;
@@ -548,17 +636,16 @@ function assertCleanGit(packageDir, skip) {
548
636
  throw error instanceof PublishCleanError ? error : new PublishCleanError("Unable to verify source git status.", { cause: error });
549
637
  }
550
638
  }
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);
560
- }
561
- }
639
+ /**
640
+ * The file list every content guard judges, read out of the archive by `tar` rather than from
641
+ * an extracted copy: this is the same enumeration a consumer's installer sees, and it needs no
642
+ * filesystem to exist.
643
+ *
644
+ * `tar tzf` prints one name per line, so a filename containing a newline would arrive as two
645
+ * entries. That is safe in the only direction that matters, because every guard here fails
646
+ * closed: splitting a name can only add entries to a leak scan that refuses on any match, and a
647
+ * declared path whose name was split is then absent and refused as missing.
648
+ */
562
649
  function listTarballFiles(tarball, cwd) {
563
650
  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();
564
651
  }
@@ -571,104 +658,64 @@ function readTarballJson(tarball, file, cwd) {
571
658
  `package/${file}`
572
659
  ], cwd));
573
660
  } catch (cause) {
574
- throw new PublishCleanError(`Unable to read JSON from final npm tarball: ${file}`, { cause });
661
+ throw new PublishCleanError(`Unable to read JSON from ${path.basename(tarball)}: ${file}`, { cause });
575
662
  }
576
- if (!isObject(parsed)) throw new PublishCleanError(`Final npm tarball ${file} must contain a JSON object.`);
663
+ if (!isObject(parsed)) throw new PublishCleanError(`${file} in ${path.basename(tarball)} must contain a JSON object.`);
577
664
  return parsed;
578
665
  }
579
666
  /**
580
- * Locates the tarball a packer just produced by reading its destination directory.
667
+ * Locates the tarball `pnpm pack` just produced by reading its destination directory.
581
668
  *
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.
669
+ * The pack targets a directory this process created and owns exclusively, so the result is
670
+ * discoverable without interpreting the packer's output at all. That matters because `pack`
671
+ * runs the package's `prepare`/`prepack` lifecycle scripts and forwards their stdout: any
672
+ * build tool that logs — most of them — lands ahead of a `--json` payload and breaks a parse
673
+ * of that stream. Reading the directory is immune to whatever a foreign package's scripts
674
+ * choose to print.
588
675
  *
589
676
  * Exactly one tarball is the invariant, not a convenience: more than one means the
590
677
  * destination was not exclusive and the wrong artifact could be published.
591
678
  */
592
- async function soleTarball(packRoot, packer) {
679
+ async function soleTarball(packRoot) {
593
680
  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.`);
681
+ if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
595
682
  return path.join(packRoot, tarball);
596
683
  }
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
684
  async function packAndClean(packageDir, opts) {
629
685
  requireTool("pnpm"), requireTool("npm"), requireTool("tar"), warnIfNonPnpmLifecycle();
630
686
  let sourcePkg = readJson(path.join(packageDir, "package.json"));
631
687
  !opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
632
688
  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);
633
689
  assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
634
- let root = await mkdtemp(path.join(tmpdir(), "publish-clean-")), keepRoot = !1;
690
+ let root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
635
691
  try {
636
692
  run("pnpm", [
637
693
  "pack",
638
694
  "--pack-destination",
639
695
  root
640
696
  ], 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));
697
+ let tarball = await soleTarball(root), cleanedPkg = withRegistry(stripManifest(readTarballJson(tarball, "package.json", root), extraDevFields), registry), unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
698
+ unrecognized && console.warn(unrecognized);
656
699
  let publishRoot = path.join(root, "publish");
657
700
  await mkdir(publishRoot);
658
701
  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.");
702
+ await writeFile(finalTarball, replaceTarballManifest(await readFile(tarball), stringifyJson(cleanedPkg)));
703
+ let finalFiles = listTarballFiles(finalTarball, root);
704
+ assertSameEntries(listTarballFiles(tarball, root), finalFiles), validatePackedFiles(finalFiles, skipFileCheck), assertDeclaredFiles(cleanedPkg, finalFiles);
705
+ let shippedPkg = readTarballJson(finalTarball, "package.json", root);
706
+ if (assertNoMonorepoProtocols(shippedPkg), assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields), stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
662
707
  if (opts.tarballOut !== null) {
663
708
  await mkdir(opts.tarballOut, { recursive: !0 });
664
709
  let kept = path.join(opts.tarballOut, path.basename(finalTarball));
665
710
  await copyFile(finalTarball, kept), console.log(`Final tarball kept at: ${kept}`);
666
711
  }
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}`);
712
+ if (opts.dryRun) {
713
+ console.log(`[dry-run] ${finalFiles.length} files:`);
714
+ for (let file of finalFiles) console.log(` ${file}`);
715
+ console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
670
716
  return;
671
717
  }
718
+ if (opts.guardOnly) return;
672
719
  assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv()), runAttached("npm", registry ? [
673
720
  "publish",
674
721
  finalTarball,
@@ -679,9 +726,9 @@ async function packAndClean(packageDir, opts) {
679
726
  "publish",
680
727
  finalTarball,
681
728
  ...opts.publishArgs
682
- ], extracted);
729
+ ], packageDir);
683
730
  } finally {
684
- keepRoot || await rm(root, {
731
+ await rm(root, {
685
732
  recursive: !0,
686
733
  force: !0
687
734
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@anizoptera/publish-clean",
3
- "version": "0.4.0",
4
- "description": "Publish npm packages with a consumer-only package.json. Refuses to ship a .env, a private key, or an unresolved workspace dependency.",
3
+ "version": "0.5.0",
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",
7
7
  "cleanup",
@@ -42,6 +42,6 @@
42
42
  "provenance": true
43
43
  },
44
44
  "engines": {
45
- "node": ">=20"
45
+ "node": ">=22.14.0"
46
46
  }
47
47
  }