@icebreakers/monorepo 5.6.0 → 5.7.1
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 +2 -0
- package/dist/baseline-CRCTiMNM.mjs +146 -0
- package/dist/bundle-B9vRch4R.mjs +49 -0
- package/dist/catalog-D0Sk385O.mjs +299 -0
- package/dist/cli.mjs +1487 -156
- package/dist/commands-Bj0sX3R9.mjs +13849 -0
- package/dist/config-Dg-voj8q.mjs +66 -0
- package/dist/{create-flow-CXRhfGbb.mjs → create-flow-BWFWDWR4.mjs} +90 -24
- package/dist/deps-BbykICqB.mjs +47 -0
- package/dist/execute-D2GlX018.mjs +68 -0
- package/dist/execute-DI1mgVLv.mjs +663 -0
- package/dist/format-Dbs0fupU.mjs +28 -0
- package/dist/index-CoCTFWZJ.d.mts +2150 -0
- package/dist/index.d.mts +1738 -112
- package/dist/index.mjs +60 -7
- package/dist/inputs-BKtLcrQ9.mjs +50 -0
- package/dist/npm-Bh6HBy5V.mjs +82 -0
- package/dist/plan-CxySMaLN.mjs +75 -0
- package/dist/run-D_bceMqf.mjs +165 -0
- package/dist/save-DzIWKs0T.mjs +79 -0
- package/dist/scan-B_-E6BWh.mjs +293 -0
- package/dist/template-drift-D0hKxixr.mjs +2740 -0
- package/dist/tooling-entry.d.mts +1 -1
- package/dist/tooling-entry.mjs +2 -2
- package/dist/transaction-DFam8_dp.mjs +168 -0
- package/dist/tsconfig-BZ6E1fBA.mjs +1483 -0
- package/dist/{vitest-Blzbh8xZ.mjs → vitest-XbNmiloj.mjs} +1 -1
- package/dist/workspace-tasks-C5W-QwWj.mjs +4435 -0
- package/package.json +22 -4
- package/resources/api-report/runner.cjs +76 -0
- package/resources/devcontainer/setup.mjs +36 -0
- package/resources/knip/reporter.mjs +46 -0
- package/resources/maintenance/migration-lanes.mjs +141 -0
- package/resources/maintenance/migration-lock.mjs +119 -0
- package/resources/maintenance/migrations.mjs +215 -0
- package/resources/maintenance/presets.mjs +130 -0
- package/resources/maintenance/validate.mjs +233 -0
- package/resources/maintenance/workflow.yml +151 -0
- package/resources/skills/repoctl/SKILL.md +2 -0
- package/resources/skills/repoctl/references/commands.md +224 -13
- package/resources/skills/repoctl/references/config.md +70 -6
- package/resources/skills/repoctl/references/dependencies.md +37 -0
- package/resources/skills/repoctl/references/knip.md +34 -0
- package/resources/skills/repoctl/references/templates.md +23 -0
- package/dist/commands-D4xZQ5t-.mjs +0 -5685
- package/dist/config-p842Knhq.mjs +0 -114
- package/dist/index-Bl_PB2Ch.d.mts +0 -1039
- package/dist/tsconfig-BrjI_5yI.mjs +0 -75
- package/dist/types-MAUIQpfp.mjs +0 -499
- package/dist/workspace-MCKewElu.mjs +0 -123
|
@@ -0,0 +1,2740 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
2
|
+
import { J as getWorkspaceGraph, St as localize, Y as parseDependencyReference, at as record$3, jt as fs$2, nt as workspaceDependencyTypes, rt as hash, ut as hasLegacyToolingReference } from "./workspace-tasks-C5W-QwWj.mjs";
|
|
3
|
+
import { E as relativeFile, T as readOptional, f as loadMonorepoConfigDetails, j as ConfigValidationError, w as hash$1 } from "./tsconfig-BZ6E1fBA.mjs";
|
|
4
|
+
import { a as dependencySections, i as rangesOverlap, r as parseSpecifier, t as scanDependencies } from "./scan-B_-E6BWh.mjs";
|
|
5
|
+
import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
|
|
6
|
+
import path from "pathe";
|
|
7
|
+
import process from "node:process";
|
|
8
|
+
import { access, lstat, open, readFile, readdir, realpath } from "node:fs/promises";
|
|
9
|
+
import { constants, realpathSync } from "node:fs";
|
|
10
|
+
import { compare, eq, gte, intersects, lt, major, minVersion, prerelease, satisfies, valid, validRange } from "semver";
|
|
11
|
+
import validatePackageName from "validate-npm-package-name";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import path$1 from "node:path";
|
|
14
|
+
import { getAssetTargets, isExactTemplateVersion, isGitignoreFile, loadTemplateBaseline, loadTemplateInstanceRegistry, readTemplatePackageVersion, safeInstancePath, templateRegistryPath, toPublishGitignorePath, toWorkspaceAssetPath, toWorkspaceGitignorePath } from "@icebreakers/monorepo-templates";
|
|
15
|
+
import { Buffer } from "node:buffer";
|
|
16
|
+
import YAML from "yaml";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { isDeepStrictEqual } from "node:util";
|
|
19
|
+
//#region src/commands/doctor/helpers.ts
|
|
20
|
+
function createCheck(check) {
|
|
21
|
+
return check;
|
|
22
|
+
}
|
|
23
|
+
function summarizeChecks(checks, includeSuppressed = false) {
|
|
24
|
+
return checks.reduce((summary, check) => {
|
|
25
|
+
if (includeSuppressed || check.suppression?.state !== "active") summary[check.status] += 1;
|
|
26
|
+
return summary;
|
|
27
|
+
}, {
|
|
28
|
+
pass: 0,
|
|
29
|
+
warn: 0,
|
|
30
|
+
fail: 0
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function getWorkspacePatterns(manifest) {
|
|
34
|
+
if (typeof manifest !== "object" || manifest === null) return [];
|
|
35
|
+
const packages = manifest.packages;
|
|
36
|
+
return Array.isArray(packages) ? packages.filter((item) => typeof item === "string") : [];
|
|
37
|
+
}
|
|
38
|
+
function isWorkspacePatternCovered(relativeDir, patterns) {
|
|
39
|
+
const normalized = relativeDir.split("\\").join("/");
|
|
40
|
+
return patterns.some((pattern) => {
|
|
41
|
+
if (pattern.startsWith("!")) return false;
|
|
42
|
+
if (pattern.endsWith("/*")) {
|
|
43
|
+
const base = pattern.slice(0, -2);
|
|
44
|
+
return normalized.startsWith(`${base}/`) && normalized.slice(base.length + 1).split("/").length === 1;
|
|
45
|
+
}
|
|
46
|
+
if (pattern.endsWith("/**")) return normalized.startsWith(`${pattern.slice(0, -3)}/`);
|
|
47
|
+
return normalized === pattern;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/commands/doctor/manifest/types.ts
|
|
52
|
+
function record$2(value) {
|
|
53
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/commands/template-drift/files.ts
|
|
57
|
+
const contentHash = (content) => createHash("sha256").update(content).digest("hex");
|
|
58
|
+
const errorDetail = (error) => error instanceof Error ? error.message : String(error);
|
|
59
|
+
const isMissing = (error) => ["ENOENT", "ENOTDIR"].includes(error.code ?? "");
|
|
60
|
+
/** Open only retained managed paths and hash in bounded chunks, without serializing business contents. */
|
|
61
|
+
async function compareManagedFile(workspaceDir, filename, baselineHash, executable) {
|
|
62
|
+
try {
|
|
63
|
+
const file = await safeInstancePath(workspaceDir, filename);
|
|
64
|
+
const expected = await lstat(file);
|
|
65
|
+
if (!expected.isFile() || expected.isSymbolicLink() || expected.nlink !== 1) throw new Error("The managed path is not a regular, singly linked file.");
|
|
66
|
+
const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
67
|
+
try {
|
|
68
|
+
const before = await handle.stat();
|
|
69
|
+
if (!before.isFile() || before.nlink !== 1 || before.ino !== expected.ino || before.dev !== expected.dev) throw new Error("The managed path is not a regular, singly linked file.");
|
|
70
|
+
const hash = createHash("sha256");
|
|
71
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk);
|
|
72
|
+
const after = await handle.stat();
|
|
73
|
+
const current = await lstat(await safeInstancePath(workspaceDir, filename));
|
|
74
|
+
if (current.ino !== before.ino || current.dev !== before.dev || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error("The managed file changed while its digest was being read.");
|
|
75
|
+
const currentHash = hash.digest("hex");
|
|
76
|
+
const modeChanged = executable !== void 0 && process.platform !== "win32" && (after.mode & 73) !== 0 !== executable;
|
|
77
|
+
return {
|
|
78
|
+
path: filename,
|
|
79
|
+
baselineHash,
|
|
80
|
+
currentHash,
|
|
81
|
+
state: currentHash === baselineHash && !modeChanged ? "unchanged" : "modified",
|
|
82
|
+
...modeChanged ? { detail: "The executable flag differs from the retained baseline." } : {}
|
|
83
|
+
};
|
|
84
|
+
} finally {
|
|
85
|
+
await handle.close();
|
|
86
|
+
}
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return {
|
|
89
|
+
path: filename,
|
|
90
|
+
baselineHash,
|
|
91
|
+
state: isMissing(error) ? "deleted" : "unavailable",
|
|
92
|
+
...isMissing(error) ? {} : { detail: errorDetail(error) }
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function snapshotFileHash(file) {
|
|
97
|
+
return contentHash(Buffer.from(file.content, "base64"));
|
|
98
|
+
}
|
|
99
|
+
function localDriftState(files, baseline) {
|
|
100
|
+
if (baseline !== "available" || files.some((file) => file.state === "unavailable")) return "unknown";
|
|
101
|
+
if (files.some((file) => file.state === "modified" || file.state === "deleted")) return "drifted";
|
|
102
|
+
return files.length && files.every((file) => file.state === "excluded") ? "excluded" : "unchanged";
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/commands/template-drift/versions.ts
|
|
106
|
+
const templatePackageName = "@icebreakers/monorepo-templates";
|
|
107
|
+
async function collectVersionEvidence(options) {
|
|
108
|
+
const kind = options.remote ? "remote" : options.sourceDir ? "extracted" : "installed";
|
|
109
|
+
try {
|
|
110
|
+
let version;
|
|
111
|
+
if (options.remote) {
|
|
112
|
+
const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(templatePackageName)}/latest`, {
|
|
113
|
+
signal: AbortSignal.timeout(1e4),
|
|
114
|
+
headers: { accept: "application/json" }
|
|
115
|
+
});
|
|
116
|
+
if (!response.ok) throw new Error(`Registry returned HTTP ${response.status}.`);
|
|
117
|
+
const manifest = await response.json();
|
|
118
|
+
if (manifest.name !== "@icebreakers/monorepo-templates" || typeof manifest.version !== "string" || !isExactTemplateVersion(manifest.version)) throw new Error("Registry response does not identify an exact template package version.");
|
|
119
|
+
version = manifest.version;
|
|
120
|
+
} else version = await readTemplatePackageVersion(options.sourceDir);
|
|
121
|
+
if (!valid(version)) throw new Error("The template package version cannot be compared as supported semver.");
|
|
122
|
+
return {
|
|
123
|
+
kind,
|
|
124
|
+
status: "available",
|
|
125
|
+
package: templatePackageName,
|
|
126
|
+
version,
|
|
127
|
+
detail: kind === "remote" ? "Explicit query of the public npm latest dist-tag." : `Actual ${kind} template package metadata; the remote latest version was not queried.`
|
|
128
|
+
};
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return {
|
|
131
|
+
kind,
|
|
132
|
+
status: "unavailable",
|
|
133
|
+
package: templatePackageName,
|
|
134
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function compareTemplateVersion(source, evidence) {
|
|
139
|
+
const versions = {
|
|
140
|
+
...source.version ? { currentVersion: source.version } : {},
|
|
141
|
+
...evidence.version ? { comparedVersion: evidence.version } : {}
|
|
142
|
+
};
|
|
143
|
+
if (source.kind !== "package" || source.packageName !== "@icebreakers/monorepo-templates" || !source.version || !isExactTemplateVersion(source.version) || !valid(source.version)) return {
|
|
144
|
+
...versions,
|
|
145
|
+
status: "unknown",
|
|
146
|
+
detail: "The source has no comparable exact template package version."
|
|
147
|
+
};
|
|
148
|
+
if (evidence.status !== "available" || !evidence.version) return {
|
|
149
|
+
...versions,
|
|
150
|
+
status: "unknown",
|
|
151
|
+
detail: `Version evidence is unavailable: ${evidence.detail}`
|
|
152
|
+
};
|
|
153
|
+
const difference = compare(evidence.version, source.version);
|
|
154
|
+
const status = difference > 0 ? "newer" : difference < 0 ? "ahead" : "same";
|
|
155
|
+
return {
|
|
156
|
+
...versions,
|
|
157
|
+
status,
|
|
158
|
+
detail: `Compared retained ${source.version} with ${evidence.kind} ${evidence.version}; ${status === "newer" ? "a newer package version is known" : status === "ahead" ? "the retained source is newer than this comparison package" : "these package versions match"}.`
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/commands/template-drift/instances.ts
|
|
163
|
+
async function inspectInstance(workspaceDir, instance, evidence) {
|
|
164
|
+
const owner = {
|
|
165
|
+
kind: "instance",
|
|
166
|
+
id: instance.id,
|
|
167
|
+
path: instance.target,
|
|
168
|
+
template: instance.template,
|
|
169
|
+
source: instance.source,
|
|
170
|
+
baseline: {
|
|
171
|
+
status: "unverified",
|
|
172
|
+
detail: "No trustworthy historical baseline is registered."
|
|
173
|
+
},
|
|
174
|
+
version: compareTemplateVersion(instance.source, evidence),
|
|
175
|
+
local: "unknown",
|
|
176
|
+
files: [],
|
|
177
|
+
recommendations: []
|
|
178
|
+
};
|
|
179
|
+
if (instance.baseline.status === "available") try {
|
|
180
|
+
await loadTemplateBaseline(workspaceDir, instance.baseline.original);
|
|
181
|
+
const baseline = await loadTemplateBaseline(workspaceDir, instance.baseline.rendered);
|
|
182
|
+
owner.baseline = {
|
|
183
|
+
status: "available",
|
|
184
|
+
detail: "Both retained source and rendered snapshots passed integrity validation."
|
|
185
|
+
};
|
|
186
|
+
try {
|
|
187
|
+
if (!(await lstat(await safeInstancePath(workspaceDir, instance.target))).isDirectory()) owner.files.push({
|
|
188
|
+
path: instance.target,
|
|
189
|
+
state: "modified",
|
|
190
|
+
detail: "The instance directory was replaced by a non-directory."
|
|
191
|
+
});
|
|
192
|
+
} catch (error) {
|
|
193
|
+
owner.files.push({
|
|
194
|
+
path: instance.target,
|
|
195
|
+
state: isMissing(error) ? "deleted" : "unavailable",
|
|
196
|
+
detail: errorDetail(error)
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
const excluded = (filename) => instance.excludedPaths?.some((prefix) => filename === prefix || filename.startsWith(`${prefix}/`));
|
|
200
|
+
for (const file of baseline.files) {
|
|
201
|
+
const filename = `${instance.target}/${file.path}`;
|
|
202
|
+
owner.files.push(excluded(file.path) ? {
|
|
203
|
+
path: filename,
|
|
204
|
+
state: "excluded",
|
|
205
|
+
baselineHash: snapshotFileHash(file),
|
|
206
|
+
detail: "Explicitly excluded from template management."
|
|
207
|
+
} : await compareManagedFile(workspaceDir, filename, snapshotFileHash(file), file.executable));
|
|
208
|
+
}
|
|
209
|
+
for (const relative of baseline.directories) {
|
|
210
|
+
const filename = `${instance.target}/${relative}`;
|
|
211
|
+
let result = {
|
|
212
|
+
path: filename,
|
|
213
|
+
state: "excluded",
|
|
214
|
+
detail: "Explicitly excluded from template management."
|
|
215
|
+
};
|
|
216
|
+
if (!excluded(relative)) try {
|
|
217
|
+
const stat = await lstat(await safeInstancePath(workspaceDir, filename));
|
|
218
|
+
result = {
|
|
219
|
+
path: filename,
|
|
220
|
+
state: stat.isDirectory() ? "unchanged" : "modified",
|
|
221
|
+
...stat.isDirectory() ? {} : { detail: "A retained template directory was replaced." }
|
|
222
|
+
};
|
|
223
|
+
} catch (error) {
|
|
224
|
+
result = {
|
|
225
|
+
path: filename,
|
|
226
|
+
state: isMissing(error) ? "deleted" : "unavailable",
|
|
227
|
+
detail: errorDetail(error)
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
owner.files.push(result);
|
|
231
|
+
}
|
|
232
|
+
} catch (error) {
|
|
233
|
+
owner.baseline = {
|
|
234
|
+
status: "unavailable",
|
|
235
|
+
detail: errorDetail(error)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
for (const relative of instance.excludedPaths ?? []) {
|
|
239
|
+
const filename = `${instance.target}/${relative}`;
|
|
240
|
+
if (!owner.files.some((file) => file.path === filename)) owner.files.push({
|
|
241
|
+
path: filename,
|
|
242
|
+
state: "excluded",
|
|
243
|
+
detail: "Explicitly excluded from template management."
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
owner.local = localDriftState(owner.files, owner.baseline.status);
|
|
247
|
+
if (owner.version.status === "newer") owner.recommendations.push(`Preview templates upgrade ${instance.id} --source-version ${evidence.version} before applying changes.`);
|
|
248
|
+
if (owner.local === "drifted") owner.recommendations.push("Review local modifications and deletions; preserve business changes or explicitly exclude owned paths during an instance upgrade.");
|
|
249
|
+
if (owner.baseline.status !== "available") owner.recommendations.push("Restore retained metadata, or link the instance to its verified exact historical source. Do not treat current files as a historical baseline.");
|
|
250
|
+
if (owner.local === "unknown" && owner.baseline.status === "available") owner.recommendations.push("Resolve unavailable managed paths and rerun the read-only check.");
|
|
251
|
+
return owner;
|
|
252
|
+
}
|
|
253
|
+
async function collectInstanceDrift(workspaceDir, evidence) {
|
|
254
|
+
let registry = {
|
|
255
|
+
path: templateRegistryPath,
|
|
256
|
+
status: "available",
|
|
257
|
+
detail: "Registered template instances were loaded."
|
|
258
|
+
};
|
|
259
|
+
try {
|
|
260
|
+
try {
|
|
261
|
+
await lstat(await safeInstancePath(workspaceDir, templateRegistryPath));
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (!isMissing(error)) throw error;
|
|
264
|
+
registry = {
|
|
265
|
+
...registry,
|
|
266
|
+
status: "absent",
|
|
267
|
+
detail: "No template instances are registered; unmanaged projects were not inspected."
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const record = await loadTemplateInstanceRegistry(workspaceDir);
|
|
271
|
+
const owners = [];
|
|
272
|
+
for (const instance of record.instances) owners.push(await inspectInstance(workspaceDir, instance, evidence));
|
|
273
|
+
return {
|
|
274
|
+
registry,
|
|
275
|
+
owners
|
|
276
|
+
};
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return {
|
|
279
|
+
registry: {
|
|
280
|
+
...registry,
|
|
281
|
+
status: "unavailable",
|
|
282
|
+
detail: errorDetail(error)
|
|
283
|
+
},
|
|
284
|
+
owners: []
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
//#endregion
|
|
289
|
+
//#region src/commands/upgrade/baseline/record.ts
|
|
290
|
+
const baselineDirectory = ".repoctl/baselines/root";
|
|
291
|
+
const templatePackage = "@icebreakers/monorepo-templates";
|
|
292
|
+
function isRootAsset(filename) {
|
|
293
|
+
return getAssetTargets().some((target) => filename === target || filename.startsWith(`${target}/`));
|
|
294
|
+
}
|
|
295
|
+
const baselinePath = (filename) => `${baselineDirectory}/${hash$1(Buffer.from(filename))}.json`;
|
|
296
|
+
const encodeBaseline = (record) => Buffer.from(`${JSON.stringify(record, null, 2)}\n`);
|
|
297
|
+
function parseBaseline(content, filename) {
|
|
298
|
+
const record = JSON.parse(content.toString());
|
|
299
|
+
if (!record || record.schemaVersion !== 1 || typeof record.path !== "string" || !isRootAsset(relativeFile(record.path)) || filename !== baselinePath(record.path) || !record.source || record.source.package !== "@icebreakers/monorepo-templates" || typeof record.source.version !== "string" || !record.source.version || typeof record.source.assetPath !== "string" || !relativeFile(record.source.assetPath) || toWorkspaceAssetPath(record.source.assetPath) !== record.path || !/^[\da-f]{64}$/.test(record.source.hash) || !record.upstream || typeof record.upstream.content !== "string" || Buffer.from(record.upstream.content, "base64").toString("base64") !== record.upstream.content || hash$1(Buffer.from(record.upstream.content, "base64")) !== record.upstream.hash) throw new Error(`Invalid root asset baseline: ${filename}`);
|
|
300
|
+
return record;
|
|
301
|
+
}
|
|
302
|
+
//#endregion
|
|
303
|
+
//#region src/commands/template-drift/root-assets.ts
|
|
304
|
+
async function collectRootAssetDrift(workspaceDir, evidence) {
|
|
305
|
+
const registry = {
|
|
306
|
+
path: baselineDirectory,
|
|
307
|
+
status: "available",
|
|
308
|
+
detail: "Retained root asset baselines were inspected."
|
|
309
|
+
};
|
|
310
|
+
const owners = [];
|
|
311
|
+
try {
|
|
312
|
+
const directory = await safeInstancePath(workspaceDir, baselineDirectory);
|
|
313
|
+
if (!(await lstat(directory)).isDirectory()) throw new Error("The root asset baseline registry is not a directory.");
|
|
314
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
315
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
316
|
+
if (!entry.name.endsWith(".json")) continue;
|
|
317
|
+
const filename = `${baselineDirectory}/${entry.name}`;
|
|
318
|
+
try {
|
|
319
|
+
const bytes = await readOptional(workspaceDir, filename);
|
|
320
|
+
if (!bytes) throw new Error("The retained baseline disappeared during inspection.");
|
|
321
|
+
const record = parseBaseline(bytes, filename);
|
|
322
|
+
const source = {
|
|
323
|
+
kind: "package",
|
|
324
|
+
packageName: record.source.package,
|
|
325
|
+
version: record.source.version,
|
|
326
|
+
templatePath: record.source.assetPath,
|
|
327
|
+
digest: record.source.hash
|
|
328
|
+
};
|
|
329
|
+
const file = await compareManagedFile(workspaceDir, record.path, record.upstream.hash);
|
|
330
|
+
const owner = {
|
|
331
|
+
kind: "root-asset",
|
|
332
|
+
id: record.path,
|
|
333
|
+
path: record.path,
|
|
334
|
+
source,
|
|
335
|
+
baseline: {
|
|
336
|
+
status: "available",
|
|
337
|
+
detail: "The retained root upstream baseline passed schema, path and content hash validation."
|
|
338
|
+
},
|
|
339
|
+
version: compareTemplateVersion(source, evidence),
|
|
340
|
+
local: localDriftState([file], "available"),
|
|
341
|
+
files: [file],
|
|
342
|
+
recommendations: []
|
|
343
|
+
};
|
|
344
|
+
if (owner.version.status === "newer") owner.recommendations.push("Review the exact template package upgrade and its root asset plan before applying changes.");
|
|
345
|
+
if (owner.local === "drifted") owner.recommendations.push("Review local root asset modifications or deletions; use the retained baseline when planning an upgrade.");
|
|
346
|
+
if (owner.local === "unknown") owner.recommendations.push("Resolve the unavailable managed path and rerun the read-only check.");
|
|
347
|
+
owners.push(owner);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
registry.status = "unavailable";
|
|
350
|
+
registry.detail += ` Untrusted baseline ${filename}: ${errorDetail(error)}`;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (!owners.length && registry.status === "available") {
|
|
354
|
+
registry.status = "absent";
|
|
355
|
+
registry.detail = "No trustworthy root asset baselines are registered; existing root files were not inspected.";
|
|
356
|
+
}
|
|
357
|
+
} catch (error) {
|
|
358
|
+
registry.status = isMissing(error) ? "absent" : "unavailable";
|
|
359
|
+
registry.detail = isMissing(error) ? "No root asset baselines are registered; existing root files were not inspected." : errorDetail(error);
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
registry,
|
|
363
|
+
owners
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/commands/template-drift/collector.ts
|
|
368
|
+
/** This layer never loads config, writes assets, renders templates or executes package scripts. */
|
|
369
|
+
async function collectTemplateDrift(workspaceDir, options = {}) {
|
|
370
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || options.remote !== void 0 && typeof options.remote !== "boolean" || options.sourceDir !== void 0 && (typeof options.sourceDir !== "string" || !options.sourceDir.trim()) || options.remote && options.sourceDir) throw new Error("Template drift options require either an extracted source directory or explicit remote lookup, not both.");
|
|
371
|
+
workspaceDir = path.normalize(await realpath(workspaceDir));
|
|
372
|
+
const evidence = await collectVersionEvidence(options);
|
|
373
|
+
const instances = await collectInstanceDrift(workspaceDir, evidence);
|
|
374
|
+
const roots = await collectRootAssetDrift(workspaceDir, evidence);
|
|
375
|
+
return {
|
|
376
|
+
schemaVersion: 1,
|
|
377
|
+
workspaceDir,
|
|
378
|
+
evidence,
|
|
379
|
+
instanceRegistry: instances.registry,
|
|
380
|
+
rootRegistry: roots.registry,
|
|
381
|
+
owners: [...instances.owners, ...roots.owners]
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
//#endregion
|
|
385
|
+
//#region src/commands/template-drift/checks.ts
|
|
386
|
+
const templateDriftRuleIds = [
|
|
387
|
+
"template-version-evidence",
|
|
388
|
+
"template-instance-registry",
|
|
389
|
+
"template-instance-baseline",
|
|
390
|
+
"template-instance-version",
|
|
391
|
+
"template-instance-drift",
|
|
392
|
+
"root-asset-registry",
|
|
393
|
+
"root-asset-version",
|
|
394
|
+
"root-asset-drift"
|
|
395
|
+
];
|
|
396
|
+
function templateDriftChecks(report) {
|
|
397
|
+
const checks = [{
|
|
398
|
+
id: "template-version-evidence",
|
|
399
|
+
title: "Template package comparison evidence",
|
|
400
|
+
status: report.evidence.status === "available" ? "pass" : "warn",
|
|
401
|
+
detail: report.evidence.detail,
|
|
402
|
+
...report.evidence.status === "unavailable" ? { fix: "Supply an extracted template package or retry an explicitly enabled remote lookup." } : {}
|
|
403
|
+
}];
|
|
404
|
+
for (const [id, registry] of [["template-instance-registry", report.instanceRegistry], ["root-asset-registry", report.rootRegistry]]) checks.push({
|
|
405
|
+
id,
|
|
406
|
+
title: "Managed template baseline registry",
|
|
407
|
+
status: registry.status === "unavailable" ? "warn" : "pass",
|
|
408
|
+
path: registry.path,
|
|
409
|
+
detail: `${registry.status}: ${registry.detail}`,
|
|
410
|
+
...registry.status === "unavailable" ? { fix: "Restore trustworthy metadata before checking managed file drift." } : {}
|
|
411
|
+
});
|
|
412
|
+
for (const owner of report.owners) {
|
|
413
|
+
const prefix = owner.kind === "instance" ? "template-instance" : "root-asset";
|
|
414
|
+
if (owner.kind === "instance") checks.push({
|
|
415
|
+
id: `${prefix}-baseline`,
|
|
416
|
+
title: "Template instance baseline",
|
|
417
|
+
path: owner.path,
|
|
418
|
+
status: owner.baseline.status === "available" ? "pass" : "warn",
|
|
419
|
+
detail: `${owner.baseline.status}: ${owner.baseline.detail}`,
|
|
420
|
+
...owner.baseline.status !== "available" ? { fix: owner.recommendations.join(" ") } : {}
|
|
421
|
+
});
|
|
422
|
+
checks.push({
|
|
423
|
+
id: `${prefix}-version`,
|
|
424
|
+
title: "Retained template package version",
|
|
425
|
+
path: owner.path,
|
|
426
|
+
status: ["newer", "unknown"].includes(owner.version.status) ? "warn" : "pass",
|
|
427
|
+
detail: owner.version.detail,
|
|
428
|
+
...["newer", "unknown"].includes(owner.version.status) ? { fix: owner.recommendations.join(" ") || "Obtain verified source version evidence before claiming the template is current." } : {}
|
|
429
|
+
});
|
|
430
|
+
for (const file of owner.files) {
|
|
431
|
+
const status = [
|
|
432
|
+
"modified",
|
|
433
|
+
"deleted",
|
|
434
|
+
"unavailable"
|
|
435
|
+
].includes(file.state) ? "warn" : "pass";
|
|
436
|
+
checks.push({
|
|
437
|
+
id: `${prefix}-drift`,
|
|
438
|
+
title: "Managed template path",
|
|
439
|
+
path: file.path,
|
|
440
|
+
status,
|
|
441
|
+
detail: `${file.state}${file.detail ? `: ${file.detail}` : ""}`,
|
|
442
|
+
...status === "warn" ? { fix: owner.recommendations.join(" ") } : {}
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return checks;
|
|
447
|
+
}
|
|
448
|
+
async function collectTemplateDriftChecks(context, selected) {
|
|
449
|
+
return templateDriftChecks(await collectTemplateDrift(context.workspaceDir)).filter((check) => selected.has(check.id));
|
|
450
|
+
}
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/commands/deps/admission/baseline.ts
|
|
453
|
+
function canonical$1(value) {
|
|
454
|
+
if (Array.isArray(value)) return value.map(canonical$1);
|
|
455
|
+
const object = record$3(value);
|
|
456
|
+
return object ? Object.fromEntries(Object.keys(object).sort().filter((key) => object[key] !== void 0).map((key) => [key, canonical$1(object[key])])) : value;
|
|
457
|
+
}
|
|
458
|
+
const admissionPolicyHash = (policy) => hash(JSON.stringify(canonical$1(policy)));
|
|
459
|
+
function admissionFindingKey(finding) {
|
|
460
|
+
const declaration = finding.declaration;
|
|
461
|
+
return hash(JSON.stringify([
|
|
462
|
+
finding.id,
|
|
463
|
+
finding.rule,
|
|
464
|
+
...declaration ? [
|
|
465
|
+
declaration.workspace,
|
|
466
|
+
declaration.section,
|
|
467
|
+
declaration.name,
|
|
468
|
+
declaration.target
|
|
469
|
+
] : [finding.detail]
|
|
470
|
+
]));
|
|
471
|
+
}
|
|
472
|
+
/** The baseline is an explicitly reviewed artifact, not a source of policy or execution. */
|
|
473
|
+
function readAdmissionBaseline(value, policyHash) {
|
|
474
|
+
const baseline = record$3(value);
|
|
475
|
+
if (!baseline || baseline["schemaVersion"] !== 1 || baseline["kind"] !== "dependency-admission" || baseline["policyHash"] !== policyHash || !Array.isArray(baseline["findings"])) throw new Error("Dependency policy baseline is invalid or was created with a different policy. Review a new baseline or explicitly use --full.");
|
|
476
|
+
const keys = /* @__PURE__ */ new Set();
|
|
477
|
+
for (const value of baseline["findings"]) {
|
|
478
|
+
const finding = record$3(value);
|
|
479
|
+
if (!finding || typeof finding["id"] !== "string" || !finding["id"].startsWith("admission-") || typeof finding["rule"] !== "string" || typeof finding["detail"] !== "string" || !["warn", "fail"].includes(finding["status"]) || typeof finding["key"] !== "string") throw new Error("Dependency policy baseline contains an invalid finding.");
|
|
480
|
+
if (finding["declaration"] !== void 0) {
|
|
481
|
+
const declaration = record$3(finding["declaration"]);
|
|
482
|
+
if (!declaration || ![
|
|
483
|
+
"workspace",
|
|
484
|
+
"path",
|
|
485
|
+
"section",
|
|
486
|
+
"name"
|
|
487
|
+
].every((key) => typeof declaration[key] === "string") || declaration["target"] !== null && typeof declaration["target"] !== "string") throw new Error("Dependency policy baseline contains an invalid declaration.");
|
|
488
|
+
}
|
|
489
|
+
if (finding["key"] !== admissionFindingKey(finding) || keys.has(finding["key"])) throw new Error("Dependency policy baseline finding keys are inconsistent or duplicated.");
|
|
490
|
+
keys.add(finding["key"]);
|
|
491
|
+
}
|
|
492
|
+
return keys;
|
|
493
|
+
}
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/commands/deps/admission/config.ts
|
|
496
|
+
const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
497
|
+
const text$1 = (value) => typeof value === "string" && value.trim().length > 0;
|
|
498
|
+
const strings = (value) => Array.isArray(value) && value.length > 0 && value.every(text$1);
|
|
499
|
+
function requireValue$1(value, field, message) {
|
|
500
|
+
if (!value) throw new Error(`dependencyPolicy.${field}: ${message}`);
|
|
501
|
+
}
|
|
502
|
+
function fields$1(value, keys, field) {
|
|
503
|
+
requireValue$1(object(value), field, "Expected an object.");
|
|
504
|
+
requireValue$1(Object.keys(value).every((key) => keys.includes(key)), field, "Unknown configuration field.");
|
|
505
|
+
}
|
|
506
|
+
function validWorkspaceSelector(value) {
|
|
507
|
+
if (value === "*" || value === ".") return true;
|
|
508
|
+
const base = value.endsWith("/**") ? value.slice(0, -3) : value;
|
|
509
|
+
return !/[\\:*?[\]{}!]/u.test(base) && !base.startsWith("/") && base.split("/").every((part) => part && part !== "." && part !== "..");
|
|
510
|
+
}
|
|
511
|
+
function dependencyPattern(value) {
|
|
512
|
+
return /^(?:@[^\s/@*]+\/(?:[^\s/@*]+|\*)|[^\s/@*]+)$/u.test(value);
|
|
513
|
+
}
|
|
514
|
+
function validDate(value) {
|
|
515
|
+
return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/u.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
516
|
+
}
|
|
517
|
+
function parseAdmissionConfig(input) {
|
|
518
|
+
fields$1(input, ["rules", "exceptions"], "");
|
|
519
|
+
requireValue$1(Array.isArray(input["rules"]), "rules", "Expected explicit allow/deny rules.");
|
|
520
|
+
const ids = /* @__PURE__ */ new Set();
|
|
521
|
+
for (const [index, rule] of input["rules"].entries()) {
|
|
522
|
+
const field = `rules[${index}]`;
|
|
523
|
+
fields$1(rule, [
|
|
524
|
+
"id",
|
|
525
|
+
"workspaces",
|
|
526
|
+
"dependencies",
|
|
527
|
+
"effect",
|
|
528
|
+
"sections",
|
|
529
|
+
"reason",
|
|
530
|
+
"alternative",
|
|
531
|
+
"severity"
|
|
532
|
+
], field);
|
|
533
|
+
requireValue$1(text$1(rule["id"]) && /^[\w.-]+$/u.test(rule["id"]) && !ids.has(rule["id"]), `${field}.id`, "Expected a unique ASCII rule ID using letters, numbers, dots, underscores or hyphens.");
|
|
534
|
+
ids.add(rule["id"]);
|
|
535
|
+
requireValue$1(strings(rule["workspaces"]) && rule["workspaces"].every(validWorkspaceSelector), `${field}.workspaces`, "Use exact names/paths, directory/** or *.");
|
|
536
|
+
requireValue$1(strings(rule["dependencies"]) && rule["dependencies"].every(dependencyPattern), `${field}.dependencies`, "Use exact dependency names or @scope/*.");
|
|
537
|
+
requireValue$1(["allow", "deny"].includes(rule["effect"]), `${field}.effect`, "Expected allow or deny.");
|
|
538
|
+
requireValue$1(strings(rule["sections"]) && rule["sections"].every((section) => dependencySections.includes(section)), `${field}.sections`, "Explicitly select supported dependency fields.");
|
|
539
|
+
requireValue$1(text$1(rule["reason"]), `${field}.reason`, "A rule requires a reason.");
|
|
540
|
+
requireValue$1(rule["alternative"] === void 0 || text$1(rule["alternative"]), `${field}.alternative`, "Expected a nonempty suggestion.");
|
|
541
|
+
requireValue$1(rule["severity"] === void 0 || ["warn", "fail"].includes(rule["severity"]), `${field}.severity`, "Expected warn or fail.");
|
|
542
|
+
}
|
|
543
|
+
requireValue$1(input["exceptions"] === void 0 || Array.isArray(input["exceptions"]), "exceptions", "Expected an exception array.");
|
|
544
|
+
const exceptions = /* @__PURE__ */ new Set();
|
|
545
|
+
for (const [index, exception] of (input["exceptions"] ?? []).entries()) {
|
|
546
|
+
const field = `exceptions[${index}]`;
|
|
547
|
+
fields$1(exception, [
|
|
548
|
+
"rule",
|
|
549
|
+
"workspace",
|
|
550
|
+
"dependency",
|
|
551
|
+
"section",
|
|
552
|
+
"reason",
|
|
553
|
+
"expiresOn"
|
|
554
|
+
], field);
|
|
555
|
+
requireValue$1(text$1(exception["rule"]) && ids.has(exception["rule"]), `${field}.rule`, "Expected a configured rule ID.");
|
|
556
|
+
requireValue$1(text$1(exception["workspace"]) && !exception["workspace"].includes("*") && validWorkspaceSelector(exception["workspace"]), `${field}.workspace`, "Use an exact workspace-relative directory.");
|
|
557
|
+
requireValue$1(text$1(exception["dependency"]) && dependencyPattern(exception["dependency"]) && !exception["dependency"].includes("*"), `${field}.dependency`, "Use an exact manifest dependency key.");
|
|
558
|
+
requireValue$1(dependencySections.includes(exception["section"]), `${field}.section`, "Expected a dependency field.");
|
|
559
|
+
requireValue$1(text$1(exception["reason"]), `${field}.reason`, "An exception requires a reason.");
|
|
560
|
+
requireValue$1(exception["expiresOn"] === void 0 || validDate(exception["expiresOn"]), `${field}.expiresOn`, "Expected a valid YYYY-MM-DD date.");
|
|
561
|
+
const key = JSON.stringify([
|
|
562
|
+
exception["rule"],
|
|
563
|
+
exception["workspace"],
|
|
564
|
+
exception["dependency"],
|
|
565
|
+
exception["section"]
|
|
566
|
+
]);
|
|
567
|
+
requireValue$1(!exceptions.has(key), field, "Duplicate exception.");
|
|
568
|
+
exceptions.add(key);
|
|
569
|
+
}
|
|
570
|
+
return input;
|
|
571
|
+
}
|
|
572
|
+
function rejectNull$1(value) {
|
|
573
|
+
requireValue$1(value !== null, "", "Null is not a policy value; omit optional fields instead.");
|
|
574
|
+
if (object(value) || Array.isArray(value)) Object.values(value).forEach(rejectNull$1);
|
|
575
|
+
}
|
|
576
|
+
async function loadAdmissionConfig(cwd) {
|
|
577
|
+
const loaded = await loadMonorepoConfigDetails(cwd, { refresh: true });
|
|
578
|
+
for (const layer of loaded.rawLayers) rejectNull$1(layer.dependencyPolicy);
|
|
579
|
+
return {
|
|
580
|
+
configured: loaded.config.dependencyPolicy !== void 0,
|
|
581
|
+
config: parseAdmissionConfig(loaded.config.dependencyPolicy === void 0 ? { rules: [] } : loaded.config.dependencyPolicy)
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region src/commands/deps/admission/scan.ts
|
|
586
|
+
function catalogValue(name, specifier, workspace) {
|
|
587
|
+
if (!specifier.startsWith("catalog:")) return specifier;
|
|
588
|
+
const key = specifier.slice(8) || "default";
|
|
589
|
+
const catalogs = record$3(workspace["catalogs"]);
|
|
590
|
+
if (key === "default" && workspace["catalog"] != null && catalogs?.["default"] != null) return null;
|
|
591
|
+
const value = (key === "default" ? record$3(workspace["catalog"] ?? catalogs?.["default"]) : record$3(catalogs?.[key]))?.[name];
|
|
592
|
+
return typeof value === "string" && !value.startsWith("catalog:") ? value : null;
|
|
593
|
+
}
|
|
594
|
+
function targetName(item, effective) {
|
|
595
|
+
if (!effective.startsWith("npm:")) return item.name;
|
|
596
|
+
return /^npm:((?:@[^/@\s]+\/)?[^/@\s]+)(?:@\S+)?$/u.exec(effective)?.[1] ?? null;
|
|
597
|
+
}
|
|
598
|
+
async function internalReason(item, effective, target, root, nodes) {
|
|
599
|
+
if (effective.startsWith("workspace:")) return "explicit-workspace-protocol";
|
|
600
|
+
if (/^(?:file|link):/u.test(effective)) {
|
|
601
|
+
let directory = path.resolve(root, item.workspace, effective.slice(effective.indexOf(":") + 1));
|
|
602
|
+
try {
|
|
603
|
+
directory = path.normalize(await realpath(directory));
|
|
604
|
+
} catch {}
|
|
605
|
+
if (nodes.some((node) => path.resolve(root, node.id) === directory)) return "local-workspace-directory";
|
|
606
|
+
}
|
|
607
|
+
const parsed = parseSpecifier(item.name, effective);
|
|
608
|
+
if (target && parsed.range && validRange(parsed.range) && nodes.some((node) => node.name === target && node.version && satisfies(node.version, parsed.range))) return "matching-local-candidate";
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
async function scanAdmission(cwd) {
|
|
612
|
+
const scan = await scanDependencies(cwd, { policy: false });
|
|
613
|
+
const graph = await getWorkspaceGraph(scan.workspaceDir, {
|
|
614
|
+
ignoreRootPackage: false,
|
|
615
|
+
ignorePrivatePackage: false
|
|
616
|
+
});
|
|
617
|
+
const workspace = record$3(YAML.parse(scan.contents.get("pnpm-workspace.yaml"))) ?? {};
|
|
618
|
+
const declarations = [];
|
|
619
|
+
const skipped = [];
|
|
620
|
+
for (const item of scan.occurrences) {
|
|
621
|
+
const effective = catalogValue(item.name, item.specifier, workspace);
|
|
622
|
+
const target = effective === null ? null : targetName(item, effective);
|
|
623
|
+
const declaration = {
|
|
624
|
+
workspace: item.workspace,
|
|
625
|
+
path: item.path,
|
|
626
|
+
section: item.section,
|
|
627
|
+
name: item.name,
|
|
628
|
+
target
|
|
629
|
+
};
|
|
630
|
+
const internal = effective === null ? null : await internalReason(item, effective, target, scan.workspaceDir, graph.nodes);
|
|
631
|
+
if (internal === "matching-local-candidate") declarations.push({
|
|
632
|
+
declaration,
|
|
633
|
+
problem: "This semver declaration could resolve locally or from a registry. Use workspace: for internal dependencies before evaluating admission."
|
|
634
|
+
});
|
|
635
|
+
else if (internal) skipped.push({
|
|
636
|
+
...declaration,
|
|
637
|
+
reason: internal
|
|
638
|
+
});
|
|
639
|
+
else declarations.push({
|
|
640
|
+
declaration,
|
|
641
|
+
...!target ? { problem: "Cannot resolve a catalog or npm alias target; review its declaration before evaluating policy." } : {}
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
workspaceDir: scan.workspaceDir,
|
|
646
|
+
declarations,
|
|
647
|
+
skipped,
|
|
648
|
+
nodes: graph.nodes
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
function matchesWorkspace(selector, node) {
|
|
652
|
+
return selector === "*" || selector === node.id || selector === node.name || selector.endsWith("/**") && node.id.startsWith(`${selector.slice(0, -3)}/`);
|
|
653
|
+
}
|
|
654
|
+
function matchesDependency(pattern, name) {
|
|
655
|
+
return pattern.endsWith("/*") ? name.startsWith(pattern.slice(0, -1)) : pattern === name;
|
|
656
|
+
}
|
|
657
|
+
//#endregion
|
|
658
|
+
//#region src/commands/deps/admission/evaluate.ts
|
|
659
|
+
function evaluateAdmission(inputs, nodes, config, report, now) {
|
|
660
|
+
const add = (finding) => {
|
|
661
|
+
const key = admissionFindingKey(finding);
|
|
662
|
+
if (!report.findings.some((item) => item.key === key)) report.findings.push({
|
|
663
|
+
...finding,
|
|
664
|
+
key,
|
|
665
|
+
baseline: "new"
|
|
666
|
+
});
|
|
667
|
+
};
|
|
668
|
+
const today = now.toISOString().slice(0, 10);
|
|
669
|
+
const used = /* @__PURE__ */ new Set();
|
|
670
|
+
const waiverResults = /* @__PURE__ */ new Map();
|
|
671
|
+
function waive(rule, declaration) {
|
|
672
|
+
const index = config.exceptions?.findIndex((item) => item.rule === rule && item.workspace === declaration.workspace && item.section === declaration.section && item.dependency === declaration.name) ?? -1;
|
|
673
|
+
if (index < 0) return false;
|
|
674
|
+
if (waiverResults.has(index)) return waiverResults.get(index);
|
|
675
|
+
used.add(index);
|
|
676
|
+
const exception = config.exceptions[index];
|
|
677
|
+
if (exception.expiresOn && exception.expiresOn < today) {
|
|
678
|
+
add({
|
|
679
|
+
id: "admission-expired-exception",
|
|
680
|
+
status: "warn",
|
|
681
|
+
rule,
|
|
682
|
+
declaration,
|
|
683
|
+
reason: exception.reason,
|
|
684
|
+
detail: `Exception expired after ${exception.expiresOn} UTC and does not waive this violation.`
|
|
685
|
+
});
|
|
686
|
+
waiverResults.set(index, false);
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
waiverResults.set(index, true);
|
|
690
|
+
report.exceptions.push({
|
|
691
|
+
...exception,
|
|
692
|
+
declaration
|
|
693
|
+
});
|
|
694
|
+
if (exception.expiresOn && Date.parse(exception.expiresOn) - Date.parse(today) <= 6048e5) add({
|
|
695
|
+
id: "admission-expiring-exception",
|
|
696
|
+
status: "warn",
|
|
697
|
+
rule,
|
|
698
|
+
declaration,
|
|
699
|
+
reason: exception.reason,
|
|
700
|
+
detail: `Exception is valid through ${exception.expiresOn} UTC and expires within seven days.`
|
|
701
|
+
});
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
const scopes = new Map(config.rules.map((rule) => [rule.id, new Set(nodes.filter((node) => rule.workspaces.some((selector) => matchesWorkspace(selector, node))).map((node) => node.id))]));
|
|
705
|
+
for (const rule of config.rules) for (const selector of rule.workspaces) if (!nodes.some((node) => matchesWorkspace(selector, node))) add({
|
|
706
|
+
id: "admission-selector-unmatched",
|
|
707
|
+
status: "warn",
|
|
708
|
+
rule: rule.id,
|
|
709
|
+
detail: `No workspace matches selector ${selector}.`
|
|
710
|
+
});
|
|
711
|
+
for (const { declaration, problem } of inputs) {
|
|
712
|
+
const rules = config.rules.filter((rule) => scopes.get(rule.id).has(declaration.workspace) && rule.sections.includes(declaration.section));
|
|
713
|
+
if (!rules.length) continue;
|
|
714
|
+
if (problem) {
|
|
715
|
+
add({
|
|
716
|
+
id: "admission-resolution",
|
|
717
|
+
status: "fail",
|
|
718
|
+
rule: "",
|
|
719
|
+
declaration,
|
|
720
|
+
detail: problem
|
|
721
|
+
});
|
|
722
|
+
continue;
|
|
723
|
+
}
|
|
724
|
+
const matchesTarget = (patterns) => patterns.some((pattern) => matchesDependency(pattern, declaration.target));
|
|
725
|
+
const allows = rules.filter((rule) => rule.effect === "allow");
|
|
726
|
+
const permitting = allows.filter((rule) => matchesTarget(rule.dependencies));
|
|
727
|
+
const denying = rules.filter((rule) => rule.effect === "deny" && rule.dependencies.some((pattern) => matchesDependency(pattern, declaration.name) || matchesDependency(pattern, declaration.target)));
|
|
728
|
+
if (permitting.length && denying.length) {
|
|
729
|
+
add({
|
|
730
|
+
id: "admission-conflict",
|
|
731
|
+
status: "fail",
|
|
732
|
+
rule: [...permitting, ...denying].map((rule) => rule.id).sort().join(", "),
|
|
733
|
+
declaration,
|
|
734
|
+
detail: "The same declaration is explicitly allowed and denied. Resolve the conflicting scopes; rule order and exceptions cannot choose a winner."
|
|
735
|
+
});
|
|
736
|
+
continue;
|
|
737
|
+
}
|
|
738
|
+
const missingAllowance = allows.length > 0 && !permitting.length && !allows.some((rule) => waive(rule.id, declaration));
|
|
739
|
+
const violated = [...denying, ...missingAllowance ? allows : []];
|
|
740
|
+
for (const rule of violated) {
|
|
741
|
+
if (waive(rule.id, declaration)) continue;
|
|
742
|
+
add({
|
|
743
|
+
id: rule.effect === "deny" ? "admission-denied" : "admission-not-allowed",
|
|
744
|
+
status: rule.severity ?? "fail",
|
|
745
|
+
rule: rule.id,
|
|
746
|
+
declaration,
|
|
747
|
+
detail: rule.effect === "deny" ? "A deny rule matches the declaration or its npm alias target." : "The actual dependency target is outside the workspace allowlist.",
|
|
748
|
+
reason: rule.reason,
|
|
749
|
+
...rule.alternative ? { alternative: rule.alternative } : {}
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
config.exceptions?.forEach((exception, index) => {
|
|
754
|
+
if (!used.has(index)) add({
|
|
755
|
+
id: "admission-unused-exception",
|
|
756
|
+
status: "warn",
|
|
757
|
+
rule: exception.rule,
|
|
758
|
+
detail: `Unused exception for ${exception.workspace} ${exception.section}.${exception.dependency}; ${exception.reason}`
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
//#endregion
|
|
763
|
+
//#region src/commands/deps/admission/index.ts
|
|
764
|
+
/** Offline inspection of third-party direct declarations; never changes manifests or lockfiles. */
|
|
765
|
+
async function checkDependencyAdmission(cwd, options = {}) {
|
|
766
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
767
|
+
if (!(now instanceof Date) || !Number.isFinite(now.getTime())) throw new TypeError("Dependency policy checks require a valid evaluation date.");
|
|
768
|
+
const scan = await scanAdmission(cwd).catch(() => {
|
|
769
|
+
throw new Error("Cannot read workspace manifests or catalogs for dependency admission. Validate pnpm-workspace.yaml and package.json files before retrying.");
|
|
770
|
+
});
|
|
771
|
+
const config = options.config === void 0 ? (await loadAdmissionConfig(scan.workspaceDir)).config : parseAdmissionConfig(options.config);
|
|
772
|
+
const policyHash = admissionPolicyHash(config);
|
|
773
|
+
const added = !options.full && options.baseline !== void 0;
|
|
774
|
+
const baseline = added ? readAdmissionBaseline(options.baseline, policyHash) : /* @__PURE__ */ new Set();
|
|
775
|
+
const report = {
|
|
776
|
+
schemaVersion: 1,
|
|
777
|
+
kind: "dependency-admission",
|
|
778
|
+
workspaceDir: scan.workspaceDir,
|
|
779
|
+
policyHash,
|
|
780
|
+
mode: added ? "added" : "full",
|
|
781
|
+
declarations: scan.declarations.map((item) => item.declaration),
|
|
782
|
+
skipped: scan.skipped,
|
|
783
|
+
findings: [],
|
|
784
|
+
exceptions: [],
|
|
785
|
+
summary: {
|
|
786
|
+
fail: 0,
|
|
787
|
+
warn: 0,
|
|
788
|
+
existing: 0,
|
|
789
|
+
waived: 0
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
evaluateAdmission(scan.declarations, scan.nodes, config, report, now);
|
|
793
|
+
for (const finding of report.findings) if (baseline.has(finding.key)) {
|
|
794
|
+
finding.baseline = "existing";
|
|
795
|
+
report.summary.existing++;
|
|
796
|
+
} else report.summary[finding.status]++;
|
|
797
|
+
report.summary.waived = report.exceptions.length;
|
|
798
|
+
return report;
|
|
799
|
+
}
|
|
800
|
+
//#endregion
|
|
801
|
+
//#region src/commands/doctor/admission.ts
|
|
802
|
+
async function collectAdmissionChecks(workspaceDir, selected) {
|
|
803
|
+
const title = "Third-party dependency admission";
|
|
804
|
+
try {
|
|
805
|
+
const { config, configured } = await loadAdmissionConfig(workspaceDir);
|
|
806
|
+
if (!configured) return [];
|
|
807
|
+
const report = await checkDependencyAdmission(workspaceDir, { config });
|
|
808
|
+
const checks = report.findings.map((item) => ({
|
|
809
|
+
id: item.id,
|
|
810
|
+
title,
|
|
811
|
+
status: item.status,
|
|
812
|
+
...item.declaration ? {
|
|
813
|
+
path: item.declaration.path,
|
|
814
|
+
field: `${item.declaration.section}.${item.declaration.name}`
|
|
815
|
+
} : {},
|
|
816
|
+
detail: `${item.rule}: ${item.declaration ? `${item.declaration.path} ${item.declaration.section}.${item.declaration.name}: ` : ""}${item.detail}${item.reason ? ` ${item.reason}` : ""}${item.alternative ? ` Alternative: ${item.alternative}` : ""}`
|
|
817
|
+
}));
|
|
818
|
+
if (report.exceptions.length) checks.push({
|
|
819
|
+
id: "admission-exceptions",
|
|
820
|
+
status: "pass",
|
|
821
|
+
title,
|
|
822
|
+
detail: report.exceptions.map((item) => `${item.rule}: ${item.workspace} ${item.section}.${item.dependency}: ${item.reason}`).join("\n")
|
|
823
|
+
});
|
|
824
|
+
if (!checks.length || selected?.has("admission-policy") && checks.some((check) => !selected.has(check.id))) checks.push({
|
|
825
|
+
id: "admission-policy",
|
|
826
|
+
title,
|
|
827
|
+
status: report.summary.fail ? "fail" : report.summary.warn ? "warn" : "pass",
|
|
828
|
+
detail: report.findings.length ? report.findings.map((item) => `${item.rule}: ${item.detail}`).join("\n") : "No violations in the configured third-party direct dependency policy."
|
|
829
|
+
});
|
|
830
|
+
return selected ? checks.filter((check) => selected.has(check.id) || check.id === "admission-config") : checks;
|
|
831
|
+
} catch {
|
|
832
|
+
return [{
|
|
833
|
+
id: "admission-config",
|
|
834
|
+
status: "fail",
|
|
835
|
+
title,
|
|
836
|
+
detail: "Cannot inspect dependency admission. Run deps policy to review configuration or manifest diagnostics."
|
|
837
|
+
}];
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
//#endregion
|
|
841
|
+
//#region src/core/workspace-boundaries/config.ts
|
|
842
|
+
const dependencyTypes = [
|
|
843
|
+
"dependencies",
|
|
844
|
+
"devDependencies",
|
|
845
|
+
"peerDependencies",
|
|
846
|
+
"optionalDependencies"
|
|
847
|
+
];
|
|
848
|
+
const record$1 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
849
|
+
const text = (value) => typeof value === "string" && value.trim().length > 0;
|
|
850
|
+
var BoundaryConfigError = class extends Error {
|
|
851
|
+
field;
|
|
852
|
+
constructor(field, detail) {
|
|
853
|
+
super(detail);
|
|
854
|
+
this.field = field;
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
function requireValue(value, field, message) {
|
|
858
|
+
if (!value) throw new BoundaryConfigError(field, message);
|
|
859
|
+
}
|
|
860
|
+
function fields(value, allowed, field) {
|
|
861
|
+
requireValue(record$1(value), field, "Expected a configuration object.");
|
|
862
|
+
for (const key of Object.keys(value)) requireValue(allowed.includes(key), `${field}.${key}`, "Unknown configuration field.");
|
|
863
|
+
}
|
|
864
|
+
function validPath(value) {
|
|
865
|
+
return value === "." || !/[\\:*?[\]{}!]/u.test(value) && !value.startsWith("/") && value.split("/").every((part) => part && part !== "." && part !== "..");
|
|
866
|
+
}
|
|
867
|
+
function selector(value, field, tags, allowTags = true) {
|
|
868
|
+
fields(value, allowTags ? [
|
|
869
|
+
"packages",
|
|
870
|
+
"paths",
|
|
871
|
+
"tags",
|
|
872
|
+
"private"
|
|
873
|
+
] : [
|
|
874
|
+
"packages",
|
|
875
|
+
"paths",
|
|
876
|
+
"private"
|
|
877
|
+
], field);
|
|
878
|
+
requireValue(Object.values(value).some((item) => item !== void 0), field, "An empty selector is ambiguous; select paths, packages, tags or private explicitly.");
|
|
879
|
+
for (const key of [
|
|
880
|
+
"packages",
|
|
881
|
+
"paths",
|
|
882
|
+
"tags"
|
|
883
|
+
]) {
|
|
884
|
+
if (value[key] === void 0) continue;
|
|
885
|
+
const values = value[key];
|
|
886
|
+
requireValue(Array.isArray(values) && values.length && values.every(text), `${field}.${key}`, "Expected a nonempty string array.");
|
|
887
|
+
for (const item of values) {
|
|
888
|
+
if (key === "paths") requireValue(validPath(item.endsWith("/**") ? item.slice(0, -3) : item), `${field}.paths`, "Use an exact relative directory, or directory/**; other glob syntax is unsupported.");
|
|
889
|
+
if (key === "tags") requireValue(tags.includes(item), `${field}.tags`, `Unknown tag: ${item}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
requireValue(value["private"] === void 0 || typeof value["private"] === "boolean", `${field}.private`, "Expected a boolean.");
|
|
893
|
+
}
|
|
894
|
+
function policy(value, field) {
|
|
895
|
+
requireValue(value["severity"] === void 0 || ["warn", "fail"].includes(value["severity"]), `${field}.severity`, "Severity must be warn or fail.");
|
|
896
|
+
requireValue(value["dependencyTypes"] === void 0 || Array.isArray(value["dependencyTypes"]) && value["dependencyTypes"].length && value["dependencyTypes"].every((type) => dependencyTypes.includes(type)), `${field}.dependencyTypes`, "Select at least one supported manifest dependency field.");
|
|
897
|
+
}
|
|
898
|
+
/** Runtime validation is shared by CLI, doctor and API. No rules silently disappear. */
|
|
899
|
+
function parseBoundariesConfig(value) {
|
|
900
|
+
fields(value, [
|
|
901
|
+
"tags",
|
|
902
|
+
"rules",
|
|
903
|
+
"cycles",
|
|
904
|
+
"exceptions"
|
|
905
|
+
], "boundaries");
|
|
906
|
+
requireValue(value["tags"] === void 0 || record$1(value["tags"]), "boundaries.tags", "Expected a tag-to-selector object.");
|
|
907
|
+
const tags = Object.keys(value["tags"] ?? {});
|
|
908
|
+
for (const [name, definition] of Object.entries(value["tags"] ?? {})) {
|
|
909
|
+
requireValue(text(name), "boundaries.tags", "Tag names must be nonempty.");
|
|
910
|
+
selector(definition, `boundaries.tags.${name}`, [], false);
|
|
911
|
+
}
|
|
912
|
+
requireValue(value["rules"] === void 0 || Array.isArray(value["rules"]), "boundaries.rules", "Expected an array of rules.");
|
|
913
|
+
const ids = /* @__PURE__ */ new Set(["cycle"]);
|
|
914
|
+
for (const [index, rule] of (value["rules"] ?? []).entries()) {
|
|
915
|
+
const field = `boundaries.rules[${index}]`;
|
|
916
|
+
fields(rule, [
|
|
917
|
+
"id",
|
|
918
|
+
"from",
|
|
919
|
+
"allow",
|
|
920
|
+
"severity",
|
|
921
|
+
"dependencyTypes"
|
|
922
|
+
], field);
|
|
923
|
+
requireValue(text(rule["id"]) && !ids.has(rule["id"]), `${field}.id`, "Rule IDs must be nonempty and unique; cycle is reserved.");
|
|
924
|
+
ids.add(rule["id"]);
|
|
925
|
+
selector(rule["from"], `${field}.from`, tags);
|
|
926
|
+
requireValue(Array.isArray(rule["allow"]), `${field}.allow`, "Expected selector alternatives; [] explicitly denies all internal edges.");
|
|
927
|
+
rule["allow"].forEach((item, i) => selector(item, `${field}.allow[${i}]`, tags));
|
|
928
|
+
policy(rule, field);
|
|
929
|
+
}
|
|
930
|
+
if (value["cycles"] !== void 0 && value["cycles"] !== false) {
|
|
931
|
+
fields(value["cycles"], ["severity", "dependencyTypes"], "boundaries.cycles");
|
|
932
|
+
policy(value["cycles"], "boundaries.cycles");
|
|
933
|
+
}
|
|
934
|
+
requireValue(value["exceptions"] === void 0 || Array.isArray(value["exceptions"]), "boundaries.exceptions", "Expected an exception array.");
|
|
935
|
+
const exceptions = /* @__PURE__ */ new Set();
|
|
936
|
+
for (const [index, exception] of (value["exceptions"] ?? []).entries()) {
|
|
937
|
+
const field = `boundaries.exceptions[${index}]`;
|
|
938
|
+
fields(exception, [
|
|
939
|
+
"rule",
|
|
940
|
+
"source",
|
|
941
|
+
"target",
|
|
942
|
+
"type",
|
|
943
|
+
"reason"
|
|
944
|
+
], field);
|
|
945
|
+
requireValue(text(exception["rule"]) && ids.has(exception["rule"]), `${field}.rule`, "Exception must reference a configured rule or cycle.");
|
|
946
|
+
for (const key of ["source", "target"]) requireValue(text(exception[key]) && validPath(exception[key]), `${field}.${key}`, "Expected an exact workspace-relative directory.");
|
|
947
|
+
requireValue(dependencyTypes.includes(exception["type"]), `${field}.type`, "Expected a supported manifest dependency field.");
|
|
948
|
+
requireValue(text(exception["reason"]), `${field}.reason`, "Every exception requires a reason.");
|
|
949
|
+
const key = JSON.stringify([
|
|
950
|
+
exception["rule"],
|
|
951
|
+
exception["source"],
|
|
952
|
+
exception["target"],
|
|
953
|
+
exception["type"]
|
|
954
|
+
]);
|
|
955
|
+
requireValue(!exceptions.has(key), field, "Duplicate exception.");
|
|
956
|
+
exceptions.add(key);
|
|
957
|
+
}
|
|
958
|
+
return value;
|
|
959
|
+
}
|
|
960
|
+
//#endregion
|
|
961
|
+
//#region src/core/workspace-boundaries/cycles.ts
|
|
962
|
+
/** Iterative Kosaraju traversal avoids recursive stack overflow and cycle enumeration. */
|
|
963
|
+
function findWorkspaceCycles(ids, edges) {
|
|
964
|
+
const forward = new Map(ids.map((id) => [id, []]));
|
|
965
|
+
const reverse = new Map(ids.map((id) => [id, []]));
|
|
966
|
+
for (const edge of edges) {
|
|
967
|
+
forward.get(edge.source).push(edge);
|
|
968
|
+
reverse.get(edge.target).push(edge.source);
|
|
969
|
+
}
|
|
970
|
+
const seen = /* @__PURE__ */ new Set();
|
|
971
|
+
const order = [];
|
|
972
|
+
for (const id of ids) {
|
|
973
|
+
if (seen.has(id)) continue;
|
|
974
|
+
seen.add(id);
|
|
975
|
+
const stack = [{
|
|
976
|
+
id,
|
|
977
|
+
index: 0
|
|
978
|
+
}];
|
|
979
|
+
while (stack.length) {
|
|
980
|
+
const frame = stack.at(-1);
|
|
981
|
+
const edge = forward.get(frame.id)[frame.index++];
|
|
982
|
+
if (!edge) {
|
|
983
|
+
order.push(frame.id);
|
|
984
|
+
stack.pop();
|
|
985
|
+
} else if (!seen.has(edge.target)) {
|
|
986
|
+
seen.add(edge.target);
|
|
987
|
+
stack.push({
|
|
988
|
+
id: edge.target,
|
|
989
|
+
index: 0
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
995
|
+
const cycles = [];
|
|
996
|
+
for (const id of order.reverse()) {
|
|
997
|
+
if (assigned.has(id)) continue;
|
|
998
|
+
const members = [];
|
|
999
|
+
const stack = [id];
|
|
1000
|
+
assigned.add(id);
|
|
1001
|
+
while (stack.length) {
|
|
1002
|
+
const member = stack.pop();
|
|
1003
|
+
members.push(member);
|
|
1004
|
+
for (const source of reverse.get(member)) if (!assigned.has(source)) {
|
|
1005
|
+
assigned.add(source);
|
|
1006
|
+
stack.push(source);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
members.sort();
|
|
1010
|
+
const start = members[0];
|
|
1011
|
+
if (members.length === 1 && !forward.get(start).some((edge) => edge.target === start)) continue;
|
|
1012
|
+
const allowed = new Set(members);
|
|
1013
|
+
const queue = [start];
|
|
1014
|
+
const parent = /* @__PURE__ */ new Map();
|
|
1015
|
+
const visited = /* @__PURE__ */ new Set([start]);
|
|
1016
|
+
let closing;
|
|
1017
|
+
for (let i = 0; i < queue.length && !closing; i++) for (const edge of forward.get(queue[i])) {
|
|
1018
|
+
if (!allowed.has(edge.target)) continue;
|
|
1019
|
+
if (edge.target === start) {
|
|
1020
|
+
closing = edge;
|
|
1021
|
+
break;
|
|
1022
|
+
}
|
|
1023
|
+
if (!visited.has(edge.target)) {
|
|
1024
|
+
visited.add(edge.target);
|
|
1025
|
+
parent.set(edge.target, edge);
|
|
1026
|
+
queue.push(edge.target);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
const path = [closing];
|
|
1030
|
+
let node = closing.source;
|
|
1031
|
+
while (node !== start) {
|
|
1032
|
+
const edge = parent.get(node);
|
|
1033
|
+
path.push(edge);
|
|
1034
|
+
node = edge.source;
|
|
1035
|
+
}
|
|
1036
|
+
path.reverse();
|
|
1037
|
+
cycles.push({
|
|
1038
|
+
members,
|
|
1039
|
+
edges: path,
|
|
1040
|
+
chain: [start, ...path.map((edge) => edge.target)]
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
return cycles.sort((a, b) => a.members[0] < b.members[0] ? -1 : 1);
|
|
1044
|
+
}
|
|
1045
|
+
//#endregion
|
|
1046
|
+
//#region src/core/workspace-boundaries/selectors.ts
|
|
1047
|
+
function matches(node, selector, tags) {
|
|
1048
|
+
return (selector.private === void 0 || node.private === selector.private) && (!selector.packages || selector.packages.includes(node.name ?? "")) && (!selector.paths || selector.paths.some((pattern) => pattern.endsWith("/**") ? pattern === "./**" || node.id.startsWith(`${pattern.slice(0, -3)}/`) : node.id === pattern)) && (!selector.tags || selector.tags.some((tag) => tags.get(tag)?.has(node.id)));
|
|
1049
|
+
}
|
|
1050
|
+
function selectBoundaryNodes(nodes, selector, tags, field, findings) {
|
|
1051
|
+
for (const key of [
|
|
1052
|
+
"packages",
|
|
1053
|
+
"paths",
|
|
1054
|
+
"tags"
|
|
1055
|
+
]) for (const value of selector[key] ?? []) if (!nodes.some((node) => matches(node, { [key]: [value] }, tags))) findings.push({
|
|
1056
|
+
id: "boundary-selector-unmatched",
|
|
1057
|
+
status: "warn",
|
|
1058
|
+
field: `${field}.${key}`,
|
|
1059
|
+
detail: `No workspace matches ${key} selector ${value}.`
|
|
1060
|
+
});
|
|
1061
|
+
const selected = new Set(nodes.filter((node) => matches(node, selector, tags)).map((node) => node.id));
|
|
1062
|
+
if (!selected.size) findings.push({
|
|
1063
|
+
id: "boundary-selector-unmatched",
|
|
1064
|
+
status: "warn",
|
|
1065
|
+
field,
|
|
1066
|
+
detail: "The combined selector matches no workspace."
|
|
1067
|
+
});
|
|
1068
|
+
return selected;
|
|
1069
|
+
}
|
|
1070
|
+
//#endregion
|
|
1071
|
+
//#region src/core/workspace-boundaries/evaluate.ts
|
|
1072
|
+
function evaluateBoundaries(graph, config, report) {
|
|
1073
|
+
const findings = report.findings;
|
|
1074
|
+
const tags = /* @__PURE__ */ new Map();
|
|
1075
|
+
for (const [tag, selector] of Object.entries(config.tags ?? {}).sort(([a], [b]) => a < b ? -1 : 1)) tags.set(tag, selectBoundaryNodes(graph.nodes, selector, tags, `boundaries.tags.${tag}`, findings));
|
|
1076
|
+
const used = /* @__PURE__ */ new Set();
|
|
1077
|
+
const requiredDiagnostics = new Set(graph.diagnostics.filter((item) => !item.type));
|
|
1078
|
+
if (config.cycles !== false) {
|
|
1079
|
+
const types = config.cycles?.dependencyTypes ?? ["dependencies", "optionalDependencies"];
|
|
1080
|
+
graph.diagnostics.filter((item) => item.type && types.includes(item.type)).forEach((item) => requiredDiagnostics.add(item));
|
|
1081
|
+
}
|
|
1082
|
+
function exempt(rule, edge) {
|
|
1083
|
+
const index = config.exceptions?.findIndex((item) => item.rule === rule && item.source === edge.source && item.target === edge.target && item.type === edge.type) ?? -1;
|
|
1084
|
+
if (index < 0) return false;
|
|
1085
|
+
used.add(index);
|
|
1086
|
+
let entry = report.exceptions.find((item) => item.rule === rule && item.source === edge.source && item.target === edge.target && item.type === edge.type);
|
|
1087
|
+
if (!entry) {
|
|
1088
|
+
entry = {
|
|
1089
|
+
...config.exceptions[index],
|
|
1090
|
+
edges: []
|
|
1091
|
+
};
|
|
1092
|
+
report.exceptions.push(entry);
|
|
1093
|
+
}
|
|
1094
|
+
entry.edges.push(edge);
|
|
1095
|
+
return true;
|
|
1096
|
+
}
|
|
1097
|
+
for (const [index, rule] of (config.rules ?? []).entries()) {
|
|
1098
|
+
const field = `boundaries.rules[${index}]`;
|
|
1099
|
+
const from = selectBoundaryNodes(graph.nodes, rule.from, tags, `${field}.from`, findings);
|
|
1100
|
+
graph.diagnostics.filter((item) => item.source && from.has(item.source) && item.type && (rule.dependencyTypes ?? dependencyTypes).includes(item.type)).forEach((item) => requiredDiagnostics.add(item));
|
|
1101
|
+
const allowed = new Set(rule.allow.flatMap((selector, i) => [...selectBoundaryNodes(graph.nodes, selector, tags, `${field}.allow[${i}]`, findings)]));
|
|
1102
|
+
for (const edge of graph.edges) {
|
|
1103
|
+
if (!from.has(edge.source) || allowed.has(edge.target) || !(rule.dependencyTypes ?? dependencyTypes).includes(edge.type) || exempt(rule.id, edge)) continue;
|
|
1104
|
+
findings.push({
|
|
1105
|
+
id: "boundary-rule",
|
|
1106
|
+
status: rule.severity ?? "fail",
|
|
1107
|
+
rule: rule.id,
|
|
1108
|
+
path: edge.source,
|
|
1109
|
+
field: `${edge.type}.${edge.dependency}`,
|
|
1110
|
+
detail: `Rule ${rule.id} disallows ${edge.source} -> ${edge.target} (${edge.type}.${edge.dependency}).`,
|
|
1111
|
+
chain: [edge.source, edge.target],
|
|
1112
|
+
edges: [edge]
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
if (config.cycles !== false) {
|
|
1117
|
+
const policy = config.cycles ?? {};
|
|
1118
|
+
const types = policy.dependencyTypes ?? ["dependencies", "optionalDependencies"];
|
|
1119
|
+
const edges = graph.edges.filter((edge) => types.includes(edge.type));
|
|
1120
|
+
const cyclic = /* @__PURE__ */ new Map();
|
|
1121
|
+
for (const [index, cycle] of findWorkspaceCycles(graph.nodes.map((node) => node.id), edges).entries()) for (const member of cycle.members) cyclic.set(member, index);
|
|
1122
|
+
const retained = edges.filter((edge) => cyclic.get(edge.source) === void 0 || cyclic.get(edge.source) !== cyclic.get(edge.target) || !exempt("cycle", edge));
|
|
1123
|
+
for (const cycle of findWorkspaceCycles(graph.nodes.map((node) => node.id), retained)) {
|
|
1124
|
+
const edge = cycle.edges[0];
|
|
1125
|
+
findings.push({
|
|
1126
|
+
id: "boundary-cycle",
|
|
1127
|
+
status: policy.severity ?? "fail",
|
|
1128
|
+
rule: "cycle",
|
|
1129
|
+
path: edge.source,
|
|
1130
|
+
field: `${edge.type}.${edge.dependency}`,
|
|
1131
|
+
detail: `Internal dependency cycle: ${cycle.chain.join(" -> ")}.`,
|
|
1132
|
+
...cycle
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
config.exceptions?.forEach((exception, index) => {
|
|
1137
|
+
if (!used.has(index)) findings.push({
|
|
1138
|
+
id: "boundary-exception-unused",
|
|
1139
|
+
status: "warn",
|
|
1140
|
+
rule: exception.rule,
|
|
1141
|
+
path: exception.source,
|
|
1142
|
+
field: `boundaries.exceptions[${index}]`,
|
|
1143
|
+
detail: "This exception matches no active violation; remove it or review its endpoints and dependency field."
|
|
1144
|
+
});
|
|
1145
|
+
});
|
|
1146
|
+
for (const diagnostic of requiredDiagnostics) findings.push({
|
|
1147
|
+
id: "boundary-graph",
|
|
1148
|
+
status: "fail",
|
|
1149
|
+
...diagnostic.source ? { path: diagnostic.source } : {},
|
|
1150
|
+
field: diagnostic.type ? `${diagnostic.type}.${diagnostic.dependency}` : "name",
|
|
1151
|
+
detail: `Dependency graph is incomplete for an enabled policy: ${diagnostic.code} (${diagnostic.dependency}).`
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
//#endregion
|
|
1155
|
+
//#region src/core/workspace-boundaries/project.ts
|
|
1156
|
+
/** C12 defaults intentionally discard null; a malformed policy must not disappear. */
|
|
1157
|
+
function rejectNull(value, field) {
|
|
1158
|
+
if (value === null) throw new BoundaryConfigError(field, "Null is not a valid boundary policy value; omit optional fields instead.");
|
|
1159
|
+
if (typeof value === "object" && value) for (const [key, child] of Object.entries(value)) rejectNull(child, `${field}.${key}`);
|
|
1160
|
+
}
|
|
1161
|
+
async function loadBoundaryConfiguration(cwd) {
|
|
1162
|
+
const loaded = await loadMonorepoConfigDetails(cwd, { refresh: true });
|
|
1163
|
+
for (const layer of loaded.rawLayers) rejectNull(layer.boundaries, "boundaries");
|
|
1164
|
+
return {
|
|
1165
|
+
file: loaded.file,
|
|
1166
|
+
configured: loaded.config.boundaries !== void 0,
|
|
1167
|
+
config: parseBoundariesConfig(loaded.config.boundaries === void 0 ? {} : loaded.config.boundaries)
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
//#endregion
|
|
1171
|
+
//#region src/core/workspace-boundaries/index.ts
|
|
1172
|
+
/** Manifest graph inspection only: never executes tasks, rewrites dependencies or scans imports. */
|
|
1173
|
+
async function checkWorkspaceBoundaries(cwd, options = {}) {
|
|
1174
|
+
const graph = await getWorkspaceGraph(cwd, {
|
|
1175
|
+
ignoreRootPackage: false,
|
|
1176
|
+
ignorePrivatePackage: false
|
|
1177
|
+
});
|
|
1178
|
+
const report = {
|
|
1179
|
+
schemaVersion: 1,
|
|
1180
|
+
workspaceDir: graph.workspaceDir,
|
|
1181
|
+
configFile: null,
|
|
1182
|
+
packageCount: graph.nodes.length,
|
|
1183
|
+
findings: [],
|
|
1184
|
+
exceptions: [],
|
|
1185
|
+
summary: {
|
|
1186
|
+
warn: 0,
|
|
1187
|
+
fail: 0,
|
|
1188
|
+
waived: 0
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
try {
|
|
1192
|
+
const loaded = options.config === void 0 ? await loadBoundaryConfiguration(graph.workspaceDir) : null;
|
|
1193
|
+
report.configFile = loaded?.file ?? null;
|
|
1194
|
+
const configured = options.config !== void 0 ? options.config : loaded?.config;
|
|
1195
|
+
evaluateBoundaries(graph, parseBoundariesConfig(configured === void 0 ? {} : configured), report);
|
|
1196
|
+
} catch (error) {
|
|
1197
|
+
const diagnostic = error instanceof ConfigValidationError ? error.diagnostics[0] : void 0;
|
|
1198
|
+
report.findings.push({
|
|
1199
|
+
id: "boundary-config",
|
|
1200
|
+
status: "fail",
|
|
1201
|
+
field: diagnostic?.path ?? (error instanceof BoundaryConfigError ? error.field : "boundaries"),
|
|
1202
|
+
detail: error instanceof ConfigValidationError || error instanceof BoundaryConfigError ? error.message : "Unable to load boundary configuration. Review repoctl.config and its imports."
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
for (const finding of report.findings) report.summary[finding.status]++;
|
|
1206
|
+
report.summary.waived = report.exceptions.reduce((sum, exception) => sum + exception.edges.length, 0);
|
|
1207
|
+
return report;
|
|
1208
|
+
}
|
|
1209
|
+
//#endregion
|
|
1210
|
+
//#region src/commands/doctor/boundaries.ts
|
|
1211
|
+
/** Architecture policy is opt-in for existing doctor callers. */
|
|
1212
|
+
async function collectBoundaryChecks(workspaceDir, selected) {
|
|
1213
|
+
const title = localize("Workspace architecture boundaries", "工作区架构边界");
|
|
1214
|
+
try {
|
|
1215
|
+
const { config, configured } = await loadBoundaryConfiguration(workspaceDir);
|
|
1216
|
+
if (!configured) return [];
|
|
1217
|
+
const report = await checkWorkspaceBoundaries(workspaceDir, { config });
|
|
1218
|
+
const checks = report.findings.map((finding) => ({
|
|
1219
|
+
id: finding.id,
|
|
1220
|
+
title,
|
|
1221
|
+
status: finding.status,
|
|
1222
|
+
detail: `${finding.field ? `${finding.field}: ` : ""}${finding.detail}`,
|
|
1223
|
+
...finding.path ? { path: finding.path } : {},
|
|
1224
|
+
...finding.field ? { field: finding.field } : {}
|
|
1225
|
+
}));
|
|
1226
|
+
if (report.exceptions.length) checks.push({
|
|
1227
|
+
id: "boundary-exceptions",
|
|
1228
|
+
title,
|
|
1229
|
+
status: "pass",
|
|
1230
|
+
detail: report.exceptions.map((item) => `${item.rule}: ${item.source} -> ${item.target} (${item.type}): ${item.reason}`).join("\n")
|
|
1231
|
+
});
|
|
1232
|
+
if (!checks.length || selected?.has("boundary-policy") && checks.some((check) => !selected.has(check.id))) checks.push({
|
|
1233
|
+
id: "boundary-policy",
|
|
1234
|
+
title,
|
|
1235
|
+
status: report.summary.fail ? "fail" : report.summary.warn ? "warn" : "pass",
|
|
1236
|
+
detail: report.findings.length ? report.findings.map((finding) => finding.detail).join("\n") : "No violations in the configured internal manifest dependency policy."
|
|
1237
|
+
});
|
|
1238
|
+
return selected ? checks.filter((check) => selected.has(check.id) || check.id === "boundary-config" || check.id === "boundary-graph") : checks;
|
|
1239
|
+
} catch {
|
|
1240
|
+
return [{
|
|
1241
|
+
id: "boundary-config",
|
|
1242
|
+
title,
|
|
1243
|
+
status: "fail",
|
|
1244
|
+
detail: "Unable to inspect workspace boundaries; check configuration and workspace manifests."
|
|
1245
|
+
}];
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
//#endregion
|
|
1249
|
+
//#region src/core/lockfile/index.ts
|
|
1250
|
+
const lockfileRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1251
|
+
/** pnpm 12 prepends a separate package-manager/config dependency document. */
|
|
1252
|
+
function parseWorkspaceLockfile(source) {
|
|
1253
|
+
try {
|
|
1254
|
+
const documents = YAML.parseAllDocuments(source);
|
|
1255
|
+
if (documents.some((document) => document.errors.length)) return;
|
|
1256
|
+
const candidates = documents.map((document) => lockfileRecord(document.toJSON())).filter((document) => {
|
|
1257
|
+
const root = lockfileRecord(lockfileRecord(document?.["importers"])?.["."]);
|
|
1258
|
+
return root && !("packageManagerDependencies" in root || "configDependencies" in root);
|
|
1259
|
+
});
|
|
1260
|
+
return candidates.length === 1 && String(candidates[0]?.["lockfileVersion"]) === "9.0" ? candidates[0] : void 0;
|
|
1261
|
+
} catch {
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
//#endregion
|
|
1266
|
+
//#region src/commands/doctor/installation/lockfile.ts
|
|
1267
|
+
const dependencyGroups = [
|
|
1268
|
+
"dependencies",
|
|
1269
|
+
"devDependencies",
|
|
1270
|
+
"optionalDependencies"
|
|
1271
|
+
];
|
|
1272
|
+
function record(value) {
|
|
1273
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1274
|
+
}
|
|
1275
|
+
async function readYaml(path) {
|
|
1276
|
+
try {
|
|
1277
|
+
const docs = YAML.parseAllDocuments(await fs$2.readFile(path, "utf8"));
|
|
1278
|
+
if (docs.some((doc) => doc.errors.length)) return;
|
|
1279
|
+
return docs.map((doc) => record(doc.toJSON())).filter((doc) => !!doc);
|
|
1280
|
+
} catch {
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
async function readLockfile(path) {
|
|
1285
|
+
try {
|
|
1286
|
+
return parseWorkspaceLockfile(await fs$2.readFile(path, "utf8"));
|
|
1287
|
+
} catch {
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
function catalogSpecifier(specifier, name, workspace) {
|
|
1292
|
+
if (!specifier.startsWith("catalog:")) return specifier;
|
|
1293
|
+
const catalog = specifier.slice(8);
|
|
1294
|
+
const named = record(workspace["catalogs"]);
|
|
1295
|
+
const isDefault = !catalog || catalog === "default";
|
|
1296
|
+
const duplicateDefault = workspace["catalog"] != null && named?.["default"] != null;
|
|
1297
|
+
return (isDefault ? duplicateDefault ? void 0 : record(workspace["catalog"] ?? named?.["default"]) : record(named?.[catalog]))?.[name];
|
|
1298
|
+
}
|
|
1299
|
+
function effectiveManifest(manifest, workspace, lockfile) {
|
|
1300
|
+
if ((workspace["autoInstallPeers"] ?? record(lockfile["settings"])?.["autoInstallPeers"] ?? true) !== true) return manifest;
|
|
1301
|
+
if (manifest["dependencies"] !== void 0 && !record(manifest["dependencies"])) return manifest;
|
|
1302
|
+
const explicit = new Set(dependencyGroups.flatMap((group) => Object.keys(record(manifest[group]) ?? {})));
|
|
1303
|
+
const peers = Object.fromEntries(Object.entries(record(manifest["peerDependencies"]) ?? {}).filter(([name]) => !explicit.has(name)));
|
|
1304
|
+
return {
|
|
1305
|
+
...manifest,
|
|
1306
|
+
dependencies: {
|
|
1307
|
+
...peers,
|
|
1308
|
+
...record(manifest["dependencies"])
|
|
1309
|
+
}
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
function compareManifest(originalManifest, importer, workspace, lockfile) {
|
|
1313
|
+
const manifest = effectiveManifest(originalManifest, workspace, lockfile);
|
|
1314
|
+
const mismatches = [];
|
|
1315
|
+
const unknown = [];
|
|
1316
|
+
for (const group of dependencyGroups) {
|
|
1317
|
+
if (manifest[group] !== void 0 && !record(manifest[group]) || importer[group] !== void 0 && !record(importer[group])) {
|
|
1318
|
+
unknown.push(`${group} (unsupported dependency map)`);
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
const expected = record(manifest[group]) ?? {};
|
|
1322
|
+
const locked = record(importer[group]) ?? {};
|
|
1323
|
+
for (const [name, specifier] of Object.entries(expected)) {
|
|
1324
|
+
if (group !== "optionalDependencies" && name in (record(manifest["optionalDependencies"]) ?? {})) continue;
|
|
1325
|
+
if (group === "devDependencies" && name in (record(manifest["dependencies"]) ?? {})) continue;
|
|
1326
|
+
const entry = record(locked[name]);
|
|
1327
|
+
const desired = typeof specifier === "string" ? catalogSpecifier(specifier, name, workspace) : void 0;
|
|
1328
|
+
if (typeof desired !== "string" || name in locked && !entry || entry && (typeof entry["specifier"] !== "string" || typeof entry["version"] !== "string")) {
|
|
1329
|
+
unknown.push(`${group}.${name}`);
|
|
1330
|
+
continue;
|
|
1331
|
+
}
|
|
1332
|
+
let actual = entry?.["specifier"];
|
|
1333
|
+
if (typeof specifier === "string" && specifier.startsWith("catalog:") && actual === specifier) {
|
|
1334
|
+
const catalog = specifier.slice(8) || "default";
|
|
1335
|
+
actual = record(record(record(lockfile["catalogs"])?.[catalog])?.[name])?.["specifier"];
|
|
1336
|
+
if (typeof actual !== "string") {
|
|
1337
|
+
unknown.push(`${group}.${name}`);
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
if (actual !== desired) {
|
|
1342
|
+
const overrides = record(workspace["overrides"]) ?? record(record(manifest["pnpm"])?.["overrides"]) ?? {};
|
|
1343
|
+
if (Object.keys(overrides).some((key) => key === name || key.includes(`${name}@`) || key.endsWith(`>${name}`))) unknown.push(`${group}.${name} (override)`);
|
|
1344
|
+
else mismatches.push(`${group}.${name}`);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
for (const name of Object.keys(locked)) if (!(name in expected)) mismatches.push(`${group}.${name} (removed)`);
|
|
1348
|
+
}
|
|
1349
|
+
return {
|
|
1350
|
+
mismatches,
|
|
1351
|
+
unknown
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
//#endregion
|
|
1355
|
+
//#region src/utils/pnpm-runtime.ts
|
|
1356
|
+
/** Read version evidence without executing package-manager shims or activating Corepack. */
|
|
1357
|
+
async function inspectPnpmRuntime() {
|
|
1358
|
+
const userAgent = process.env["npm_config_user_agent"]?.match(/^pnpm\/([^ ]+)/)?.[1];
|
|
1359
|
+
if (userAgent && valid(userAgent) && /pnpm/i.test(process.env["npm_execpath"] ?? "")) return {
|
|
1360
|
+
state: "observed",
|
|
1361
|
+
version: userAgent,
|
|
1362
|
+
source: "npm_config_user_agent (inherited launch evidence)"
|
|
1363
|
+
};
|
|
1364
|
+
const names = process.platform === "win32" ? [
|
|
1365
|
+
"pnpm.exe",
|
|
1366
|
+
"pnpm.cmd",
|
|
1367
|
+
"pnpm.bat",
|
|
1368
|
+
"pnpm"
|
|
1369
|
+
] : ["pnpm"];
|
|
1370
|
+
for (const entry of (process.env["PATH"] ?? "").split(process.platform === "win32" ? ";" : ":")) for (const name of names) {
|
|
1371
|
+
const candidate = path.resolve(entry || ".", name);
|
|
1372
|
+
try {
|
|
1373
|
+
await access(candidate, process.platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
1374
|
+
} catch {
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
try {
|
|
1378
|
+
let dir = path.dirname(await realpath(candidate));
|
|
1379
|
+
for (let depth = 0; depth < 3; depth++) {
|
|
1380
|
+
try {
|
|
1381
|
+
const pkg = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
|
|
1382
|
+
if (pkg.name === "pnpm" && pkg.version && valid(pkg.version)) return {
|
|
1383
|
+
state: "observed",
|
|
1384
|
+
version: pkg.version,
|
|
1385
|
+
source: `PATH package metadata: ${candidate}`
|
|
1386
|
+
};
|
|
1387
|
+
if (pkg.name === "corepack") return {
|
|
1388
|
+
state: "unknown",
|
|
1389
|
+
source: `Corepack shim: ${candidate}`
|
|
1390
|
+
};
|
|
1391
|
+
} catch {}
|
|
1392
|
+
dir = path.dirname(dir);
|
|
1393
|
+
}
|
|
1394
|
+
} catch {}
|
|
1395
|
+
return {
|
|
1396
|
+
state: "unknown",
|
|
1397
|
+
source: `Unrecognized pnpm launcher: ${candidate}`
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
return {
|
|
1401
|
+
state: "missing",
|
|
1402
|
+
source: "PATH"
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
//#endregion
|
|
1406
|
+
//#region src/commands/doctor/runtime/pnpm.ts
|
|
1407
|
+
function declaredPnpmVersion(value) {
|
|
1408
|
+
if (typeof value !== "string" || !value.startsWith("pnpm@")) return;
|
|
1409
|
+
const version = value.slice(5).split("+sha")[0];
|
|
1410
|
+
return valid(version) ?? void 0;
|
|
1411
|
+
}
|
|
1412
|
+
async function collectPnpmChecks({ packageJson }, selected) {
|
|
1413
|
+
const declared = declaredPnpmVersion(packageJson.packageManager);
|
|
1414
|
+
const checks = [];
|
|
1415
|
+
if (!selected || selected.has("package-manager")) checks.push({
|
|
1416
|
+
id: "package-manager",
|
|
1417
|
+
title: localize("Declared package manager", "声明的包管理器"),
|
|
1418
|
+
status: declared ? "pass" : packageJson.packageManager ? "fail" : "warn",
|
|
1419
|
+
detail: declared ? localize(`packageManager pins pnpm@${declared}.`, `packageManager 固定为 pnpm@${declared}。`) : localize("packageManager must declare an exact pnpm version to verify consistency.", "packageManager 需要声明明确的 pnpm 版本才能验证一致性。"),
|
|
1420
|
+
...!declared ? { fix: localize("Set packageManager to pnpm@<version> in the root package.json.", "在根 package.json 中设置 packageManager 为 pnpm@<版本>。") } : {}
|
|
1421
|
+
});
|
|
1422
|
+
if (!selected || selected.has("pnpm-version")) {
|
|
1423
|
+
const runtime = await inspectPnpmRuntime();
|
|
1424
|
+
const status = runtime.state === "missing" ? "fail" : runtime.state === "unknown" || !declared ? "warn" : eq(runtime.version, declared) ? "pass" : "fail";
|
|
1425
|
+
checks.push({
|
|
1426
|
+
id: "pnpm-version",
|
|
1427
|
+
title: localize("Observed pnpm version", "观测到的 pnpm 版本"),
|
|
1428
|
+
status,
|
|
1429
|
+
detail: runtime.state === "observed" ? localize(`Observed pnpm ${runtime.version}; declared ${declared ?? "unknown"}. Source: ${runtime.source}.`, `观测到 pnpm ${runtime.version};声明版本 ${declared ?? "未知"}。来源:${runtime.source}。`) : runtime.state === "missing" ? localize("pnpm is missing from PATH and no pnpm launch evidence is available.", "PATH 中没有 pnpm,也没有 pnpm 启动证据。") : localize(`pnpm version is unknown; no launcher was executed. ${runtime.source}.`, `pnpm 版本未知,未执行启动器。${runtime.source}。`),
|
|
1430
|
+
...status !== "pass" ? { fix: localize("Install/select the declared pnpm version explicitly, then run pnpm exec repo doctor. Doctor never activates or downloads pnpm.", "手动安装或选择声明的 pnpm 版本,然后执行 pnpm exec repo doctor。Doctor 不会激活或下载 pnpm。") } : {}
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
return checks;
|
|
1434
|
+
}
|
|
1435
|
+
//#endregion
|
|
1436
|
+
//#region src/commands/doctor/installation/state.ts
|
|
1437
|
+
async function checkInstallation(context, wanted, lockCheck, manifests) {
|
|
1438
|
+
const { workspaceDir, packageJson } = context;
|
|
1439
|
+
const modulesDir = path.join(workspaceDir, "node_modules");
|
|
1440
|
+
const result = (status, en, zh) => ({
|
|
1441
|
+
id: "installation-state",
|
|
1442
|
+
title: localize("Recorded installation state", "安装记录状态"),
|
|
1443
|
+
status,
|
|
1444
|
+
detail: localize(en, zh),
|
|
1445
|
+
...status !== "pass" ? { fix: status === "warn" ? localize("Review the evidence limit and validate with the declared pnpm version. Explicitly run pnpm install if the installation is missing or stale; unsupported layouts remain unknown.", "检查证据限制并使用声明的 pnpm 版本手动验证。缺少安装或安装过期时手动运行 pnpm install;不支持的布局仍会显示未知。") : localize("Review the lockfile diagnostics, then explicitly run pnpm install with the declared pnpm version. This check never installs dependencies.", "检查锁文件诊断后,手动使用声明的 pnpm 版本执行 pnpm install。本检查不会安装依赖。") } : {}
|
|
1446
|
+
});
|
|
1447
|
+
if (!await fs$2.pathExists(modulesDir)) return result("warn", "No root node_modules: no installation evidence was found.", "根目录没有 node_modules,未发现安装证据。");
|
|
1448
|
+
const metadata = (await readYaml(path.join(modulesDir, ".modules.yaml")))?.[0];
|
|
1449
|
+
const installedBy = declaredPnpmVersion(metadata?.["packageManager"]);
|
|
1450
|
+
if (!metadata || metadata["layoutVersion"] !== 5 || !installedBy || typeof metadata["virtualStoreDir"] !== "string") return result("warn", "Installation state is unknown: node_modules has missing or unsupported pnpm metadata.", "安装状态未知:node_modules 缺少 pnpm 元数据或其格式不受支持。");
|
|
1451
|
+
if (metadata["nodeLinker"] && metadata["nodeLinker"] !== "isolated") return result("warn", "Installation state is unknown: only the isolated pnpm node linker is supported.", "安装状态未知:当前仅支持 pnpm isolated node linker。");
|
|
1452
|
+
const declared = declaredPnpmVersion(packageJson["packageManager"]);
|
|
1453
|
+
if (declared && !eq(installedBy, declared)) return result("fail", `Dependencies were installed by pnpm ${installedBy}, but packageManager declares ${declared}.`, `依赖由 pnpm ${installedBy} 安装,但 packageManager 声明 ${declared}。`);
|
|
1454
|
+
const included = record(metadata["included"]);
|
|
1455
|
+
if (dependencyGroups.some((group) => included?.[group] !== true)) return result("warn", "Installation is partial or unknown: not all dependency groups were included.", "安装不完整或状态未知:未包含所有依赖类型。");
|
|
1456
|
+
const current = await readLockfile(path.resolve(modulesDir, metadata["virtualStoreDir"], "lock.yaml"));
|
|
1457
|
+
if (!wanted || !current) return result("warn", "Installation state is unknown: a supported workspace and installed lockfile are both required.", "安装状态未知:需要可识别的 workspace 锁文件和安装锁文件。");
|
|
1458
|
+
for (const field of [
|
|
1459
|
+
"importers",
|
|
1460
|
+
"packages",
|
|
1461
|
+
"snapshots",
|
|
1462
|
+
"settings",
|
|
1463
|
+
"overrides",
|
|
1464
|
+
"catalogs",
|
|
1465
|
+
"patchedDependencies"
|
|
1466
|
+
]) if (!isDeepStrictEqual(wanted[field], current[field])) return result("fail", `Installed lockfile differs from pnpm-lock.yaml (${field}); the recorded installation is stale.`, `安装锁文件与 pnpm-lock.yaml 不同(${field}),安装记录已过期。`);
|
|
1467
|
+
if (lockCheck.status !== "pass") return result(lockCheck.status, "Installation cannot be confirmed until manifest/lockfile consistency is resolved.", "需要先确认清单与锁文件一致,才能确认安装记录。");
|
|
1468
|
+
for (const { dir, manifest } of manifests) for (const group of ["dependencies", "devDependencies"]) for (const name of Object.keys(record(manifest[group]) ?? {})) {
|
|
1469
|
+
if (name in (record(manifest["optionalDependencies"]) ?? {})) continue;
|
|
1470
|
+
if (!await fs$2.pathExists(path.join(workspaceDir, dir, "node_modules", name, "package.json"))) return result("fail", `Installed direct dependency is missing: ${dir}: ${name}.`, `已安装的直接依赖缺失:${dir}:${name}。`);
|
|
1471
|
+
}
|
|
1472
|
+
return result("pass", "Manifest specifiers, lockfiles and recorded pnpm installation agree; required direct dependency manifests exist. Package integrity and build scripts were not checked.", "依赖声明、锁文件与 pnpm 安装记录一致,必需的直接依赖清单存在。未检查包内容完整性或构建脚本。");
|
|
1473
|
+
}
|
|
1474
|
+
//#endregion
|
|
1475
|
+
//#region src/commands/doctor/installation/index.ts
|
|
1476
|
+
async function collectInstallationChecks(context, selected) {
|
|
1477
|
+
const { workspaceDir, packageJson } = context;
|
|
1478
|
+
const manifests = context.manifests.filter((entry) => entry.data).map((entry) => ({
|
|
1479
|
+
dir: path.relative(workspaceDir, entry.directory) || ".",
|
|
1480
|
+
manifest: entry.data
|
|
1481
|
+
}));
|
|
1482
|
+
const lockfilePath = path.join(workspaceDir, "pnpm-lock.yaml");
|
|
1483
|
+
const lockfile = await readLockfile(lockfilePath);
|
|
1484
|
+
const workspace = (await readYaml(path.join(workspaceDir, "pnpm-workspace.yaml")))?.[0] ?? {};
|
|
1485
|
+
const mismatches = [];
|
|
1486
|
+
const unknown = context.manifests.filter((entry) => entry.error).map((entry) => `${entry.path} (invalid manifest)`);
|
|
1487
|
+
for (const entry of context.manifests) for (const section of [
|
|
1488
|
+
"dependencies",
|
|
1489
|
+
"devDependencies",
|
|
1490
|
+
"optionalDependencies",
|
|
1491
|
+
"peerDependencies"
|
|
1492
|
+
]) if (entry.data?.[section] !== void 0 && !record(entry.data[section])) unknown.push(`${entry.path}: ${section} (invalid structure)`);
|
|
1493
|
+
if (context.workspaceManifestError || !context.manifests.some((entry) => entry.directory === workspaceDir && entry.data)) unknown.push("workspace or root package manifest is unreadable");
|
|
1494
|
+
if (lockfile) {
|
|
1495
|
+
const overrides = record(workspace["overrides"]) ?? record(record(packageJson)?.["pnpm"])?.["overrides"] ?? {};
|
|
1496
|
+
if (!isDeepStrictEqual(overrides, lockfile["overrides"] ?? {})) unknown.push("workspace overrides differ from lockfile overrides");
|
|
1497
|
+
for (const { dir, manifest } of manifests) {
|
|
1498
|
+
const importer = record(record(lockfile["importers"])?.[dir]);
|
|
1499
|
+
if (!importer) {
|
|
1500
|
+
mismatches.push(`${dir} (missing importer)`);
|
|
1501
|
+
continue;
|
|
1502
|
+
}
|
|
1503
|
+
const compared = compareManifest(manifest, importer, workspace, lockfile);
|
|
1504
|
+
mismatches.push(...compared.mismatches.map((name) => `${dir}: ${name}`));
|
|
1505
|
+
unknown.push(...compared.unknown.map((name) => `${dir}: ${name}`));
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
if (await fs$2.pathExists(path.join(workspaceDir, ".pnpmfile.cjs")) || await fs$2.pathExists(path.join(workspaceDir, ".pnpmfile.mjs")) || !!workspace["pnpmfile"] || !!workspace["configDependencies"]) unknown.push("pnpmfile/config dependency transformations", ...mismatches.splice(0));
|
|
1509
|
+
const status = mismatches.length ? "fail" : !lockfile || unknown.length ? "warn" : "pass";
|
|
1510
|
+
const lockCheck = {
|
|
1511
|
+
id: "lockfile-sync",
|
|
1512
|
+
title: localize("Manifest and lockfile consistency", "清单与锁文件一致性"),
|
|
1513
|
+
status,
|
|
1514
|
+
detail: !lockfile ? await fs$2.pathExists(lockfilePath) ? localize("Lockfile state is unknown: malformed or unsupported format (supported: pnpm lockfile v9).", "锁文件状态未知:格式损坏或不受支持(支持 pnpm v9 锁文件)。") : localize("pnpm-lock.yaml is missing; dependency resolution has not been recorded.", "缺少 pnpm-lock.yaml,尚无依赖解析记录。") : mismatches.length ? localize(`Manifest/lockfile mismatch: ${mismatches.join("; ")}.`, `清单与锁文件不匹配:${mismatches.join(";")}。`) : unknown.length ? localize(`Cannot prove consistency for transformed or unsupported specifiers: ${unknown.join("; ")}.`, `无法确认经过转换或不受支持的依赖声明:${unknown.join(";")}。`) : localize(`Dependency specifiers match the lockfile for ${manifests.length} workspace manifest(s).`, `${manifests.length} 个 workspace 清单的依赖声明与锁文件一致。`),
|
|
1515
|
+
...status !== "pass" ? { fix: status === "warn" ? localize("Review the evidence limit and validate with the declared pnpm version. Regenerate the lockfile only when dependency state needs updating; unsupported transformations remain unknown.", "检查证据限制并使用声明的 pnpm 版本手动验证。仅在依赖状态需要更新时重新生成锁文件;不支持的转换仍会显示未知。") : localize("Review manifest changes and pnpm configuration, then explicitly run pnpm install with the declared version to regenerate the lockfile.", "检查清单变更和 pnpm 配置,然后手动使用声明版本运行 pnpm install 更新锁文件。") } : {}
|
|
1516
|
+
};
|
|
1517
|
+
const checks = !selected || selected.has("lockfile-sync") ? [lockCheck] : [];
|
|
1518
|
+
if (!selected || selected.has("installation-state")) checks.push(await checkInstallation(context, lockfile, lockCheck, manifests));
|
|
1519
|
+
return checks;
|
|
1520
|
+
}
|
|
1521
|
+
//#endregion
|
|
1522
|
+
//#region src/commands/doctor/manifest/finding.ts
|
|
1523
|
+
function finding(entry, id, field, status, english, chinese) {
|
|
1524
|
+
return {
|
|
1525
|
+
id: `manifest-${id}`,
|
|
1526
|
+
path: entry.path,
|
|
1527
|
+
field,
|
|
1528
|
+
title: `${entry.path} — ${field}`,
|
|
1529
|
+
status,
|
|
1530
|
+
detail: localize(english, chinese)
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
//#endregion
|
|
1534
|
+
//#region src/commands/doctor/manifest/dependencies.ts
|
|
1535
|
+
function canonical(directory) {
|
|
1536
|
+
try {
|
|
1537
|
+
return realpathSync(directory);
|
|
1538
|
+
} catch {
|
|
1539
|
+
return path$1.resolve(directory);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function dependencyChecks(entry, manifests, selected) {
|
|
1543
|
+
const includes = (id) => !selected || selected.has(`manifest-${id}`);
|
|
1544
|
+
const resolveTargets = [
|
|
1545
|
+
"self-dependency",
|
|
1546
|
+
"workspace-specifier",
|
|
1547
|
+
"workspace-target",
|
|
1548
|
+
"workspace-ambiguous",
|
|
1549
|
+
"workspace-unreadable",
|
|
1550
|
+
"workspace-version-unknown",
|
|
1551
|
+
"workspace-version-mismatch"
|
|
1552
|
+
].some(includes);
|
|
1553
|
+
const data = entry.data;
|
|
1554
|
+
const checks = [];
|
|
1555
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
1556
|
+
for (const section of workspaceDependencyTypes) {
|
|
1557
|
+
if (data[section] === void 0) continue;
|
|
1558
|
+
const dependencies = record$2(data[section]);
|
|
1559
|
+
if (!dependencies) {
|
|
1560
|
+
if (includes("dependency-section")) checks.push(finding(entry, "dependency-section", section, "fail", "Dependency sections must be objects mapping names to specifiers.", "依赖分区必须是包名到版本声明的对象。"));
|
|
1561
|
+
continue;
|
|
1562
|
+
}
|
|
1563
|
+
for (const [name, specifier] of Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b))) {
|
|
1564
|
+
const field = `${section}.${name}`;
|
|
1565
|
+
if (typeof specifier !== "string" || !specifier.trim()) {
|
|
1566
|
+
if (includes("dependency-specifier")) checks.push(finding(entry, "dependency-specifier", field, "fail", "A dependency specifier must be a nonempty string.", "依赖声明必须为非空字符串。"));
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1569
|
+
const existing = declarations.get(name) ?? [];
|
|
1570
|
+
existing.push({
|
|
1571
|
+
section,
|
|
1572
|
+
specifier
|
|
1573
|
+
});
|
|
1574
|
+
declarations.set(name, existing);
|
|
1575
|
+
if (!resolveTargets) continue;
|
|
1576
|
+
const reference = parseDependencyReference(name, specifier, entry.directory);
|
|
1577
|
+
const targets = reference?.directory ? manifests.filter((target) => target.directory === canonical(reference.directory)) : reference?.name ? manifests.filter((target) => target.data?.["name"] === reference.name) : [];
|
|
1578
|
+
if (includes("self-dependency") && (typeof reference?.name === "string" && reference.name === data["name"] || targets.some((target) => target.directory === entry.directory))) checks.push(finding(entry, "self-dependency", field, "fail", "A package must not depend on itself, including through an alias.", "包不能依赖自身,包括通过别名引用自身。"));
|
|
1579
|
+
if (!specifier.startsWith("workspace:")) continue;
|
|
1580
|
+
if (!reference?.range) {
|
|
1581
|
+
if (includes("workspace-specifier")) checks.push(finding(entry, "workspace-specifier", field, "fail", "The workspace protocol has an invalid range or target.", "workspace 协议的范围或目标无效。"));
|
|
1582
|
+
} else if (!targets.length) {
|
|
1583
|
+
if (includes("workspace-target")) checks.push(finding(entry, "workspace-target", field, "fail", "The required workspace target was not discovered. Check its name, path and workspace patterns.", "未发现必需的 workspace 目标,请检查包名、路径及 workspace 匹配规则。"));
|
|
1584
|
+
} else if (targets.length > 1) {
|
|
1585
|
+
if (includes("workspace-ambiguous")) checks.push(finding(entry, "workspace-ambiguous", field, "fail", "Multiple workspace packages match this dependency.", "此依赖匹配多个 workspace 包。"));
|
|
1586
|
+
} else if (!targets[0].data) {
|
|
1587
|
+
if (includes("workspace-unreadable")) checks.push(finding(entry, "workspace-unreadable", field, "warn", "The workspace target exists but its manifest cannot be read.", "workspace 目标存在,但无法读取其清单。"));
|
|
1588
|
+
} else if (reference.range !== "*") {
|
|
1589
|
+
const version = targets[0].data["version"];
|
|
1590
|
+
if (typeof version !== "string" || !valid(version)) {
|
|
1591
|
+
if (includes("workspace-version-unknown")) checks.push(finding(entry, "workspace-version-unknown", field, "warn", "The target has no valid version to compare with this explicit workspace range.", "目标没有有效版本,无法核对显式 workspace 范围。"));
|
|
1592
|
+
} else if (!satisfies(version, reference.range)) {
|
|
1593
|
+
if (includes("workspace-version-mismatch")) checks.push(finding(entry, "workspace-version-mismatch", field, "fail", "The workspace target version does not satisfy this explicit dependency range.", "workspace 目标版本不满足此显式依赖范围。"));
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
if (!includes("dependency-conflict") && !includes("dependency-duplicate")) return checks;
|
|
1599
|
+
for (const [name, items] of declarations) {
|
|
1600
|
+
const concrete = items.filter((item) => item.section !== "peerDependencies");
|
|
1601
|
+
if (concrete.length < 2) continue;
|
|
1602
|
+
const optionalOverride = concrete.length === 2 && concrete.some((item) => item.section === "dependencies") && concrete.some((item) => item.section === "optionalDependencies");
|
|
1603
|
+
const parsed = concrete.map((item) => parseSpecifier(name, item.specifier));
|
|
1604
|
+
const known = parsed.every((item) => item.source && item.range);
|
|
1605
|
+
const conflict = !optionalOverride && known && (new Set(parsed.map((item) => item.source)).size > 1 || rangesOverlap(parsed.map((item) => item.range)) === false);
|
|
1606
|
+
if (!includes(conflict ? "dependency-conflict" : "dependency-duplicate")) continue;
|
|
1607
|
+
checks.push(finding(entry, conflict ? "dependency-conflict" : "dependency-duplicate", `${concrete.map((item) => item.section).join(",")}.${name}`, conflict ? "fail" : "warn", optionalOverride ? "optionalDependencies overrides dependencies for this name. Review whether both declarations are intentional." : conflict ? "The dependency has conflicting declarations across dependency sections." : "The dependency is repeated across concrete dependency sections.", optionalOverride ? "optionalDependencies 会覆盖 dependencies 中同名声明,请确认两处声明均有必要。" : conflict ? "此依赖在多个依赖分区中声明了冲突版本。" : "此依赖在多个具体依赖分区中重复声明。"));
|
|
1608
|
+
}
|
|
1609
|
+
return checks;
|
|
1610
|
+
}
|
|
1611
|
+
//#endregion
|
|
1612
|
+
//#region src/commands/doctor/manifest/metadata.ts
|
|
1613
|
+
function metadataChecks(entry, workspaceDir, selected) {
|
|
1614
|
+
const includes = (id) => !selected || selected.has(`manifest-${id}`);
|
|
1615
|
+
const data = entry.data;
|
|
1616
|
+
const checks = [];
|
|
1617
|
+
const add = (id, field, status, en, zh) => {
|
|
1618
|
+
if (includes(id)) checks.push(finding(entry, id, field, status, en, zh));
|
|
1619
|
+
};
|
|
1620
|
+
if ([
|
|
1621
|
+
"name-missing",
|
|
1622
|
+
"name-invalid",
|
|
1623
|
+
"name-legacy"
|
|
1624
|
+
].some(includes)) {
|
|
1625
|
+
if (typeof data["name"] !== "string" || !data["name"]) add("name-missing", "name", "fail", "Declare a nonempty package name.", "请声明非空包名。");
|
|
1626
|
+
else {
|
|
1627
|
+
const name = validatePackageName(data["name"]);
|
|
1628
|
+
if (!name.validForOldPackages) add("name-invalid", "name", "fail", "The package name is not a valid npm package name.", "包名不符合 npm 包名规则。");
|
|
1629
|
+
else if (!name.validForNewPackages && data["private"] !== true) add("name-legacy", "name", "warn", "This legacy package name is not accepted for new npm packages.", "此旧包名不满足新 npm 包的命名要求。");
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
if (includes("private-invalid") && data["private"] !== void 0 && typeof data["private"] !== "boolean") add("private-invalid", "private", "fail", "private must be a boolean; only true prevents publication.", "private 必须为布尔值;只有 true 会阻止发布。");
|
|
1633
|
+
if (includes("version-invalid") && data["version"] !== void 0 && (typeof data["version"] !== "string" || !valid(data["version"]))) add("version-invalid", "version", "fail", "version must be a valid semver version.", "version 必须为有效 semver 版本。");
|
|
1634
|
+
if (data["private"] === true) return checks;
|
|
1635
|
+
if (includes("version-missing") && data["version"] === void 0) add("version-missing", "version", "warn", "A publishable package needs a version; use private: true for an unpublished application.", "可发布包需要 version;不发布的应用应声明 private: true。");
|
|
1636
|
+
if (includes("license") && (typeof data["license"] !== "string" || !data["license"].trim())) add("license", "license", "warn", "Declare the package license or an explicit unlicensed policy before publishing.", "发布前请声明包的 license 或明确的不授权策略。");
|
|
1637
|
+
const repository = record$2(data["repository"]);
|
|
1638
|
+
if (includes("repository")) {
|
|
1639
|
+
if (!data["repository"]) add("repository", "repository", "warn", "Repository metadata is recommended for a publishable package.", "建议为可发布包声明 repository 元信息。");
|
|
1640
|
+
else if (typeof data["repository"] !== "string" && (!repository || typeof repository["url"] !== "string")) add("repository", "repository", "warn", "repository must be a URL string or an object with a URL.", "repository 应为 URL 字符串或包含 URL 的对象。");
|
|
1641
|
+
}
|
|
1642
|
+
const directory = repository?.["directory"];
|
|
1643
|
+
if (includes("repository-directory") && directory !== void 0 && (typeof directory !== "string" || path$1.isAbsolute(directory) || directory.includes("\\") || path$1.resolve(workspaceDir, directory) !== entry.directory)) add("repository-directory", "repository.directory", "warn", "repository.directory should identify this package relative to the repository root; review external repository layouts manually.", "repository.directory 应指向相对仓库根目录的当前包;外部仓库布局请人工核查。");
|
|
1644
|
+
const publish = record$2(data["publishConfig"]);
|
|
1645
|
+
if (includes("publish-config") && data["publishConfig"] !== void 0 && !publish) add("publish-config", "publishConfig", "warn", "publishConfig must be an object.", "publishConfig 应为对象。");
|
|
1646
|
+
if (includes("publish-access") && publish?.["access"] !== void 0 && !["public", "restricted"].includes(publish["access"])) add("publish-access", "publishConfig.access", "warn", "publishConfig.access must be public or restricted.", "publishConfig.access 应为 public 或 restricted。");
|
|
1647
|
+
if (includes("publish-registry") && publish?.["registry"] !== void 0) try {
|
|
1648
|
+
const url = typeof publish["registry"] === "string" ? new URL(publish["registry"]) : null;
|
|
1649
|
+
if (!url || !["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("invalid registry");
|
|
1650
|
+
} catch {
|
|
1651
|
+
add("publish-registry", "publishConfig.registry", "warn", "Use an HTTP(S) registry URL without embedded credentials.", "请使用不含内嵌凭据的 HTTP(S) registry URL。");
|
|
1652
|
+
}
|
|
1653
|
+
return checks;
|
|
1654
|
+
}
|
|
1655
|
+
//#endregion
|
|
1656
|
+
//#region src/commands/doctor/manifest/index.ts
|
|
1657
|
+
function collectManifestChecks(context, selected) {
|
|
1658
|
+
const active = selected?.has("manifest-health") ? void 0 : selected;
|
|
1659
|
+
const includes = (id) => !active || active.has(id);
|
|
1660
|
+
const checks = [];
|
|
1661
|
+
for (const entry of context.manifests) {
|
|
1662
|
+
if (entry.error && includes(entry.error === "multiple_manifests" ? "manifest-multiple" : "manifest-parse")) checks.push(finding(entry, entry.error === "multiple_manifests" ? "multiple" : "parse", "$", "fail", entry.error === "multiple_manifests" ? "Multiple package manifests exist in this directory; keep one authoritative manifest." : "The package manifest is unreadable or is not a valid object. Other packages are still checked.", entry.error === "multiple_manifests" ? "此目录存在多个包清单,请保留一个权威清单。" : "包清单无法读取或不是有效对象;仍会继续检查其他包。"));
|
|
1663
|
+
if (!entry.data) continue;
|
|
1664
|
+
checks.push(...metadataChecks(entry, context.workspaceDir, active), ...dependencyChecks(entry, context.manifests, active));
|
|
1665
|
+
const name = entry.data["name"];
|
|
1666
|
+
if (includes("manifest-name-duplicate") && typeof name === "string" && context.manifests.filter((item) => item.data?.["name"] === name).length > 1) checks.push(finding(entry, "name-duplicate", "name", "fail", "This name is used by another workspace package, including the root.", "此名称与另一个 workspace 包(包含根包)重复。"));
|
|
1667
|
+
}
|
|
1668
|
+
if (includes("manifest-workspace-parse") && context.workspaceManifestError) checks.push({
|
|
1669
|
+
id: "manifest-workspace-parse",
|
|
1670
|
+
path: "pnpm-workspace.yaml",
|
|
1671
|
+
field: "packages",
|
|
1672
|
+
title: "pnpm-workspace.yaml — packages",
|
|
1673
|
+
status: "fail",
|
|
1674
|
+
detail: localize("Workspace patterns could not be read; package discovery is incomplete.", "无法读取 workspace 匹配规则;包发现不完整。")
|
|
1675
|
+
});
|
|
1676
|
+
if (selected?.has("manifest-health") && checks.some((check) => !selected.has(check.id))) checks.push({
|
|
1677
|
+
id: "manifest-health",
|
|
1678
|
+
title: localize("Workspace manifest health", "Workspace 包清单健康"),
|
|
1679
|
+
status: checks.some((check) => check.status === "fail") ? "fail" : "warn",
|
|
1680
|
+
detail: localize(`Static manifest checks found ${checks.length} issue(s). Select individual manifest rule IDs for details.`, `静态清单检查发现 ${checks.length} 个问题。选择具体 manifest 规则 ID 查看详情。`)
|
|
1681
|
+
});
|
|
1682
|
+
const result = checks.length ? checks.sort((a, b) => `${a.path}\0${a.field}\0${a.id}`.localeCompare(`${b.path}\0${b.field}\0${b.id}`)) : [{
|
|
1683
|
+
id: "manifest-health",
|
|
1684
|
+
title: localize("Workspace manifest health", "Workspace 包清单健康"),
|
|
1685
|
+
status: "pass",
|
|
1686
|
+
detail: localize(`Static manifest checks passed for ${context.manifests.length} package(s).`, `${context.manifests.length} 个包通过静态清单检查。`)
|
|
1687
|
+
}];
|
|
1688
|
+
return selected ? result.filter((check) => selected.has(check.id)) : result;
|
|
1689
|
+
}
|
|
1690
|
+
//#endregion
|
|
1691
|
+
//#region src/commands/upgrade/release-migration/classify.ts
|
|
1692
|
+
const releaseWorkflowMarker = "# repoctl-managed: release/v2";
|
|
1693
|
+
function isLegacyReleaseWorkflow(content) {
|
|
1694
|
+
if (!content.includes("changesets/action")) return false;
|
|
1695
|
+
return content.includes("publish-script:") || content.includes("changeset publish") || content.includes("changeset version") || content.includes("pnpm exec repo release");
|
|
1696
|
+
}
|
|
1697
|
+
async function classifyReleaseWorkflow(workspaceDir) {
|
|
1698
|
+
const workflowPath = path.join(workspaceDir, ".github/workflows/release.yml");
|
|
1699
|
+
if (!await fs$2.pathExists(workflowPath)) return "missing";
|
|
1700
|
+
const content = await fs$2.readFile(workflowPath, "utf8");
|
|
1701
|
+
if (content.includes("# repoctl-managed: release/v2")) return "managed";
|
|
1702
|
+
if (isLegacyReleaseWorkflow(content)) return "legacy";
|
|
1703
|
+
return "custom";
|
|
1704
|
+
}
|
|
1705
|
+
//#endregion
|
|
1706
|
+
//#region src/commands/doctor/release.ts
|
|
1707
|
+
const releaseCiMinimumVersion = "5.1.0";
|
|
1708
|
+
function hasValidFixedGroups(fixed) {
|
|
1709
|
+
return fixed === void 0 || Array.isArray(fixed) && fixed.every((group) => Array.isArray(group) && group.length > 0 && group.every((name) => typeof name === "string" && name.trim().length > 0));
|
|
1710
|
+
}
|
|
1711
|
+
function check(id, title, status, detail, fix) {
|
|
1712
|
+
return {
|
|
1713
|
+
id,
|
|
1714
|
+
title,
|
|
1715
|
+
status,
|
|
1716
|
+
detail,
|
|
1717
|
+
...fix ? { fix } : {}
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
function minimumDependencyVersion(range) {
|
|
1721
|
+
const normalized = range?.startsWith("workspace:") ? range.slice(10) : range;
|
|
1722
|
+
if (!normalized || normalized === "*" || normalized === "^" || normalized === "~") return null;
|
|
1723
|
+
try {
|
|
1724
|
+
return minVersion(normalized);
|
|
1725
|
+
} catch {
|
|
1726
|
+
return null;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
async function collectReleaseChecks(workspaceDir, pkgJson, selected) {
|
|
1730
|
+
const includes = (id) => !selected || selected.has(id);
|
|
1731
|
+
const workflowPath = path.join(workspaceDir, ".github/workflows/release.yml");
|
|
1732
|
+
const [hasWorkflow, hasPreState, hasChangesetConfig] = await Promise.all([
|
|
1733
|
+
[
|
|
1734
|
+
"release-workflow",
|
|
1735
|
+
"release-cli-version",
|
|
1736
|
+
"release-versioning-config"
|
|
1737
|
+
].some(includes) && fs$2.pathExists(workflowPath),
|
|
1738
|
+
includes("release-prerelease-state") && fs$2.pathExists(path.join(workspaceDir, ".changeset/pre.json")),
|
|
1739
|
+
includes("release-changeset-config") && fs$2.pathExists(path.join(workspaceDir, ".changeset/config.json"))
|
|
1740
|
+
]);
|
|
1741
|
+
if (!hasWorkflow && !hasPreState && !hasChangesetConfig) return [];
|
|
1742
|
+
const checks = [];
|
|
1743
|
+
const workflowStatus = includes("release-workflow") ? await classifyReleaseWorkflow(workspaceDir) : "missing";
|
|
1744
|
+
if (workflowStatus === "managed") checks.push(check("release-workflow", "release workflow", "pass", localize(`The release workflow is managed by ${releaseWorkflowMarker}.`, `release workflow 已由 ${releaseWorkflowMarker} 管理。`)));
|
|
1745
|
+
else if (workflowStatus === "legacy") checks.push(check("release-workflow", "release workflow", "warn", localize("Found a legacy Changesets release workflow.", "检测到旧的 Changesets release workflow。"), localize("Run pnpm dlx repoctl@latest upgrade --yes for the initial migration.", "首次迁移运行 pnpm dlx repoctl@latest upgrade --yes。")));
|
|
1746
|
+
else if (workflowStatus === "custom") checks.push(check("release-workflow", "release workflow", "warn", localize("The release workflow has no repoctl managed marker and may contain custom logic.", "release workflow 未包含 repoctl managed marker,可能存在自定义发布逻辑。"), localize("Review it, then run repo upgrade --overwrite-release or add the managed marker manually.", "确认内容后运行 repo upgrade --overwrite-release,或手动加入 repoctl-managed: release/v2。")));
|
|
1747
|
+
if (hasPreState) checks.push(check("release-prerelease-state", "prerelease state", "warn", localize("Found legacy .changeset/pre.json prerelease state.", "检测到旧的 .changeset/pre.json。"), localize("Run pnpm dlx repoctl@latest upgrade --yes to migrate to pnpm versioning lanes.", "运行 pnpm dlx repoctl@latest upgrade --yes 将其迁移为 pnpm versioning.lanes。")));
|
|
1748
|
+
if (hasChangesetConfig) checks.push(check("release-changeset-config", "changeset config", "warn", localize("Found .changeset/config.json from the Changesets CLI.", "检测到只属于 Changesets CLI 的 .changeset/config.json。"), localize("Run pnpm dlx repoctl@latest upgrade --yes to remove legacy configuration.", "运行 pnpm dlx repoctl@latest upgrade --yes 清理旧配置。")));
|
|
1749
|
+
if (hasWorkflow && includes("release-cli-version")) {
|
|
1750
|
+
const packageVersion = pkgJson.devDependencies?.["repoctl"] ?? pkgJson.dependencies?.["repoctl"];
|
|
1751
|
+
const parsed = minimumDependencyVersion(packageVersion);
|
|
1752
|
+
if (!parsed || !gte(parsed, "5.1.0")) checks.push(check("release-cli-version", "release CLI version", "warn", localize(`repoctl ${packageVersion ?? "missing"} does not guarantee release ci support.`, `repoctl 版本 ${packageVersion ?? "missing"} 不保证支持 release ci。`), localize(`Upgrade repoctl to >=${releaseCiMinimumVersion}.`, `运行 pnpm dlx repoctl@latest upgrade --yes,或将 repoctl 升级到 >=${releaseCiMinimumVersion}。`)));
|
|
1753
|
+
else checks.push(check("release-cli-version", "release CLI version", "pass", localize(`repoctl ${packageVersion} supports release ci.`, `repoctl 版本 ${packageVersion} 支持 release ci。`)));
|
|
1754
|
+
}
|
|
1755
|
+
if (hasWorkflow && includes("release-versioning-config")) try {
|
|
1756
|
+
const workspace = YAML.parse(await readFile(path.join(workspaceDir, "pnpm-workspace.yaml"), "utf8"));
|
|
1757
|
+
const hasValidFixed = hasValidFixedGroups(workspace.versioning?.fixed);
|
|
1758
|
+
const hasRepositoryChangelog = workspace.versioning?.changelog?.storage === "repository";
|
|
1759
|
+
checks.push(hasValidFixed && hasRepositoryChangelog ? check("release-versioning-config", "release versioning config", "pass", localize("pnpm fixed groups are valid and repository changelog storage is configured.", "pnpm fixed group 配置合法,且已配置 repository changelog。")) : check("release-versioning-config", "release versioning config", "warn", localize("pnpm-workspace.yaml has invalid fixed groups or is missing repository changelog storage.", "pnpm-workspace.yaml 的 fixed group 配置不合法,或缺少 repository changelog 配置。"), localize("Run repo upgrade --yes to synchronize pnpm versioning configuration.", "运行 repo upgrade --yes 同步 pnpm versioning 配置。")));
|
|
1760
|
+
} catch {
|
|
1761
|
+
checks.push(check("release-versioning-config", "release versioning config", "warn", localize("Unable to read versioning configuration from pnpm-workspace.yaml.", "无法读取 pnpm-workspace.yaml 的 versioning 配置。"), localize("Run repo upgrade --yes to synchronize pnpm versioning configuration.", "运行 repo upgrade --yes 同步 pnpm versioning 配置。")));
|
|
1762
|
+
}
|
|
1763
|
+
return checks;
|
|
1764
|
+
}
|
|
1765
|
+
//#endregion
|
|
1766
|
+
//#region src/commands/doctor/runtime/node.ts
|
|
1767
|
+
function checkNodeVersion({ packageJson }) {
|
|
1768
|
+
const range = packageJson.engines?.node;
|
|
1769
|
+
const known = typeof range === "string" && !!validRange(range);
|
|
1770
|
+
const status = known ? satisfies(process.version, range) ? "pass" : "fail" : "warn";
|
|
1771
|
+
return {
|
|
1772
|
+
id: "node-version",
|
|
1773
|
+
title: localize("Node version", "Node 版本"),
|
|
1774
|
+
status,
|
|
1775
|
+
detail: known ? localize(`Node ${process.version} ${status === "pass" ? "satisfies" : "does not satisfy"} ${range}.`, `当前 Node ${process.version} ${status === "pass" ? "满足" : "不满足"} ${range}。`) : localize("engines.node is missing or is not a supported semver range; compatibility is unknown.", "engines.node 缺失或不是可识别的 semver 范围,兼容性未知。"),
|
|
1776
|
+
...status !== "pass" ? { fix: localize("Declare engines.node and switch to a Node version it allows.", "声明 engines.node,并切换到允许的 Node 版本。") } : {}
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
async function checkNodeVersionFiles({ workspaceDir, packageJson }) {
|
|
1780
|
+
const versions = [];
|
|
1781
|
+
const unknown = [];
|
|
1782
|
+
const conflicts = [];
|
|
1783
|
+
for (const file of [".nvmrc", ".node-version"]) {
|
|
1784
|
+
if (!await fs$2.pathExists(`${workspaceDir}/${file}`)) continue;
|
|
1785
|
+
try {
|
|
1786
|
+
const value = (await fs$2.readFile(`${workspaceDir}/${file}`, "utf8")).replace(/#.*$/gm, "").trim();
|
|
1787
|
+
const range = /^v?\d+(?:\.\d+){0,2}(?:-[\w.-]+)?$/.test(value) ? validRange(value) : null;
|
|
1788
|
+
if (!range) {
|
|
1789
|
+
unknown.push(`${file}=${value || "(empty)"}`);
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
versions.push({
|
|
1793
|
+
file,
|
|
1794
|
+
value,
|
|
1795
|
+
range
|
|
1796
|
+
});
|
|
1797
|
+
if (!satisfies(process.version, range)) conflicts.push(`${file}=${value} / Node ${process.version}`);
|
|
1798
|
+
const engines = packageJson.engines?.node;
|
|
1799
|
+
if (engines && validRange(engines) && !intersects(range, engines)) conflicts.push(`${file}=${value} / engines.node=${engines}`);
|
|
1800
|
+
} catch {
|
|
1801
|
+
unknown.push(`${file} (unreadable)`);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
if (versions.length === 2 && !intersects(versions[0].range, versions[1].range)) conflicts.push(".nvmrc / .node-version");
|
|
1805
|
+
const status = conflicts.length ? "fail" : unknown.length ? "warn" : "pass";
|
|
1806
|
+
return {
|
|
1807
|
+
id: "node-version-files",
|
|
1808
|
+
title: localize("Node version files", "Node 版本文件"),
|
|
1809
|
+
status,
|
|
1810
|
+
detail: conflicts.length ? localize(`Conflicting Node versions: ${conflicts.join("; ")}.`, `Node 版本冲突:${conflicts.join(";")}。`) : unknown.length ? localize(`Version is unknown without resolving aliases online: ${unknown.join("; ")}.`, `无法离线解析版本或别名:${unknown.join(";")}。`) : localize("Existing numeric Node version files agree with this runtime and engines.node (when declared); missing files are optional.", "现有数字版本文件与当前 Node 及已声明的 engines.node 一致;版本文件可选。"),
|
|
1811
|
+
...status !== "pass" ? { fix: localize("Align .nvmrc, .node-version and engines.node using numeric versions, then switch Node.", "使用数字版本统一 .nvmrc、.node-version 和 engines.node,然后切换 Node。") } : {}
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
//#endregion
|
|
1815
|
+
//#region src/commands/doctor/security/settings.ts
|
|
1816
|
+
const policyKeys = [
|
|
1817
|
+
"minimumReleaseAge",
|
|
1818
|
+
"minimumReleaseAgeStrict",
|
|
1819
|
+
"minimumReleaseAgeExclude",
|
|
1820
|
+
"minimumReleaseAgeIgnoreMissingTime",
|
|
1821
|
+
"trustPolicy",
|
|
1822
|
+
"trustPolicyExclude",
|
|
1823
|
+
"trustPolicyIgnoreAfter",
|
|
1824
|
+
"trustLockfile",
|
|
1825
|
+
"allowBuilds",
|
|
1826
|
+
"onlyBuiltDependencies",
|
|
1827
|
+
"onlyBuiltDependenciesFile",
|
|
1828
|
+
"neverBuiltDependencies",
|
|
1829
|
+
"ignoredBuiltDependencies",
|
|
1830
|
+
"ignoreDepScripts",
|
|
1831
|
+
"ignoreScripts",
|
|
1832
|
+
"dangerouslyAllowAllBuilds",
|
|
1833
|
+
"strictDepBuilds"
|
|
1834
|
+
];
|
|
1835
|
+
const legacyBuildKeys = [
|
|
1836
|
+
"onlyBuiltDependencies",
|
|
1837
|
+
"onlyBuiltDependenciesFile",
|
|
1838
|
+
"neverBuiltDependencies",
|
|
1839
|
+
"ignoredBuiltDependencies",
|
|
1840
|
+
"ignoreDepScripts"
|
|
1841
|
+
];
|
|
1842
|
+
const since = {
|
|
1843
|
+
minimumReleaseAge: "10.16.0",
|
|
1844
|
+
minimumReleaseAgeExclude: "10.16.0",
|
|
1845
|
+
minimumReleaseAgeStrict: "11.0.0",
|
|
1846
|
+
minimumReleaseAgeIgnoreMissingTime: "11.0.0",
|
|
1847
|
+
trustPolicy: "10.21.0",
|
|
1848
|
+
trustPolicyExclude: "10.22.0",
|
|
1849
|
+
trustPolicyIgnoreAfter: "10.27.0",
|
|
1850
|
+
trustLockfile: "11.3.0",
|
|
1851
|
+
allowBuilds: "10.26.0",
|
|
1852
|
+
dangerouslyAllowAllBuilds: "10.9.0",
|
|
1853
|
+
strictDepBuilds: "10.3.0",
|
|
1854
|
+
ignoredBuiltDependencies: "10.1.0"
|
|
1855
|
+
};
|
|
1856
|
+
function supportedVersion(version) {
|
|
1857
|
+
return !!version && major(version) >= 10 && major(version) <= 12 && prerelease(version) === null;
|
|
1858
|
+
}
|
|
1859
|
+
function settingState(key, version) {
|
|
1860
|
+
if (!supportedVersion(version)) return "unknown";
|
|
1861
|
+
if (gte(version, "11.0.0") && legacyBuildKeys.includes(key)) return "removed";
|
|
1862
|
+
if (since[key] && lt(version, since[key])) return "unsupported";
|
|
1863
|
+
return "active";
|
|
1864
|
+
}
|
|
1865
|
+
function defaultSetting(key, version, releaseAgeConfigured) {
|
|
1866
|
+
if (key === "minimumReleaseAge") return gte(version, "11.0.0") ? 1440 : 0;
|
|
1867
|
+
if (key === "minimumReleaseAgeStrict") return releaseAgeConfigured;
|
|
1868
|
+
if (key === "strictDepBuilds") return gte(version, "11.0.0");
|
|
1869
|
+
if (key === "minimumReleaseAgeIgnoreMissingTime") return true;
|
|
1870
|
+
if ([
|
|
1871
|
+
"trustLockfile",
|
|
1872
|
+
"ignoreScripts",
|
|
1873
|
+
"ignoreDepScripts",
|
|
1874
|
+
"dangerouslyAllowAllBuilds"
|
|
1875
|
+
].includes(key)) return false;
|
|
1876
|
+
if (key === "trustPolicy") return "off";
|
|
1877
|
+
if (key === "minimumReleaseAgeExclude" || key === "trustPolicyExclude") return [];
|
|
1878
|
+
return null;
|
|
1879
|
+
}
|
|
1880
|
+
/** Return public package identity, never a Git URL, credential or arbitrary selector text. */
|
|
1881
|
+
function selectorIdentity(value) {
|
|
1882
|
+
if (typeof value !== "string") return null;
|
|
1883
|
+
const matched = /^(@[\w.~-]+\/[\w.~*+-]+|[\w.~*+-]+)(?:@(.+))?$/iu.exec(value);
|
|
1884
|
+
if (!matched) return null;
|
|
1885
|
+
const suffix = matched[2];
|
|
1886
|
+
return {
|
|
1887
|
+
package: matched[1],
|
|
1888
|
+
selector: !suffix ? "package" : validRange(suffix) ? "version" : /^(?:git|https?:|ssh:|bitbucket:)/u.test(suffix) ? "artifact" : null
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
function validPolicyValue(key, value) {
|
|
1892
|
+
if (key === "minimumReleaseAge") return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
1893
|
+
if (key === "trustPolicy") return value === "off" || value === "no-downgrade";
|
|
1894
|
+
if (key === "trustPolicyIgnoreAfter") return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
1895
|
+
if (key === "allowBuilds") return value !== null && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([name, decision]) => selectorIdentity(name)?.selector && (typeof decision === "boolean" || decision === null));
|
|
1896
|
+
if (key === "onlyBuiltDependenciesFile") return typeof value === "string" && value.length > 0 && !value.includes("${");
|
|
1897
|
+
if ([
|
|
1898
|
+
"minimumReleaseAgeExclude",
|
|
1899
|
+
"trustPolicyExclude",
|
|
1900
|
+
"onlyBuiltDependencies",
|
|
1901
|
+
"neverBuiltDependencies",
|
|
1902
|
+
"ignoredBuiltDependencies"
|
|
1903
|
+
].includes(key)) return Array.isArray(value) && value.every((item) => selectorIdentity(item)?.selector);
|
|
1904
|
+
return typeof value === "boolean";
|
|
1905
|
+
}
|
|
1906
|
+
/** Minor releases introduced selector syntax separately from the setting itself. */
|
|
1907
|
+
function selectorSyntaxSupported(key, value, version) {
|
|
1908
|
+
if (!Array.isArray(value)) return true;
|
|
1909
|
+
if (key === "minimumReleaseAgeExclude" && lt(version, "10.17.0") && value.some((item) => typeof item === "string" && item.includes("*"))) return false;
|
|
1910
|
+
return !(["minimumReleaseAgeExclude", "onlyBuiltDependencies"].includes(key) && lt(version, "10.19.0") && value.some((item) => selectorIdentity(item)?.selector === "version"));
|
|
1911
|
+
}
|
|
1912
|
+
//#endregion
|
|
1913
|
+
//#region src/commands/doctor/security/evaluate.ts
|
|
1914
|
+
const installSecurityRuleIds = [
|
|
1915
|
+
"install-security-version",
|
|
1916
|
+
"install-security-release-age",
|
|
1917
|
+
"install-security-trust",
|
|
1918
|
+
"install-security-builds",
|
|
1919
|
+
"install-security-compatibility",
|
|
1920
|
+
"install-security-config",
|
|
1921
|
+
"install-security-expectation",
|
|
1922
|
+
"install-security-exception"
|
|
1923
|
+
];
|
|
1924
|
+
function evaluateSecurity(source, selected) {
|
|
1925
|
+
const checks = [];
|
|
1926
|
+
const add = (id, status, detail) => {
|
|
1927
|
+
if (!selected || selected.has(id)) checks.push({
|
|
1928
|
+
id,
|
|
1929
|
+
status,
|
|
1930
|
+
title: "pnpm installation security policy",
|
|
1931
|
+
detail
|
|
1932
|
+
});
|
|
1933
|
+
};
|
|
1934
|
+
const settings = [];
|
|
1935
|
+
const values = /* @__PURE__ */ new Map();
|
|
1936
|
+
for (const key of policyKeys) {
|
|
1937
|
+
const configured = source.values.get(key);
|
|
1938
|
+
let state = source.uncertain.has(key) ? "unknown" : settingState(key, source.version);
|
|
1939
|
+
const value = configured ? configured.value : state === "active" ? defaultSetting(key, source.version, source.values.has("minimumReleaseAge")) : null;
|
|
1940
|
+
if (configured && state === "active" && !validPolicyValue(key, value)) {
|
|
1941
|
+
state = "invalid";
|
|
1942
|
+
add("install-security-config", "fail", `Invalid ${key} in ${configured.source}; its raw value is omitted.`);
|
|
1943
|
+
}
|
|
1944
|
+
if (configured && state === "active" && !selectorSyntaxSupported(key, value, source.version)) state = "unsupported";
|
|
1945
|
+
if (state === "active") values.set(key, value);
|
|
1946
|
+
const publicValue = state !== "active" ? null : key === "allowBuilds" ? null : key === "onlyBuiltDependenciesFile" ? value ? "external allowlist (not inspected)" : null : Array.isArray(value) ? value.map((item) => selectorIdentity(item)?.package).filter((item) => !!item) : typeof value === "string" || typeof value === "boolean" || typeof value === "number" ? value : null;
|
|
1947
|
+
settings.push({
|
|
1948
|
+
key,
|
|
1949
|
+
source: configured?.source ?? "pnpm default",
|
|
1950
|
+
configured: !!configured,
|
|
1951
|
+
state,
|
|
1952
|
+
value: publicValue
|
|
1953
|
+
});
|
|
1954
|
+
if (configured && state !== "active" && state !== "invalid") add("install-security-compatibility", "warn", `${key} in ${configured.source} is ${state} for the audited pnpm version. No setting was migrated.`);
|
|
1955
|
+
}
|
|
1956
|
+
add("install-security-version", supportedVersion(source.version) && source.evidence !== "declared" ? "pass" : "warn", source.version ? `Audited pnpm ${source.version}; version evidence: ${source.evidence}. No pnpm launcher was executed.` : "The pnpm version is unknown; defaults cannot be established.");
|
|
1957
|
+
for (const inactive of source.inactive) add("install-security-compatibility", "warn", `${inactive.key} from ${inactive.source} is not read by this pnpm version.`);
|
|
1958
|
+
const age = values.get("minimumReleaseAge");
|
|
1959
|
+
const strictAge = values.get("minimumReleaseAgeStrict");
|
|
1960
|
+
add("install-security-release-age", age === void 0 ? "warn" : "pass", age === void 0 ? "The effective minimum release age is unknown or unsupported." : `minimumReleaseAge: ${age} minute(s), ${source.values.has("minimumReleaseAge") ? "explicitly configured" : "pnpm default"}; ${age === 0 ? "release waiting is disabled" : strictAge === false ? "pnpm may fall back to younger versions" : "versions younger than the configured age are rejected"}. Exceptions are reported by package name.`);
|
|
1961
|
+
const trust = values.get("trustPolicy");
|
|
1962
|
+
add("install-security-trust", trust === void 0 ? "warn" : "pass", trust === void 0 ? "The effective trust policy is unknown or unsupported." : `trustPolicy: ${trust}; minimumReleaseAgeIgnoreMissingTime: ${values.get("minimumReleaseAgeIgnoreMissingTime") ?? "unsupported"}; trustPolicyIgnoreAfter: ${values.get("trustPolicyIgnoreAfter") ?? "unset"} minute(s); trustLockfile: ${values.get("trustLockfile") ?? "unsupported"}. Off, exclusions, age cutoffs and trusted lockfiles reduce the checked scope.`);
|
|
1963
|
+
const builds = {
|
|
1964
|
+
decisions: [],
|
|
1965
|
+
pendingPackages: [],
|
|
1966
|
+
override: "none",
|
|
1967
|
+
default: "unreviewed"
|
|
1968
|
+
};
|
|
1969
|
+
const modern = source.version !== null && gte(source.version, "11.0.0");
|
|
1970
|
+
const allowBuilds = record$3(values.get("allowBuilds"));
|
|
1971
|
+
if (allowBuilds) for (const [selector, decision] of Object.entries(allowBuilds)) {
|
|
1972
|
+
const identity = selectorIdentity(selector);
|
|
1973
|
+
builds.decisions.push({
|
|
1974
|
+
package: identity.package,
|
|
1975
|
+
selector: identity.selector,
|
|
1976
|
+
decision: decision === true ? "allow" : decision === false ? "deny" : "pending",
|
|
1977
|
+
source: source.values.get("allowBuilds").source
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
if (!modern && !allowBuilds) {
|
|
1981
|
+
for (const key of [
|
|
1982
|
+
"onlyBuiltDependencies",
|
|
1983
|
+
"neverBuiltDependencies",
|
|
1984
|
+
"ignoredBuiltDependencies"
|
|
1985
|
+
]) {
|
|
1986
|
+
const entries = values.get(key);
|
|
1987
|
+
if (Array.isArray(entries)) for (const selector of entries) {
|
|
1988
|
+
const identity = selectorIdentity(selector);
|
|
1989
|
+
builds.decisions.push({
|
|
1990
|
+
package: identity.package,
|
|
1991
|
+
selector: identity.selector,
|
|
1992
|
+
decision: key === "onlyBuiltDependencies" ? "allow" : "deny",
|
|
1993
|
+
source: source.values.get(key).source
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
if (Array.isArray(values.get("neverBuiltDependencies")) && !source.values.has("onlyBuiltDependencies") && !source.values.has("onlyBuiltDependenciesFile")) builds.default = "allowed";
|
|
1998
|
+
if (values.get("onlyBuiltDependenciesFile")) {
|
|
1999
|
+
builds.default = "unknown";
|
|
2000
|
+
add("install-security-builds", "warn", "onlyBuiltDependenciesFile can add permissions. The external allowlist is not loaded; build policy is incomplete.");
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (!modern && allowBuilds && legacyBuildKeys.some((key) => source.values.has(key))) {
|
|
2004
|
+
add("install-security-compatibility", "warn", "allowBuilds coexists with historical build settings. Review the pnpm 10 configuration conflict before installation; no automatic migration was performed.");
|
|
2005
|
+
builds.default = "unknown";
|
|
2006
|
+
}
|
|
2007
|
+
if (values.get("dangerouslyAllowAllBuilds") === true) {
|
|
2008
|
+
builds.default = "allowed";
|
|
2009
|
+
builds.override = "allow-all";
|
|
2010
|
+
if (source.values.has("allowBuilds") || legacyBuildKeys.some((key) => source.values.has(key))) {
|
|
2011
|
+
builds.default = "unknown";
|
|
2012
|
+
builds.override = "conflict";
|
|
2013
|
+
add("install-security-compatibility", "warn", "An allow-all override coexists with package build decisions; pnpm may reject this combination. Effective build permissions are unknown.");
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
if (values.get("ignoreScripts") === true || values.get("ignoreDepScripts") === true) {
|
|
2017
|
+
if (builds.override !== "conflict") {
|
|
2018
|
+
builds.default = "blocked";
|
|
2019
|
+
builds.override = "ignore-scripts";
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
if (!source.version || settings.some((item) => [
|
|
2023
|
+
"allowBuilds",
|
|
2024
|
+
"ignoreScripts",
|
|
2025
|
+
"dangerouslyAllowAllBuilds"
|
|
2026
|
+
].includes(item.key) && ["invalid", "unknown"].includes(item.state))) {
|
|
2027
|
+
builds.default = "unknown";
|
|
2028
|
+
builds.override = "unknown";
|
|
2029
|
+
}
|
|
2030
|
+
const pending = Array.isArray(source.modules["pendingBuilds"]) ? source.modules["pendingBuilds"] : [];
|
|
2031
|
+
builds.pendingPackages = [...new Set(pending.flatMap((value) => typeof value === "string" && value !== "." ? [selectorIdentity(value.replace(/\(.*$/u, ""))?.package].filter((item) => !!item) : []))].sort();
|
|
2032
|
+
builds.decisions.sort((a, b) => a.package.localeCompare(b.package) || a.selector.localeCompare(b.selector));
|
|
2033
|
+
add("install-security-builds", builds.default === "unknown" ? "warn" : "pass", `Unlisted dependency builds: ${builds.default}; strictDepBuilds: ${values.get("strictDepBuilds") ?? "unsupported"}. Global build override: ${builds.override}. Explicit allow, deny and pending decisions describe configured declarations; overrides may prevent or bypass them. Installation pendingBuilds means not yet built, not necessarily unapproved. ignoreScripts does not disable pnpmfile hooks.`);
|
|
2034
|
+
return {
|
|
2035
|
+
checks,
|
|
2036
|
+
settings,
|
|
2037
|
+
builds,
|
|
2038
|
+
values,
|
|
2039
|
+
add,
|
|
2040
|
+
version: source.version
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
//#endregion
|
|
2044
|
+
//#region src/commands/doctor/security/expectations.ts
|
|
2045
|
+
function validateExpectations(input) {
|
|
2046
|
+
const config = record$3(input);
|
|
2047
|
+
if (!config || Object.keys(config).some((key) => ![
|
|
2048
|
+
"minimumReleaseAge",
|
|
2049
|
+
"trustPolicy",
|
|
2050
|
+
"requireBuildApproval",
|
|
2051
|
+
"severity",
|
|
2052
|
+
"exceptions"
|
|
2053
|
+
].includes(key)) || config["minimumReleaseAge"] !== void 0 && (typeof config["minimumReleaseAge"] !== "number" || !Number.isFinite(config["minimumReleaseAge"]) || config["minimumReleaseAge"] < 0) || config["trustPolicy"] !== void 0 && config["trustPolicy"] !== "no-downgrade" || config["requireBuildApproval"] !== void 0 && typeof config["requireBuildApproval"] !== "boolean" || config["severity"] !== void 0 && !["warn", "fail"].includes(config["severity"]) || config["exceptions"] !== void 0 && !Array.isArray(config["exceptions"])) throw new Error("Invalid installation security expectations.");
|
|
2054
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2055
|
+
for (const item of config["exceptions"] ?? []) {
|
|
2056
|
+
const exception = record$3(item);
|
|
2057
|
+
if (!exception || Object.keys(exception).some((key) => ![
|
|
2058
|
+
"key",
|
|
2059
|
+
"package",
|
|
2060
|
+
"reason"
|
|
2061
|
+
].includes(key)) || !["minimumReleaseAgeExclude", "trustPolicyExclude"].includes(exception["key"]) || !selectorIdentity(exception["package"])?.selector || typeof exception["reason"] !== "string" || !exception["reason"].trim()) throw new Error("Installation security exceptions require a supported policy key, package selector and reason.");
|
|
2062
|
+
const id = JSON.stringify([exception["key"], exception["package"]]);
|
|
2063
|
+
if (seen.has(id)) throw new Error("Duplicate installation security exception.");
|
|
2064
|
+
seen.add(id);
|
|
2065
|
+
}
|
|
2066
|
+
return config;
|
|
2067
|
+
}
|
|
2068
|
+
function evaluateExpectations(result, config) {
|
|
2069
|
+
const status = config.severity ?? "warn";
|
|
2070
|
+
if (config.minimumReleaseAge !== void 0) {
|
|
2071
|
+
const age = result.values.get("minimumReleaseAge");
|
|
2072
|
+
if (typeof age !== "number" || age < config.minimumReleaseAge || config.minimumReleaseAge > 0 && (result.values.get("minimumReleaseAgeStrict") === false || result.values.get("minimumReleaseAgeIgnoreMissingTime") === true)) result.add("install-security-expectation", status, `Expected at least ${config.minimumReleaseAge} minutes of release age without non-strict fallback.`);
|
|
2073
|
+
}
|
|
2074
|
+
if (config.trustPolicy && (result.values.get("trustPolicy") !== config.trustPolicy || result.values.get("trustLockfile") === true || result.version && gte(result.version, "11.23.0") && result.values.get("minimumReleaseAgeIgnoreMissingTime") === true || result.values.get("trustPolicyIgnoreAfter") != null)) result.add("install-security-expectation", status, "Expected trustPolicy=no-downgrade without trusted-lockfile, missing-time or age-cutoff bypasses.");
|
|
2075
|
+
if (config.requireBuildApproval && ["unknown", "allowed"].includes(result.builds.default)) result.add("install-security-expectation", status, "Expected explicit approval before dependency scripts can run.");
|
|
2076
|
+
for (const key of ["minimumReleaseAgeExclude", "trustPolicyExclude"]) {
|
|
2077
|
+
const selectors = result.values.get(key);
|
|
2078
|
+
for (const selector of Array.isArray(selectors) ? selectors : []) {
|
|
2079
|
+
const exception = config.exceptions?.find((item) => item.key === key && item.package === selector);
|
|
2080
|
+
result.add("install-security-exception", exception ? "pass" : status, `${key}: ${selectorIdentity(selector).package}; ${exception ? exception.reason : "no organization exception reason is recorded"}.`);
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
for (const exception of config.exceptions ?? []) {
|
|
2084
|
+
const selectors = result.values.get(exception.key);
|
|
2085
|
+
if (!Array.isArray(selectors) || !selectors.includes(exception.package)) result.add("install-security-exception", "warn", `Unused reason for ${exception.key}: ${selectorIdentity(exception.package).package}.`);
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
//#endregion
|
|
2089
|
+
//#region src/commands/doctor/security/sources.ts
|
|
2090
|
+
const keyName = (key) => key.replace(/[-_]/gu, "").toLowerCase();
|
|
2091
|
+
async function textFile(filename, label) {
|
|
2092
|
+
try {
|
|
2093
|
+
return await readFile(filename, "utf8");
|
|
2094
|
+
} catch (error) {
|
|
2095
|
+
if (error.code === "ENOENT") return;
|
|
2096
|
+
throw new Error(`Cannot read ${label} for installation policy inspection.`);
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
async function yamlFile(filename, label) {
|
|
2100
|
+
const content = await textFile(filename, label);
|
|
2101
|
+
if (content === void 0) return {};
|
|
2102
|
+
try {
|
|
2103
|
+
const value = YAML.parse(content);
|
|
2104
|
+
if (value === null) return {};
|
|
2105
|
+
const object = record$3(value);
|
|
2106
|
+
if (!object) throw new Error("Expected a map");
|
|
2107
|
+
return object;
|
|
2108
|
+
} catch {
|
|
2109
|
+
throw new Error(`Invalid ${label}; parser content is omitted to protect unrelated configuration values.`);
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
/** Read only recognized non-auth keys; never return complete npmrc content. */
|
|
2113
|
+
async function npmrcFile(filename, label) {
|
|
2114
|
+
const content = await textFile(filename, label);
|
|
2115
|
+
const output = {};
|
|
2116
|
+
for (const line of content?.split(/\r?\n/u) ?? []) {
|
|
2117
|
+
const separator = line.indexOf("=");
|
|
2118
|
+
if (separator < 1) continue;
|
|
2119
|
+
const declared = line.slice(0, separator).trim();
|
|
2120
|
+
const array = declared.endsWith("[]");
|
|
2121
|
+
const name = array ? declared.slice(0, -2) : declared;
|
|
2122
|
+
const key = policyKeys.find((key) => keyName(key) === keyName(name));
|
|
2123
|
+
if (!key) continue;
|
|
2124
|
+
let value;
|
|
2125
|
+
try {
|
|
2126
|
+
value = YAML.parse(line.slice(separator + 1).trim());
|
|
2127
|
+
} catch {
|
|
2128
|
+
value = void 0;
|
|
2129
|
+
}
|
|
2130
|
+
output[key] = array ? [...Array.isArray(output[key]) ? output[key] : [], value] : value;
|
|
2131
|
+
}
|
|
2132
|
+
return output;
|
|
2133
|
+
}
|
|
2134
|
+
function environmentValues(prefix) {
|
|
2135
|
+
const values = {};
|
|
2136
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
2137
|
+
if (!name.toLowerCase().startsWith(prefix)) continue;
|
|
2138
|
+
const key = policyKeys.find((key) => keyName(key) === keyName(name.slice(prefix.length)));
|
|
2139
|
+
if (key && value !== void 0) try {
|
|
2140
|
+
values[key] = YAML.parse(value);
|
|
2141
|
+
} catch {
|
|
2142
|
+
values[key] = void 0;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
return values;
|
|
2146
|
+
}
|
|
2147
|
+
function environmentPath(name) {
|
|
2148
|
+
return Object.entries(process.env).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
2149
|
+
}
|
|
2150
|
+
function globalDirectory() {
|
|
2151
|
+
if (process.env["XDG_CONFIG_HOME"]) return path.join(process.env["XDG_CONFIG_HOME"], "pnpm");
|
|
2152
|
+
return process.platform === "win32" ? process.env["LOCALAPPDATA"] ? path.join(process.env["LOCALAPPDATA"], "pnpm/config") : path.join(homedir(), ".config/pnpm") : process.platform === "darwin" ? path.join(homedir(), "Library/Preferences/pnpm") : path.join(homedir(), ".config/pnpm");
|
|
2153
|
+
}
|
|
2154
|
+
async function readSecuritySources(cwd, options = {}) {
|
|
2155
|
+
const found = await findWorkspaceDir(cwd);
|
|
2156
|
+
if (!found) throw new Error("Installation policy inspection requires a pnpm workspace.");
|
|
2157
|
+
const workspaceDir = path.normalize(await realpath(found));
|
|
2158
|
+
let manifest;
|
|
2159
|
+
try {
|
|
2160
|
+
manifest = record$3(JSON.parse(await readFile(path.join(workspaceDir, "package.json"), "utf8"))) ?? {};
|
|
2161
|
+
} catch {
|
|
2162
|
+
throw new Error("Cannot read the root package manifest for installation policy inspection.");
|
|
2163
|
+
}
|
|
2164
|
+
if (options.pnpmVersion !== void 0 && valid(options.pnpmVersion) !== options.pnpmVersion) throw new Error("Installation policy auditing requires an exact pnpm version.");
|
|
2165
|
+
const runtime = await inspectPnpmRuntime();
|
|
2166
|
+
const declared = declaredPnpmVersion(manifest["packageManager"]);
|
|
2167
|
+
const version = options.pnpmVersion ?? (runtime.state === "observed" ? runtime.version : declared) ?? null;
|
|
2168
|
+
const evidence = options.pnpmVersion ? "explicit" : runtime.state === "observed" ? "observed" : declared ? "declared" : "unknown";
|
|
2169
|
+
const modern = !!version && gte(version, "11.0.0");
|
|
2170
|
+
const global = globalDirectory();
|
|
2171
|
+
if (process.platform === "win32" && global.includes("%")) throw new Error("Unexpanded configuration directory variables require review before policy inspection.");
|
|
2172
|
+
const workspace = await yamlFile(path.join(workspaceDir, "pnpm-workspace.yaml"), "pnpm-workspace.yaml");
|
|
2173
|
+
const layers = [
|
|
2174
|
+
{
|
|
2175
|
+
source: "global rc",
|
|
2176
|
+
values: await npmrcFile(path.join(global, "rc"), "global rc"),
|
|
2177
|
+
active: !modern
|
|
2178
|
+
},
|
|
2179
|
+
{
|
|
2180
|
+
source: "user .npmrc",
|
|
2181
|
+
values: await npmrcFile(environmentPath("npm_config_userconfig") ?? path.join(homedir(), ".npmrc"), "user .npmrc"),
|
|
2182
|
+
active: !modern
|
|
2183
|
+
},
|
|
2184
|
+
{
|
|
2185
|
+
source: "global config.yaml",
|
|
2186
|
+
values: modern ? await yamlFile(path.join(global, "config.yaml"), "global config.yaml") : {},
|
|
2187
|
+
active: modern
|
|
2188
|
+
},
|
|
2189
|
+
{
|
|
2190
|
+
source: "package.json#pnpm",
|
|
2191
|
+
values: record$3(manifest["pnpm"]) ?? {},
|
|
2192
|
+
active: !modern
|
|
2193
|
+
},
|
|
2194
|
+
{
|
|
2195
|
+
source: "project .npmrc",
|
|
2196
|
+
values: await npmrcFile(path.join(workspaceDir, ".npmrc"), "project .npmrc"),
|
|
2197
|
+
active: !modern
|
|
2198
|
+
},
|
|
2199
|
+
{
|
|
2200
|
+
source: "pnpm-workspace.yaml",
|
|
2201
|
+
values: workspace,
|
|
2202
|
+
active: true
|
|
2203
|
+
},
|
|
2204
|
+
{
|
|
2205
|
+
source: "npm_config environment",
|
|
2206
|
+
values: environmentValues("npm_config_"),
|
|
2207
|
+
active: !modern
|
|
2208
|
+
},
|
|
2209
|
+
{
|
|
2210
|
+
source: "pnpm_config environment",
|
|
2211
|
+
values: environmentValues("pnpm_config_"),
|
|
2212
|
+
active: modern
|
|
2213
|
+
}
|
|
2214
|
+
];
|
|
2215
|
+
const values = /* @__PURE__ */ new Map();
|
|
2216
|
+
const inactive = [];
|
|
2217
|
+
const uncertain = /* @__PURE__ */ new Set();
|
|
2218
|
+
for (const layer of layers) for (const key of policyKeys) {
|
|
2219
|
+
if (!Object.hasOwn(layer.values, key)) continue;
|
|
2220
|
+
if (!layer.active || layer.source === "global config.yaml" && (key === "allowBuilds" || [
|
|
2221
|
+
"onlyBuiltDependencies",
|
|
2222
|
+
"onlyBuiltDependenciesFile",
|
|
2223
|
+
"neverBuiltDependencies",
|
|
2224
|
+
"ignoredBuiltDependencies",
|
|
2225
|
+
"ignoreDepScripts"
|
|
2226
|
+
].includes(key))) {
|
|
2227
|
+
inactive.push({
|
|
2228
|
+
key,
|
|
2229
|
+
source: layer.source
|
|
2230
|
+
});
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
if (!modern && values.has(key) && JSON.stringify(values.get(key).value) !== JSON.stringify(layer.values[key])) uncertain.add(key);
|
|
2234
|
+
if (key === "allowBuilds" && layer.source.endsWith("environment")) uncertain.add(key);
|
|
2235
|
+
values.set(key, {
|
|
2236
|
+
value: layer.values[key],
|
|
2237
|
+
source: layer.source
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
const modules = await yamlFile(path.join(workspaceDir, "node_modules/.modules.yaml"), "installation metadata");
|
|
2241
|
+
const limitations = ["CLI arguments of other pnpm invocations are not observable; this report describes persisted settings and inherited environment.", "No dependency lifecycle scripts or pnpmfile hooks are executed."];
|
|
2242
|
+
if (workspace["configDependencies"] || workspace["packageConfigs"]) {
|
|
2243
|
+
limitations.push("Config dependencies or per-package policy can change effective settings; only the workspace-level declarations are inspected.");
|
|
2244
|
+
policyKeys.forEach((key) => uncertain.add(key));
|
|
2245
|
+
}
|
|
2246
|
+
if ([...values.values()].some(({ value }) => typeof value === "string" && value.includes("${"))) limitations.push("Environment interpolation in policy values is not expanded; unresolved values are reported as invalid.");
|
|
2247
|
+
return {
|
|
2248
|
+
workspaceDir,
|
|
2249
|
+
version,
|
|
2250
|
+
evidence,
|
|
2251
|
+
values,
|
|
2252
|
+
inactive,
|
|
2253
|
+
uncertain,
|
|
2254
|
+
modules,
|
|
2255
|
+
limitations
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
//#endregion
|
|
2259
|
+
//#region src/commands/doctor/security/index.ts
|
|
2260
|
+
async function inspectInstallSecurity(cwd, options = {}, selected) {
|
|
2261
|
+
const source = await readSecuritySources(cwd, options);
|
|
2262
|
+
const result = evaluateSecurity(source, selected);
|
|
2263
|
+
const loaded = options.expectations === void 0 ? await loadMonorepoConfigDetails(source.workspaceDir, { refresh: true }).catch(() => {
|
|
2264
|
+
throw new Error("Cannot load installation security expectations; configuration details are omitted.");
|
|
2265
|
+
}) : void 0;
|
|
2266
|
+
for (const layer of loaded?.rawLayers ?? []) if (Object.hasOwn(layer, "installationSecurity")) validateExpectations(layer.installationSecurity);
|
|
2267
|
+
const configured = options.expectations === void 0 ? loaded?.config.installationSecurity : options.expectations;
|
|
2268
|
+
if (configured !== void 0) evaluateExpectations(result, validateExpectations(configured));
|
|
2269
|
+
return {
|
|
2270
|
+
schemaVersion: 1,
|
|
2271
|
+
kind: "install-security",
|
|
2272
|
+
workspaceDir: source.workspaceDir,
|
|
2273
|
+
pnpm: {
|
|
2274
|
+
version: source.version,
|
|
2275
|
+
evidence: source.evidence
|
|
2276
|
+
},
|
|
2277
|
+
settings: result.settings,
|
|
2278
|
+
builds: result.builds,
|
|
2279
|
+
checks: result.checks,
|
|
2280
|
+
summary: summarizeChecks(result.checks),
|
|
2281
|
+
limitations: source.limitations
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
async function collectInstallSecurityChecks(context, selected) {
|
|
2285
|
+
try {
|
|
2286
|
+
return (await inspectInstallSecurity(context.workspaceDir, {}, selected)).checks;
|
|
2287
|
+
} catch {
|
|
2288
|
+
return [{
|
|
2289
|
+
id: "install-security-config",
|
|
2290
|
+
title: "pnpm installation security policy",
|
|
2291
|
+
status: "fail",
|
|
2292
|
+
detail: "Installation policy could not be inspected. Run doctor security to review its configuration; no scripts were executed."
|
|
2293
|
+
}];
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
//#endregion
|
|
2297
|
+
//#region src/commands/doctor/tooling.ts
|
|
2298
|
+
const recommendedRepoScripts = {
|
|
2299
|
+
"repo:init": "repo init",
|
|
2300
|
+
"repo:new": "repo new",
|
|
2301
|
+
"repo:check": "repo check",
|
|
2302
|
+
"repo:doctor": "repo doctor"
|
|
2303
|
+
};
|
|
2304
|
+
function resolveToolPackage(pkgJson) {
|
|
2305
|
+
const version = pkgJson.devDependencies?.["repoctl"] ?? pkgJson.dependencies?.["repoctl"];
|
|
2306
|
+
return typeof version === "string" ? {
|
|
2307
|
+
name: "repoctl",
|
|
2308
|
+
version
|
|
2309
|
+
} : null;
|
|
2310
|
+
}
|
|
2311
|
+
function hasScript(pkgJson, name) {
|
|
2312
|
+
return typeof pkgJson.scripts?.[name] === "string" && pkgJson.scripts[name].length > 0;
|
|
2313
|
+
}
|
|
2314
|
+
async function findLegacyToolingFiles(context) {
|
|
2315
|
+
const files = [...context.isSourceWorkspace ? [] : [
|
|
2316
|
+
"eslint.config.js",
|
|
2317
|
+
"stylelint.config.js",
|
|
2318
|
+
"lint-staged.config.js",
|
|
2319
|
+
"vitest.config.ts"
|
|
2320
|
+
]];
|
|
2321
|
+
for (const baseDir of [
|
|
2322
|
+
"apps",
|
|
2323
|
+
"packages",
|
|
2324
|
+
"examples"
|
|
2325
|
+
]) {
|
|
2326
|
+
const absoluteBase = `${context.workspaceDir}/${baseDir}`;
|
|
2327
|
+
if (!await fs$2.pathExists(absoluteBase)) continue;
|
|
2328
|
+
for (const entry of await readdir(absoluteBase)) files.push(`${baseDir}/${entry}/eslint.config.js`, `${baseDir}/${entry}/vitest.config.ts`);
|
|
2329
|
+
}
|
|
2330
|
+
const legacyFiles = [];
|
|
2331
|
+
await Promise.all(files.map(async (file) => {
|
|
2332
|
+
const candidate = `${context.workspaceDir}/${file}`;
|
|
2333
|
+
if (await fs$2.pathExists(candidate) && hasLegacyToolingReference(await fs$2.readFile(candidate, "utf8"))) legacyFiles.push(file);
|
|
2334
|
+
}));
|
|
2335
|
+
return legacyFiles.sort((left, right) => left.localeCompare(right));
|
|
2336
|
+
}
|
|
2337
|
+
async function collectToolingChecks(context, selected) {
|
|
2338
|
+
const checks = [];
|
|
2339
|
+
if (!selected || selected.has("tool-package")) {
|
|
2340
|
+
const toolPackage = resolveToolPackage(context.packageJson);
|
|
2341
|
+
checks.push(toolPackage ? createCheck({
|
|
2342
|
+
id: "tool-package",
|
|
2343
|
+
title: localize("repo CLI dependency", "repo CLI 依赖"),
|
|
2344
|
+
status: "pass",
|
|
2345
|
+
detail: localize(`Detected CLI dependency: ${toolPackage.name}@${toolPackage.version}`, `已检测到 CLI 依赖:${toolPackage.name}@${toolPackage.version}`)
|
|
2346
|
+
}) : createCheck({
|
|
2347
|
+
id: "tool-package",
|
|
2348
|
+
title: localize("repo CLI dependency", "repo CLI 依赖"),
|
|
2349
|
+
status: "fail",
|
|
2350
|
+
detail: localize("The root package.json does not contain a repoctl dependency.", "根 package.json 中没有 repoctl 依赖。"),
|
|
2351
|
+
fix: localize("Run repo init --yes or pnpm add -D repoctl.", "运行 repo init --yes,或执行 pnpm add -D repoctl。")
|
|
2352
|
+
}));
|
|
2353
|
+
}
|
|
2354
|
+
if (!selected || selected.has("root-scripts")) {
|
|
2355
|
+
const missing = Object.keys(recommendedRepoScripts).filter((name) => !hasScript(context.packageJson, name));
|
|
2356
|
+
const unexpected = Object.entries(recommendedRepoScripts).filter(([name, command]) => hasScript(context.packageJson, name) && context.packageJson.scripts?.[name] !== command).map(([name]) => name);
|
|
2357
|
+
checks.push(missing.length === 0 && unexpected.length === 0 ? createCheck({
|
|
2358
|
+
id: "root-scripts",
|
|
2359
|
+
title: localize("repo:* root scripts", "repo:* 根脚本"),
|
|
2360
|
+
status: "pass",
|
|
2361
|
+
detail: localize("Found repo:init, repo:new, repo:check, and repo:doctor root scripts.", "已检测到 repo:init、repo:new、repo:check 和 repo:doctor 根脚本。")
|
|
2362
|
+
}) : createCheck({
|
|
2363
|
+
id: "root-scripts",
|
|
2364
|
+
title: localize("repo:* root scripts", "repo:* 根脚本"),
|
|
2365
|
+
status: "warn",
|
|
2366
|
+
detail: localize(`Recommended root scripts need attention. Missing: ${missing.join(", ") || "none"}; unexpected: ${unexpected.join(", ") || "none"}.`, `推荐根脚本需要调整。缺少:${missing.join(", ") || "无"};命令不一致:${unexpected.join(", ") || "无"}。`),
|
|
2367
|
+
fix: localize("Run repo init --yes or update the scripts in package.json.", "运行 repo init --yes,或更新 package.json 中的脚本。")
|
|
2368
|
+
}));
|
|
2369
|
+
}
|
|
2370
|
+
if (!selected || selected.has("tooling-imports")) {
|
|
2371
|
+
const legacyFiles = await findLegacyToolingFiles(context);
|
|
2372
|
+
checks.push(legacyFiles.length === 0 ? createCheck({
|
|
2373
|
+
id: "tooling-imports",
|
|
2374
|
+
title: localize("Tooling imports", "Tooling 导入"),
|
|
2375
|
+
status: "pass",
|
|
2376
|
+
detail: localize("Tooling configuration uses current repoctl entrypoints.", "Tooling 配置使用当前 repoctl 入口。")
|
|
2377
|
+
}) : createCheck({
|
|
2378
|
+
id: "tooling-imports",
|
|
2379
|
+
title: localize("Tooling imports", "Tooling 导入"),
|
|
2380
|
+
status: "warn",
|
|
2381
|
+
detail: localize(`These files reference legacy tooling entries: ${legacyFiles.join(", ")}.`, `以下文件引用旧 tooling 入口:${legacyFiles.join(", ")}。`),
|
|
2382
|
+
fix: localize("Run repo upgrade --yes to migrate to repoctl/tooling.", "运行 repo upgrade --yes 迁移到 repoctl/tooling。")
|
|
2383
|
+
}));
|
|
2384
|
+
}
|
|
2385
|
+
return checks;
|
|
2386
|
+
}
|
|
2387
|
+
//#endregion
|
|
2388
|
+
//#region src/commands/doctor/workspace.ts
|
|
2389
|
+
function collectWorkspaceChecks(context, selected) {
|
|
2390
|
+
const includes = (id) => !selected || selected.has(id);
|
|
2391
|
+
const rootManifest = context.manifests.find((entry) => entry.directory === context.workspaceDir);
|
|
2392
|
+
const { hasPackageJson, hasWorkspaceManifest, hasRepoctlConfig, hasLegacyMonorepoConfig, hasHuskyPreCommit, hasLintStagedConfig, packageCount, workspaceDir, workspacePackageDirs, workspacePatterns } = context;
|
|
2393
|
+
const checks = [];
|
|
2394
|
+
if (includes("package-json")) checks.push(hasPackageJson || rootManifest ? createCheck({
|
|
2395
|
+
id: "package-json",
|
|
2396
|
+
title: rootManifest?.path ?? "package.json",
|
|
2397
|
+
status: "pass",
|
|
2398
|
+
detail: localize(`Found root package manifest: ${workspaceDir}/${rootManifest?.path ?? "package.json"}`, `已找到根包清单:${workspaceDir}/${rootManifest?.path ?? "package.json"}`)
|
|
2399
|
+
}) : createCheck({
|
|
2400
|
+
id: "package-json",
|
|
2401
|
+
title: "package.json",
|
|
2402
|
+
status: "fail",
|
|
2403
|
+
detail: localize("The current directory does not contain a root package.json.", "当前目录缺少根 package.json。"),
|
|
2404
|
+
fix: localize("Run the command from the monorepo root or initialize the workspace first.", "请在 monorepo 根目录执行命令,或先完成工作区初始化。")
|
|
2405
|
+
}));
|
|
2406
|
+
if (includes("workspace-manifest")) checks.push(hasWorkspaceManifest ? createCheck({
|
|
2407
|
+
id: "workspace-manifest",
|
|
2408
|
+
title: "pnpm workspace",
|
|
2409
|
+
status: "pass",
|
|
2410
|
+
detail: localize(`Found a pnpm workspace with ${packageCount} package(s).`, `已找到 pnpm workspace,当前识别到 ${packageCount} 个 workspace 包。`)
|
|
2411
|
+
}) : createCheck({
|
|
2412
|
+
id: "workspace-manifest",
|
|
2413
|
+
title: "pnpm workspace",
|
|
2414
|
+
status: "fail",
|
|
2415
|
+
detail: localize("pnpm-workspace.yaml is missing; this directory is not a complete pnpm monorepo root.", "缺少 pnpm-workspace.yaml,当前目录不是完整的 pnpm monorepo 根目录。"),
|
|
2416
|
+
fix: localize("Run repo init --yes or switch to the workspace root.", "运行 repo init --yes,或切换到 workspace 根目录。")
|
|
2417
|
+
}));
|
|
2418
|
+
if (includes("config-file")) {
|
|
2419
|
+
if (hasLegacyMonorepoConfig) checks.push(createCheck({
|
|
2420
|
+
id: "config-file",
|
|
2421
|
+
title: localize("Configuration file", "配置文件"),
|
|
2422
|
+
status: "fail",
|
|
2423
|
+
detail: localize("Found deprecated monorepo.config.ts; repoctl no longer loads it.", "检测到已废弃的 monorepo.config.ts;repoctl 不再加载该文件。"),
|
|
2424
|
+
fix: localize("Rename it to repoctl.config.ts and keep only the repoctl config.", "将其重命名为 repoctl.config.ts,并只保留 repoctl 配置。")
|
|
2425
|
+
}));
|
|
2426
|
+
else if (hasRepoctlConfig) checks.push(createCheck({
|
|
2427
|
+
id: "config-file",
|
|
2428
|
+
title: localize("Configuration file", "配置文件"),
|
|
2429
|
+
status: "pass",
|
|
2430
|
+
detail: localize("Found repoctl.config.ts.", "已检测到 repoctl.config.ts。")
|
|
2431
|
+
}));
|
|
2432
|
+
else checks.push(createCheck({
|
|
2433
|
+
id: "config-file",
|
|
2434
|
+
title: localize("Configuration file", "配置文件"),
|
|
2435
|
+
status: "warn",
|
|
2436
|
+
detail: localize("No custom configuration file was found; the CLI will use defaults.", "未找到自定义配置文件;CLI 将使用默认配置。"),
|
|
2437
|
+
fix: localize("Run repo upgrade --yes or add repoctl.config.ts manually.", "运行 repo upgrade --yes,或手动添加 repoctl.config.ts。")
|
|
2438
|
+
}));
|
|
2439
|
+
}
|
|
2440
|
+
if (includes("commit-hooks")) {
|
|
2441
|
+
if (hasHuskyPreCommit && hasLintStagedConfig) checks.push(createCheck({
|
|
2442
|
+
id: "commit-hooks",
|
|
2443
|
+
title: localize("Commit hooks", "提交钩子"),
|
|
2444
|
+
status: "pass",
|
|
2445
|
+
detail: localize("Found .husky/pre-commit and lint-staged.config.js.", "已检测到 .husky/pre-commit 和 lint-staged.config.js。")
|
|
2446
|
+
}));
|
|
2447
|
+
else checks.push(createCheck({
|
|
2448
|
+
id: "commit-hooks",
|
|
2449
|
+
title: localize("Commit hooks", "提交钩子"),
|
|
2450
|
+
status: "warn",
|
|
2451
|
+
detail: localize("Husky and lint-staged are not both configured.", "Husky 和 lint-staged 尚未同时配置。"),
|
|
2452
|
+
fix: localize("Run repo upgrade --yes to synchronize the default hooks.", "运行 repo upgrade --yes 同步默认钩子。")
|
|
2453
|
+
}));
|
|
2454
|
+
}
|
|
2455
|
+
if (hasWorkspaceManifest && includes("workspace-patterns")) {
|
|
2456
|
+
const missingPatterns = [
|
|
2457
|
+
"apps",
|
|
2458
|
+
"packages",
|
|
2459
|
+
"examples"
|
|
2460
|
+
].filter((base) => workspacePackageDirs.some((dir) => dir.startsWith(`${base}/`))).map((base) => `${base}/*`).filter((pattern) => !workspacePatterns.includes(pattern));
|
|
2461
|
+
checks.push(createCheck(missingPatterns.length === 0 ? {
|
|
2462
|
+
id: "workspace-patterns",
|
|
2463
|
+
title: localize("Workspace patterns", "Workspace 匹配规则"),
|
|
2464
|
+
status: "pass",
|
|
2465
|
+
detail: localize("pnpm-workspace.yaml includes the existing conventional workspace directories.", "pnpm-workspace.yaml 已包含现有的常规 workspace 目录。")
|
|
2466
|
+
} : {
|
|
2467
|
+
id: "workspace-patterns",
|
|
2468
|
+
title: localize("Workspace patterns", "Workspace 匹配规则"),
|
|
2469
|
+
status: "warn",
|
|
2470
|
+
detail: localize(`pnpm-workspace.yaml is missing: ${missingPatterns.join(", ")}.`, `pnpm-workspace.yaml 缺少:${missingPatterns.join(", ")}。`),
|
|
2471
|
+
fix: localize("Run repo init --yes to append missing workspace patterns.", "运行 repo init --yes 追加缺失的 workspace 匹配规则。")
|
|
2472
|
+
}));
|
|
2473
|
+
}
|
|
2474
|
+
if (hasWorkspaceManifest && includes("workspace-package-coverage")) {
|
|
2475
|
+
const uncovered = workspacePackageDirs.filter((dir) => !isWorkspacePatternCovered(dir, workspacePatterns));
|
|
2476
|
+
checks.push(createCheck(uncovered.length === 0 ? {
|
|
2477
|
+
id: "workspace-package-coverage",
|
|
2478
|
+
title: localize("Workspace package coverage", "Workspace 包覆盖"),
|
|
2479
|
+
status: "pass",
|
|
2480
|
+
detail: localize("Every package.json in a conventional workspace directory is covered.", "常规 workspace 目录中的 package.json 均已覆盖。")
|
|
2481
|
+
} : {
|
|
2482
|
+
id: "workspace-package-coverage",
|
|
2483
|
+
title: localize("Workspace package coverage", "Workspace 包覆盖"),
|
|
2484
|
+
status: "warn",
|
|
2485
|
+
detail: localize(`These packages are not covered by pnpm-workspace.yaml: ${uncovered.join(", ")}.`, `以下包未被 pnpm-workspace.yaml 覆盖:${uncovered.join(", ")}。`),
|
|
2486
|
+
fix: localize("Run repo init --yes to append missing workspace patterns.", "运行 repo init --yes 追加缺失的 workspace 匹配规则。")
|
|
2487
|
+
}));
|
|
2488
|
+
}
|
|
2489
|
+
return checks;
|
|
2490
|
+
}
|
|
2491
|
+
//#endregion
|
|
2492
|
+
//#region src/commands/doctor/rules.ts
|
|
2493
|
+
const manifestIds = [
|
|
2494
|
+
"multiple",
|
|
2495
|
+
"parse",
|
|
2496
|
+
"name-missing",
|
|
2497
|
+
"name-invalid",
|
|
2498
|
+
"name-legacy",
|
|
2499
|
+
"private-invalid",
|
|
2500
|
+
"version-invalid",
|
|
2501
|
+
"version-missing",
|
|
2502
|
+
"license",
|
|
2503
|
+
"repository",
|
|
2504
|
+
"repository-directory",
|
|
2505
|
+
"publish-config",
|
|
2506
|
+
"publish-access",
|
|
2507
|
+
"publish-registry",
|
|
2508
|
+
"name-duplicate",
|
|
2509
|
+
"dependency-section",
|
|
2510
|
+
"dependency-specifier",
|
|
2511
|
+
"self-dependency",
|
|
2512
|
+
"workspace-specifier",
|
|
2513
|
+
"workspace-target",
|
|
2514
|
+
"workspace-ambiguous",
|
|
2515
|
+
"workspace-unreadable",
|
|
2516
|
+
"workspace-version-unknown",
|
|
2517
|
+
"workspace-version-mismatch",
|
|
2518
|
+
"dependency-conflict",
|
|
2519
|
+
"dependency-duplicate",
|
|
2520
|
+
"workspace-parse",
|
|
2521
|
+
"health"
|
|
2522
|
+
].map((id) => `manifest-${id}`);
|
|
2523
|
+
const collectors = [
|
|
2524
|
+
{
|
|
2525
|
+
ids: templateDriftRuleIds,
|
|
2526
|
+
collect: collectTemplateDriftChecks
|
|
2527
|
+
},
|
|
2528
|
+
{
|
|
2529
|
+
ids: [
|
|
2530
|
+
"package-json",
|
|
2531
|
+
"workspace-manifest",
|
|
2532
|
+
"config-file",
|
|
2533
|
+
"commit-hooks",
|
|
2534
|
+
"workspace-patterns",
|
|
2535
|
+
"workspace-package-coverage"
|
|
2536
|
+
],
|
|
2537
|
+
collect: collectWorkspaceChecks
|
|
2538
|
+
},
|
|
2539
|
+
{
|
|
2540
|
+
ids: manifestIds,
|
|
2541
|
+
collect: collectManifestChecks
|
|
2542
|
+
},
|
|
2543
|
+
{
|
|
2544
|
+
ids: [
|
|
2545
|
+
"boundary-rule",
|
|
2546
|
+
"boundary-cycle",
|
|
2547
|
+
"boundary-config",
|
|
2548
|
+
"boundary-selector-unmatched",
|
|
2549
|
+
"boundary-graph",
|
|
2550
|
+
"boundary-exception-unused",
|
|
2551
|
+
"boundary-exceptions",
|
|
2552
|
+
"boundary-policy"
|
|
2553
|
+
],
|
|
2554
|
+
collect: (context, selected) => collectBoundaryChecks(context.workspaceDir, selected)
|
|
2555
|
+
},
|
|
2556
|
+
{
|
|
2557
|
+
ids: [
|
|
2558
|
+
"admission-denied",
|
|
2559
|
+
"admission-not-allowed",
|
|
2560
|
+
"admission-conflict",
|
|
2561
|
+
"admission-resolution",
|
|
2562
|
+
"admission-unused-exception",
|
|
2563
|
+
"admission-expired-exception",
|
|
2564
|
+
"admission-expiring-exception",
|
|
2565
|
+
"admission-selector-unmatched",
|
|
2566
|
+
"admission-exceptions",
|
|
2567
|
+
"admission-policy",
|
|
2568
|
+
"admission-config"
|
|
2569
|
+
],
|
|
2570
|
+
collect: (context, selected) => collectAdmissionChecks(context.workspaceDir, selected)
|
|
2571
|
+
},
|
|
2572
|
+
{
|
|
2573
|
+
ids: ["node-version"],
|
|
2574
|
+
collect: (context) => [checkNodeVersion(context)]
|
|
2575
|
+
},
|
|
2576
|
+
{
|
|
2577
|
+
ids: ["node-version-files"],
|
|
2578
|
+
collect: async (context) => [await checkNodeVersionFiles(context)]
|
|
2579
|
+
},
|
|
2580
|
+
{
|
|
2581
|
+
ids: ["package-manager", "pnpm-version"],
|
|
2582
|
+
collect: collectPnpmChecks
|
|
2583
|
+
},
|
|
2584
|
+
{
|
|
2585
|
+
ids: ["lockfile-sync", "installation-state"],
|
|
2586
|
+
collect: collectInstallationChecks
|
|
2587
|
+
},
|
|
2588
|
+
{
|
|
2589
|
+
ids: installSecurityRuleIds,
|
|
2590
|
+
collect: collectInstallSecurityChecks
|
|
2591
|
+
},
|
|
2592
|
+
{
|
|
2593
|
+
ids: [
|
|
2594
|
+
"tool-package",
|
|
2595
|
+
"root-scripts",
|
|
2596
|
+
"tooling-imports"
|
|
2597
|
+
],
|
|
2598
|
+
collect: collectToolingChecks
|
|
2599
|
+
},
|
|
2600
|
+
{
|
|
2601
|
+
ids: [
|
|
2602
|
+
"release-workflow",
|
|
2603
|
+
"release-prerelease-state",
|
|
2604
|
+
"release-changeset-config",
|
|
2605
|
+
"release-cli-version",
|
|
2606
|
+
"release-versioning-config"
|
|
2607
|
+
],
|
|
2608
|
+
collect: (context, selected) => collectReleaseChecks(context.workspaceDir, context.packageJson, selected)
|
|
2609
|
+
}
|
|
2610
|
+
];
|
|
2611
|
+
/** Stable IDs shared by config, CLI, and report consumers. */
|
|
2612
|
+
function getDoctorRuleIds() {
|
|
2613
|
+
return collectors.flatMap((collector) => collector.ids);
|
|
2614
|
+
}
|
|
2615
|
+
function selectDoctorRules(rules) {
|
|
2616
|
+
const available = getDoctorRuleIds();
|
|
2617
|
+
if (rules === void 0) return new Set(available);
|
|
2618
|
+
if (!Array.isArray(rules) || rules.some((id) => typeof id !== "string" || !available.includes(id))) throw new Error(`Unknown or invalid doctor rules. Available: ${available.join(", ")}`);
|
|
2619
|
+
return new Set(rules);
|
|
2620
|
+
}
|
|
2621
|
+
async function collectSelectedDoctorChecks(context, selected) {
|
|
2622
|
+
const checks = [];
|
|
2623
|
+
for (const collector of collectors) if (collector.ids.some((id) => selected.has(id))) checks.push(...await collector.collect(context, selected));
|
|
2624
|
+
return checks;
|
|
2625
|
+
}
|
|
2626
|
+
//#endregion
|
|
2627
|
+
//#region src/commands/doctor/settings.ts
|
|
2628
|
+
/** C12 defaults drop nulls. Reject them in original layers before merging hides mistakes. */
|
|
2629
|
+
function validateDoctorConfiguration(value, field = "commands.doctor") {
|
|
2630
|
+
if (value === null) throw new Error(`${field} cannot be null; omit optional settings instead.`);
|
|
2631
|
+
if (value && typeof value === "object") for (const [key, child] of Object.entries(value)) validateDoctorConfiguration(child, `${field}.${key}`);
|
|
2632
|
+
}
|
|
2633
|
+
//#endregion
|
|
2634
|
+
//#region src/commands/doctor/suppressions.ts
|
|
2635
|
+
function isRecord(value) {
|
|
2636
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2637
|
+
}
|
|
2638
|
+
function validateDoctorSuppressions(value) {
|
|
2639
|
+
if (value === void 0) return [];
|
|
2640
|
+
if (!Array.isArray(value)) throw new TypeError("doctor.suppressions must be an array.");
|
|
2641
|
+
const ids = getDoctorRuleIds();
|
|
2642
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2643
|
+
return value.map((item) => {
|
|
2644
|
+
if (!isRecord(item) || typeof item["id"] !== "string" || !ids.includes(item["id"])) throw new Error(`Unknown doctor suppression ID. Available: ${ids.join(", ")}`);
|
|
2645
|
+
if (Object.keys(item).some((key) => ![
|
|
2646
|
+
"id",
|
|
2647
|
+
"reason",
|
|
2648
|
+
"expires",
|
|
2649
|
+
"path"
|
|
2650
|
+
].includes(key))) throw new Error(`Unknown doctor suppression field for ${item["id"]}. Use id, reason, expires, and path.`);
|
|
2651
|
+
if (typeof item["reason"] !== "string" || !item["reason"].trim()) throw new Error(`Doctor suppression ${item["id"]} requires a nonempty reason.`);
|
|
2652
|
+
const expires = item["expires"];
|
|
2653
|
+
if (expires !== void 0 && (typeof expires !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(expires) || Number.isNaN(Date.parse(expires)) || new Date(expires).toISOString().slice(0, 10) !== expires)) throw new Error(`Doctor suppression ${item["id"]} requires a valid YYYY-MM-DD expiry.`);
|
|
2654
|
+
const path = item["path"];
|
|
2655
|
+
if (path !== void 0 && (typeof path !== "string" || !path || path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..") || /^[a-z]:/i.test(path))) throw new Error(`Doctor suppression ${item["id"]} requires a workspace-relative path.`);
|
|
2656
|
+
const key = `${item["id"]}\0${path ?? ""}`;
|
|
2657
|
+
if (seen.has(key)) throw new Error(`Duplicate doctor suppression: ${item["id"]}.`);
|
|
2658
|
+
seen.add(key);
|
|
2659
|
+
return {
|
|
2660
|
+
id: item["id"],
|
|
2661
|
+
reason: item["reason"].trim(),
|
|
2662
|
+
...typeof expires === "string" ? { expires } : {},
|
|
2663
|
+
...typeof path === "string" ? { path } : {}
|
|
2664
|
+
};
|
|
2665
|
+
});
|
|
2666
|
+
}
|
|
2667
|
+
function applyDoctorSuppressions(checks, suppressions, now = /* @__PURE__ */ new Date()) {
|
|
2668
|
+
const today = now.toISOString().slice(0, 10);
|
|
2669
|
+
const reports = suppressions.map((suppression) => ({
|
|
2670
|
+
...suppression,
|
|
2671
|
+
state: suppression.expires && suppression.expires < today ? "expired" : "active",
|
|
2672
|
+
matched: checks.filter((check) => check.status !== "pass" && check.id === suppression.id && (suppression.path === void 0 || check.path === suppression.path)).length
|
|
2673
|
+
}));
|
|
2674
|
+
for (const check of checks) {
|
|
2675
|
+
if (check.status === "pass") continue;
|
|
2676
|
+
const matches = reports.filter((item) => item.id === check.id && (item.path === void 0 || item.path === check.path));
|
|
2677
|
+
const match = matches.find((item) => item.state === "active") ?? matches[0];
|
|
2678
|
+
if (match) {
|
|
2679
|
+
const { matched: _, ...suppression } = match;
|
|
2680
|
+
check.suppression = suppression;
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
return reports;
|
|
2684
|
+
}
|
|
2685
|
+
//#endregion
|
|
2686
|
+
//#region src/commands/template-drift/report.ts
|
|
2687
|
+
const cell = (value) => value.replaceAll("|", "\\|").replaceAll("\n", " ").replaceAll("\r", "");
|
|
2688
|
+
function hasTemplateDriftIssues(report, strict = false) {
|
|
2689
|
+
return report.summary.fail > 0 || strict && report.summary.warn > 0;
|
|
2690
|
+
}
|
|
2691
|
+
function formatTemplateDriftReport(report) {
|
|
2692
|
+
const lines = [
|
|
2693
|
+
"# Template drift report",
|
|
2694
|
+
"",
|
|
2695
|
+
`Workspace: ${cell(report.workspaceDir)}`,
|
|
2696
|
+
"",
|
|
2697
|
+
`Comparison: ${report.evidence.kind} / ${report.evidence.status} / ${report.evidence.version ?? "unknown"}. ${cell(report.evidence.detail)}`,
|
|
2698
|
+
"",
|
|
2699
|
+
`Instance registry: ${report.instanceRegistry.status}. ${cell(report.instanceRegistry.detail)}`,
|
|
2700
|
+
"",
|
|
2701
|
+
`Root baseline registry: ${report.rootRegistry.status}. ${cell(report.rootRegistry.detail)}`,
|
|
2702
|
+
"",
|
|
2703
|
+
"| Instance or root asset | Source | Retained version | Baseline | Version comparison | Local state |",
|
|
2704
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
2705
|
+
...report.owners.map((owner) => `| ${cell(`${owner.id} (${owner.path})`)} | ${cell(`${owner.source.packageName ?? owner.source.kind}:${owner.source.templatePath}`)} | ${cell(owner.source.version ?? "unversioned")} | ${owner.baseline.status} | ${owner.version.status} | ${owner.local} |`),
|
|
2706
|
+
"",
|
|
2707
|
+
"| Rule | Path | Status | Detail | Recommendation | Suppression |",
|
|
2708
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
2709
|
+
...report.checks.map((check) => `| ${check.id} | ${cell(check.path ?? "-")} | ${check.status} | ${cell(check.detail)} | ${cell(check.fix ?? "-")} | ${cell(check.suppression ? `${check.suppression.state}: ${check.suppression.reason}${check.suppression.expires ? ` (expires ${check.suppression.expires})` : ""}` : "-")} |`),
|
|
2710
|
+
"",
|
|
2711
|
+
`Effective: ${report.summary.pass} pass, ${report.summary.warn} warn, ${report.summary.fail} fail. Raw: ${report.rawSummary.pass} pass, ${report.rawSummary.warn} warn, ${report.rawSummary.fail} fail.`
|
|
2712
|
+
];
|
|
2713
|
+
for (const owner of report.owners) for (const recommendation of owner.recommendations) lines.push("", `- ${cell(owner.path)}: ${cell(recommendation)}`);
|
|
2714
|
+
for (const suppression of report.suppressions) lines.push("", `Suppression ${suppression.id}${suppression.path ? ` (${cell(suppression.path)})` : ""}: ${suppression.state}, ${suppression.matched} matched; ${cell(suppression.reason)}.`);
|
|
2715
|
+
return lines.join("\n");
|
|
2716
|
+
}
|
|
2717
|
+
//#endregion
|
|
2718
|
+
//#region src/commands/template-drift/index.ts
|
|
2719
|
+
var template_drift_exports = /* @__PURE__ */ __exportAll({
|
|
2720
|
+
checkTemplateDrift: () => checkTemplateDrift,
|
|
2721
|
+
formatTemplateDriftReport: () => formatTemplateDriftReport,
|
|
2722
|
+
hasTemplateDriftIssues: () => hasTemplateDriftIssues
|
|
2723
|
+
});
|
|
2724
|
+
async function checkTemplateDrift(cwd, options = {}) {
|
|
2725
|
+
const collection = await collectTemplateDrift(await findWorkspaceDir(cwd) ?? cwd, options);
|
|
2726
|
+
const { config, rawLayers } = await loadMonorepoConfigDetails(collection.workspaceDir, { refresh: true });
|
|
2727
|
+
for (const layer of rawLayers) validateDoctorConfiguration(layer.commands?.doctor);
|
|
2728
|
+
const suppressions = validateDoctorSuppressions(options.suppressions === void 0 ? config.commands?.doctor?.suppressions : options.suppressions);
|
|
2729
|
+
const checks = templateDriftChecks(collection);
|
|
2730
|
+
const reports = applyDoctorSuppressions(checks, suppressions);
|
|
2731
|
+
return {
|
|
2732
|
+
...collection,
|
|
2733
|
+
checks,
|
|
2734
|
+
summary: summarizeChecks(checks),
|
|
2735
|
+
rawSummary: summarizeChecks(checks, true),
|
|
2736
|
+
suppressions: reports
|
|
2737
|
+
};
|
|
2738
|
+
}
|
|
2739
|
+
//#endregion
|
|
2740
|
+
export { record$2 as A, baselineDirectory as C, parseBaseline as D, isRootAsset as E, toWorkspaceAssetPath as F, toWorkspaceGitignorePath as I, summarizeChecks as M, isGitignoreFile as N, templatePackage as O, toPublishGitignorePath as P, checkDependencyAdmission as S, encodeBaseline as T, releaseWorkflowMarker as _, applyDoctorSuppressions as a, parseWorkspaceLockfile as b, collectSelectedDoctorChecks as c, recommendedRepoScripts as d, inspectInstallSecurity as f, isLegacyReleaseWorkflow as g, supportedVersion as h, hasTemplateDriftIssues as i, getWorkspacePatterns as j, getAssetTargets as k, getDoctorRuleIds as l, settingState as m, template_drift_exports as n, validateDoctorSuppressions as o, readSecuritySources as p, formatTemplateDriftReport as r, validateDoctorConfiguration as s, checkTemplateDrift as t, selectDoctorRules as u, inspectPnpmRuntime as v, baselinePath as w, checkWorkspaceBoundaries as x, lockfileRecord as y };
|