@anizoptera/publish-clean 0.8.0 → 0.9.1

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 +142 -195
  2. package/dist/cli.js +25 -7
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,8 +1,7 @@
1
1
  # @anizoptera/publish-clean
2
2
 
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.
3
+ Publish npm packages with a clean `package.json` and checks for unwanted files,
4
+ unresolved workspace dependencies and missing entry points.
6
5
 
7
6
  [![npm version](https://img.shields.io/npm/v/@anizoptera/publish-clean?label=npm)](https://www.npmjs.com/package/@anizoptera/publish-clean)
8
7
  [![Signed provenance](https://img.shields.io/badge/provenance-signed-2ea44f?logo=npm&logoColor=white)](https://www.npmjs.com/package/@anizoptera/publish-clean#provenance)
@@ -11,29 +10,23 @@ dependencies. No deps, one JS file.
11
10
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
12
11
  [![License](https://img.shields.io/github/license/Anizoptera/publish-clean)](LICENSE)
13
12
 
14
- When you run `npm publish`, two things ship that you probably did not mean to ship.
13
+ `publish-clean` removes `devDependencies`, workspace settings and tool config from the
14
+ published manifest. Consumer fields and lifecycle helpers stay. Unknown fields are
15
+ reported for review and kept unless you choose to remove them.
15
16
 
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.
19
- npm sends all of it, unchanged, to everyone who installs your package. In a pnpm
20
- workspace it can also send `workspace:*` and `catalog:` specs that were never resolved,
21
- and those break the install for every consumer.
17
+ It packs once with pnpm, cleans the manifest inside the tarball, checks that file, then
18
+ uploads it with npm. The checked bytes are the published bytes. Cleaning leaves your
19
+ source files alone; your pack hooks still run and can change them.
22
20
 
23
- The second is files. A `.env`, an `.npmrc` with a token in it, a stray `.pem`, your
24
- tests, `.github/`, a lockfile. You do not see the tarball before it goes out, and once a
25
- version is published you cannot edit it. Unpublishing only works for a short window and
26
- under conditions npm decides.
21
+ Preview, then publish:
27
22
 
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
- Cleaning does not edit your working tree; your pack lifecycle scripts can. 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.
23
+ ```sh
24
+ pnpm exec publish-clean --dry-run
25
+ pnpm exec publish-clean -- --access public --tag latest --provenance
26
+ ```
33
27
 
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).
28
+ Requires Node.js 22+, pnpm and npm. The CLI has no runtime dependencies. The publish
29
+ command above needs [CI provenance setup](#publishing-a-public-package-from-ci).
37
30
 
38
31
  ## Install
39
32
 
@@ -44,22 +37,13 @@ choices are argued, with measurements, in
44
37
  | npm | `npm i -D @anizoptera/publish-clean` | `npm exec publish-clean` |
45
38
  | Yarn | `yarn add -D @anizoptera/publish-clean` | `yarn publish-clean` |
46
39
 
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
- Node.js 22+ runs it. npm provenance additionally needs 22.14+, because below that npm
51
- cannot mint it.
40
+ Both `pnpm` and `npm` must be on `PATH`, including in Bun, npm and Yarn projects and CI.
41
+ The CLI is one JavaScript file with no runtime dependencies. pnpm and npm are separate
42
+ requirements, not bundled dependencies.
52
43
 
53
- That installs one package and nothing else. `publish-clean` has zero runtime
54
- dependencies: it is a single file that talks to `pnpm` and `npm`, and reads and rewrites
55
- the tarball itself, so there is nothing else to have on the machine.
56
-
57
- For something that sits on your publish path and handles your
58
- registry credentials, that matters. A publishing tool with a dependency tree is a
59
- supply-chain risk of its own, and this one has no transitive code to audit.
60
-
61
- `--provenance` additionally needs npm 11.5.1+ and a cloud CI runner. npm will not sign a
62
- publish that came from your laptop.
44
+ For trusted publishing, use Node.js 22.14+ and npm 11.5.1+. Provenance requires a public
45
+ package, a public source repository and a supported CI provider. See
46
+ [npm's requirements](https://docs.npmjs.com/trusted-publishers/).
63
47
 
64
48
  ### Running it under Bun
65
49
 
@@ -73,26 +57,20 @@ bun ./node_modules/.bin/publish-clean
73
57
  The installed command has a Node shebang. Passing the file directly avoids relying on
74
58
  how a package runner selects an interpreter or changes the child tools' environment.
75
59
 
76
- Either runtime produces valid gzip with identical contents, so the choice is free. The one
77
- rule is not to switch runtimes _within_ a version: if a release is re-run to repair its
78
- artifacts, the bytes have to come out the same, and the two encoders do not agree.
60
+ Keep the runtime and its version fixed when rebuilding a release artifact. Node and
61
+ Bun can encode the same archive contents into different gzip bytes, which changes the
62
+ artifact's hash.
79
63
 
80
64
  ## Package managers
81
65
 
82
- pnpm resolves workspace dependencies and applies its manifest overrides; npm uploads the
83
- resulting tarball. Compatibility evidence and limitations live in
84
- [why pnpm packs and npm publishes](docs/why-pnpm-and-npm.md).
66
+ The CLI uses pnpm for workspace resolution and `publishConfig` overrides, and npm to upload the
67
+ checked tarball. The [packer comparison](docs/why-pnpm-and-npm.md) explains the trade-offs.
85
68
 
86
- Started with anything other than pnpm, it prints an advisory on stderr saying so. That is
87
- a warning, not an error. Nothing behaves differently because of it, and there is no flag
88
- to silence it.
69
+ Starting through another package manager prints an advisory on stderr. It does not change
70
+ the packer or stop publication, and there is no option to suppress it.
89
71
 
90
- For a single package every manager behaves the same, since nothing in the manifest needs
91
- resolving before it ships.
92
-
93
- Monorepos are where it matters. `pnpm pack` resolves `workspace:` and `catalog:` specs by
94
- finding the dependency inside the packing package's own `node_modules`. What decides
95
- whether that works is the layout your installer left behind, not which installer it was.
72
+ For `workspace:` and `catalog:` specs, pnpm needs the installed dependency in the packing
73
+ package's own `node_modules`. Compatibility depends on your install layout.
96
74
 
97
75
  Bun gives each package its own `node_modules`, so a Bun workspace packs as it stands: no
98
76
  `pnpm-workspace.yaml`, no switching package managers. Yarn hoists workspace dependencies
@@ -101,32 +79,32 @@ all. Both need a `pnpm-workspace.yaml` and one `pnpm install` before packing wor
101
79
  package with no `workspace:` or `catalog:` specs needs neither, because there's nothing to
102
80
  resolve.
103
81
 
104
- Either way the workspace has to be installed. Pack one nobody has installed and it stops
105
- on pnpm's own error:
82
+ Install the workspace before packing. An unresolved workspace dependency stops packing:
106
83
 
107
84
  ```
108
85
  ERR_PNPM_CANNOT_RESOLVE_WORKSPACE_PROTOCOL
109
86
  ```
110
87
 
111
- Which is what you want. Nothing gets published, and a manifest that would have been
112
- uninstallable for everyone never reaches the registry. Run your usual install and pack
113
- again.
88
+ Install with the layout described above, then retry.
114
89
 
115
90
  ## Pick your setup
116
91
 
117
92
  ### Publishing a public package from CI
118
93
 
119
- The common case. `id-token: write` is what lets npm sign the release. Once trusted
120
- publishing is configured for the package, no npm token is involved at all.
94
+ Configure an npm trusted publisher for your repository and workflow filename, with
95
+ permission for direct `npm publish`. In the publish job, grant `id-token: write` so npm
96
+ can authenticate through GitHub OIDC without an npm token. Run tests in a separate job
97
+ and make the publish job depend on their success.
121
98
 
122
99
  ```yaml
123
- # .github/workflows/release.yml
100
+ # Inside the publish job, after its required check jobs have passed:
124
101
  permissions:
125
102
  contents: read
126
103
  id-token: write
127
104
  steps:
128
105
  - uses: actions/checkout@v7
129
106
  - uses: pnpm/action-setup@v6
107
+ # Set packageManager in package.json to select your pnpm version.
130
108
  - uses: actions/setup-node@v7
131
109
  with:
132
110
  node-version: "24"
@@ -136,13 +114,13 @@ steps:
136
114
  - run: pnpm exec publish-clean -- --access public --tag latest --provenance
137
115
  ```
138
116
 
139
- Always pass the dist-tag. npm defaults to `latest`, which is wrong for a prerelease and
140
- easy to forget.
117
+ Use `--tag latest` for stable releases and `--tag next` for prereleases. npm defaults
118
+ to `latest`, so omitting the tag can give ordinary installs a prerelease.
141
119
 
142
- Publishing a package name for the first time cannot use trusted publishing at all. That
143
- case has its own page: [docs/first-publish.md](docs/first-publish.md).
120
+ For a new package name, follow the [first-publish setup](docs/first-publish.md).
144
121
 
145
- To stop a stray `npm publish` from bypassing all of this:
122
+ To block direct publication from your source directory, add this hook. Publishing a
123
+ tarball does not run it:
146
124
 
147
125
  ```json
148
126
  {
@@ -154,8 +132,8 @@ To stop a stray `npm publish` from bypassing all of this:
154
132
 
155
133
  ### Keeping your existing release tool
156
134
 
157
- If Changesets, semantic-release, release-it or np already owns your releases, use
158
- `publish-clean` as a check rather than replacing the publish:
135
+ If your release tool supports a custom upload command, use `publish-clean` there.
136
+ For a preview check only, add:
159
137
 
160
138
  ```json
161
139
  {
@@ -176,8 +154,8 @@ to invoke `publish-clean` for the upload instead.
176
154
  pnpm exec publish-clean --dry-run
177
155
  ```
178
156
 
179
- Prints every file that would ship and the cleaned `package.json`, then deletes its temp
180
- tree. Add `--tarball-out DIR` to keep the tarball itself.
157
+ Prints the checked file list and cleaned `package.json`. Add `--tarball-out DIR` to keep
158
+ the tarball; otherwise temporary files are removed.
181
159
 
182
160
  ### Publishing a restricted package
183
161
 
@@ -185,8 +163,8 @@ tree. Add `--tarball-out DIR` to keep the tarball itself.
185
163
  publish-clean -- --access restricted --tag latest
186
164
  ```
187
165
 
188
- No provenance here, because npm only signs public packages. Do not set `private: true`
189
- either. npm treats it as a publish block, and `publish-clean` refuses it too.
166
+ Omit provenance for restricted packages. Leave `private: true` unset: it prohibits
167
+ publication, even to a private registry.
190
168
 
191
169
  ### Publishing one package out of a monorepo
192
170
 
@@ -199,108 +177,77 @@ publish-clean packages/my-lib -- --access public --tag next
199
177
  ```mermaid
200
178
  flowchart TD
201
179
  A[Your package directory] -->|pnpm pack| B[Tarball, file set chosen by pnpm]
202
- B --> C[Copy it, rewriting only the package.json inside]
180
+ B --> C[Rewrite only package.json inside]
203
181
  C --> D[Final tarball]
204
182
  D --> E{Checks, all reading this tarball}
205
183
  E -->|any fails| F[Exit non-zero, publish nothing]
206
184
  E -->|all pass| G[npm publish this same tarball]
207
185
  ```
208
186
 
209
- The checks are listed under [What it checks](#what-it-checks). The point of the shape is
210
- that they all read the tarball that gets uploaded, so what passed the checks and what
211
- reached the registry are the same bytes, not two things that ought to match.
212
-
213
- `--dry-run` and `--guard-only` validate the artifact. They do not contact the registry or
214
- validate publication credentials, provenance runtime requirements or repository identity.
187
+ `--dry-run` and `--guard-only` validate the artifact, but skip publication preflight.
188
+ Neither proves that registry access, credentials, provenance requirements or repository
189
+ identity are correct. Pack hooks still run, including any network operations they perform.
215
190
 
216
191
  ## Why it works this way
217
192
 
218
- ### Why pnpm packs, and npm publishes
219
-
220
- Use the [packer and uploader rationale](docs/why-pnpm-and-npm.md) when evaluating a replacement.
221
- It covers workspace resolution, pnpm overrides, bundled dependencies and the exact-byte
222
- upload requirement. Other clients also support provenance; that feature alone does not
223
- establish equivalent behavior throughout this pipeline.
224
-
225
193
  ### Why cleaning happens in the tarball
226
194
 
227
- The manifest is rewritten inside the tarball in a temporary directory.
228
- The cleaner never writes the source manifest; pack hooks still run in
229
- your source directory and may change it.
230
-
231
- The obvious alternative is what a lot of hand-rolled release scripts do: edit
232
- `package.json`, publish, edit it back. That's fine until something dies in the middle,
233
- and then your repo is sitting on a manifest nobody meant to keep. It also can't be run
234
- twice at once. Cleaning the temporary tarball avoids those source edits.
195
+ Cleaning stays out of the source tree so an interrupted publish cannot leave your
196
+ `package.json` half-edited. Pack hooks still run in the source directory and may change it.
235
197
 
236
198
  ### Why the tarball is edited instead of packed again
237
199
 
238
- Give npm a directory and it packs during the upload, so the bytes that reach the registry
239
- only come into existence after the last check has run. Packing first means they exist
240
- before anything is uploaded: they can be listed, scanned for leaks, kept with
241
- `--tarball-out` for a build attestation, and then published as themselves. What you
242
- inspect is what ships.
243
-
244
- So the manifest has to be cleaned inside a tarball that already exists. The obvious way is
245
- to unpack, edit, and pack again — and it is wrong. `files` is a packing instruction, and
246
- cleaning removes it, because it is useless to anyone installing the package. A second pack
247
- then has nothing left to select with, falls back to your `.gitignore`/`.npmignore` for
248
- exclusion, and quietly drops files the first pack included. A package shipping a
249
- `.gitignore` that excludes any other shipped file loses it.
250
-
251
- Editing avoids the question. Only the `package/package.json` member is replaced. Every
252
- other entry's raw bytes are preserved. The reader resolves USTAR prefixes and PAX paths
253
- before scanning; malformed or unsupported path metadata is refused. This keeps pnpm's
254
- normalised metadata: owner `0:0`, a fixed
255
- timestamp and file modes. A plain `tar` invocation would replace those with whatever the build
256
- machine happens to have.
257
-
258
- Lifecycle scripts run once, at the first pack. `pnpm pack` runs your `prepare` and
259
- `prepack`, which is how build output reaches the package at all. npm skips package lifecycle
260
- scripts for a tarball input, so upload does not rerun hooks against the checked artifact.
200
+ Uploading the checked tarball prevents npm from choosing files again.
201
+ Cleaning removes `files` from its manifest because installation no longer needs that
202
+ packing instruction. Repacking the cleaned directory could then fall back to ignore rules
203
+ and drop files the first pack included.
204
+
205
+ Only `package/package.json` is replaced. Other archive entries retain their bytes,
206
+ order and metadata, including pnpm's owner `0:0`, fixed timestamps and file modes.
207
+ The reader resolves USTAR and PAX paths before checking files and rejects malformed or
208
+ unsupported path metadata.
209
+
210
+ `pnpm pack` runs pack hooks, including `prepare` and `prepack`. npm runs no package
211
+ lifecycle scripts when uploading a tarball, so those hooks cannot change the checked
212
+ artifact during upload.
261
213
 
262
214
  ## What it checks
263
215
 
264
- `publish-clean` stops, and publishes nothing, when:
216
+ Publication stops when:
265
217
 
266
218
  - the package is marked `private: true`
267
219
  - the working tree has uncommitted changes (`--no-git-checks` to allow it)
268
220
  - the package has no non-empty `files` array (`--skip-file-check` to allow it)
269
- - the tarball holds tests, CI config, a lockfile or a `tsconfig` (`--allow-suspicious` to
270
- allow it — a separate switch from the one above, so waiving a manifest convention never
271
- silently disarms the artifact scan)
272
- - the tarball holds something that should never ship: a `.env`, an `.npmrc`, `.git`,
273
- `node_modules`, or a private key. This one has no off switch, by any flag or config key
221
+ - the tarball contains a recognised test, CI, lockfile or `tsconfig` path
222
+ (`--allow-suspicious` to allow it)
223
+ - a filename matches the protected rules for environment files, npm credentials, Git
224
+ internals, `node_modules` or key files; these checks cannot be disabled
274
225
  - a dependency is still written as `catalog:`, `workspace:`, `link:` or `portal:`, or a local
275
226
  dependency points outside the shipped files
276
- - the manifest points `exports`, `types`, `main`, `browser`, `bin` or `sideEffects` at a
277
- path that is not in the tarball
227
+ - a declared entry point cannot resolve against the shipped files; checks account for
228
+ extension lookup, conditions and fallbacks, and allow unmatched `sideEffects` globs
278
229
  - rewriting the manifest changed anything else in the tarball
279
- - you asked for `--provenance` from GitHub Actions, but the `repository` in your manifest
230
+ - GitHub trusted publishing or provenance is enabled, but the `repository` in your manifest
280
231
  is not the repository the workflow is running in
281
232
 
282
- It warns, without stopping, when it was started by npm, Yarn or Bun rather than pnpm. The
283
- packing still goes through pnpm, but the warning is there because the rest of your release
284
- probably should too.
233
+ File guards check paths, not file contents. They cannot detect a credential embedded
234
+ in an otherwise allowed source file. See [the rules](src/artifact.ts).
285
235
 
286
236
  ## What the cleaned manifest keeps
287
237
 
288
- Everything a consumer or a registry reads survives: `name`, `version`, `license`,
238
+ The cleaner preserves consumer and registry fields: `name`, `version`, `license`,
289
239
  `dependencies`, `peerDependencies` and their meta, `exports`, `main`, `module`, `types`,
290
- `bin`, `engines`, `os`, `cpu`, `sideEffects`, `publishConfig`, and the rest of the public
291
- surface.
240
+ `bin`, `engines`, `os`, `cpu`, `sideEffects` and `publishConfig`, among others.
292
241
 
293
- `files` goes, because it is spent: it told the packer what to include, the tarball already
294
- exists, nothing re-selects afterwards, and an install extracts every entry unfiltered. npm
295
- agrees — its registry drops the field from the metadata it serves.
242
+ It removes `files` after packing; installers extract the tarball without using that field.
296
243
 
297
- What else goes: `devDependencies`, `workspaces`, `pnpm`, `packageManager`, `overrides`,
244
+ It also removes `devDependencies`, `workspaces`, `pnpm`, `packageManager`, `overrides`,
298
245
  `resolutions`, and the config blocks belonging to test runners, linters, formatters,
299
246
  coverage tools, build systems and release tools. When `preinstall`, `install`, `postinstall`,
300
247
  `prepare` or `uninstall` exists, the complete scripts block survives: a lifecycle may call
301
248
  any helper script. Otherwise the development-only scripts block is removed.
302
249
 
303
- Anything the tool does not recognise ships, and you get told it did:
250
+ Unknown fields are kept and reported:
304
251
 
305
252
  ```
306
253
  publish-clean: these manifest fields are not recognised and are retained as-is:
@@ -310,13 +257,9 @@ Strip the ones consumers do not read, and acknowledge the ones they do:
310
257
  "publish-clean": { "keepFields": ["someToolConfig"] }
311
258
  ```
312
259
 
313
- The strip list cannot know about a tool invented after it was written, so new
314
- `package.json` keys would otherwise leak into every install unnoticed. Dropping them
315
- instead would be worse: a key some consumer actually resolves would vanish, and you would
316
- hear about it from a stranger's broken build rather than from your own release.
317
-
318
- Add your own with `devFields`. Better still, run `--dry-run` and read the manifest that
319
- would ship instead of trusting this list.
260
+ Unknown fields stay because removing an unfamiliar field can break a consumer's build.
261
+ Use `devFields` to remove a field you know is development-only, or `keepFields` to suppress
262
+ its report. Inspect the result with `--dry-run`.
320
263
 
321
264
  ## Options and config
322
265
 
@@ -324,8 +267,8 @@ would ship instead of trusting this list.
324
267
  publish-clean [options] [package-dir] [-- npm-publish-args]
325
268
  ```
326
269
 
327
- Most settings can be a flag or a `package.json` key. Flags win, so keep per-release
328
- choices like dist-tags on the command line and stable project policy in the manifest:
270
+ Set project defaults in `package.json`. A CLI registry overrides the configured registry;
271
+ boolean flags enable their setting. Pass per-release npm options, such as dist-tags, after `--`:
329
272
 
330
273
  ```json
331
274
  {
@@ -359,84 +302,67 @@ operands, workspace selectors, unknown options and values starting with `-` are
359
302
  so npm cannot substitute an unchecked package. For a filename starting with `-`, use `./`.
360
303
  Pass the dist-tag explicitly: `--tag latest` for a normal public release.
361
304
 
362
- A few of these deserve a sentence more.
305
+ `--tarball-out` saves the checked bytes in every mode, before any upload. You can inspect
306
+ them, attach them to a release or attest them, even if publication fails.
363
307
 
364
- `--tarball-out` keeps the bytes that were published, so a release pipeline can attach them
365
- to a GitHub Release or sign them with build-provenance attestation. The copy happens in
366
- every mode, before the publish, so you get the validated artifact even if the upload fails.
367
-
368
- `registry` pins where the package goes, so it cannot end up on whatever registry the
369
- machine happens to be pointed at.
308
+ `registry` sets both the general and package-scope destination in the cleaned manifest.
370
309
  Registry URLs must not contain usernames or passwords, including scoped destinations in
371
310
  `publishConfig`. Configure npm authentication in npm configuration instead.
372
311
 
373
- `skipFileCheck` and `allowSuspicious` are deliberately two switches. A missing `files`
374
- array is a manifest convention some packages do not follow; tests or a lockfile in the
375
- tarball is content nobody meant to ship. Neither touches the leak checks, which have no
376
- off switch at all.
312
+ `skipFileCheck` waives the manifest's `files` requirement. `allowSuspicious` permits the
313
+ listed development files. Neither disables the protected filename checks.
377
314
 
378
- `noGitChecks` is what you need when you publish from a build directory, or from a checkout
379
- that is not a git repository at all.
315
+ Use `noGitChecks` for a build directory or another directory outside a Git repository.
380
316
 
381
- `devFields` refuses fields that npm or your consumers actually read, like `exports`, `bin`,
382
- `engines` and the dependency maps, so a typo cannot quietly break your package.
317
+ `devFields` refuses known consumer fields such as `exports`, `bin`, `engines` and dependency
318
+ maps to prevent accidental removal.
383
319
 
384
- `keepFields` answers the unrecognised-field report the other way: the field belongs in the
385
- published package, stop mentioning it. A VS Code extension needs `contributes` and
386
- `publisher` in the artifact to work, and no generic publishing tool is ever going to know
387
- that.
320
+ Use `keepFields` for consumer fields the tool does not recognise, such as a VS Code
321
+ extension's `contributes` and `publisher`. It suppresses reports; it does not restore stripped fields.
388
322
 
389
323
  ## What it does not do
390
324
 
391
- It isn't a release manager. It won't pick your version number, write a changelog, tag
392
- anything, push a commit, create a GitHub release, or set up trusted publishing for you. It
393
- checks declared paths, not whether the JavaScript executes or the type declarations work
394
- for every consumer. Pair it with a release manager and a validator; the next section names them.
325
+ Use your release tool for versions, changelogs, tags and GitHub releases. Configure trusted
326
+ publishing separately. `publish-clean` checks declared paths; it does not execute your
327
+ package or validate its type declarations.
395
328
 
396
- It can't publish a package that uses `bundleDependencies`. pnpm links dependencies rather
397
- than copying them, so it has nothing to bundle and refuses:
329
+ Bundled `node_modules` are not allowed. pnpm may first reject `bundleDependencies` with:
398
330
 
399
331
  ```
400
332
  Add "nodeLinker: hoisted" to pnpm-workspace.yaml or delete bundleDependencies
401
333
  ```
402
334
 
403
- A hoisted layout can let pnpm bundle dependencies, but this tool still refuses the resulting
404
- `node_modules` entries. Changing the linker does not bypass that artifact policy. Packages
405
- that must ship bundled dependencies need a different publication policy.
335
+ A hoisted layout can make pnpm pack them, but the resulting `node_modules` entries still
336
+ fail this tool's file checks. Use another publication path if you need to ship them.
406
337
 
407
- ## How it compares
338
+ ## Related tools
408
339
 
409
- [`clean-publish`](https://github.com/shashkovdanil/clean-publish) is the closest prior
410
- art, and the reason this package exists at all. It copies your source tree into a temp
411
- directory, deletes the files and fields it recognises, and publishes that.
340
+ [`clean-publish`](https://github.com/shashkovdanil/clean-publish) cleans a temporary copy
341
+ of the source tree before publishing. `publish-clean` instead cleans a pnpm-produced tarball.
412
342
 
413
- `publish-clean` starts from what `pnpm pack` produced, which is the file
414
- list your package manager would have shipped, including `files`, `.npmignore`, packlist
415
- rules and resolved `workspace:` specs. Only the manifest is rewritten after that, and the
416
- result is validated again before upload.
343
+ That preserves pnpm's file selection and workspace resolution, and lets the checks read
344
+ the same bytes npm uploads.
417
345
 
418
- Release managers ([Changesets](https://github.com/changesets/changesets),
419
- [release-please](https://github.com/googleapis/release-please),
346
+ Release tools such as [Changesets](https://github.com/changesets/changesets),
420
347
  [semantic-release](https://github.com/semantic-release/semantic-release),
421
- [release-it](https://github.com/release-it/release-it),
422
- [np](https://github.com/sindresorhus/np)) pick versions, write changelogs, tag, and call
423
- `npm publish`. See the `--guard-only` setup above for its preview-only boundary; configure
424
- the upload through `publish-clean` when the release must use the checked artifact.
348
+ [release-please](https://github.com/googleapis/release-please),
349
+ [release-it](https://github.com/release-it/release-it) and [np](https://github.com/sindresorhus/np)
350
+ handle release tasks. See [integration](#keeping-your-existing-release-tool) for the
351
+ difference between a preview check and publishing through this CLI.
425
352
 
426
353
  [`publint`](https://publint.dev) and
427
354
  [`@arethetypeswrong/cli`](https://github.com/arethetypeswrong/arethetypeswrong.github.io)
428
- check that your entry points and type definitions resolve properly for consumers. That is
429
- a different question from what is in the tarball. Run them as well.
355
+ check package entry points and TypeScript compatibility. Use them alongside this tool.
430
356
 
431
- `npm publish --dry-run` prints the file list and stops there. It does not clean anything
432
- and will happily list a `.env` without complaining.
357
+ `npm publish --dry-run` previews npm's publication. It does not clean the manifest or apply
358
+ this tool's protected filename rules.
433
359
 
434
- [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) proves who
435
- published. This tool decides what gets published. They solve different halves of the same
436
- worry, and this package is built to use both.
360
+ [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) authorises a CI
361
+ workflow to publish. Provenance links a release to its source and build; it does not
362
+ check package contents for you.
437
363
 
438
364
  [`pkg-pr-new`](https://github.com/stackblitz-labs/pkg.pr.new) publishes preview builds
439
- per commit without touching the registry. Useful next to this, unrelated to cleaning.
365
+ per commit without publishing a version to npm.
440
366
 
441
367
  Underlying behaviour is defined by [`npm-packlist`](https://github.com/npm/npm-packlist),
442
368
  [`npm pack`](https://docs.npmjs.com/cli/v11/commands/npm-pack/),
@@ -457,3 +383,24 @@ reporting, not public issues: see [SECURITY.md](SECURITY.md).
457
383
  ## License
458
384
 
459
385
  Apache-2.0. Copyright 2026 Anizoptera and Art Shendrik.
386
+
387
+
388
+ ## Validate the final artifact
389
+
390
+ Set `publish-clean.validateArtifact` to an executable and its arguments to check the exact cleaned tarball before retention or upload:
391
+
392
+ ```json
393
+ {
394
+ "publish-clean": {
395
+ "validateArtifact": ["node", "scripts/check-artifact.mjs"]
396
+ }
397
+ }
398
+ ```
399
+
400
+ The command runs once in the source package directory, with the absolute tarball path appended as its last argument. It runs in normal, `--dry-run` and `--guard-only` modes, after built-in artifact checks and before `--tarball-out` copies anything. The configuration is stripped from the published manifest.
401
+
402
+ Use an executable, not a shell command or a Windows `.cmd` shim. Arguments remain literal; pipes, redirection and environment assignments are not interpreted. Relative script paths resolve from the package directory. The executable must be available in PATH or named by a path.
403
+
404
+ The validator must finish successfully and leave the tarball bytes unchanged. A launch failure, nonzero exit, changed or missing artifact stops retention and publication. Successful output is quiet; failure output is reported, with captured output bounded to prevent runaway memory use. Cancellation stops the child process tree before temporary files are removed. The validator is trusted project code, not a sandbox: it must not leave background writers or modify other project files.
405
+
406
+ Inspect the supplied archive directly. Do not invoke `publish-clean` or pack the package again inside the validator; that would recurse or validate different bytes.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- // @anizoptera/publish-clean 0.8.0 | https://github.com/Anizoptera/publish-clean#readme
3
+ // @anizoptera/publish-clean 0.9.1 | https://github.com/Anizoptera/publish-clean#readme
4
4
  import { readFileSync } from "node:fs";
5
5
  import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
@@ -317,10 +317,11 @@ function run(command, args, cwd, options = {}) {
317
317
  const output = options.output ?? "capture";
318
318
  const detached = process.platform !== "win32" && output !== "publish";
319
319
  return new Promise((resolve, reject) => {
320
- const child = spawn(...spawnArgs(command, args, process.platform), {
320
+ const invocation = output === "validator" ? [command, [...args]] : spawnArgs(command, args, process.platform);
321
+ const child = spawn(invocation[0], invocation[1], {
321
322
  cwd,
322
323
  detached,
323
- stdio: output === "capture" ? [
324
+ stdio: output === "capture" || output === "validator" ? [
324
325
  "ignore",
325
326
  "pipe",
326
327
  "pipe"
@@ -379,7 +380,7 @@ function run(command, args, cwd, options = {}) {
379
380
  if (stream === "stdout") stdout += chunk.toString();
380
381
  else stderr += chunk.toString();
381
382
  if (stdout.length + stderr.length > 1048576) {
382
- failure = new PublishCleanError(`${command} exceeded the output limit for a metadata query.`);
383
+ failure = new PublishCleanError(`${command} exceeded the captured output limit.`);
383
384
  stdout = stdout.slice(-4096);
384
385
  stderr = stderr.slice(-4096);
385
386
  stop();
@@ -403,7 +404,7 @@ function run(command, args, cwd, options = {}) {
403
404
  }
404
405
  if (failure || status !== 0) {
405
406
  const reason = failure && isObject(failure) && failure.code === "ENOENT" ? "is not available in PATH" : failure?.message ?? `exited with ${signal ?? status}`;
406
- reject(new PublishCleanError(`${command} ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ""}`, { cause: failure }));
407
+ reject(new PublishCleanError(`${command} ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ""}${output === "validator" && stdout.trim() ? `\n${stdout.trim()}` : ""}`, { cause: failure }));
407
408
  } else resolve(stdout);
408
409
  });
409
410
  if (options.signal?.aborted) stop();
@@ -704,7 +705,8 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
704
705
  "keepFields",
705
706
  "noGitChecks",
706
707
  "registry",
707
- "skipFileCheck"
708
+ "skipFileCheck",
709
+ "validateArtifact"
708
710
  ]);
709
711
  function packageConfig(pkg) {
710
712
  const config = pkg["publish-clean"];
@@ -720,6 +722,10 @@ function packageConfig(pkg) {
720
722
  if (config.registry !== void 0) assertRegistry(config.registry);
721
723
  stringList(config, "devFields");
722
724
  stringList(config, "keepFields");
725
+ if (config.validateArtifact !== void 0) {
726
+ const argv = stringList(config, "validateArtifact");
727
+ if (!argv[0]?.trim() || argv.some((argument) => argument.includes("\0"))) throw new PublishCleanError("publish-clean.validateArtifact must contain an executable followed by optional arguments, without NUL bytes.");
728
+ }
723
729
  return config;
724
730
  }
725
731
  /**
@@ -821,6 +827,7 @@ Options:
821
827
  -v, --version Show the publish-clean version.
822
828
 
823
829
  Manifest configuration, under a "publish-clean" key in package.json:
830
+ validateArtifact string[] Executable and arguments; appends the final tarball path in every mode.
824
831
  devFields string[] Extra fields to strip. Refused for fields consumers resolve.
825
832
  keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
826
833
  registry string Default for --registry.
@@ -1293,7 +1300,8 @@ async function packAndClean(packageDir, signal, opts) {
1293
1300
  const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
1294
1301
  if (unrecognized) console.warn(unrecognized);
1295
1302
  await writeFile(finalTarball, replaceManifest(packed, cleanedText));
1296
- const published = await readTarball(finalTarball);
1303
+ const finalBytes = await readFile(finalTarball);
1304
+ const published = readArchive(finalBytes);
1297
1305
  const finalFiles = packageFiles(published);
1298
1306
  assertSameEntries(packageFiles(packed), finalFiles);
1299
1307
  assertPreservedArchive(packed, published);
@@ -1304,6 +1312,16 @@ async function packAndClean(packageDir, signal, opts) {
1304
1312
  assertNoMonorepoProtocols(shippedPkg, finalFiles);
1305
1313
  assertNoLostConsumerFields(packedPkg, shippedPkg, extraDevFields);
1306
1314
  if (manifestText(published) !== cleanedText) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
1315
+ const validator = config.validateArtifact;
1316
+ if (validator) try {
1317
+ await run(validator[0], [...validator.slice(1), finalTarball], packageDir, {
1318
+ signal,
1319
+ output: "validator"
1320
+ });
1321
+ if (!finalBytes.equals(await readFile(finalTarball))) throw new PublishCleanError("The validator changed the tarball. Validators must be read-only.");
1322
+ } catch (cause) {
1323
+ throw new PublishCleanError("publish-clean.validateArtifact failed; no tarball was retained or published.", { cause });
1324
+ }
1307
1325
  if (opts.tarballOut !== null) {
1308
1326
  await mkdir(opts.tarballOut, { recursive: true });
1309
1327
  const kept = path.join(opts.tarballOut, path.basename(finalTarball));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anizoptera/publish-clean",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
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",