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