@xiangyixie/dsh-superagent 0.9.3 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +210 -0
- package/LICENSE +21 -21
- package/README.md +422 -42
- package/bin/archive.js +185 -0
- package/bin/doctor.js +84 -0
- package/bin/report.js +79 -79
- package/bin/watch.js +57 -57
- package/cordis.patch.yml +9 -9
- package/lib/control.js +495 -494
- package/lib/cost.js +267 -0
- package/lib/doctor.js +876 -0
- package/lib/errors.js +205 -199
- package/lib/index.js +767 -42
- package/lib/ledger.js +270 -0
- package/lib/lock.js +107 -0
- package/lib/memory.js +736 -0
- package/lib/notify.js +257 -0
- package/lib/orchestrator.js +1975 -127
- package/lib/report.js +350 -15
- package/lib/store.js +503 -15
- package/lib/templates.js +690 -0
- package/lib/usage.js +152 -152
- package/lib/watch.js +422 -70
- package/lib/workspace.js +433 -0
- package/package.json +16 -3
package/lib/doctor.js
ADDED
|
@@ -0,0 +1,876 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only installation checks for dsh-superagent.
|
|
3
|
+
*
|
|
4
|
+
* Two real releases failed in the same shape: the package installed cleanly and
|
|
5
|
+
* then did nothing. One shipped an `index.js` that imported `lib/memory.js`,
|
|
6
|
+
* `lib/notify.js`, and `lib/lock.js` while `package.json` `files` left them out,
|
|
7
|
+
* so `npm pack` produced 15 files and the first `import` threw. Another profile
|
|
8
|
+
* was left half-unpacked by an interrupted install: `package.json` said 0.9.1
|
|
9
|
+
* while only five of eleven `lib` files existed, so the host could not mount
|
|
10
|
+
* the plugin and nothing said why.
|
|
11
|
+
*
|
|
12
|
+
* `doctor` compares the three layers that have to agree — what the code
|
|
13
|
+
* imports, what `files` promises, and what is actually on disk — plus the
|
|
14
|
+
* profile wiring and the registered tool count. It only reads: no install, no
|
|
15
|
+
* mount, no edit to the profile. The one write-free exception is the optional
|
|
16
|
+
* registry comparison, which downloads one public tarball to hash it.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-superagent/doctor
|
|
19
|
+
*/
|
|
20
|
+
import { exec, execFile } from 'node:child_process'
|
|
21
|
+
import { createHash } from 'node:crypto'
|
|
22
|
+
import fsp from 'node:fs/promises'
|
|
23
|
+
import os from 'node:os'
|
|
24
|
+
import path from 'node:path'
|
|
25
|
+
import { gunzipSync } from 'node:zlib'
|
|
26
|
+
|
|
27
|
+
export const PACKAGE_NAME = '@xiangyixie/dsh-superagent'
|
|
28
|
+
|
|
29
|
+
/** Tools this package version must register for the plugin to be complete. */
|
|
30
|
+
export const TOOL_NAMES = [
|
|
31
|
+
'superagent_start',
|
|
32
|
+
'superagent_status',
|
|
33
|
+
'superagent_list',
|
|
34
|
+
'superagent_cancel',
|
|
35
|
+
'superagent_resume',
|
|
36
|
+
'superagent_followup',
|
|
37
|
+
'superagent_answer',
|
|
38
|
+
'superagent_memory',
|
|
39
|
+
'superagent_template',
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
/** Files npm always includes, whether or not `files` lists them. */
|
|
43
|
+
const ALWAYS_PACKED = new Set(['package.json'])
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Relative import specifiers: `import x from './y.js'`, `export … from './y.js'`,
|
|
47
|
+
* and `import './y.js'`. Only specifiers that start with `.` are package files;
|
|
48
|
+
* bare names are built-ins or dependencies and are not ours to ship.
|
|
49
|
+
*/
|
|
50
|
+
const RELATIVE_IMPORT = /\b(?:from\s*|import\s*\(\s*|import\s*)['"](\.[^'"]+)['"]/g
|
|
51
|
+
|
|
52
|
+
export function normalizeRel(value) {
|
|
53
|
+
return String(value).replace(/\\/g, '/').replace(/^\.\//, '')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Remove comments while keeping string literals intact. A doc comment that
|
|
58
|
+
* mentions an import path must not become a dependency of the package.
|
|
59
|
+
*/
|
|
60
|
+
export function stripComments(source) {
|
|
61
|
+
const text = String(source)
|
|
62
|
+
let out = ''
|
|
63
|
+
let state = null
|
|
64
|
+
for (let index = 0; index < text.length; index++) {
|
|
65
|
+
const char = text[index]
|
|
66
|
+
const next = text[index + 1]
|
|
67
|
+
if (state === null) {
|
|
68
|
+
if (char === '/' && next === '/') {
|
|
69
|
+
state = 'line'
|
|
70
|
+
index += 1
|
|
71
|
+
} else if (char === '/' && next === '*') {
|
|
72
|
+
state = 'block'
|
|
73
|
+
index += 1
|
|
74
|
+
} else {
|
|
75
|
+
if (char === "'" || char === '"' || char === '`') state = char
|
|
76
|
+
out += char
|
|
77
|
+
}
|
|
78
|
+
} else if (state === 'line') {
|
|
79
|
+
if (char === '\n') {
|
|
80
|
+
state = null
|
|
81
|
+
out += char
|
|
82
|
+
}
|
|
83
|
+
} else if (state === 'block') {
|
|
84
|
+
if (char === '*' && next === '/') {
|
|
85
|
+
state = null
|
|
86
|
+
index += 1
|
|
87
|
+
} else if (char === '\n') {
|
|
88
|
+
out += char
|
|
89
|
+
}
|
|
90
|
+
} else {
|
|
91
|
+
out += char
|
|
92
|
+
if (char === '\\') {
|
|
93
|
+
if (index + 1 < text.length) out += text[++index]
|
|
94
|
+
} else if (char === state) {
|
|
95
|
+
state = null
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return out
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Every relative specifier a source file mentions, in order, without duplicates. */
|
|
103
|
+
export function scanRelativeImports(source) {
|
|
104
|
+
const found = new Set()
|
|
105
|
+
for (const match of stripComments(source).matchAll(RELATIVE_IMPORT)) {
|
|
106
|
+
if (match[1].startsWith('..') || match[1].startsWith('./')) found.add(match[1])
|
|
107
|
+
}
|
|
108
|
+
return [...found]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Tool names a plugin entry point registers.
|
|
113
|
+
*
|
|
114
|
+
* The registration call is split at `ctx.tools.register(` and the first `name:`
|
|
115
|
+
* in each chunk is the tool. That survives reformatting far better than one
|
|
116
|
+
* giant regular expression, and it still counts a registration whose body the
|
|
117
|
+
* parser would reject.
|
|
118
|
+
*/
|
|
119
|
+
export function readRegisteredTools(source) {
|
|
120
|
+
const names = []
|
|
121
|
+
for (const chunk of String(source).split('ctx.tools.register(').slice(1)) {
|
|
122
|
+
const match = /name:\s*['"]([^'"]+)['"]/.exec(chunk)
|
|
123
|
+
if (match) names.push(match[1])
|
|
124
|
+
}
|
|
125
|
+
return names
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parseVersion(value) {
|
|
129
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? '').trim())
|
|
130
|
+
return match ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) } : null
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function compareVersions(left, right) {
|
|
134
|
+
for (const key of ['major', 'minor', 'patch']) {
|
|
135
|
+
if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1
|
|
136
|
+
}
|
|
137
|
+
return 0
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function satisfiesToken(token, version) {
|
|
141
|
+
const match = /^(>=|<=|>|<|=|\^|~)?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(token)
|
|
142
|
+
if (!match) return false
|
|
143
|
+
const target = {
|
|
144
|
+
major: Number(match[2]),
|
|
145
|
+
minor: Number(match[3] ?? 0),
|
|
146
|
+
patch: Number(match[4] ?? 0),
|
|
147
|
+
}
|
|
148
|
+
const relation = compareVersions(version, target)
|
|
149
|
+
switch (match[1] ?? '=') {
|
|
150
|
+
case '>=': return relation >= 0
|
|
151
|
+
case '>': return relation > 0
|
|
152
|
+
case '<=': return relation <= 0
|
|
153
|
+
case '<': return relation < 0
|
|
154
|
+
case '=': return relation === 0
|
|
155
|
+
case '^': {
|
|
156
|
+
if (relation < 0) return false
|
|
157
|
+
const ceiling = target.major > 0
|
|
158
|
+
? { major: target.major + 1, minor: 0, patch: 0 }
|
|
159
|
+
: { major: 0, minor: target.minor + 1, patch: 0 }
|
|
160
|
+
return compareVersions(version, ceiling) < 0
|
|
161
|
+
}
|
|
162
|
+
case '~': {
|
|
163
|
+
if (relation < 0) return false
|
|
164
|
+
return compareVersions(version, { major: target.major, minor: target.minor + 1, patch: 0 }) < 0
|
|
165
|
+
}
|
|
166
|
+
default: return false
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Test a plain semver range against a version. Supports `||`, space-separated
|
|
172
|
+
* conjunctions, and the comparators an `engines` field actually uses. Anything
|
|
173
|
+
* it cannot parse fails closed, because "unknown range" must not read as "fine".
|
|
174
|
+
*/
|
|
175
|
+
export function satisfiesRange(range, version) {
|
|
176
|
+
const parsed = parseVersion(version)
|
|
177
|
+
if (!parsed) return false
|
|
178
|
+
const text = String(range ?? '').trim()
|
|
179
|
+
if (!text || text === '*') return true
|
|
180
|
+
return text.split('||').some(part => {
|
|
181
|
+
const tokens = part.trim().split(/\s+/).filter(Boolean)
|
|
182
|
+
return tokens.length === 0 || tokens.every(token => satisfiesToken(token, parsed))
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function exists(target) {
|
|
187
|
+
try {
|
|
188
|
+
await fsp.access(target)
|
|
189
|
+
return true
|
|
190
|
+
} catch {
|
|
191
|
+
return false
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export async function readPackageJson(packageRoot) {
|
|
196
|
+
const file = path.join(packageRoot, 'package.json')
|
|
197
|
+
let text
|
|
198
|
+
try {
|
|
199
|
+
text = await fsp.readFile(file, 'utf8')
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throw new Error(`cannot read ${file}: ${error?.message ?? error}`)
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
return JSON.parse(text)
|
|
205
|
+
} catch (error) {
|
|
206
|
+
throw new Error(`${file} is not valid JSON: ${error?.message ?? error}`)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function exportTargets(exportsField) {
|
|
211
|
+
const targets = []
|
|
212
|
+
const walk = value => {
|
|
213
|
+
if (typeof value === 'string') targets.push(value)
|
|
214
|
+
else if (Array.isArray(value)) value.forEach(walk)
|
|
215
|
+
else if (value && typeof value === 'object') Object.values(value).forEach(walk)
|
|
216
|
+
}
|
|
217
|
+
walk(exportsField)
|
|
218
|
+
return targets
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Resolve `./x.js` written in `fromRel` to a repo-relative path that exists. */
|
|
222
|
+
async function resolveLocalFile(packageRoot, fromRel, specifier) {
|
|
223
|
+
const joined = path.posix.normalize(path.posix.join(path.posix.dirname(fromRel), specifier))
|
|
224
|
+
if (joined.startsWith('..')) return null
|
|
225
|
+
const candidates = [joined]
|
|
226
|
+
if (!path.posix.extname(joined)) candidates.push(`${joined}.js`, `${joined}/index.js`)
|
|
227
|
+
for (const candidate of candidates) {
|
|
228
|
+
if (await exists(path.join(packageRoot, candidate))) return candidate
|
|
229
|
+
}
|
|
230
|
+
return joined
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Files the package cannot run without: entry points plus everything they
|
|
235
|
+
* import, transitively. `package.json` is included because `index.js` reads its
|
|
236
|
+
* version, but npm always packs it, so it needs no `files` entry.
|
|
237
|
+
*/
|
|
238
|
+
export async function requiredFiles(packageRoot) {
|
|
239
|
+
const pkg = await readPackageJson(packageRoot)
|
|
240
|
+
const roots = new Set()
|
|
241
|
+
const addRoot = value => {
|
|
242
|
+
if (typeof value === 'string' && value.trim()) roots.add(normalizeRel(value.trim()))
|
|
243
|
+
}
|
|
244
|
+
addRoot(pkg.main)
|
|
245
|
+
for (const value of Object.values(pkg.bin ?? {})) addRoot(value)
|
|
246
|
+
exportTargets(pkg.exports).forEach(addRoot)
|
|
247
|
+
addRoot(pkg.dsh?.bundle?.patch)
|
|
248
|
+
if (roots.size === 0) addRoot('lib/index.js')
|
|
249
|
+
|
|
250
|
+
const required = new Set()
|
|
251
|
+
const queue = [...roots]
|
|
252
|
+
while (queue.length > 0) {
|
|
253
|
+
const rel = queue.shift()
|
|
254
|
+
if (required.has(rel)) continue
|
|
255
|
+
required.add(rel)
|
|
256
|
+
if (!rel.endsWith('.js')) continue
|
|
257
|
+
let source
|
|
258
|
+
try {
|
|
259
|
+
source = await fsp.readFile(path.join(packageRoot, rel), 'utf8')
|
|
260
|
+
} catch {
|
|
261
|
+
continue
|
|
262
|
+
}
|
|
263
|
+
for (const specifier of scanRelativeImports(source)) {
|
|
264
|
+
const resolved = await resolveLocalFile(packageRoot, rel, specifier)
|
|
265
|
+
if (resolved && !required.has(resolved)) queue.push(resolved)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return [...required].sort()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function matchesFilesEntry(rel, entry) {
|
|
272
|
+
const pattern = normalizeRel(entry).replace(/\/+$/, '')
|
|
273
|
+
if (!pattern) return false
|
|
274
|
+
if (!pattern.includes('*')) return rel === pattern || rel.startsWith(`${pattern}/`)
|
|
275
|
+
const escaped = pattern
|
|
276
|
+
.split('*')
|
|
277
|
+
.map(part => part.replace(/[.+^${}()|[\]\\]/g, '\\$&'))
|
|
278
|
+
.join('[^/]*')
|
|
279
|
+
return new RegExp(`^${escaped}$`).test(rel) || new RegExp(`^${escaped}/`).test(rel)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Compare one package directory's imports, `files` whitelist, and disk contents.
|
|
284
|
+
* @param {string} packageRoot - absolute package directory.
|
|
285
|
+
*/
|
|
286
|
+
export async function auditLayout(packageRoot) {
|
|
287
|
+
const pkg = await readPackageJson(packageRoot)
|
|
288
|
+
const required = await requiredFiles(packageRoot)
|
|
289
|
+
const declared = Array.isArray(pkg.files) ? pkg.files.map(normalizeRel) : []
|
|
290
|
+
|
|
291
|
+
const missingFromDisk = []
|
|
292
|
+
for (const rel of required) {
|
|
293
|
+
if (!(await exists(path.join(packageRoot, rel)))) missingFromDisk.push(rel)
|
|
294
|
+
}
|
|
295
|
+
const uncovered = required.filter(rel => !ALWAYS_PACKED.has(rel)
|
|
296
|
+
&& !declared.some(entry => matchesFilesEntry(rel, entry)))
|
|
297
|
+
|
|
298
|
+
const missingDeclared = []
|
|
299
|
+
for (const entry of declared) {
|
|
300
|
+
if (entry.includes('*')) continue
|
|
301
|
+
if (!(await exists(path.join(packageRoot, entry)))) missingDeclared.push(entry)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
let libOnDisk = 0
|
|
305
|
+
try {
|
|
306
|
+
const entries = await fsp.readdir(path.join(packageRoot, 'lib'), { withFileTypes: true })
|
|
307
|
+
libOnDisk = entries.filter(entry => entry.isFile() && entry.name.endsWith('.js')).length
|
|
308
|
+
} catch {
|
|
309
|
+
libOnDisk = 0
|
|
310
|
+
}
|
|
311
|
+
const libDeclared = declared.filter(entry => /^lib\/[^/*]+\.js$/.test(entry)).length
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
packageRoot,
|
|
315
|
+
name: pkg.name ?? null,
|
|
316
|
+
version: pkg.version ?? null,
|
|
317
|
+
engines: pkg.engines ?? {},
|
|
318
|
+
declared,
|
|
319
|
+
required,
|
|
320
|
+
missingFromDisk,
|
|
321
|
+
uncovered,
|
|
322
|
+
missingDeclared,
|
|
323
|
+
libOnDisk,
|
|
324
|
+
libDeclared,
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Paths of everything `npm pack` would include, via a dry run (no tarball). */
|
|
329
|
+
export function packFileList(packageRoot) {
|
|
330
|
+
const args = 'pack --dry-run --json --ignore-scripts'
|
|
331
|
+
const options = { cwd: packageRoot, timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }
|
|
332
|
+
return new Promise((resolve, reject) => {
|
|
333
|
+
const done = (error, stdout, stderr) => {
|
|
334
|
+
if (error) {
|
|
335
|
+
reject(new Error(`npm pack --dry-run failed: ${(stderr || error.message || '').trim()}`))
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const start = stdout.indexOf('[')
|
|
340
|
+
const parsed = JSON.parse(start >= 0 ? stdout.slice(start) : stdout)
|
|
341
|
+
resolve((parsed[0]?.files ?? []).map(file => normalizeRel(file.path)))
|
|
342
|
+
} catch (parseError) {
|
|
343
|
+
reject(new Error(`cannot parse npm pack JSON: ${parseError.message}`))
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// npm is a .cmd shim on Windows, which needs a shell; the command string is
|
|
347
|
+
// composed only of literals, so there is nothing to escape.
|
|
348
|
+
if (process.platform === 'win32') exec(`npm ${args}`, options, done)
|
|
349
|
+
else execFile('npm', args.split(' '), options, done)
|
|
350
|
+
})
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The CI guard: every file the code imports must appear in the tarball, and
|
|
355
|
+
* every plain `files` entry must actually be packed. A `files` entry npm cannot
|
|
356
|
+
* find is silently skipped, which is how an import ships a promise instead of a
|
|
357
|
+
* module.
|
|
358
|
+
* @param {{ packageRoot: string, packed: string[] }} input - dry-run file list.
|
|
359
|
+
*/
|
|
360
|
+
export async function auditPackedFiles({ packageRoot, packed }) {
|
|
361
|
+
const layout = await auditLayout(packageRoot)
|
|
362
|
+
const shipped = new Set(packed.map(normalizeRel))
|
|
363
|
+
const missing = layout.required.filter(rel => !ALWAYS_PACKED.has(rel) && !shipped.has(rel))
|
|
364
|
+
const notPacked = layout.declared.filter(entry => !entry.includes('*')
|
|
365
|
+
&& !ALWAYS_PACKED.has(entry)
|
|
366
|
+
&& !shipped.has(entry))
|
|
367
|
+
return { ...layout, packed: [...shipped], missing, notPacked }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function readTarString(header, start, length) {
|
|
371
|
+
return header.toString('utf8', start, start + length).replace(/\0.*$/s, '').trimEnd()
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Minimal ustar reader: only what a published npm tarball contains. Returns
|
|
376
|
+
* regular files with their bytes, so hashes can be compared without unpacking
|
|
377
|
+
* to disk.
|
|
378
|
+
*/
|
|
379
|
+
export function readTarEntries(buffer) {
|
|
380
|
+
const data = buffer[0] === 0x1f && buffer[1] === 0x8b ? gunzipSync(buffer) : buffer
|
|
381
|
+
const entries = []
|
|
382
|
+
let offset = 0
|
|
383
|
+
while (offset + 512 <= data.length) {
|
|
384
|
+
const header = data.subarray(offset, offset + 512)
|
|
385
|
+
if (header.every(byte => byte === 0)) break
|
|
386
|
+
const name = readTarString(header, 0, 100)
|
|
387
|
+
const prefix = readTarString(header, 345, 155)
|
|
388
|
+
const size = Number.parseInt(readTarString(header, 124, 12), 8) || 0
|
|
389
|
+
const type = String.fromCharCode(header[156] || 48)
|
|
390
|
+
offset += 512
|
|
391
|
+
const fullName = normalizeRel(prefix ? `${prefix}/${name}` : name)
|
|
392
|
+
if (type === '0' || type === '\0' || type === '7') {
|
|
393
|
+
entries.push({ name: fullName.replace(/^package\//, ''), data: data.subarray(offset, offset + size) })
|
|
394
|
+
}
|
|
395
|
+
offset += Math.ceil(size / 512) * 512
|
|
396
|
+
}
|
|
397
|
+
return entries
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function sha256(data) {
|
|
401
|
+
return createHash('sha256').update(data).digest('hex')
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Compare the files of the installed copy with the published tarball for the
|
|
406
|
+
* same version. Networks are optional: an unreachable registry degrades this
|
|
407
|
+
* check to a warning with the command that would confirm it by hand.
|
|
408
|
+
* @param {object} input - package directory, fetch implementation, timeout.
|
|
409
|
+
*/
|
|
410
|
+
export async function auditRegistry({ packageRoot, fetchImpl = globalThis.fetch, timeoutMs = 8000, profileName = null } = {}) {
|
|
411
|
+
const pkg = await readPackageJson(packageRoot)
|
|
412
|
+
const name = pkg.name ?? PACKAGE_NAME
|
|
413
|
+
const version = pkg.version ?? '0.0.0'
|
|
414
|
+
const registry = String(pkg.publishConfig?.registry ?? 'https://registry.npmjs.org').replace(/\/+$/, '')
|
|
415
|
+
const metadataUrl = `${registry}/${name.replace('/', '%2F')}/${version}`
|
|
416
|
+
const offlineFix = `npm view ${name}@${version} dist.tarball`
|
|
417
|
+
|
|
418
|
+
if (typeof fetchImpl !== 'function') {
|
|
419
|
+
return { status: 'warn', detail: ['no fetch implementation; registry comparison skipped'], fix: offlineFix }
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
const metaResponse = await fetchImpl(metadataUrl, {
|
|
423
|
+
headers: { accept: 'application/json' },
|
|
424
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
425
|
+
})
|
|
426
|
+
if (!metaResponse.ok) throw new Error(`registry returned HTTP ${metaResponse.status}`)
|
|
427
|
+
const meta = await metaResponse.json()
|
|
428
|
+
const tarballUrl = meta?.dist?.tarball
|
|
429
|
+
if (!tarballUrl) throw new Error('registry metadata has no dist.tarball')
|
|
430
|
+
|
|
431
|
+
const tarResponse = await fetchImpl(tarballUrl, { signal: AbortSignal.timeout(timeoutMs) })
|
|
432
|
+
if (!tarResponse.ok) throw new Error(`tarball returned HTTP ${tarResponse.status}`)
|
|
433
|
+
const tarball = Buffer.from(await tarResponse.arrayBuffer())
|
|
434
|
+
const published = new Map(readTarEntries(tarball).map(entry => [entry.name, sha256(entry.data)]))
|
|
435
|
+
|
|
436
|
+
const missing = []
|
|
437
|
+
const different = []
|
|
438
|
+
let compared = 0
|
|
439
|
+
for (const [file, digest] of published) {
|
|
440
|
+
// package.json is rewritten by tooling on some installs; the version field
|
|
441
|
+
// is checked by the layout audit instead of by byte equality.
|
|
442
|
+
if (file === 'package.json') continue
|
|
443
|
+
let local
|
|
444
|
+
try {
|
|
445
|
+
local = await fsp.readFile(path.join(packageRoot, file))
|
|
446
|
+
} catch {
|
|
447
|
+
missing.push(file)
|
|
448
|
+
continue
|
|
449
|
+
}
|
|
450
|
+
compared += 1
|
|
451
|
+
if (sha256(local) !== digest) different.push(file)
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const extra = []
|
|
455
|
+
for (const file of await listFilesRecursive(packageRoot)) {
|
|
456
|
+
if (file === 'package.json') continue
|
|
457
|
+
if (!published.has(file)) extra.push(file)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (missing.length > 0 || different.length > 0) {
|
|
461
|
+
const detail = []
|
|
462
|
+
if (missing.length > 0) {
|
|
463
|
+
detail.push(`${missing.length} published file(s) are missing from the installed copy:`)
|
|
464
|
+
detail.push(...missing.slice(0, 8).map(file => ` ${file}`))
|
|
465
|
+
}
|
|
466
|
+
if (different.length > 0) {
|
|
467
|
+
detail.push(`${different.length} file(s) differ from ${name}@${version}:`)
|
|
468
|
+
detail.push(...different.slice(0, 8).map(file => ` ${file}`))
|
|
469
|
+
}
|
|
470
|
+
return {
|
|
471
|
+
status: 'fail',
|
|
472
|
+
detail,
|
|
473
|
+
fix: 'this copy is not the published artifact; reinstall it from the registry:\n'
|
|
474
|
+
+ reinstallCommand(profileName, version)
|
|
475
|
+
+ '\n# if it came from a local tarball, rebuild that tarball and reinstall it instead',
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
const detail = [`${compared} file(s) match ${name}@${version} by sha256`]
|
|
479
|
+
if (extra.length > 0) detail.push(`${extra.length} local file(s) are not in the published tarball: ${extra.slice(0, 5).join(', ')}`)
|
|
480
|
+
return { status: extra.length > 0 ? 'warn' : 'pass', detail }
|
|
481
|
+
} catch (error) {
|
|
482
|
+
return {
|
|
483
|
+
status: 'warn',
|
|
484
|
+
detail: [`registry comparison skipped: ${error?.message ?? error}`, 'offline is fine; the other checks still ran'],
|
|
485
|
+
fix: offlineFix,
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async function listFilesRecursive(root) {
|
|
491
|
+
const found = []
|
|
492
|
+
const walk = async dir => {
|
|
493
|
+
let entries
|
|
494
|
+
try {
|
|
495
|
+
entries = await fsp.readdir(dir, { withFileTypes: true })
|
|
496
|
+
} catch {
|
|
497
|
+
return
|
|
498
|
+
}
|
|
499
|
+
for (const entry of entries) {
|
|
500
|
+
const abs = path.join(dir, entry.name)
|
|
501
|
+
if (entry.isDirectory()) await walk(abs)
|
|
502
|
+
else if (entry.isFile()) found.push(normalizeRel(path.relative(root, abs)))
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
await walk(root)
|
|
506
|
+
return found.sort()
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Resolve `--profile web` to `<DSH_HOME>/profiles/web`; a path is used as-is. */
|
|
510
|
+
export function resolveProfileDir(profile, dshHome) {
|
|
511
|
+
if (!profile) return null
|
|
512
|
+
if (profile === '.' || profile === '..' || profile.includes('/') || profile.includes('\\')) {
|
|
513
|
+
return path.resolve(profile)
|
|
514
|
+
}
|
|
515
|
+
return path.join(dshHome, 'profiles', profile)
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Infer the profile from a package path such as
|
|
520
|
+
* `<DSH_HOME>/profiles/web/node_modules/@xiangyixie/dsh-superagent`.
|
|
521
|
+
*/
|
|
522
|
+
export function inferProfileDir(packageRoot) {
|
|
523
|
+
const parts = path.resolve(packageRoot).split(path.sep)
|
|
524
|
+
const index = parts.lastIndexOf('profiles')
|
|
525
|
+
if (index < 0 || index + 1 >= parts.length) return null
|
|
526
|
+
const name = parts[index + 1]
|
|
527
|
+
if (!name || name === 'node_modules') return null
|
|
528
|
+
return parts.slice(0, index + 2).join(path.sep)
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function reinstallCommand(profileName, version) {
|
|
532
|
+
return `dsh plugin --profile ${profileName ?? '<profile>'} add ${PACKAGE_NAME}@${version ?? '<version>'}`
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function cleanCopyCommand(packageDir) {
|
|
536
|
+
return process.platform === 'win32'
|
|
537
|
+
? `Remove-Item -Recurse -Force "${packageDir}"`
|
|
538
|
+
: `rm -rf "${packageDir}"`
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function check(id, title, status, detail = [], fix = null) {
|
|
542
|
+
return { id, title, status, detail, fix }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function checkNodeEngine(layout, nodeVersion) {
|
|
546
|
+
const range = layout.engines?.node
|
|
547
|
+
if (!range) {
|
|
548
|
+
return check('node-engine', 'Node version', 'warn', ['package.json declares no engines.node, so no minimum is enforced'])
|
|
549
|
+
}
|
|
550
|
+
if (satisfiesRange(range, nodeVersion)) {
|
|
551
|
+
return check('node-engine', 'Node version', 'pass', [`v${nodeVersion} satisfies "${range}"`])
|
|
552
|
+
}
|
|
553
|
+
return check('node-engine', 'Node version', 'fail', [
|
|
554
|
+
`installed Node is v${nodeVersion}, but package.json requires "${range}"`,
|
|
555
|
+
'the host and this package are running on an unsupported Node; imports can fail at startup',
|
|
556
|
+
], `install Node ${range} (or newer) and run the host on it:\nnode --version`)
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function checkFilesCoverage(layout, { profileName }) {
|
|
560
|
+
const detail = []
|
|
561
|
+
if (layout.uncovered.length > 0) {
|
|
562
|
+
detail.push(`${layout.uncovered.length} imported file(s) are not matched by package.json "files":`)
|
|
563
|
+
detail.push(...layout.uncovered.slice(0, 8).map(file => ` ${file}`))
|
|
564
|
+
if (layout.uncovered.length > 8) detail.push(` ... and ${layout.uncovered.length - 8} more`)
|
|
565
|
+
}
|
|
566
|
+
if (layout.missingFromDisk.length > 0) {
|
|
567
|
+
detail.push(`${layout.missingFromDisk.length} imported file(s) do not exist on disk:`)
|
|
568
|
+
detail.push(...layout.missingFromDisk.slice(0, 8).map(file => ` ${file}`))
|
|
569
|
+
}
|
|
570
|
+
if (detail.length === 0) {
|
|
571
|
+
return check('package-files', 'Package files', 'pass', [
|
|
572
|
+
`${layout.required.length} file(s) reachable from the entry points; all are shipped by "files"`,
|
|
573
|
+
])
|
|
574
|
+
}
|
|
575
|
+
const fixLines = []
|
|
576
|
+
if (layout.uncovered.length > 0) {
|
|
577
|
+
fixLines.push('add the missing entry to "files" in package.json, then pack and reinstall:')
|
|
578
|
+
fixLines.push(...layout.uncovered.slice(0, 8).map(file => ` "${file}"`))
|
|
579
|
+
fixLines.push('npm pack --dry-run --json')
|
|
580
|
+
}
|
|
581
|
+
if (layout.missingFromDisk.length > 0) {
|
|
582
|
+
fixLines.push('restore the file from git, or reinstall a complete copy:')
|
|
583
|
+
fixLines.push(reinstallCommand(profileName, layout.version))
|
|
584
|
+
}
|
|
585
|
+
return check('package-files', 'Package files', 'fail', detail, fixLines.join('\n'))
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function checkInstalledCopy(layout, { profileName }) {
|
|
589
|
+
if (layout.missingDeclared.length === 0 && layout.libDeclared <= layout.libOnDisk) {
|
|
590
|
+
return check('installed-copy', 'Installed copy', 'pass', [
|
|
591
|
+
`package.json ${layout.version ?? '(no version)'} declares ${layout.declared.length} packed file(s); `
|
|
592
|
+
+ `${layout.libOnDisk} lib file(s) on disk`,
|
|
593
|
+
])
|
|
594
|
+
}
|
|
595
|
+
const detail = [
|
|
596
|
+
`package.json says version ${layout.version ?? '(none)'} and "files" lists ${layout.libDeclared} lib file(s), `
|
|
597
|
+
+ `but only ${layout.libOnDisk} are on disk`,
|
|
598
|
+
]
|
|
599
|
+
if (layout.missingDeclared.length > 0) {
|
|
600
|
+
detail.push(`${layout.missingDeclared.length} declared file(s) are absent:`)
|
|
601
|
+
detail.push(...layout.missingDeclared.slice(0, 8).map(file => ` ${file}`))
|
|
602
|
+
if (layout.missingDeclared.length > 8) detail.push(` ... and ${layout.missingDeclared.length - 8} more`)
|
|
603
|
+
}
|
|
604
|
+
detail.push('this is what an interrupted install leaves behind: package.json is complete, the unpacked tree is not')
|
|
605
|
+
return check('installed-copy', 'Installed copy', 'fail', detail, [
|
|
606
|
+
'remove the partial copy and install it again:',
|
|
607
|
+
cleanCopyCommand(layout.packageRoot),
|
|
608
|
+
reinstallCommand(profileName, layout.version),
|
|
609
|
+
].join('\n'))
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function checkSyntax(packageRoot, required, { profileName, version }) {
|
|
613
|
+
return new Promise(resolve => {
|
|
614
|
+
const files = required.filter(file => file.endsWith('.js'))
|
|
615
|
+
const broken = []
|
|
616
|
+
const verify = index => {
|
|
617
|
+
if (index >= files.length) {
|
|
618
|
+
if (broken.length === 0) {
|
|
619
|
+
resolve(check('syntax', 'File syntax', 'pass', [`${files.length} shipped JavaScript file(s) parse`]))
|
|
620
|
+
return
|
|
621
|
+
}
|
|
622
|
+
resolve(check('syntax', 'File syntax', 'fail', [
|
|
623
|
+
`${broken.length} shipped file(s) cannot be parsed (truncated by a partial unpack or a broken build):`,
|
|
624
|
+
...broken.map(item => ` ${item.file}: ${item.reason}`),
|
|
625
|
+
], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`))
|
|
626
|
+
return
|
|
627
|
+
}
|
|
628
|
+
const file = files[index]
|
|
629
|
+
execFile(process.execPath, ['--check', path.join(packageRoot, file)], { timeout: 20_000 }, (error, _stdout, stderr) => {
|
|
630
|
+
if (error) {
|
|
631
|
+
const reason = String(stderr || error.message).split('\n').find(line => line.trim()) ?? 'parse error'
|
|
632
|
+
broken.push({ file, reason: reason.replace(/^.*?Error:\s*/, '').trim() })
|
|
633
|
+
}
|
|
634
|
+
verify(index + 1)
|
|
635
|
+
})
|
|
636
|
+
}
|
|
637
|
+
verify(0)
|
|
638
|
+
})
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async function checkTools(packageDir, expected, { profileName, version }) {
|
|
642
|
+
const entry = path.join(packageDir, 'lib', 'index.js')
|
|
643
|
+
let source
|
|
644
|
+
try {
|
|
645
|
+
source = await fsp.readFile(entry, 'utf8')
|
|
646
|
+
} catch {
|
|
647
|
+
return check('tools', 'Registered tools', 'fail', [
|
|
648
|
+
`cannot read ${entry}`,
|
|
649
|
+
'without the entry point the host mounts no tools at all',
|
|
650
|
+
], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`)
|
|
651
|
+
}
|
|
652
|
+
const names = readRegisteredTools(source)
|
|
653
|
+
const missing = expected.filter(name => !names.includes(name))
|
|
654
|
+
const extra = names.filter(name => !expected.includes(name))
|
|
655
|
+
if (missing.length === 0 && extra.length === 0) {
|
|
656
|
+
return check('tools', 'Registered tools', 'pass', [`${names.length}/${expected.length} expected tools are registered`])
|
|
657
|
+
}
|
|
658
|
+
const detail = [`registered ${names.length} of ${expected.length} expected tools`]
|
|
659
|
+
if (missing.length > 0) detail.push(`missing: ${missing.join(', ')}`)
|
|
660
|
+
if (extra.length > 0) detail.push(`unexpected: ${extra.join(', ')}`)
|
|
661
|
+
return check('tools', 'Registered tools', 'fail', detail, [
|
|
662
|
+
'this copy registers a different tool set than the version claims; reinstall it:',
|
|
663
|
+
reinstallCommand(profileName, version),
|
|
664
|
+
].join('\n'))
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async function checkPatchFile(packageDir, pkg, { profileName }) {
|
|
668
|
+
const patchRel = pkg?.dsh?.bundle?.patch
|
|
669
|
+
if (typeof patchRel !== 'string' || !patchRel.trim()) {
|
|
670
|
+
return check('patch', 'Bundle patch', 'fail', [
|
|
671
|
+
'package.json has no dsh.bundle.patch, so the host has no row to mount',
|
|
672
|
+
], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
|
|
673
|
+
}
|
|
674
|
+
const file = path.join(packageDir, normalizeRel(patchRel))
|
|
675
|
+
let text
|
|
676
|
+
try {
|
|
677
|
+
text = await fsp.readFile(file, 'utf8')
|
|
678
|
+
} catch {
|
|
679
|
+
return check('patch', 'Bundle patch', 'fail', [
|
|
680
|
+
`package.json points at ${patchRel}, but that file is not in the package`,
|
|
681
|
+
], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
|
|
682
|
+
}
|
|
683
|
+
const namesPackage = text.includes(pkg?.name ?? PACKAGE_NAME)
|
|
684
|
+
const inserts = /(^|\n)\s*-\s*insert:/.test(text)
|
|
685
|
+
if (!inserts || !namesPackage) {
|
|
686
|
+
return check('patch', 'Bundle patch', 'fail', [
|
|
687
|
+
`${patchRel} does not insert a row for ${pkg?.name ?? PACKAGE_NAME}`,
|
|
688
|
+
'without the row the plugin is installed but never mounted',
|
|
689
|
+
], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
|
|
690
|
+
}
|
|
691
|
+
return check('patch', 'Bundle patch', 'pass', [`${patchRel} inserts the plugin row at profile scope`])
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
async function checkProfile(profileDir, profileName) {
|
|
695
|
+
if (!(await exists(profileDir))) {
|
|
696
|
+
return check('profile', 'DSH profile', 'fail', [
|
|
697
|
+
`no profile at ${profileDir}`,
|
|
698
|
+
'nothing is installed there, so no superagent tool can exist in it',
|
|
699
|
+
], `${reinstallCommand(profileName, null)}\n# if DSH_HOME points elsewhere, pass the full path: --profile "<path>"`)
|
|
700
|
+
}
|
|
701
|
+
const detail = []
|
|
702
|
+
try {
|
|
703
|
+
await readPackageJson(profileDir)
|
|
704
|
+
} catch (error) {
|
|
705
|
+
return check('profile', 'DSH profile', 'fail', [String(error.message)], [
|
|
706
|
+
'make the profile readable, then reinstall the plugin:',
|
|
707
|
+
reinstallCommand(profileName, null),
|
|
708
|
+
].join('\n'))
|
|
709
|
+
}
|
|
710
|
+
const hasNodeModules = await exists(path.join(profileDir, 'node_modules'))
|
|
711
|
+
const hasRoot = await exists(path.join(profileDir, 'cordis.yml'))
|
|
712
|
+
if (!hasNodeModules) {
|
|
713
|
+
detail.push('node_modules is missing, so no plugin copy is installed')
|
|
714
|
+
}
|
|
715
|
+
if (!hasRoot) {
|
|
716
|
+
detail.push('cordis.yml is missing; the host composes an empty root, which usually still works')
|
|
717
|
+
}
|
|
718
|
+
if (!hasNodeModules) {
|
|
719
|
+
return check('profile', 'DSH profile', 'fail', detail, [
|
|
720
|
+
'install the plugin into this profile:',
|
|
721
|
+
reinstallCommand(profileName, null),
|
|
722
|
+
].join('\n'))
|
|
723
|
+
}
|
|
724
|
+
return check('profile', 'DSH profile', hasRoot ? 'pass' : 'warn', detail.length > 0
|
|
725
|
+
? detail
|
|
726
|
+
: [`${profileDir} has package.json, cordis.yml, and node_modules`])
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
async function checkBundle(profileDir, packageName, profileName, version) {
|
|
730
|
+
try {
|
|
731
|
+
const pkg = await readPackageJson(profileDir)
|
|
732
|
+
const bundles = pkg?.dsh?.profile?.bundles
|
|
733
|
+
if (Array.isArray(bundles) && bundles.includes(packageName)) {
|
|
734
|
+
return check('bundle', 'Profile registration', 'pass', [
|
|
735
|
+
`dsh.profile.bundles includes ${packageName}`,
|
|
736
|
+
])
|
|
737
|
+
}
|
|
738
|
+
return check('bundle', 'Profile registration', 'fail', [
|
|
739
|
+
`${packageName} is not in dsh.profile.bundles, so its cordis.patch.yml is never loaded`,
|
|
740
|
+
'the installed files are fine; the profile simply does not mount them',
|
|
741
|
+
], `${reinstallCommand(profileName, version)}\n# then confirm the row appears:\ndsh --profile ${profileName ?? '<profile>'} --dump-config`)
|
|
742
|
+
} catch (error) {
|
|
743
|
+
return check('bundle', 'Profile registration', 'fail', [String(error.message)])
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
async function checkVersionDrift(packageRoot, targetDir, profileName) {
|
|
748
|
+
if (path.resolve(packageRoot) === path.resolve(targetDir)) return null
|
|
749
|
+
try {
|
|
750
|
+
const checkout = await readPackageJson(packageRoot)
|
|
751
|
+
const installed = await readPackageJson(targetDir)
|
|
752
|
+
if (checkout.version === installed.version) return null
|
|
753
|
+
return check('version', 'Version match', 'warn', [
|
|
754
|
+
`installed copy is ${installed.version}, this checkout is ${checkout.version}`,
|
|
755
|
+
`${targetDir} did not come from this source tree; reinstall it before trusting a fix here`,
|
|
756
|
+
], reinstallCommand(profileName, checkout.version))
|
|
757
|
+
} catch {
|
|
758
|
+
return null
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Run every check and return structured results. Rendering is separate so the
|
|
764
|
+
* CLI and the tests see the same verdicts.
|
|
765
|
+
* @param {object} [options] - paths, offline switch, and injectable fetch.
|
|
766
|
+
*/
|
|
767
|
+
export async function runDoctor(options = {}) {
|
|
768
|
+
const packageRoot = path.resolve(options.packageRoot ?? process.cwd())
|
|
769
|
+
const dshHome = options.dshHome ?? process.env.DSH_HOME?.trim() ?? path.join(os.homedir(), '.dsh')
|
|
770
|
+
const profileDir = options.profile === undefined
|
|
771
|
+
? inferProfileDir(packageRoot)
|
|
772
|
+
: resolveProfileDir(options.profile, dshHome)
|
|
773
|
+
const profileName = profileDir ? path.basename(profileDir) : null
|
|
774
|
+
const nodeVersion = options.nodeVersion ?? process.versions.node
|
|
775
|
+
|
|
776
|
+
let pkg
|
|
777
|
+
try {
|
|
778
|
+
pkg = await readPackageJson(packageRoot)
|
|
779
|
+
} catch (error) {
|
|
780
|
+
return {
|
|
781
|
+
packageRoot,
|
|
782
|
+
profileDir,
|
|
783
|
+
profileName,
|
|
784
|
+
targetDir: packageRoot,
|
|
785
|
+
version: null,
|
|
786
|
+
nodeVersion,
|
|
787
|
+
ok: false,
|
|
788
|
+
checks: [check('package', 'Package', 'fail', [String(error.message)], 'run this command from an installed copy or pass --package <dir>')],
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
const packageName = pkg.name ?? PACKAGE_NAME
|
|
792
|
+
const candidate = profileDir
|
|
793
|
+
? path.join(profileDir, 'node_modules', ...packageName.split('/'))
|
|
794
|
+
: null
|
|
795
|
+
const installedDir = candidate && await exists(candidate) ? candidate : null
|
|
796
|
+
const targetDir = installedDir ?? packageRoot
|
|
797
|
+
const targetPkg = installedDir ? await readPackageJson(installedDir).catch(() => pkg) : pkg
|
|
798
|
+
|
|
799
|
+
const layout = await auditLayout(targetDir)
|
|
800
|
+
const checks = []
|
|
801
|
+
checks.push(checkNodeEngine(layout, nodeVersion))
|
|
802
|
+
checks.push(checkFilesCoverage(layout, { profileName }))
|
|
803
|
+
checks.push(checkInstalledCopy(layout, { profileName }))
|
|
804
|
+
checks.push(await checkSyntax(targetDir, layout.required, { profileName, version: targetPkg.version }))
|
|
805
|
+
if (options.online === false) {
|
|
806
|
+
checks.push(check('registry', 'Registry match', 'warn', ['registry comparison skipped (--offline)'], `npm view ${packageName}@${targetPkg.version} dist.tarball`))
|
|
807
|
+
} else {
|
|
808
|
+
const registry = await auditRegistry({
|
|
809
|
+
packageRoot: targetDir,
|
|
810
|
+
fetchImpl: options.fetchImpl,
|
|
811
|
+
timeoutMs: options.registryTimeoutMs,
|
|
812
|
+
profileName,
|
|
813
|
+
})
|
|
814
|
+
checks.push(check('registry', 'Registry match', registry.status, registry.detail, registry.fix ?? null))
|
|
815
|
+
}
|
|
816
|
+
checks.push(await checkTools(targetDir, options.expectedTools ?? TOOL_NAMES, { profileName, version: targetPkg.version }))
|
|
817
|
+
checks.push(await checkPatchFile(targetDir, targetPkg, { profileName }))
|
|
818
|
+
if (profileDir) {
|
|
819
|
+
checks.push(await checkProfile(profileDir, profileName))
|
|
820
|
+
checks.push(await checkBundle(profileDir, packageName, profileName, targetPkg.version))
|
|
821
|
+
const drift = await checkVersionDrift(packageRoot, targetDir, profileName)
|
|
822
|
+
if (drift) checks.push(drift)
|
|
823
|
+
} else {
|
|
824
|
+
checks.push(check('profile', 'DSH profile', 'warn', [
|
|
825
|
+
'no profile given, so profile wiring was not checked',
|
|
826
|
+
'run again with --profile <name> (for example: --profile web)',
|
|
827
|
+
]))
|
|
828
|
+
}
|
|
829
|
+
const counts = { pass: 0, warn: 0, fail: 0 }
|
|
830
|
+
for (const item of checks) counts[item.status] += 1
|
|
831
|
+
return {
|
|
832
|
+
packageRoot,
|
|
833
|
+
profileDir,
|
|
834
|
+
profileName,
|
|
835
|
+
targetDir,
|
|
836
|
+
version: targetPkg.version ?? null,
|
|
837
|
+
nodeVersion,
|
|
838
|
+
checks,
|
|
839
|
+
counts,
|
|
840
|
+
ok: counts.fail === 0,
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const STATUS_COLOR = { pass: '32', warn: '33', fail: '31' }
|
|
845
|
+
const STATUS_LABEL = { pass: 'PASS', warn: 'WARN', fail: 'FAIL' }
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Human report: one block per check, then the exact commands that fix what is
|
|
849
|
+
* broken. Commands sit on their own lines so they can be copied verbatim.
|
|
850
|
+
*/
|
|
851
|
+
export function renderReport(result, { color = false } = {}) {
|
|
852
|
+
const paint = (code, text) => (color ? `\x1b[${code}m${text}\x1b[0m` : text)
|
|
853
|
+
const lines = [
|
|
854
|
+
`dsh-superagent doctor${result.version ? ` ${result.version}` : ''}`,
|
|
855
|
+
`node v${result.nodeVersion} · ${process.platform}`,
|
|
856
|
+
`package: ${result.targetDir}`,
|
|
857
|
+
result.profileDir
|
|
858
|
+
? `profile: ${result.profileDir}`
|
|
859
|
+
: 'profile: not specified (pass --profile <name> to check a DSH profile)',
|
|
860
|
+
'',
|
|
861
|
+
]
|
|
862
|
+
for (const item of result.checks) {
|
|
863
|
+
lines.push(`${paint(STATUS_COLOR[item.status], `[${STATUS_LABEL[item.status]}]`)} ${item.title}`)
|
|
864
|
+
for (const detail of item.detail ?? []) lines.push(` ${detail}`)
|
|
865
|
+
if (item.fix) {
|
|
866
|
+
lines.push(' fix:')
|
|
867
|
+
for (const fixLine of item.fix.split('\n')) lines.push(` ${fixLine}`)
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
const { pass, warn, fail } = result.counts
|
|
871
|
+
lines.push('', `${fail} failed, ${warn} warning(s), ${pass} passed`)
|
|
872
|
+
lines.push(fail === 0
|
|
873
|
+
? 'no blocking problem found: this copy matches what it claims to be'
|
|
874
|
+
: 'blocking checks failed; run the fix lines above, then re-run doctor')
|
|
875
|
+
return lines.join('\n')
|
|
876
|
+
}
|