@anizoptera/publish-clean 0.2.0 → 0.4.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 +402 -158
- package/dist/cli.js +435 -169
- package/package.json +7 -8
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
3
|
import { readFileSync, statSync } from "node:fs";
|
|
4
|
-
import { copyFile, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { parseArgs } from "node:util";
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
9
|
+
//#region src/rules.ts
|
|
10
|
+
/**
|
|
11
|
+
* Every decision this tool makes about what a published package carries, with no process,
|
|
12
|
+
* filesystem or argv in reach. The split is not cosmetic: these are the rules that say what
|
|
13
|
+
* ships, and each is worth exercising directly, one input to one output, rather than through
|
|
14
|
+
* two package managers and a tarball. cli.ts owns the effects and wires them to these.
|
|
15
|
+
*
|
|
16
|
+
* Ambient inputs arrive as parameters, never by reaching for them: reading `process.env` from
|
|
17
|
+
* here would make these cases depend on state a test can only set process-wide, which is both
|
|
18
|
+
* a mock and a race against every case running beside it.
|
|
19
|
+
*/
|
|
20
|
+
const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.catalogs.patchedDependencies.private.files.stylelint.trustedDependencies.wireit.devDependencies.overrides.resolutions.ava.c8.jest.mocha.nyc.tap.vitest.babel.biome.browserslist.eslintConfig.eslintIgnore.prettier.remarkConfig.xo.commitlint.husky.lint-staged.simple-git-hooks.clean-publish.publish-clean.semantic-release.packageManager.pnpm.volta.workspaces.nx.turbo".split(".")), CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
|
|
10
21
|
"preinstall",
|
|
11
22
|
"install",
|
|
12
23
|
"postinstall",
|
|
@@ -24,7 +35,7 @@ const DEV_FIELDS = new Set(/* @__PURE__ */ "devDependencies.overrides.resolution
|
|
|
24
35
|
"workspace:",
|
|
25
36
|
"link:",
|
|
26
37
|
"portal:"
|
|
27
|
-
], RUNTIME_MANIFEST_FIELDS = new Set([
|
|
38
|
+
], RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
28
39
|
...DEP_FIELDS,
|
|
29
40
|
"bin",
|
|
30
41
|
"browser",
|
|
@@ -33,13 +44,12 @@ const DEV_FIELDS = new Set(/* @__PURE__ */ "devDependencies.overrides.resolution
|
|
|
33
44
|
"cpu",
|
|
34
45
|
"engines",
|
|
35
46
|
"exports",
|
|
36
|
-
"files",
|
|
37
47
|
"imports",
|
|
48
|
+
"libc",
|
|
38
49
|
"license",
|
|
39
50
|
"main",
|
|
40
51
|
"module",
|
|
41
52
|
"name",
|
|
42
|
-
"optionalDependencies",
|
|
43
53
|
"os",
|
|
44
54
|
"peerDependenciesMeta",
|
|
45
55
|
"publishConfig",
|
|
@@ -49,19 +59,103 @@ const DEV_FIELDS = new Set(/* @__PURE__ */ "devDependencies.overrides.resolution
|
|
|
49
59
|
"typesVersions",
|
|
50
60
|
"typings",
|
|
51
61
|
"version"
|
|
52
|
-
]),
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
62
|
+
]), REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
63
|
+
"author",
|
|
64
|
+
"bugs",
|
|
65
|
+
"config",
|
|
66
|
+
"contributors",
|
|
67
|
+
"deno",
|
|
68
|
+
"description",
|
|
69
|
+
"directories",
|
|
70
|
+
"funding",
|
|
71
|
+
"gitHead",
|
|
72
|
+
"homepage",
|
|
73
|
+
"jsdelivr",
|
|
74
|
+
"keywords",
|
|
75
|
+
"maintainers",
|
|
76
|
+
"man",
|
|
77
|
+
"preferGlobal",
|
|
78
|
+
"react-native",
|
|
79
|
+
"repository",
|
|
80
|
+
"sass",
|
|
81
|
+
"scripts",
|
|
82
|
+
"style",
|
|
83
|
+
"styleModule",
|
|
84
|
+
"svelte",
|
|
85
|
+
"unpkg"
|
|
86
|
+
]);
|
|
87
|
+
/**
|
|
88
|
+
* Refuses a published manifest that lost a field the source declared and consumers read.
|
|
89
|
+
*
|
|
90
|
+
* Every other check here asks whether something got in that should not have. This asks the
|
|
91
|
+
* opposite, and nothing else does: cleaning is subtraction, so the way it fails is by
|
|
92
|
+
* taking too much. A dropped `repository` breaks provenance verification, a dropped
|
|
93
|
+
* `exports` makes the package unimportable, and neither leaves any trace in the artifact
|
|
94
|
+
* to notice later. The registry keeps the version forever either way.
|
|
95
|
+
*
|
|
96
|
+
* Compared against the *final* tarball rather than the cleaned directory, so a loss
|
|
97
|
+
* introduced by the re-pack is caught as well as one introduced by stripping.
|
|
98
|
+
*
|
|
99
|
+
* `devFields` entries are exempt: removing those was the request. `scripts` is exempt
|
|
100
|
+
* because it is rewritten rather than removed, down to the install lifecycle hooks a
|
|
101
|
+
* consumer runs, and a package whose scripts are all developer-only correctly ends up with
|
|
102
|
+
* none.
|
|
103
|
+
*/
|
|
104
|
+
function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
105
|
+
let expected = /* @__PURE__ */ new Set([
|
|
106
|
+
...DEV_FIELDS,
|
|
107
|
+
...removedOnRequest,
|
|
108
|
+
"scripts"
|
|
109
|
+
]), lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
|
|
110
|
+
if (lost.length > 0) throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${lost.join("\n")}`);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Names the fields that survived cleaning without anyone recognising them.
|
|
114
|
+
*
|
|
115
|
+
* The strip list can only ever describe tools that existed when it was written, so every new
|
|
116
|
+
* `package.json` key some tool invents ships to consumers until a human notices. This cannot
|
|
117
|
+
* be fixed by keeping only recognised fields: that would silently drop a key some consumer
|
|
118
|
+
* genuinely resolves, and the breakage would surface in a stranger's project rather than here.
|
|
119
|
+
* So the field ships, and the maintainer is told it did, with the exact config that would drop
|
|
120
|
+
* it next time. It is advice about the package, not an error in it — nothing about the
|
|
121
|
+
* published artifact depends on whether anyone reads it.
|
|
122
|
+
*
|
|
123
|
+
* Returned rather than printed, so the message is this function's value and can be asserted
|
|
124
|
+
* whole. Writing to `console` from here would make that assertion a spy on a process-wide
|
|
125
|
+
* object, which two cases running side by side can clobber.
|
|
126
|
+
*/
|
|
127
|
+
function unrecognizedFieldsReport(pkg, kept) {
|
|
128
|
+
let acknowledged = new Set(kept), unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
|
|
129
|
+
return unrecognized.length === 0 ? null : `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(", ")}] }`;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Content that must never reach a registry. Matched against tarball paths with the
|
|
133
|
+
* `package/` prefix already stripped, so `^` means the package root.
|
|
134
|
+
*
|
|
135
|
+
* Case-insensitive throughout, because the filesystems most packages are built on are
|
|
136
|
+
* too. On macOS and Windows `Server.PEM` and `server.pem` are the same file, so a
|
|
137
|
+
* case-sensitive guard refuses one and publishes the other, which is worse than no guard:
|
|
138
|
+
* it reads as coverage.
|
|
139
|
+
*
|
|
140
|
+
* Private keys are matched by extension and, separately, by exact filename. SSH keys carry
|
|
141
|
+
* no extension at all, and `id_rsa` is the most common private-key filename there is. The
|
|
142
|
+
* exact-name form deliberately does not match `id_rsa.pub`, which is public by design and
|
|
143
|
+
* legitimate to ship.
|
|
144
|
+
*/
|
|
145
|
+
const CRITICAL_PATTERNS = [
|
|
146
|
+
/(?:^|\/)node_modules(?:\/|$)/i,
|
|
147
|
+
/(?:^|\/)\.git(?:\/|$)/i,
|
|
148
|
+
/(?:^|\/)\.env(?:\.|$)/i,
|
|
149
|
+
/(?:^|\/)\.npmrc$/i,
|
|
150
|
+
/\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
|
|
151
|
+
/(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
|
|
58
152
|
], SUSPICIOUS_PATTERNS = [
|
|
59
153
|
/(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
|
|
60
154
|
/(?:^|\/)\.github(?:\/|$)/,
|
|
61
155
|
/(?:^|\/)tsconfig[^/]*\.json$/,
|
|
62
156
|
/(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
|
|
63
157
|
/\.(?:test|spec)\.[cm]?[jt]sx?$/
|
|
64
|
-
], PUBLISH_ADVISORY = "publish-clean
|
|
158
|
+
], 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.", MIN_TRUSTED_NPM_VERSION = [
|
|
65
159
|
11,
|
|
66
160
|
5,
|
|
67
161
|
1
|
|
@@ -74,6 +168,251 @@ var PublishCleanError = class extends Error {
|
|
|
74
168
|
function isObject(value) {
|
|
75
169
|
return typeof value == "object" && !!value && !Array.isArray(value);
|
|
76
170
|
}
|
|
171
|
+
function stringifyJson(value) {
|
|
172
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
173
|
+
}
|
|
174
|
+
function stableJson(value) {
|
|
175
|
+
return JSON.stringify(stableValue(value));
|
|
176
|
+
}
|
|
177
|
+
function stableValue(value) {
|
|
178
|
+
return Array.isArray(value) ? value.map(stableValue) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)])) : value;
|
|
179
|
+
}
|
|
180
|
+
function isAtLeast(actual, minimum) {
|
|
181
|
+
for (let index of [
|
|
182
|
+
0,
|
|
183
|
+
1,
|
|
184
|
+
2
|
|
185
|
+
]) {
|
|
186
|
+
if (actual[index] > minimum[index]) return !0;
|
|
187
|
+
if (actual[index] < minimum[index]) return !1;
|
|
188
|
+
}
|
|
189
|
+
return !0;
|
|
190
|
+
}
|
|
191
|
+
function wantsTrustedPublish(pkg, publishArgs, env) {
|
|
192
|
+
return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
|
|
193
|
+
}
|
|
194
|
+
function assertPublicPackage(pkg) {
|
|
195
|
+
if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
|
|
196
|
+
}
|
|
197
|
+
function repositoryUrl(pkg) {
|
|
198
|
+
return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
|
|
199
|
+
}
|
|
200
|
+
function githubRepositorySlug(url) {
|
|
201
|
+
let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
|
|
202
|
+
if (withoutGitPrefix.startsWith("git@github.com:")) {
|
|
203
|
+
let slug = withoutGitPrefix.slice(15);
|
|
204
|
+
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
let parsed = new URL(withoutGitPrefix);
|
|
208
|
+
if (parsed.hostname !== "github.com") return null;
|
|
209
|
+
let slug = parsed.pathname.replace(/^\/+/, "");
|
|
210
|
+
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
211
|
+
} catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
|
|
216
|
+
if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
|
|
217
|
+
let repoUrl = repositoryUrl(pkg);
|
|
218
|
+
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
219
|
+
if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
|
|
220
|
+
}
|
|
221
|
+
function stripManifest(pkg, extraDevFields) {
|
|
222
|
+
let stripped = { ...pkg };
|
|
223
|
+
for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
224
|
+
let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
225
|
+
if (scripts) {
|
|
226
|
+
let kept = {};
|
|
227
|
+
for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
|
|
228
|
+
Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
|
|
229
|
+
}
|
|
230
|
+
return stripped;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Pins the published manifest to a registry, when one was chosen.
|
|
234
|
+
*
|
|
235
|
+
* Written into `publishConfig` rather than passed only on the command line, because that is
|
|
236
|
+
* where npm looks when someone later republishes the same tarball by hand — the artifact then
|
|
237
|
+
* carries its own destination instead of depending on whoever runs the command. Any other
|
|
238
|
+
* `publishConfig` keys the author set are consumer-facing and survive untouched.
|
|
239
|
+
*
|
|
240
|
+
* Returns the manifest unchanged when no registry was chosen, so the caller has no branch and
|
|
241
|
+
* cannot forget one.
|
|
242
|
+
*/
|
|
243
|
+
function withRegistry(pkg, registry) {
|
|
244
|
+
if (registry === null) return pkg;
|
|
245
|
+
let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
|
|
246
|
+
return publishConfig.registry = registry, {
|
|
247
|
+
...pkg,
|
|
248
|
+
publishConfig
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Refuses a manifest that still carries a spec only a workspace can resolve. Published
|
|
253
|
+
* with one, the package is uninstallable for everyone, and the version cannot be taken
|
|
254
|
+
* back.
|
|
255
|
+
*
|
|
256
|
+
* Both call sites pass an already-stripped manifest, so the dev-only members of
|
|
257
|
+
* DEP_FIELDS are absent by construction. They are still checked, because a guard whose
|
|
258
|
+
* correctness depends on the order it happens to be called in fails silently the day
|
|
259
|
+
* someone reorders it.
|
|
260
|
+
*/
|
|
261
|
+
function assertNoMonorepoProtocols(pkg) {
|
|
262
|
+
let failures = [];
|
|
263
|
+
for (let field of DEP_FIELDS) {
|
|
264
|
+
let map = pkg[field];
|
|
265
|
+
if (isObject(map)) for (let [name, spec] of Object.entries(map)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`${field}.${name}: ${spec}`);
|
|
266
|
+
}
|
|
267
|
+
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
268
|
+
}
|
|
269
|
+
function customDevFields(config) {
|
|
270
|
+
if (!Array.isArray(config.devFields)) return [];
|
|
271
|
+
let fields = config.devFields.filter((field) => typeof field == "string"), unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
|
|
272
|
+
if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
|
|
273
|
+
return fields;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Fields the maintainer has confirmed belong in the published package, so they stop being
|
|
277
|
+
* reported as unrecognised.
|
|
278
|
+
*
|
|
279
|
+
* Without this the report has only one resolution, `devFields`, which deletes the field.
|
|
280
|
+
* That is the wrong answer for every package whose ecosystem this tool has never heard of:
|
|
281
|
+
* a VS Code extension needs `contributes` and `publisher` in the artifact to function at
|
|
282
|
+
* all. Its author would face a warning on every release that can only be silenced by
|
|
283
|
+
* breaking the extension, and a warning nobody can act on trains everyone to ignore the
|
|
284
|
+
* next one, including a real leak.
|
|
285
|
+
*/
|
|
286
|
+
function keptFields(config) {
|
|
287
|
+
return Array.isArray(config.keepFields) ? config.keepFields.filter((field) => typeof field == "string") : [];
|
|
288
|
+
}
|
|
289
|
+
function assertFilesField(pkg, skip) {
|
|
290
|
+
if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
|
|
291
|
+
}
|
|
292
|
+
function validatePackedFiles(files, skipSuspicious) {
|
|
293
|
+
let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
|
|
294
|
+
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
|
|
295
|
+
if (skipSuspicious) return;
|
|
296
|
+
let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
|
|
297
|
+
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Walks a manifest value of any shape and collects the strings that name a file inside
|
|
301
|
+
* the package, so the caller can prove each one exists in the tarball.
|
|
302
|
+
*
|
|
303
|
+
* `mode` exists because the two families of path-bearing fields disagree about what a
|
|
304
|
+
* bare string means, and reading one by the other's rules produces wrong answers in both
|
|
305
|
+
* directions:
|
|
306
|
+
*
|
|
307
|
+
* - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
|
|
308
|
+
* where every string is a path into this package.
|
|
309
|
+
* - `"relative-only"` for `exports`, `imports`, `sideEffects` and the object form of
|
|
310
|
+
* `browser`, where a string may just as well be an external package name, a condition
|
|
311
|
+
* target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
|
|
312
|
+
* rest would report a missing file for something that was never a file.
|
|
313
|
+
*
|
|
314
|
+
* Booleans are skipped rather than ignored by accident: `sideEffects: false` and
|
|
315
|
+
* `exports` condition values legitimately hold them.
|
|
316
|
+
*/
|
|
317
|
+
function collectDeclaredPaths(value, out, mode) {
|
|
318
|
+
if (typeof value == "string") {
|
|
319
|
+
(mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (typeof value != "boolean") {
|
|
323
|
+
if (Array.isArray(value)) {
|
|
324
|
+
for (let item of value) collectDeclaredPaths(item, out, mode);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out, mode);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function normalizeDeclaredPath(declared) {
|
|
331
|
+
let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
|
|
332
|
+
if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
|
|
333
|
+
let normalized = path.posix.normalize(withoutDot);
|
|
334
|
+
return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
|
|
335
|
+
}
|
|
336
|
+
function packageConfig(pkg) {
|
|
337
|
+
let config = pkg["publish-clean"];
|
|
338
|
+
return isObject(config) ? config : {};
|
|
339
|
+
}
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/tarball.ts
|
|
342
|
+
/**
|
|
343
|
+
* Replaces the manifest inside a packed tarball without repacking it.
|
|
344
|
+
*
|
|
345
|
+
* The pipeline packs once, with pnpm, because that packer decides the file set. Cleaning the
|
|
346
|
+
* manifest by unpacking and packing again hands that decision to a second packer, which
|
|
347
|
+
* re-derives it from the very field being cleaned and silently disagrees; rewriting the one
|
|
348
|
+
* member that changed keeps the first packer's selection, and its normalisation (uid/gid 0,
|
|
349
|
+
* a fixed mtime, mode 644) that a naive `tar` invocation leaks the build machine's identity
|
|
350
|
+
* into.
|
|
351
|
+
*
|
|
352
|
+
* Every entry other than the manifest is copied as opaque bytes and never decoded, so entry
|
|
353
|
+
* shapes this code does not model — pax extended headers, ustar prefix splitting, GNU long
|
|
354
|
+
* names — survive untouched. Only walking is universal: an entry's length is always its
|
|
355
|
+
* header block plus its size rounded up to a block, whatever the type.
|
|
356
|
+
*/
|
|
357
|
+
const MANIFEST_PATH = "package/package.json", PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
|
|
358
|
+
function field(block, offset, length) {
|
|
359
|
+
return block.toString("utf8", offset, offset + length).replace(/\0.*/s, "");
|
|
360
|
+
}
|
|
361
|
+
function entrySize(block) {
|
|
362
|
+
if ((block[124] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
|
|
363
|
+
let size = Number.parseInt(field(block, 124, 12).trim(), 8);
|
|
364
|
+
if (!Number.isFinite(size) || size < 0) throw new PublishCleanError("Tarball entry has an unreadable size field.");
|
|
365
|
+
return size;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Rejects a pax header that renames another entry onto the manifest path.
|
|
369
|
+
*
|
|
370
|
+
* Without this the archive could extract a `package.json` that no check ever saw: the guards
|
|
371
|
+
* validate the entry rewritten here, while an extractor honours the pax override and writes
|
|
372
|
+
* a different one over it. The header's own name field is `PaxHeader`, so nothing about the
|
|
373
|
+
* substitution is visible from the walk alone.
|
|
374
|
+
*/
|
|
375
|
+
function assertNoManifestOverride(payload) {
|
|
376
|
+
for (let 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}.`);
|
|
377
|
+
}
|
|
378
|
+
/** Rebuilds a header for a changed payload size, keeping every other field of the original. */
|
|
379
|
+
function reheader(original, size) {
|
|
380
|
+
let header = Buffer.from(original);
|
|
381
|
+
header.write(size.toString(8).padStart(11, "0") + "\0", 124, 12, "ascii"), header.write(" ".repeat(8), 148, 8, "ascii");
|
|
382
|
+
let sum = 0;
|
|
383
|
+
for (let byte of header) sum += byte;
|
|
384
|
+
return header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii"), header;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Returns the gzipped tarball with `package/package.json` replaced by `manifest`.
|
|
388
|
+
*
|
|
389
|
+
* Refuses anything it cannot rewrite unambiguously. Duplicate manifest entries are a refusal
|
|
390
|
+
* rather than a last-one-wins guess, because extractors disagree about which survives and the
|
|
391
|
+
* published manifest would then depend on the extractor rather than on this tool.
|
|
392
|
+
*/
|
|
393
|
+
function replaceTarballManifest(archive, manifest) {
|
|
394
|
+
let tar = gunzipSync(archive), parts = [], replaced = !1;
|
|
395
|
+
for (let offset = 0; offset < tar.length;) {
|
|
396
|
+
let header = tar.subarray(offset, offset + 512), name = field(header, 0, 100);
|
|
397
|
+
if (name === "") {
|
|
398
|
+
parts.push(tar.subarray(offset));
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512), type = field(header, 156, 1);
|
|
402
|
+
if (PAX_TYPES.has(type) && assertNoManifestOverride(tar.subarray(offset + 512, offset + 512 + size)), name === MANIFEST_PATH) {
|
|
403
|
+
if (replaced) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
|
|
404
|
+
if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
|
|
405
|
+
let body = Buffer.from(manifest, "utf8");
|
|
406
|
+
parts.push(reheader(header, body.length), body, Buffer.alloc(512 * Math.ceil(body.length / 512) - body.length)), replaced = !0;
|
|
407
|
+
} else parts.push(tar.subarray(offset, end));
|
|
408
|
+
offset = end;
|
|
409
|
+
}
|
|
410
|
+
if (!replaced) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
|
|
411
|
+
return gzipSync(Buffer.concat(parts));
|
|
412
|
+
}
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/cli.ts
|
|
415
|
+
const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
77
416
|
function readJson(file) {
|
|
78
417
|
let parsed;
|
|
79
418
|
try {
|
|
@@ -84,15 +423,6 @@ function readJson(file) {
|
|
|
84
423
|
if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
|
|
85
424
|
return parsed;
|
|
86
425
|
}
|
|
87
|
-
function stringifyJson(value) {
|
|
88
|
-
return `${JSON.stringify(value, null, 2)}\n`;
|
|
89
|
-
}
|
|
90
|
-
function stableJson(value) {
|
|
91
|
-
return JSON.stringify(stableValue(value));
|
|
92
|
-
}
|
|
93
|
-
function stableValue(value) {
|
|
94
|
-
return Array.isArray(value) ? value.map(stableValue) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)])) : value;
|
|
95
|
-
}
|
|
96
426
|
function run(command, args, cwd) {
|
|
97
427
|
return execFileSync(command, [...args], {
|
|
98
428
|
cwd,
|
|
@@ -109,11 +439,60 @@ function outputFromError(error, key) {
|
|
|
109
439
|
let output = error[key];
|
|
110
440
|
return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
|
|
111
441
|
}
|
|
442
|
+
/**
|
|
443
|
+
* Runs a command with its streams attached to this process instead of captured.
|
|
444
|
+
*
|
|
445
|
+
* Reserved for `npm publish`. Every other command here is run for its output or its
|
|
446
|
+
* effect, but the publish is the one irreversible step, and npm's output is the only
|
|
447
|
+
* receipt the operator gets: the version that went out, the tarball size, the integrity
|
|
448
|
+
* hash, and the registry's own wording when it refuses. `run` would swallow all of it on
|
|
449
|
+
* success and hold the failure text until the process exits, which in CI means a log
|
|
450
|
+
* that says nothing about the one action that cannot be undone.
|
|
451
|
+
*/
|
|
452
|
+
function runAttached(command, args, cwd) {
|
|
453
|
+
execFileSync(command, [...args], {
|
|
454
|
+
cwd,
|
|
455
|
+
stdio: [
|
|
456
|
+
"ignore",
|
|
457
|
+
"inherit",
|
|
458
|
+
"inherit"
|
|
459
|
+
]
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* A required tool can fail three ways, and each one asks something different of the
|
|
464
|
+
* reader, so the probe reports what it observed instead of assuming the common case.
|
|
465
|
+
* A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
|
|
466
|
+
* to run when no version is pinned; calling that absence sends the reader to verify the
|
|
467
|
+
* one thing already correct, and `which pnpm` then agrees with them and not with us. The
|
|
468
|
+
* shim's own message names the fix, so it is forwarded rather than replaced.
|
|
469
|
+
*/
|
|
470
|
+
function toolFailureReason(cause) {
|
|
471
|
+
if (isObject(cause)) {
|
|
472
|
+
if (cause.code === "ENOENT") return "is not available in PATH";
|
|
473
|
+
if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
|
|
474
|
+
}
|
|
475
|
+
let stderr = outputFromError(cause, "stderr");
|
|
476
|
+
return `is present but failed to run${stderr ? `: ${stderr}` : ""}`;
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* The probe is bounded because a wedged shim would otherwise hang the publish with no end:
|
|
480
|
+
* `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
|
|
481
|
+
* belongs on the spawn itself. It stays generous because the only job is to separate a
|
|
482
|
+
* tool that answers from one that never will.
|
|
483
|
+
*/
|
|
112
484
|
function requireTool(name) {
|
|
113
485
|
try {
|
|
114
|
-
execFileSync(name, ["--version"], {
|
|
486
|
+
execFileSync(name, ["--version"], {
|
|
487
|
+
stdio: [
|
|
488
|
+
"ignore",
|
|
489
|
+
"ignore",
|
|
490
|
+
"pipe"
|
|
491
|
+
],
|
|
492
|
+
timeout: TOOL_PROBE_TIMEOUT_MS
|
|
493
|
+
});
|
|
115
494
|
} catch (cause) {
|
|
116
|
-
throw new PublishCleanError(`Required tool "${name}"
|
|
495
|
+
throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
|
|
117
496
|
}
|
|
118
497
|
}
|
|
119
498
|
function npmVersion() {
|
|
@@ -125,22 +504,20 @@ function npmVersion() {
|
|
|
125
504
|
parts[2] ?? 0
|
|
126
505
|
];
|
|
127
506
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
function wantsTrustedPublish(pkg, publishArgs) {
|
|
140
|
-
return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : process.env.GITHUB_ACTIONS === "true" && typeof process.env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
|
|
507
|
+
/**
|
|
508
|
+
* The single place the ambient environment is read for publish decisions. Naming the three
|
|
509
|
+
* variables here keeps `process` out of the rules and makes the whole environmental surface of
|
|
510
|
+
* a publish visible at once, rather than spread across the guards that consult it.
|
|
511
|
+
*/
|
|
512
|
+
function publishEnv() {
|
|
513
|
+
return {
|
|
514
|
+
ACTIONS_ID_TOKEN_REQUEST_URL: process.env.ACTIONS_ID_TOKEN_REQUEST_URL,
|
|
515
|
+
GITHUB_ACTIONS: process.env.GITHUB_ACTIONS,
|
|
516
|
+
GITHUB_REPOSITORY: process.env.GITHUB_REPOSITORY
|
|
517
|
+
};
|
|
141
518
|
}
|
|
142
519
|
function assertTrustedPublishingRuntime(pkg, publishArgs) {
|
|
143
|
-
if (!wantsTrustedPublish(pkg, publishArgs)) return;
|
|
520
|
+
if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
|
|
144
521
|
let actual = npmVersion();
|
|
145
522
|
if (!isAtLeast(actual, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${actual.join(".")}.`);
|
|
146
523
|
let node = process.versions.node.split(".").map(Number);
|
|
@@ -171,60 +548,6 @@ function assertCleanGit(packageDir, skip) {
|
|
|
171
548
|
throw error instanceof PublishCleanError ? error : new PublishCleanError("Unable to verify source git status.", { cause: error });
|
|
172
549
|
}
|
|
173
550
|
}
|
|
174
|
-
function assertPublicPackage(pkg) {
|
|
175
|
-
if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
|
|
176
|
-
}
|
|
177
|
-
function repositoryUrl(pkg) {
|
|
178
|
-
return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
|
|
179
|
-
}
|
|
180
|
-
function githubRepositorySlug(url) {
|
|
181
|
-
let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
|
|
182
|
-
if (withoutGitPrefix.startsWith("git@github.com:")) {
|
|
183
|
-
let slug = withoutGitPrefix.slice(15);
|
|
184
|
-
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
185
|
-
}
|
|
186
|
-
try {
|
|
187
|
-
let parsed = new URL(withoutGitPrefix);
|
|
188
|
-
if (parsed.hostname !== "github.com") return null;
|
|
189
|
-
let slug = parsed.pathname.replace(/^\/+/, "");
|
|
190
|
-
return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
|
|
191
|
-
} catch {
|
|
192
|
-
return null;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
function assertRepositoryForTrustedPublish(pkg, publishArgs) {
|
|
196
|
-
if (!wantsTrustedPublish(pkg, publishArgs) || process.env.GITHUB_ACTIONS !== "true" || typeof process.env.GITHUB_REPOSITORY != "string") return;
|
|
197
|
-
let repoUrl = repositoryUrl(pkg);
|
|
198
|
-
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
199
|
-
if (githubRepositorySlug(repoUrl) !== process.env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${process.env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
|
|
200
|
-
}
|
|
201
|
-
function stripManifest(pkg, extraDevFields) {
|
|
202
|
-
let stripped = { ...pkg };
|
|
203
|
-
for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
204
|
-
let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
205
|
-
if (scripts) {
|
|
206
|
-
let kept = {};
|
|
207
|
-
for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
|
|
208
|
-
Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
|
|
209
|
-
}
|
|
210
|
-
return stripped;
|
|
211
|
-
}
|
|
212
|
-
function assertNoMonorepoProtocols(pkg) {
|
|
213
|
-
let failures = [];
|
|
214
|
-
for (let field of DEP_FIELDS) {
|
|
215
|
-
let map = pkg[field];
|
|
216
|
-
if (isObject(map)) for (let [name, spec] of Object.entries(map)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`${field}.${name}: ${spec}`);
|
|
217
|
-
}
|
|
218
|
-
let pnpm = pkg.pnpm;
|
|
219
|
-
if (isObject(pnpm) && isObject(pnpm.overrides)) for (let [name, spec] of Object.entries(pnpm.overrides)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`pnpm.overrides.${name}: ${spec}`);
|
|
220
|
-
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
221
|
-
}
|
|
222
|
-
function customDevFields(config) {
|
|
223
|
-
if (!Array.isArray(config.devFields)) return [];
|
|
224
|
-
let fields = config.devFields.filter((field) => typeof field == "string"), unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
|
|
225
|
-
if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
|
|
226
|
-
return fields;
|
|
227
|
-
}
|
|
228
551
|
async function walkFiles(dir, root, files) {
|
|
229
552
|
let entries = await readdir(dir, { withFileTypes: !0 });
|
|
230
553
|
for (let entry of entries) {
|
|
@@ -236,16 +559,6 @@ async function walkFiles(dir, root, files) {
|
|
|
236
559
|
entry.isFile() && files.push(relative);
|
|
237
560
|
}
|
|
238
561
|
}
|
|
239
|
-
function assertFilesField(pkg, skip) {
|
|
240
|
-
if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
|
|
241
|
-
}
|
|
242
|
-
function validatePackedFiles(files, skipSuspicious) {
|
|
243
|
-
let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
|
|
244
|
-
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
|
|
245
|
-
if (skipSuspicious) return;
|
|
246
|
-
let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
|
|
247
|
-
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
|
|
248
|
-
}
|
|
249
562
|
function listTarballFiles(tarball, cwd) {
|
|
250
563
|
return run("tar", ["tzf", tarball], cwd).trim().split("\n").filter(Boolean).map((file) => file.replaceAll(path.sep, "/")).map((file) => file.startsWith("package/") ? file.slice(8) : file).filter((file) => file.length > 0 && !file.endsWith("/")).sort();
|
|
251
564
|
}
|
|
@@ -281,42 +594,6 @@ async function soleTarball(packRoot, packer) {
|
|
|
281
594
|
if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`${packer} left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
|
|
282
595
|
return path.join(packRoot, tarball);
|
|
283
596
|
}
|
|
284
|
-
function assertFinalTarballIncludesCleanedFiles(cleanedFiles, finalFiles) {
|
|
285
|
-
let missing = cleanedFiles.filter((file) => !finalFiles.includes(file)).sort();
|
|
286
|
-
if (missing.length !== 0) throw new PublishCleanError(`Final npm tarball dropped files from the cleaned package:\n${missing.join("\n")}`);
|
|
287
|
-
}
|
|
288
|
-
function collectDeclaredPaths(value, out) {
|
|
289
|
-
if (typeof value == "string") {
|
|
290
|
-
out.push(value);
|
|
291
|
-
return;
|
|
292
|
-
}
|
|
293
|
-
if (typeof value != "boolean") {
|
|
294
|
-
if (Array.isArray(value)) {
|
|
295
|
-
for (let item of value) collectDeclaredPaths(item, out);
|
|
296
|
-
return;
|
|
297
|
-
}
|
|
298
|
-
if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
function collectRelativeDeclaredPaths(value, out) {
|
|
302
|
-
if (typeof value == "string") {
|
|
303
|
-
(value.startsWith("./") || value.startsWith("../")) && out.push(value);
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
if (typeof value != "boolean") {
|
|
307
|
-
if (Array.isArray(value)) {
|
|
308
|
-
for (let item of value) collectRelativeDeclaredPaths(item, out);
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
if (isObject(value)) for (let item of Object.values(value)) collectRelativeDeclaredPaths(item, out);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
function normalizeDeclaredPath(declared) {
|
|
315
|
-
let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
|
|
316
|
-
if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
|
|
317
|
-
let normalized = path.posix.normalize(withoutDot);
|
|
318
|
-
return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
|
|
319
|
-
}
|
|
320
597
|
function assertDeclaredFiles(pkg, packageDir) {
|
|
321
598
|
let paths = [];
|
|
322
599
|
for (let field of [
|
|
@@ -325,14 +602,14 @@ function assertDeclaredFiles(pkg, packageDir) {
|
|
|
325
602
|
"types",
|
|
326
603
|
"typings",
|
|
327
604
|
"bin"
|
|
328
|
-
]) collectDeclaredPaths(pkg[field], paths);
|
|
329
|
-
typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, paths) :
|
|
605
|
+
]) collectDeclaredPaths(pkg[field], paths, "every-string");
|
|
606
|
+
typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, paths, "every-string") : collectDeclaredPaths(pkg.browser, paths, "relative-only");
|
|
330
607
|
for (let field of [
|
|
331
608
|
"exports",
|
|
332
609
|
"imports",
|
|
333
610
|
"sideEffects"
|
|
334
|
-
])
|
|
335
|
-
collectDeclaredPaths(pkg.typesVersions, paths);
|
|
611
|
+
]) collectDeclaredPaths(pkg[field], paths, "relative-only");
|
|
612
|
+
collectDeclaredPaths(pkg.typesVersions, paths, "every-string");
|
|
336
613
|
let normalized = paths.map((declared) => ({
|
|
337
614
|
declared,
|
|
338
615
|
normalized: normalizeDeclaredPath(declared)
|
|
@@ -348,15 +625,11 @@ function exists(file) {
|
|
|
348
625
|
return !1;
|
|
349
626
|
}
|
|
350
627
|
}
|
|
351
|
-
function packageConfig(pkg) {
|
|
352
|
-
let config = pkg["publish-clean"];
|
|
353
|
-
return isObject(config) ? config : {};
|
|
354
|
-
}
|
|
355
628
|
async function packAndClean(packageDir, opts) {
|
|
356
629
|
requireTool("pnpm"), requireTool("npm"), requireTool("tar"), warnIfNonPnpmLifecycle();
|
|
357
630
|
let sourcePkg = readJson(path.join(packageDir, "package.json"));
|
|
358
631
|
!opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
|
|
359
|
-
let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config);
|
|
632
|
+
let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config), keepFields = keptFields(config);
|
|
360
633
|
assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
|
|
361
634
|
let root = await mkdtemp(path.join(tmpdir(), "publish-clean-")), keepRoot = !1;
|
|
362
635
|
try {
|
|
@@ -364,9 +637,11 @@ async function packAndClean(packageDir, opts) {
|
|
|
364
637
|
"pack",
|
|
365
638
|
"--pack-destination",
|
|
366
639
|
root
|
|
367
|
-
], packageDir)
|
|
640
|
+
], packageDir);
|
|
641
|
+
let tarball = await soleTarball(root, "pnpm pack");
|
|
642
|
+
run("tar", [
|
|
368
643
|
"xzf",
|
|
369
|
-
|
|
644
|
+
tarball,
|
|
370
645
|
"-C",
|
|
371
646
|
root
|
|
372
647
|
], packageDir);
|
|
@@ -374,25 +649,16 @@ async function packAndClean(packageDir, opts) {
|
|
|
374
649
|
if (!(await stat(extracted)).isDirectory()) throw new PublishCleanError("Extracted tarball did not contain package/ directory.");
|
|
375
650
|
let files = [];
|
|
376
651
|
await walkFiles(extracted, extracted, files), validatePackedFiles(files, skipFileCheck);
|
|
377
|
-
let packedPkgPath = path.join(extracted, "package.json"), cleanedPkg = stripManifest(readJson(packedPkgPath), extraDevFields);
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
let
|
|
384
|
-
await
|
|
385
|
-
let
|
|
386
|
-
|
|
387
|
-
"pack",
|
|
388
|
-
"--ignore-scripts",
|
|
389
|
-
"--pack-destination",
|
|
390
|
-
finalPackRoot
|
|
391
|
-
], extracted);
|
|
392
|
-
let finalTarball = await soleTarball(finalPackRoot, "npm pack"), finalFiles = listTarballFiles(finalTarball, extracted);
|
|
393
|
-
validatePackedFiles(finalFiles, skipFileCheck), assertFinalTarballIncludesCleanedFiles(cleanedFiles, finalFiles);
|
|
394
|
-
let finalPkg = readTarballJson(finalTarball, "package.json", extracted);
|
|
395
|
-
if (assertNoMonorepoProtocols(finalPkg), stableJson(finalPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Final npm tarball manifest differs from the cleaned manifest.");
|
|
652
|
+
let packedPkgPath = path.join(extracted, "package.json"), cleanedPkg = withRegistry(stripManifest(readJson(packedPkgPath), extraDevFields), registry);
|
|
653
|
+
assertNoMonorepoProtocols(cleanedPkg);
|
|
654
|
+
let unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
|
|
655
|
+
unrecognized && console.warn(unrecognized), assertDeclaredFiles(cleanedPkg, extracted), await writeFile(packedPkgPath, stringifyJson(cleanedPkg));
|
|
656
|
+
let publishRoot = path.join(root, "publish");
|
|
657
|
+
await mkdir(publishRoot);
|
|
658
|
+
let finalTarball = path.join(publishRoot, path.basename(tarball));
|
|
659
|
+
await writeFile(finalTarball, replaceTarballManifest(await readFile(tarball), stringifyJson(cleanedPkg))), validatePackedFiles(listTarballFiles(finalTarball, root), skipFileCheck);
|
|
660
|
+
let finalPkg = readTarballJson(finalTarball, "package.json", root);
|
|
661
|
+
if (assertNoMonorepoProtocols(finalPkg), assertNoLostConsumerFields(sourcePkg, finalPkg, extraDevFields), stableJson(finalPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
|
|
396
662
|
if (opts.tarballOut !== null) {
|
|
397
663
|
await mkdir(opts.tarballOut, { recursive: !0 });
|
|
398
664
|
let kept = path.join(opts.tarballOut, path.basename(finalTarball));
|
|
@@ -403,7 +669,7 @@ async function packAndClean(packageDir, opts) {
|
|
|
403
669
|
keepRoot = !0, console.log(`[dry-run] Extracted package at: ${extracted}`), console.log(`[dry-run] Final tarball at: ${finalTarball}`);
|
|
404
670
|
return;
|
|
405
671
|
}
|
|
406
|
-
assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs),
|
|
672
|
+
assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv()), runAttached("npm", registry ? [
|
|
407
673
|
"publish",
|
|
408
674
|
finalTarball,
|
|
409
675
|
"--registry",
|