@anizoptera/publish-clean 0.7.2 → 0.8.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 +54 -66
- package/dist/cli.js +598 -369
- package/package.json +4 -2
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// @anizoptera/publish-clean 0.8.0 | https://github.com/Anizoptera/publish-clean#readme
|
|
2
4
|
import { readFileSync } from "node:fs";
|
|
3
5
|
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
6
|
import { tmpdir } from "node:os";
|
|
5
7
|
import path from "node:path";
|
|
6
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
7
10
|
import { parseArgs } from "node:util";
|
|
8
|
-
import { execFileSync } from "node:child_process";
|
|
9
11
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
10
12
|
|
|
11
13
|
//#region src/error.ts
|
|
@@ -34,18 +36,6 @@ function isObject(value) {
|
|
|
34
36
|
function stringifyJson(value) {
|
|
35
37
|
return `${JSON.stringify(value, null, 2)}\n`;
|
|
36
38
|
}
|
|
37
|
-
/**
|
|
38
|
-
* The form used only to compare two manifests for equality. Key order carries no meaning to a
|
|
39
|
-
* consumer, so comparing the written form would report a difference where none exists.
|
|
40
|
-
*/
|
|
41
|
-
function stableJson(value) {
|
|
42
|
-
return JSON.stringify(stableValue(value));
|
|
43
|
-
}
|
|
44
|
-
function stableValue(value) {
|
|
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)]));
|
|
48
|
-
}
|
|
49
39
|
|
|
50
40
|
//#endregion
|
|
51
41
|
//#region src/artifact.ts
|
|
@@ -88,10 +78,10 @@ const SUSPICIOUS_PATTERNS = [
|
|
|
88
78
|
];
|
|
89
79
|
function validatePackedFiles(files, skipSuspicious) {
|
|
90
80
|
const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
|
|
91
|
-
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
|
|
81
|
+
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
92
82
|
if (skipSuspicious) return;
|
|
93
83
|
const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
|
|
94
|
-
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
|
|
84
|
+
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
95
85
|
}
|
|
96
86
|
/**
|
|
97
87
|
* Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
|
|
@@ -123,13 +113,13 @@ function assertSameEntries(packed, published) {
|
|
|
123
113
|
*
|
|
124
114
|
* - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
|
|
125
115
|
* where every string is a path into this package.
|
|
126
|
-
* - `"relative-only"` for `
|
|
116
|
+
* - `"relative-only"` for `sideEffects` and the object form of
|
|
127
117
|
* `browser`, where a string may just as well be an external package name, a condition
|
|
128
118
|
* target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
|
|
129
119
|
* rest would report a missing file for something that was never a file.
|
|
130
120
|
*
|
|
131
121
|
* Booleans are skipped rather than ignored by accident: `sideEffects: false` and
|
|
132
|
-
* `
|
|
122
|
+
* `browser` replacements legitimately hold them. Export/import targets use their own walker.
|
|
133
123
|
*/
|
|
134
124
|
function collectDeclaredPaths(value, out, mode) {
|
|
135
125
|
if (typeof value === "string") {
|
|
@@ -151,39 +141,139 @@ function normalizeDeclaredPath(declared) {
|
|
|
151
141
|
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
152
142
|
return normalized;
|
|
153
143
|
}
|
|
154
|
-
/**
|
|
155
|
-
|
|
156
|
-
*
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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. */
|
|
161
236
|
function assertDeclaredFiles(pkg, published) {
|
|
162
237
|
const declared = [];
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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")}`);
|
|
187
277
|
}
|
|
188
278
|
|
|
189
279
|
//#endregion
|
|
@@ -196,12 +286,7 @@ function assertDeclaredFiles(pkg, published) {
|
|
|
196
286
|
* arguments a caller wrote after `--` straight into `npm publish`, so that vector is
|
|
197
287
|
* attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
|
|
198
288
|
*/
|
|
199
|
-
/**
|
|
200
|
-
* The probe below is bounded because a wedged shim would otherwise hang the publish with no
|
|
201
|
-
* end: `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
|
|
202
|
-
* belongs on the spawn itself. It stays generous because the only job is to separate a tool
|
|
203
|
-
* that answers from one that never will.
|
|
204
|
-
*/
|
|
289
|
+
/** Bound a hung version-manager shim without blocking the event loop. */
|
|
205
290
|
const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
206
291
|
/**
|
|
207
292
|
* Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
|
|
@@ -217,8 +302,8 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
|
217
302
|
*/
|
|
218
303
|
function spawnArgs(command, args, platform) {
|
|
219
304
|
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")}\
|
|
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.`);
|
|
222
307
|
return ["cmd.exe", [
|
|
223
308
|
"/d",
|
|
224
309
|
"/c",
|
|
@@ -226,74 +311,110 @@ function spawnArgs(command, args, platform) {
|
|
|
226
311
|
...args
|
|
227
312
|
]];
|
|
228
313
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
}
|
|
240
|
-
/**
|
|
241
|
-
* Runs a command with its streams attached to this process instead of captured.
|
|
242
|
-
*
|
|
243
|
-
* Reserved for `npm publish`. Every other command here is run for its output or its
|
|
244
|
-
* effect, but the publish is the one irreversible step, and npm's output is the only
|
|
245
|
-
* receipt the operator gets: the version that went out, the tarball size, the integrity
|
|
246
|
-
* hash, and the registry's own wording when it refuses. `run` would swallow all of it on
|
|
247
|
-
* success and hold the failure text until the process exits, which in CI means a log
|
|
248
|
-
* that says nothing about the one action that cannot be undone.
|
|
249
|
-
*/
|
|
250
|
-
function runAttached(command, args, cwd) {
|
|
251
|
-
execFileSync(...spawnArgs(command, args, process.platform), {
|
|
252
|
-
cwd,
|
|
253
|
-
stdio: [
|
|
254
|
-
"ignore",
|
|
255
|
-
"inherit",
|
|
256
|
-
"inherit"
|
|
257
|
-
]
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
/** Child output survives only on the thrown error, and is lost unless read off it here. */
|
|
261
|
-
function outputFromError(error, key) {
|
|
262
|
-
if (!isObject(error)) return "";
|
|
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 "";
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* A required tool can fail three ways, and each one asks something different of the
|
|
270
|
-
* reader, so the probe reports what it observed instead of assuming the common case.
|
|
271
|
-
* A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
|
|
272
|
-
* to run when no version is pinned; calling that absence sends the reader to verify the
|
|
273
|
-
* one thing already correct, and `which pnpm` then agrees with them and not with us. The
|
|
274
|
-
* shim's own message names the fix, so it is forwarded rather than replaced.
|
|
275
|
-
*/
|
|
276
|
-
function toolFailureReason(cause) {
|
|
277
|
-
if (isObject(cause)) {
|
|
278
|
-
if (cause.code === "ENOENT") return "is not available in PATH";
|
|
279
|
-
if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
|
|
280
|
-
}
|
|
281
|
-
const stderr = outputFromError(cause, "stderr");
|
|
282
|
-
return `failed to run${stderr ? `: ${stderr}` : ""}`;
|
|
283
|
-
}
|
|
284
|
-
function requireTool(name) {
|
|
285
|
-
try {
|
|
286
|
-
execFileSync(...spawnArgs(name, ["--version"], process.platform), {
|
|
287
|
-
stdio: [
|
|
288
|
-
"ignore",
|
|
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" ? [
|
|
289
324
|
"ignore",
|
|
325
|
+
"pipe",
|
|
290
326
|
"pipe"
|
|
291
|
-
]
|
|
292
|
-
|
|
327
|
+
] : output === "pack" ? [
|
|
328
|
+
"ignore",
|
|
329
|
+
process.stderr,
|
|
330
|
+
process.stderr
|
|
331
|
+
] : "inherit"
|
|
293
332
|
});
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
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();
|
|
297
418
|
}
|
|
298
419
|
|
|
299
420
|
//#endregion
|
|
@@ -373,6 +494,17 @@ const MONOREPO_PROTOCOLS = [
|
|
|
373
494
|
* platform gating, so `devFields` is not allowed to name them.
|
|
374
495
|
*/
|
|
375
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",
|
|
376
508
|
...DEP_FIELDS,
|
|
377
509
|
"bin",
|
|
378
510
|
"browser",
|
|
@@ -397,39 +529,20 @@ const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
|
397
529
|
"typings",
|
|
398
530
|
"version"
|
|
399
531
|
]);
|
|
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
|
-
*/
|
|
532
|
+
/** Registry metadata is recognised; consumer-resolved fields are protected separately. */
|
|
409
533
|
const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
410
534
|
"author",
|
|
411
535
|
"bugs",
|
|
412
|
-
"config",
|
|
413
536
|
"contributors",
|
|
414
|
-
"deno",
|
|
415
537
|
"description",
|
|
416
|
-
"directories",
|
|
417
538
|
"funding",
|
|
418
539
|
"gitHead",
|
|
419
540
|
"homepage",
|
|
420
|
-
"jsdelivr",
|
|
421
541
|
"keywords",
|
|
422
542
|
"maintainers",
|
|
423
|
-
"man",
|
|
424
543
|
"preferGlobal",
|
|
425
|
-
"react-native",
|
|
426
544
|
"repository",
|
|
427
|
-
"
|
|
428
|
-
"scripts",
|
|
429
|
-
"style",
|
|
430
|
-
"styleModule",
|
|
431
|
-
"svelte",
|
|
432
|
-
"unpkg"
|
|
545
|
+
"scripts"
|
|
433
546
|
]);
|
|
434
547
|
/**
|
|
435
548
|
* Shown when another package manager started this tool, so the pnpm requirement is not a
|
|
@@ -446,13 +559,29 @@ function stripManifest(pkg, extraDevFields) {
|
|
|
446
559
|
for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
447
560
|
const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
448
561
|
if (scripts) {
|
|
449
|
-
|
|
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;
|
|
562
|
+
if (Object.entries(scripts).some(([name, value]) => CONSUMER_SCRIPTS.has(name) && typeof value === "string")) stripped.scripts = scripts;
|
|
452
563
|
else delete stripped.scripts;
|
|
453
564
|
}
|
|
454
565
|
return stripped;
|
|
455
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
|
+
}
|
|
456
585
|
/**
|
|
457
586
|
* Pins the published manifest to a registry, when one was chosen.
|
|
458
587
|
*
|
|
@@ -466,8 +595,11 @@ function stripManifest(pkg, extraDevFields) {
|
|
|
466
595
|
*/
|
|
467
596
|
function withRegistry(pkg, registry) {
|
|
468
597
|
if (registry === null) return pkg;
|
|
598
|
+
assertRegistry(registry);
|
|
469
599
|
const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
|
|
470
600
|
publishConfig.registry = registry;
|
|
601
|
+
const scope = packageScope(pkg);
|
|
602
|
+
if (scope) publishConfig[`${scope}:registry`] = registry;
|
|
471
603
|
return {
|
|
472
604
|
...pkg,
|
|
473
605
|
publishConfig
|
|
@@ -486,9 +618,8 @@ function withRegistry(pkg, registry) {
|
|
|
486
618
|
* introduced while rewriting the archive is caught as well as one introduced by stripping.
|
|
487
619
|
*
|
|
488
620
|
* `devFields` entries are exempt: removing those was the request. `scripts` is exempt
|
|
489
|
-
* because
|
|
490
|
-
*
|
|
491
|
-
* none.
|
|
621
|
+
* because its entire block survives when consumer lifecycle hooks exist, and otherwise
|
|
622
|
+
* the development-only block is removed.
|
|
492
623
|
*/
|
|
493
624
|
function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
494
625
|
const expected = /* @__PURE__ */ new Set([
|
|
@@ -518,7 +649,9 @@ function unrecognizedFieldsReport(pkg, kept) {
|
|
|
518
649
|
const acknowledged = new Set(kept);
|
|
519
650
|
const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
|
|
520
651
|
if (unrecognized.length === 0) return null;
|
|
521
|
-
|
|
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}] }`;
|
|
522
655
|
}
|
|
523
656
|
/**
|
|
524
657
|
* Refuses a manifest that still carries a spec only a workspace can resolve. Published
|
|
@@ -529,14 +662,23 @@ function unrecognizedFieldsReport(pkg, kept) {
|
|
|
529
662
|
* absent by construction. They are still checked, because a guard whose correctness depends on
|
|
530
663
|
* the order it happens to be called in fails silently the day someone reorders it.
|
|
531
664
|
*/
|
|
532
|
-
function assertNoMonorepoProtocols(pkg) {
|
|
665
|
+
function assertNoMonorepoProtocols(pkg, files = []) {
|
|
533
666
|
const failures = [];
|
|
667
|
+
const shipped = new Set(files);
|
|
534
668
|
for (const field of DEP_FIELDS) {
|
|
535
669
|
const map = pkg[field];
|
|
536
670
|
if (!isObject(map)) continue;
|
|
537
671
|
for (const [name, spec] of Object.entries(map)) {
|
|
538
672
|
if (typeof spec !== "string") continue;
|
|
539
|
-
|
|
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
|
+
}
|
|
540
682
|
}
|
|
541
683
|
}
|
|
542
684
|
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
@@ -546,8 +688,11 @@ function assertPublicPackage(pkg) {
|
|
|
546
688
|
}
|
|
547
689
|
function assertFilesField(pkg, skip) {
|
|
548
690
|
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.");
|
|
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.");
|
|
550
692
|
}
|
|
693
|
+
|
|
694
|
+
//#endregion
|
|
695
|
+
//#region src/config.ts
|
|
551
696
|
/**
|
|
552
697
|
* Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
|
|
553
698
|
* makes a typo an error instead of a silent no-op — and a silent no-op here is not cosmetic:
|
|
@@ -563,9 +708,18 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
|
563
708
|
]);
|
|
564
709
|
function packageConfig(pkg) {
|
|
565
710
|
const config = pkg["publish-clean"];
|
|
566
|
-
if (
|
|
711
|
+
if (config === void 0) return {};
|
|
712
|
+
if (!isObject(config)) throw new PublishCleanError("\"publish-clean\" must be an object.");
|
|
567
713
|
const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
|
|
568
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");
|
|
569
723
|
return config;
|
|
570
724
|
}
|
|
571
725
|
/**
|
|
@@ -604,63 +758,172 @@ function keptFields(config) {
|
|
|
604
758
|
}
|
|
605
759
|
|
|
606
760
|
//#endregion
|
|
607
|
-
//#region src/
|
|
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
|
+
}
|
|
608
797
|
/**
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
* re-derives it from the very field being cleaned and silently disagrees; rewriting the one
|
|
615
|
-
* member that changed keeps the first packer's selection, and its normalisation (uid/gid 0,
|
|
616
|
-
* a fixed mtime, mode 644) that a naive `tar` invocation leaks the build machine's identity
|
|
617
|
-
* into.
|
|
618
|
-
*
|
|
619
|
-
* Every entry other than the manifest is copied as opaque bytes and never decoded, so entry
|
|
620
|
-
* shapes this code does not model — pax extended headers, ustar prefix splitting — survive
|
|
621
|
-
* untouched. Only walking is universal: an entry's length is always its header block plus its
|
|
622
|
-
* size rounded up to a block, whatever the type.
|
|
623
|
-
*
|
|
624
|
-
* Reading here rather than through the `tar` binary is what makes the whole tool depend on
|
|
625
|
-
* nothing but Node: one archive is decompressed once and answers every question about it
|
|
626
|
-
* (file list, manifest bytes, rewrite), instead of one spawn and one decompression per
|
|
627
|
-
* question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
|
|
628
|
-
* containing a newline arrives as two entries there and as itself here.
|
|
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.
|
|
629
803
|
*/
|
|
804
|
+
const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
|
|
805
|
+
|
|
806
|
+
Packs with pnpm, strips developer-only fields from the packed manifest, validates the
|
|
807
|
+
artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
|
|
808
|
+
\`npm publish\` as publication options (e.g. --access public --tag next --provenance).
|
|
809
|
+
Allowed: ${[...PUBLISH_OPTIONS.keys()].map((name) => `--${name}`).join(", ")}.
|
|
810
|
+
Additional package operands and workspace selectors are rejected.
|
|
811
|
+
|
|
812
|
+
Options:
|
|
813
|
+
--dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
|
|
814
|
+
--guard-only Validate a preview artifact; no file-list output or publish.
|
|
815
|
+
--tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
|
|
816
|
+
--registry URL Publish to URL, and record it in the artifact's publishConfig.
|
|
817
|
+
--no-git-checks Publish from a working tree with uncommitted changes.
|
|
818
|
+
--skip-file-check Allow a manifest with no "files" array.
|
|
819
|
+
--allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
|
|
820
|
+
-h, --help Show this help.
|
|
821
|
+
-v, --version Show the publish-clean version.
|
|
822
|
+
|
|
823
|
+
Manifest configuration, under a "publish-clean" key in package.json:
|
|
824
|
+
devFields string[] Extra fields to strip. Refused for fields consumers resolve.
|
|
825
|
+
keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
|
|
826
|
+
registry string Default for --registry.
|
|
827
|
+
noGitChecks boolean Default for --no-git-checks.
|
|
828
|
+
skipFileCheck boolean Default for --skip-file-check.
|
|
829
|
+
allowSuspicious boolean Default for --allow-suspicious.
|
|
830
|
+
|
|
831
|
+
Preview modes do not test registry access, credentials or provenance eligibility.
|
|
832
|
+
Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
|
|
833
|
+
npm 11.5.1+, and only a cloud CI runner can produce it.`;
|
|
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. */
|
|
630
891
|
const BLOCK = 512;
|
|
631
892
|
const NAME_LEN = 100;
|
|
632
893
|
const SIZE_OFFSET = 124;
|
|
633
894
|
const CHECKSUM_OFFSET = 148;
|
|
634
895
|
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
896
|
const MANIFEST_PATH = "package/package.json";
|
|
641
|
-
/** Extended (`x`) and global (`g`) pax headers carry key/value overrides for other entries. */
|
|
642
897
|
const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
|
|
643
|
-
/** Tar's flag for a directory entry. Directories are not files a consumer imports. */
|
|
644
898
|
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";
|
|
899
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
656
900
|
function field(block, offset, length) {
|
|
657
|
-
|
|
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));
|
|
658
904
|
}
|
|
659
905
|
function entrySize(block) {
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
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;
|
|
664
927
|
}
|
|
665
928
|
/**
|
|
666
929
|
* Verifies a header block against the checksum tar stores inside it.
|
|
@@ -687,17 +950,6 @@ function assertChecksum(header, name) {
|
|
|
687
950
|
}
|
|
688
951
|
if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
|
|
689
952
|
}
|
|
690
|
-
/**
|
|
691
|
-
* Rejects a pax header that renames another entry onto the manifest path.
|
|
692
|
-
*
|
|
693
|
-
* Without this the archive could extract a `package.json` that no check ever saw: the guards
|
|
694
|
-
* validate the entry rewritten here, while an extractor honours the pax override and writes
|
|
695
|
-
* a different one over it. The header's own name field is `PaxHeader`, so nothing about the
|
|
696
|
-
* substitution is visible from the walk alone.
|
|
697
|
-
*/
|
|
698
|
-
function assertNoManifestOverride(payload) {
|
|
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}.`);
|
|
700
|
-
}
|
|
701
953
|
/** Rebuilds a header for a changed payload size, keeping every other field of the original. */
|
|
702
954
|
function reheader(original, size) {
|
|
703
955
|
const header = Buffer.from(original);
|
|
@@ -721,26 +973,55 @@ function reheader(original, size) {
|
|
|
721
973
|
function readArchive(gzipped) {
|
|
722
974
|
const tar = gunzipSync(gzipped);
|
|
723
975
|
const entries = [];
|
|
976
|
+
const names = /* @__PURE__ */ new Set();
|
|
977
|
+
let local = null;
|
|
724
978
|
let tail = null;
|
|
725
979
|
for (let offset = 0; offset < tar.length;) {
|
|
726
980
|
const header = tar.subarray(offset, offset + BLOCK);
|
|
727
981
|
if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
|
|
728
|
-
|
|
729
|
-
if (name === "") {
|
|
982
|
+
if (header.every((byte) => byte === 0)) {
|
|
730
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.");
|
|
731
985
|
break;
|
|
732
986
|
}
|
|
733
|
-
assertChecksum(header, name);
|
|
734
|
-
const size = entrySize(header);
|
|
735
|
-
const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
|
|
736
|
-
if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
|
|
737
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.`);
|
|
738
1000
|
const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
|
|
739
|
-
if (type ===
|
|
740
|
-
if (
|
|
741
|
-
|
|
742
|
-
if (
|
|
743
|
-
if (
|
|
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;
|
|
744
1025
|
}
|
|
745
1026
|
entries.push({
|
|
746
1027
|
name,
|
|
@@ -752,11 +1033,20 @@ function readArchive(gzipped) {
|
|
|
752
1033
|
offset = end;
|
|
753
1034
|
}
|
|
754
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.");
|
|
755
1037
|
return {
|
|
756
1038
|
entries,
|
|
757
1039
|
tail
|
|
758
1040
|
};
|
|
759
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
|
+
}
|
|
760
1050
|
/**
|
|
761
1051
|
* The paths a consumer's installer writes, with the `package/` prefix stripped — the list every
|
|
762
1052
|
* content guard judges. Directories and pax headers are dropped: neither is a file anyone
|
|
@@ -766,7 +1056,7 @@ function packageFiles(archive) {
|
|
|
766
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();
|
|
767
1057
|
}
|
|
768
1058
|
function manifestEntry(archive) {
|
|
769
|
-
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
|
|
1059
|
+
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH && !PAX_TYPES.has(candidate.type));
|
|
770
1060
|
if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
|
|
771
1061
|
return entry;
|
|
772
1062
|
}
|
|
@@ -799,8 +1089,8 @@ function replaceManifest(archive, manifest) {
|
|
|
799
1089
|
* The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
|
|
800
1090
|
* message so the version a reader is told to install is the version the comparison made.
|
|
801
1091
|
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
1092
|
+
* These floors apply to trusted publication; ordinary token-based publication can use the
|
|
1093
|
+
* lower Node floor declared by engines.node.
|
|
804
1094
|
*/
|
|
805
1095
|
const MIN_TRUSTED_NPM_VERSION = [
|
|
806
1096
|
11,
|
|
@@ -824,9 +1114,12 @@ function isAtLeast(actual, minimum) {
|
|
|
824
1114
|
return true;
|
|
825
1115
|
}
|
|
826
1116
|
function wantsTrustedPublish(pkg, publishArgs, env) {
|
|
827
|
-
if (
|
|
828
|
-
|
|
829
|
-
|
|
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);
|
|
830
1123
|
}
|
|
831
1124
|
function repositoryUrl(pkg) {
|
|
832
1125
|
if (typeof pkg.repository === "string") return pkg.repository;
|
|
@@ -848,8 +1141,7 @@ function githubRepositorySlug(url) {
|
|
|
848
1141
|
return null;
|
|
849
1142
|
}
|
|
850
1143
|
}
|
|
851
|
-
function assertRepositoryForTrustedPublish(pkg,
|
|
852
|
-
if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
|
|
1144
|
+
function assertRepositoryForTrustedPublish(pkg, env) {
|
|
853
1145
|
if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
|
|
854
1146
|
const repoUrl = repositoryUrl(pkg);
|
|
855
1147
|
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
@@ -859,40 +1151,6 @@ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
|
|
|
859
1151
|
//#endregion
|
|
860
1152
|
//#region src/cli.ts
|
|
861
1153
|
/**
|
|
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.`;
|
|
895
|
-
/**
|
|
896
1154
|
* Read from the installed manifest rather than baked in at build time, so the number cannot
|
|
897
1155
|
* drift from the package a user actually has — which is the only reason anyone asks a tool
|
|
898
1156
|
* for its version.
|
|
@@ -921,8 +1179,8 @@ function readJson(file) {
|
|
|
921
1179
|
* is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
|
|
922
1180
|
* so reading it would answer a question nobody asked while looking exactly like a check.
|
|
923
1181
|
*/
|
|
924
|
-
function toolVersion(command) {
|
|
925
|
-
const raw =
|
|
1182
|
+
function toolVersion(command, version) {
|
|
1183
|
+
const raw = version.trim().replace(/^v/, "");
|
|
926
1184
|
const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
|
|
927
1185
|
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
|
|
928
1186
|
return [
|
|
@@ -943,11 +1201,10 @@ function publishEnv() {
|
|
|
943
1201
|
GITHUB_REPOSITORY: process.env.GITHUB_REPOSITORY
|
|
944
1202
|
};
|
|
945
1203
|
}
|
|
946
|
-
function assertTrustedPublishingRuntime(
|
|
947
|
-
|
|
948
|
-
const npm = toolVersion("npm");
|
|
1204
|
+
async function assertTrustedPublishingRuntime(cwd, npmVersion, signal) {
|
|
1205
|
+
const npm = toolVersion("npm", npmVersion);
|
|
949
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(".")}.`);
|
|
950
|
-
const node = toolVersion("node");
|
|
1207
|
+
const node = toolVersion("node", await requireTool("node", cwd, signal));
|
|
951
1208
|
if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
|
|
952
1209
|
throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
|
|
953
1210
|
}
|
|
@@ -956,21 +1213,15 @@ function warnIfNonPnpmLifecycle() {
|
|
|
956
1213
|
if (!userAgent || userAgent.startsWith("pnpm/")) return;
|
|
957
1214
|
console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
|
|
958
1215
|
}
|
|
959
|
-
function assertCleanGit(packageDir, skip) {
|
|
1216
|
+
async function assertCleanGit(packageDir, skip, signal) {
|
|
960
1217
|
if (skip) return;
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
|
|
969
|
-
} catch (error) {
|
|
970
|
-
if (error instanceof PublishCleanError) throw error;
|
|
971
|
-
const stderr = outputFromError(error, "stderr");
|
|
972
|
-
throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
|
|
973
|
-
}
|
|
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}`);
|
|
974
1225
|
}
|
|
975
1226
|
/**
|
|
976
1227
|
* Reads an archive from disk, so every judgement is made about bytes that exist as a file
|
|
@@ -1009,12 +1260,10 @@ async function soleTarball(packRoot) {
|
|
|
1009
1260
|
if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
|
|
1010
1261
|
return path.join(packRoot, tarball);
|
|
1011
1262
|
}
|
|
1012
|
-
async function packAndClean(packageDir, opts) {
|
|
1013
|
-
requireTool("pnpm");
|
|
1014
|
-
requireTool("npm");
|
|
1263
|
+
async function packAndClean(packageDir, signal, opts) {
|
|
1264
|
+
const [, npmVersion] = await Promise.all([requireTool("pnpm", packageDir, signal), requireTool("npm", packageDir, signal)]);
|
|
1015
1265
|
warnIfNonPnpmLifecycle();
|
|
1016
1266
|
const sourcePkg = readJson(path.join(packageDir, "package.json"));
|
|
1017
|
-
if (!opts.guardOnly && !opts.dryRun) assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
|
|
1018
1267
|
const config = packageConfig(sourcePkg);
|
|
1019
1268
|
const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
|
|
1020
1269
|
const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
|
|
@@ -1023,33 +1272,38 @@ async function packAndClean(packageDir, opts) {
|
|
|
1023
1272
|
const extraDevFields = customDevFields(config);
|
|
1024
1273
|
const keepFields = keptFields(config);
|
|
1025
1274
|
assertPublicPackage(sourcePkg);
|
|
1026
|
-
assertCleanGit(packageDir, noGitChecks);
|
|
1275
|
+
await assertCleanGit(packageDir, noGitChecks, signal);
|
|
1027
1276
|
assertFilesField(sourcePkg, skipFileCheck);
|
|
1028
1277
|
const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
|
|
1029
1278
|
try {
|
|
1030
|
-
run("pnpm", [
|
|
1279
|
+
await run("pnpm", [
|
|
1031
1280
|
"pack",
|
|
1032
1281
|
"--pack-destination",
|
|
1033
1282
|
root
|
|
1034
|
-
], packageDir
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
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);
|
|
1038
1293
|
const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
|
|
1039
1294
|
if (unrecognized) console.warn(unrecognized);
|
|
1040
|
-
|
|
1041
|
-
await mkdir(publishRoot);
|
|
1042
|
-
const finalTarball = path.join(publishRoot, path.basename(tarball));
|
|
1043
|
-
await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
|
|
1295
|
+
await writeFile(finalTarball, replaceManifest(packed, cleanedText));
|
|
1044
1296
|
const published = await readTarball(finalTarball);
|
|
1045
1297
|
const finalFiles = packageFiles(published);
|
|
1046
1298
|
assertSameEntries(packageFiles(packed), finalFiles);
|
|
1299
|
+
assertPreservedArchive(packed, published);
|
|
1047
1300
|
validatePackedFiles(finalFiles, allowSuspicious);
|
|
1048
|
-
assertDeclaredFiles(cleanedPkg, finalFiles);
|
|
1049
1301
|
const shippedPkg = manifestOf(published, "the published tarball");
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
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.");
|
|
1053
1307
|
if (opts.tarballOut !== null) {
|
|
1054
1308
|
await mkdir(opts.tarballOut, { recursive: true });
|
|
1055
1309
|
const kept = path.join(opts.tarballOut, path.basename(finalTarball));
|
|
@@ -1058,24 +1312,43 @@ async function packAndClean(packageDir, opts) {
|
|
|
1058
1312
|
}
|
|
1059
1313
|
if (opts.dryRun) {
|
|
1060
1314
|
console.log(`[dry-run] ${finalFiles.length} files:`);
|
|
1061
|
-
for (const file of finalFiles) console.log(` ${file}`);
|
|
1062
|
-
console.log(`[dry-run] cleaned package.json:\n${
|
|
1315
|
+
for (const file of finalFiles) console.log(` ${JSON.stringify(file)}`);
|
|
1316
|
+
console.log(`[dry-run] cleaned package.json:\n${cleanedText}`);
|
|
1063
1317
|
return;
|
|
1064
1318
|
}
|
|
1065
1319
|
if (opts.guardOnly) return;
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
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 = [
|
|
1074
1340
|
"publish",
|
|
1075
1341
|
finalTarball,
|
|
1076
1342
|
...opts.publishArgs
|
|
1077
1343
|
];
|
|
1078
|
-
|
|
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
|
+
});
|
|
1079
1352
|
} finally {
|
|
1080
1353
|
await rm(root, {
|
|
1081
1354
|
recursive: true,
|
|
@@ -1083,56 +1356,9 @@ async function packAndClean(packageDir, opts) {
|
|
|
1083
1356
|
});
|
|
1084
1357
|
}
|
|
1085
1358
|
}
|
|
1086
|
-
async function main() {
|
|
1087
|
-
const
|
|
1088
|
-
const
|
|
1089
|
-
const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
|
|
1090
|
-
const publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1);
|
|
1091
|
-
const parsed = parseArgs({
|
|
1092
|
-
args: cliArgs,
|
|
1093
|
-
allowPositionals: true,
|
|
1094
|
-
options: {
|
|
1095
|
-
"allow-suspicious": {
|
|
1096
|
-
type: "boolean",
|
|
1097
|
-
default: false
|
|
1098
|
-
},
|
|
1099
|
-
"dry-run": {
|
|
1100
|
-
type: "boolean",
|
|
1101
|
-
default: false
|
|
1102
|
-
},
|
|
1103
|
-
"guard-only": {
|
|
1104
|
-
type: "boolean",
|
|
1105
|
-
default: false
|
|
1106
|
-
},
|
|
1107
|
-
help: {
|
|
1108
|
-
type: "boolean",
|
|
1109
|
-
short: "h",
|
|
1110
|
-
default: false
|
|
1111
|
-
},
|
|
1112
|
-
"no-git-checks": {
|
|
1113
|
-
type: "boolean",
|
|
1114
|
-
default: false
|
|
1115
|
-
},
|
|
1116
|
-
registry: {
|
|
1117
|
-
type: "string",
|
|
1118
|
-
default: void 0
|
|
1119
|
-
},
|
|
1120
|
-
"skip-file-check": {
|
|
1121
|
-
type: "boolean",
|
|
1122
|
-
default: false
|
|
1123
|
-
},
|
|
1124
|
-
"tarball-out": {
|
|
1125
|
-
type: "string",
|
|
1126
|
-
default: void 0
|
|
1127
|
-
},
|
|
1128
|
-
version: {
|
|
1129
|
-
type: "boolean",
|
|
1130
|
-
short: "v",
|
|
1131
|
-
default: false
|
|
1132
|
-
}
|
|
1133
|
-
},
|
|
1134
|
-
strict: true
|
|
1135
|
-
});
|
|
1359
|
+
async function main(signal) {
|
|
1360
|
+
const parsed = parseOptions(process.argv.slice(2));
|
|
1361
|
+
const { publishArgs } = parsed;
|
|
1136
1362
|
if (parsed.values.version) {
|
|
1137
1363
|
console.log(ownVersion());
|
|
1138
1364
|
return;
|
|
@@ -1142,7 +1368,7 @@ async function main() {
|
|
|
1142
1368
|
return;
|
|
1143
1369
|
}
|
|
1144
1370
|
if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
|
|
1145
|
-
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
|
|
1371
|
+
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), signal, {
|
|
1146
1372
|
allowSuspicious: parsed.values["allow-suspicious"] === true,
|
|
1147
1373
|
dryRun: parsed.values["dry-run"] === true,
|
|
1148
1374
|
guardOnly: parsed.values["guard-only"] === true,
|
|
@@ -1153,14 +1379,17 @@ async function main() {
|
|
|
1153
1379
|
tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
|
|
1154
1380
|
});
|
|
1155
1381
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
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;
|
|
1164
1393
|
});
|
|
1165
1394
|
|
|
1166
1395
|
//#endregion
|