@aiwayds/dsh-opentui 0.17.3 → 0.18.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/CHANGELOG.md +29 -0
- package/README.md +61 -0
- package/bin/dsh-opentui.mjs +43 -2
- package/bin/lib/launcher.mjs +129 -1
- package/dist/client/index.js +1 -1
- package/package.json +1 -1
- package/scripts/lib/provision-plan.mjs +150 -7
- package/scripts/lib/provision-state.mjs +294 -0
- package/scripts/lib/upgrade-plan.mjs +406 -0
- package/scripts/provision-opentui-profile.mjs +239 -20
- package/scripts/upgrade.mjs +947 -0
|
@@ -0,0 +1,947 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// upgrade.mjs — the body of `dsh-opentui upgrade`.
|
|
3
|
+
//
|
|
4
|
+
// Phases (control flow is defined in the implementation plan §6.3):
|
|
5
|
+
// 1. Plan (read-only): resolve the registry, read the opentui profile's
|
|
6
|
+
// dependencies and the versions on disk, query the dist-tag once per
|
|
7
|
+
// upgradable package, print the table. A missing profile is a normal
|
|
8
|
+
// terminal state (exit 0): the launcher provisions it on the next start.
|
|
9
|
+
// 2. Confirmation: skipped by --dry-run and --yes; otherwise an interactive
|
|
10
|
+
// prompt, and a refusal (exit 2) when neither stdin nor CI allows it.
|
|
11
|
+
// 3. Self upgrade: `npm i -g <own name>@<target>`, only when the running
|
|
12
|
+
// copy demonstrably lives under the npm global prefix. Every other
|
|
13
|
+
// install form is skipped with a warning — installing into a different
|
|
14
|
+
// prefix would create a shadow copy that `dsh-opentui` never resolves.
|
|
15
|
+
// A hard failure here aborts BEFORE anything touches the profile.
|
|
16
|
+
// 4. Plugins: `applyPluginUpgrades(ctx)` — back up the profile, run ONE
|
|
17
|
+
// batched `dsh plugin add`, verify each package on disk, and record the
|
|
18
|
+
// landed versions in upgrade-overrides.json. An install failure restores
|
|
19
|
+
// the backup and re-adds the pre-upgrade specs; a version that did not
|
|
20
|
+
// land is reported but never rolls back a successful install.
|
|
21
|
+
//
|
|
22
|
+
// Exit codes: 0 done/nothing to do/dry-run/help; 1 hard failure OR any package
|
|
23
|
+
// whose target version could not be determined (a query failure means the
|
|
24
|
+
// target is unknown, which is not "up to date"; nothing is written in that
|
|
25
|
+
// case); 2 usage refusal; 3 partially applied (some package is not at its
|
|
26
|
+
// planned version, or the override file could not be written).
|
|
27
|
+
//
|
|
28
|
+
// Dependency injection: every child process goes through `run(cmd, args, {
|
|
29
|
+
// timeout })` and every file operation through `fs`, both overridable from the
|
|
30
|
+
// context argument. That is what lets the tests exercise the install, verify
|
|
31
|
+
// and abort paths without npm, a TTY, or a real profile.
|
|
32
|
+
import { execFileSync } from 'node:child_process'
|
|
33
|
+
import {
|
|
34
|
+
copyFileSync,
|
|
35
|
+
existsSync,
|
|
36
|
+
mkdirSync,
|
|
37
|
+
readFileSync,
|
|
38
|
+
readSync,
|
|
39
|
+
realpathSync,
|
|
40
|
+
renameSync,
|
|
41
|
+
rmdirSync,
|
|
42
|
+
rmSync,
|
|
43
|
+
writeFileSync,
|
|
44
|
+
} from 'node:fs'
|
|
45
|
+
import { homedir } from 'node:os'
|
|
46
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
47
|
+
import { fileURLToPath } from 'node:url'
|
|
48
|
+
import { formatUpgradeUsage } from '../bin/lib/launcher.mjs'
|
|
49
|
+
import {
|
|
50
|
+
PLUGIN_SET,
|
|
51
|
+
PROFILE,
|
|
52
|
+
compareVersions,
|
|
53
|
+
parseVersion,
|
|
54
|
+
resolveEffectivePin,
|
|
55
|
+
} from './lib/provision-plan.mjs'
|
|
56
|
+
import {
|
|
57
|
+
buildUpgradePlan,
|
|
58
|
+
buildViewArgs,
|
|
59
|
+
isOfficialRegistry,
|
|
60
|
+
isUpgradableDependency,
|
|
61
|
+
parseOverrides,
|
|
62
|
+
resolveRegistry,
|
|
63
|
+
serializeOverrides,
|
|
64
|
+
} from './lib/upgrade-plan.mjs'
|
|
65
|
+
|
|
66
|
+
const PREFIX = 'dsh-opentui upgrade: '
|
|
67
|
+
// Matched to buildViewArgs' `--fetch-timeout 20000` (+ slack for npm startup
|
|
68
|
+
// and DNS): the child enforces its own fetch budget, so this backstop only
|
|
69
|
+
// matters when an argv flag is ignored (an old npm, a wrapper). Without the
|
|
70
|
+
// leftover margin a single dead registry would cost 60s per package.
|
|
71
|
+
const QUERY_TIMEOUT_MS = 25 * 1000
|
|
72
|
+
const PREFIX_TIMEOUT_MS = 10 * 1000
|
|
73
|
+
const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
|
|
74
|
+
const OVERRIDE_FILE = 'upgrade-overrides.json'
|
|
75
|
+
const BACKUP_DIR_NAME = '.upgrade-backup'
|
|
76
|
+
// pnpm-workspace.yaml belongs here because users hand-write allowBuilds in it:
|
|
77
|
+
// a host rollback that restored only the manifest and the lock would leave the
|
|
78
|
+
// rewritten workspace file in place.
|
|
79
|
+
const BACKUP_FILE_NAMES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', OVERRIDE_FILE]
|
|
80
|
+
const SAVE_EXACT = '--save-exact'
|
|
81
|
+
// The host forwards unknown flags to pnpm, but a future argv parser could
|
|
82
|
+
// reject it; only a rejection of THIS flag earns the one retry without it.
|
|
83
|
+
const SAVE_EXACT_REJECTED = /save-exact|unknown option|unrecognized/i
|
|
84
|
+
|
|
85
|
+
/** The shipped pins, keyed by package name: the only versions provisioning
|
|
86
|
+
* may be raised above, so the only names an override can ever affect. */
|
|
87
|
+
const SHIPPED_PINS = new Map(PLUGIN_SET.map((plugin) => [plugin.name, plugin.version]))
|
|
88
|
+
|
|
89
|
+
const ACTION_LABEL = {
|
|
90
|
+
upgrade: 'upgrade',
|
|
91
|
+
latest: 'up to date',
|
|
92
|
+
'query-failed': 'query-failed',
|
|
93
|
+
excluded: 'excluded',
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const say = (message) => console.log(`${PREFIX}${message}`)
|
|
97
|
+
const warn = (message) => console.error(`${PREFIX}warning: ${message}`)
|
|
98
|
+
|
|
99
|
+
function isPlainObject(value) {
|
|
100
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Injected effects — the defaults used by the real CLI
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Run a command and NEVER throw on a non-zero exit: the caller inspects
|
|
109
|
+
* `status`. stderr/stdout are strings ('' when absent) so tail printing and
|
|
110
|
+
* JSON parsing need no Buffer handling.
|
|
111
|
+
*
|
|
112
|
+
* `env` is merged over the parent environment (never replaces it): the plugin
|
|
113
|
+
* install must inherit the caller's DSH_HOME, and a spawn that dropped it
|
|
114
|
+
* would operate on the default profile instead of the selected one.
|
|
115
|
+
*
|
|
116
|
+
* @param {string} cmd
|
|
117
|
+
* @param {string[]} args
|
|
118
|
+
* @param {{ timeout?: number, env?: Record<string, string | undefined> }} [options]
|
|
119
|
+
* @returns {{ status: number, stdout: string, stderr: string }}
|
|
120
|
+
*/
|
|
121
|
+
export function defaultRun(cmd, args = [], { timeout, env } = {}) {
|
|
122
|
+
const childEnv = {}
|
|
123
|
+
if (env && typeof env === 'object') {
|
|
124
|
+
Object.assign(childEnv, process.env)
|
|
125
|
+
for (const [key, value] of Object.entries(env)) {
|
|
126
|
+
if (typeof value === 'string') childEnv[key] = value
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const stdout = execFileSync(cmd, args, {
|
|
131
|
+
encoding: 'utf8',
|
|
132
|
+
timeout,
|
|
133
|
+
...(env && typeof env === 'object' ? { env: childEnv } : {}),
|
|
134
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
135
|
+
})
|
|
136
|
+
return { status: 0, stdout: String(stdout ?? ''), stderr: '' }
|
|
137
|
+
} catch (err) {
|
|
138
|
+
return {
|
|
139
|
+
status: typeof err?.status === 'number' ? err.status : 1,
|
|
140
|
+
stdout: String(err?.stdout ?? ''),
|
|
141
|
+
stderr: String(err?.stderr ?? err?.message ?? ''),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The file operations the command needs, as an object so a test can replace
|
|
148
|
+
* the whole surface. Path-only helpers (`realpathSync` in canonicalPath) stay
|
|
149
|
+
* on the module import: the injected set deliberately covers reads/writes
|
|
150
|
+
* only, and canonicalPath remembers a path it was already given.
|
|
151
|
+
*/
|
|
152
|
+
export const defaultFs = {
|
|
153
|
+
readFileSync: (path, encoding) => readFileSync(path, encoding),
|
|
154
|
+
writeFileSync: (path, data, encoding) => writeFileSync(path, data, encoding),
|
|
155
|
+
existsSync: (path) => existsSync(path),
|
|
156
|
+
mkdirSync: (path, options) => mkdirSync(path, options),
|
|
157
|
+
rmSync: (path, options) => rmSync(path, options),
|
|
158
|
+
rmdirSync: (path) => rmdirSync(path),
|
|
159
|
+
copyFileSync: (from, to) => copyFileSync(from, to),
|
|
160
|
+
renameSync: (from, to) => renameSync(from, to),
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** A synchronous one-line read from stdin (the confirmation prompt). */
|
|
164
|
+
function defaultReadLine() {
|
|
165
|
+
const buffer = Buffer.alloc(1024)
|
|
166
|
+
try {
|
|
167
|
+
const read = readSync(0, buffer, 0, buffer.length, null)
|
|
168
|
+
return buffer.subarray(0, read).toString('utf8')
|
|
169
|
+
} catch {
|
|
170
|
+
return ''
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const defaultPrompt = (text) => process.stdout.write(text)
|
|
175
|
+
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
// Small readers
|
|
178
|
+
// ---------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Absolute path for comparisons. Uses realpathSync when it resolves and falls
|
|
182
|
+
* back to a lexical resolve, so a path that only exists in a test fixture is
|
|
183
|
+
* still comparable (and a broken symlink never throws here).
|
|
184
|
+
*/
|
|
185
|
+
function canonicalPath(path) {
|
|
186
|
+
try {
|
|
187
|
+
return realpathSync(path)
|
|
188
|
+
} catch {
|
|
189
|
+
return resolve(path)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Is `child` the same as `parent` or below it? */
|
|
194
|
+
function isInside(parent, child) {
|
|
195
|
+
const base = canonicalPath(parent).replace(/\/+$/, '')
|
|
196
|
+
const target = canonicalPath(child)
|
|
197
|
+
return target === base || target.startsWith(`${base}${sep}`)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Parsed JSON, or undefined for a missing/unreadable/malformed file. */
|
|
201
|
+
function readJson(fs, path) {
|
|
202
|
+
try {
|
|
203
|
+
return JSON.parse(fs.readFileSync(path, 'utf8'))
|
|
204
|
+
} catch {
|
|
205
|
+
return undefined
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** File contents, or undefined when the file cannot be read. */
|
|
210
|
+
function readText(fs, path) {
|
|
211
|
+
try {
|
|
212
|
+
const text = fs.readFileSync(path, 'utf8')
|
|
213
|
+
return typeof text === 'string' ? text : undefined
|
|
214
|
+
} catch {
|
|
215
|
+
return undefined
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* npmrc texts, least specific first (resolveRegistry lets the LAST text win).
|
|
221
|
+
* Only files that exist are passed, so a missing file cannot shadow a present
|
|
222
|
+
* one: profile/.npmrc > $DSH_HOME/.npmrc > ~/.npmrc.
|
|
223
|
+
*/
|
|
224
|
+
function collectNpmrcTexts({ fs, dshHome, profileDir, env }) {
|
|
225
|
+
const home = env.HOME || homedir()
|
|
226
|
+
const paths = [join(home, '.npmrc'), join(dshHome, '.npmrc'), join(profileDir, '.npmrc')]
|
|
227
|
+
const texts = []
|
|
228
|
+
for (const path of paths) {
|
|
229
|
+
const text = readText(fs, path)
|
|
230
|
+
if (text !== undefined) texts.push(text)
|
|
231
|
+
}
|
|
232
|
+
return texts
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The version on disk for a profile dependency, when readable. */
|
|
236
|
+
function readInstalledVersion(fs, profileDir, name) {
|
|
237
|
+
const manifest = readJson(fs, join(profileDir, 'node_modules', ...name.split('/'), 'package.json'))
|
|
238
|
+
return isPlainObject(manifest) && typeof manifest.version === 'string' && manifest.version
|
|
239
|
+
? manifest.version
|
|
240
|
+
: undefined
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The launcher's own name/version — read from ITS manifest, never guessed. */
|
|
244
|
+
function readSelf(fs, pkgRoot) {
|
|
245
|
+
const manifest = readJson(fs, join(pkgRoot, 'package.json'))
|
|
246
|
+
if (!isPlainObject(manifest)) return null
|
|
247
|
+
if (typeof manifest.name !== 'string' || manifest.name === '') return null
|
|
248
|
+
if (typeof manifest.version !== 'string' || manifest.version === '') return null
|
|
249
|
+
return { name: manifest.name, version: manifest.version }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* `npm view <pkg> dist-tags --json` for one package. Returns the version the
|
|
254
|
+
* requested tag points at, or null when the query failed OR the tag is absent.
|
|
255
|
+
* A single package failing is recorded as `query-failed` by the caller.
|
|
256
|
+
*/
|
|
257
|
+
function queryDistTag({ run, pkg, registry, tag }) {
|
|
258
|
+
const result = run('npm', buildViewArgs({ pkg, registry }), { timeout: QUERY_TIMEOUT_MS })
|
|
259
|
+
if (!result || result.status !== 0) return null
|
|
260
|
+
let tags
|
|
261
|
+
try {
|
|
262
|
+
tags = JSON.parse(result.stdout)
|
|
263
|
+
} catch {
|
|
264
|
+
return null
|
|
265
|
+
}
|
|
266
|
+
if (!isPlainObject(tags)) return null
|
|
267
|
+
const version = tags[tag]
|
|
268
|
+
return typeof version === 'string' && version !== '' ? version : null
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Plain, ANSI-free table with content-sized columns. */
|
|
272
|
+
function formatPlanTable(rows) {
|
|
273
|
+
const header = ['PACKAGE', 'CURRENT', 'TARGET', 'ACTION']
|
|
274
|
+
const body = rows.map((row) => [
|
|
275
|
+
row.name,
|
|
276
|
+
row.current ?? '-',
|
|
277
|
+
row.target ?? '-',
|
|
278
|
+
ACTION_LABEL[row.action] ?? row.action,
|
|
279
|
+
])
|
|
280
|
+
const widths = header.map((title, column) =>
|
|
281
|
+
Math.max(title.length, ...body.map((cells) => cells[column].length)),
|
|
282
|
+
)
|
|
283
|
+
const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd()
|
|
284
|
+
return [line(header), ...body.map(line)].join('\n')
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The last `count` non-empty lines of a command's stderr. */
|
|
288
|
+
function tailLines(text, count = 10) {
|
|
289
|
+
const lines = String(text ?? '')
|
|
290
|
+
.trimEnd()
|
|
291
|
+
.split(/\r?\n/)
|
|
292
|
+
.filter((line) => line !== '')
|
|
293
|
+
return lines.slice(-count)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Semver-equal per provision-plan's single comparison rule. */
|
|
297
|
+
function sameVersion(a, b) {
|
|
298
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false
|
|
299
|
+
if (a === b) return true
|
|
300
|
+
return Boolean(parseVersion(a) && parseVersion(b) && compareVersions(a, b) === 0)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** `20261116T142530Z` — sortable and filename-safe. */
|
|
304
|
+
function backupStamp(now = new Date()) {
|
|
305
|
+
return now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
// Phase: self upgrade
|
|
310
|
+
// ---------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Bring the launcher itself up to `target`, but only when the running copy is
|
|
314
|
+
* the one the npm global prefix owns.
|
|
315
|
+
*
|
|
316
|
+
* @returns {{ kind: 'skipped', form: string } |
|
|
317
|
+
* { kind: 'latest', version: string } |
|
|
318
|
+
* { kind: 'upgraded', from: string, to: string } |
|
|
319
|
+
* { kind: 'failed', exitCode: 1 }}
|
|
320
|
+
*/
|
|
321
|
+
function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
|
|
322
|
+
if (!self || typeof target !== 'string' || target === '') {
|
|
323
|
+
say('self: skipped (install form: unknown)')
|
|
324
|
+
warn(
|
|
325
|
+
'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
|
|
326
|
+
)
|
|
327
|
+
return { kind: 'skipped', form: 'unknown' }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Install form: only a copy under `<npm prefix -g>/lib/node_modules/<name>`
|
|
331
|
+
// is ours to replace. Anything else (source tree, a copy in another prefix)
|
|
332
|
+
// must not be upgraded from here.
|
|
333
|
+
const prefixResult = run('npm', ['prefix', '-g'], { timeout: PREFIX_TIMEOUT_MS })
|
|
334
|
+
let form = 'unknown'
|
|
335
|
+
let globalPkgDir = null
|
|
336
|
+
if (prefixResult && prefixResult.status === 0) {
|
|
337
|
+
const prefix = String(prefixResult.stdout ?? '').trim()
|
|
338
|
+
if (prefix !== '') {
|
|
339
|
+
globalPkgDir = join(prefix, 'lib', 'node_modules', ...self.name.split('/'))
|
|
340
|
+
form = isInside(globalPkgDir, selfPath) ? 'global-npm' : 'foreign'
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (form !== 'global-npm' || globalPkgDir === null) {
|
|
345
|
+
say(`self: skipped (install form: ${form})`)
|
|
346
|
+
warn(
|
|
347
|
+
'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
|
|
348
|
+
)
|
|
349
|
+
return { kind: 'skipped', form }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (sameVersion(self.version, target)) {
|
|
353
|
+
say(`self: already up to date (${self.version})`)
|
|
354
|
+
return { kind: 'latest', version: self.version }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const install = run('npm', ['i', '-g', `${self.name}@${target}`, '--registry', registry], {
|
|
358
|
+
timeout: INSTALL_TIMEOUT_MS,
|
|
359
|
+
})
|
|
360
|
+
if (!install || install.status !== 0) {
|
|
361
|
+
const tail = tailLines(install?.stderr, 10)
|
|
362
|
+
if (tail.length > 0) console.error(tail.join('\n'))
|
|
363
|
+
if (/EACCES|permission denied/i.test(String(install?.stderr ?? ''))) {
|
|
364
|
+
say(`try npm i -g ${self.name}@${target} with a writable prefix`)
|
|
365
|
+
}
|
|
366
|
+
say('upgrade aborted; profile untouched')
|
|
367
|
+
return { kind: 'failed', exitCode: 1 }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Landing check reads the INSTALLED copy, never the running pkgRoot: npm may
|
|
371
|
+
// have replaced the directory this process was loaded from.
|
|
372
|
+
const landed = readJson(fs, join(globalPkgDir, 'package.json'))
|
|
373
|
+
const actual = isPlainObject(landed) && typeof landed.version === 'string' ? landed.version : undefined
|
|
374
|
+
if (actual !== target) {
|
|
375
|
+
say(`installed ${actual ?? 'nothing'}, expected ${target}`)
|
|
376
|
+
say('upgrade aborted; profile untouched')
|
|
377
|
+
return { kind: 'failed', exitCode: 1 }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
say(`upgraded ${self.name} ${self.version} -> ${target}`)
|
|
381
|
+
say(`this process still runs the old code; quit and re-run \`dsh-opentui\` to start on ${target}`)
|
|
382
|
+
return { kind: 'upgraded', from: self.version, to: target }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ---------------------------------------------------------------------------
|
|
386
|
+
// Phase: plugins
|
|
387
|
+
//
|
|
388
|
+
// The install is deliberately ONE `dsh plugin ... add` for every target: the
|
|
389
|
+
// host takes the profile lock once, saves/restores package.json + lock around
|
|
390
|
+
// the run, and pnpm resolves the batch as a whole. Per-package calls would
|
|
391
|
+
// turn one bad version into "3 landed, 1 failed" and leave the profile
|
|
392
|
+
// inconsistent, so a failure rolls the whole batch back instead.
|
|
393
|
+
// ---------------------------------------------------------------------------
|
|
394
|
+
|
|
395
|
+
/** Numeric exit status of an injected run result; missing results count as 1. */
|
|
396
|
+
function runStatus(result) {
|
|
397
|
+
return result && typeof result.status === 'number' ? result.status : 1
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** argv tail for the batched install (and for the rollback convergence). */
|
|
401
|
+
function pluginAddArgs(specs, { saveExact = true } = {}) {
|
|
402
|
+
const args = ['plugin', '--profile', PROFILE, 'add']
|
|
403
|
+
if (saveExact) args.push(SAVE_EXACT)
|
|
404
|
+
return [...args, ...specs]
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Copy the files a rollback needs. Only files that EXIST are copied: a file
|
|
409
|
+
* that was never there must be re-absent after a rollback, which the caller
|
|
410
|
+
* infers from the missing key (it deletes the override path in that case).
|
|
411
|
+
*
|
|
412
|
+
* @returns {Record<string, string>} original file name -> backup copy path
|
|
413
|
+
*/
|
|
414
|
+
function createBackup({ fs, profileDir, backupDir }) {
|
|
415
|
+
fs.mkdirSync(backupDir, { recursive: true })
|
|
416
|
+
const copies = {}
|
|
417
|
+
for (const name of BACKUP_FILE_NAMES) {
|
|
418
|
+
const source = join(profileDir, name)
|
|
419
|
+
if (!fs.existsSync(source)) continue
|
|
420
|
+
const target = join(backupDir, name)
|
|
421
|
+
fs.copyFileSync(source, target)
|
|
422
|
+
copies[name] = target
|
|
423
|
+
}
|
|
424
|
+
return copies
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Put the profile back the way the backup found it. `package.json` and the
|
|
429
|
+
* lock are copy-restored; `upgrade-overrides.json` is restored when it was
|
|
430
|
+
* backed up, and REMOVED when it was not (a rollback must not leave behind a
|
|
431
|
+
* file the user never had).
|
|
432
|
+
*/
|
|
433
|
+
function restoreBackup({ fs, profileDir, overridePath, copies }) {
|
|
434
|
+
for (const [name, copy] of Object.entries(copies)) {
|
|
435
|
+
fs.copyFileSync(copy, join(profileDir, name))
|
|
436
|
+
}
|
|
437
|
+
if (!Object.prototype.hasOwnProperty.call(copies, OVERRIDE_FILE)) {
|
|
438
|
+
fs.rmSync(overridePath, { force: true })
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Remove the backup after a fully successful run: the stamp directory first,
|
|
444
|
+
* then its hidden `.upgrade-backup` parent when it is empty. `rmdir` (not
|
|
445
|
+
* `rm -r`) is deliberate — it refuses to touch a parent that still holds
|
|
446
|
+
* another run's backup (ENOTEMPTY is ignored), so concurrent upgrades cannot
|
|
447
|
+
* delete each other's rollback material. The failure paths never call this.
|
|
448
|
+
*/
|
|
449
|
+
function removeSuccessfulBackup({ fs, backupDir }) {
|
|
450
|
+
fs.rmSync(backupDir, { recursive: true, force: true })
|
|
451
|
+
try {
|
|
452
|
+
fs.rmdirSync(dirname(backupDir))
|
|
453
|
+
} catch {
|
|
454
|
+
/* not empty, already gone, or not ours to remove — leave it */
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** The specs of the pre-upgrade manifest, read from its BACKUP copy (the live
|
|
459
|
+
* manifest may already have been rewritten by the host). Local and host
|
|
460
|
+
* specs are skipped: they are not installable from the registry. */
|
|
461
|
+
function originalSpecs({ fs, copies, manifestPath }) {
|
|
462
|
+
const manifest = readJson(fs, copies['package.json'] ?? manifestPath)
|
|
463
|
+
const dependencies = isPlainObject(manifest?.dependencies) ? manifest.dependencies : {}
|
|
464
|
+
return Object.entries(dependencies)
|
|
465
|
+
.filter(([name, spec]) => isUpgradableDependency(name, spec))
|
|
466
|
+
.map(([name, spec]) => `${name}@${spec}`)
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* One batched install. A host that rejects `--save-exact` gets exactly one
|
|
471
|
+
* retry without it; every other failure is final (no per-package retry).
|
|
472
|
+
*
|
|
473
|
+
* @returns {{ status: number, args: string[], stderr: string }}
|
|
474
|
+
*/
|
|
475
|
+
function installPlugins({ run, env, specs, warn }) {
|
|
476
|
+
let args = pluginAddArgs(specs)
|
|
477
|
+
let result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
|
|
478
|
+
let status = runStatus(result)
|
|
479
|
+
if (status === 0) return { status, args, stderr: '' }
|
|
480
|
+
|
|
481
|
+
const stderr = String(result?.stderr ?? '')
|
|
482
|
+
if (SAVE_EXACT_REJECTED.test(stderr)) {
|
|
483
|
+
warn('--save-exact not supported by host; relying on upgrade-overrides')
|
|
484
|
+
args = pluginAddArgs(specs, { saveExact: false })
|
|
485
|
+
result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
|
|
486
|
+
status = runStatus(result)
|
|
487
|
+
if (status === 0) return { status, args, stderr: '' }
|
|
488
|
+
}
|
|
489
|
+
return { status, args, stderr }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Strict per-package check: only an exact string match counts as landed. */
|
|
493
|
+
function verifyPlugins({ fs, profileDir, rows }) {
|
|
494
|
+
const landed = []
|
|
495
|
+
const mismatched = []
|
|
496
|
+
for (const row of rows) {
|
|
497
|
+
const actual = readInstalledVersion(fs, profileDir, row.name)
|
|
498
|
+
if (actual !== undefined && actual === row.target) {
|
|
499
|
+
landed.push({ name: row.name, version: actual, from: row.current })
|
|
500
|
+
} else {
|
|
501
|
+
mismatched.push({ name: row.name, expected: row.target, actual: actual ?? null })
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return { landed, mismatched }
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Merge the landed packages into the override document.
|
|
509
|
+
*
|
|
510
|
+
* An entry is only added when `resolveEffectivePin` — the single authority
|
|
511
|
+
* provisioning also uses — agrees the entry would take effect. That one check
|
|
512
|
+
* covers all the ways an entry is useless: a package outside PLUGIN_SET, a
|
|
513
|
+
* version that is not newer than the shipped pin (stale or downgrade), and a
|
|
514
|
+
* version that does not parse.
|
|
515
|
+
*
|
|
516
|
+
* @returns {{
|
|
517
|
+
* packages: Record<string, unknown>,
|
|
518
|
+
* written: string[],
|
|
519
|
+
* atPin: string[],
|
|
520
|
+
* ineffective: Array<{ name: string, reason: string }>,
|
|
521
|
+
* }}
|
|
522
|
+
*/
|
|
523
|
+
function planOverrides({ packages, landed, updatedAt }) {
|
|
524
|
+
const next = { ...packages }
|
|
525
|
+
const written = []
|
|
526
|
+
const atPin = []
|
|
527
|
+
const ineffective = []
|
|
528
|
+
|
|
529
|
+
for (const entry of landed) {
|
|
530
|
+
const shippedPin = SHIPPED_PINS.get(entry.name)
|
|
531
|
+
if (shippedPin !== undefined && entry.version === shippedPin) {
|
|
532
|
+
// The profile is already on the shipped pin: an override would restate
|
|
533
|
+
// it, so the package counts as up to date instead of upgraded.
|
|
534
|
+
atPin.push(entry.name)
|
|
535
|
+
continue
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const candidate = {
|
|
539
|
+
...next,
|
|
540
|
+
[entry.name]: { version: entry.version, shippedPin: shippedPin ?? null, updatedAt },
|
|
541
|
+
}
|
|
542
|
+
const effective = resolveEffectivePin({ name: entry.name, shippedPin, overrides: candidate })
|
|
543
|
+
if (effective !== entry.version) {
|
|
544
|
+
ineffective.push({ name: entry.name, version: entry.version, shippedPin: shippedPin ?? null })
|
|
545
|
+
continue
|
|
546
|
+
}
|
|
547
|
+
next[entry.name] = candidate[entry.name]
|
|
548
|
+
written.push(entry.name)
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return { packages: next, written, atPin, ineffective }
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** The rollback's second half: re-add the pre-upgrade specs so node_modules
|
|
555
|
+
* matches the restored manifest again. A failure here is reported with the
|
|
556
|
+
* exact command the user can run by hand. */
|
|
557
|
+
function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
|
|
558
|
+
const specs = originalSpecs({ fs, copies, manifestPath })
|
|
559
|
+
if (specs.length === 0) return
|
|
560
|
+
|
|
561
|
+
const result = run('dsh', pluginAddArgs(specs), { timeout: INSTALL_TIMEOUT_MS, env })
|
|
562
|
+
const status = runStatus(result)
|
|
563
|
+
if (status === 0) {
|
|
564
|
+
log(`restored the previous plugin versions (${specs.length} spec(s))`)
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
warn(`could not restore the previous plugin versions (dsh plugin add exit ${status})`)
|
|
568
|
+
warn(`run this by hand to restore them: dsh plugin --profile ${PROFILE} add ${specs.join(' ')}`)
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Phase 4: install every planned plugin upgrade, verify it landed, and record
|
|
573
|
+
* the landed versions in `upgrade-overrides.json`.
|
|
574
|
+
*
|
|
575
|
+
* Outcomes (they map 1:1 to the process exit code, see exitCodeAfterPlugins):
|
|
576
|
+
* - all landed, overrides written or unnecessary -> backup deleted, code 0
|
|
577
|
+
* - install failed -> rollback, backup kept, code 1
|
|
578
|
+
* - install ok, some version did not land -> no rollback, code 3
|
|
579
|
+
* - override write failed -> code 3
|
|
580
|
+
*
|
|
581
|
+
* @param {{
|
|
582
|
+
* profileDir: string, manifestPath: string, overridePath: string,
|
|
583
|
+
* backupDir: string, pluginRows: Array<{name: string, current: string|null, target: string}>,
|
|
584
|
+
* rows: Array<{name: string, action: string}>,
|
|
585
|
+
* counts: {latest: number, excluded: number}, selfName: string|null,
|
|
586
|
+
* env: Record<string, string|undefined>,
|
|
587
|
+
* run: Function, fs: typeof defaultFs,
|
|
588
|
+
* log: (message: string) => void, warn: (message: string) => void,
|
|
589
|
+
* }} ctx
|
|
590
|
+
* @returns {{
|
|
591
|
+
* landed: Array<{name: string, version: string, from: string|null}>,
|
|
592
|
+
* mismatched: Array<{name: string, expected: string, actual: string|null}>,
|
|
593
|
+
* failed: Array<{reason: string, status?: number}>,
|
|
594
|
+
* overridesError?: boolean,
|
|
595
|
+
* upgraded?: number,
|
|
596
|
+
* upToDate?: number,
|
|
597
|
+
* }}
|
|
598
|
+
*/
|
|
599
|
+
function applyPluginUpgrades(ctx) {
|
|
600
|
+
const { profileDir, manifestPath, overridePath, backupDir, rows, pluginRows, counts, selfName, env, run, fs, log, warn } =
|
|
601
|
+
ctx
|
|
602
|
+
|
|
603
|
+
if (pluginRows.length === 0) {
|
|
604
|
+
log('plugins: already up to date')
|
|
605
|
+
return { landed: [], mismatched: [], failed: [] }
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const specs = pluginRows.map((row) => `${row.name}@${row.target}`)
|
|
609
|
+
const copies = createBackup({ fs, profileDir, backupDir })
|
|
610
|
+
log(`backup: ${backupDir}`)
|
|
611
|
+
log(`plugins: installing ${specs.length} package(s)`)
|
|
612
|
+
|
|
613
|
+
const install = installPlugins({ run, env, specs, warn })
|
|
614
|
+
if (install.status !== 0) {
|
|
615
|
+
const tail = tailLines(install.stderr, 10)
|
|
616
|
+
if (tail.length > 0) console.error(tail.join('\n'))
|
|
617
|
+
restoreBackup({ fs, profileDir, overridePath, copies })
|
|
618
|
+
convergeProfile({ fs, run, env, copies, manifestPath, log, warn })
|
|
619
|
+
log(`upgrade failed at plugin install; profile restored from ${backupDir}`)
|
|
620
|
+
log('if the profile still looks wrong, fix it by hand before starting the TUI')
|
|
621
|
+
return { landed: [], mismatched: [], failed: [{ reason: 'install', status: install.status }] }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const { landed, mismatched } = verifyPlugins({ fs, profileDir, rows: pluginRows })
|
|
625
|
+
for (const item of mismatched) {
|
|
626
|
+
log(`mismatch: ${item.name} expected ${item.expected}, installed ${item.actual ?? 'nothing'}`)
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// --- overrides: read, merge, assert, write -------------------------------
|
|
630
|
+
// A file that is not a usable override document is left UNTOUCHED: it may
|
|
631
|
+
// hold hand-edited entries this module would silently drop. Nothing is
|
|
632
|
+
// recorded in that case (the run reports a partial result), and the file is
|
|
633
|
+
// in the backup if the user wants it back.
|
|
634
|
+
const existingText = readText(fs, overridePath)
|
|
635
|
+
const parsed = existingText === undefined ? null : parseOverrides(existingText)
|
|
636
|
+
const unusable = existingText !== undefined && parsed === null
|
|
637
|
+
if (unusable) {
|
|
638
|
+
warn(
|
|
639
|
+
`${overridePath} is not a usable override document; leaving it untouched — fix or delete it and re-run, or the next start will reinstall the shipped pins`,
|
|
640
|
+
)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
let overridesError = unusable
|
|
644
|
+
let written = []
|
|
645
|
+
let atPin = []
|
|
646
|
+
if (!unusable) {
|
|
647
|
+
const document = parsed ?? { version: 1, packages: {} }
|
|
648
|
+
const updatedAt = new Date().toISOString()
|
|
649
|
+
const plan = planOverrides({ packages: document.packages ?? {}, landed, updatedAt })
|
|
650
|
+
written = plan.written
|
|
651
|
+
atPin = plan.atPin
|
|
652
|
+
|
|
653
|
+
for (const item of plan.ineffective) {
|
|
654
|
+
if (item.shippedPin === null) {
|
|
655
|
+
// The package is not in PLUGIN_SET, so provisioning never installs or
|
|
656
|
+
// converges it: an override would be dead data, not a lost upgrade.
|
|
657
|
+
warn(`${item.name}: not managed by provisioning; no override recorded`)
|
|
658
|
+
continue
|
|
659
|
+
}
|
|
660
|
+
warn(
|
|
661
|
+
`${item.name}: an override at ${item.version} would be ignored by provisioning (shipped pin ${item.shippedPin}); not recorded — the next start will reinstall the shipped pin`,
|
|
662
|
+
)
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
if (written.length > 0) {
|
|
666
|
+
const nextDocument = { ...document, version: document.version ?? 1, updatedAt, packages: plan.packages }
|
|
667
|
+
// Write-then-rename in the SAME directory: a crash mid-write cannot leave
|
|
668
|
+
// a torn upgrade-overrides.json that provisioning would silently ignore.
|
|
669
|
+
const tmpPath = `${overridePath}.tmp`
|
|
670
|
+
try {
|
|
671
|
+
fs.writeFileSync(tmpPath, serializeOverrides(nextDocument), 'utf8')
|
|
672
|
+
fs.renameSync(tmpPath, overridePath)
|
|
673
|
+
log(`wrote ${written.length} override(s) to ${overridePath}`)
|
|
674
|
+
} catch (err) {
|
|
675
|
+
overridesError = true
|
|
676
|
+
warn(`could not write ${overridePath}: ${err?.message ?? err}`)
|
|
677
|
+
warn('the next start may reinstall the shipped pins and downgrade these plugins')
|
|
678
|
+
log(`override write failed; backup kept at ${backupDir}`)
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// --- summary + exit-code material ---------------------------------------
|
|
684
|
+
// The launcher has its own row and its own report, so it never counts here.
|
|
685
|
+
const latestPlugins = rows.filter(
|
|
686
|
+
(row) => row.action === 'latest' && (selfName === null || row.name !== selfName),
|
|
687
|
+
).length
|
|
688
|
+
const upgraded = landed.length - atPin.length
|
|
689
|
+
const upToDate = latestPlugins + atPin.length
|
|
690
|
+
log(
|
|
691
|
+
`${upgraded} upgraded, ${upToDate} up to date, ${mismatched.length} mismatched, ${counts.excluded} excluded`,
|
|
692
|
+
)
|
|
693
|
+
log('restart required: exit the TUI and run dsh-opentui again')
|
|
694
|
+
|
|
695
|
+
if (mismatched.length > 0) {
|
|
696
|
+
log(
|
|
697
|
+
'packages without an override will be reinstalled at the shipped pin on the next start (possible downgrade)',
|
|
698
|
+
)
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (mismatched.length === 0 && !overridesError) {
|
|
702
|
+
removeSuccessfulBackup({ fs, backupDir })
|
|
703
|
+
log(`upgraded ${upgraded} plugin(s)`)
|
|
704
|
+
} else {
|
|
705
|
+
log(`backup kept at ${backupDir}`)
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return { landed, mismatched, failed: [], overridesError, upgraded, upToDate }
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Exit code after the plugin phase (plan §1.3):
|
|
713
|
+
* 1 - the batched install failed and the profile was rolled back;
|
|
714
|
+
* 3 - partially applied: the install exited 0 but a package is not at its
|
|
715
|
+
* target version, or the override file could not be written;
|
|
716
|
+
* 0 - every target is on disk at its planned version.
|
|
717
|
+
*/
|
|
718
|
+
function exitCodeAfterPlugins({ pluginResult } = {}) {
|
|
719
|
+
if (!pluginResult) return 0
|
|
720
|
+
if (Array.isArray(pluginResult.failed) && pluginResult.failed.length > 0) return 1
|
|
721
|
+
if (pluginResult.overridesError) return 3
|
|
722
|
+
if (Array.isArray(pluginResult.mismatched) && pluginResult.mismatched.length > 0) return 3
|
|
723
|
+
return 0
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// ---------------------------------------------------------------------------
|
|
727
|
+
// Entry point
|
|
728
|
+
// ---------------------------------------------------------------------------
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Run the upgrade command and return the process exit code.
|
|
732
|
+
*
|
|
733
|
+
* @param {{
|
|
734
|
+
* dryRun?: boolean, yes?: boolean, tag?: string, noSelf?: boolean,
|
|
735
|
+
* noPlugins?: boolean, resetOverrides?: boolean, help?: boolean,
|
|
736
|
+
* }} [opts]
|
|
737
|
+
* @param {{
|
|
738
|
+
* pkgRoot?: string,
|
|
739
|
+
* env?: Record<string, string | undefined>,
|
|
740
|
+
* run?: (cmd: string, args: string[], options?: { timeout?: number }) =>
|
|
741
|
+
* { status: number, stdout: string, stderr: string },
|
|
742
|
+
* fs?: typeof defaultFs,
|
|
743
|
+
* selfPath?: string,
|
|
744
|
+
* isTTY?: boolean,
|
|
745
|
+
* readLine?: () => string,
|
|
746
|
+
* prompt?: (text: string) => void,
|
|
747
|
+
* }} [context]
|
|
748
|
+
* @returns {number} 0 done / nothing to do / --dry-run / --help,
|
|
749
|
+
* 1 hard failure or an undetermined target version, 2 non-interactive
|
|
750
|
+
* refusal (the bin owns the other usage errors), 3 partially applied
|
|
751
|
+
*/
|
|
752
|
+
export function runUpgrade(
|
|
753
|
+
opts = {},
|
|
754
|
+
{
|
|
755
|
+
pkgRoot = defaultPkgRoot(),
|
|
756
|
+
env = process.env,
|
|
757
|
+
run = defaultRun,
|
|
758
|
+
fs = defaultFs,
|
|
759
|
+
selfPath = fileURLToPath(import.meta.url),
|
|
760
|
+
isTTY = Boolean(process.stdin.isTTY),
|
|
761
|
+
readLine = defaultReadLine,
|
|
762
|
+
prompt = defaultPrompt,
|
|
763
|
+
} = {},
|
|
764
|
+
) {
|
|
765
|
+
if (opts.help) {
|
|
766
|
+
console.log(formatUpgradeUsage())
|
|
767
|
+
return 0
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const dshHome = env.DSH_HOME || join(homedir(), '.dsh')
|
|
771
|
+
const profileDir = join(dshHome, 'profiles', PROFILE)
|
|
772
|
+
const manifestPath = join(profileDir, 'package.json')
|
|
773
|
+
const overridePath = join(profileDir, OVERRIDE_FILE)
|
|
774
|
+
|
|
775
|
+
// --- --reset-overrides: a terminal action, never a step of the upgrade ---
|
|
776
|
+
if (opts.resetOverrides) {
|
|
777
|
+
if (!fs.existsSync(overridePath)) {
|
|
778
|
+
say('no overrides to reset')
|
|
779
|
+
return 0
|
|
780
|
+
}
|
|
781
|
+
if (opts.dryRun) {
|
|
782
|
+
say(`would remove ${overridePath}`)
|
|
783
|
+
return 0
|
|
784
|
+
}
|
|
785
|
+
fs.rmSync(overridePath, { force: true })
|
|
786
|
+
say(`removed ${overridePath}`)
|
|
787
|
+
warn('next provisioning will restore shipped pins; plugins may be downgraded')
|
|
788
|
+
return 0
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
if (!fs.existsSync(profileDir)) {
|
|
792
|
+
say(`no opentui profile at ${profileDir}; run dsh-opentui once to provision it`)
|
|
793
|
+
return 0
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// --- 1. Plan (read-only) -------------------------------------------------
|
|
797
|
+
const manifest = readJson(fs, manifestPath)
|
|
798
|
+
if (!isPlainObject(manifest)) {
|
|
799
|
+
warn(`could not read ${manifestPath}; treating the profile as having no plugin dependencies`)
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const { registry, source } = resolveRegistry({
|
|
803
|
+
env,
|
|
804
|
+
npmrcTexts: collectNpmrcTexts({ fs, dshHome, profileDir, env }),
|
|
805
|
+
})
|
|
806
|
+
|
|
807
|
+
const tag = opts.tag ?? 'latest'
|
|
808
|
+
say(`dsh home ${dshHome} · profile ${PROFILE} · tag ${tag}`)
|
|
809
|
+
say(`registry ${registry} (source: ${source})`)
|
|
810
|
+
if (!isOfficialRegistry(registry)) {
|
|
811
|
+
say(`note: resolved via ${registry}; "${tag}" may lag behind npmjs`)
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// `deps` keeps the excluded entries too: buildUpgradePlan must report them
|
|
815
|
+
// as `excluded` rather than silently dropping them from the table.
|
|
816
|
+
const deps = {}
|
|
817
|
+
const installedVersions = {}
|
|
818
|
+
|
|
819
|
+
if (!opts.noPlugins) {
|
|
820
|
+
const dependencies = isPlainObject(manifest?.dependencies) ? manifest.dependencies : {}
|
|
821
|
+
for (const [name, spec] of Object.entries(dependencies)) {
|
|
822
|
+
deps[name] = spec
|
|
823
|
+
const installed = readInstalledVersion(fs, profileDir, name)
|
|
824
|
+
if (installed !== undefined) installedVersions[name] = installed
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const self = opts.noSelf ? null : readSelf(fs, pkgRoot)
|
|
829
|
+
if (self !== null && !Object.prototype.hasOwnProperty.call(deps, self.name)) {
|
|
830
|
+
// The launcher is not a profile dependency; give it a row of its own so
|
|
831
|
+
// "the launcher is already up to date" is visible instead of implied.
|
|
832
|
+
deps[self.name] = self.version
|
|
833
|
+
installedVersions[self.name] = self.version
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// Excluded entries (`@deepseek-ai/*`, local specs) are never queried: their
|
|
837
|
+
// target is meaningless by definition.
|
|
838
|
+
const latestByPkg = {}
|
|
839
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
840
|
+
if (!isUpgradableDependency(name, spec)) continue
|
|
841
|
+
const target = queryDistTag({ run, pkg: name, registry, tag })
|
|
842
|
+
if (target !== null) latestByPkg[name] = target
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
const { rows, counts } = buildUpgradePlan({ deps, installedVersions, latestByPkg, tag })
|
|
846
|
+
|
|
847
|
+
console.log(formatPlanTable(rows))
|
|
848
|
+
console.log(
|
|
849
|
+
`${counts.upgrade} to upgrade, ${counts.latest} up to date, ${counts.queryFailed} failed, ${counts.excluded} excluded`,
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
// An undetermined target is not a satisfied package: without a target there
|
|
853
|
+
// is nothing to install, so the run must not claim success — and it writes
|
|
854
|
+
// nothing, --dry-run included.
|
|
855
|
+
if (counts.queryFailed > 0) {
|
|
856
|
+
say(`could not determine target version for ${counts.queryFailed} package(s); nothing changed`)
|
|
857
|
+
return 1
|
|
858
|
+
}
|
|
859
|
+
if (opts.dryRun) return 0
|
|
860
|
+
if (counts.upgrade === 0) {
|
|
861
|
+
// No target needs work: there is nothing to back up and nothing to spawn.
|
|
862
|
+
say(opts.noPlugins ? 'plugins: skipped (--no-plugins)' : 'plugins: already up to date')
|
|
863
|
+
say('nothing to do')
|
|
864
|
+
return 0
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// --- 2. Confirmation -----------------------------------------------------
|
|
868
|
+
if (!opts.yes) {
|
|
869
|
+
if (env.CI || !isTTY) {
|
|
870
|
+
console.error(`${PREFIX}refusing to run non-interactively; pass --yes`)
|
|
871
|
+
return 2
|
|
872
|
+
}
|
|
873
|
+
prompt('Proceed with upgrade? [y/N] ')
|
|
874
|
+
const answer = String(readLine() ?? '').trim().toLowerCase()
|
|
875
|
+
if (answer !== 'y' && answer !== 'yes') {
|
|
876
|
+
say('aborted')
|
|
877
|
+
return 0
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// --- 3. Self upgrade -----------------------------------------------------
|
|
882
|
+
const selfRow = self === null ? undefined : rows.find((row) => row.name === self.name)
|
|
883
|
+
let selfResult
|
|
884
|
+
if (opts.noSelf) {
|
|
885
|
+
say('self: skipped (--no-self)')
|
|
886
|
+
selfResult = { kind: 'skipped', form: 'skipped-by-flag' }
|
|
887
|
+
} else {
|
|
888
|
+
selfResult = upgradeSelf({
|
|
889
|
+
self,
|
|
890
|
+
target: selfRow?.target ?? null,
|
|
891
|
+
registry,
|
|
892
|
+
run,
|
|
893
|
+
fs,
|
|
894
|
+
selfPath,
|
|
895
|
+
})
|
|
896
|
+
if (selfResult.kind === 'failed') return selfResult.exitCode
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// --- 4. Plugins ----------------------------------------------------------
|
|
900
|
+
const pluginRows = rows.filter(
|
|
901
|
+
(row) => row.action === 'upgrade' && (self === null || row.name !== self.name),
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
if (opts.noPlugins) {
|
|
905
|
+
say('plugins: skipped (--no-plugins)')
|
|
906
|
+
return 0
|
|
907
|
+
}
|
|
908
|
+
if (pluginRows.length === 0) {
|
|
909
|
+
say('plugins: already up to date')
|
|
910
|
+
return 0
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
const ctx = {
|
|
914
|
+
// Locations
|
|
915
|
+
dshHome,
|
|
916
|
+
profileDir,
|
|
917
|
+
manifestPath,
|
|
918
|
+
overridePath,
|
|
919
|
+
// Plan
|
|
920
|
+
registry,
|
|
921
|
+
tag,
|
|
922
|
+
rows,
|
|
923
|
+
counts,
|
|
924
|
+
pluginRows,
|
|
925
|
+
installedVersions,
|
|
926
|
+
latestByPkg,
|
|
927
|
+
// Self result
|
|
928
|
+
selfName: self?.name ?? null,
|
|
929
|
+
selfResult,
|
|
930
|
+
// Where the plugin phase writes its backup (created there, not here):
|
|
931
|
+
// $DSH_HOME/profiles/opentui/.upgrade-backup/<UTC stamp>-<pid>/
|
|
932
|
+
backupDir: join(profileDir, BACKUP_DIR_NAME, `${backupStamp()}-${process.pid}`),
|
|
933
|
+
// Injected effects + logging
|
|
934
|
+
env,
|
|
935
|
+
run,
|
|
936
|
+
fs,
|
|
937
|
+
log: say,
|
|
938
|
+
warn,
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
const pluginResult = applyPluginUpgrades(ctx)
|
|
942
|
+
return exitCodeAfterPlugins({ pluginResult })
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function defaultPkgRoot() {
|
|
946
|
+
return dirname(dirname(fileURLToPath(import.meta.url)))
|
|
947
|
+
}
|