@anizoptera/publish-clean 0.8.0 → 0.10.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 +406 -199
- package/dist/cli.js +49 -1367
- package/package.json +3 -2
package/dist/cli.js
CHANGED
|
@@ -1,817 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
// @anizoptera/publish-clean 0.
|
|
4
|
-
import {
|
|
5
|
-
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
6
|
-
import { tmpdir } from "node:os";
|
|
7
|
-
import path from "node:path";
|
|
8
|
-
import { fileURLToPath } from "node:url";
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
10
|
-
import { parseArgs } from "node:util";
|
|
11
|
-
import { gunzipSync, gzipSync } from "node:zlib";
|
|
3
|
+
// @anizoptera/publish-clean 0.10.0 | https://github.com/Anizoptera/publish-clean#readme
|
|
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(`
|
|
12
5
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
function
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
* newline, and key order left exactly as the packer emitted it. Preserving order is what makes
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
* the archive's entry paths with the `package/` prefix already stripped — never a directory on
|
|
45
|
-
* disk, because that list is what a consumer's installer unpacks and it needs no filesystem to
|
|
46
|
-
* exist.
|
|
47
|
-
*
|
|
48
|
-
* Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
|
|
49
|
-
* argv here. `cli.ts` owns the effects.
|
|
50
|
-
*/
|
|
51
|
-
/**
|
|
52
|
-
* Content that must never reach a registry. `^` means the package root.
|
|
53
|
-
*
|
|
54
|
-
* Case-insensitive throughout, because the filesystems most packages are built on are
|
|
55
|
-
* too. On macOS and Windows `Server.PEM` and `server.pem` are the same file, so a
|
|
56
|
-
* case-sensitive guard refuses one and publishes the other, which is worse than no guard:
|
|
57
|
-
* it reads as coverage.
|
|
58
|
-
*
|
|
59
|
-
* Private keys are matched by extension and, separately, by exact filename. SSH keys carry
|
|
60
|
-
* no extension at all, and `id_rsa` is the most common private-key filename there is. The
|
|
61
|
-
* exact-name form deliberately does not match `id_rsa.pub`, which is public by design and
|
|
62
|
-
* legitimate to ship.
|
|
63
|
-
*/
|
|
64
|
-
const CRITICAL_PATTERNS = [
|
|
65
|
-
/(?:^|\/)node_modules(?:\/|$)/i,
|
|
66
|
-
/(?:^|\/)\.git(?:\/|$)/i,
|
|
67
|
-
/(?:^|\/)\.env(?:\.|$)/i,
|
|
68
|
-
/(?:^|\/)\.npmrc$/i,
|
|
69
|
-
/\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
|
|
70
|
-
/(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
|
|
71
|
-
];
|
|
72
|
-
const SUSPICIOUS_PATTERNS = [
|
|
73
|
-
/(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
|
|
74
|
-
/(?:^|\/)\.github(?:\/|$)/,
|
|
75
|
-
/(?:^|\/)tsconfig[^/]*\.json$/,
|
|
76
|
-
/(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
|
|
77
|
-
/\.(?:test|spec)\.[cm]?[jt]sx?$/
|
|
78
|
-
];
|
|
79
|
-
function validatePackedFiles(files, skipSuspicious) {
|
|
80
|
-
const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
|
|
81
|
-
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
82
|
-
if (skipSuspicious) return;
|
|
83
|
-
const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
|
|
84
|
-
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
|
|
88
|
-
*
|
|
89
|
-
* Replacing a member is supposed to change one member, and the rewriter copies every other
|
|
90
|
-
* entry as opaque bytes — so this can only fail through a defect in that code, which is exactly
|
|
91
|
-
* why it is worth asserting on the step that cannot be taken back. Nothing else would notice a
|
|
92
|
-
* dropped file: the leak checks only ask what is present, and a package missing a file installs
|
|
93
|
-
* fine and then fails at import, on a version the registry keeps forever.
|
|
94
|
-
*
|
|
95
|
-
* The two lists come from the same reader, so this cannot catch a defect in the reader itself —
|
|
96
|
-
* only one in the rewrite, which is what it is for. Independence from the reader is bought
|
|
97
|
-
* elsewhere, by the case in test/cli.test.ts that compares the list this reader prints against
|
|
98
|
-
* `tar tzf` of the same tarball — an instrument that cannot share a mistake with this one.
|
|
99
|
-
*/
|
|
100
|
-
function assertSameEntries(packed, published) {
|
|
101
|
-
const before = new Set(packed);
|
|
102
|
-
const after = new Set(published);
|
|
103
|
-
const changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
|
|
104
|
-
if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Walks a manifest value of any shape and collects the strings that name a file inside
|
|
108
|
-
* the package, so the caller can prove each one exists in the tarball.
|
|
109
|
-
*
|
|
110
|
-
* `mode` exists because the two families of path-bearing fields disagree about what a
|
|
111
|
-
* bare string means, and reading one by the other's rules produces wrong answers in both
|
|
112
|
-
* directions:
|
|
113
|
-
*
|
|
114
|
-
* - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
|
|
115
|
-
* where every string is a path into this package.
|
|
116
|
-
* - `"relative-only"` for `sideEffects` and the object form of
|
|
117
|
-
* `browser`, where a string may just as well be an external package name, a condition
|
|
118
|
-
* target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
|
|
119
|
-
* rest would report a missing file for something that was never a file.
|
|
120
|
-
*
|
|
121
|
-
* Booleans are skipped rather than ignored by accident: `sideEffects: false` and
|
|
122
|
-
* `browser` replacements legitimately hold them. Export/import targets use their own walker.
|
|
123
|
-
*/
|
|
124
|
-
function collectDeclaredPaths(value, out, mode) {
|
|
125
|
-
if (typeof value === "string") {
|
|
126
|
-
if (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) out.push(value);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
if (typeof value === "boolean") return;
|
|
130
|
-
if (Array.isArray(value)) {
|
|
131
|
-
for (const item of value) collectDeclaredPaths(item, out, mode);
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
if (!isObject(value)) return;
|
|
135
|
-
for (const item of Object.values(value)) collectDeclaredPaths(item, out, mode);
|
|
136
|
-
}
|
|
137
|
-
function normalizeDeclaredPath(declared) {
|
|
138
|
-
const withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
|
|
139
|
-
if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
|
|
140
|
-
const normalized = path.posix.normalize(withoutDot);
|
|
141
|
-
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
142
|
-
return normalized;
|
|
143
|
-
}
|
|
144
|
-
/** Node replaces every target star with the same subpath, including slashes. */
|
|
145
|
-
function matchesTarget(file, pattern) {
|
|
146
|
-
const parts = pattern.split("*");
|
|
147
|
-
const count = parts.length - 1;
|
|
148
|
-
if (count === 0) return file === pattern;
|
|
149
|
-
const size = (file.length - parts.reduce((sum, part) => sum + part.length, 0)) / count;
|
|
150
|
-
if (!Number.isInteger(size) || size < 0) return false;
|
|
151
|
-
const start = parts[0]?.length ?? 0;
|
|
152
|
-
return parts.join(file.slice(start, start + size)) === file;
|
|
153
|
-
}
|
|
154
|
-
/** Arrays skip invalid targets, but package-configuration errors must escape the fallback. */
|
|
155
|
-
var InvalidPackageTarget = class extends PublishCleanError {};
|
|
156
|
-
/** Export targets are URLs, unlike legacy main/bin paths; normalization must not hide invalid segments. */
|
|
157
|
-
function targetPath(target) {
|
|
158
|
-
if (!target.startsWith("./") || /%2f|%5c/i.test(target)) throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`);
|
|
159
|
-
try {
|
|
160
|
-
if (decodeURIComponent(target.split(/[?#]/, 1)[0] ?? "").slice(2).split(/[\\/]/).some((segment) => [
|
|
161
|
-
".",
|
|
162
|
-
"..",
|
|
163
|
-
"node_modules"
|
|
164
|
-
].includes(segment.toLowerCase()))) throw new Error("Invalid target segment");
|
|
165
|
-
return decodeURIComponent(new URL(target, "file:///package/").pathname).slice(9);
|
|
166
|
-
} catch (cause) {
|
|
167
|
-
throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`, { cause });
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
/** True selects a target, null blocks a condition, undefined leaves later conditions reachable. */
|
|
171
|
-
function collectTargets(value, imports, pattern, out) {
|
|
172
|
-
if (value === null) return null;
|
|
173
|
-
if (typeof value === "string") {
|
|
174
|
-
if (imports && !value.startsWith(".") && !value.startsWith("/")) return true;
|
|
175
|
-
out.push({
|
|
176
|
-
name: targetPath(value),
|
|
177
|
-
kind: "target",
|
|
178
|
-
pattern
|
|
179
|
-
});
|
|
180
|
-
return true;
|
|
181
|
-
}
|
|
182
|
-
if (Array.isArray(value)) {
|
|
183
|
-
if (value.length === 0) return null;
|
|
184
|
-
let invalid;
|
|
185
|
-
for (const item of value) try {
|
|
186
|
-
const result = collectTargets(item, imports, pattern, out);
|
|
187
|
-
if (result === true) return true;
|
|
188
|
-
if (result === null) invalid = null;
|
|
189
|
-
} catch (error) {
|
|
190
|
-
if (!(error instanceof InvalidPackageTarget)) throw error;
|
|
191
|
-
invalid = error;
|
|
192
|
-
}
|
|
193
|
-
if (invalid) throw invalid;
|
|
194
|
-
return invalid;
|
|
195
|
-
}
|
|
196
|
-
if (!isObject(value)) throw new InvalidPackageTarget("Invalid exports/imports target; expected a path, condition object, array or null.");
|
|
197
|
-
const conditions = Object.entries(value);
|
|
198
|
-
for (const [condition] of conditions) {
|
|
199
|
-
const number = Number(condition);
|
|
200
|
-
if (String(number) === condition && number >= 0 && number < 4294967295) throw new PublishCleanError(`Invalid export condition: ${JSON.stringify(condition)}.`);
|
|
201
|
-
}
|
|
202
|
-
for (const [condition, item] of conditions) {
|
|
203
|
-
const definite = collectTargets(item, imports, pattern, out);
|
|
204
|
-
if (condition === "default" && definite !== void 0) return definite;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
function collectMap(value, imports, out) {
|
|
208
|
-
if (value === void 0 || value === null) return;
|
|
209
|
-
if (imports && !isObject(value)) throw new PublishCleanError("imports must be a subpath map.");
|
|
210
|
-
if (!(isObject(value) && (imports || Object.keys(value).some((key) => key.startsWith("."))))) {
|
|
211
|
-
collectTargets(value, imports, false, out);
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
for (const [key, target] of Object.entries(value)) {
|
|
215
|
-
if (imports ? !key.startsWith("#") || key === "#" || key.startsWith("#/") : key !== "." && !key.startsWith("./")) throw new PublishCleanError(`Invalid exports/imports key: ${JSON.stringify(key)}.`);
|
|
216
|
-
collectTargets(target, imports, key.includes("*"), out);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
/** A CommonJS main tries file extensions and index files, not a nested package's main. */
|
|
220
|
-
function mainExists(name, files) {
|
|
221
|
-
const file = (target) => [
|
|
222
|
-
"",
|
|
223
|
-
".js",
|
|
224
|
-
".json",
|
|
225
|
-
".node"
|
|
226
|
-
].some((ext) => files.has(target + ext));
|
|
227
|
-
if (file(name)) return true;
|
|
228
|
-
const prefix = name ? `${name}/` : "";
|
|
229
|
-
return [
|
|
230
|
-
".js",
|
|
231
|
-
".json",
|
|
232
|
-
".node"
|
|
233
|
-
].some((extension) => files.has(`${prefix}index${extension}`));
|
|
234
|
-
}
|
|
235
|
-
/** Validate declared files using each field's consumer semantics, without extracting the archive. */
|
|
236
|
-
function assertDeclaredFiles(pkg, published) {
|
|
237
|
-
const declared = [];
|
|
238
|
-
const collect = (value, kind, mode = "every-string", patterns = false) => {
|
|
239
|
-
const names = [];
|
|
240
|
-
collectDeclaredPaths(value, names, mode);
|
|
241
|
-
declared.push(...names.map((name) => ({
|
|
242
|
-
name,
|
|
243
|
-
kind,
|
|
244
|
-
pattern: patterns && name.includes("*")
|
|
245
|
-
})));
|
|
246
|
-
};
|
|
247
|
-
collect(pkg.main, "main");
|
|
248
|
-
for (const field of ["types", "typings"]) collect(pkg[field], "types");
|
|
249
|
-
collect(pkg.typesVersions, "types", "every-string", true);
|
|
250
|
-
for (const field of ["module", "bin"]) collect(pkg[field], "file");
|
|
251
|
-
collect(pkg.browser, "file", typeof pkg.browser === "string" ? "every-string" : "relative-only");
|
|
252
|
-
collect(pkg.sideEffects, "glob", "relative-only");
|
|
253
|
-
collectMap(pkg.exports, false, declared);
|
|
254
|
-
collectMap(pkg.imports, true, declared);
|
|
255
|
-
const files = new Set(published);
|
|
256
|
-
const missing = [];
|
|
257
|
-
for (const item of declared) {
|
|
258
|
-
if (item.kind === "glob" && /[*?[\]{}]/.test(item.name)) continue;
|
|
259
|
-
const name = item.kind === "main" && [
|
|
260
|
-
"",
|
|
261
|
-
".",
|
|
262
|
-
"./"
|
|
263
|
-
].includes(item.name) ? "" : normalizeDeclaredPath(item.name);
|
|
264
|
-
if (name === null) throw new PublishCleanError(`Manifest declares invalid package paths: ${JSON.stringify(item.name)}`);
|
|
265
|
-
let found = files.has(name);
|
|
266
|
-
if (!found && item.pattern) found = published.some((file) => matchesTarget(file, name));
|
|
267
|
-
else if (!found && item.kind === "main") found = mainExists(name.replace(/\/$/, ""), files);
|
|
268
|
-
else if (!found && item.kind === "types") found = [
|
|
269
|
-
".d.ts",
|
|
270
|
-
".d.mts",
|
|
271
|
-
".d.cts",
|
|
272
|
-
"/index.d.ts"
|
|
273
|
-
].some((suffix) => files.has(name + suffix));
|
|
274
|
-
if (!found) missing.push(item.name);
|
|
275
|
-
}
|
|
276
|
-
if (missing.length) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((name) => JSON.stringify(name)).join("\n")}`);
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
//#endregion
|
|
280
|
-
//#region src/command.ts
|
|
281
|
-
/**
|
|
282
|
-
* Runs the external tools this CLI depends on: `pnpm`, `npm` and `git`.
|
|
283
|
-
*
|
|
284
|
-
* Never `{ shell: true }`. It space-joins the argument vector with no escaping at all, which
|
|
285
|
-
* Node runtime-deprecated in v24 as shell injection (DEP0190) — and this tool forwards
|
|
286
|
-
* arguments a caller wrote after `--` straight into `npm publish`, so that vector is
|
|
287
|
-
* attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
|
|
288
|
-
*/
|
|
289
|
-
/** Bound a hung version-manager shim without blocking the event loop. */
|
|
290
|
-
const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
291
|
-
/**
|
|
292
|
-
* Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
|
|
293
|
-
* documentation states a `.cmd` "cannot be launched using child_process.execFile()" — so the
|
|
294
|
-
* spawn fails as ENOENT and the probe below would report a working package manager as missing.
|
|
295
|
-
* Of the three routes Node names, this is the one that adds no parsing of our own: cmd.exe runs
|
|
296
|
-
* the shim AND does the PATH/PATHEXT lookup, so no name resolution belongs here either.
|
|
297
|
-
*
|
|
298
|
-
* `/d` skips registry AutoRun commands, which would otherwise execute inside a publish. Neither
|
|
299
|
-
* `/s` nor `windowsVerbatimArguments` is used: without them Node applies its ordinary C-runtime
|
|
300
|
-
* quoting to every argument, exactly as on any other platform, so this file owns no escaping.
|
|
301
|
-
* What it owns instead is the refusal below, which is what keeps that true.
|
|
302
|
-
*/
|
|
303
|
-
function spawnArgs(command, args, platform) {
|
|
304
|
-
if (platform !== "win32") return [command, [...args]];
|
|
305
|
-
const unsafe = [command, ...args].filter((argument) => /[&|<>^%()\r\n]/.test(argument));
|
|
306
|
-
if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.map((argument) => JSON.stringify(argument)).join("\n")}\nUse arguments without & | < > ^ % ( ) or line breaks, or publish from Linux or macOS.`);
|
|
307
|
-
return ["cmd.exe", [
|
|
308
|
-
"/d",
|
|
309
|
-
"/c",
|
|
310
|
-
command,
|
|
311
|
-
...args
|
|
312
|
-
]];
|
|
313
|
-
}
|
|
314
|
-
/** Await child settlement before returning, so temporary files cannot be removed under a live packer. */
|
|
315
|
-
function run(command, args, cwd, options = {}) {
|
|
316
|
-
options.signal?.throwIfAborted();
|
|
317
|
-
const output = options.output ?? "capture";
|
|
318
|
-
const detached = process.platform !== "win32" && output !== "publish";
|
|
319
|
-
return new Promise((resolve, reject) => {
|
|
320
|
-
const child = spawn(...spawnArgs(command, args, process.platform), {
|
|
321
|
-
cwd,
|
|
322
|
-
detached,
|
|
323
|
-
stdio: output === "capture" ? [
|
|
324
|
-
"ignore",
|
|
325
|
-
"pipe",
|
|
326
|
-
"pipe"
|
|
327
|
-
] : output === "pack" ? [
|
|
328
|
-
"ignore",
|
|
329
|
-
process.stderr,
|
|
330
|
-
process.stderr
|
|
331
|
-
] : "inherit"
|
|
332
|
-
});
|
|
333
|
-
let stdout = "";
|
|
334
|
-
let stderr = "";
|
|
335
|
-
let failure;
|
|
336
|
-
let escalation;
|
|
337
|
-
let stopping = false;
|
|
338
|
-
let termination;
|
|
339
|
-
const killGroup = (signal) => {
|
|
340
|
-
try {
|
|
341
|
-
if (child.pid !== void 0) {
|
|
342
|
-
if (detached) process.kill(-child.pid, signal);
|
|
343
|
-
else child.kill(signal);
|
|
344
|
-
}
|
|
345
|
-
} catch (error) {
|
|
346
|
-
if (!isObject(error) || error.code !== "ESRCH") failure = error instanceof Error ? error : new Error(String(error));
|
|
347
|
-
}
|
|
348
|
-
};
|
|
349
|
-
const stop = () => {
|
|
350
|
-
if (stopping || child.pid === void 0) return;
|
|
351
|
-
stopping = true;
|
|
352
|
-
if (process.platform === "win32") termination = new Promise((done) => {
|
|
353
|
-
const killer = spawn("taskkill", [
|
|
354
|
-
"/pid",
|
|
355
|
-
String(child.pid),
|
|
356
|
-
"/t",
|
|
357
|
-
"/f"
|
|
358
|
-
], { stdio: "ignore" });
|
|
359
|
-
killer.on("error", (error) => {
|
|
360
|
-
failure = error;
|
|
361
|
-
child.kill();
|
|
362
|
-
});
|
|
363
|
-
killer.once("close", (status) => {
|
|
364
|
-
if (status !== 0 && !failure) failure = new PublishCleanError("Unable to terminate the child process tree.");
|
|
365
|
-
done();
|
|
366
|
-
});
|
|
367
|
-
});
|
|
368
|
-
else {
|
|
369
|
-
killGroup("SIGTERM");
|
|
370
|
-
escalation = setTimeout(() => killGroup("SIGKILL"), 1e3);
|
|
371
|
-
escalation.unref();
|
|
372
|
-
}
|
|
373
|
-
};
|
|
374
|
-
const timer = options.timeout === void 0 ? void 0 : setTimeout(() => {
|
|
375
|
-
failure = new PublishCleanError(`${command} did not finish within ${options.timeout}ms.`);
|
|
376
|
-
stop();
|
|
377
|
-
}, options.timeout);
|
|
378
|
-
const collect = (chunk, stream) => {
|
|
379
|
-
if (stream === "stdout") stdout += chunk.toString();
|
|
380
|
-
else stderr += chunk.toString();
|
|
381
|
-
if (stdout.length + stderr.length > 1048576) {
|
|
382
|
-
failure = new PublishCleanError(`${command} exceeded the output limit for a metadata query.`);
|
|
383
|
-
stdout = stdout.slice(-4096);
|
|
384
|
-
stderr = stderr.slice(-4096);
|
|
385
|
-
stop();
|
|
386
|
-
}
|
|
387
|
-
};
|
|
388
|
-
child.stdout?.on("data", (chunk) => collect(chunk, "stdout"));
|
|
389
|
-
child.stderr?.on("data", (chunk) => collect(chunk, "stderr"));
|
|
390
|
-
child.on("error", (error) => {
|
|
391
|
-
failure = error;
|
|
392
|
-
});
|
|
393
|
-
options.signal?.addEventListener("abort", stop, { once: true });
|
|
394
|
-
child.once("close", async (status, signal) => {
|
|
395
|
-
if (stopping && process.platform !== "win32") killGroup("SIGKILL");
|
|
396
|
-
await termination;
|
|
397
|
-
clearTimeout(timer);
|
|
398
|
-
clearTimeout(escalation);
|
|
399
|
-
options.signal?.removeEventListener("abort", stop);
|
|
400
|
-
if (options.signal?.aborted) {
|
|
401
|
-
reject(options.signal.reason);
|
|
402
|
-
return;
|
|
403
|
-
}
|
|
404
|
-
if (failure || status !== 0) {
|
|
405
|
-
const reason = failure && isObject(failure) && failure.code === "ENOENT" ? "is not available in PATH" : failure?.message ?? `exited with ${signal ?? status}`;
|
|
406
|
-
reject(new PublishCleanError(`${command} ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ""}`, { cause: failure }));
|
|
407
|
-
} else resolve(stdout);
|
|
408
|
-
});
|
|
409
|
-
if (options.signal?.aborted) stop();
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
/** Probe in the package directory: version-manager shims resolve their toolchain from cwd. */
|
|
413
|
-
async function requireTool(name, cwd, signal) {
|
|
414
|
-
return (await run(name, ["--version"], cwd, {
|
|
415
|
-
signal,
|
|
416
|
-
timeout: TOOL_PROBE_TIMEOUT_MS
|
|
417
|
-
})).trim();
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
//#endregion
|
|
421
|
-
//#region src/manifest.ts
|
|
422
|
-
/**
|
|
423
|
-
* What the published `package.json` carries: which fields survive cleaning, which are refused,
|
|
424
|
-
* and what the author may add to either list.
|
|
425
|
-
*
|
|
426
|
-
* Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
|
|
427
|
-
* argv here — so every rule is one input to one output. `cli.ts` owns the effects.
|
|
428
|
-
*/
|
|
429
|
-
const DEV_FIELDS = /* @__PURE__ */ new Set([
|
|
430
|
-
"$schema",
|
|
431
|
-
"catalog",
|
|
432
|
-
"catalogs",
|
|
433
|
-
"patchedDependencies",
|
|
434
|
-
"private",
|
|
435
|
-
"files",
|
|
436
|
-
"stylelint",
|
|
437
|
-
"trustedDependencies",
|
|
438
|
-
"wireit",
|
|
439
|
-
"devDependencies",
|
|
440
|
-
"overrides",
|
|
441
|
-
"resolutions",
|
|
442
|
-
"ava",
|
|
443
|
-
"c8",
|
|
444
|
-
"jest",
|
|
445
|
-
"mocha",
|
|
446
|
-
"nyc",
|
|
447
|
-
"tap",
|
|
448
|
-
"vitest",
|
|
449
|
-
"babel",
|
|
450
|
-
"biome",
|
|
451
|
-
"browserslist",
|
|
452
|
-
"eslintConfig",
|
|
453
|
-
"eslintIgnore",
|
|
454
|
-
"prettier",
|
|
455
|
-
"remarkConfig",
|
|
456
|
-
"xo",
|
|
457
|
-
"commitlint",
|
|
458
|
-
"husky",
|
|
459
|
-
"lint-staged",
|
|
460
|
-
"simple-git-hooks",
|
|
461
|
-
"clean-publish",
|
|
462
|
-
"publish-clean",
|
|
463
|
-
"semantic-release",
|
|
464
|
-
"packageManager",
|
|
465
|
-
"pnpm",
|
|
466
|
-
"volta",
|
|
467
|
-
"workspaces",
|
|
468
|
-
"nx",
|
|
469
|
-
"turbo"
|
|
470
|
-
]);
|
|
471
|
-
const CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
|
|
472
|
-
"preinstall",
|
|
473
|
-
"install",
|
|
474
|
-
"postinstall",
|
|
475
|
-
"prepare",
|
|
476
|
-
"uninstall"
|
|
477
|
-
]);
|
|
478
|
-
const DEP_FIELDS = [
|
|
479
|
-
"dependencies",
|
|
480
|
-
"devDependencies",
|
|
481
|
-
"optionalDependencies",
|
|
482
|
-
"peerDependencies",
|
|
483
|
-
"overrides",
|
|
484
|
-
"resolutions"
|
|
485
|
-
];
|
|
486
|
-
const MONOREPO_PROTOCOLS = [
|
|
487
|
-
"catalog:",
|
|
488
|
-
"workspace:",
|
|
489
|
-
"link:",
|
|
490
|
-
"portal:"
|
|
491
|
-
];
|
|
492
|
-
/**
|
|
493
|
-
* Fields a consumer's toolchain resolves. Stripping one breaks installs, imports or
|
|
494
|
-
* platform gating, so `devFields` is not allowed to name them.
|
|
495
|
-
*/
|
|
496
|
-
const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
497
|
-
"config",
|
|
498
|
-
"deno",
|
|
499
|
-
"directories",
|
|
500
|
-
"jsdelivr",
|
|
501
|
-
"man",
|
|
502
|
-
"react-native",
|
|
503
|
-
"sass",
|
|
504
|
-
"style",
|
|
505
|
-
"styleModule",
|
|
506
|
-
"svelte",
|
|
507
|
-
"unpkg",
|
|
508
|
-
...DEP_FIELDS,
|
|
509
|
-
"bin",
|
|
510
|
-
"browser",
|
|
511
|
-
"bundleDependencies",
|
|
512
|
-
"bundledDependencies",
|
|
513
|
-
"cpu",
|
|
514
|
-
"engines",
|
|
515
|
-
"exports",
|
|
516
|
-
"imports",
|
|
517
|
-
"libc",
|
|
518
|
-
"license",
|
|
519
|
-
"main",
|
|
520
|
-
"module",
|
|
521
|
-
"name",
|
|
522
|
-
"os",
|
|
523
|
-
"peerDependenciesMeta",
|
|
524
|
-
"publishConfig",
|
|
525
|
-
"sideEffects",
|
|
526
|
-
"type",
|
|
527
|
-
"types",
|
|
528
|
-
"typesVersions",
|
|
529
|
-
"typings",
|
|
530
|
-
"version"
|
|
531
|
-
]);
|
|
532
|
-
/** Registry metadata is recognised; consumer-resolved fields are protected separately. */
|
|
533
|
-
const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
534
|
-
"author",
|
|
535
|
-
"bugs",
|
|
536
|
-
"contributors",
|
|
537
|
-
"description",
|
|
538
|
-
"funding",
|
|
539
|
-
"gitHead",
|
|
540
|
-
"homepage",
|
|
541
|
-
"keywords",
|
|
542
|
-
"maintainers",
|
|
543
|
-
"preferGlobal",
|
|
544
|
-
"repository",
|
|
545
|
-
"scripts"
|
|
546
|
-
]);
|
|
547
|
-
/**
|
|
548
|
-
* Shown when another package manager started this tool, so the pnpm requirement is not a
|
|
549
|
-
* surprise. It names the packer and the consequence for the reader's own layout, rather
|
|
550
|
-
* than claiming the alternatives are broken, because what a reader needs to do next
|
|
551
|
-
* depends on which package manager they came from.
|
|
552
|
-
*
|
|
553
|
-
* The measured comparison behind the choice of packer, and the standing rule against
|
|
554
|
-
* swapping it, live in this repository's AGENTS.md.
|
|
555
|
-
*/
|
|
556
|
-
const PUBLISH_ADVISORY = "publish-clean packs with pnpm: it resolves workspace: and catalog: specs from the packing package's own node_modules, so a Bun workspace works as-is and a Yarn one needs a pnpm-workspace.yaml plus one pnpm install. npm packs those specs unresolved.";
|
|
557
|
-
function stripManifest(pkg, extraDevFields) {
|
|
558
|
-
const stripped = { ...pkg };
|
|
559
|
-
for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
560
|
-
const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
561
|
-
if (scripts) {
|
|
562
|
-
if (Object.entries(scripts).some(([name, value]) => CONSUMER_SCRIPTS.has(name) && typeof value === "string")) stripped.scripts = scripts;
|
|
563
|
-
else delete stripped.scripts;
|
|
564
|
-
}
|
|
565
|
-
return stripped;
|
|
566
|
-
}
|
|
567
|
-
/** npm gives a scope registry priority over the general registry setting. */
|
|
568
|
-
function packageScope(pkg) {
|
|
569
|
-
if (typeof pkg.name !== "string" || !pkg.name.startsWith("@")) return null;
|
|
570
|
-
const slash = pkg.name.indexOf("/");
|
|
571
|
-
return slash > 1 ? pkg.name.slice(0, slash) : null;
|
|
572
|
-
}
|
|
573
|
-
/** A misspelled registry must fail locally rather than fall back to a public destination. */
|
|
574
|
-
function assertRegistry(value) {
|
|
575
|
-
if (typeof value !== "string" || !URL.canParse(value)) throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
|
|
576
|
-
const url = new URL(value);
|
|
577
|
-
if (url.protocol !== "http:" && url.protocol !== "https:") throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
|
|
578
|
-
if (url.username || url.password) throw new PublishCleanError("Registry URLs must not contain credentials. Configure npm authentication separately.");
|
|
579
|
-
}
|
|
580
|
-
/** Check every registry destination in the artifact without disclosing its credentials. */
|
|
581
|
-
function assertRegistryDestinations(pkg) {
|
|
582
|
-
if (!isObject(pkg.publishConfig)) return;
|
|
583
|
-
for (const [key, value] of Object.entries(pkg.publishConfig)) if (key === "registry" || key.endsWith(":registry")) assertRegistry(value);
|
|
584
|
-
}
|
|
585
|
-
/**
|
|
586
|
-
* Pins the published manifest to a registry, when one was chosen.
|
|
587
|
-
*
|
|
588
|
-
* Written into `publishConfig` rather than passed only on the command line, because that is
|
|
589
|
-
* where npm looks when someone later republishes the same tarball by hand — the artifact then
|
|
590
|
-
* carries its own destination instead of depending on whoever runs the command. Any other
|
|
591
|
-
* `publishConfig` keys the author set are consumer-facing and survive untouched.
|
|
592
|
-
*
|
|
593
|
-
* Returns the manifest unchanged when no registry was chosen, so the caller has no branch and
|
|
594
|
-
* cannot forget one.
|
|
595
|
-
*/
|
|
596
|
-
function withRegistry(pkg, registry) {
|
|
597
|
-
if (registry === null) return pkg;
|
|
598
|
-
assertRegistry(registry);
|
|
599
|
-
const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
|
|
600
|
-
publishConfig.registry = registry;
|
|
601
|
-
const scope = packageScope(pkg);
|
|
602
|
-
if (scope) publishConfig[`${scope}:registry`] = registry;
|
|
603
|
-
return {
|
|
604
|
-
...pkg,
|
|
605
|
-
publishConfig
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
/**
|
|
609
|
-
* Refuses a published manifest that lost a field the source declared and consumers read.
|
|
610
|
-
*
|
|
611
|
-
* Every other check here asks whether something got in that should not have. This asks the
|
|
612
|
-
* opposite, and nothing else does: cleaning is subtraction, so the way it fails is by
|
|
613
|
-
* taking too much. A dropped `repository` breaks provenance verification, a dropped
|
|
614
|
-
* `exports` makes the package unimportable, and neither leaves any trace in the artifact
|
|
615
|
-
* to notice later. The registry keeps the version forever either way.
|
|
616
|
-
*
|
|
617
|
-
* Read out of the published tarball rather than from the cleaned value in memory, so a loss
|
|
618
|
-
* introduced while rewriting the archive is caught as well as one introduced by stripping.
|
|
619
|
-
*
|
|
620
|
-
* `devFields` entries are exempt: removing those was the request. `scripts` is exempt
|
|
621
|
-
* because its entire block survives when consumer lifecycle hooks exist, and otherwise
|
|
622
|
-
* the development-only block is removed.
|
|
623
|
-
*/
|
|
624
|
-
function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
625
|
-
const expected = /* @__PURE__ */ new Set([
|
|
626
|
-
...DEV_FIELDS,
|
|
627
|
-
...removedOnRequest,
|
|
628
|
-
"scripts"
|
|
629
|
-
]);
|
|
630
|
-
const lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
|
|
631
|
-
if (lost.length > 0) throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${lost.join("\n")}`);
|
|
632
|
-
}
|
|
633
|
-
/**
|
|
634
|
-
* Names the fields that survived cleaning without anyone recognising them.
|
|
635
|
-
*
|
|
636
|
-
* The strip list can only ever describe tools that existed when it was written, so every new
|
|
637
|
-
* `package.json` key some tool invents ships to consumers until a human notices. This cannot
|
|
638
|
-
* be fixed by keeping only recognised fields: that would silently drop a key some consumer
|
|
639
|
-
* genuinely resolves, and the breakage would surface in a stranger's project rather than here.
|
|
640
|
-
* So the field ships, and the maintainer is told it did, with the exact config that would drop
|
|
641
|
-
* it next time. It is advice about the package, not an error in it — nothing about the
|
|
642
|
-
* published artifact depends on whether anyone reads it.
|
|
643
|
-
*
|
|
644
|
-
* Returned rather than printed, so the message is this function's value and can be asserted
|
|
645
|
-
* whole. Writing to `console` from here would make that assertion a spy on a process-wide
|
|
646
|
-
* object, which two cases running side by side can clobber.
|
|
647
|
-
*/
|
|
648
|
-
function unrecognizedFieldsReport(pkg, kept) {
|
|
649
|
-
const acknowledged = new Set(kept);
|
|
650
|
-
const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
|
|
651
|
-
if (unrecognized.length === 0) return null;
|
|
652
|
-
const quoted = unrecognized.map((field) => JSON.stringify(field));
|
|
653
|
-
const list = quoted.join(", ");
|
|
654
|
-
return `publish-clean: these manifest fields are not recognised and are retained as-is:\n ${quoted.join("\n ")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${list}] }\n "publish-clean": { "keepFields": [${list}] }`;
|
|
655
|
-
}
|
|
656
|
-
/**
|
|
657
|
-
* Refuses a manifest that still carries a spec only a workspace can resolve. Published
|
|
658
|
-
* with one, the package is uninstallable for everyone, and the version cannot be taken
|
|
659
|
-
* back.
|
|
660
|
-
*
|
|
661
|
-
* The caller passes an already-stripped manifest, so the dev-only members of DEP_FIELDS are
|
|
662
|
-
* absent by construction. They are still checked, because a guard whose correctness depends on
|
|
663
|
-
* the order it happens to be called in fails silently the day someone reorders it.
|
|
664
|
-
*/
|
|
665
|
-
function assertNoMonorepoProtocols(pkg, files = []) {
|
|
666
|
-
const failures = [];
|
|
667
|
-
const shipped = new Set(files);
|
|
668
|
-
for (const field of DEP_FIELDS) {
|
|
669
|
-
const map = pkg[field];
|
|
670
|
-
if (!isObject(map)) continue;
|
|
671
|
-
for (const [name, spec] of Object.entries(map)) {
|
|
672
|
-
if (typeof spec !== "string") continue;
|
|
673
|
-
const resolved = spec.startsWith("npm:") ? spec.slice(spec.lastIndexOf("@") + 1) : spec;
|
|
674
|
-
if (MONOREPO_PROTOCOLS.some((prefix) => resolved.startsWith(prefix))) failures.push(`${field}.${name}: ${spec}`);
|
|
675
|
-
if (/^(?:file:|git\+file:|\.{1,2}(?:[\\/]|$)|\/|~[\\/]|[a-z]:[\\/])/i.test(spec)) {
|
|
676
|
-
let local = null;
|
|
677
|
-
try {
|
|
678
|
-
local = normalizeDeclaredPath(decodeURIComponent(spec.replace(/^file:/i, "")));
|
|
679
|
-
} catch {}
|
|
680
|
-
if (!local || /[\\]/.test(local) || /^(?:git\+file:|~[\\/]|(?:file:)?[a-z]:[\\/])/i.test(spec) || !(/\.(?:tgz|tar\.gz|tar)$/.test(local) && shipped.has(local) || shipped.has(`${local}/package.json`))) failures.push(`${field}.${name}: ${spec} (local target is not in the artifact)`);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
685
|
-
}
|
|
686
|
-
function assertPublicPackage(pkg) {
|
|
687
|
-
if (pkg.private === true) throw new PublishCleanError("Refusing to publish a package with private: true.");
|
|
688
|
-
}
|
|
689
|
-
function assertFilesField(pkg, skip) {
|
|
690
|
-
if (skip) return;
|
|
691
|
-
if (!Array.isArray(pkg.files) || pkg.files.length === 0 || pkg.files.some((file) => typeof file !== "string" || !file.trim())) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array of non-empty strings.");
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
//#endregion
|
|
695
|
-
//#region src/config.ts
|
|
696
|
-
/**
|
|
697
|
-
* Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
|
|
698
|
-
* makes a typo an error instead of a silent no-op — and a silent no-op here is not cosmetic:
|
|
699
|
-
* `devFeilds` publishes the field the author meant to strip, and nothing in the output says so.
|
|
700
|
-
*/
|
|
701
|
-
const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
702
|
-
"allowSuspicious",
|
|
703
|
-
"devFields",
|
|
704
|
-
"keepFields",
|
|
705
|
-
"noGitChecks",
|
|
706
|
-
"registry",
|
|
707
|
-
"skipFileCheck"
|
|
708
|
-
]);
|
|
709
|
-
function packageConfig(pkg) {
|
|
710
|
-
const config = pkg["publish-clean"];
|
|
711
|
-
if (config === void 0) return {};
|
|
712
|
-
if (!isObject(config)) throw new PublishCleanError("\"publish-clean\" must be an object.");
|
|
713
|
-
const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
|
|
714
|
-
if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
|
|
715
|
-
for (const key of [
|
|
716
|
-
"allowSuspicious",
|
|
717
|
-
"noGitChecks",
|
|
718
|
-
"skipFileCheck"
|
|
719
|
-
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") throw new PublishCleanError(`publish-clean.${key} must be a boolean.`);
|
|
720
|
-
if (config.registry !== void 0) assertRegistry(config.registry);
|
|
721
|
-
stringList(config, "devFields");
|
|
722
|
-
stringList(config, "keepFields");
|
|
723
|
-
return config;
|
|
724
|
-
}
|
|
725
|
-
/**
|
|
726
|
-
* Reads a string-list option, refusing anything else outright rather than filtering it out.
|
|
727
|
-
* A number or a nested object in this list is a mistake in the manifest, and skipping it
|
|
728
|
-
* silently means the author's intent is lost with no signal anywhere.
|
|
729
|
-
*/
|
|
730
|
-
function stringList(config, key) {
|
|
731
|
-
const value = config[key];
|
|
732
|
-
if (value === void 0) return [];
|
|
733
|
-
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
|
|
734
|
-
return value;
|
|
735
|
-
}
|
|
736
|
-
function customDevFields(config) {
|
|
737
|
-
const fields = stringList(config, "devFields");
|
|
738
|
-
const kept = new Set(stringList(config, "keepFields"));
|
|
739
|
-
const contradictory = fields.filter((field) => kept.has(field));
|
|
740
|
-
if (contradictory.length > 0) throw new PublishCleanError(`These fields are listed as both devFields and keepFields, which asks to strip and to publish the same key:\n${contradictory.join("\n")}`);
|
|
741
|
-
const unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
|
|
742
|
-
if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
|
|
743
|
-
return fields;
|
|
744
|
-
}
|
|
745
|
-
/**
|
|
746
|
-
* Fields the maintainer has confirmed belong in the published package, so they stop being
|
|
747
|
-
* reported as unrecognised.
|
|
748
|
-
*
|
|
749
|
-
* Without this the report has only one resolution, `devFields`, which deletes the field.
|
|
750
|
-
* That is the wrong answer for every package whose ecosystem this tool has never heard of:
|
|
751
|
-
* a VS Code extension needs `contributes` and `publisher` in the artifact to function at
|
|
752
|
-
* all. Its author would face a warning on every release that can only be silenced by
|
|
753
|
-
* breaking the extension, and a warning nobody can act on trains everyone to ignore the
|
|
754
|
-
* next one, including a real leak.
|
|
755
|
-
*/
|
|
756
|
-
function keptFields(config) {
|
|
757
|
-
return stringList(config, "keepFields");
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
//#endregion
|
|
761
|
-
//#region src/options.ts
|
|
762
|
-
const PUBLISH_OPTIONS = /* @__PURE__ */ new Map([
|
|
763
|
-
["access", "string"],
|
|
764
|
-
["tag", "string"],
|
|
765
|
-
["otp", "string"],
|
|
766
|
-
["registry", "string"],
|
|
767
|
-
["provenance-file", "string"],
|
|
768
|
-
["provenance", "boolean"],
|
|
769
|
-
["dry-run", "boolean"],
|
|
770
|
-
["ignore-scripts", "boolean"],
|
|
771
|
-
["json", "boolean"],
|
|
772
|
-
["loglevel", "string"]
|
|
773
|
-
]);
|
|
774
|
-
/** npm reparses even equals-form values as flags; reject flag-shaped values before forwarding. */
|
|
775
|
-
function publicationArgs(args) {
|
|
776
|
-
const result = [];
|
|
777
|
-
for (let index = 0; index < args.length; index++) {
|
|
778
|
-
const arg = args[index] ?? "";
|
|
779
|
-
const equal = arg.indexOf("=");
|
|
780
|
-
const flag = equal < 0 ? arg : arg.slice(0, equal);
|
|
781
|
-
const negative = flag.startsWith("--no-");
|
|
782
|
-
const name = flag.slice(negative ? 5 : 2);
|
|
783
|
-
const type = flag.startsWith("--") ? PUBLISH_OPTIONS.get(name) : void 0;
|
|
784
|
-
if (!type || negative && type !== "boolean") throw new PublishCleanError(`After --, use publication options only: ${[...PUBLISH_OPTIONS.keys()].join(", ")}. Package operands and workspace selectors are forbidden.`);
|
|
785
|
-
let value = equal < 0 ? void 0 : arg.slice(equal + 1);
|
|
786
|
-
if (value === void 0 && (type === "string" || args[index + 1] === "true" || args[index + 1] === "false")) value = args[++index];
|
|
787
|
-
if (type === "boolean") {
|
|
788
|
-
value ??= "true";
|
|
789
|
-
if (value !== "true" && value !== "false") throw new PublishCleanError(`--${name} requires true or false.`);
|
|
790
|
-
if (negative) value = value === "true" ? "false" : "true";
|
|
791
|
-
} else if (!value || value.startsWith("-")) throw new PublishCleanError(`--${name} requires a value that does not start with -. Use ./ for a filename starting with -.`);
|
|
792
|
-
if (name === "registry") assertRegistry(value);
|
|
793
|
-
result.push(`--${name}=${value}`);
|
|
794
|
-
}
|
|
795
|
-
return result;
|
|
796
|
-
}
|
|
797
|
-
/**
|
|
798
|
-
* The whole interface in one screen, because this is where an out-of-context reader lands:
|
|
799
|
-
* the flags, the manifest config block that sets the same policies durably, and the `--`
|
|
800
|
-
* convention that decides which arguments this tool reads and which npm does. Anything a
|
|
801
|
-
* user must know to publish correctly belongs here, not only in the README, which is not
|
|
802
|
-
* installed next to the binary.
|
|
803
|
-
*/
|
|
804
|
-
const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
|
|
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
|
+
${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:
|
|
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=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=new Map,i=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
|
+
`+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
|
+
`)+`
|
|
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
|
+
`+s.map(e=>` ${e.file} — ${e.defect.reason}`).join(`
|
|
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);return}if(typeof e!=`boolean`){if(Array.isArray(e)){for(let r of e)collectDeclaredPaths(r,t,n);return}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<4294967295)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);return}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
|
+
`)}`);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){(!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)=>{if(h&&process.platform!==`win32`&&killGroup(`SIGKILL`),await g,clearTimeout(_),clearTimeout(m),r.signal?.removeEventListener(`abort`,stop),r.signal?.aborted){s(r.signal.reason);return}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=new Set(`$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=new Set([`preinstall`,`install`,`postinstall`,`prepare`,`uninstall`]),w=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`,`overrides`,`resolutions`],T=[`catalog:`,`workspace:`,`link:`,`portal:`],E=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=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=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
|
+
`)}`)}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
|
+
`)}\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=new Set([`allowSuspicious`,`allowUnreferenced`,`devFields`,`heal`,`keepFields`,`noGitChecks`,`registry`,`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`),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
|
+
`)}`);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===`
|
|
28
|
+
`&&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`){i&&n.push(e);return}if(Array.isArray(e)){for(let t of e)walk(t,i);return}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=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=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
|
+
`,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=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=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
|
+
`)}\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
|
+
${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=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
|
+
publish-clean verify [package-dir]
|
|
805
37
|
|
|
806
38
|
Packs with pnpm, strips developer-only fields from the packed manifest, validates the
|
|
807
39
|
artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
|
|
808
40
|
\`npm publish\` as publication options (e.g. --access public --tag next --provenance).
|
|
809
|
-
Allowed: ${[...
|
|
41
|
+
Allowed: ${[...B.keys()].map(e=>`--${e}`).join(`, `)}.
|
|
810
42
|
Additional package operands and workspace selectors are rejected.
|
|
811
43
|
|
|
812
44
|
Options:
|
|
45
|
+
verify [dir] Pack, clean and check; publish nothing. Works on private packages.
|
|
46
|
+
--verify-only The same as the verify subcommand, for scripts that take flags only.
|
|
47
|
+
--strict Treat warnings as errors. Never makes an already-repaired finding fatal.
|
|
48
|
+
--no-heal Report repairable exports/imports defects without repairing them.
|
|
813
49
|
--dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
|
|
814
|
-
--guard-only
|
|
50
|
+
--guard-only Deprecated alias for verify, on a public package.
|
|
815
51
|
--tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
|
|
816
52
|
--registry URL Publish to URL, and record it in the artifact's publishConfig.
|
|
817
53
|
--no-git-checks Publish from a working tree with uncommitted changes.
|
|
@@ -821,576 +57,22 @@ Options:
|
|
|
821
57
|
-v, --version Show the publish-clean version.
|
|
822
58
|
|
|
823
59
|
Manifest configuration, under a "publish-clean" key in package.json:
|
|
60
|
+
validateArtifact string[] Executable and arguments; appends the final tarball path in every mode.
|
|
824
61
|
devFields string[] Extra fields to strip. Refused for fields consumers resolve.
|
|
825
62
|
keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
|
|
826
63
|
registry string Default for --registry.
|
|
64
|
+
heal boolean Set false to report exports/imports repairs without applying them.
|
|
65
|
+
allowUnreferenced string[] Shipped files nothing imports on purpose: a binary a loader finds by
|
|
66
|
+
path, a directory read at run time. Matched as a prefix, so naming a
|
|
67
|
+
directory covers everything under it.
|
|
827
68
|
noGitChecks boolean Default for --no-git-checks.
|
|
828
69
|
skipFileCheck boolean Default for --skip-file-check.
|
|
829
70
|
allowSuspicious boolean Default for --allow-suspicious.
|
|
830
71
|
|
|
831
72
|
Preview modes do not test registry access, credentials or provenance eligibility.
|
|
832
|
-
Requires pnpm
|
|
833
|
-
npm 11.5.1+, and only a cloud CI
|
|
834
|
-
function parseOptions(rawArgs) {
|
|
835
|
-
const separator = rawArgs.indexOf("--");
|
|
836
|
-
const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
|
|
837
|
-
const publishArgs = publicationArgs(separator === -1 ? [] : rawArgs.slice(separator + 1));
|
|
838
|
-
return {
|
|
839
|
-
...parseArgs({
|
|
840
|
-
args: cliArgs,
|
|
841
|
-
allowPositionals: true,
|
|
842
|
-
options: {
|
|
843
|
-
"allow-suspicious": {
|
|
844
|
-
type: "boolean",
|
|
845
|
-
default: false
|
|
846
|
-
},
|
|
847
|
-
"dry-run": {
|
|
848
|
-
type: "boolean",
|
|
849
|
-
default: false
|
|
850
|
-
},
|
|
851
|
-
"guard-only": {
|
|
852
|
-
type: "boolean",
|
|
853
|
-
default: false
|
|
854
|
-
},
|
|
855
|
-
help: {
|
|
856
|
-
type: "boolean",
|
|
857
|
-
short: "h",
|
|
858
|
-
default: false
|
|
859
|
-
},
|
|
860
|
-
"no-git-checks": {
|
|
861
|
-
type: "boolean",
|
|
862
|
-
default: false
|
|
863
|
-
},
|
|
864
|
-
registry: {
|
|
865
|
-
type: "string",
|
|
866
|
-
default: void 0
|
|
867
|
-
},
|
|
868
|
-
"skip-file-check": {
|
|
869
|
-
type: "boolean",
|
|
870
|
-
default: false
|
|
871
|
-
},
|
|
872
|
-
"tarball-out": {
|
|
873
|
-
type: "string",
|
|
874
|
-
default: void 0
|
|
875
|
-
},
|
|
876
|
-
version: {
|
|
877
|
-
type: "boolean",
|
|
878
|
-
short: "v",
|
|
879
|
-
default: false
|
|
880
|
-
}
|
|
881
|
-
},
|
|
882
|
-
strict: true
|
|
883
|
-
}),
|
|
884
|
-
publishArgs
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
//#endregion
|
|
889
|
-
//#region src/tarball.ts
|
|
890
|
-
/** Read effective archive paths and rewrite only the manifest, preserving every other raw entry. */
|
|
891
|
-
const BLOCK = 512;
|
|
892
|
-
const NAME_LEN = 100;
|
|
893
|
-
const SIZE_OFFSET = 124;
|
|
894
|
-
const CHECKSUM_OFFSET = 148;
|
|
895
|
-
const TYPE_OFFSET = 156;
|
|
896
|
-
const MANIFEST_PATH = "package/package.json";
|
|
897
|
-
const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
|
|
898
|
-
const DIRECTORY_TYPE = "5";
|
|
899
|
-
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
900
|
-
function field(block, offset, length) {
|
|
901
|
-
const bytes = block.subarray(offset, offset + length);
|
|
902
|
-
const nul = bytes.indexOf(0);
|
|
903
|
-
return UTF8.decode(nul < 0 ? bytes : bytes.subarray(0, nul));
|
|
904
|
-
}
|
|
905
|
-
function entrySize(block) {
|
|
906
|
-
const value = field(block, SIZE_OFFSET, 12).trim();
|
|
907
|
-
if (!/^[0-7]+$/.test(value)) throw new PublishCleanError("Tarball entry has an unreadable size field.");
|
|
908
|
-
return Number.parseInt(value, 8);
|
|
909
|
-
}
|
|
910
|
-
/** PAX lengths count bytes, including their own digits; values may contain newlines. */
|
|
911
|
-
function paxFields(payload) {
|
|
912
|
-
const fields = /* @__PURE__ */ new Map();
|
|
913
|
-
for (let offset = 0; offset < payload.length;) {
|
|
914
|
-
const space = payload.indexOf(32, offset);
|
|
915
|
-
const digits = payload.toString("ascii", offset, space < 0 ? offset : space);
|
|
916
|
-
const length = Number(digits);
|
|
917
|
-
const end = offset + length;
|
|
918
|
-
const equals = payload.indexOf(61, space + 1);
|
|
919
|
-
if (!/^[1-9][0-9]*$/.test(digits) || !Number.isSafeInteger(length) || end > payload.length || equals <= space + 1 || equals >= end - 1 || payload[end - 1] !== 10) throw new PublishCleanError("Tarball has a malformed PAX record.");
|
|
920
|
-
const key = UTF8.decode(payload.subarray(space + 1, equals));
|
|
921
|
-
const value = UTF8.decode(payload.subarray(equals + 1, end - 1));
|
|
922
|
-
if (key.includes("sparse") || key === "hdrcharset") throw new PublishCleanError(`Tarball uses unsupported PAX ${key}.`);
|
|
923
|
-
fields.set(key, value);
|
|
924
|
-
offset = end;
|
|
925
|
-
}
|
|
926
|
-
return fields;
|
|
927
|
-
}
|
|
928
|
-
/**
|
|
929
|
-
* Verifies a header block against the checksum tar stores inside it.
|
|
930
|
-
*
|
|
931
|
-
* This is the format's own integrity check over the 512 bytes that say where an entry starts,
|
|
932
|
-
* how long it is and what it is called — the fields a walk trusts absolutely. The gzip CRC
|
|
933
|
-
* already covers every byte of the archive, so on a packed tarball this is redundant; it is
|
|
934
|
-
* here because the rewrite AUTHORS one of these blocks, and a checksum nothing verifies is a
|
|
935
|
-
* value vouching for itself. Reading the written artifact back runs this over that block.
|
|
936
|
-
*
|
|
937
|
-
* Both sums are accepted because tar has two historical conventions: the standard sums the
|
|
938
|
-
* bytes unsigned, while older implementations summed them as signed chars. The two agree for
|
|
939
|
-
* every all-ASCII header and diverge the moment a name carries a byte above 127, so refusing
|
|
940
|
-
* the signed form would reject valid archives holding non-ASCII filenames.
|
|
941
|
-
*/
|
|
942
|
-
function assertChecksum(header, name) {
|
|
943
|
-
const stored = Number.parseInt(field(header, CHECKSUM_OFFSET, 8).trim(), 8);
|
|
944
|
-
let unsigned = 0;
|
|
945
|
-
let signed = 0;
|
|
946
|
-
for (const [index, byte] of header.entries()) {
|
|
947
|
-
const value = index >= CHECKSUM_OFFSET && index < 156 ? 32 : byte;
|
|
948
|
-
unsigned += value;
|
|
949
|
-
signed += value > 127 ? value - 256 : value;
|
|
950
|
-
}
|
|
951
|
-
if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
|
|
952
|
-
}
|
|
953
|
-
/** Rebuilds a header for a changed payload size, keeping every other field of the original. */
|
|
954
|
-
function reheader(original, size) {
|
|
955
|
-
const header = Buffer.from(original);
|
|
956
|
-
header.write(size.toString(8).padStart(11, "0") + "\0", SIZE_OFFSET, 12, "ascii");
|
|
957
|
-
header.write(" ".repeat(8), CHECKSUM_OFFSET, 8, "ascii");
|
|
958
|
-
let sum = 0;
|
|
959
|
-
for (const byte of header) sum += byte;
|
|
960
|
-
header.write(sum.toString(8).padStart(6, "0") + "\0 ", CHECKSUM_OFFSET, 8, "ascii");
|
|
961
|
-
return header;
|
|
962
|
-
}
|
|
963
|
-
/**
|
|
964
|
-
* Decodes a gzipped tarball into its entries, refusing every shape whose meaning this tool
|
|
965
|
-
* cannot state unambiguously.
|
|
966
|
-
*
|
|
967
|
-
* A duplicate manifest is a refusal rather than a last-one-wins guess, because extractors
|
|
968
|
-
* disagree about which survives and the published manifest would then depend on the extractor
|
|
969
|
-
* rather than on this tool. A short final block is a truncation: an archive that ends
|
|
970
|
-
* mid-entry would otherwise read as a valid one that simply stops, which is exactly how a
|
|
971
|
-
* partial write becomes a published package.
|
|
972
|
-
*/
|
|
973
|
-
function readArchive(gzipped) {
|
|
974
|
-
const tar = gunzipSync(gzipped);
|
|
975
|
-
const entries = [];
|
|
976
|
-
const names = /* @__PURE__ */ new Set();
|
|
977
|
-
let local = null;
|
|
978
|
-
let tail = null;
|
|
979
|
-
for (let offset = 0; offset < tar.length;) {
|
|
980
|
-
const header = tar.subarray(offset, offset + BLOCK);
|
|
981
|
-
if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
|
|
982
|
-
if (header.every((byte) => byte === 0)) {
|
|
983
|
-
tail = tar.subarray(offset);
|
|
984
|
-
if (tail.length < BLOCK * 2 || tail.length % BLOCK || tail.some((byte) => byte !== 0)) throw new PublishCleanError("Tarball has an invalid end-of-archive marker.");
|
|
985
|
-
break;
|
|
986
|
-
}
|
|
987
|
-
const type = field(header, TYPE_OFFSET, 1);
|
|
988
|
-
const rawName = [field(header, 257, 6) === "ustar" ? field(header, 345, 155) : "", field(header, 0, NAME_LEN)].filter(Boolean).join("/");
|
|
989
|
-
assertChecksum(header, rawName);
|
|
990
|
-
const extended = PAX_TYPES.has(type);
|
|
991
|
-
const name = extended ? rawName : local?.get("path") || rawName;
|
|
992
|
-
let size = entrySize(header);
|
|
993
|
-
const sizeOverride = !extended && local?.get("size");
|
|
994
|
-
if (sizeOverride) {
|
|
995
|
-
if (!/^[0-9]+$/.test(sizeOverride) || !Number.isSafeInteger(Number(sizeOverride))) throw new PublishCleanError("Tarball has an invalid PAX size.");
|
|
996
|
-
size = Number(sizeOverride);
|
|
997
|
-
}
|
|
998
|
-
const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
|
|
999
|
-
if (!Number.isSafeInteger(end) || end > tar.length) throw new PublishCleanError(`Tarball entry ${JSON.stringify(name)} runs past the end of the archive.`);
|
|
1000
|
-
const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
|
|
1001
|
-
if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
|
|
1002
|
-
if (extended) {
|
|
1003
|
-
const fields = paxFields(body);
|
|
1004
|
-
if (fields.get("path") === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
|
|
1005
|
-
if (type === "g") {
|
|
1006
|
-
if ([
|
|
1007
|
-
"path",
|
|
1008
|
-
"size",
|
|
1009
|
-
"linkpath"
|
|
1010
|
-
].some((key) => fields.has(key))) throw new PublishCleanError("Tarball has a global PAX path, linkpath or size override.");
|
|
1011
|
-
} else {
|
|
1012
|
-
if (local) throw new PublishCleanError("Tarball has consecutive PAX extended headers.");
|
|
1013
|
-
local = fields;
|
|
1014
|
-
}
|
|
1015
|
-
} else {
|
|
1016
|
-
if (name === MANIFEST_PATH) {
|
|
1017
|
-
if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
|
|
1018
|
-
if (sizeOverride) throw new PublishCleanError("Tarball manifest has a PAX size override that cannot survive rewriting.");
|
|
1019
|
-
}
|
|
1020
|
-
const parts = name.replace(/\/$/, "").split("/");
|
|
1021
|
-
if (parts[0] !== "package" || parts.some((part) => !part || part === "." || part === "..") || name.includes("\\") || name.includes("\0")) throw new PublishCleanError(`Tarball has an unsafe entry path: ${JSON.stringify(name)}.`);
|
|
1022
|
-
if (names.has(name)) throw new PublishCleanError(`Tarball contains ${JSON.stringify(name)} more than once.`);
|
|
1023
|
-
names.add(name);
|
|
1024
|
-
local = null;
|
|
1025
|
-
}
|
|
1026
|
-
entries.push({
|
|
1027
|
-
name,
|
|
1028
|
-
type,
|
|
1029
|
-
header,
|
|
1030
|
-
body,
|
|
1031
|
-
raw: tar.subarray(offset, end)
|
|
1032
|
-
});
|
|
1033
|
-
offset = end;
|
|
1034
|
-
}
|
|
1035
|
-
if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
|
|
1036
|
-
if (local) throw new PublishCleanError("Tarball ends with an unused PAX extended header.");
|
|
1037
|
-
return {
|
|
1038
|
-
entries,
|
|
1039
|
-
tail
|
|
1040
|
-
};
|
|
1041
|
-
}
|
|
1042
|
-
/** Check the final readback against the packed bytes, including entry order and metadata. */
|
|
1043
|
-
function assertPreservedArchive(before, after) {
|
|
1044
|
-
if (before.entries.length !== after.entries.length || !before.tail.equals(after.tail)) throw new PublishCleanError("Rewriting the manifest changed the archive structure.");
|
|
1045
|
-
for (const [index, original] of before.entries.entries()) {
|
|
1046
|
-
const result = after.entries[index];
|
|
1047
|
-
if (!result || original.name !== result.name || original.type !== result.type || (original.name === MANIFEST_PATH && !PAX_TYPES.has(original.type) ? !reheader(original.header, result.body.length).equals(result.header) : !original.raw.equals(result.raw))) throw new PublishCleanError(`Rewriting the manifest changed archive entry ${JSON.stringify(original.name)}.`);
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
/**
|
|
1051
|
-
* The paths a consumer's installer writes, with the `package/` prefix stripped — the list every
|
|
1052
|
-
* content guard judges. Directories and pax headers are dropped: neither is a file anyone
|
|
1053
|
-
* imports, and a pax header's own name (`PaxHeader`) names no file at all.
|
|
1054
|
-
*/
|
|
1055
|
-
function packageFiles(archive) {
|
|
1056
|
-
return archive.entries.filter((entry) => entry.type !== DIRECTORY_TYPE && !PAX_TYPES.has(entry.type)).map((entry) => entry.name.startsWith("package/") ? entry.name.slice(8) : entry.name).filter((name) => name.length > 0 && !name.endsWith("/")).sort();
|
|
1057
|
-
}
|
|
1058
|
-
function manifestEntry(archive) {
|
|
1059
|
-
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH && !PAX_TYPES.has(candidate.type));
|
|
1060
|
-
if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
|
|
1061
|
-
return entry;
|
|
1062
|
-
}
|
|
1063
|
-
/** The manifest exactly as the archive carries it, for parsing by the caller. */
|
|
1064
|
-
function manifestText(archive) {
|
|
1065
|
-
return manifestEntry(archive).body.toString("utf8");
|
|
1066
|
-
}
|
|
1067
|
-
/** Returns the gzipped tarball with `package/package.json` replaced by `manifest`. */
|
|
1068
|
-
function replaceManifest(archive, manifest) {
|
|
1069
|
-
const target = manifestEntry(archive);
|
|
1070
|
-
const body = Buffer.from(manifest, "utf8");
|
|
1071
|
-
const parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
|
|
1072
|
-
reheader(entry.header, body.length),
|
|
1073
|
-
body,
|
|
1074
|
-
Buffer.alloc(BLOCK * Math.ceil(body.length / BLOCK) - body.length)
|
|
1075
|
-
]) : entry.raw);
|
|
1076
|
-
parts.push(archive.tail);
|
|
1077
|
-
return gzipSync(Buffer.concat(parts), { level: 9 });
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
//#endregion
|
|
1081
|
-
//#region src/trusted-publish.ts
|
|
1082
|
-
/**
|
|
1083
|
-
* Who npm will believe is publishing, and what the toolchain must be for it to sign anything.
|
|
1084
|
-
*
|
|
1085
|
-
* Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
|
|
1086
|
-
* argv here. `cli.ts` owns the effects.
|
|
1087
|
-
*/
|
|
1088
|
-
/**
|
|
1089
|
-
* The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
|
|
1090
|
-
* message so the version a reader is told to install is the version the comparison made.
|
|
1091
|
-
*
|
|
1092
|
-
* These floors apply to trusted publication; ordinary token-based publication can use the
|
|
1093
|
-
* lower Node floor declared by engines.node.
|
|
1094
|
-
*/
|
|
1095
|
-
const MIN_TRUSTED_NPM_VERSION = [
|
|
1096
|
-
11,
|
|
1097
|
-
5,
|
|
1098
|
-
1
|
|
1099
|
-
];
|
|
1100
|
-
const MIN_TRUSTED_NODE_VERSION = [
|
|
1101
|
-
22,
|
|
1102
|
-
14,
|
|
1103
|
-
0
|
|
1104
|
-
];
|
|
1105
|
-
function isAtLeast(actual, minimum) {
|
|
1106
|
-
for (const index of [
|
|
1107
|
-
0,
|
|
1108
|
-
1,
|
|
1109
|
-
2
|
|
1110
|
-
]) {
|
|
1111
|
-
if (actual[index] > minimum[index]) return true;
|
|
1112
|
-
if (actual[index] < minimum[index]) return false;
|
|
1113
|
-
}
|
|
1114
|
-
return true;
|
|
1115
|
-
}
|
|
1116
|
-
function wantsTrustedPublish(pkg, publishArgs, env) {
|
|
1117
|
-
if (env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string") return true;
|
|
1118
|
-
for (let index = publishArgs.length - 1; index >= 0; index--) {
|
|
1119
|
-
if (publishArgs[index] === "--provenance=true" || publishArgs[index] === "--provenance") return true;
|
|
1120
|
-
if (publishArgs[index] === "--provenance=false") return false;
|
|
1121
|
-
}
|
|
1122
|
-
if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance !== void 0) return Boolean(pkg.publishConfig.provenance);
|
|
1123
|
-
}
|
|
1124
|
-
function repositoryUrl(pkg) {
|
|
1125
|
-
if (typeof pkg.repository === "string") return pkg.repository;
|
|
1126
|
-
if (isObject(pkg.repository) && typeof pkg.repository.url === "string") return pkg.repository.url;
|
|
1127
|
-
return null;
|
|
1128
|
-
}
|
|
1129
|
-
function githubRepositorySlug(url) {
|
|
1130
|
-
const withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
|
|
1131
|
-
if (withoutGitPrefix.startsWith("git@github.com:")) {
|
|
1132
|
-
const slug = withoutGitPrefix.slice(15);
|
|
1133
|
-
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
1134
|
-
}
|
|
1135
|
-
try {
|
|
1136
|
-
const parsed = new URL(withoutGitPrefix);
|
|
1137
|
-
if (parsed.hostname !== "github.com") return null;
|
|
1138
|
-
const slug = parsed.pathname.replace(/^\/+/, "");
|
|
1139
|
-
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
1140
|
-
} catch {
|
|
1141
|
-
return null;
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
function assertRepositoryForTrustedPublish(pkg, env) {
|
|
1145
|
-
if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
|
|
1146
|
-
const repoUrl = repositoryUrl(pkg);
|
|
1147
|
-
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
1148
|
-
if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
//#endregion
|
|
1152
|
-
//#region src/cli.ts
|
|
1153
|
-
/**
|
|
1154
|
-
* Read from the installed manifest rather than baked in at build time, so the number cannot
|
|
1155
|
-
* drift from the package a user actually has — which is the only reason anyone asks a tool
|
|
1156
|
-
* for its version.
|
|
1157
|
-
*/
|
|
1158
|
-
function ownVersion() {
|
|
1159
|
-
const manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
|
|
1160
|
-
return typeof manifest.version === "string" ? manifest.version : "unknown";
|
|
1161
|
-
}
|
|
1162
|
-
function readJson(file) {
|
|
1163
|
-
let parsed;
|
|
1164
|
-
try {
|
|
1165
|
-
parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
1166
|
-
} catch (cause) {
|
|
1167
|
-
throw new PublishCleanError(`Unable to parse JSON file: ${file}`, { cause });
|
|
1168
|
-
}
|
|
1169
|
-
if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
|
|
1170
|
-
return parsed;
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Asks an executable on PATH what version it is, e.g. `24.15.0` from node's `v24.15.0`.
|
|
1174
|
-
*
|
|
1175
|
-
* Both provenance floors are asked of PATH rather than read from this process, because the
|
|
1176
|
-
* process that has to satisfy them is npm's, not this one. `npm` is a `#!/usr/bin/env node`
|
|
1177
|
-
* script, so the Node enforcing the floor is whichever one PATH resolves — and that is not
|
|
1178
|
-
* necessarily the one executing this file. Under Bun the gap is total: `process.versions.node`
|
|
1179
|
-
* is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
|
|
1180
|
-
* so reading it would answer a question nobody asked while looking exactly like a check.
|
|
1181
|
-
*/
|
|
1182
|
-
function toolVersion(command, version) {
|
|
1183
|
-
const raw = version.trim().replace(/^v/, "");
|
|
1184
|
-
const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
|
|
1185
|
-
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
|
|
1186
|
-
return [
|
|
1187
|
-
parts[0] ?? 0,
|
|
1188
|
-
parts[1] ?? 0,
|
|
1189
|
-
parts[2] ?? 0
|
|
1190
|
-
];
|
|
1191
|
-
}
|
|
1192
|
-
/**
|
|
1193
|
-
* The single place the ambient environment is read for publish decisions. Naming the three
|
|
1194
|
-
* variables here keeps `process` out of the rules and makes the whole environmental surface of
|
|
1195
|
-
* a publish visible at once, rather than spread across the guards that consult it.
|
|
1196
|
-
*/
|
|
1197
|
-
function publishEnv() {
|
|
1198
|
-
return {
|
|
1199
|
-
ACTIONS_ID_TOKEN_REQUEST_URL: process.env.ACTIONS_ID_TOKEN_REQUEST_URL,
|
|
1200
|
-
GITHUB_ACTIONS: process.env.GITHUB_ACTIONS,
|
|
1201
|
-
GITHUB_REPOSITORY: process.env.GITHUB_REPOSITORY
|
|
1202
|
-
};
|
|
1203
|
-
}
|
|
1204
|
-
async function assertTrustedPublishingRuntime(cwd, npmVersion, signal) {
|
|
1205
|
-
const npm = toolVersion("npm", npmVersion);
|
|
1206
|
-
if (!isAtLeast(npm, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${npm.join(".")}.`);
|
|
1207
|
-
const node = toolVersion("node", await requireTool("node", cwd, signal));
|
|
1208
|
-
if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
|
|
1209
|
-
throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
|
|
1210
|
-
}
|
|
1211
|
-
function warnIfNonPnpmLifecycle() {
|
|
1212
|
-
const userAgent = process.env.npm_config_user_agent;
|
|
1213
|
-
if (!userAgent || userAgent.startsWith("pnpm/")) return;
|
|
1214
|
-
console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
|
|
1215
|
-
}
|
|
1216
|
-
async function assertCleanGit(packageDir, skip, signal) {
|
|
1217
|
-
if (skip) return;
|
|
1218
|
-
const output = (await run("git", [
|
|
1219
|
-
"status",
|
|
1220
|
-
"--porcelain",
|
|
1221
|
-
"--",
|
|
1222
|
-
"."
|
|
1223
|
-
], packageDir, { signal })).trim();
|
|
1224
|
-
if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
|
|
1225
|
-
}
|
|
1226
|
-
/**
|
|
1227
|
-
* Reads an archive from disk, so every judgement is made about bytes that exist as a file
|
|
1228
|
-
* rather than about a buffer this process is holding. The final artifact is read back this
|
|
1229
|
-
* way after it is written, which also proves the write itself landed whole.
|
|
1230
|
-
*/
|
|
1231
|
-
async function readTarball(tarball) {
|
|
1232
|
-
return readArchive(await readFile(tarball));
|
|
1233
|
-
}
|
|
1234
|
-
function manifestOf(archive, label) {
|
|
1235
|
-
let parsed;
|
|
1236
|
-
try {
|
|
1237
|
-
parsed = JSON.parse(manifestText(archive));
|
|
1238
|
-
} catch (cause) {
|
|
1239
|
-
throw new PublishCleanError(`Unable to parse package.json inside ${label}.`, { cause });
|
|
1240
|
-
}
|
|
1241
|
-
if (!isObject(parsed)) throw new PublishCleanError(`package.json inside ${label} must contain a JSON object.`);
|
|
1242
|
-
return parsed;
|
|
1243
|
-
}
|
|
1244
|
-
/**
|
|
1245
|
-
* Locates the tarball `pnpm pack` just produced by reading its destination directory.
|
|
1246
|
-
*
|
|
1247
|
-
* The pack targets a directory this process created and owns exclusively, so the result is
|
|
1248
|
-
* discoverable without interpreting the packer's output at all. That matters because `pack`
|
|
1249
|
-
* runs the package's `prepare`/`prepack` lifecycle scripts and forwards their stdout: any
|
|
1250
|
-
* build tool that logs — most of them — lands ahead of a `--json` payload and breaks a parse
|
|
1251
|
-
* of that stream. Reading the directory is immune to whatever a foreign package's scripts
|
|
1252
|
-
* choose to print.
|
|
1253
|
-
*
|
|
1254
|
-
* Exactly one tarball is the invariant, not a convenience: more than one means the
|
|
1255
|
-
* destination was not exclusive and the wrong artifact could be published.
|
|
1256
|
-
*/
|
|
1257
|
-
async function soleTarball(packRoot) {
|
|
1258
|
-
const tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz"));
|
|
1259
|
-
const [tarball] = tarballs;
|
|
1260
|
-
if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
|
|
1261
|
-
return path.join(packRoot, tarball);
|
|
1262
|
-
}
|
|
1263
|
-
async function packAndClean(packageDir, signal, opts) {
|
|
1264
|
-
const [, npmVersion] = await Promise.all([requireTool("pnpm", packageDir, signal), requireTool("npm", packageDir, signal)]);
|
|
1265
|
-
warnIfNonPnpmLifecycle();
|
|
1266
|
-
const sourcePkg = readJson(path.join(packageDir, "package.json"));
|
|
1267
|
-
const config = packageConfig(sourcePkg);
|
|
1268
|
-
const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
|
|
1269
|
-
const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
|
|
1270
|
-
const noGitChecks = opts.noGitChecks || config.noGitChecks === true;
|
|
1271
|
-
const registry = opts.registry ?? (typeof config.registry === "string" ? config.registry : null);
|
|
1272
|
-
const extraDevFields = customDevFields(config);
|
|
1273
|
-
const keepFields = keptFields(config);
|
|
1274
|
-
assertPublicPackage(sourcePkg);
|
|
1275
|
-
await assertCleanGit(packageDir, noGitChecks, signal);
|
|
1276
|
-
assertFilesField(sourcePkg, skipFileCheck);
|
|
1277
|
-
const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
|
|
1278
|
-
try {
|
|
1279
|
-
await run("pnpm", [
|
|
1280
|
-
"pack",
|
|
1281
|
-
"--pack-destination",
|
|
1282
|
-
root
|
|
1283
|
-
], packageDir, {
|
|
1284
|
-
signal,
|
|
1285
|
-
output: "pack"
|
|
1286
|
-
});
|
|
1287
|
-
const finalTarball = await soleTarball(root);
|
|
1288
|
-
const packed = await readTarball(finalTarball);
|
|
1289
|
-
const packedPkg = manifestOf(packed, "the packed tarball");
|
|
1290
|
-
assertPublicPackage(packedPkg);
|
|
1291
|
-
const cleanedPkg = withRegistry(stripManifest(packedPkg, extraDevFields), registry);
|
|
1292
|
-
const cleanedText = stringifyJson(cleanedPkg);
|
|
1293
|
-
const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
|
|
1294
|
-
if (unrecognized) console.warn(unrecognized);
|
|
1295
|
-
await writeFile(finalTarball, replaceManifest(packed, cleanedText));
|
|
1296
|
-
const published = await readTarball(finalTarball);
|
|
1297
|
-
const finalFiles = packageFiles(published);
|
|
1298
|
-
assertSameEntries(packageFiles(packed), finalFiles);
|
|
1299
|
-
assertPreservedArchive(packed, published);
|
|
1300
|
-
validatePackedFiles(finalFiles, allowSuspicious);
|
|
1301
|
-
const shippedPkg = manifestOf(published, "the published tarball");
|
|
1302
|
-
assertRegistryDestinations(shippedPkg);
|
|
1303
|
-
assertDeclaredFiles(shippedPkg, finalFiles);
|
|
1304
|
-
assertNoMonorepoProtocols(shippedPkg, finalFiles);
|
|
1305
|
-
assertNoLostConsumerFields(packedPkg, shippedPkg, extraDevFields);
|
|
1306
|
-
if (manifestText(published) !== cleanedText) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
|
|
1307
|
-
if (opts.tarballOut !== null) {
|
|
1308
|
-
await mkdir(opts.tarballOut, { recursive: true });
|
|
1309
|
-
const kept = path.join(opts.tarballOut, path.basename(finalTarball));
|
|
1310
|
-
await copyFile(finalTarball, kept);
|
|
1311
|
-
console.log(`Final tarball kept at: ${kept}`);
|
|
1312
|
-
}
|
|
1313
|
-
if (opts.dryRun) {
|
|
1314
|
-
console.log(`[dry-run] ${finalFiles.length} files:`);
|
|
1315
|
-
for (const file of finalFiles) console.log(` ${JSON.stringify(file)}`);
|
|
1316
|
-
console.log(`[dry-run] cleaned package.json:\n${cleanedText}`);
|
|
1317
|
-
return;
|
|
1318
|
-
}
|
|
1319
|
-
if (opts.guardOnly) return;
|
|
1320
|
-
const env = publishEnv();
|
|
1321
|
-
let trusted = wantsTrustedPublish(shippedPkg, opts.publishArgs, env);
|
|
1322
|
-
if (trusted === void 0) {
|
|
1323
|
-
const value = (await run("npm", [
|
|
1324
|
-
"config",
|
|
1325
|
-
"get",
|
|
1326
|
-
"provenance"
|
|
1327
|
-
], packageDir, {
|
|
1328
|
-
signal,
|
|
1329
|
-
timeout: 1e4
|
|
1330
|
-
})).trim();
|
|
1331
|
-
if (value !== "true" && value !== "false") throw new PublishCleanError("npm config get provenance must return true or false.");
|
|
1332
|
-
trusted = value === "true";
|
|
1333
|
-
}
|
|
1334
|
-
if (trusted) {
|
|
1335
|
-
await assertTrustedPublishingRuntime(packageDir, npmVersion, signal);
|
|
1336
|
-
assertRepositoryForTrustedPublish(shippedPkg, env);
|
|
1337
|
-
}
|
|
1338
|
-
const scope = packageScope(shippedPkg);
|
|
1339
|
-
const publishArgs = [
|
|
1340
|
-
"publish",
|
|
1341
|
-
finalTarball,
|
|
1342
|
-
...opts.publishArgs
|
|
1343
|
-
];
|
|
1344
|
-
if (registry) {
|
|
1345
|
-
publishArgs.push("--registry", registry);
|
|
1346
|
-
if (scope) publishArgs.push(`--${scope}:registry=${registry}`);
|
|
1347
|
-
}
|
|
1348
|
-
await run("npm", publishArgs, packageDir, {
|
|
1349
|
-
signal,
|
|
1350
|
-
output: "publish"
|
|
1351
|
-
});
|
|
1352
|
-
} finally {
|
|
1353
|
-
await rm(root, {
|
|
1354
|
-
recursive: true,
|
|
1355
|
-
force: true
|
|
1356
|
-
});
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
async function main(signal) {
|
|
1360
|
-
const parsed = parseOptions(process.argv.slice(2));
|
|
1361
|
-
const { publishArgs } = parsed;
|
|
1362
|
-
if (parsed.values.version) {
|
|
1363
|
-
console.log(ownVersion());
|
|
1364
|
-
return;
|
|
1365
|
-
}
|
|
1366
|
-
if (parsed.values.help) {
|
|
1367
|
-
console.log(HELP);
|
|
1368
|
-
return;
|
|
1369
|
-
}
|
|
1370
|
-
if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
|
|
1371
|
-
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), signal, {
|
|
1372
|
-
allowSuspicious: parsed.values["allow-suspicious"] === true,
|
|
1373
|
-
dryRun: parsed.values["dry-run"] === true,
|
|
1374
|
-
guardOnly: parsed.values["guard-only"] === true,
|
|
1375
|
-
noGitChecks: parsed.values["no-git-checks"] === true,
|
|
1376
|
-
publishArgs,
|
|
1377
|
-
registry: typeof parsed.values.registry === "string" ? parsed.values.registry : null,
|
|
1378
|
-
skipFileCheck: parsed.values["skip-file-check"] === true,
|
|
1379
|
-
tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
|
|
1380
|
-
});
|
|
1381
|
-
}
|
|
1382
|
-
const cancellation = new AbortController();
|
|
1383
|
-
let interrupted = false;
|
|
1384
|
-
for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]]) process.on(signal, () => {
|
|
1385
|
-
interrupted = true;
|
|
1386
|
-
process.exitCode = code;
|
|
1387
|
-
cancellation.abort(new PublishCleanError(`Cancelled by ${signal}.`));
|
|
1388
|
-
});
|
|
1389
|
-
main(cancellation.signal).catch((error) => {
|
|
1390
|
-
console.error("publish-clean:", error instanceof PublishCleanError ? error.message : error);
|
|
1391
|
-
if (error instanceof PublishCleanError && error.cause) console.error("Caused by:", error.cause);
|
|
1392
|
-
if (!interrupted) process.exitCode = 1;
|
|
1393
|
-
});
|
|
73
|
+
Requires pnpm on PATH; npm as well to publish, since only the upload uses it. npm
|
|
74
|
+
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(`
|
|
1394
76
|
|
|
1395
|
-
|
|
1396
|
-
|
|
77
|
+
`));let x;try{x=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`,x],e,{signal:a,output:`pack`});let r=await soleTarball(x),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=reviewExports(withRegistry(stripManifest(c,_),g),{files:new Set(p),heal:u.heal&&f.heal!==!1}),b=[...h.findings,...reviewUnrecognizedFields(h.manifest,v)],S=stringifyJson(h.manifest);await s(r,replaceManifest(o,S));let C=await i(r),w=readArchive(C),T=packageFiles(w);assertSameEntries(p,T),assertPreservedArchive(o,w);let E=manifestOf(w,`the published tarball`);try{if(b.push(...reviewPackedContent(T,m),...reviewRegistryDestinations(E),...reviewMonorepoProtocols(E,T)),b.push(...reviewDeclaredFiles(E,T)),assertNoLostConsumerFields(c,E,_),manifestText(w)!==S)throw new PublishCleanError(`Rewritten tarball manifest differs from the cleaned manifest.`);let e=forbiddenPackedFiles(T,m),t=new Map([...packageContents(w)].filter(([t])=>!e.has(t)));b.push(...reviewPackedNames(E,T),...reviewShippedFiles(E,t),...reviewSelfReferences(E,t),...reviewUnreferencedFiles(E,t,y))}finally{b.length>0&&console.warn(formatFindings(b,u.strict))}let D=publishRefusal(b,u.strict);if(D)throw new PublishCleanError(D);console.warn(b.length===0?`publish-clean: no findings.`:`publish-clean: ${countOf(b.length,`finding`)} above, none of which stops a publish.`);let O=f.validateArtifact;if(O)try{if(await run(O[0],[...O.slice(1),r],e,{signal:a,output:`validator`}),!C.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] ${T.length} files:`);for(let e of T)console.log(` ${JSON.stringify(e)}`);console.log(`[dry-run] cleaned package.json:\n${S}`);return}if(u.guardOnly||u.verify)return;let k=await requireTool(`npm`,e,a),A=publishEnv(),j=wantsTrustedPublish(E,u.publishArgs,A);if(j===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.`);j=t===`true`}j&&(await assertTrustedPublishingRuntime(e,k,a),assertRepositoryForTrustedPublish(E,A));let M=packageScope(E),N=[`publish`,r,...u.publishArgs];g&&(N.push(`--registry`,g),M&&N.push(`--${M}:registry=${g}`)),await run(`npm`,N,e,{signal:a,output:`publish`})}finally{await o(x,{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());return}if(t.values.help){console.log(V);return}if(t.positionals.length>1)throw new PublishCleanError(`Unexpected positional arguments before --:\n${t.positionals.slice(1).join(`
|
|
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 Y=new AbortController;let X=!1;for(let[e,t]of[[`SIGINT`,130],[`SIGTERM`,143]])process.on(e,()=>{X=!0,process.exitCode=t,Y.abort(new PublishCleanError(`Cancelled by ${e}.`))});main(Y.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),X||(process.exitCode=1)});export{};
|