dsh-coexist-cli 0.0.0-stage → 0.1.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/src/report.js ADDED
@@ -0,0 +1,542 @@
1
+ export function renderGraph(graph) {
2
+ const lines = []
3
+ lines.push(`DSH home: ${graph.home}`)
4
+ lines.push(`Profile: ${graph.profile}`)
5
+ if (graph.hostVersion) {
6
+ lines.push(`Host: ${graph.hostVersion}${graph.hostChanged ? ' (changed since last check)' : ''}`)
7
+ }
8
+ lines.push(`Bundles: ${graph.bundles.length}`)
9
+
10
+ const bundlePatches = (graph.bundleInfo ?? []).filter((info) => info.patch)
11
+ if (bundlePatches.length > 0) {
12
+ lines.push(`Bundle patches: ${bundlePatches.length}`)
13
+ }
14
+ const patchErrors = (graph.bundleInfo ?? []).filter((info) => info.patchError)
15
+ if (patchErrors.length > 0) {
16
+ lines.push(`Bundle patches failed to parse: ${patchErrors.length}`)
17
+ for (const info of patchErrors) {
18
+ lines.push(` - ${info.name}: ${info.patchError}`)
19
+ }
20
+ }
21
+ lines.push(`Patch files: ${graph.patches.map((patch) => patch.file).join(', ') || '(none)'}`)
22
+
23
+ const conflicts = graph.conflicts.filter((conflict) => conflict.severity !== 'info')
24
+ const overrides = graph.conflicts.filter((conflict) => conflict.severity === 'info')
25
+
26
+ if (conflicts.length === 0) {
27
+ lines.push('')
28
+ lines.push('No coexistence conflicts found.')
29
+ } else {
30
+ lines.push('')
31
+ lines.push(`Conflicts: ${conflicts.length}`)
32
+ conflicts.forEach((conflict, index) => {
33
+ lines.push(` ${index + 1}. ${conflict.resource.type}: ${conflict.resource.key}`)
34
+ lines.push(` owners: ${conflict.owners.join(', ')}`)
35
+ if (conflict.detail) lines.push(` detail: ${conflict.detail}`)
36
+ lines.push(
37
+ ` strategies: ${conflict.strategies.join(', ')} (recommended: ${conflict.recommended})`,
38
+ )
39
+ })
40
+ }
41
+
42
+ if (overrides.length > 0) {
43
+ lines.push('')
44
+ lines.push(`Overrides (informational): ${overrides.length}`)
45
+ overrides.forEach((conflict) => {
46
+ lines.push(` - ${conflict.resource.type}: ${conflict.resource.key}`)
47
+ lines.push(` ${conflict.detail}`)
48
+ })
49
+ }
50
+
51
+ const logIssues = graph.logIssues ?? []
52
+ if (logIssues.length > 0) {
53
+ lines.push('')
54
+ lines.push(`Log evidence: ${logIssues.length} (from ${graph.logFile}, may be historical)`)
55
+ for (const issue of logIssues.slice(0, 10)) {
56
+ lines.push(` - ${issue.type}: ${issue.key} (line ${issue.line})`)
57
+ }
58
+ if (logIssues.length > 10) {
59
+ lines.push(` ... and ${logIssues.length - 10} more (see --json)`)
60
+ }
61
+ }
62
+
63
+ return lines.join('\n')
64
+ }
65
+
66
+ export function renderPlan(plan) {
67
+ const lines = []
68
+ lines.push(`Repair plan for profile: ${plan.profile ?? 'unknown'}`)
69
+ if (plan.id) lines.push(`Plan: ${plan.id} (${plan.createdAt ?? 'unknown'})`)
70
+ if (plan.dumpConfig) {
71
+ lines.push(
72
+ plan.dumpConfig.ok
73
+ ? `Dump config: ok (${plan.dumpConfig.stdout.length} bytes)`
74
+ : `Dump config: failed (${plan.dumpConfig.error})`,
75
+ )
76
+ }
77
+
78
+ if (plan.actions.length === 0) {
79
+ lines.push('No automatic repairs. Nothing to do.')
80
+ return lines.join('\n')
81
+ }
82
+
83
+ plan.actions.forEach((action, index) => {
84
+ if (action.kind === 'rename-loader-id') {
85
+ lines.push(
86
+ ` ${index + 1}. rename loader id "${action.oldId}" -> "${action.newId}" in ${action.file}`,
87
+ )
88
+ } else if (action.kind === 'dedupe-bundles') {
89
+ lines.push(` ${index + 1}. dedupe bundle "${action.key}" in ${action.file}`)
90
+ } else if (action.kind === 'change-port') {
91
+ lines.push(
92
+ ` ${index + 1}. change port ${action.oldPort} -> ${action.newPort} for "${action.id}" in ${action.file}`,
93
+ )
94
+ } else if (action.kind === 'append-patch') {
95
+ lines.push(
96
+ ` ${index + 1}. append merged patch for "${action.targetId}" in ${action.file}`,
97
+ )
98
+ } else if (action.kind === 'peer-override') {
99
+ lines.push(
100
+ ` ${index + 1}. set peer override "${action.dep}" -> ${action.version} in ${action.file}`,
101
+ )
102
+ } else if (action.kind === 'disable-loader-row') {
103
+ lines.push(` ${index + 1}. disable loader row "${action.oldId}" in ${action.file}`)
104
+ } else if (action.kind === 'clone-loader-row') {
105
+ lines.push(
106
+ ` ${index + 1}. clone loader row "${action.oldId}" -> "${action.newId}" in ${action.file}`,
107
+ )
108
+ } else {
109
+ const type = action.conflict?.resource?.type ?? 'unknown'
110
+ const key = action.conflict?.resource?.key ?? ''
111
+ lines.push(` ${index + 1}. manual: ${type} ${key}`)
112
+ if (action.conflict?.detail) lines.push(` ${action.conflict.detail}`)
113
+ if (action.hint) lines.push(` ${action.hint}`)
114
+ }
115
+ })
116
+
117
+ if (plan.preview?.error) {
118
+ lines.push('', `Preview failed: ${plan.preview.error}`)
119
+ } else if (plan.preview?.files?.length) {
120
+ lines.push('', 'Preview:')
121
+ for (const file of plan.preview.files) {
122
+ if (!file.diff?.length) continue
123
+ lines.push(` ${file.file}`)
124
+ for (const line of file.diff.slice(0, 30)) lines.push(` ${line}`)
125
+ if (file.diff.length > 30) lines.push(` ... and ${file.diff.length - 30} more`)
126
+ }
127
+ }
128
+
129
+ return lines.join('\n')
130
+ }
131
+
132
+ export function renderApply(result) {
133
+ const lines = []
134
+ if (result.plan?.id) lines.push(`Plan: ${result.plan.id}`)
135
+ lines.push(`Backup: ${result.backup ?? '(none)'}`)
136
+
137
+ if (result.applied.length === 0) {
138
+ lines.push('Nothing applied.')
139
+ return lines.join('\n')
140
+ }
141
+
142
+ lines.push('Applied:')
143
+ for (const action of result.applied) {
144
+ if (action.kind === 'rename-loader-id') {
145
+ lines.push(` - renamed "${action.oldId}" -> "${action.newId}" (${action.file})`)
146
+ } else if (action.kind === 'dedupe-bundles') {
147
+ lines.push(` - deduped "${action.key}" (${action.file})`)
148
+ } else if (action.kind === 'change-port') {
149
+ lines.push(
150
+ ` - changed port ${action.oldPort} -> ${action.newPort} for "${action.id}" (${action.file})`,
151
+ )
152
+ } else if (action.kind === 'append-patch') {
153
+ lines.push(` - appended merged patch for "${action.targetId}" (${action.file})`)
154
+ } else if (action.kind === 'peer-override') {
155
+ lines.push(
156
+ ` - set peer override "${action.dep}" -> ${action.version} (${action.manager ?? 'npm'})`,
157
+ )
158
+ } else if (action.kind === 'disable-loader-row') {
159
+ lines.push(` - disabled loader row "${action.oldId}" (${action.file})`)
160
+ } else if (action.kind === 'clone-loader-row') {
161
+ lines.push(
162
+ ` - cloned loader row "${action.oldId}" -> "${action.newId}" (${action.file})`,
163
+ )
164
+ } else {
165
+ lines.push(` - ${action.kind} (${action.file ?? ''})`)
166
+ }
167
+ }
168
+
169
+ if (result.applied.some((action) => action.kind === 'peer-override')) {
170
+ const managers = new Set(
171
+ result.applied
172
+ .filter((action) => action.kind === 'peer-override')
173
+ .map((action) => action.manager ?? 'npm'),
174
+ )
175
+ lines.push('', `Peer overrides written. Reinstall the profile (${[...managers].join('/')} install).`)
176
+ }
177
+
178
+ return lines.join('\n')
179
+ }
180
+
181
+ export function renderRollback(result) {
182
+ if (result.error) {
183
+ const lines = [`Rollback failed: ${result.error}`]
184
+ if (result.available?.length) {
185
+ lines.push('Available backups:')
186
+ for (const id of result.available) lines.push(` - ${id}`)
187
+ }
188
+ return lines.join('\n')
189
+ }
190
+ if (!result.backup) return 'No backup found. Nothing to roll back.'
191
+ const lines = [`Restored from ${result.backup}:`]
192
+ for (const file of result.restored) lines.push(` - ${file}`)
193
+ if (result.reinstall) {
194
+ lines.push(
195
+ '',
196
+ result.reinstall.ok
197
+ ? `Dependencies reinstalled (${result.reinstall.packageManager}).`
198
+ : `Dependency reinstall failed: ${result.reinstall.errors.join(' | ')}`,
199
+ )
200
+ }
201
+ return lines.join('\n')
202
+ }
203
+
204
+ export function renderList(result) {
205
+ const lines = [
206
+ `Profile: ${result.profile} (${result.dir})`,
207
+ `Bundles: ${result.bundles.length}`,
208
+ ]
209
+ for (const bundle of result.bundles) {
210
+ const patch = bundle.hasPatch ? ' [patch]' : ''
211
+ const version = bundle.version ? `@${bundle.version}` : ''
212
+ lines.push(` - ${bundle.name}${version}${patch}`)
213
+ if (bundle.patchError) lines.push(` patch error: ${bundle.patchError}`)
214
+ }
215
+
216
+ lines.push('', `Conflicts: ${result.conflicts.length}`)
217
+ for (const conflict of result.conflicts) {
218
+ lines.push(
219
+ ` - [${conflict.severity}] ${conflict.type}: ${conflict.key} (${conflict.owners.join(', ')})`,
220
+ )
221
+ }
222
+ return lines.join('\n')
223
+ }
224
+
225
+ export function renderAudit(result) {
226
+ if (!result.exists) return `No audit log at ${result.file}.`
227
+ if (result.entries.length === 0) return `No audit entries in ${result.file}.`
228
+ const lines = [`Audit: ${result.file}`]
229
+ for (const entry of result.entries) {
230
+ const applied = Array.isArray(entry.applied) ? entry.applied : []
231
+ lines.push(` - ${entry.at ?? 'unknown'}: ${applied.length} action(s)`)
232
+ if (entry.backup) lines.push(` backup: ${entry.backup}`)
233
+ for (const action of applied.slice(0, 5)) {
234
+ lines.push(` ${action.kind}${action.file ? ` (${action.file})` : ''}`)
235
+ }
236
+ if (applied.length > 5) lines.push(` ... and ${applied.length - 5} more`)
237
+ }
238
+ return lines.join('\n')
239
+ }
240
+
241
+ export function renderBackups(result) {
242
+ if (result.ids.length === 0) return `No backups under ${result.home}.`
243
+ const lines = [`Backups under ${result.home}:`]
244
+ for (const id of result.ids) lines.push(` - ${id}`)
245
+ return lines.join('\n')
246
+ }
247
+
248
+ export function renderReport(result) {
249
+ if (!result.exists) {
250
+ return [
251
+ `No runtime report at ${result.file}.`,
252
+ 'Start DSH with the coexist plugin installed, then run this command again.',
253
+ ].join('\n')
254
+ }
255
+
256
+ const report = result.report
257
+ const lines = []
258
+ lines.push(`Runtime report: ${result.file}`)
259
+ lines.push(`Generated: ${report.generatedAt ?? 'unknown'}`)
260
+ lines.push(`Mode: ${report.mode ?? 'alias'}`)
261
+ if (report.plan?.id) {
262
+ lines.push(
263
+ `Runtime plan: ${report.plan.id} (${report.plan.actions ?? 0} actions${
264
+ report.plan.applied ? `, applied ${report.plan.applied.actions ?? 0}` : ''
265
+ })`,
266
+ )
267
+ }
268
+ const caps = report.capabilities ?? {}
269
+ const enabled = Object.entries(caps)
270
+ .filter(([, value]) => value === true)
271
+ .map(([key]) => key)
272
+ if (enabled.length > 0) lines.push(`Capabilities: ${enabled.join(', ')}`)
273
+
274
+ const aliases = report.tools?.aliases ?? []
275
+ lines.push(`Tool aliases: ${aliases.length}`)
276
+ for (const alias of aliases) {
277
+ const calls = alias.calls ? ` (calls=${alias.calls})` : ''
278
+ lines.push(` - ${alias.name} -> ${alias.alias}${calls}`)
279
+ }
280
+
281
+ const fallbacks = report.tools?.fallbacks ?? []
282
+ if (fallbacks.length > 0) {
283
+ lines.push(`Fallbacks: ${fallbacks.length}`)
284
+ for (const fallback of fallbacks.slice(-5)) {
285
+ lines.push(` - ${fallback.tool}: ${fallback.error}`)
286
+ }
287
+ }
288
+
289
+ const routes = report.tools?.routes ?? []
290
+ if (routes.length > 0) {
291
+ lines.push(`Routes: ${routes.length}`)
292
+ for (const route of routes.slice(-5)) {
293
+ lines.push(` - ${route.tool} -> ${route.target} (${route.reason ?? 'rule'})`)
294
+ }
295
+ }
296
+
297
+ const stats = Object.entries(report.tools?.stats ?? {})
298
+ if (stats.length > 0) {
299
+ const total = stats.reduce((sum, [, stat]) => sum + stat.calls, 0)
300
+ lines.push(`Tool calls: ${total}`)
301
+ for (const [tool, stat] of stats.sort((a, b) => b[1].calls - a[1].calls).slice(0, 8)) {
302
+ const avg = stat.calls > 0 ? Math.round(stat.totalMs / stat.calls) : 0
303
+ const extra = [
304
+ stat.errors > 0 ? `errors=${stat.errors}` : '',
305
+ stat.blocked > 0 ? `blocked=${stat.blocked}` : '',
306
+ ]
307
+ .filter(Boolean)
308
+ .join(', ')
309
+ lines.push(` - ${tool}: ${stat.calls} calls, avg ${avg}ms${extra ? ` (${extra})` : ''}`)
310
+ }
311
+ }
312
+
313
+ const commandAliases = report.commands?.aliases ?? []
314
+ if (commandAliases.length > 0) {
315
+ lines.push(`Command aliases: ${commandAliases.length}`)
316
+ for (const alias of commandAliases) {
317
+ lines.push(` - /${alias.name} -> /${alias.alias}`)
318
+ }
319
+ }
320
+
321
+ const providerAliases = report.providers?.aliases ?? []
322
+ if (providerAliases.length > 0) {
323
+ lines.push(`Provider aliases: ${providerAliases.length}`)
324
+ for (const alias of providerAliases) {
325
+ lines.push(` - ${alias.name} -> ${alias.alias}`)
326
+ }
327
+ }
328
+
329
+ const providerConflicts = report.providers?.conflicts ?? []
330
+ if (providerConflicts.length > 0) {
331
+ lines.push(`Provider conflicts: ${providerConflicts.length}`)
332
+ for (const conflict of providerConflicts) {
333
+ lines.push(
334
+ ` - ${conflict.name}: ${conflict.resolution ?? 'blocked'}${conflict.message ? ` (${conflict.message})` : ''}`,
335
+ )
336
+ }
337
+ }
338
+
339
+ lines.push(`Service conflicts: ${report.serviceConflicts?.length ?? 0}`)
340
+ for (const conflict of report.serviceConflicts ?? []) {
341
+ const resolution =
342
+ conflict.resolution === 'bridged'
343
+ ? ' (bridged)'
344
+ : conflict.resolution === 'isolated'
345
+ ? ' (isolated)'
346
+ : ''
347
+ lines.push(
348
+ ` - ${conflict.service}: ${conflict.existing ?? 'unknown'} vs ${conflict.incoming ?? 'unknown'}${resolution}`,
349
+ )
350
+ if (conflict.suggestion) lines.push(` ${conflict.suggestion}`)
351
+ }
352
+
353
+ const recoveries = report.recoveries ?? []
354
+ if (recoveries.length > 0) {
355
+ lines.push(`Recovery attempts: ${recoveries.length}`)
356
+ for (const item of recoveries) {
357
+ lines.push(
358
+ ` - ${item.plugin}: ${item.state}${item.error ? ` (${item.error})` : ''}`,
359
+ )
360
+ }
361
+ }
362
+
363
+ lines.push(`Failed plugins: ${report.failures?.length ?? 0}`)
364
+ for (const failure of report.failures ?? []) {
365
+ const kind = failure.kind ? ` [${failure.kind}]` : ''
366
+ lines.push(` - ${failure.plugin}${kind}: ${failure.error ?? failure.state}`)
367
+ if (failure.suggestion) lines.push(` ${failure.suggestion}`)
368
+ }
369
+
370
+ lines.push(`Pending plugins: ${report.pending?.length ?? 0}`)
371
+ for (const pending of report.pending ?? []) {
372
+ const missing = pending.missing?.length ? ` missing: ${pending.missing.join(', ')}` : ''
373
+ lines.push(` - ${pending.plugin} (${pending.state})${missing}`)
374
+ if (pending.suggestion) lines.push(` ${pending.suggestion}`)
375
+ }
376
+ if (report.pending?.length) {
377
+ lines.push(' (pending may be optional capabilities, not necessarily a failure)')
378
+ }
379
+
380
+ const hooks = [...(report.eventHooks ?? [])].sort(
381
+ (left, right) =>
382
+ (right.prepend ?? 0) - (left.prepend ?? 0) ||
383
+ (right.listeners ?? 0) - (left.listeners ?? 0),
384
+ )
385
+ lines.push(`Shared event hooks: ${hooks.length}`)
386
+ for (const hook of hooks.slice(0, 10)) {
387
+ const prepend = hook.prepend ? `, prepend=${hook.prepend}` : ''
388
+ const risk = hook.risk ? ` [${hook.risk}]` : ''
389
+ lines.push(` - ${hook.event}: ${hook.owners.join(', ')}${prepend}${risk}`)
390
+ if (hook.reason && hook.risk !== 'low') lines.push(` ${hook.reason}`)
391
+ }
392
+ if (hooks.length > 10) {
393
+ lines.push(` ... and ${hooks.length - 10} more (see report.json)`)
394
+ }
395
+ if (hooks.length > 0) {
396
+ lines.push(' (Cordis runs every listener; shared hooks are informational)')
397
+ }
398
+
399
+ return lines.join('\n')
400
+ }
401
+
402
+ function compatibilityLine(compatibility) {
403
+ if (!compatibility || compatibility.checks.length === 0) return 'unknown (plugin declares no engine/peer range)'
404
+ if (compatibility.status === 'ok') return 'ok'
405
+ const failed = compatibility.checks.filter((check) => check.ok === false)
406
+ if (failed.length > 0) {
407
+ return failed
408
+ .map((check) => `blocked: ${check.name} ${check.range} (host ${check.actual ?? 'unknown'})`)
409
+ .join('; ')
410
+ }
411
+ const unknown = compatibility.checks.filter((check) => check.ok === null)
412
+ return `unknown: ${unknown.map((check) => `${check.name} ${check.range}`).join('; ')}`
413
+ }
414
+
415
+ export function renderInstall(result) {
416
+ const lines = []
417
+ const action = result.dryRun ? 'Would install' : result.ok ? 'Installed' : 'Install failed'
418
+ lines.push(`${action}: ${result.plugin.name}@${result.plugin.version ?? '?'}`)
419
+ lines.push(`Profile: ${result.profile} (${result.profileDir})`)
420
+ lines.push(`Host: ${result.host.version ?? 'unknown'} (${result.host.source ?? 'not detected'})`)
421
+ lines.push(`Compatibility: ${compatibilityLine(result.compatibility)}`)
422
+
423
+ if (result.dryRun) return lines.join('\n')
424
+
425
+ if (result.error) lines.push(`Error: ${result.error}`)
426
+ if (result.backup) lines.push(`Backup: ${result.backup}`)
427
+ if (result.packageManager) lines.push(`Package manager: ${result.packageManager}`)
428
+ if (result.dumpConfig) {
429
+ const dump = result.dumpConfig
430
+ lines.push(
431
+ `Dump config: ${
432
+ dump.ok
433
+ ? `ok (${dump.bytes} bytes)`
434
+ : dump.skipped
435
+ ? `skipped (${dump.error})`
436
+ : `failed (${dump.error})`
437
+ }`,
438
+ )
439
+ }
440
+ if (result.rolledBack) {
441
+ lines.push(`Rolled back: ${(result.restored ?? []).join(', ') || '(no files)'}`)
442
+ }
443
+ if (result.bundles?.length) lines.push(`Bundles: ${result.bundles.join(', ')}`)
444
+ for (const warning of result.warnings ?? []) lines.push(`Warning: ${warning}`)
445
+ if (result.ok) lines.push('', 'Restart DSH to load the plugin.')
446
+ return lines.join('\n')
447
+ }
448
+
449
+ export function renderUninstall(result) {
450
+ const lines = [`Uninstalled: ${result.plugin}`, `Profile: ${result.profile}`, `Backup: ${result.backup}`]
451
+ lines.push(`Removed: ${result.removed.join(', ') || '(nothing was registered)'}`)
452
+ if (result.packageManager) lines.push(`Package manager: ${result.packageManager}`)
453
+ for (const path of result.cleaned ?? []) lines.push(`Cleaned: ${path}`)
454
+ if (result.purged) lines.push('Purged: ~/.dsh/coexist (backups, reports, config)')
455
+ for (const warning of result.warnings ?? []) lines.push(`Warning: ${warning}`)
456
+ lines.push('', 'Restart DSH to unload the plugin.')
457
+ return lines.join('\n')
458
+ }
459
+
460
+ export function renderMatrix(result) {
461
+ const lines = [
462
+ `Profile: ${result.profile} (${result.profileDir})`,
463
+ `Host: ${result.host.version ?? 'unknown'} (${result.host.source ?? 'not detected'})`,
464
+ '',
465
+ ]
466
+ const rows = result.rows.map((row) => {
467
+ const detail =
468
+ row.status === 'missing'
469
+ ? 'not installed'
470
+ : row.checks.length === 0
471
+ ? 'no declared range'
472
+ : row.checks
473
+ .map((check) => {
474
+ const state = check.ok === true ? 'ok' : check.ok === false ? 'FAIL' : '?'
475
+ return `${check.kind}:${check.name} ${state}`
476
+ })
477
+ .join(', ')
478
+ return { ...row, detail }
479
+ })
480
+ const width = Math.max(8, ...rows.map((row) => row.name.length))
481
+ lines.push(`${'PLUGIN'.padEnd(width)} ${'VERSION'.padEnd(12)} STATUS DETAIL`)
482
+ for (const row of rows) {
483
+ lines.push(
484
+ `${row.name.padEnd(width)} ${String(row.version ?? '-').padEnd(12)} ${row.status.padEnd(8)} ${row.detail}`,
485
+ )
486
+ }
487
+ return lines.join('\n')
488
+ }
489
+
490
+ export function renderDesktopPlan(result) {
491
+ const lines = [`DSH app: ${result.appExe}`, `Launcher: ${result.paths.launcherVbs}`, 'Shortcuts:']
492
+ for (const shortcut of result.shortcuts) {
493
+ lines.push(` - ${shortcut.Path}${shortcut.created ? ' (create)' : ''}`)
494
+ }
495
+ return lines.join('\n')
496
+ }
497
+
498
+ export function renderDesktopInstall(result) {
499
+ const lines = [
500
+ `Installed: ${result.paths.launcherVbs}`,
501
+ `Backup: ${result.backupDir}`,
502
+ 'Updated shortcuts:',
503
+ ]
504
+ for (const entry of result.entries) {
505
+ lines.push(` - ${entry.path}${entry.created ? ' (created)' : ''}`)
506
+ }
507
+ if (result.errors?.length) {
508
+ lines.push('Errors:')
509
+ for (const error of result.errors) lines.push(` - ${error.path}: ${error.message}`)
510
+ }
511
+ lines.push('', 'Fully quit DSH, then double-click the DSH shortcut.')
512
+ return lines.join('\n')
513
+ }
514
+
515
+ export function renderDesktopRestore(result) {
516
+ if (result.missing) return 'No desktop install manifest found.'
517
+ const lines = [`Restored ${result.restored.length} shortcut(s).`]
518
+ for (const item of result.restored) lines.push(` - ${item.action}: ${item.path}`)
519
+ return lines.join('\n')
520
+ }
521
+
522
+ export function renderDesktopStatus(result) {
523
+ const lines = []
524
+ lines.push(`DSH app: ${result.appExe ?? `(not found: ${result.appError})`}`)
525
+ lines.push(`Launcher: ${result.launcherExists ? result.paths.launcherVbs : '(not installed)'}`)
526
+ lines.push(`Log: ${result.paths.logPath}`)
527
+ lines.push(`Shortcuts: ${result.shortcuts.length}`)
528
+ for (const shortcut of result.shortcuts) {
529
+ lines.push(` - ${shortcut.Path} -> ${shortcut.TargetPath}`)
530
+ }
531
+ return lines.join('\n')
532
+ }
533
+
534
+ export function renderDesktopLog(result) {
535
+ if (!result.exists) {
536
+ return [
537
+ `No preload log at ${result.file}.`,
538
+ 'Fully quit DSH, then start it from the DSH icon on the Desktop or Start Menu.',
539
+ ].join('\n')
540
+ }
541
+ return result.text
542
+ }
package/src/semver.js ADDED
@@ -0,0 +1,138 @@
1
+ const VERSION_RE = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?/
2
+ const COMPARATOR_RE = /^(>=|<=|>|<|=|\^|~)?\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/
3
+
4
+ function parseVersion(text) {
5
+ const match = String(text ?? '').trim().match(VERSION_RE)
6
+ if (!match) return null
7
+ return {
8
+ major: Number(match[1]),
9
+ minor: Number(match[2] ?? 0),
10
+ patch: Number(match[3] ?? 0),
11
+ precision: [match[1], match[2], match[3]].filter((part) => part !== undefined).length,
12
+ prerelease: match[4] ?? null,
13
+ }
14
+ }
15
+
16
+ export function compareVersions(leftText, rightText) {
17
+ const left = parseVersion(leftText)
18
+ const right = parseVersion(rightText)
19
+ if (!left || !right) return null
20
+
21
+ for (const key of ['major', 'minor', 'patch']) {
22
+ if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1
23
+ }
24
+
25
+ if (!left.prerelease && right.prerelease) return 1
26
+ if (left.prerelease && !right.prerelease) return -1
27
+ if (!left.prerelease && !right.prerelease) return 0
28
+ if (left.prerelease === right.prerelease) return 0
29
+ return left.prerelease < right.prerelease ? -1 : 1
30
+ }
31
+
32
+ function atLeast(version, bound) {
33
+ return compareVersions(version, bound) >= 0
34
+ }
35
+
36
+ function below(version, bound) {
37
+ return compareVersions(version, bound) < 0
38
+ }
39
+
40
+ function tokenMatches(versionText, token) {
41
+ if (token === '*' || token.toLowerCase() === 'x') return true
42
+
43
+ const match = token.match(COMPARATOR_RE)
44
+ if (!match) return true
45
+
46
+ const operator = match[1] ?? '='
47
+ const parts = [match[2], match[3], match[4]].filter((part) => part !== undefined)
48
+ const baseText = parts.join('.') + (match[5] ? `-${match[5]}` : '')
49
+ const base = parseVersion(baseText)
50
+ if (!base) return true
51
+
52
+ if (operator === '>=') return atLeast(versionText, baseText)
53
+ if (operator === '>') return compareVersions(versionText, baseText) > 0
54
+ if (operator === '<=') return compareVersions(versionText, baseText) <= 0
55
+ if (operator === '<') return below(versionText, baseText)
56
+
57
+ if (operator === '^') {
58
+ const upper = upperForCaret(base)
59
+ return atLeast(versionText, lowerOf(base)) && below(versionText, upper)
60
+ }
61
+
62
+ if (operator === '~') {
63
+ const upper = upperForTilde(base)
64
+ return atLeast(versionText, lowerOf(base)) && below(versionText, upper)
65
+ }
66
+
67
+ // 精确版本:只写 1 或 1.2 时按 SemVer 视为范围。
68
+ if (base.precision === 1) {
69
+ return atLeast(versionText, `${base.major}.0.0`) && below(versionText, `${base.major + 1}.0.0`)
70
+ }
71
+ if (base.precision === 2) {
72
+ return (
73
+ atLeast(versionText, `${base.major}.${base.minor}.0`) &&
74
+ below(versionText, `${base.major}.${base.minor + 1}.0`)
75
+ )
76
+ }
77
+ return compareVersions(versionText, baseText) === 0
78
+ }
79
+
80
+ function lowerOf(base) {
81
+ return `${base.major}.${base.minor}.${base.patch}${base.prerelease ? `-${base.prerelease}` : ''}`
82
+ }
83
+
84
+ function upperForCaret(base) {
85
+ if (base.major > 0) return `${base.major + 1}.0.0`
86
+ if (base.precision === 1) return '1.0.0'
87
+ if (base.minor > 0) return `0.${base.minor + 1}.0`
88
+ return `0.0.${base.patch + 1}`
89
+ }
90
+
91
+ function upperForTilde(base) {
92
+ if (base.precision >= 2) return `${base.major}.${base.minor + 1}.0`
93
+ return `${base.major + 1}.0.0`
94
+ }
95
+
96
+ /**
97
+ * 判断版本是否落在 npm 风格的 semver 范围内。
98
+ * 支持:精确版本、1 / 1.2 这类部分版本、*、^、~、>=、>、<=、<、||。
99
+ * 不支持 hyphen、预发布标签的完整语义;遇到无法解析的 token 时放行(fail-open)。
100
+ */
101
+ export function satisfies(versionText, rangeText) {
102
+ const version = String(versionText ?? '').trim()
103
+ if (!parseVersion(version)) return false
104
+
105
+ const range = String(rangeText ?? '').trim()
106
+ if (range === '' || range === '*' || range.toLowerCase() === 'x') return true
107
+
108
+ return range.split('||').some((alternative) => {
109
+ const tokens = alternative.trim().split(/\s+/).filter(Boolean)
110
+ if (tokens.length === 0) return true
111
+ return tokens.every((token) => tokenMatches(version, token))
112
+ })
113
+ }
114
+
115
+ /**
116
+ * 取一个范围的“最低可满足版本”,用于生成受控 peer override。
117
+ * 多段(||)取其中最高的最低版本;无法解析时返回 null。
118
+ */
119
+ export function minVersionForRange(rangeText) {
120
+ const range = String(rangeText ?? '').trim()
121
+ if (!range) return null
122
+
123
+ const versions = []
124
+ for (const alternative of range.split('||')) {
125
+ for (const token of alternative.trim().split(/\s+/).filter(Boolean)) {
126
+ const match = token.match(COMPARATOR_RE)
127
+ if (!match) continue
128
+ const parts = [match[2], match[3], match[4]].filter((part) => part !== undefined)
129
+ if (parts.length === 0) continue
130
+ versions.push(`${Number(match[2])}.${Number(match[3] ?? 0)}.${Number(match[4] ?? 0)}`)
131
+ break
132
+ }
133
+ }
134
+
135
+ if (versions.length === 0) return null
136
+ versions.sort((left, right) => compareVersions(right, left))
137
+ return versions[0]
138
+ }