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