@anizoptera/publish-clean 0.7.1 → 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/dist/cli.js +367 -153
- package/package.json +1 -1
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,8 +42,11 @@ 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
|
/**
|
|
@@ -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
|
/**
|
|
@@ -101,7 +108,9 @@ function validatePackedFiles(files, skipSuspicious) {
|
|
|
101
108
|
* `tar tzf` of the same tarball — an instrument that cannot share a mistake with this one.
|
|
102
109
|
*/
|
|
103
110
|
function assertSameEntries(packed, published) {
|
|
104
|
-
|
|
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}`)];
|
|
105
114
|
if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
|
|
106
115
|
}
|
|
107
116
|
/**
|
|
@@ -123,23 +132,24 @@ function assertSameEntries(packed, published) {
|
|
|
123
132
|
* `exports` condition values legitimately hold them.
|
|
124
133
|
*/
|
|
125
134
|
function collectDeclaredPaths(value, out, mode) {
|
|
126
|
-
if (typeof value
|
|
127
|
-
(mode === "every-string" || value.startsWith("./") || value.startsWith("../"))
|
|
135
|
+
if (typeof value === "string") {
|
|
136
|
+
if (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) out.push(value);
|
|
128
137
|
return;
|
|
129
138
|
}
|
|
130
|
-
if (typeof value
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
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;
|
|
136
143
|
}
|
|
144
|
+
if (!isObject(value)) return;
|
|
145
|
+
for (const item of Object.values(value)) collectDeclaredPaths(item, out, mode);
|
|
137
146
|
}
|
|
138
147
|
function normalizeDeclaredPath(declared) {
|
|
139
|
-
|
|
148
|
+
const withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
|
|
140
149
|
if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
|
|
141
|
-
|
|
142
|
-
|
|
150
|
+
const normalized = path.posix.normalize(withoutDot);
|
|
151
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
152
|
+
return normalized;
|
|
143
153
|
}
|
|
144
154
|
/**
|
|
145
155
|
* Refuses a manifest whose declared entry points are not in the tarball.
|
|
@@ -149,29 +159,33 @@ function normalizeDeclaredPath(declared) {
|
|
|
149
159
|
* answer a question npm answers at install time.
|
|
150
160
|
*/
|
|
151
161
|
function assertDeclaredFiles(pkg, published) {
|
|
152
|
-
|
|
153
|
-
for (
|
|
162
|
+
const declared = [];
|
|
163
|
+
for (const field of [
|
|
154
164
|
"main",
|
|
155
165
|
"module",
|
|
156
166
|
"types",
|
|
157
167
|
"typings",
|
|
158
168
|
"bin"
|
|
159
169
|
]) collectDeclaredPaths(pkg[field], declared, "every-string");
|
|
160
|
-
typeof pkg.browser
|
|
161
|
-
|
|
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 [
|
|
162
173
|
"exports",
|
|
163
174
|
"imports",
|
|
164
175
|
"sideEffects"
|
|
165
176
|
]) collectDeclaredPaths(pkg[field], declared, "relative-only");
|
|
166
177
|
collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
|
|
167
|
-
|
|
178
|
+
const resolved = declared.map((declaredPath) => ({
|
|
168
179
|
path: declaredPath,
|
|
169
180
|
normalized: normalizeDeclaredPath(declaredPath)
|
|
170
|
-
}))
|
|
181
|
+
}));
|
|
182
|
+
const invalid = resolved.filter((item) => item.normalized === null);
|
|
171
183
|
if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.path).join("\n")}`);
|
|
172
|
-
|
|
184
|
+
const shipped = new Set(published);
|
|
185
|
+
const missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
|
|
173
186
|
if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
|
|
174
187
|
}
|
|
188
|
+
|
|
175
189
|
//#endregion
|
|
176
190
|
//#region src/command.ts
|
|
177
191
|
/**
|
|
@@ -203,7 +217,7 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
|
203
217
|
*/
|
|
204
218
|
function spawnArgs(command, args, platform) {
|
|
205
219
|
if (platform !== "win32") return [command, [...args]];
|
|
206
|
-
|
|
220
|
+
const unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
|
|
207
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.`);
|
|
208
222
|
return ["cmd.exe", [
|
|
209
223
|
"/d",
|
|
@@ -246,8 +260,10 @@ function runAttached(command, args, cwd) {
|
|
|
246
260
|
/** Child output survives only on the thrown error, and is lost unless read off it here. */
|
|
247
261
|
function outputFromError(error, key) {
|
|
248
262
|
if (!isObject(error)) return "";
|
|
249
|
-
|
|
250
|
-
|
|
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 "";
|
|
251
267
|
}
|
|
252
268
|
/**
|
|
253
269
|
* A required tool can fail three ways, and each one asks something different of the
|
|
@@ -262,7 +278,7 @@ function toolFailureReason(cause) {
|
|
|
262
278
|
if (cause.code === "ENOENT") return "is not available in PATH";
|
|
263
279
|
if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
|
|
264
280
|
}
|
|
265
|
-
|
|
281
|
+
const stderr = outputFromError(cause, "stderr");
|
|
266
282
|
return `failed to run${stderr ? `: ${stderr}` : ""}`;
|
|
267
283
|
}
|
|
268
284
|
function requireTool(name) {
|
|
@@ -279,6 +295,7 @@ function requireTool(name) {
|
|
|
279
295
|
throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
|
|
280
296
|
}
|
|
281
297
|
}
|
|
298
|
+
|
|
282
299
|
//#endregion
|
|
283
300
|
//#region src/manifest.ts
|
|
284
301
|
/**
|
|
@@ -288,25 +305,74 @@ function requireTool(name) {
|
|
|
288
305
|
* Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
|
|
289
306
|
* argv here — so every rule is one input to one output. `cli.ts` owns the effects.
|
|
290
307
|
*/
|
|
291
|
-
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([
|
|
292
351
|
"preinstall",
|
|
293
352
|
"install",
|
|
294
353
|
"postinstall",
|
|
295
354
|
"prepare",
|
|
296
355
|
"uninstall"
|
|
297
|
-
])
|
|
356
|
+
]);
|
|
357
|
+
const DEP_FIELDS = [
|
|
298
358
|
"dependencies",
|
|
299
359
|
"devDependencies",
|
|
300
360
|
"optionalDependencies",
|
|
301
361
|
"peerDependencies",
|
|
302
362
|
"overrides",
|
|
303
363
|
"resolutions"
|
|
304
|
-
]
|
|
364
|
+
];
|
|
365
|
+
const MONOREPO_PROTOCOLS = [
|
|
305
366
|
"catalog:",
|
|
306
367
|
"workspace:",
|
|
307
368
|
"link:",
|
|
308
369
|
"portal:"
|
|
309
|
-
]
|
|
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([
|
|
310
376
|
...DEP_FIELDS,
|
|
311
377
|
"bin",
|
|
312
378
|
"browser",
|
|
@@ -330,7 +396,17 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
|
|
|
330
396
|
"typesVersions",
|
|
331
397
|
"typings",
|
|
332
398
|
"version"
|
|
333
|
-
])
|
|
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([
|
|
334
410
|
"author",
|
|
335
411
|
"bugs",
|
|
336
412
|
"config",
|
|
@@ -354,15 +430,26 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
|
|
|
354
430
|
"styleModule",
|
|
355
431
|
"svelte",
|
|
356
432
|
"unpkg"
|
|
357
|
-
])
|
|
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.";
|
|
358
444
|
function stripManifest(pkg, extraDevFields) {
|
|
359
|
-
|
|
360
|
-
for (
|
|
361
|
-
|
|
445
|
+
const stripped = { ...pkg };
|
|
446
|
+
for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
447
|
+
const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
362
448
|
if (scripts) {
|
|
363
|
-
|
|
364
|
-
for (
|
|
365
|
-
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;
|
|
366
453
|
}
|
|
367
454
|
return stripped;
|
|
368
455
|
}
|
|
@@ -379,8 +466,9 @@ function stripManifest(pkg, extraDevFields) {
|
|
|
379
466
|
*/
|
|
380
467
|
function withRegistry(pkg, registry) {
|
|
381
468
|
if (registry === null) return pkg;
|
|
382
|
-
|
|
383
|
-
|
|
469
|
+
const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
|
|
470
|
+
publishConfig.registry = registry;
|
|
471
|
+
return {
|
|
384
472
|
...pkg,
|
|
385
473
|
publishConfig
|
|
386
474
|
};
|
|
@@ -403,11 +491,12 @@ function withRegistry(pkg, registry) {
|
|
|
403
491
|
* none.
|
|
404
492
|
*/
|
|
405
493
|
function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
406
|
-
|
|
494
|
+
const expected = /* @__PURE__ */ new Set([
|
|
407
495
|
...DEV_FIELDS,
|
|
408
496
|
...removedOnRequest,
|
|
409
497
|
"scripts"
|
|
410
|
-
])
|
|
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));
|
|
411
500
|
if (lost.length > 0) throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${lost.join("\n")}`);
|
|
412
501
|
}
|
|
413
502
|
/**
|
|
@@ -426,8 +515,10 @@ function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
|
426
515
|
* object, which two cases running side by side can clobber.
|
|
427
516
|
*/
|
|
428
517
|
function unrecognizedFieldsReport(pkg, kept) {
|
|
429
|
-
|
|
430
|
-
|
|
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(", ")}] }`;
|
|
431
522
|
}
|
|
432
523
|
/**
|
|
433
524
|
* Refuses a manifest that still carries a spec only a workspace can resolve. Published
|
|
@@ -439,18 +530,23 @@ function unrecognizedFieldsReport(pkg, kept) {
|
|
|
439
530
|
* the order it happens to be called in fails silently the day someone reorders it.
|
|
440
531
|
*/
|
|
441
532
|
function assertNoMonorepoProtocols(pkg) {
|
|
442
|
-
|
|
443
|
-
for (
|
|
444
|
-
|
|
445
|
-
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
|
+
}
|
|
446
541
|
}
|
|
447
542
|
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
448
543
|
}
|
|
449
544
|
function assertPublicPackage(pkg) {
|
|
450
|
-
if (pkg.private ===
|
|
545
|
+
if (pkg.private === true) throw new PublishCleanError("Refusing to publish a package with private: true.");
|
|
451
546
|
}
|
|
452
547
|
function assertFilesField(pkg, skip) {
|
|
453
|
-
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.");
|
|
454
550
|
}
|
|
455
551
|
/**
|
|
456
552
|
* Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
|
|
@@ -466,9 +562,9 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
|
466
562
|
"skipFileCheck"
|
|
467
563
|
]);
|
|
468
564
|
function packageConfig(pkg) {
|
|
469
|
-
|
|
565
|
+
const config = pkg["publish-clean"];
|
|
470
566
|
if (!isObject(config)) return {};
|
|
471
|
-
|
|
567
|
+
const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
|
|
472
568
|
if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
|
|
473
569
|
return config;
|
|
474
570
|
}
|
|
@@ -478,15 +574,17 @@ function packageConfig(pkg) {
|
|
|
478
574
|
* silently means the author's intent is lost with no signal anywhere.
|
|
479
575
|
*/
|
|
480
576
|
function stringList(config, key) {
|
|
481
|
-
|
|
577
|
+
const value = config[key];
|
|
482
578
|
if (value === void 0) return [];
|
|
483
|
-
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.`);
|
|
484
580
|
return value;
|
|
485
581
|
}
|
|
486
582
|
function customDevFields(config) {
|
|
487
|
-
|
|
583
|
+
const fields = stringList(config, "devFields");
|
|
584
|
+
const kept = new Set(stringList(config, "keepFields"));
|
|
585
|
+
const contradictory = fields.filter((field) => kept.has(field));
|
|
488
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")}`);
|
|
489
|
-
|
|
587
|
+
const unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
|
|
490
588
|
if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
|
|
491
589
|
return fields;
|
|
492
590
|
}
|
|
@@ -504,6 +602,7 @@ function customDevFields(config) {
|
|
|
504
602
|
function keptFields(config) {
|
|
505
603
|
return stringList(config, "keepFields");
|
|
506
604
|
}
|
|
605
|
+
|
|
507
606
|
//#endregion
|
|
508
607
|
//#region src/tarball.ts
|
|
509
608
|
/**
|
|
@@ -528,13 +627,38 @@ function keptFields(config) {
|
|
|
528
627
|
* question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
|
|
529
628
|
* containing a newline arrives as two entries there and as itself here.
|
|
530
629
|
*/
|
|
531
|
-
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";
|
|
532
656
|
function field(block, offset, length) {
|
|
533
657
|
return block.toString("utf8", offset, offset + length).replace(/\0.*/s, "");
|
|
534
658
|
}
|
|
535
659
|
function entrySize(block) {
|
|
536
|
-
if ((block[
|
|
537
|
-
|
|
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);
|
|
538
662
|
if (!Number.isFinite(size) || size < 0) throw new PublishCleanError("Tarball entry has an unreadable size field.");
|
|
539
663
|
return size;
|
|
540
664
|
}
|
|
@@ -553,10 +677,13 @@ function entrySize(block) {
|
|
|
553
677
|
* the signed form would reject valid archives holding non-ASCII filenames.
|
|
554
678
|
*/
|
|
555
679
|
function assertChecksum(header, name) {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
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;
|
|
560
687
|
}
|
|
561
688
|
if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
|
|
562
689
|
}
|
|
@@ -569,15 +696,17 @@ function assertChecksum(header, name) {
|
|
|
569
696
|
* substitution is visible from the walk alone.
|
|
570
697
|
*/
|
|
571
698
|
function assertNoManifestOverride(payload) {
|
|
572
|
-
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}.`);
|
|
573
700
|
}
|
|
574
701
|
/** Rebuilds a header for a changed payload size, keeping every other field of the original. */
|
|
575
702
|
function reheader(original, size) {
|
|
576
|
-
|
|
577
|
-
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");
|
|
578
706
|
let sum = 0;
|
|
579
|
-
for (
|
|
580
|
-
|
|
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;
|
|
581
710
|
}
|
|
582
711
|
/**
|
|
583
712
|
* Decodes a gzipped tarball into its entries, refusing every shape whose meaning this tool
|
|
@@ -590,21 +719,26 @@ function reheader(original, size) {
|
|
|
590
719
|
* partial write becomes a published package.
|
|
591
720
|
*/
|
|
592
721
|
function readArchive(gzipped) {
|
|
593
|
-
|
|
722
|
+
const tar = gunzipSync(gzipped);
|
|
723
|
+
const entries = [];
|
|
724
|
+
let tail = null;
|
|
594
725
|
for (let offset = 0; offset < tar.length;) {
|
|
595
|
-
|
|
596
|
-
if (header.length <
|
|
597
|
-
|
|
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);
|
|
598
729
|
if (name === "") {
|
|
599
730
|
tail = tar.subarray(offset);
|
|
600
731
|
break;
|
|
601
732
|
}
|
|
602
733
|
assertChecksum(header, name);
|
|
603
|
-
|
|
734
|
+
const size = entrySize(header);
|
|
735
|
+
const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
|
|
604
736
|
if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
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) {
|
|
608
742
|
if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
|
|
609
743
|
if (entries.some((entry) => entry.name === MANIFEST_PATH)) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
|
|
610
744
|
}
|
|
@@ -614,7 +748,8 @@ function readArchive(gzipped) {
|
|
|
614
748
|
header,
|
|
615
749
|
body,
|
|
616
750
|
raw: tar.subarray(offset, end)
|
|
617
|
-
})
|
|
751
|
+
});
|
|
752
|
+
offset = end;
|
|
618
753
|
}
|
|
619
754
|
if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
|
|
620
755
|
return {
|
|
@@ -628,10 +763,10 @@ function readArchive(gzipped) {
|
|
|
628
763
|
* imports, and a pax header's own name (`PaxHeader`) names no file at all.
|
|
629
764
|
*/
|
|
630
765
|
function packageFiles(archive) {
|
|
631
|
-
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();
|
|
632
767
|
}
|
|
633
768
|
function manifestEntry(archive) {
|
|
634
|
-
|
|
769
|
+
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
|
|
635
770
|
if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
|
|
636
771
|
return entry;
|
|
637
772
|
}
|
|
@@ -641,13 +776,17 @@ function manifestText(archive) {
|
|
|
641
776
|
}
|
|
642
777
|
/** Returns the gzipped tarball with `package/package.json` replaced by `manifest`. */
|
|
643
778
|
function replaceManifest(archive, manifest) {
|
|
644
|
-
|
|
779
|
+
const target = manifestEntry(archive);
|
|
780
|
+
const body = Buffer.from(manifest, "utf8");
|
|
781
|
+
const parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
|
|
645
782
|
reheader(entry.header, body.length),
|
|
646
783
|
body,
|
|
647
|
-
Buffer.alloc(
|
|
784
|
+
Buffer.alloc(BLOCK * Math.ceil(body.length / BLOCK) - body.length)
|
|
648
785
|
]) : entry.raw);
|
|
649
|
-
|
|
786
|
+
parts.push(archive.tail);
|
|
787
|
+
return gzipSync(Buffer.concat(parts), { level: 9 });
|
|
650
788
|
}
|
|
789
|
+
|
|
651
790
|
//#endregion
|
|
652
791
|
//#region src/trusted-publish.ts
|
|
653
792
|
/**
|
|
@@ -667,57 +806,100 @@ const MIN_TRUSTED_NPM_VERSION = [
|
|
|
667
806
|
11,
|
|
668
807
|
5,
|
|
669
808
|
1
|
|
670
|
-
]
|
|
809
|
+
];
|
|
810
|
+
const MIN_TRUSTED_NODE_VERSION = [
|
|
671
811
|
22,
|
|
672
812
|
14,
|
|
673
813
|
0
|
|
674
814
|
];
|
|
675
815
|
function isAtLeast(actual, minimum) {
|
|
676
|
-
for (
|
|
816
|
+
for (const index of [
|
|
677
817
|
0,
|
|
678
818
|
1,
|
|
679
819
|
2
|
|
680
820
|
]) {
|
|
681
|
-
if (actual[index] > minimum[index]) return
|
|
682
|
-
if (actual[index] < minimum[index]) return
|
|
821
|
+
if (actual[index] > minimum[index]) return true;
|
|
822
|
+
if (actual[index] < minimum[index]) return false;
|
|
683
823
|
}
|
|
684
|
-
return
|
|
824
|
+
return true;
|
|
685
825
|
}
|
|
686
826
|
function wantsTrustedPublish(pkg, publishArgs, env) {
|
|
687
|
-
|
|
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";
|
|
688
830
|
}
|
|
689
831
|
function repositoryUrl(pkg) {
|
|
690
|
-
|
|
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;
|
|
691
835
|
}
|
|
692
836
|
function githubRepositorySlug(url) {
|
|
693
|
-
|
|
837
|
+
const withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
|
|
694
838
|
if (withoutGitPrefix.startsWith("git@github.com:")) {
|
|
695
|
-
|
|
839
|
+
const slug = withoutGitPrefix.slice(15);
|
|
696
840
|
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
697
841
|
}
|
|
698
842
|
try {
|
|
699
|
-
|
|
843
|
+
const parsed = new URL(withoutGitPrefix);
|
|
700
844
|
if (parsed.hostname !== "github.com") return null;
|
|
701
|
-
|
|
845
|
+
const slug = parsed.pathname.replace(/^\/+/, "");
|
|
702
846
|
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
703
847
|
} catch {
|
|
704
848
|
return null;
|
|
705
849
|
}
|
|
706
850
|
}
|
|
707
851
|
function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
|
|
708
|
-
if (!wantsTrustedPublish(pkg, publishArgs, env)
|
|
709
|
-
|
|
852
|
+
if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
|
|
853
|
+
if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
|
|
854
|
+
const repoUrl = repositoryUrl(pkg);
|
|
710
855
|
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
711
856
|
if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
|
|
712
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.`;
|
|
713
895
|
/**
|
|
714
896
|
* Read from the installed manifest rather than baked in at build time, so the number cannot
|
|
715
897
|
* drift from the package a user actually has — which is the only reason anyone asks a tool
|
|
716
898
|
* for its version.
|
|
717
899
|
*/
|
|
718
900
|
function ownVersion() {
|
|
719
|
-
|
|
720
|
-
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";
|
|
721
903
|
}
|
|
722
904
|
function readJson(file) {
|
|
723
905
|
let parsed;
|
|
@@ -740,7 +922,8 @@ function readJson(file) {
|
|
|
740
922
|
* so reading it would answer a question nobody asked while looking exactly like a check.
|
|
741
923
|
*/
|
|
742
924
|
function toolVersion(command) {
|
|
743
|
-
|
|
925
|
+
const raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, "");
|
|
926
|
+
const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
|
|
744
927
|
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
|
|
745
928
|
return [
|
|
746
929
|
parts[0] ?? 0,
|
|
@@ -762,18 +945,21 @@ function publishEnv() {
|
|
|
762
945
|
}
|
|
763
946
|
function assertTrustedPublishingRuntime(pkg, publishArgs) {
|
|
764
947
|
if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
|
|
765
|
-
|
|
948
|
+
const npm = toolVersion("npm");
|
|
766
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(".")}.`);
|
|
767
|
-
|
|
768
|
-
if (
|
|
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(".")}.`);
|
|
769
953
|
}
|
|
770
954
|
function warnIfNonPnpmLifecycle() {
|
|
771
|
-
|
|
772
|
-
!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}`);
|
|
773
958
|
}
|
|
774
959
|
function assertCleanGit(packageDir, skip) {
|
|
775
|
-
if (
|
|
776
|
-
|
|
960
|
+
if (skip) return;
|
|
961
|
+
try {
|
|
962
|
+
const output = run("git", [
|
|
777
963
|
"status",
|
|
778
964
|
"--porcelain",
|
|
779
965
|
"--",
|
|
@@ -782,7 +968,7 @@ function assertCleanGit(packageDir, skip) {
|
|
|
782
968
|
if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
|
|
783
969
|
} catch (error) {
|
|
784
970
|
if (error instanceof PublishCleanError) throw error;
|
|
785
|
-
|
|
971
|
+
const stderr = outputFromError(error, "stderr");
|
|
786
972
|
throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
|
|
787
973
|
}
|
|
788
974
|
}
|
|
@@ -818,46 +1004,67 @@ function manifestOf(archive, label) {
|
|
|
818
1004
|
* destination was not exclusive and the wrong artifact could be published.
|
|
819
1005
|
*/
|
|
820
1006
|
async function soleTarball(packRoot) {
|
|
821
|
-
|
|
1007
|
+
const tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz"));
|
|
1008
|
+
const [tarball] = tarballs;
|
|
822
1009
|
if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
|
|
823
1010
|
return path.join(packRoot, tarball);
|
|
824
1011
|
}
|
|
825
1012
|
async function packAndClean(packageDir, opts) {
|
|
826
|
-
requireTool("pnpm")
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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-"));
|
|
832
1029
|
try {
|
|
833
1030
|
run("pnpm", [
|
|
834
1031
|
"pack",
|
|
835
1032
|
"--pack-destination",
|
|
836
1033
|
root
|
|
837
1034
|
], packageDir);
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
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");
|
|
841
1041
|
await mkdir(publishRoot);
|
|
842
|
-
|
|
1042
|
+
const finalTarball = path.join(publishRoot, path.basename(tarball));
|
|
843
1043
|
await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
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.");
|
|
848
1053
|
if (opts.tarballOut !== null) {
|
|
849
|
-
await mkdir(opts.tarballOut, { recursive:
|
|
850
|
-
|
|
851
|
-
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}`);
|
|
852
1058
|
}
|
|
853
1059
|
if (opts.dryRun) {
|
|
854
1060
|
console.log(`[dry-run] ${finalFiles.length} files:`);
|
|
855
|
-
for (
|
|
1061
|
+
for (const file of finalFiles) console.log(` ${file}`);
|
|
856
1062
|
console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
|
|
857
1063
|
return;
|
|
858
1064
|
}
|
|
859
1065
|
if (opts.guardOnly) return;
|
|
860
|
-
assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv())
|
|
1066
|
+
assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv());
|
|
1067
|
+
const publishArgs = registry ? [
|
|
861
1068
|
"publish",
|
|
862
1069
|
finalTarball,
|
|
863
1070
|
"--registry",
|
|
@@ -867,39 +1074,44 @@ async function packAndClean(packageDir, opts) {
|
|
|
867
1074
|
"publish",
|
|
868
1075
|
finalTarball,
|
|
869
1076
|
...opts.publishArgs
|
|
870
|
-
]
|
|
1077
|
+
];
|
|
1078
|
+
runAttached("npm", publishArgs, packageDir);
|
|
871
1079
|
} finally {
|
|
872
1080
|
await rm(root, {
|
|
873
|
-
recursive:
|
|
874
|
-
force:
|
|
1081
|
+
recursive: true,
|
|
1082
|
+
force: true
|
|
875
1083
|
});
|
|
876
1084
|
}
|
|
877
1085
|
}
|
|
878
1086
|
async function main() {
|
|
879
|
-
|
|
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({
|
|
880
1092
|
args: cliArgs,
|
|
881
|
-
allowPositionals:
|
|
1093
|
+
allowPositionals: true,
|
|
882
1094
|
options: {
|
|
883
1095
|
"allow-suspicious": {
|
|
884
1096
|
type: "boolean",
|
|
885
|
-
default:
|
|
1097
|
+
default: false
|
|
886
1098
|
},
|
|
887
1099
|
"dry-run": {
|
|
888
1100
|
type: "boolean",
|
|
889
|
-
default:
|
|
1101
|
+
default: false
|
|
890
1102
|
},
|
|
891
1103
|
"guard-only": {
|
|
892
1104
|
type: "boolean",
|
|
893
|
-
default:
|
|
1105
|
+
default: false
|
|
894
1106
|
},
|
|
895
1107
|
help: {
|
|
896
1108
|
type: "boolean",
|
|
897
1109
|
short: "h",
|
|
898
|
-
default:
|
|
1110
|
+
default: false
|
|
899
1111
|
},
|
|
900
1112
|
"no-git-checks": {
|
|
901
1113
|
type: "boolean",
|
|
902
|
-
default:
|
|
1114
|
+
default: false
|
|
903
1115
|
},
|
|
904
1116
|
registry: {
|
|
905
1117
|
type: "string",
|
|
@@ -907,7 +1119,7 @@ async function main() {
|
|
|
907
1119
|
},
|
|
908
1120
|
"skip-file-check": {
|
|
909
1121
|
type: "boolean",
|
|
910
|
-
default:
|
|
1122
|
+
default: false
|
|
911
1123
|
},
|
|
912
1124
|
"tarball-out": {
|
|
913
1125
|
type: "string",
|
|
@@ -916,38 +1128,40 @@ async function main() {
|
|
|
916
1128
|
version: {
|
|
917
1129
|
type: "boolean",
|
|
918
1130
|
short: "v",
|
|
919
|
-
default:
|
|
1131
|
+
default: false
|
|
920
1132
|
}
|
|
921
1133
|
},
|
|
922
|
-
strict:
|
|
1134
|
+
strict: true
|
|
923
1135
|
});
|
|
924
1136
|
if (parsed.values.version) {
|
|
925
1137
|
console.log(ownVersion());
|
|
926
1138
|
return;
|
|
927
1139
|
}
|
|
928
1140
|
if (parsed.values.help) {
|
|
929
|
-
console.log(
|
|
1141
|
+
console.log(HELP);
|
|
930
1142
|
return;
|
|
931
1143
|
}
|
|
932
1144
|
if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
|
|
933
1145
|
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
|
|
934
|
-
allowSuspicious: parsed.values["allow-suspicious"] ===
|
|
935
|
-
dryRun: parsed.values["dry-run"] ===
|
|
936
|
-
guardOnly: parsed.values["guard-only"] ===
|
|
937
|
-
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,
|
|
938
1150
|
publishArgs,
|
|
939
|
-
registry: typeof parsed.values.registry
|
|
940
|
-
skipFileCheck: parsed.values["skip-file-check"] ===
|
|
941
|
-
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
|
|
942
1154
|
});
|
|
943
1155
|
}
|
|
944
1156
|
main().catch((error) => {
|
|
945
|
-
|
|
1157
|
+
const details = [
|
|
946
1158
|
error instanceof Error ? error.message : String(error),
|
|
947
1159
|
outputFromError(error, "stdout"),
|
|
948
1160
|
outputFromError(error, "stderr")
|
|
949
1161
|
].filter((detail) => detail.length > 0);
|
|
950
|
-
console.error(`publish-clean: ${details.join("\n")}`)
|
|
1162
|
+
console.error(`publish-clean: ${details.join("\n")}`);
|
|
1163
|
+
process.exitCode = 1;
|
|
951
1164
|
});
|
|
1165
|
+
|
|
952
1166
|
//#endregion
|
|
953
|
-
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",
|