@anizoptera/publish-clean 0.10.0 → 0.12.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.
- package/README.md +42 -10
- package/dist/cli.js +21 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,13 +14,20 @@ verified `exports`, checks for unwanted files, unresolved workspace dependencies
|
|
|
14
14
|
what was verified is exactly what the registry stores and what provenance signs.
|
|
15
15
|
|
|
16
16
|
```text
|
|
17
|
-
pnpm pack
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
17
|
+
pnpm pack
|
|
18
|
+
│
|
|
19
|
+
▼
|
|
20
|
+
rewrite package.json inside the tarball
|
|
21
|
+
│
|
|
22
|
+
▼
|
|
23
|
+
re-read it from disk and check it
|
|
24
|
+
│
|
|
25
|
+
├─▶ unrepaired, and it leaks
|
|
26
|
+
│ or breaks a consumer
|
|
27
|
+
│ └─▶ exit 1
|
|
28
|
+
│
|
|
29
|
+
└─▶ repaired, or only reported
|
|
30
|
+
└─▶ npm publish <that exact file>
|
|
24
31
|
```
|
|
25
32
|
|
|
26
33
|
```sh
|
|
@@ -317,7 +324,7 @@ publish-clean packages/my-lib -- --access public --tag next
|
|
|
317
324
|
```mermaid
|
|
318
325
|
flowchart TD
|
|
319
326
|
A[Your package directory] -->|pnpm pack| B[Tarball, file set chosen by pnpm]
|
|
320
|
-
B --> C[Rewrite only package.json inside]
|
|
327
|
+
B --> C[Rewrite only package.json inside, and the names renameFiles lists]
|
|
321
328
|
C --> D[Final tarball]
|
|
322
329
|
D --> E{Checks, all reading this tarball}
|
|
323
330
|
E -->|any fails| F[Exit non-zero, publish nothing]
|
|
@@ -391,14 +398,17 @@ Publication stops when:
|
|
|
391
398
|
- the tarball contains a recognised test, CI, lockfile or `tsconfig` path
|
|
392
399
|
(`--allow-suspicious` to allow it) [`suspicious-file`]
|
|
393
400
|
- a filename matches the protected rules for environment files, npm credentials [`secret-file`],
|
|
394
|
-
or Git internals
|
|
401
|
+
or Git internals, `node_modules`, and editor or coding-agent state (`.idea`, `.vscode`,
|
|
402
|
+
`.cursor`, `.windsurf`, `.junie`, `.claude`, `.codex`, `.gemini`, `.agent`, `.agents`, `.omc`,
|
|
403
|
+
`.aider*`) at any depth [`internal-file`]; these checks cannot be disabled
|
|
395
404
|
- a dependency is still written as `catalog:`, `workspace:`, `link:` or `portal:`, or a local
|
|
396
405
|
dependency points outside the shipped files [`monorepo-only-spec`]
|
|
397
406
|
- a declared entry point cannot resolve against the shipped files; checks account for
|
|
398
407
|
extension lookup, conditions and fallbacks. A declared path no consumer can resolve — an object
|
|
399
408
|
`browser`, `sideEffects`, an internal `#` import, a `*` pattern matching no packed file — reports
|
|
400
409
|
and continues instead [`declared-path-inert`], and `--strict` refuses it
|
|
401
|
-
- rewriting the manifest changed anything else in the tarball
|
|
410
|
+
- rewriting the manifest changed anything else in the tarball, beyond the names
|
|
411
|
+
[`renameFiles`](#ship-a-file-under-another-name) asked for
|
|
402
412
|
- GitHub trusted publishing or provenance is enabled, but the `repository` in your manifest
|
|
403
413
|
is not the repository the workflow is running in
|
|
404
414
|
- a `require` condition resolves to an ES module [`require-branch-is-esm`]. Node can require one
|
|
@@ -545,6 +555,7 @@ boolean flags enable their setting. Pass per-release npm options, such as dist-t
|
|
|
545
555
|
| - | `devFields` | Extra manifest fields to strip. |
|
|
546
556
|
| - | `keepFields` | Fields that belong in the published package, so stop reporting them. |
|
|
547
557
|
| - | `allowUnreferenced` | Shipped paths nothing imports, on purpose. Matched as a prefix, so a directory name covers everything under it. |
|
|
558
|
+
| - | [`renameFiles`](#ship-a-file-under-another-name) | Ship a packed file under another name, e.g. `{ "AGENTS.consumer.md": "AGENTS.md" }`. |
|
|
548
559
|
| - | [`validateArtifact`](#validate-the-final-artifact) | Run your checks on the cleaned tarball before copying or publishing it. |
|
|
549
560
|
| `-h`, `--help` | - | Print usage, every flag, and the config keys. |
|
|
550
561
|
| `-v`, `--version` | - | Print the installed version. |
|
|
@@ -598,6 +609,27 @@ Your script runs with your permissions. Keep it read-only and wait for its child
|
|
|
598
609
|
|
|
599
610
|
Check the supplied tarball. Packing again checks different bytes; calling publish-clean from the script runs the same hook again.
|
|
600
611
|
|
|
612
|
+
### Ship a file under another name
|
|
613
|
+
|
|
614
|
+
Use `renameFiles` when a file must reach consumers under a name your package root already uses for something that must not ship. The usual case is a package whose root is its repository root: `AGENTS.md` holds the maintainer's agent rules, and the consumer's agent instructions live in `AGENTS.consumer.md` but must install as `AGENTS.md`. A `prepack` copy cannot do this, because the target already exists in the tree pnpm packs.
|
|
615
|
+
|
|
616
|
+
```json
|
|
617
|
+
{
|
|
618
|
+
"files": ["dist", "AGENTS.consumer.md"],
|
|
619
|
+
"publish-clean": {
|
|
620
|
+
"renameFiles": { "AGENTS.consumer.md": "AGENTS.md" }
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
pnpm still decides what is packed, so list the source in `files`, and leave the target out. Paths are relative to the package root, as pnpm packs them. Only the member's name in the tarball changes: its contents, mode and timestamp stay exactly as pnpm wrote them, and nothing in your source tree is touched. Every check judges the renamed file under its new name, which is what consumers install, and the credential, build-machine and development-file guards also judge it under its packed name, so a rename cannot carry a `.env` or a test file past them. The config is removed from the published manifest.
|
|
626
|
+
|
|
627
|
+
A map that cannot work is refused before packing: a path that is absolute, starts with `./`, contains `.` or `..` segments or a backslash, renames `package.json`, renames a file to itself, gives two sources one target, or uses a target that is also a source. After packing, the run stops when:
|
|
628
|
+
|
|
629
|
+
- the source is not in the packed tarball, so nothing would ship under the new name [`rename-source-missing`]. Add it to `files`, or fix the path
|
|
630
|
+
- the tarball already carries the target, or a file or directory overlapping it [`rename-target-exists`]: two members on one path leave the installed file to whichever the extractor writes last
|
|
631
|
+
- the rename cannot be written [`rename-unsupported`]: the source is a directory rather than a file, pnpm stored its name in a long-name header, or the target does not fit a tar header (100 bytes, or up to 155 more split at a `/`)
|
|
632
|
+
|
|
601
633
|
## What it does not do
|
|
602
634
|
|
|
603
635
|
Use your release tool for versions, changelogs, tags and GitHub releases. Configure trusted
|
package/dist/cli.js
CHANGED
|
@@ -1,38 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
// @anizoptera/publish-clean 0.
|
|
3
|
+
// @anizoptera/publish-clean 0.12.0 | https://github.com/Anizoptera/publish-clean#readme
|
|
4
4
|
import{readFileSync as e}from"node:fs";import{copyFile as t,mkdir as n,mkdtemp as r,readFile as i,readdir as a,rm as o,writeFile as s}from"node:fs/promises";import{tmpdir as c}from"node:os";import l from"node:path";import{fileURLToPath as u}from"node:url";import{spawn as d}from"node:child_process";import{Script as f}from"node:vm";import{parseArgs as p}from"node:util";import{gunzipSync as m,gzipSync as h}from"node:zlib";var PublishCleanError=class extends Error{constructor(e,t){super(e,t),this.name=`PublishCleanError`}};function countOf(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function severityOf(e,t){return e.consequence===`waste`?e.rulesAbort===!0||t?`error`:`warning`:`error`}function isFatal(e,t){return!e.healed&&severityOf(e,t)===`error`}function publishRefusal(e,t){let n=e.filter(e=>isFatal(e,t));return n.length===0?null:`Refusing to publish: ${countOf(n.length,`unrepaired finding`)} above would reach consumers. A published version cannot be taken back.`}function formatFindings(e,t){return e.map(e=>{let n=e.healed?` repaired in the published artifact, not in your source:`:``;return`publish-clean [${severityOf(e,t)}] ${e.rule} at ${e.where}${n}\n${e.message}`}).join(`
|
|
5
5
|
|
|
6
6
|
`)}const g=[{rule:`secret-file`,patterns:[/(?:^|\/)\.env(?:\.|$)/i,/(?:^|\/)\.npmrc$/i,/\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,/(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i],consequence:`harm`,rulesAbort:!1,waivable:!1,explain:e=>`Treat every file below as a compromised credential and rotate it now. Publishing was never required for that — it was packed, so it already exists outside your repository:
|
|
7
7
|
${e.map(e=>` ${e}`).join(`
|
|
8
|
-
`)}\nThis tool will not strip them for you: a stripped secret has still leaked, and an artifact that looks clean is how a leak goes unrotated. Once the credentials are dead, narrow the "files" array in your package.json so the next pack cannot reach them.`},{rule:`internal-file`,patterns:[/(?:^|\/)node_modules(?:\/|$)/i,/(?:^|\/)\.git(?:\/|$)/i],consequence:`harm`,rulesAbort:!1,waivable:!1,explain:e=>`These belong to the machine that built the package, not to the package:\n${e.map(e=>` ${e}`).join(`
|
|
9
|
-
`)}\nA packed .git carries every committed blob and your remote URLs; a packed node_modules installs a second, unresolvable copy of your dependency tree over the consumer's own. Narrow the "files" array in your package.json.`},{rule:`suspicious-file`,patterns:[/(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,/(?:^|\/)\.github(?:\/|$)/,/(?:^|\/)tsconfig[^/]*\.json$/,/(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,/\.(?:test|spec)\.[cm]?[jt]sx?$/],consequence:`waste`,rulesAbort:!0,waivable:!0,explain:e=>`These are development files rather than anything a consumer installs, so everyone who installs this package downloads them forever for nothing:
|
|
8
|
+
`)}\nThis tool will not strip them for you: a stripped secret has still leaked, and an artifact that looks clean is how a leak goes unrotated. Once the credentials are dead, narrow the "files" array in your package.json so the next pack cannot reach them.`},{rule:`internal-file`,patterns:[/(?:^|\/)node_modules(?:\/|$)/i,/(?:^|\/)\.git(?:\/|$)/i,/(?:^|\/)\.(?:idea|vscode|cursor|windsurf|junie|claude|codex|gemini|agents?|omc)(?:\/|$)/i,/(?:^|\/)\.aider[^/]*(?:\/|$)/i],consequence:`harm`,rulesAbort:!1,waivable:!1,explain:e=>`These belong to the machine that built the package, not to the package:\n${e.map(e=>` ${e}`).join(`
|
|
9
|
+
`)}\nA packed .git carries every committed blob and your remote URLs; a packed node_modules installs a second, unresolvable copy of your dependency tree over the consumer's own; editor and coding-agent state (.idea, .vscode, .claude, .codex and the like) carries your settings, sessions and memory. Narrow the "files" array in your package.json, or exclude the directory with a "!" entry when it sits inside a shipped folder.`},{rule:`suspicious-file`,patterns:[/(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,/(?:^|\/)\.github(?:\/|$)/,/(?:^|\/)tsconfig[^/]*\.json$/,/(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,/\.(?:test|spec)\.[cm]?[jt]sx?$/],consequence:`waste`,rulesAbort:!0,waivable:!0,explain:e=>`These are development files rather than anything a consumer installs, so everyone who installs this package downloads them forever for nothing:
|
|
10
10
|
${e.map(e=>` ${e}`).join(`
|
|
11
|
-
`)}\nRemove them from the "files" array in your package.json. If this package ships them on purpose — a test helper other packages import, a tsconfig consumers extend — overrule the judgement with --allow-suspicious, or "publish-clean": { "allowSuspicious": true }.`}];function matchPackedContent(e,t){let n=g.filter(e=>!e.waivable||!t),r
|
|
12
|
-
`)}`)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}function foldName(e){return e.normalize(`NFC`).toLowerCase()}const _=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i,v=/[<>:"|?*\\\u0000-\u001f]/,y=/[. ]$/;function unportableName(e,t){for(let n of e.split(`/`)){let e=JSON.stringify(n);if(Buffer.byteLength(n,`utf8`)>255)return{reason:`${e} is longer than 255 bytes`,windowsOnly:!1};if(t){if(_.test(n))return{reason:`${e} is a reserved device name on Windows`,windowsOnly:!0};if(v.test(n))return{reason:`${e} holds a character Windows forbids in a name`,windowsOnly:!0};if(y.test(n))return{reason:`${e} ends in a dot or space, which Windows strips`,windowsOnly:!0}}}}function targetsWindows(e){if(!Array.isArray(e))return!0;let t=e.filter(e=>typeof e==`string`).map(e=>e.toLowerCase());if(t.length===0)return!0;if(t.includes(`!win32`))return!1;let n=t.filter(e=>!e.startsWith(`!`));return n.length===0||n.includes(`win32`)}function reviewPackedNames(e,t){let n=[],r
|
|
11
|
+
`)}\nRemove them from the "files" array in your package.json. If this package ships them on purpose — a test helper other packages import, a tsconfig consumers extend — overrule the judgement with --allow-suspicious, or "publish-clean": { "allowSuspicious": true }.`}];function matchPackedContent(e,t){let n=g.filter(e=>!e.waivable||!t),r=/* @__PURE__ */ new Map;for(let t of e){let e=n.find(({patterns:e})=>e.some(e=>e.test(t)));if(!e)continue;let i=r.get(e);i?i.push(t):r.set(e,[t])}return r}function forbiddenPackedFiles(e,t){return new Set([...matchPackedContent(e,t).values()].flat())}function reviewPackedContent(e,t){let n=matchPackedContent(e,t);return g.flatMap(e=>{let t=n.get(e);return t?[{rule:e.rule,consequence:e.consequence,rulesAbort:e.rulesAbort,healed:!1,where:countOf(t.length,`packed file`),message:e.explain(t)}]:[]})}function assertSameEntries(e,t){let n=new Set(e),r=new Set(t),i=[...e.filter(e=>!r.has(e)).map(e=>`- ${e}`),...t.filter(e=>!n.has(e)).map(e=>`+ ${e}`)];if(i.length>0)throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${i.join(`
|
|
12
|
+
`)}`)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}function foldName(e){return e.normalize(`NFC`).toLowerCase()}const _=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i,v=/[<>:"|?*\\\u0000-\u001f]/,y=/[. ]$/;function unportableName(e,t){for(let n of e.split(`/`)){let e=JSON.stringify(n);if(Buffer.byteLength(n,`utf8`)>255)return{reason:`${e} is longer than 255 bytes`,windowsOnly:!1};if(t){if(_.test(n))return{reason:`${e} is a reserved device name on Windows`,windowsOnly:!0};if(v.test(n))return{reason:`${e} holds a character Windows forbids in a name`,windowsOnly:!0};if(y.test(n))return{reason:`${e} ends in a dot or space, which Windows strips`,windowsOnly:!0}}}}function targetsWindows(e){if(!Array.isArray(e))return!0;let t=e.filter(e=>typeof e==`string`).map(e=>e.toLowerCase());if(t.length===0)return!0;if(t.includes(`!win32`))return!1;let n=t.filter(e=>!e.startsWith(`!`));return n.length===0||n.includes(`win32`)}function reviewPackedNames(e,t){let n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let e of t){let t=foldName(e),n=r.get(t);n?n.push(e):r.set(t,[e]);for(let t=e.indexOf(`/`);t!==-1;t=e.indexOf(`/`,t+1))i.set(foldName(e.slice(0,t)),e.slice(0,t))}let a=[...r.entries()].flatMap(([e,t])=>{let n=i.get(e),r=n===void 0?t:[...t,`${n}/`];return r.length>1?[r]:[]});a.length>0&&n.push({rule:`packed-name-collision`,consequence:`breaks`,healed:!1,where:countOf(a.length,`colliding name`),message:`These entries collapse onto one path wherever the filesystem ignores letter case or Unicode form, which is macOS and Windows by default. Two files means one silently replaces the other and the install still reports success; a file against a directory means the install fails outright:
|
|
13
13
|
`+a.map(e=>{let t=new Set(e.map(e=>e.normalize(`NFC`))).size===1?`Unicode form`:`letter case`;return` ${e.join(` and `)} — differ only in ${t}`}).join(`
|
|
14
14
|
`)+`
|
|
15
15
|
Rename one of each group so the names differ by more than case or Unicode form.`});let o=targetsWindows(e.os),s=[];for(let e of t){let t=unportableName(e,o);t!==void 0&&s.push({file:e,defect:t})}return s.length>0&&n.push({rule:`packed-name-unportable`,consequence:`breaks`,healed:!1,where:countOf(s.length,`file`),message:`These packed names cannot be created on a consumer's filesystem. Installing either fails outright or writes the file under a different name, and nothing imports the name it lands under:
|
|
16
16
|
`+s.map(e=>` ${e.file} — ${e.defect.reason}`).join(`
|
|
17
17
|
`)+`
|
|
18
|
-
Rename them so every path component is legal everywhere.`+(s.every(e=>e.defect.windowsOnly)?` If this package genuinely does not run on Windows, say so instead and npm will refuse the install there rather than break it: "os": ["!win32"].`:``)}),n}function collectDeclaredPaths(e,t,n){if(typeof e==`string`){if(e===``)return;(n===`every-string`||e.startsWith(`./`)||e.startsWith(`../`))&&t.push(e)
|
|
18
|
+
Rename them so every path component is legal everywhere.`+(s.every(e=>e.defect.windowsOnly)?` If this package genuinely does not run on Windows, say so instead and npm will refuse the install there rather than break it: "os": ["!win32"].`:``)}),n}function collectDeclaredPaths(e,t,n){if(typeof e==`string`){if(e===``)return;(n===`every-string`||e.startsWith(`./`)||e.startsWith(`../`))&&t.push(e)}else if(typeof e!=`boolean`){if(Array.isArray(e))for(let r of e)collectDeclaredPaths(r,t,n);else if(isObject(e))for(let r of Object.values(e))collectDeclaredPaths(r,t,n)}}function normalizeDeclaredPath(e){let t=e.startsWith(`./`)?e.slice(2):e;if(!t||l.posix.isAbsolute(t))return null;let n=l.posix.normalize(t);return n===`.`||n===`..`||n.startsWith(`../`)?null:n}const b=/\.d\.[cm]?ts$/,x=/\.[cm]?[jt]sx?$/;function checkerFinds(e,t){if(!x.test(t))return`other`;let n=normalizeDeclaredPath(t);if(n===null||!e.has(n))return`other`;if(b.test(t)||/\.[cm]?tsx?$/.test(t))return`declarations`;let r=t.replace(x,``);return[`.d.ts`,`.d.mts`,`.d.cts`].some(t=>{let n=normalizeDeclaredPath(r+t);return n!==null&&e.has(n)})?`declarations`:`javascript`}function matchesTarget(e,t){let n=t.split(`*`),r=n.length-1;if(r===0)return e===t;let i=(e.length-n.reduce((e,t)=>e+t.length,0))/r;if(!Number.isInteger(i)||i<0)return!1;let a=n[0]?.length??0;return n.join(e.slice(a,a+i))===e}var InvalidPackageTarget=class extends PublishCleanError{};function targetPath(e){if(!e.startsWith(`./`)||/%2f|%5c/i.test(e))throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(e)}`);try{if(decodeURIComponent(e.split(/[?#]/,1)[0]??``).slice(2).split(/[\\/]/).some(e=>[`.`,`..`,`node_modules`].includes(e.toLowerCase())))throw Error(`Invalid target segment`);return decodeURIComponent(new URL(e,`file:///package/`).pathname).slice(9)}catch(t){throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(e)}`,{cause:t})}}function collectTargets(e,t,n,r){if(e===null)return null;if(typeof e==`string`)return t&&!e.startsWith(`.`)&&!e.startsWith(`/`)||r.push({name:targetPath(e),kind:`target`,pattern:n,inert:t}),!0;if(Array.isArray(e)){if(e.length===0)return null;let i;for(let a of e)try{let e=collectTargets(a,t,n,r);if(e===!0)return!0;e===null&&(i=null)}catch(e){if(!(e instanceof InvalidPackageTarget))throw e;i=e}if(i)throw i;return i}if(!isObject(e))throw new InvalidPackageTarget(`Invalid exports/imports target; expected a path, condition object, array or null.`);let i=Object.entries(e);for(let[e]of i){let t=Number(e);if(String(t)===e&&t>=0&&t<0xffffffff)throw new PublishCleanError(`Invalid export condition: ${JSON.stringify(e)}.`)}for(let[e,a]of i){let i=collectTargets(a,t,n,r);if(e==="default"&&i!==void 0)return i}}function collectMap(e,t,n){if(e!=null){if(t&&!isObject(e))throw new PublishCleanError(`imports must be a subpath map.`);if(!(isObject(e)&&(t||Object.keys(e).some(e=>e.startsWith(`.`)))))collectTargets(e,t,!1,n);else for(let[r,i]of Object.entries(e)){if(t?!r.startsWith(`#`)||r===`#`||r.startsWith(`#/`):r!==`.`&&!r.startsWith(`./`))throw new PublishCleanError(`Invalid exports/imports key: ${JSON.stringify(r)}.`);collectTargets(i,t,r.includes(`*`),n)}}}function mainExists(e,t){if((e=>[``,`.js`,`.json`,`.node`].some(n=>t.has(e+n)))(e))return!0;let n=e?`${e}/`:``;return[`.js`,`.json`,`.node`].some(e=>t.has(`${n}index${e}`))}function nearMatch(e,t){let n=foldName(e);return t.find(e=>foldName(e)===n)}function reviewDeclaredFiles(e,t){let n=[],collect=(e,t,{inert:r=!1,mode:i=`every-string`,patterns:a=!1}={})=>{let o=[];collectDeclaredPaths(e,o,i),n.push(...o.map(e=>({name:e,kind:t,pattern:a&&e.includes(`*`),inert:r})))};collect(e.main,`main`);for(let t of[`types`,`typings`])collect(e[t],`types`);collect(e.typesVersions,`types`,{patterns:!0}),collect(e.module,`main`),collect(e.bin,`file`);let r=typeof e.browser==`string`;collect(e.browser,`main`,{inert:!r,mode:r?`every-string`:`relative-only`}),collect(e.sideEffects,`glob`,{inert:!0,mode:`relative-only`}),collectMap(e.exports,!1,n),collectMap(e.imports,!0,n);let i=new Set(t),a=[],o=[],s=0;for(let e of n){if(e.kind===`glob`&&/[*?[\]{}]/.test(e.name))continue;let n=e.kind===`main`&&[`.`,`./`].includes(e.name)?``:normalizeDeclaredPath(e.name);if(n===null)throw new PublishCleanError(`Manifest declares invalid package paths: ${JSON.stringify(e.name)}`);let r=i.has(n);if(!r&&n.endsWith(`/`)?r=t.some(e=>e.startsWith(n)):!r&&e.pattern?r=t.some(e=>matchesTarget(e,n)):!r&&e.kind===`main`?r=mainExists(n.replace(/\/$/,``),i):!r&&e.kind===`types`&&(r=[`.d.ts`,`.d.mts`,`.d.cts`,`/index.d.ts`].some(e=>i.has(n+e))),r)s++;else if(e.inert||e.pattern){o.push({rule:`declared-path-inert`,consequence:`waste`,healed:!1,where:e.name,message:`The manifest declares ${JSON.stringify(e.name)} and the archive does not carry it. Nothing a consumer resolves reaches this entry — it is a bundler hint, an internal "#" import, or a pattern matching no packed file — so the publish is not stopped and nothing here is rewritten. It is stale: delete it, or pack the file it names. Use --strict to refuse a publish over this.`});continue}if(!r){let r=nearMatch(n,t);a.push(r===void 0?JSON.stringify(e.name):`${JSON.stringify(e.name)} — the archive holds ${JSON.stringify(r)}, which differs only in case or Unicode form, so it resolves only where the filesystem ignores that difference. The machine this was built on does; a consumer's may not. Rename it to match the packed name exactly`)}}if(s===0&&a.push(...o.map(e=>JSON.stringify(e.where))),a.length)throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${a.join(`
|
|
19
19
|
`)}`);return o}function spawnArgs(e,t,n){if(n!==`win32`)return[e,[...t]];let r=[e,...t].filter(e=>/[&|<>^%()\r\n]/.test(e));if(r.length>0)throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${r.map(e=>JSON.stringify(e)).join(`
|
|
20
|
-
`)}\nUse arguments without & | < > ^ % ( ) or line breaks, or publish from Linux or macOS.`);return[`cmd.exe`,[`/d`,`/c`,e,...t]]}function failureReason(e,t){let n=isObject(e)?e.code:void 0;return n===`ENOENT`?`is not available in PATH`:n===`EACCES`?"is on PATH but carries no execute permission. Restore it with `chmod +x`, or reinstall the tool":n===`ENOEXEC`?`is on PATH but cannot be executed: the file is a script with no shebang line, or a program built for another architecture. An installer that skipped build scripts leaves such a placeholder behind — reinstall it with its build scripts allowed`:e?.message??t}function run(e,t,n,r={}){r.signal?.throwIfAborted();let i=r.output??`capture`,a=process.platform!==`win32`&&i!==`publish`;return new Promise((o,s)=>{let c=i===`validator`?[e,[...t]]:spawnArgs(e,t,process.platform),l=d(c[0],c[1],{cwd:n,detached:a,stdio:i===`capture`||i===`validator`?[`ignore`,`pipe`,`pipe`]:i===`pack`?[`ignore`,process.stderr,process.stderr]:`inherit`}),u=``,f=``,p,m,h=!1,g,killGroup=e=>{try{l.pid!==void 0&&(a?process.kill(-l.pid,e):l.kill(e))}catch(e){
|
|
20
|
+
`)}\nUse arguments without & | < > ^ % ( ) or line breaks, or publish from Linux or macOS.`);return[`cmd.exe`,[`/d`,`/c`,e,...t]]}function failureReason(e,t){let n=isObject(e)?e.code:void 0;return n===`ENOENT`?`is not available in PATH`:n===`EACCES`?"is on PATH but carries no execute permission. Restore it with `chmod +x`, or reinstall the tool":n===`ENOEXEC`?`is on PATH but cannot be executed: the file is a script with no shebang line, or a program built for another architecture. An installer that skipped build scripts leaves such a placeholder behind — reinstall it with its build scripts allowed`:e?.message??t}function run(e,t,n,r={}){r.signal?.throwIfAborted();let i=r.output??`capture`,a=process.platform!==`win32`&&i!==`publish`;return new Promise((o,s)=>{let c=i===`validator`?[e,[...t]]:spawnArgs(e,t,process.platform),l=d(c[0],c[1],{cwd:n,detached:a,stdio:i===`capture`||i===`validator`?[`ignore`,`pipe`,`pipe`]:i===`pack`?[`ignore`,process.stderr,process.stderr]:`inherit`}),u=``,f=``,p,m,h=!1,g,killGroup=e=>{try{l.pid!==void 0&&(a?process.kill(-l.pid,e):l.kill(e))}catch(e){isObject(e)&&e.code===`ESRCH`||(p=e instanceof Error?e:Error(String(e)))}},stop=()=>{h||l.pid===void 0||(h=!0,process.platform===`win32`?g=new Promise(e=>{let t=d(`taskkill`,[`/pid`,String(l.pid),`/t`,`/f`],{stdio:`ignore`});t.on(`error`,e=>{p=e,l.kill()}),t.once(`close`,t=>{t!==0&&!p&&(p=new PublishCleanError(`Unable to terminate the child process tree.`)),e()})}):(killGroup(`SIGTERM`),m=setTimeout(()=>killGroup(`SIGKILL`),1e3),m.unref()))},_=r.timeout===void 0?void 0:setTimeout(()=>{p=new PublishCleanError(`${e} did not finish within ${r.timeout}ms.`),stop()},r.timeout),collect=(t,n)=>{n===`stdout`?u+=t.toString():f+=t.toString(),u.length+f.length>1048576&&(p=new PublishCleanError(`${e} exceeded the captured output limit.`),u=u.slice(-4096),f=f.slice(-4096),stop())};l.stdout?.on(`data`,e=>collect(e,`stdout`)),l.stderr?.on(`data`,e=>collect(e,`stderr`)),l.on(`error`,e=>{p=e}),r.signal?.addEventListener(`abort`,stop,{once:!0}),l.once(`close`,async(t,n)=>{h&&process.platform!==`win32`&&killGroup(`SIGKILL`),await g,clearTimeout(_),clearTimeout(m),r.signal?.removeEventListener(`abort`,stop),r.signal?.aborted?s(r.signal.reason):p||t!==0?s(new PublishCleanError(`${e} ${failureReason(p,`exited with ${n??t}`)}${f.trim()?`: ${f.trim()}`:``}${i===`validator`&&u.trim()?`\n${u.trim()}`:``}`,{cause:p})):o(u)}),r.signal?.aborted&&stop()})}async function requireTool(e,t,n){return(await run(e,[`--version`],t,{signal:n,timeout:1e4})).trim()}const S=/* @__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(`.`)),C=/* @__PURE__ */ new Set([`preinstall`,`install`,`postinstall`,`prepare`,`uninstall`]),w=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`,`overrides`,`resolutions`],T=[`catalog:`,`workspace:`,`link:`,`portal:`],E=/* @__PURE__ */ new Set([`config`,`deno`,`directories`,`jsdelivr`,`man`,`preferUnplugged`,`react-native`,`sass`,`style`,`styleModule`,`svelte`,`unpkg`,...w,`bin`,`browser`,`bundleDependencies`,`bundledDependencies`,`cpu`,`engines`,`exports`,`imports`,`libc`,`license`,`main`,`module`,`name`,`os`,`peerDependenciesMeta`,`publishConfig`,`sideEffects`,`type`,`types`,`typesVersions`,`typings`,`version`]),D=/* @__PURE__ */ new Set([`author`,`bugs`,`contributors`,`description`,`funding`,`gitHead`,`homepage`,`keywords`,`maintainers`,`preferGlobal`,`repository`,`scripts`]),O=`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.`;function stripManifest(e,t){let n={...e};for(let e of[...S,...t])delete n[e];let r=isObject(e.scripts)?e.scripts:null;return r&&(Object.entries(r).some(([e,t])=>C.has(e)&&typeof t==`string`)?n.scripts=r:delete n.scripts),n}function assertNoLostConsumerFields(e,t,n){let r=/* @__PURE__ */ new Set([...S,...n,`scripts`]),i=Object.keys(e).filter(e=>(E.has(e)||D.has(e))&&!r.has(e)&&!(e in t));if(i.length>0)throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${i.join(`
|
|
21
21
|
`)}`)}function reviewUnrecognizedFields(e,t){let n=new Set(t),r=Object.keys(e).filter(e=>!E.has(e)&&!D.has(e)&&!n.has(e));if(r.length===0)return[];let i=r.map(e=>JSON.stringify(e)),a=i.join(`, `);return[{rule:`unrecognized-field`,consequence:`waste`,healed:!1,where:countOf(r.length,`manifest field`),message:`These manifest fields are not recognised and are retained as-is:\n ${i.join(`
|
|
22
22
|
`)}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${a}] }\n "publish-clean": { "keepFields": [${a}] }`}]}function reviewMonorepoProtocols(e,t=[]){let n=[],r=new Set(t);for(let t of w){let i=e[t];if(isObject(i))for(let[e,a]of Object.entries(i)){if(typeof a!=`string`)continue;let i=a.startsWith(`npm:`)?a.slice(a.lastIndexOf(`@`)+1):a;if(T.some(e=>i.startsWith(e))&&n.push(`${t}.${e}: ${a}`),/^(?:file:|git\+file:|\.{1,2}(?:[\\/]|$)|\/|~[\\/]|[a-z]:[\\/])/i.test(a)){let i=null;try{i=normalizeDeclaredPath(decodeURIComponent(a.replace(/^file:/i,``)))}catch{}(!i||/[\\]/.test(i)||/^(?:git\+file:|~[\\/]|(?:file:)?[a-z]:[\\/])/i.test(a)||!(/\.(?:tgz|tar\.gz|tar)$/.test(i)&&r.has(i)||r.has(`${i}/package.json`)))&&n.push(`${t}.${e}: ${a} (local target is not in the artifact)`)}}}return n.length===0?[]:[{rule:`monorepo-only-spec`,consequence:`breaks`,healed:!1,where:countOf(n.length,`dependency spec`),message:`Packed manifest contains unresolved monorepo-only dependency specs:\n${n.join(`
|
|
23
|
-
`)}\n${O}`}]}function privatePackageRefusal(e){return e.private===!0?`Refusing to publish a package with private: true.`:null}function filesFieldRefusal(e,t){return t?null:!Array.isArray(e.files)||e.files.length===0||e.files.some(e=>typeof e!=`string`||!e.trim())?`Package manifest must define a non-empty "files" array of non-empty strings. Without it the packer falls back to .gitignore/.npmignore, which selects a file set nobody wrote down. Waive the convention with --skip-file-check if that is deliberate.`:null}function packageScope(e){if(typeof e.name!=`string`||!e.name.startsWith(`@`))return null;let t=e.name.indexOf(`/`);return t>1?e.name.slice(0,t):null}function registryFault(e){let t={rule:`registry-not-a-url`,message:`Registry must be an absolute HTTP(S) URL. The value is withheld here because a registry URL commonly carries a password; read it from your own package.json.`};if(typeof e!=`string`||!URL.canParse(e))return t;let n=new URL(e);return n.protocol!==`http:`&&n.protocol!==`https:`?t:n.username||n.password?{rule:`registry-credentials`,message:`Registry URLs must not contain credentials. Configure npm authentication separately — an .npmrc auth token, or a CI secret — and leave the URL bare. Treat the credential in this one as compromised: it is in your package.json and was about to be published inside the tarball's manifest.`}:null}function assertRegistry(e){let t=registryFault(e);if(t)throw new PublishCleanError(t.message)}function reviewRegistryDestinations(e){return isObject(e.publishConfig)?Object.entries(e.publishConfig).flatMap(([e,t])=>{if(e!==`registry`&&!e.endsWith(`:registry`))return[];let n=registryFault(t);return n?[{rule:n.rule,consequence:`harm`,healed:!1,where:`publishConfig[${JSON.stringify(e)}]`,message:n.message}]:[]}):[]}function withRegistry(e,t){if(t===null)return e;assertRegistry(t);let n=isObject(e.publishConfig)?{...e.publishConfig}:{};n.registry=t;let r=packageScope(e);return r&&(n[`${r}:registry`]=t),{...e,publishConfig:n}}const k
|
|
24
|
-
`)}\nValid options: ${[...k].join(`, `)}`);for(let e of[`allowSuspicious`,`heal`,`noGitChecks`,`skipFileCheck`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)throw new PublishCleanError(`publish-clean.${e} must be a boolean.`);if(t.registry!==void 0&&assertRegistry(t.registry),stringList(t,`devFields`),stringList(t,`keepFields`),stringList(t,`allowUnreferenced`),t.validateArtifact!==void 0){let e=stringList(t,`validateArtifact`);if(!e[0]?.trim()||e.some(e=>e.includes(`\0`)))throw new PublishCleanError(`publish-clean.validateArtifact must contain an executable followed by optional arguments, without NUL bytes.`)}return t}function stringList(e,t){let n=e[t];if(n===void 0)return[];if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new PublishCleanError(`publish-clean.${t} must be an array of strings.`);return n}function customDevFields(e){let t=stringList(e,`devFields`),n=new Set(stringList(e,`keepFields`)),r=t.filter(e=>n.has(e));if(r.length>0)throw new PublishCleanError(`These fields are listed as both devFields and keepFields, which asks to strip and to publish the same key:\n${r.join(`
|
|
23
|
+
`)}\n${O}`}]}function privatePackageRefusal(e){return e.private===!0?`Refusing to publish a package with private: true.`:null}function filesFieldRefusal(e,t){return t?null:!Array.isArray(e.files)||e.files.length===0||e.files.some(e=>typeof e!=`string`||!e.trim())?`Package manifest must define a non-empty "files" array of non-empty strings. Without it the packer falls back to .gitignore/.npmignore, which selects a file set nobody wrote down. Waive the convention with --skip-file-check if that is deliberate.`:null}function packageScope(e){if(typeof e.name!=`string`||!e.name.startsWith(`@`))return null;let t=e.name.indexOf(`/`);return t>1?e.name.slice(0,t):null}function registryFault(e){let t={rule:`registry-not-a-url`,message:`Registry must be an absolute HTTP(S) URL. The value is withheld here because a registry URL commonly carries a password; read it from your own package.json.`};if(typeof e!=`string`||!URL.canParse(e))return t;let n=new URL(e);return n.protocol!==`http:`&&n.protocol!==`https:`?t:n.username||n.password?{rule:`registry-credentials`,message:`Registry URLs must not contain credentials. Configure npm authentication separately — an .npmrc auth token, or a CI secret — and leave the URL bare. Treat the credential in this one as compromised: it is in your package.json and was about to be published inside the tarball's manifest.`}:null}function assertRegistry(e){let t=registryFault(e);if(t)throw new PublishCleanError(t.message)}function reviewRegistryDestinations(e){return isObject(e.publishConfig)?Object.entries(e.publishConfig).flatMap(([e,t])=>{if(e!==`registry`&&!e.endsWith(`:registry`))return[];let n=registryFault(t);return n?[{rule:n.rule,consequence:`harm`,healed:!1,where:`publishConfig[${JSON.stringify(e)}]`,message:n.message}]:[]}):[]}function withRegistry(e,t){if(t===null)return e;assertRegistry(t);let n=isObject(e.publishConfig)?{...e.publishConfig}:{};n.registry=t;let r=packageScope(e);return r&&(n[`${r}:registry`]=t),{...e,publishConfig:n}}const k=/* @__PURE__ */ new Set([`allowSuspicious`,`allowUnreferenced`,`devFields`,`heal`,`keepFields`,`noGitChecks`,`registry`,`renameFiles`,`skipFileCheck`,`validateArtifact`]);function packageConfig(e){let t=e[`publish-clean`];if(t===void 0)return{};if(!isObject(t))throw new PublishCleanError(`"publish-clean" must be an object.`);let n=Object.keys(t).filter(e=>!k.has(e));if(n.length>0)throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${n.join(`
|
|
24
|
+
`)}\nValid options: ${[...k].join(`, `)}`);for(let e of[`allowSuspicious`,`heal`,`noGitChecks`,`skipFileCheck`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)throw new PublishCleanError(`publish-clean.${e} must be a boolean.`);if(t.registry!==void 0&&assertRegistry(t.registry),stringList(t,`devFields`),stringList(t,`keepFields`),stringList(t,`allowUnreferenced`),renamedFiles(t),t.validateArtifact!==void 0){let e=stringList(t,`validateArtifact`);if(!e[0]?.trim()||e.some(e=>e.includes(`\0`)))throw new PublishCleanError(`publish-clean.validateArtifact must contain an executable followed by optional arguments, without NUL bytes.`)}return t}function stringList(e,t){let n=e[t];if(n===void 0)return[];if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new PublishCleanError(`publish-clean.${t} must be an array of strings.`);return n}function customDevFields(e){let t=stringList(e,`devFields`),n=new Set(stringList(e,`keepFields`)),r=t.filter(e=>n.has(e));if(r.length>0)throw new PublishCleanError(`These fields are listed as both devFields and keepFields, which asks to strip and to publish the same key:\n${r.join(`
|
|
25
25
|
`)}`);let i=t.filter(e=>E.has(e));if(i.length>0)throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${i.join(`
|
|
26
|
-
`)}`);return t}function keptFields(e){return stringList(e,`keepFields`)}function allowedUnreferenced(e){return stringList(e,`allowUnreferenced`)}const A=[[`import`,`require`],[`development`,`production`]],j=4096;var TooComplex=class extends Error{};function spend(e,t=1){if(e.left-=t,e.left<0)throw new TooComplex}function bind(e,t,n){let r=e.get(t);if(r!==void 0)return r===n?e:null;let i=new Map(e);if(i.set(t,n),!n)return i;for(let[e,n]of A){let r=e===t?n:n===t?e:null;if(r!==null){if(i.get(r)===!0)return null;i.set(r,!1)}}return i}function flatten(e,t,n,r){if(e===null){spend(r),n.push({literals:t,target:{kind:`blocked`}});return}if(typeof e==`string`){spend(r),n.push({literals:t,target:{kind:`file`,file:e}});return}if(Array.isArray(e)){spend(r),n.push({literals:t,target:{kind:`opaque`,key:JSON.stringify(e)}});return}if(!isObject(e)){spend(r),n.push({literals:t,target:{kind:`miss`}});return}let i=[t];for(let[t,a]of Object.entries(e)){let e=[];for(let o of i){let i=t==="default"?o:bind(o,t,!0);if(i){let t=[];flatten(a,i,t,r);for(let r of t)r.target.kind===`miss`?e.push(r.literals):n.push(r)}if(t!=="default"){let n=bind(o,t,!1);n&&e.push(n)}}e.length>i.length&&spend(r,e.length-i.length),i=e}for(let e of i)n.push({literals:e,target:{kind:`miss`}})}function rowsOf(e){let t=[];try{flatten(e,new Map,t,{left:j})}catch(e){if(e instanceof TooComplex)return null;throw e}return t}function satisfiable(e,t){for(let[n,r]of e){let e=t.get(n);if(e!==void 0&&e!==r)return!1}return!0}function sameTarget(e,t){return e.kind===t.kind?e.kind===`file`&&t.kind===`file`?e.file===t.file:e.kind===`opaque`&&t.kind===`opaque`?e.key===t.key:!0:!1}function equivalent(e,t){let n=rowsOf(e),r=rowsOf(t);if(!n||!r)return!1;for(let e of n)for(let t of r)if(satisfiable(e.literals,t.literals)&&!sameTarget(e.target,t.target))return!1;return!0}function reachableByAnyConsumer(e){return e.get(`import`)!==!1||e.get(`require`)!==!1}const M=[{forced:!0,names:[`types`]},{forced:!0,names:[`react-server`]},{forced:!0,names:[`andromeda`,`arvancloud`,`azion`,`bun`,`convex`,`deno`,`edge-light`,`edge-routine`,`electron`,`fastly`,`kiesel`,`lagon`,`moddable`,`netlify`,`pythonmonkey`,`quickjs`,`quickjs-ng`,`react-native`,`rhino`,`wasmer`,`workerd`]},{forced:!1,names:[`node-addons`]},{forced:!1,names:[`browser`,`node`]},{forced:!1,names:[`development`,`production`]},{forced:!1,names:[`module-sync`]},{forced:!0,names:[`module`]},{forced:!1,names:[`import`,`require`]},{forced:!0,names:[`default`]}],N=new Map(M.flatMap((e,t)=>e.names.map(e=>[e,t]))),P=new Set([...N.keys(),`style`,`source`,`worker`,`asset`,`sass`,`svelte`]);function conditionRank(e){return N.get(e.startsWith(`types@`)?`types`:e)}function isKnown(e){return P.has(e)||e.startsWith(`types@`)}function forcedOrderConsequence(e){let t=Object.keys(e),n;for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r]??``,o=t[i]??``,s=conditionRank(a),c=conditionRank(o);if(s===void 0||c===void 0||s<=c||a==="default"||!(M[c]?.forced??!1))continue;let l=e[a];if(!(isObject(l)&&Object.hasOwn(l,o))&&JSON.stringify(l)!==JSON.stringify(e[o])&&c!==conditionRank(`types`)){if(o===`module`&&a===`import`)n??=`waste`;else return`breaks`}}return n}function canonicalOrder(e){let t=e.filter(e=>conditionRank(e)!==void 0).map((e,t)=>({key:e,index:t})).sort((e,t)=>(conditionRank(e.key)??0)-(conditionRank(t.key)??0)||e.index-t.index).map(e=>e.key),n=0;return e.map(e=>conditionRank(e)===void 0?e:t[n++]??e)}function reorder(e,t){let n={};for(let r of t)Object.defineProperty(n,r,{...F,value:e[r]});return n}const F={configurable:!0,enumerable:!0,writable:!0};function without(e,t){return reorder(e,Object.keys(e).filter(e=>e!==t))}function leaves(e,t=[]){if(typeof e==`string`)t.push(e);else if(isObject(e))for(let n of Object.values(e))leaves(n,t);return t}function isTypesCondition(e){return conditionRank(e)===conditionRank(`types`)}function repairTypes(e,t,n,r){let hoist=(e,t,i)=>{let a=t.filter(isTypesCondition);if(a.length===0||isTypesCondition(t[0]??``)||containsArray(e))return e;let o=t.slice(0,t.indexOf(a[0]??``));if(o.includes(`default`)||o.some(e=>!isKnown(e)))return e;let reached=t=>leaves(e[t]).some(e=>checkerFinds(r,e)===`declarations`);return!a.some(reached)||o.some(reached)?e:(n.push({rule:`types-branch-unreachable`,consequence:`breaks`,healed:!0,where:i,message:`${a.map(e=>JSON.stringify(e)).join(`, `)} sits behind ${o.map(e=>JSON.stringify(e)).join(`, `)}, and a type checker activates those too, so it takes one of them and finds no declarations there or beside them — the declarations this branch names reach nobody. Moved to the front of this object in the published manifest; no runtime activates "types", so nothing that executes your package can tell. Put "types" first in your package.json to stop this report.`}),reorder(e,[...a,...t.filter(e=>!isTypesCondition(e))]))},visit=(e,t,i)=>{if(typeof e==`string`){if(!i||checkerFinds(r,e)!==`javascript`)return e;n.push({rule:`types-branch-not-declarations`,consequence:`breaks`,healed:!0,where:t,message:`This "types" condition resolves to ${JSON.stringify(e)}, which is not a declaration file and has none shipped beside it, so a checker taking this branch reads JavaScript as the package's API. Removed from the published manifest, which leaves a checker reporting an untyped package instead of the wrong one. Build the declarations and point the branch at them, or delete the condition yourself to stop this report.`});return}if(!isObject(e))return e;let a={},o=!1;for(let[n,r]of Object.entries(e)){let e=visit(r,`${t}[${JSON.stringify(n)}]`,i||isTypesCondition(n));o||=e!==r,e!==void 0&&Object.defineProperty(a,n,{...F,value:e})}let s=Object.keys(a);if(!(s.length===0&&Object.keys(e).length>0))return hoist(o?a:e,s,t)};return visit(e,t,!1)}function healNode(e,t,n){if(Array.isArray(e))return n.push({rule:`exports-fallback-array`,consequence:`waste`,healed:!1,where:t,message:`A fallback array resolves differently across runtimes: Bun fails on [null, …] and on ["not-relative", …] where Node and Deno resolve the next entry. Nothing inside this value is rewritten, and no sibling key of it is either. Replace the array with the single target you mean, if you can.`}),e;if(!isObject(e))return e;let r=!1,i=reorder(e,Object.keys(e));for(let e of Object.keys(i)){let a=healNode(i[e],`${t}[${JSON.stringify(e)}]`,n);r||=a!==i[e],i[e]=a}let a=Object.keys(i),repaired=()=>r?i:e;if(a.length===0||a.some(e=>containsArray(i[e])))return repaired();for(let e of a)isKnown(e)||n.push({rule:`exports-unknown-condition`,consequence:`waste`,healed:!1,where:`${t}[${JSON.stringify(e)}]`,message:`No consumer measured for this tool activates ${JSON.stringify(e)} by default, so only a project that configures it deliberately takes this branch. That is legitimate — private conditions appear in 2.5% of published packages — and nothing here is reordered across it or removed. Reported so a typo cannot hide as a private name.`});for(let e of a){if(Object.keys(i).length<2)break;let a=without(i,e);equivalent(i,a)&&(n.push({rule:`exports-inert-condition`,consequence:`waste`,healed:!0,where:`${t}[${JSON.stringify(e)}]`,message:`This condition resolves to the same target every consumer would reach without it, so it changes nothing and tells nobody anything. Removed from the published manifest. Delete it from your package.json to stop this report.`}),i=a,r=!0)}let o=canonicalOrder(Object.keys(i));if(o.join(`\0`)!==Object.keys(i).join(`\0`)){let e=reorder(i,o);if(equivalent(i,e))n.push({rule:`exports-condition-order`,consequence:`waste`,healed:!0,where:t,message:`Reordered to ${o.map(e=>JSON.stringify(e)).join(`, `)}, which resolves identically for every possible consumer — proven, not assumed. Most specific first: types, then framework and runtime names, then environment, then module system, then default. Apply the same order in your package.json to stop this report.`}),i=e,r=!0;else{let e=forcedOrderConsequence(i);e!==void 0&&n.push({rule:`exports-condition-order-unsafe`,consequence:e,healed:!1,where:t,message:`These keys are out of canonical order and reordering them would change what some consumer resolves, so this tool will not do it: ${Object.keys(i).map(e=>JSON.stringify(e)).join(`, `)}. The order that holds for every measured consumer is ${o.map(e=>JSON.stringify(e)).join(`, `)}. `+(e===`breaks`?`Because a checker also activates node/import/require, and a bundler activates module even under require, and Bun and Deno both activate node, the current order hands at least one of them a file meant for another. Fix it by hand: the branches differ, so only you know which target each consumer should get.`:`What is out of place here costs no consumer another runtime's build: "module" is a bundler's tuned ESM variant losing to the ESM entry point beside it, so both sides of the inversion are ES modules. Fix it by hand — the branches differ, so only you know which target each consumer should get — or use --strict to refuse a publish over it.`)})}}let s=Object.keys(i);if(s.length===1&&s[0]==="default"){let e=i.default;if(equivalent(i,e))return n.push({rule:`exports-redundant-default`,consequence:`waste`,healed:!0,where:t,message:`An object whose only key is "default" resolves exactly as the target it wraps. Replaced with that target in the published manifest; do the same in your package.json.`}),e}return repaired()}function containsArray(e){return Array.isArray(e)?!0:isObject(e)?Object.values(e).some(containsArray):!1}function reportReachability(e,t,n){let r=rowsOf(e);if(!r)return n.push({rule:`exports-too-complex`,consequence:`waste`,healed:!1,where:t,message:`This map has more distinct resolution outcomes than this tool will enumerate (${j}), so nothing inside it was verified, reordered or removed. It is published exactly as written.`}),!1;let i=new Set(r.flatMap(e=>e.target.kind===`file`?[e.target.file]:[])),a=[];collectStrings(e,a);for(let e of a)i.has(e)||n.push({rule:`exports-unreachable-branch`,consequence:`waste`,healed:!1,where:t,message:`No consumer can ever resolve ${JSON.stringify(e)}: it sits after a key that always matches, or behind a combination of conditions that cannot occur together. It is dead code in the manifest — delete the branch, or move it ahead of the key that shadows it.`});return r.some(e=>e.target.kind===`miss`&&reachableByAnyConsumer(e.literals))&&n.push({rule:`exports-unresolvable`,consequence:`waste`,healed:!1,where:t,message:`Some consumer resolves nothing here and fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Edge runtimes (workerd, edge-light, netlify, fastly) activate neither "node" nor "browser", and a bundler targeting neither activates neither, so a map built from environment names alone leaves them with no branch at all. Add a "default" key as the last entry, pointing at the build that works anywhere. Ignore this if excluding those consumers is deliberate — a types-only package resolves nothing at run time by design.`}),!0}function collectStrings(e,t){if(typeof e==`string`)t.push(e);else if(isObject(e))for(let n of Object.values(e))collectStrings(n,t)}function reviewExports(e,t){let{files:n,heal:r}=t,i=[],analyse=(e,t)=>{let a=i.length,withheld=()=>{for(let e=a;e<i.length;e++){let t=i[e];t?.healed&&(i[e]={...t,healed:!1})}return e},o=repairTypes(e,t,i,n)??{};if(!reportReachability(e,t,i))return r?o:withheld();let s=healNode(o,t,i);if(!equivalent(o,s))throw Error(`publish-clean defect: repairing ${t} changed what a consumer resolves. This is a bug in publish-clean, not in your package; publish with --no-heal meanwhile.`);return r?s:withheld()},a=e;for(let t of[`exports`,`imports`]){let n=e[t];if(n==null)continue;if(!isObject(n)||t!==`imports`&&!Object.keys(n).some(e=>e.startsWith(`.`))){let e=analyse(n,t);e!==n&&(a={...a,[t]:e});continue}let r={},i=!1;for(let[e,a]of Object.entries(n)){let n=analyse(a,`${t}[${JSON.stringify(e)}]`);i||=n!==a,Object.defineProperty(r,e,{...F,value:n})}i&&(a={...a,[t]:r})}return{manifest:a,findings:i}}const I=[`code`,`comment`,`text`];function lexicalZones(e){let t=new Uint8Array(e.length),n=[],r=0,i=``,a=0;for(;a<e.length;){let o=e[a]??``,s=e[a+1]??``;if(r===0){if(o===`/`&&s===`/`){t[a]=1,t[a+1]=1,a+=2,r=1,i=`
|
|
27
|
-
`;continue}if(o===`/`&&s===`*`){t[a]=1,t[a+1]=1,a+=2,r=1,i=`*/`;continue}if(o===`"`||o===`'`||o==="`"){t[a]=2,a+=1,r=2,i=o;continue}let e=n.length-1;if(e>=0&&(o===`{`||o===`}`)){let s=n[e]??0;if(o===`}`&&s===0){n.pop(),t[a]=2,a+=1,r=2,i="`";continue}n[e]=o===`{`?s+1:s-1}t[a]=0,a+=1;continue}if(t[a]=r===1?1:2,r===2){if(o===`\\`){t[a+1]=2,a+=2;continue}if(i==="`"&&o===`$`&&s===`{`){t[a+1]=2,n.push(0),a+=2,r=0;continue}o===i&&(r=0),a+=1;continue}if(i===`
|
|
26
|
+
`)}`);return t}function keptFields(e){return stringList(e,`keepFields`)}function allowedUnreferenced(e){return stringList(e,`allowUnreferenced`)}function renamedFiles(e){let t=e.renameFiles;if(t===void 0)return/* @__PURE__ */ new Map;if(!isObject(t)||Object.values(t).some(e=>typeof e!=`string`))throw new PublishCleanError(`publish-clean.renameFiles must be an object mapping a packed path to its published path, e.g. { "AGENTS.consumer.md": "AGENTS.md" }.`);let n=new Map(Object.entries(t)),r=[],i=/* @__PURE__ */ new Map;for(let[e,t]of n){for(let n of[e,t])isPackagePath(n)?n===`package.json`&&r.push(`package.json cannot be renamed: it is the manifest this tool rewrites.`):r.push(`${JSON.stringify(n)} is not a relative file path inside the package (no leading "/" or "./", no "." or ".." segments, no "\\", no trailing "/").`);e===t&&r.push(`${JSON.stringify(e)} is renamed to itself.`);let a=i.get(t);a!==void 0&&r.push(`${JSON.stringify(a)} and ${JSON.stringify(e)} are both renamed to ${JSON.stringify(t)}.`),i.set(t,e),e!==t&&n.has(t)&&r.push(`${JSON.stringify(t)} is both a rename target and a rename source, so the result would depend on the order renames run.`)}if(r.length>0)throw new PublishCleanError(`publish-clean.renameFiles:\n${[...new Set(r)].join(`
|
|
27
|
+
`)}`);return n}function isPackagePath(e){let t=e.split(`/`);return e.length>0&&!e.includes(`\\`)&&!e.includes(`\0`)&&t.every(e=>e!==``&&e!==`.`&&e!==`..`)}const A=[[`import`,`require`],[`development`,`production`]],j=4096;var TooComplex=class extends Error{};function spend(e,t=1){if(e.left-=t,e.left<0)throw new TooComplex}function bind(e,t,n){let r=e.get(t);if(r!==void 0)return r===n?e:null;let i=new Map(e);if(i.set(t,n),!n)return i;for(let[e,n]of A){let r=e===t?n:n===t?e:null;if(r!==null){if(i.get(r)===!0)return null;i.set(r,!1)}}return i}function flatten(e,t,n,r){if(e===null){spend(r),n.push({literals:t,target:{kind:`blocked`}});return}if(typeof e==`string`){spend(r),n.push({literals:t,target:{kind:`file`,file:e}});return}if(Array.isArray(e)){spend(r),n.push({literals:t,target:{kind:`opaque`,key:JSON.stringify(e)}});return}if(!isObject(e)){spend(r),n.push({literals:t,target:{kind:`miss`}});return}let i=[t];for(let[t,a]of Object.entries(e)){let e=[];for(let o of i){let i=t==="default"?o:bind(o,t,!0);if(i){let t=[];flatten(a,i,t,r);for(let r of t)r.target.kind===`miss`?e.push(r.literals):n.push(r)}if(t!=="default"){let n=bind(o,t,!1);n&&e.push(n)}}e.length>i.length&&spend(r,e.length-i.length),i=e}for(let e of i)n.push({literals:e,target:{kind:`miss`}})}function rowsOf(e){let t=[];try{flatten(e,/* @__PURE__ */ new Map,t,{left:j})}catch(e){if(e instanceof TooComplex)return null;throw e}return t}function satisfiable(e,t){for(let[n,r]of e){let e=t.get(n);if(e!==void 0&&e!==r)return!1}return!0}function sameTarget(e,t){return e.kind===t.kind?e.kind===`file`&&t.kind===`file`?e.file===t.file:e.kind===`opaque`&&t.kind===`opaque`?e.key===t.key:!0:!1}function equivalent(e,t){let n=rowsOf(e),r=rowsOf(t);if(!n||!r)return!1;for(let e of n)for(let t of r)if(satisfiable(e.literals,t.literals)&&!sameTarget(e.target,t.target))return!1;return!0}function reachableByAnyConsumer(e){return e.get(`import`)!==!1||e.get(`require`)!==!1}const M=[{forced:!0,names:[`types`]},{forced:!0,names:[`react-server`]},{forced:!0,names:[`andromeda`,`arvancloud`,`azion`,`bun`,`convex`,`deno`,`edge-light`,`edge-routine`,`electron`,`fastly`,`kiesel`,`lagon`,`moddable`,`netlify`,`pythonmonkey`,`quickjs`,`quickjs-ng`,`react-native`,`rhino`,`wasmer`,`workerd`]},{forced:!1,names:[`node-addons`]},{forced:!1,names:[`browser`,`node`]},{forced:!1,names:[`development`,`production`]},{forced:!1,names:[`module-sync`]},{forced:!0,names:[`module`]},{forced:!1,names:[`import`,`require`]},{forced:!0,names:[`default`]}],N=new Map(M.flatMap((e,t)=>e.names.map(e=>[e,t]))),P=/* @__PURE__ */ new Set([...N.keys(),`style`,`source`,`worker`,`asset`,`sass`,`svelte`]);function conditionRank(e){return N.get(e.startsWith(`types@`)?`types`:e)}function isKnown(e){return P.has(e)||e.startsWith(`types@`)}function forcedOrderConsequence(e){let t=Object.keys(e),n;for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r]??``,o=t[i]??``,s=conditionRank(a),c=conditionRank(o);if(s===void 0||c===void 0||s<=c||a==="default"||!(M[c]?.forced??!1))continue;let l=e[a];if(!(isObject(l)&&Object.hasOwn(l,o))&&JSON.stringify(l)!==JSON.stringify(e[o])&&c!==conditionRank(`types`)){if(o===`module`&&a===`import`)n??=`waste`;else return`breaks`}}return n}function canonicalOrder(e){let t=e.filter(e=>conditionRank(e)!==void 0).map((e,t)=>({key:e,index:t})).sort((e,t)=>(conditionRank(e.key)??0)-(conditionRank(t.key)??0)||e.index-t.index).map(e=>e.key),n=0;return e.map(e=>conditionRank(e)===void 0?e:t[n++]??e)}function reorder(e,t){let n={};for(let r of t)Object.defineProperty(n,r,{...F,value:e[r]});return n}const F={configurable:!0,enumerable:!0,writable:!0};function without(e,t){return reorder(e,Object.keys(e).filter(e=>e!==t))}function leaves(e,t=[]){if(typeof e==`string`)t.push(e);else if(isObject(e))for(let n of Object.values(e))leaves(n,t);return t}function isTypesCondition(e){return conditionRank(e)===conditionRank(`types`)}function repairTypes(e,t,n,r){let hoist=(e,t,i)=>{let a=t.filter(isTypesCondition);if(a.length===0||isTypesCondition(t[0]??``)||containsArray(e))return e;let o=t.slice(0,t.indexOf(a[0]??``));if(o.includes(`default`)||o.some(e=>!isKnown(e)))return e;let reached=t=>leaves(e[t]).some(e=>checkerFinds(r,e)===`declarations`);return!a.some(reached)||o.some(reached)?e:(n.push({rule:`types-branch-unreachable`,consequence:`breaks`,healed:!0,where:i,message:`${a.map(e=>JSON.stringify(e)).join(`, `)} sits behind ${o.map(e=>JSON.stringify(e)).join(`, `)}, and a type checker activates those too, so it takes one of them and finds no declarations there or beside them — the declarations this branch names reach nobody. Moved to the front of this object in the published manifest; no runtime activates "types", so nothing that executes your package can tell. Put "types" first in your package.json to stop this report.`}),reorder(e,[...a,...t.filter(e=>!isTypesCondition(e))]))},visit=(e,t,i)=>{if(typeof e==`string`){if(!i||checkerFinds(r,e)!==`javascript`)return e;n.push({rule:`types-branch-not-declarations`,consequence:`breaks`,healed:!0,where:t,message:`This "types" condition resolves to ${JSON.stringify(e)}, which is not a declaration file and has none shipped beside it, so a checker taking this branch reads JavaScript as the package's API. Removed from the published manifest, which leaves a checker reporting an untyped package instead of the wrong one. Build the declarations and point the branch at them, or delete the condition yourself to stop this report.`});return}if(!isObject(e))return e;let a={},o=!1;for(let[n,r]of Object.entries(e)){let e=visit(r,`${t}[${JSON.stringify(n)}]`,i||isTypesCondition(n));o||=e!==r,e!==void 0&&Object.defineProperty(a,n,{...F,value:e})}let s=Object.keys(a);if(!(s.length===0&&Object.keys(e).length>0))return hoist(o?a:e,s,t)};return visit(e,t,!1)}function healNode(e,t,n){if(Array.isArray(e))return n.push({rule:`exports-fallback-array`,consequence:`waste`,healed:!1,where:t,message:`A fallback array resolves differently across runtimes: Bun fails on [null, …] and on ["not-relative", …] where Node and Deno resolve the next entry. Nothing inside this value is rewritten, and no sibling key of it is either. Replace the array with the single target you mean, if you can.`}),e;if(!isObject(e))return e;let r=!1,i=reorder(e,Object.keys(e));for(let e of Object.keys(i)){let a=healNode(i[e],`${t}[${JSON.stringify(e)}]`,n);r||=a!==i[e],i[e]=a}let a=Object.keys(i),repaired=()=>r?i:e;if(a.length===0||a.some(e=>containsArray(i[e])))return repaired();for(let e of a)isKnown(e)||n.push({rule:`exports-unknown-condition`,consequence:`waste`,healed:!1,where:`${t}[${JSON.stringify(e)}]`,message:`No consumer measured for this tool activates ${JSON.stringify(e)} by default, so only a project that configures it deliberately takes this branch. That is legitimate — private conditions appear in 2.5% of published packages — and nothing here is reordered across it or removed. Reported so a typo cannot hide as a private name.`});for(let e of a){if(Object.keys(i).length<2)break;let a=without(i,e);equivalent(i,a)&&(n.push({rule:`exports-inert-condition`,consequence:`waste`,healed:!0,where:`${t}[${JSON.stringify(e)}]`,message:`This condition resolves to the same target every consumer would reach without it, so it changes nothing and tells nobody anything. Removed from the published manifest. Delete it from your package.json to stop this report.`}),i=a,r=!0)}let o=canonicalOrder(Object.keys(i));if(o.join(`\0`)!==Object.keys(i).join(`\0`)){let e=reorder(i,o);if(equivalent(i,e))n.push({rule:`exports-condition-order`,consequence:`waste`,healed:!0,where:t,message:`Reordered to ${o.map(e=>JSON.stringify(e)).join(`, `)}, which resolves identically for every possible consumer — proven, not assumed. Most specific first: types, then framework and runtime names, then environment, then module system, then default. Apply the same order in your package.json to stop this report.`}),i=e,r=!0;else{let e=forcedOrderConsequence(i);e!==void 0&&n.push({rule:`exports-condition-order-unsafe`,consequence:e,healed:!1,where:t,message:`These keys are out of canonical order and reordering them would change what some consumer resolves, so this tool will not do it: ${Object.keys(i).map(e=>JSON.stringify(e)).join(`, `)}. The order that holds for every measured consumer is ${o.map(e=>JSON.stringify(e)).join(`, `)}. `+(e===`breaks`?`Because a checker also activates node/import/require, and a bundler activates module even under require, and Bun and Deno both activate node, the current order hands at least one of them a file meant for another. Fix it by hand: the branches differ, so only you know which target each consumer should get.`:`What is out of place here costs no consumer another runtime's build: "module" is a bundler's tuned ESM variant losing to the ESM entry point beside it, so both sides of the inversion are ES modules. Fix it by hand — the branches differ, so only you know which target each consumer should get — or use --strict to refuse a publish over it.`)})}}let s=Object.keys(i);if(s.length===1&&s[0]==="default"){let e=i.default;if(equivalent(i,e))return n.push({rule:`exports-redundant-default`,consequence:`waste`,healed:!0,where:t,message:`An object whose only key is "default" resolves exactly as the target it wraps. Replaced with that target in the published manifest; do the same in your package.json.`}),e}return repaired()}function containsArray(e){return Array.isArray(e)?!0:isObject(e)?Object.values(e).some(containsArray):!1}function reportReachability(e,t,n){let r=rowsOf(e);if(!r)return n.push({rule:`exports-too-complex`,consequence:`waste`,healed:!1,where:t,message:`This map has more distinct resolution outcomes than this tool will enumerate (${j}), so nothing inside it was verified, reordered or removed. It is published exactly as written.`}),!1;let i=new Set(r.flatMap(e=>e.target.kind===`file`?[e.target.file]:[])),a=[];collectStrings(e,a);for(let e of a)i.has(e)||n.push({rule:`exports-unreachable-branch`,consequence:`waste`,healed:!1,where:t,message:`No consumer can ever resolve ${JSON.stringify(e)}: it sits after a key that always matches, or behind a combination of conditions that cannot occur together. It is dead code in the manifest — delete the branch, or move it ahead of the key that shadows it.`});return r.some(e=>e.target.kind===`miss`&&reachableByAnyConsumer(e.literals))&&n.push({rule:`exports-unresolvable`,consequence:`waste`,healed:!1,where:t,message:`Some consumer resolves nothing here and fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Edge runtimes (workerd, edge-light, netlify, fastly) activate neither "node" nor "browser", and a bundler targeting neither activates neither, so a map built from environment names alone leaves them with no branch at all. Add a "default" key as the last entry, pointing at the build that works anywhere. Ignore this if excluding those consumers is deliberate — a types-only package resolves nothing at run time by design.`}),!0}function collectStrings(e,t){if(typeof e==`string`)t.push(e);else if(isObject(e))for(let n of Object.values(e))collectStrings(n,t)}function reviewExports(e,t){let{files:n,heal:r}=t,i=[],analyse=(e,t)=>{let a=i.length,withheld=()=>{for(let e=a;e<i.length;e++){let t=i[e];t?.healed&&(i[e]={...t,healed:!1})}return e},o=repairTypes(e,t,i,n)??{};if(!reportReachability(e,t,i))return r?o:withheld();let s=healNode(o,t,i);if(!equivalent(o,s))throw Error(`publish-clean defect: repairing ${t} changed what a consumer resolves. This is a bug in publish-clean, not in your package; publish with --no-heal meanwhile.`);return r?s:withheld()},a=e;for(let t of[`exports`,`imports`]){let n=e[t];if(n==null)continue;if(!isObject(n)||t!==`imports`&&!Object.keys(n).some(e=>e.startsWith(`.`))){let e=analyse(n,t);e!==n&&(a={...a,[t]:e});continue}let r={},i=!1;for(let[e,a]of Object.entries(n)){let n=analyse(a,`${t}[${JSON.stringify(e)}]`);i||=n!==a,Object.defineProperty(r,e,{...F,value:n})}i&&(a={...a,[t]:r})}return{manifest:a,findings:i}}const I=[`code`,`comment`,`text`];function lexicalZones(e){let t=new Uint8Array(e.length),n=[],r=0,i=``,a=0;for(;a<e.length;){let o=e[a]??``,s=e[a+1]??``;if(r===0){if(o===`/`&&s===`/`){t[a]=1,t[a+1]=1,a+=2,r=1,i=`
|
|
28
|
+
`;continue}if(o===`/`&&s===`*`){t[a]=1,t[a+1]=1,a+=2,r=1,i=`*/`;continue}if(o===`"`||o===`'`||o==="`"){t[a]=2,a+=1,r=2,i=o;continue}let e=n.length-1;if(e>=0&&(o===`{`||o===`}`)){let s=n[e]??0;if(o===`}`&&s===0){n.pop(),t[a]=2,a+=1,r=2,i="`";continue}n[e]=o===`{`?s+1:s-1}t[a]=0,a+=1}else if(t[a]=r===1?1:2,r===2){if(o===`\\`){t[a+1]=2,a+=2;continue}if(i==="`"&&o===`$`&&s===`{`){t[a+1]=2,n.push(0),a+=2,r=0;continue}o===i&&(r=0),a+=1}else{if(i===`
|
|
28
29
|
`&&o===`
|
|
29
|
-
`)r=0;else if(i===`*/`&&o===`*`&&s===`/`){t[a+1]=1,a+=2,r=0;continue}a+=1}return n.length>0?null:r===0||r===1&&i===`
|
|
30
|
-
`?t:null}function zoneAt(e,t){return I[e[t]??0]??`code`}const L=/\bdeclare\s+module\s+("|')([^"']+)\1/g,R=[/(?:^|\/|\.)(?:readme|licen[cs]e|copying|notice|changelog|history|authors|contributors)/i,/(?:^|\/)package\.json$/,/\.(?:md|markdown|txt|map|node|wasm|flow)$/i,/\.(?:css|s[ac]ss|less|html?|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|otf)$/i,/^(?:prebuilds|native|build|man|bin)\//i,b],z=/(?:from\s*|require\s*\(\s*|import\s*\(?\s*|URL\s*\(\s*|sourceMappingURL=)['"`]?(\.[^'"`\s)]+)/g;function targetsUnder(e,t,n,r){let walk=(e,i)=>{if(typeof e==`string`)
|
|
30
|
+
`)r=0;else if(i===`*/`&&o===`*`&&s===`/`){t[a+1]=1,a+=2,r=0;continue}a+=1}}return n.length>0?null:r===0||r===1&&i===`
|
|
31
|
+
`?t:null}function zoneAt(e,t){return I[e[t]??0]??`code`}const L=/\bdeclare\s+module\s+("|')([^"']+)\1/g,R=[/(?:^|\/|\.)(?:readme|licen[cs]e|copying|notice|changelog|history|authors|contributors)/i,/(?:^|\/)package\.json$/,/\.(?:md|markdown|txt|map|node|wasm|flow)$/i,/\.(?:css|s[ac]ss|less|html?|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|otf)$/i,/^(?:prebuilds|native|build|man|bin)\//i,b],z=/(?:from\s*|require\s*\(\s*|import\s*\(?\s*|URL\s*\(\s*|sourceMappingURL=)['"`]?(\.[^'"`\s)]+)/g;function targetsUnder(e,t,n,r){let walk=(e,i)=>{if(typeof e==`string`)i&&n.push(e);else if(Array.isArray(e))for(let t of e)walk(t,i);else if(isObject(e))for(let[n,a]of Object.entries(e))n!==r&&walk(a,i||n===t||n.startsWith(`${t}@`))};walk(e,!1)}function selfSpecifiers(e){let t=`(${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}(?:/[^'"\`]*)?)`;return[RegExp(`(?:from|import)\\s*(['"])${t}\\1`,`g`),RegExp(`(?:require|import)\\s*\\(\\s*(['"\`])${t}\\1`,`g`)]}function exposes(e,t){if(typeof e==`string`||Array.isArray(e))return t===`.`;if(!isObject(e))return!1;let n=Object.keys(e);if(!n.some(e=>e.startsWith(`.`)))return t===`.`;for(let r of n){let n=r.indexOf(`*`);if(!(n===-1?r===t:t.length>=r.length-1&&t.startsWith(r.slice(0,n))&&t.endsWith(r.slice(n+1))))continue;let i=rowsOf(e[r]);return i===null||i.some(e=>e.target.kind===`file`||e.target.kind===`opaque`)}return!1}function reviewSelfReferences(e,t){let n=e.name;if(typeof n!=`string`||e.exports===void 0)return[];let r=[],i=selfSpecifiers(n),a=/* @__PURE__ */ new Set;for(let[o,s]of t){if(!x.test(o))continue;let t=s.toString(`utf8`);if(!t.includes(n))continue;let c=lexicalZones(t);if(c===null)continue;let l=/* @__PURE__ */ new Set;for(let e of t.matchAll(L)){let t=zoneAt(c,e.index);t!==`text`&&t!==`comment`&&l.add(e[2]??``)}for(let s of i)for(let i of t.matchAll(s)){let s=zoneAt(c,i.index);if(s===`text`||s===`comment`&&!/^import\s*\(/.test(i[0]))continue;let u=t.lastIndexOf(`
|
|
31
32
|
`,i.index)+1,d=t.indexOf(`
|
|
32
|
-
`,i.index),f=t.slice(u,d===-1?void 0:d).trim(),p=i[2]??``,m=p===n?`.`:`.${p.slice(n.length)}`;l.has(p)||exposes(e.exports,m)||a.has(p)||(a.add(p),r.push({rule:`self-import-not-exported`,consequence:`breaks`,healed:!1,where:o,message:`${JSON.stringify(p)} is this package importing itself, and "exports" does not expose ${JSON.stringify(m)}, so it resolves to nothing for every consumer — a type checker reports TS2307 in a file they cannot edit, or silently types it as any. Inside this repository the same import resolves through the source tree, which is why it looks fine here. Add the subpath:\n "exports": { ${JSON.stringify(m)}: "./<the file it means>" }\nor rewrite the import as a relative path. Found at: ${f.slice(0,120)}`}))}}return r}function entry(e,t){let n=normalizeDeclaredPath(t);return n===null?void 0:e.get(n)}function reviewShippedFiles(e,t){let n=[],r=[e.exports,e.imports],i=[];for(let e of r)targetsUnder(e,`require`,i,`module`);for(let e of new Set(i)){if(b.test(e)||!x.test(e))continue;let r=entry(t,e);r&&!isCommonJs(r.toString(`utf8`))&&n.push({rule:`require-branch-is-esm`,consequence:`breaks`,healed:!1,where:`exports "require" -> ${e}`,message:`A "require" condition resolves to ${JSON.stringify(e)}, which uses ES module syntax. Node can require an ES module only from ^20.19.0 || >=22.12.0, a consumer can still refuse with --no-experimental-require-module, and top-level await fails on every version with ERR_REQUIRE_ASYNC_MODULE. Point "require" at a CommonJS build, or add a "module-sync" branch — that condition exists so require() and import can load one ES module.`})}let a
|
|
33
|
+
`,i.index),f=t.slice(u,d===-1?void 0:d).trim(),p=i[2]??``,m=p===n?`.`:`.${p.slice(n.length)}`;l.has(p)||exposes(e.exports,m)||a.has(p)||(a.add(p),r.push({rule:`self-import-not-exported`,consequence:`breaks`,healed:!1,where:o,message:`${JSON.stringify(p)} is this package importing itself, and "exports" does not expose ${JSON.stringify(m)}, so it resolves to nothing for every consumer — a type checker reports TS2307 in a file they cannot edit, or silently types it as any. Inside this repository the same import resolves through the source tree, which is why it looks fine here. Add the subpath:\n "exports": { ${JSON.stringify(m)}: "./<the file it means>" }\nor rewrite the import as a relative path. Found at: ${f.slice(0,120)}`}))}}return r}function entry(e,t){let n=normalizeDeclaredPath(t);return n===null?void 0:e.get(n)}function reviewShippedFiles(e,t){let n=[],r=[e.exports,e.imports],i=[];for(let e of r)targetsUnder(e,`require`,i,`module`);for(let e of new Set(i)){if(b.test(e)||!x.test(e))continue;let r=entry(t,e);r&&!isCommonJs(r.toString(`utf8`))&&n.push({rule:`require-branch-is-esm`,consequence:`breaks`,healed:!1,where:`exports "require" -> ${e}`,message:`A "require" condition resolves to ${JSON.stringify(e)}, which uses ES module syntax. Node can require an ES module only from ^20.19.0 || >=22.12.0, a consumer can still refuse with --no-experimental-require-module, and top-level await fails on every version with ERR_REQUIRE_ASYNC_MODULE. Point "require" at a CommonJS build, or add a "module-sync" branch — that condition exists so require() and import can load one ES module.`})}let a=/* @__PURE__ */ new Set,o=[];collectDeclaredPaths(e.bin,o,`every-string`);for(let e of o){let t=normalizeDeclaredPath(e);t!==null&&a.add(t)}for(let[e,r]of t){if(!r.subarray(0,2).equals(Buffer.from(`#!`))||!r.subarray(0,r.indexOf(10)+1||r.length).includes(13))continue;let t=a.has(e);n.push({rule:`shebang-carriage-return`,consequence:t?`breaks`:`waste`,healed:!1,where:e,message:`The shebang line ends with a carriage return, so running this file fails with "env: node\\r: No such file or directory" on Linux and macOS. Nothing here rewrites it — this tool alters the manifest and no other file's contents — so fix the line endings at the source: add a .gitattributes entry marking it "text eol=lf", or set your bundler to emit LF.`+(t?` "bin" names this file as a command, so an installer symlinks it and every consumer gets that failure.`:` No "bin" entry names this file, so nothing executes it through the kernel and the publish is not refused over it. Use --strict to refuse anyway.`)})}for(let e of a){let r=t.get(e);r!==void 0&&(r.subarray(0,2).toString()===`#!`||r.subarray(0,512).includes(0)||n.push({rule:`bin-no-shebang`,consequence:`breaks`,healed:!1,where:e,message:`"bin" names this file as a command, but its first line is not a shebang, so the symlink an installer creates for it cannot be executed: the command fails with "exec format error" on Linux and macOS, and npm has no interpreter to write into its Windows shim. Add "#!/usr/bin/env node" as the first line. Nothing here rewrites it — this tool alters the manifest and no other file's contents.`}))}return n}function isCommonJs(e){try{return new f(e),!0}catch{return!1}}function reviewUnreferencedFiles(e,t,n){if(e.exports===void 0)return[];let r=/* @__PURE__ */ new Set,i=[],a=[],o=Buffer.alloc(0),s,c,l,inCode=(e,t,n)=>(l?.file!==t&&(l={file:t,zones:lexicalZones(e)}),l.zones!==null&&zoneAt(l.zones,n)===`code`),visit=(e,n,l,u)=>{let d=e.replace(/[?#].*$/,``),f=d.startsWith(`./`)||d.startsWith(`../`),p=normalizeDeclaredPath(f?joinFrom(n,d):d);if(p===null)return;let m=expand(p,t);if(m.length===0&&f&&n!==``&&!p.includes(`*`)&&l!==void 0&&u!==void 0&&inCode(l,n,u)){s??=new Map([...t.keys()].map(e=>[foldName(e),e])),c??=new Map([...s.keys()].map(e=>[e,o]));let l=expand(foldName(p),c).map(e=>s?.get(e)).find(e=>e!==void 0);l!==void 0&&(a.push(` ${n} imports ${JSON.stringify(e)}, shipped as ${l}`),r.has(l)||(r.add(l),i.push(l)))}for(let e of m)r.has(e)||(r.add(e),i.push(e))},u=[];for(let t of[`main`,`module`,`types`,`typings`,`bin`,`exports`,`imports`,`man`])collectDeclaredPaths(e[t],u,`every-string`);collectDeclaredPaths(e.browser,u,typeof e.browser==`string`?`every-string`:`relative-only`);for(let e of u)visit(e,``);if(isObject(e.scripts)){for(let t of Object.values(e.scripts))if(typeof t==`string`)for(let e of t.split(/[\s'"=;&|()<>]+/))visit(e,``)}for(;i.length>0;){let e=i.pop();if(e===void 0)continue;let n=t.get(e);if(n===void 0||!(x.test(e)||n.subarray(0,2).toString()===`#!`))continue;let r=n.toString(`utf8`);for(let t of r.matchAll(z))t[1]!==void 0&&visit(t[1],e,r,t.index)}let d=[];a.length>0&&d.push({rule:`import-case-mismatch`,consequence:`breaks`,healed:!1,where:countOf(a.length,`import`),message:`These imports resolve only because the filesystem this was built on ignores letter case or Unicode form. Where one does not, the import fails and the package is broken for that consumer:\n${a.join(`
|
|
33
34
|
`)}\nRename the import or the file so the two match byte for byte.`});let f=[...t].filter(([e])=>!r.has(e)).filter(([e])=>!R.some(t=>t.test(e))).filter(([e])=>!n.some(t=>e===t||e.startsWith(t))).sort((e,t)=>t[1].length-e[1].length);if(f.length===0)return d;let p=f.reduce((e,[,t])=>e+t.length,0),m=f.map(([e,t])=>` ${e} (${Math.ceil(t.length/1024)} KB)`);return d.push({rule:`unreferenced-file`,consequence:`waste`,rulesAbort:!0,healed:!1,where:`${countOf(f.length,`file`)}, ${Math.ceil(p/1024)} KB`,message:`Nothing in this package reaches these files — no manifest field names them and no shipped file imports them — so every consumer downloads them forever for nothing:
|
|
34
35
|
${m.join(`
|
|
35
|
-
`)}\nRemove them from the "files" array in your package.json. If one is genuinely used in a way no import records — spawned as a child process, loaded by a native addon, read at run time — declare it instead:\n "publish-clean": { "allowUnreferenced": [${f.map(([e])=>JSON.stringify(e)).join(`, `)}] }`}),d}function joinFrom(e,t){return`${e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``}${t}`}function expand(e,t){if(e.includes(`*`)){let n=e.split(`*`);return[...t.keys()].filter(t=>t.length>=e.length-1&&t.startsWith(n[0]??``)&&t.endsWith(n.at(-1)??``))}if(t.has(e))return[e];let n=e.replace(/\.([cm]?)js$/,`.$1ts`),r=e.replace(/\.([cm]?)js$/,`.d.$1ts`);return(n===e?[e]:[e,n,n.replace(/ts$/,`tsx`),r]).flatMap(e=>[``,`.js`,`.mjs`,`.cjs`,`.ts`,`.mts`,`.cts`,`.tsx`,`.json`,`.node`,`.d.ts`].flatMap(t=>[e+t,`${e}/index${t}`]).concat(e)).filter(e=>t.has(e))}const B
|
|
36
|
+
`)}\nRemove them from the "files" array in your package.json. If one is genuinely used in a way no import records — spawned as a child process, loaded by a native addon, read at run time — declare it instead:\n "publish-clean": { "allowUnreferenced": [${f.map(([e])=>JSON.stringify(e)).join(`, `)}] }`}),d}function joinFrom(e,t){return`${e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``}${t}`}function expand(e,t){if(e.includes(`*`)){let n=e.split(`*`);return[...t.keys()].filter(t=>t.length>=e.length-1&&t.startsWith(n[0]??``)&&t.endsWith(n.at(-1)??``))}if(t.has(e))return[e];let n=e.replace(/\.([cm]?)js$/,`.$1ts`),r=e.replace(/\.([cm]?)js$/,`.d.$1ts`);return(n===e?[e]:[e,n,n.replace(/ts$/,`tsx`),r]).flatMap(e=>[``,`.js`,`.mjs`,`.cjs`,`.ts`,`.mts`,`.cts`,`.tsx`,`.json`,`.node`,`.d.ts`].flatMap(t=>[e+t,`${e}/index${t}`]).concat(e)).filter(e=>t.has(e))}const B=/* @__PURE__ */ new Map([[`access`,`string`],[`tag`,`string`],[`otp`,`string`],[`registry`,`string`],[`provenance-file`,`string`],[`provenance`,`boolean`],[`dry-run`,`boolean`],[`ignore-scripts`,`boolean`],[`json`,`boolean`],[`loglevel`,`string`]]);function publicationArgs(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??``,i=r.indexOf(`=`),a=i<0?r:r.slice(0,i),o=a.startsWith(`--no-`),s=a.slice(o?5:2),c=a.startsWith(`--`)?B.get(s):void 0;if(!c||o&&c!==`boolean`)throw new PublishCleanError(`After --, use publication options only: ${[...B.keys()].join(`, `)}. Package operands and workspace selectors are forbidden.`);let l=i<0?void 0:r.slice(i+1);if(l===void 0&&(c===`string`||e[n+1]===`true`||e[n+1]===`false`)&&(l=e[++n]),c===`boolean`){if(l??=`true`,l!==`true`&&l!==`false`)throw new PublishCleanError(`--${s} requires true or false.`);o&&(l=l===`true`?`false`:`true`)}else if(!l||l.startsWith(`-`))throw new PublishCleanError(`--${s} requires a value that does not start with -. Use ./ for a filename starting with -.`);s===`registry`&&assertRegistry(l),t.push(`--${s}=${l}`)}return t}const V=`publish-clean [options] [package-dir] [-- npm publish args]
|
|
36
37
|
publish-clean verify [package-dir]
|
|
37
38
|
|
|
38
39
|
Packs with pnpm, strips developer-only fields from the packed manifest, validates the
|
|
@@ -65,6 +66,8 @@ Manifest configuration, under a "publish-clean" key in package.json:
|
|
|
65
66
|
allowUnreferenced string[] Shipped files nothing imports on purpose: a binary a loader finds by
|
|
66
67
|
path, a directory read at run time. Matched as a prefix, so naming a
|
|
67
68
|
directory covers everything under it.
|
|
69
|
+
renameFiles object Packed path to published path, e.g. {"AGENTS.consumer.md": "AGENTS.md"}.
|
|
70
|
+
pnpm still selects the file; only its name in the tarball changes.
|
|
68
71
|
noGitChecks boolean Default for --no-git-checks.
|
|
69
72
|
skipFileCheck boolean Default for --skip-file-check.
|
|
70
73
|
allowSuspicious boolean Default for --allow-suspicious.
|
|
@@ -72,7 +75,7 @@ Manifest configuration, under a "publish-clean" key in package.json:
|
|
|
72
75
|
Preview modes do not test registry access, credentials or provenance eligibility.
|
|
73
76
|
Requires pnpm on PATH; npm as well to publish, since only the upload uses it. npm
|
|
74
77
|
provenance additionally requires Node.js 22.14+ and npm 11.5.1+, and only a cloud CI
|
|
75
|
-
runner can produce it.`,H={"allow-suspicious":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},"guard-only":{type:`boolean`,default:!1},help:{type:`boolean`,short:`h`,default:!1},"no-git-checks":{type:`boolean`,default:!1},"no-heal":{type:`boolean`,default:!1},registry:{type:`string`,default:void 0},"skip-file-check":{type:`boolean`,default:!1},strict:{type:`boolean`,default:!1},"tarball-out":{type:`string`,default:void 0},"verify-only":{type:`boolean`,default:!1},version:{type:`boolean`,short:`v`,default:!1}};function parseOptions(e){let t=e.indexOf(`--`),n=t===-1?e:e.slice(0,t),r=publicationArgs(t===-1?[]:e.slice(t+1)),i;try{i=p({args:n,allowPositionals:!0,options:H,strict:!0})}catch(e){throw new PublishCleanError(`${e instanceof Error?e.message.split(`. `)[0]:String(e)}.\npublish-clean accepts: ${Object.keys(H).map(e=>`--${e}`).join(`, `)}.\nRun publish-clean --help for what each one does. Arguments meant for \`npm publish\` go after a \`--\` separator.`)}let a=i.positionals[0]===`verify`?i.positionals.slice(1):i.positionals,o=a!==i.positionals||i.values[`verify-only`]===!0;return{...i,positionals:a,publishArgs:r,verify:o}}const U=`package/package.json`,W=new Set([`x`,`g`]),G=new Set([...W,`L`]),K=new TextDecoder(`utf-8`,{fatal:!0});function field(e,t,n){let r=e.subarray(t,t+n),i=r.indexOf(0);return K.decode(i<0?r:r.subarray(0,i))}function entrySize(e){let t=field(e,124,12).trim();if(!/^[0-7]+$/.test(t))throw new PublishCleanError(`Tarball entry has an unreadable size field.`);return Number.parseInt(t,8)}function paxFields(e){let t=new Map;for(let n=0;n<e.length;){let r=e.indexOf(32,n),i=e.toString(`ascii`,n,r<0?n:r),a=Number(i),o=n+a,s=e.indexOf(61,r+1);if(!/^[1-9][0-9]*$/.test(i)||!Number.isSafeInteger(a)||o>e.length||s<=r+1||s>=o-1||e[o-1]!==10)throw new PublishCleanError(`Tarball has a malformed PAX record.`);let c=K.decode(e.subarray(r+1,s)),l=K.decode(e.subarray(s+1,o-1));if(c.includes(`sparse`)||c===`hdrcharset`)throw new PublishCleanError(`Tarball uses unsupported PAX ${c}.`);t.set(c,l),n=o}return t}function assertChecksum(e,t){let n=Number.parseInt(field(e,148,8).trim(),8),r=0,i=0;for(let[t,n]of e.entries()){let e=t>=148&&t<156?32:n;r+=e,i+=e>127?e-256:e}if(n!==r&&n!==i)throw new PublishCleanError(`Tarball entry ${t} has a corrupt header checksum.`)}function gnuLongName(e){let t=e.length;for(;t>0&&e[t-1]===0;)--t;if(t===0)throw new PublishCleanError(`Tarball has an empty GNU long-name entry.`);return K.decode(e.subarray(0,t))}function reheader(e,t){let n=Buffer.from(e);n.write(t.toString(8).padStart(11,`0`)+`\0`,124,12,`ascii`),n.write(` `.repeat(8),148,8,`ascii`);let r=0;for(let e of n)r+=e;return n.write(r.toString(8).padStart(6,`0`)+`\0 `,148,8,`ascii`),n}function readArchive(e){let t=m(e),n=[],r=new Set,i=null,a=null;for(let e=0;e<t.length;){let o=t.subarray(e,e+512);if(o.length<512)throw new PublishCleanError(`Tarball ends mid-header; the archive is truncated.`);if(o.every(e=>e===0)){if(a=t.subarray(e),a.length<1024||a.length%512||a.some(e=>e!==0))throw new PublishCleanError(`Tarball has an invalid end-of-archive marker.`);break}let s=field(o,156,1),c=[field(o,257,6)===`ustar`?field(o,345,155):``,field(o,0,100)].filter(Boolean).join(`/`);assertChecksum(o,c);let l=W.has(s),u=l?c:i?.get(`path`)||c,d=entrySize(o),f=!l&&i?.get(`size`);if(f){if(!/^[0-9]+$/.test(f)||!Number.isSafeInteger(Number(f)))throw new PublishCleanError(`Tarball has an invalid PAX size.`);d=Number(f)}let p=e+512+512*Math.ceil(d/512);if(!Number.isSafeInteger(p)||p>t.length)throw new PublishCleanError(`Tarball entry ${JSON.stringify(u)} runs past the end of the archive.`);let m=t.subarray(e+512,e+512+d);if(s===`L`){if(i)throw new PublishCleanError(`Tarball has consecutive extended headers.`);let e=gnuLongName(m);if(e===U)throw new PublishCleanError(`Tarball contains a GNU long-name header renaming an entry to ${U}.`);i=new Map([[`path`,e]])}else if(l){let e=paxFields(m);if(e.get(`path`)===U)throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${U}.`);if(s===`g`){if([`path`,`size`,`linkpath`].some(t=>e.has(t)))throw new PublishCleanError(`Tarball has a global PAX path, linkpath or size override.`)}else{if(i)throw new PublishCleanError(`Tarball has consecutive extended headers.`);i=e}}else{if(u===U){if(s!==`0`&&s!==``)throw new PublishCleanError(`${U} is not a regular file in the tarball.`);if(f)throw new PublishCleanError(`Tarball manifest has a PAX size override that cannot survive rewriting.`)}let e=u.replace(/\/$/,``).split(`/`);if(e[0]!==`package`||e.some(e=>!e||e===`.`||e===`..`)||u.includes(`\\`)||u.includes(`\0`))throw new PublishCleanError(`Tarball has an unsafe entry path: ${JSON.stringify(u)}.`);if(r.has(u))throw new PublishCleanError(`Tarball contains ${JSON.stringify(u)} more than once.`);r.add(u),i=null}n.push({name:u,type:s,header:o,body:m,raw:t.subarray(e,p)}),e=p}if(a===null)throw new PublishCleanError(`Tarball has no end-of-archive marker; the archive is truncated.`);if(i)throw new PublishCleanError(`Tarball ends with an unused extended header.`);return{entries:n,tail:a}}function assertPreservedArchive(e,t){if(e.entries.length!==t.entries.length||!e.tail.equals(t.tail))throw new PublishCleanError(`Rewriting the manifest changed the archive structure.`);for(let[n,r]of e.entries.entries()){let e=t.entries[n];if(!e||r.name!==e.name||r.type!==e.type||(r.name===U&&!G.has(r.type)?!reheader(r.header,e.body.length).equals(e.header):!r.raw.equals(e.raw)))throw new PublishCleanError(`Rewriting the manifest changed archive entry ${JSON.stringify(r.name)}.`)}}function packageFiles(e){return installedEntries(e).map(e=>e.name).sort()}function installedEntries(e){return e.entries.filter(e=>e.type!==`5`&&!G.has(e.type)).map(e=>({name:e.name.startsWith(`package/`)?e.name.slice(8):e.name,body:e.body})).filter(e=>e.name.length>0&&!e.name.endsWith(`/`))}function packageContents(e){return new Map(installedEntries(e).map(e=>[e.name,e.body]))}function manifestEntry(e){let t=e.entries.find(e=>e.name===U&&!G.has(e.type));if(!t)throw new PublishCleanError(`Tarball does not contain ${U}.`);return t}function manifestText(e){return manifestEntry(e).body.toString(`utf8`)}function replaceManifest(e,t){let n=manifestEntry(e),r=Buffer.from(t,`utf8`),i=e.entries.map(e=>e===n?Buffer.concat([reheader(e.header,r.length),r,Buffer.alloc(512*Math.ceil(r.length/512)-r.length)]):e.raw);return i.push(e.tail),h(Buffer.concat(i),{level:9})}const q=[11,5,1],J=[22,14,0];function isAtLeast(e,t){for(let n of[0,1,2]){if(e[n]>t[n])return!0;if(e[n]<t[n])return!1}return!0}function wantsTrustedPublish(e,t,n){if(n.GITHUB_ACTIONS===`true`&&typeof n.ACTIONS_ID_TOKEN_REQUEST_URL==`string`)return!0;for(let e=t.length-1;e>=0;e--){if(t[e]===`--provenance=true`||t[e]===`--provenance`)return!0;if(t[e]===`--provenance=false`)return!1}if(isObject(e.publishConfig)&&e.publishConfig.provenance!==void 0)return!!e.publishConfig.provenance}function repositoryUrl(e){return typeof e.repository==`string`?e.repository:isObject(e.repository)&&typeof e.repository.url==`string`?e.repository.url:null}function githubRepositorySlug(e){let t=e.startsWith(`git+`)?e.slice(4):e;if(t.startsWith(`git@github.com:`)){let e=t.slice(15);return e.endsWith(`.git`)?e.slice(0,-4):e}try{let e=new URL(t);if(e.hostname!==`github.com`)return null;let n=e.pathname.replace(/^\/+/,``);return n.endsWith(`.git`)?n.slice(0,-4):n}catch{return null}}function assertRepositoryForTrustedPublish(e,t){if(t.GITHUB_ACTIONS!==`true`||typeof t.GITHUB_REPOSITORY!=`string`)return;let n=repositoryUrl(e);if(!n)throw new PublishCleanError(`GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.`);if(githubRepositorySlug(n)!==t.GITHUB_REPOSITORY)throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${t.GITHUB_REPOSITORY}); found ${n}.`)}function ownVersion(){let e=readJson(u(new URL(`../package.json`,import.meta.url)));return typeof e.version==`string`?e.version:`unknown`}function readJson(t){let n;try{n=e(t,`utf8`)}catch(e){throw new PublishCleanError(`Unable to read ${t}. Run publish-clean from a package directory, or name one as the first argument.`,{cause:e})}let r;try{r=JSON.parse(n)}catch(e){throw new PublishCleanError(`Unable to parse JSON file: ${t}`,{cause:e})}if(!isObject(r))throw new PublishCleanError(`${t} must contain a JSON object.`);return r}function toolVersion(e,t){let n=t.trim().replace(/^v/,``),r=n.split(`.`).map(e=>Number.parseInt(e,10));if(r.length<3||r.some(e=>Number.isNaN(e)))throw new PublishCleanError(`Unable to parse ${e} version: ${n}`);return[r[0]??0,r[1]??0,r[2]??0]}function publishEnv(){return{ACTIONS_ID_TOKEN_REQUEST_URL:process.env.ACTIONS_ID_TOKEN_REQUEST_URL,GITHUB_ACTIONS:process.env.GITHUB_ACTIONS,GITHUB_REPOSITORY:process.env.GITHUB_REPOSITORY}}async function assertTrustedPublishingRuntime(e,t,n){let r=toolVersion(`npm`,t);if(!isAtLeast(r,q))throw new PublishCleanError(`Trusted npm publishing requires npm ${q.join(`.`)} or newer; found ${r.join(`.`)}.`);let i=toolVersion(`node`,await requireTool(`node`,e,n));if(!isAtLeast(i,J))throw new PublishCleanError(`Trusted npm publishing requires Node.js ${J.join(`.`)} or newer; found ${i.join(`.`)}.`)}function warnIfNonPnpmLifecycle(){let e=process.env.npm_config_user_agent;e&&!e.startsWith(`pnpm/`)&&console.warn(`${O} Detected lifecycle user agent: ${e}`)}async function uncommittedChangesRefusal(e,t,n){if(t)return null;let r;try{r=(await run(`git`,[`status`,`--porcelain`,`--`,`.`],e,{signal:n})).trim()}catch(t){if(n.aborted)throw t;return console.warn(`publish-clean: skipping the uncommitted-changes check — ${t instanceof Error?t.message:String(t)}\nExpected a Git checkout at ${e}? Then this publishes source that was never compared against a commit.`),null}return r?`Source package has uncommitted changes:\n${r}`:null}async function readTarball(e){return readArchive(await i(e))}function manifestOf(e,t){let n;try{n=JSON.parse(manifestText(e))}catch(e){throw new PublishCleanError(`Unable to parse package.json inside ${t}.`,{cause:e})}if(!isObject(n))throw new PublishCleanError(`package.json inside ${t} must contain a JSON object.`);return n}async function soleTarball(e){let t=(await a(e)).filter(e=>e.endsWith(`.tgz`)),[n]=t;if(t.length!==1||!n)throw new PublishCleanError(`pnpm pack left ${t.length} tarballs in ${e}; expected exactly one.`);return l.join(e,n)}async function packAndClean(e,a,u){let d=readJson(l.join(e,`package.json`));await requireTool(`pnpm`,e,a),warnIfNonPnpmLifecycle();let f=packageConfig(d),p=u.skipFileCheck||f.skipFileCheck===!0,m=u.allowSuspicious||f.allowSuspicious===!0,h=u.noGitChecks||f.noGitChecks===!0,g=u.registry??(typeof f.registry==`string`?f.registry:null),_=customDevFields(f),v=keptFields(f),y=allowedUnreferenced(f),b=[u.verify?null:privatePackageRefusal(d),await uncommittedChangesRefusal(e,h,a),filesFieldRefusal(d,p)].filter(e=>e!==null);if(b.length>0)throw new PublishCleanError(b.join(`
|
|
78
|
+
runner can produce it.`,H={"allow-suspicious":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},"guard-only":{type:`boolean`,default:!1},help:{type:`boolean`,short:`h`,default:!1},"no-git-checks":{type:`boolean`,default:!1},"no-heal":{type:`boolean`,default:!1},registry:{type:`string`,default:void 0},"skip-file-check":{type:`boolean`,default:!1},strict:{type:`boolean`,default:!1},"tarball-out":{type:`string`,default:void 0},"verify-only":{type:`boolean`,default:!1},version:{type:`boolean`,short:`v`,default:!1}};function parseOptions(e){let t=e.indexOf(`--`),n=t===-1?e:e.slice(0,t),r=publicationArgs(t===-1?[]:e.slice(t+1)),i;try{i=p({args:n,allowPositionals:!0,options:H,strict:!0})}catch(e){throw new PublishCleanError(`${e instanceof Error?e.message.split(`. `)[0]:String(e)}.\npublish-clean accepts: ${Object.keys(H).map(e=>`--${e}`).join(`, `)}.\nRun publish-clean --help for what each one does. Arguments meant for \`npm publish\` go after a \`--\` separator.`)}let a=i.positionals[0]===`verify`?i.positionals.slice(1):i.positionals,o=a!==i.positionals||i.values[`verify-only`]===!0;return{...i,positionals:a,publishArgs:r,verify:o}}const U=`package/package.json`,W=/* @__PURE__ */ new Set([`x`,`g`]),G=/* @__PURE__ */ new Set([...W,`L`]),K=new TextDecoder(`utf-8`,{fatal:!0});function field(e,t,n){let r=e.subarray(t,t+n),i=r.indexOf(0);return K.decode(i<0?r:r.subarray(0,i))}function isUstar(e){return field(e,257,6)===`ustar`}function entrySize(e){let t=field(e,124,12).trim();if(!/^[0-7]+$/.test(t))throw new PublishCleanError(`Tarball entry has an unreadable size field.`);return Number.parseInt(t,8)}function paxFields(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){let r=e.indexOf(32,n),i=e.toString(`ascii`,n,r<0?n:r),a=Number(i),o=n+a,s=e.indexOf(61,r+1);if(!/^[1-9][0-9]*$/.test(i)||!Number.isSafeInteger(a)||o>e.length||s<=r+1||s>=o-1||e[o-1]!==10)throw new PublishCleanError(`Tarball has a malformed PAX record.`);let c=K.decode(e.subarray(r+1,s)),l=K.decode(e.subarray(s+1,o-1));if(c.includes(`sparse`)||c===`hdrcharset`)throw new PublishCleanError(`Tarball uses unsupported PAX ${c}.`);t.set(c,l),n=o}return t}function assertChecksum(e,t){let n=Number.parseInt(field(e,148,8).trim(),8),r=0,i=0;for(let[t,n]of e.entries()){let e=t>=148&&t<156?32:n;r+=e,i+=e>127?e-256:e}if(n!==r&&n!==i)throw new PublishCleanError(`Tarball entry ${t} has a corrupt header checksum.`)}function gnuLongName(e){let t=e.length;for(;t>0&&e[t-1]===0;)--t;if(t===0)throw new PublishCleanError(`Tarball has an empty GNU long-name entry.`);return K.decode(e.subarray(0,t))}function reheader(e,t){let n=Buffer.from(e);return n.write(t.toString(8).padStart(11,`0`)+`\0`,124,12,`ascii`),seal(n)}function seal(e){e.write(` `.repeat(8),148,8,`ascii`);let t=0;for(let n of e)t+=n;return e.write(t.toString(8).padStart(6,`0`)+`\0 `,148,8,`ascii`),e}function memberIndex(e,t){return e.entries.findIndex(e=>e.name===`package/${t}`&&!G.has(e.type))}function renameRefusal(e,t,n){let r=memberIndex(e,t),i=e.entries[r];if(!i)return`missing`;if(i.type!==`0`&&i.type!==``)return`not-file`;let a=e.entries[r-1];return a?.type===`L`||a?.type===`x`&&paxFields(a.body).has(`path`)?`extended-name`:renamedHeader(i.header,`package/${n}`)?null:`too-long`}function renamedHeader(e,t){let n=Buffer.from(t,`utf8`),r=-1;if(n.length>100){if(!isUstar(e))return null;for(let e=n.indexOf(47);e!==-1;e=n.indexOf(47,e+1))if(e<=155&&n.length-e-1<=100&&n.length-e-1>0){r=e;break}if(r===-1)return null}let i=Buffer.from(e);return i.fill(0,0,100),isUstar(e)&&i.fill(0,345,500),r===-1?n.copy(i,0):(n.copy(i,345,0,r),n.copy(i,0,r+1)),seal(i)}function isNameByte(e){return e<100||e>=148&&e<156||e>=345&&e<500}function readArchive(e){let t=m(e),n=[],r=/* @__PURE__ */ new Set,i=null,a=null;for(let e=0;e<t.length;){let o=t.subarray(e,e+512);if(o.length<512)throw new PublishCleanError(`Tarball ends mid-header; the archive is truncated.`);if(o.every(e=>e===0)){if(a=t.subarray(e),a.length<1024||a.length%512||a.some(e=>e!==0))throw new PublishCleanError(`Tarball has an invalid end-of-archive marker.`);break}let s=field(o,156,1),c=[isUstar(o)?field(o,345,155):``,field(o,0,100)].filter(Boolean).join(`/`);assertChecksum(o,c);let l=W.has(s),u=l?c:i?.get(`path`)||c,d=entrySize(o),f=!l&&i?.get(`size`);if(f){if(!/^[0-9]+$/.test(f)||!Number.isSafeInteger(Number(f)))throw new PublishCleanError(`Tarball has an invalid PAX size.`);d=Number(f)}let p=e+512+512*Math.ceil(d/512);if(!Number.isSafeInteger(p)||p>t.length)throw new PublishCleanError(`Tarball entry ${JSON.stringify(u)} runs past the end of the archive.`);let m=t.subarray(e+512,e+512+d);if(s===`L`){if(i)throw new PublishCleanError(`Tarball has consecutive extended headers.`);let e=gnuLongName(m);if(e===U)throw new PublishCleanError(`Tarball contains a GNU long-name header renaming an entry to ${U}.`);i=/* @__PURE__ */ new Map([[`path`,e]])}else if(l){let e=paxFields(m);if(e.get(`path`)===U)throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${U}.`);if(s===`g`){if([`path`,`size`,`linkpath`].some(t=>e.has(t)))throw new PublishCleanError(`Tarball has a global PAX path, linkpath or size override.`)}else{if(i)throw new PublishCleanError(`Tarball has consecutive extended headers.`);i=e}}else{if(u===U){if(s!==`0`&&s!==``)throw new PublishCleanError(`${U} is not a regular file in the tarball.`);if(f)throw new PublishCleanError(`Tarball manifest has a PAX size override that cannot survive rewriting.`)}let e=u.replace(/\/$/,``).split(`/`);if(e[0]!==`package`||e.some(e=>!e||e===`.`||e===`..`)||u.includes(`\\`)||u.includes(`\0`))throw new PublishCleanError(`Tarball has an unsafe entry path: ${JSON.stringify(u)}.`);if(r.has(u))throw new PublishCleanError(`Tarball contains ${JSON.stringify(u)} more than once.`);r.add(u),i=null}n.push({name:u,type:s,header:o,body:m,raw:t.subarray(e,p)}),e=p}if(a===null)throw new PublishCleanError(`Tarball has no end-of-archive marker; the archive is truncated.`);if(i)throw new PublishCleanError(`Tarball ends with an unused extended header.`);return{entries:n,tail:a}}function assertPreservedArchive(e,t,n=/* @__PURE__ */ new Map){if(e.entries.length!==t.entries.length||!e.tail.equals(t.tail))throw new PublishCleanError(`Rewriting the manifest changed the archive structure.`);for(let[r,i]of e.entries.entries()){let e=t.entries[r],a=!G.has(i.type),o=a?n.get(i.name.slice(8)):void 0;if(!e||i.type!==e.type||(o===void 0?i.name!==e.name||(i.name===U&&a?!reheader(i.header,e.body.length).equals(e.header):!i.raw.equals(e.raw)):e.name!==`package/${o}`||!i.raw.subarray(512).equals(e.raw.subarray(512))||i.header.some((t,n)=>!isNameByte(n)&&t!==e.header[n])))throw new PublishCleanError(`Rewriting the manifest changed archive entry ${JSON.stringify(i.name)}.`)}}function packageFiles(e){return installedEntries(e).map(e=>e.name).sort()}function installedEntries(e){return e.entries.filter(e=>e.type!==`5`&&!G.has(e.type)).map(e=>({name:e.name.startsWith(`package/`)?e.name.slice(8):e.name,body:e.body})).filter(e=>e.name.length>0&&!e.name.endsWith(`/`))}function packageContents(e){return new Map(installedEntries(e).map(e=>[e.name,e.body]))}function manifestEntry(e){let t=e.entries.find(e=>e.name===U&&!G.has(e.type));if(!t)throw new PublishCleanError(`Tarball does not contain ${U}.`);return t}function manifestText(e){return manifestEntry(e).body.toString(`utf8`)}function replaceManifest(e,t,n=/* @__PURE__ */ new Map){let r=manifestEntry(e),i=Buffer.from(t,`utf8`),a=/* @__PURE__ */ new Map;for(let[t,r]of n){let n=renameRefusal(e,t,r),i=e.entries[memberIndex(e,t)],o=i&&!n&&renamedHeader(i.header,`package/${r}`);if(!i||!o)throw new PublishCleanError(`Cannot rename ${t} to ${r}: ${n??`unknown`}.`);a.set(i,o)}let o=e.entries.map(e=>{if(e===r)return Buffer.concat([reheader(e.header,i.length),i,Buffer.alloc(512*Math.ceil(i.length/512)-i.length)]);let t=a.get(e);return t?Buffer.concat([t,e.raw.subarray(512)]):e.raw});return o.push(e.tail),h(Buffer.concat(o),{level:9})}const q={"not-file":`it is not a regular file in the archive, and only file names are renamed`,"extended-name":`pnpm stored its name in an extended (long-name) header, which this tool does not rewrite; shorten the source path`,"too-long":`the new name does not fit a tar header (100 bytes, or 155 + 100 split at a /); shorten the target path`};function reviewRenames(e,t){let n=/* @__PURE__ */ new Map,r=[];if(t.size===0)return{applied:n,findings:r};let i=packageFiles(e);for(let[a,o]of t){let t=`publish-clean.renameFiles[${JSON.stringify(a)}]`,s=renameRefusal(e,a,o);if(s===`missing`){r.push({rule:`rename-source-missing`,consequence:`breaks`,healed:!1,where:t,message:`${a} is not in the packed archive, so nothing ships as ${o}. pnpm still decides which files are packed: add ${a} to the "files" array in your package.json, or fix the path (it is relative to the package root, as pnpm packs it).`});continue}let c=i.filter(e=>e===o||e.startsWith(`${o}/`)||o.startsWith(`${e}/`));c.length>0?r.push({rule:`rename-target-exists`,consequence:`breaks`,healed:!1,where:t,message:`${a} cannot ship as ${o}: the packed archive already carries ${c.join(`, `)}, and two members claiming one path leave the installed file to whichever the extractor writes last. Stop packing the existing file — remove it from "files" or exclude it with a "!" entry — or choose another target.`}):s===null?n.set(a,o):r.push({rule:`rename-unsupported`,consequence:`breaks`,healed:!1,where:t,message:`${a} cannot ship as ${o}: ${q[s]}.`})}return{applied:n,findings:r}}const J=[11,5,1],Y=[22,14,0];function isAtLeast(e,t){for(let n of[0,1,2]){if(e[n]>t[n])return!0;if(e[n]<t[n])return!1}return!0}function wantsTrustedPublish(e,t,n){if(n.GITHUB_ACTIONS===`true`&&typeof n.ACTIONS_ID_TOKEN_REQUEST_URL==`string`)return!0;for(let e=t.length-1;e>=0;e--){if(t[e]===`--provenance=true`||t[e]===`--provenance`)return!0;if(t[e]===`--provenance=false`)return!1}if(isObject(e.publishConfig)&&e.publishConfig.provenance!==void 0)return!!e.publishConfig.provenance}function repositoryUrl(e){return typeof e.repository==`string`?e.repository:isObject(e.repository)&&typeof e.repository.url==`string`?e.repository.url:null}function githubRepositorySlug(e){let t=e.startsWith(`git+`)?e.slice(4):e;if(t.startsWith(`git@github.com:`)){let e=t.slice(15);return e.endsWith(`.git`)?e.slice(0,-4):e}try{let e=new URL(t);if(e.hostname!==`github.com`)return null;let n=e.pathname.replace(/^\/+/,``);return n.endsWith(`.git`)?n.slice(0,-4):n}catch{return null}}function assertRepositoryForTrustedPublish(e,t){if(t.GITHUB_ACTIONS!==`true`||typeof t.GITHUB_REPOSITORY!=`string`)return;let n=repositoryUrl(e);if(!n)throw new PublishCleanError(`GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.`);if(githubRepositorySlug(n)!==t.GITHUB_REPOSITORY)throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${t.GITHUB_REPOSITORY}); found ${n}.`)}function ownVersion(){let e=readJson(u(new URL(`../package.json`,import.meta.url)));return typeof e.version==`string`?e.version:`unknown`}function readJson(t){let n;try{n=e(t,`utf8`)}catch(e){throw new PublishCleanError(`Unable to read ${t}. Run publish-clean from a package directory, or name one as the first argument.`,{cause:e})}let r;try{r=JSON.parse(n)}catch(e){throw new PublishCleanError(`Unable to parse JSON file: ${t}`,{cause:e})}if(!isObject(r))throw new PublishCleanError(`${t} must contain a JSON object.`);return r}function toolVersion(e,t){let n=t.trim().replace(/^v/,``),r=n.split(`.`).map(e=>Number.parseInt(e,10));if(r.length<3||r.some(e=>Number.isNaN(e)))throw new PublishCleanError(`Unable to parse ${e} version: ${n}`);return[r[0]??0,r[1]??0,r[2]??0]}function publishEnv(){return{ACTIONS_ID_TOKEN_REQUEST_URL:process.env.ACTIONS_ID_TOKEN_REQUEST_URL,GITHUB_ACTIONS:process.env.GITHUB_ACTIONS,GITHUB_REPOSITORY:process.env.GITHUB_REPOSITORY}}async function assertTrustedPublishingRuntime(e,t,n){let r=toolVersion(`npm`,t);if(!isAtLeast(r,J))throw new PublishCleanError(`Trusted npm publishing requires npm ${J.join(`.`)} or newer; found ${r.join(`.`)}.`);let i=toolVersion(`node`,await requireTool(`node`,e,n));if(!isAtLeast(i,Y))throw new PublishCleanError(`Trusted npm publishing requires Node.js ${Y.join(`.`)} or newer; found ${i.join(`.`)}.`)}function warnIfNonPnpmLifecycle(){let e=process.env.npm_config_user_agent;e&&!e.startsWith(`pnpm/`)&&console.warn(`${O} Detected lifecycle user agent: ${e}`)}async function uncommittedChangesRefusal(e,t,n){if(t)return null;let r;try{r=(await run(`git`,[`status`,`--porcelain`,`--`,`.`],e,{signal:n})).trim()}catch(t){if(n.aborted)throw t;return console.warn(`publish-clean: skipping the uncommitted-changes check — ${t instanceof Error?t.message:String(t)}\nExpected a Git checkout at ${e}? Then this publishes source that was never compared against a commit.`),null}return r?`Source package has uncommitted changes:\n${r}`:null}async function readTarball(e){return readArchive(await i(e))}function manifestOf(e,t){let n;try{n=JSON.parse(manifestText(e))}catch(e){throw new PublishCleanError(`Unable to parse package.json inside ${t}.`,{cause:e})}if(!isObject(n))throw new PublishCleanError(`package.json inside ${t} must contain a JSON object.`);return n}async function soleTarball(e){let t=(await a(e)).filter(e=>e.endsWith(`.tgz`)),[n]=t;if(t.length!==1||!n)throw new PublishCleanError(`pnpm pack left ${t.length} tarballs in ${e}; expected exactly one.`);return l.join(e,n)}async function packAndClean(e,a,u){let d=readJson(l.join(e,`package.json`));await requireTool(`pnpm`,e,a),warnIfNonPnpmLifecycle();let f=packageConfig(d),p=u.skipFileCheck||f.skipFileCheck===!0,m=u.allowSuspicious||f.allowSuspicious===!0,h=u.noGitChecks||f.noGitChecks===!0,g=u.registry??(typeof f.registry==`string`?f.registry:null),_=customDevFields(f),v=keptFields(f),y=allowedUnreferenced(f),b=renamedFiles(f),x=[u.verify?null:privatePackageRefusal(d),await uncommittedChangesRefusal(e,h,a),filesFieldRefusal(d,p)].filter(e=>e!==null);if(x.length>0)throw new PublishCleanError(x.join(`
|
|
76
79
|
|
|
77
|
-
`));let
|
|
78
|
-
`)}`);t.values[`guard-only`]===!0&&console.warn("publish-clean: --guard-only is deprecated; use `publish-clean verify` (or --verify-only), which additionally works on a package marked private."),await packAndClean(l.resolve(String(t.positionals[0]??`.`)),e,{allowSuspicious:t.values[`allow-suspicious`]===!0,dryRun:t.values[`dry-run`]===!0,guardOnly:t.values[`guard-only`]===!0,heal:t.values[`no-heal`]!==!0,noGitChecks:t.values[`no-git-checks`]===!0,publishArgs:n,registry:typeof t.values.registry==`string`?t.values.registry:null,skipFileCheck:t.values[`skip-file-check`]===!0,strict:t.values.strict===!0,verify:t.verify,tarballOut:typeof t.values[`tarball-out`]==`string`?t.values[`tarball-out`]:null})}const
|
|
80
|
+
`));let S;try{S=await r(l.join(c(),`publish-clean-`))}catch(e){throw new PublishCleanError(`Unable to create a temporary directory in ${c()}. publish-clean packs into a temp tree, so it needs one that is writable and has room for the tarball. Set TMPDIR to somewhere else, or free space there.`,{cause:e})}try{await run(`pnpm`,[`pack`,`--pack-destination`,S],e,{signal:a,output:`pack`});let r=await soleTarball(S),o=await readTarball(r),c=manifestOf(o,`the packed tarball`),d=u.verify?null:privatePackageRefusal(c);if(d)throw new PublishCleanError(d);let p=packageFiles(o),h=reviewRenames(o,b),x=p.map(e=>h.applied.get(e)??e).sort(),C=reviewExports(withRegistry(stripManifest(c,_),g),{files:new Set(x),heal:u.heal&&f.heal!==!1}),w=[...h.findings,...C.findings,...reviewUnrecognizedFields(C.manifest,v)],T=stringifyJson(C.manifest);await s(r,replaceManifest(o,T,h.applied));let E=await i(r),D=readArchive(E),O=packageFiles(D);assertSameEntries(x,O),assertPreservedArchive(o,D,h.applied);let k=manifestOf(D,`the published tarball`);try{let e=[...h.applied.keys()];if(w.push(...reviewPackedContent([...O,...e],m),...reviewRegistryDestinations(k),...reviewMonorepoProtocols(k,O)),w.push(...reviewDeclaredFiles(k,O)),assertNoLostConsumerFields(c,k,_),manifestText(D)!==T)throw new PublishCleanError(`Rewritten tarball manifest differs from the cleaned manifest.`);let t=new Set([...forbiddenPackedFiles([...O,...e],m)].map(e=>h.applied.get(e)??e)),n=new Map([...packageContents(D)].filter(([e])=>!t.has(e)));w.push(...reviewPackedNames(k,O),...reviewShippedFiles(k,n),...reviewSelfReferences(k,n),...reviewUnreferencedFiles(k,n,y))}finally{w.length>0&&console.warn(formatFindings(w,u.strict))}let A=publishRefusal(w,u.strict);if(A)throw new PublishCleanError(A);console.warn(w.length===0?`publish-clean: no findings.`:`publish-clean: ${countOf(w.length,`finding`)} above, none of which stops a publish.`);let j=f.validateArtifact;if(j)try{if(await run(j[0],[...j.slice(1),r],e,{signal:a,output:`validator`}),!E.equals(await i(r)))throw new PublishCleanError(`The validator changed the tarball. Validators must be read-only.`)}catch(e){throw new PublishCleanError(`publish-clean.validateArtifact failed; no tarball was retained or published.`,{cause:e})}if(u.tarballOut!==null){try{await n(u.tarballOut,{recursive:!0})}catch(e){throw new PublishCleanError(`Unable to create the --tarball-out directory ${u.tarballOut}.`,{cause:e})}let e=l.join(u.tarballOut,l.basename(r));await t(r,e),console.log(`Final tarball kept at: ${e}`)}if(u.dryRun){console.log(`[dry-run] ${O.length} files:`);for(let e of O)console.log(` ${JSON.stringify(e)}`);console.log(`[dry-run] cleaned package.json:\n${T}`);return}if(u.guardOnly||u.verify)return;let M=await requireTool(`npm`,e,a),N=publishEnv(),P=wantsTrustedPublish(k,u.publishArgs,N);if(P===void 0){let t=(await run(`npm`,[`config`,`get`,`provenance`],e,{signal:a,timeout:1e4})).trim();if(t!==`true`&&t!==`false`)throw new PublishCleanError(`npm config get provenance must return true or false.`);P=t===`true`}P&&(await assertTrustedPublishingRuntime(e,M,a),assertRepositoryForTrustedPublish(k,N));let F=packageScope(k),I=[`publish`,r,...u.publishArgs];g&&(I.push(`--registry`,g),F&&I.push(`--${F}:registry=${g}`)),await run(`npm`,I,e,{signal:a,output:`publish`})}finally{await o(S,{recursive:!0,force:!0})}}async function main(e){let t=parseOptions(process.argv.slice(2)),{publishArgs:n}=t;if(t.values.version)console.log(ownVersion());else if(t.values.help)console.log(V);else{if(t.positionals.length>1)throw new PublishCleanError(`Unexpected positional arguments before --:\n${t.positionals.slice(1).join(`
|
|
81
|
+
`)}`);t.values[`guard-only`]===!0&&console.warn("publish-clean: --guard-only is deprecated; use `publish-clean verify` (or --verify-only), which additionally works on a package marked private."),await packAndClean(l.resolve(String(t.positionals[0]??`.`)),e,{allowSuspicious:t.values[`allow-suspicious`]===!0,dryRun:t.values[`dry-run`]===!0,guardOnly:t.values[`guard-only`]===!0,heal:t.values[`no-heal`]!==!0,noGitChecks:t.values[`no-git-checks`]===!0,publishArgs:n,registry:typeof t.values.registry==`string`?t.values.registry:null,skipFileCheck:t.values[`skip-file-check`]===!0,strict:t.values.strict===!0,verify:t.verify,tarballOut:typeof t.values[`tarball-out`]==`string`?t.values[`tarball-out`]:null})}}const X=new AbortController;let Z=!1;for(let[e,t]of[[`SIGINT`,130],[`SIGTERM`,143]])process.on(e,()=>{Z=!0,process.exitCode=t,X.abort(new PublishCleanError(`Cancelled by ${e}.`))});main(X.signal).catch(e=>{console.error(`publish-clean:`,e instanceof PublishCleanError?e.message:e),e instanceof PublishCleanError&&e.cause&&console.error(`Caused by:`,e.cause instanceof Error?e.cause.message:e.cause),Z||(process.exitCode=1)});export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anizoptera/publish-clean",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Cleans and helps to publish npm packages properly with a clean package.json (no unnecessary entries), verified exports, checks for unwanted files, unresolved workspace dependencies and missing entry points.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bun",
|