@aiwayds/dsh-opentui 0.27.2 → 0.28.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 +39 -15
- package/README.md +59 -178
- package/bin/dsh-opentui.mjs +70 -258
- package/bin/lib/launcher.mjs +36 -187
- package/dist/client/index.js +7636 -16519
- package/dist/client/index.js.map +28 -53
- package/dist/locales/en.json +15 -2
- package/dist/locales/zh-CN.json +15 -2
- package/package.json +7 -11
- package/scripts/lib/companion-policy.mjs +16 -0
- package/scripts/lib/inproc-companions.mjs +128 -38
- package/scripts/lib/migration-io.mjs +231 -0
- package/scripts/lib/migration.mjs +724 -0
- package/scripts/lib/patch-ownership-state.mjs +42 -0
- package/scripts/lib/patch-ownership.mjs +1428 -0
- package/scripts/lib/profile-lock.mjs +185 -0
- package/scripts/lib/profile-name.d.mts +1 -0
- package/scripts/lib/profile-name.mjs +2 -0
- package/scripts/lib/provision-run-lock.mjs +223 -0
- package/scripts/provision-inproc-profile.mjs +634 -286
- package/scripts/upgrade.mjs +445 -1110
- package/dist/host-launch.mjs +0 -1293
- package/dist/host-launch.mjs.map +0 -19
- package/dist/scripts/idle-reaper.mjs +0 -173
- package/dist/watchdog.mjs +0 -476
- package/dist/watchdog.mjs.map +0 -16
- package/scripts/e2e-client.mjs +0 -1122
- package/scripts/e2e-sweep.mjs +0 -932
- package/scripts/idle-reaper.mjs +0 -173
- package/scripts/lib/provision-plan.mjs +0 -899
- package/scripts/lib/provision-state.mjs +0 -294
- package/scripts/lib/upgrade-plan.mjs +0 -489
- package/scripts/provision-opentui-profile.mjs +0 -806
package/scripts/upgrade.mjs
CHANGED
|
@@ -1,1149 +1,484 @@
|
|
|
1
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)` — take the profile lock, back up
|
|
17
|
-
// the profile, run ONE batched `dsh plugin add`, verify each package on
|
|
18
|
-
// disk, and record the landed versions in upgrade-overrides.json. An
|
|
19
|
-
// install failure restores the backup and re-adds the pre-upgrade specs;
|
|
20
|
-
// a version that did not land is reported but never rolls back a
|
|
21
|
-
// successful install.
|
|
22
|
-
//
|
|
23
|
-
// Exit codes: 0 done/nothing to do/dry-run/help; 1 hard failure OR any package
|
|
24
|
-
// whose target version could not be determined (a query failure means the
|
|
25
|
-
// target is unknown, which is not "up to date"; nothing is written in that
|
|
26
|
-
// case); 2 usage refusal, or another upgrade already holds the profile lock;
|
|
27
|
-
// 3 partially applied (some package is not at its planned version, or the
|
|
28
|
-
// override file could not be written).
|
|
29
|
-
//
|
|
30
|
-
// Dependency injection: every child process goes through `run(cmd, args, {
|
|
31
|
-
// timeout })` and every file operation through `fs`, both overridable from the
|
|
32
|
-
// context argument. That is what lets the tests exercise the install, verify
|
|
33
|
-
// and abort paths without npm, a TTY, or a real profile.
|
|
34
|
-
import { execFileSync } from 'node:child_process'
|
|
35
|
-
import {
|
|
36
|
-
closeSync,
|
|
37
|
-
copyFileSync,
|
|
38
|
-
existsSync,
|
|
39
|
-
mkdirSync,
|
|
40
|
-
openSync,
|
|
41
|
-
readFileSync,
|
|
42
|
-
readSync,
|
|
43
|
-
realpathSync,
|
|
44
|
-
renameSync,
|
|
45
|
-
rmdirSync,
|
|
46
|
-
rmSync,
|
|
47
|
-
statSync,
|
|
48
|
-
writeFileSync,
|
|
49
|
-
writeSync,
|
|
50
|
-
} from 'node:fs'
|
|
51
|
-
import { homedir } from 'node:os'
|
|
52
|
-
import { dirname, join, resolve, sep } from 'node:path'
|
|
53
|
-
import { fileURLToPath } from 'node:url'
|
|
54
|
-
import { formatUpgradeUsage } from '../bin/lib/launcher.mjs'
|
|
55
|
-
import {
|
|
56
|
-
PLUGIN_SET,
|
|
57
|
-
PROFILE,
|
|
58
|
-
compareVersions,
|
|
59
|
-
parseVersion,
|
|
60
|
-
resolveEffectivePin,
|
|
61
|
-
} from './lib/provision-plan.mjs'
|
|
62
|
-
import {
|
|
63
|
-
NPMRC_DSH_HOME,
|
|
64
|
-
NPMRC_HOME,
|
|
65
|
-
NPMRC_PROFILE,
|
|
66
|
-
buildSelfInstallArgs,
|
|
67
|
-
buildUpgradePlan,
|
|
68
|
-
buildViewArgs,
|
|
69
|
-
isOfficialRegistry,
|
|
70
|
-
isUpgradableDependency,
|
|
71
|
-
parseOverrides,
|
|
72
|
-
resolveRegistry,
|
|
73
|
-
serializeOverrides,
|
|
74
|
-
} from './lib/upgrade-plan.mjs'
|
|
75
|
-
|
|
76
|
-
const PREFIX = 'dsh-opentui upgrade: '
|
|
77
|
-
// Matched to buildViewArgs' `--fetch-timeout 20000` (+ slack for npm startup
|
|
78
|
-
// and DNS): the child enforces its own fetch budget, so this backstop only
|
|
79
|
-
// matters when an argv flag is ignored (an old npm, a wrapper). Without the
|
|
80
|
-
// leftover margin a single dead registry would cost 60s per package.
|
|
81
|
-
const QUERY_TIMEOUT_MS = 25 * 1000
|
|
82
|
-
const PREFIX_TIMEOUT_MS = 10 * 1000
|
|
83
|
-
const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
|
|
84
|
-
const OVERRIDE_FILE = 'upgrade-overrides.json'
|
|
85
|
-
const BACKUP_DIR_NAME = '.upgrade-backup'
|
|
86
|
-
// Sits next to .provision-state.json in the profile dir: one lock per profile,
|
|
87
|
-
// held for the whole write phase (backup -> install -> override write).
|
|
88
|
-
const LOCK_FILE = '.upgrade.lock'
|
|
89
|
-
const LOCK_STALE_MS = 30 * 60 * 1000
|
|
90
|
-
// A lock file exists before its payload does: `openSync(..., 'wx')` wins the
|
|
91
|
-
// create and `writeSync` fills `{pid, startedAt}` a moment later. An unreadable
|
|
92
|
-
// payload is therefore evidence of a LIVE writer, not of a dead one, until the
|
|
93
|
-
// file itself is older than this window.
|
|
94
|
-
const LOCK_WRITE_GRACE_MS = 10 * 1000
|
|
95
|
-
// The contention line is printed verbatim (no `dsh-opentui upgrade: ` prefix):
|
|
96
|
-
// the user's question is "what is running", and the answer names the holder.
|
|
97
|
-
const LOCK_PREFIX = 'upgrade: '
|
|
98
|
-
const INSTALL_STDERR_PREFIX = 'dsh plugin add: '
|
|
99
|
-
// pnpm-workspace.yaml belongs here because users hand-write allowBuilds in it:
|
|
100
|
-
// a host rollback that restored only the manifest and the lock would leave the
|
|
101
|
-
// rewritten workspace file in place.
|
|
102
|
-
const BACKUP_FILE_NAMES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', OVERRIDE_FILE]
|
|
103
|
-
const SAVE_EXACT = '--save-exact'
|
|
104
|
-
// The host forwards unknown flags to pnpm, but a future argv parser could
|
|
105
|
-
// reject it; only a rejection of THIS flag earns the one retry without it.
|
|
106
|
-
const SAVE_EXACT_REJECTED = /save-exact|unknown option|unrecognized/i
|
|
107
|
-
|
|
108
|
-
/** The shipped pins, keyed by package name: the only versions provisioning
|
|
109
|
-
* may be raised above, so the only names an override can ever affect. */
|
|
110
|
-
const SHIPPED_PINS = new Map(PLUGIN_SET.map((plugin) => [plugin.name, plugin.version]))
|
|
111
|
-
|
|
112
|
-
const ACTION_LABEL = {
|
|
113
|
-
upgrade: 'upgrade',
|
|
114
|
-
latest: 'up to date',
|
|
115
|
-
'query-failed': 'query-failed',
|
|
116
|
-
excluded: 'excluded',
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const say = (message) => console.log(`${PREFIX}${message}`)
|
|
120
|
-
const warn = (message) => console.error(`${PREFIX}warning: ${message}`)
|
|
121
|
-
|
|
122
|
-
function isPlainObject(value) {
|
|
123
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ---------------------------------------------------------------------------
|
|
127
|
-
// Injected effects — the defaults used by the real CLI
|
|
128
|
-
// ---------------------------------------------------------------------------
|
|
129
|
-
|
|
130
2
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
3
|
+
* Minimal `dsh-opentui upgrade` — upgrade the launcher package itself, nothing
|
|
4
|
+
* else. No companions, no $DSH_HOME, no provisioning, no migration: those are
|
|
5
|
+
* the next launch's job. The only npm commands are `npm view`, `npm prefix -g`,
|
|
6
|
+
* `npm i -g` and (after install) the version re-check under the global prefix.
|
|
134
7
|
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
8
|
+
* WHY A SEPARATE MODULE: the bin is a top-level script (importing it would RUN
|
|
9
|
+
* it). Everything decision-making here is exported as a pure function over
|
|
10
|
+
* plain data; the process-touching parts (npm exec, package.json reads, logs,
|
|
11
|
+
* exit codes) are injected through `runUpgrade`'s context so tests never
|
|
12
|
+
* install anything.
|
|
138
13
|
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*/
|
|
144
|
-
export function defaultRun(cmd, args = [], { timeout, env } = {}) {
|
|
145
|
-
const childEnv = {}
|
|
146
|
-
if (env && typeof env === 'object') {
|
|
147
|
-
Object.assign(childEnv, process.env)
|
|
148
|
-
for (const [key, value] of Object.entries(env)) {
|
|
149
|
-
if (typeof value === 'string') childEnv[key] = value
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
try {
|
|
153
|
-
const stdout = execFileSync(cmd, args, {
|
|
154
|
-
encoding: 'utf8',
|
|
155
|
-
timeout,
|
|
156
|
-
...(env && typeof env === 'object' ? { env: childEnv } : {}),
|
|
157
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
158
|
-
})
|
|
159
|
-
return { status: 0, stdout: String(stdout ?? ''), stderr: '' }
|
|
160
|
-
} catch (err) {
|
|
161
|
-
return {
|
|
162
|
-
status: typeof err?.status === 'number' ? err.status : 1,
|
|
163
|
-
stdout: String(err?.stdout ?? ''),
|
|
164
|
-
stderr: String(err?.stderr ?? err?.message ?? ''),
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* The file operations the command needs, as an object so a test can replace
|
|
171
|
-
* the whole surface. Path-only helpers (`realpathSync` in canonicalPath) stay
|
|
172
|
-
* on the module import: the injected set deliberately covers reads/writes
|
|
173
|
-
* only, and canonicalPath remembers a path it was already given.
|
|
174
|
-
*/
|
|
175
|
-
export const defaultFs = {
|
|
176
|
-
readFileSync: (path, encoding) => readFileSync(path, encoding),
|
|
177
|
-
writeFileSync: (path, data, encoding) => writeFileSync(path, data, encoding),
|
|
178
|
-
existsSync: (path) => existsSync(path),
|
|
179
|
-
mkdirSync: (path, options) => mkdirSync(path, options),
|
|
180
|
-
rmSync: (path, options) => rmSync(path, options),
|
|
181
|
-
rmdirSync: (path) => rmdirSync(path),
|
|
182
|
-
copyFileSync: (from, to) => copyFileSync(from, to),
|
|
183
|
-
renameSync: (from, to) => renameSync(from, to),
|
|
184
|
-
// The lock is claimed with an exclusive create, so it needs the fd API:
|
|
185
|
-
// `openSync(path, 'wx')` is what makes "exactly one winner" atomic.
|
|
186
|
-
openSync: (path, flags) => openSync(path, flags),
|
|
187
|
-
writeSync: (fd, data) => writeSync(fd, data),
|
|
188
|
-
closeSync: (fd) => closeSync(fd),
|
|
189
|
-
// Only the lock's mtime is ever stat'ed: it dates the create->write window.
|
|
190
|
-
statSync: (path) => statSync(path),
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** A synchronous one-line read from stdin (the confirmation prompt). */
|
|
194
|
-
function defaultReadLine() {
|
|
195
|
-
const buffer = Buffer.alloc(1024)
|
|
196
|
-
try {
|
|
197
|
-
const read = readSync(0, buffer, 0, buffer.length, null)
|
|
198
|
-
return buffer.subarray(0, read).toString('utf8')
|
|
199
|
-
} catch {
|
|
200
|
-
return ''
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const defaultPrompt = (text) => process.stdout.write(text)
|
|
205
|
-
|
|
206
|
-
// ---------------------------------------------------------------------------
|
|
207
|
-
// Small readers
|
|
208
|
-
// ---------------------------------------------------------------------------
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* Absolute path for comparisons. Uses realpathSync when it resolves and falls
|
|
212
|
-
* back to a lexical resolve, so a path that only exists in a test fixture is
|
|
213
|
-
* still comparable (and a broken symlink never throws here).
|
|
214
|
-
*/
|
|
215
|
-
function canonicalPath(path) {
|
|
216
|
-
try {
|
|
217
|
-
return realpathSync(path)
|
|
218
|
-
} catch {
|
|
219
|
-
return resolve(path)
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** Is `child` the same as `parent` or below it? */
|
|
224
|
-
function isInside(parent, child) {
|
|
225
|
-
const base = canonicalPath(parent).replace(/\/+$/, '')
|
|
226
|
-
const target = canonicalPath(child)
|
|
227
|
-
return target === base || target.startsWith(`${base}${sep}`)
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/** Parsed JSON, or undefined for a missing/unreadable/malformed file. */
|
|
231
|
-
function readJson(fs, path) {
|
|
232
|
-
try {
|
|
233
|
-
return JSON.parse(fs.readFileSync(path, 'utf8'))
|
|
234
|
-
} catch {
|
|
235
|
-
return undefined
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** File contents, or undefined when the file cannot be read. */
|
|
240
|
-
function readText(fs, path) {
|
|
241
|
-
try {
|
|
242
|
-
const text = fs.readFileSync(path, 'utf8')
|
|
243
|
-
return typeof text === 'string' ? text : undefined
|
|
244
|
-
} catch {
|
|
245
|
-
return undefined
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/**
|
|
250
|
-
* The .npmrc files that may configure the registry, least specific first
|
|
251
|
-
* (resolveRegistry lets the LAST file win). Only files that exist are passed,
|
|
252
|
-
* so a missing file cannot shadow a present one: profile/.npmrc >
|
|
253
|
-
* $DSH_HOME/.npmrc > ~/.npmrc. Each entry carries the identity npm compares
|
|
254
|
-
* against, because npm itself reads only the first one.
|
|
255
|
-
*/
|
|
256
|
-
function collectNpmrcFiles({ fs, dshHome, profileDir, env }) {
|
|
257
|
-
const home = env.HOME || homedir()
|
|
258
|
-
const slots = [
|
|
259
|
-
[NPMRC_HOME, join(home, '.npmrc')],
|
|
260
|
-
[NPMRC_DSH_HOME, join(dshHome, '.npmrc')],
|
|
261
|
-
[NPMRC_PROFILE, join(profileDir, '.npmrc')],
|
|
262
|
-
]
|
|
263
|
-
const files = []
|
|
264
|
-
for (const [path, file] of slots) {
|
|
265
|
-
const text = readText(fs, file)
|
|
266
|
-
if (text !== undefined) files.push({ path, text })
|
|
267
|
-
}
|
|
268
|
-
return files
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** The version on disk for a profile dependency, when readable. */
|
|
272
|
-
function readInstalledVersion(fs, profileDir, name) {
|
|
273
|
-
const manifest = readJson(fs, join(profileDir, 'node_modules', ...name.split('/'), 'package.json'))
|
|
274
|
-
return isPlainObject(manifest) && typeof manifest.version === 'string' && manifest.version
|
|
275
|
-
? manifest.version
|
|
276
|
-
: undefined
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** The launcher's own name/version — read from ITS manifest, never guessed. */
|
|
280
|
-
function readSelf(fs, pkgRoot) {
|
|
281
|
-
const manifest = readJson(fs, join(pkgRoot, 'package.json'))
|
|
282
|
-
if (!isPlainObject(manifest)) return null
|
|
283
|
-
if (typeof manifest.name !== 'string' || manifest.name === '') return null
|
|
284
|
-
if (typeof manifest.version !== 'string' || manifest.version === '') return null
|
|
285
|
-
return { name: manifest.name, version: manifest.version }
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* `npm view <pkg> dist-tags --json` for one package. Returns the version the
|
|
290
|
-
* requested tag points at, or null when the query failed OR the tag is absent.
|
|
291
|
-
* A single package failing is recorded as `query-failed` by the caller.
|
|
14
|
+
* Registry contract (deliberately does NOT parse .npmrc): npm is trusted with
|
|
15
|
+
* its own configuration. `DSH_UPGRADE_REGISTRY` is the one explicit override —
|
|
16
|
+
* when set it is appended as `--registry <value>` to BOTH `npm view` and
|
|
17
|
+
* `npm i -g`, so resolution and installation cannot drift apart.
|
|
292
18
|
*/
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
} catch {
|
|
300
|
-
return null
|
|
301
|
-
}
|
|
302
|
-
if (!isPlainObject(tags)) return null
|
|
303
|
-
const version = tags[tag]
|
|
304
|
-
return typeof version === 'string' && version !== '' ? version : null
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** Plain, ANSI-free table with content-sized columns. */
|
|
308
|
-
function formatPlanTable(rows) {
|
|
309
|
-
const header = ['PACKAGE', 'CURRENT', 'TARGET', 'ACTION']
|
|
310
|
-
const body = rows.map((row) => [
|
|
311
|
-
row.name,
|
|
312
|
-
row.current ?? '-',
|
|
313
|
-
row.target ?? '-',
|
|
314
|
-
ACTION_LABEL[row.action] ?? row.action,
|
|
315
|
-
])
|
|
316
|
-
const widths = header.map((title, column) =>
|
|
317
|
-
Math.max(title.length, ...body.map((cells) => cells[column].length)),
|
|
318
|
-
)
|
|
319
|
-
const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd()
|
|
320
|
-
return [line(header), ...body.map(line)].join('\n')
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/** The last `count` non-empty lines of a command's stderr. */
|
|
324
|
-
function tailLines(text, count = 10) {
|
|
325
|
-
const lines = String(text ?? '')
|
|
326
|
-
.trimEnd()
|
|
327
|
-
.split(/\r?\n/)
|
|
328
|
-
.filter((line) => line !== '')
|
|
329
|
-
return lines.slice(-count)
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/** Semver-equal per provision-plan's single comparison rule. */
|
|
333
|
-
function sameVersion(a, b) {
|
|
334
|
-
if (typeof a !== 'string' || typeof b !== 'string') return false
|
|
335
|
-
if (a === b) return true
|
|
336
|
-
return Boolean(parseVersion(a) && parseVersion(b) && compareVersions(a, b) === 0)
|
|
337
|
-
}
|
|
19
|
+
import { spawnSync } from 'node:child_process'
|
|
20
|
+
import { lstatSync, realpathSync } from 'node:fs'
|
|
21
|
+
import { dirname, join, resolve } from 'node:path'
|
|
22
|
+
import { fileURLToPath } from 'node:url'
|
|
23
|
+
import { readLauncherVersion } from '../bin/lib/launcher.mjs'
|
|
24
|
+
import { compareVersions, isExactVersion } from './lib/host-compat.mjs'
|
|
338
25
|
|
|
339
|
-
|
|
340
|
-
function backupStamp(now = new Date()) {
|
|
341
|
-
return now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
|
|
342
|
-
}
|
|
26
|
+
export { compareVersions } from './lib/host-compat.mjs'
|
|
343
27
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
// describes a profile that no longer exists. The lock therefore covers the
|
|
350
|
-
// write phase only (backup -> install -> override write): a --dry-run, a
|
|
351
|
-
// no-op run, and the read-only plan never create the file.
|
|
352
|
-
// ---------------------------------------------------------------------------
|
|
353
|
-
|
|
354
|
-
/** The holder recorded in the lock file, or nulls when it cannot be read. */
|
|
355
|
-
function readLockHolder(fs, lockPath) {
|
|
356
|
-
const text = readText(fs, lockPath)
|
|
357
|
-
let doc
|
|
358
|
-
try {
|
|
359
|
-
doc = JSON.parse(String(text ?? ''))
|
|
360
|
-
} catch {
|
|
361
|
-
return { pid: null, startedAt: null }
|
|
362
|
-
}
|
|
363
|
-
if (!isPlainObject(doc)) return { pid: null, startedAt: null }
|
|
364
|
-
return {
|
|
365
|
-
pid: Number.isInteger(doc.pid) ? doc.pid : null,
|
|
366
|
-
startedAt: typeof doc.startedAt === 'string' ? doc.startedAt : null,
|
|
367
|
-
}
|
|
368
|
-
}
|
|
28
|
+
export const PACKAGE_NAME = '@aiwayds/dsh-opentui'
|
|
29
|
+
export const DEFAULT_TAG = 'latest'
|
|
30
|
+
export const REGISTRY_ENV = 'DSH_UPGRADE_REGISTRY'
|
|
31
|
+
const VIEW_TIMEOUT_MS = 15_000
|
|
32
|
+
const PREFIX_TIMEOUT_MS = 10_000
|
|
369
33
|
|
|
370
34
|
/**
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
* create->write window by mtime first (see lockIsInWriteWindow).
|
|
35
|
+
* Last-resort scrub for third-party text (npm's own error strings) that may
|
|
36
|
+
* embed a credential-bearing URL. Removes the userinfo segment only.
|
|
374
37
|
*/
|
|
375
|
-
function
|
|
376
|
-
|
|
377
|
-
const started = Date.parse(holder.startedAt)
|
|
378
|
-
if (Number.isNaN(started)) return true
|
|
379
|
-
return now - started > LOCK_STALE_MS
|
|
38
|
+
function redactSecrets(text) {
|
|
39
|
+
return String(text).replace(/\b(https?:\/\/)[^/@\s]+@/gi, (_match, scheme) => scheme)
|
|
380
40
|
}
|
|
381
41
|
|
|
382
42
|
/**
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* Returns false when the file cannot be stat'ed (it vanished or the fs has no
|
|
389
|
-
* stat): there is nothing left to protect, so the caller reclaims.
|
|
43
|
+
* Safe rendering of a registry URL for ANY user-visible output (commands we
|
|
44
|
+
* print, manual instructions, dry-run, error details). Credentials embedded in
|
|
45
|
+
* `https://user:token@host/` must never reach a terminal or CI log. The value
|
|
46
|
+
* passed to `npm` is always the ORIGINAL string — only display goes through
|
|
47
|
+
* here. Unparseable input is replaced, never echoed verbatim.
|
|
390
48
|
*/
|
|
391
|
-
function
|
|
392
|
-
|
|
49
|
+
export function displayRegistry(url) {
|
|
50
|
+
if (typeof url !== 'string' || url.trim() === '') return '<invalid registry>'
|
|
393
51
|
try {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
}
|
|
398
|
-
if (!Number.isFinite(mtimeMs)) return false
|
|
399
|
-
return now - mtimeMs < LOCK_WRITE_GRACE_MS
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Claim the lock. `openSync(path, 'wx')` is the atomic part: the kernel lets
|
|
404
|
-
* exactly one process create the file, so a claim needs no second check.
|
|
405
|
-
*
|
|
406
|
-
* A failed claim reads the holder and takes the lock over only when it is
|
|
407
|
-
* provably abandoned: a readable stamp older than LOCK_STALE_MS, or a
|
|
408
|
-
* payload-less file older than LOCK_WRITE_GRACE_MS (a fresh payload-less file
|
|
409
|
-
* belongs to a live process still inside the create->write window). One retry,
|
|
410
|
-
* then the caller reports the contention. Every operation goes through the
|
|
411
|
-
* injected `fs`, so the whole path is unit-testable.
|
|
412
|
-
*
|
|
413
|
-
* @param {{ fs: typeof defaultFs, lockPath: string, now?: number }} input
|
|
414
|
-
* @returns {{ ok: true, release: () => void } |
|
|
415
|
-
* { ok: false, holder: { pid: number|null, startedAt: string|null } }}
|
|
416
|
-
*/
|
|
417
|
-
function acquireUpgradeLock({ fs, lockPath, now = Date.now() }) {
|
|
418
|
-
const payload = JSON.stringify({ pid: process.pid, startedAt: new Date(now).toISOString() })
|
|
419
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
420
|
-
try {
|
|
421
|
-
const fd = fs.openSync(lockPath, 'wx')
|
|
422
|
-
try {
|
|
423
|
-
fs.writeSync(fd, payload)
|
|
424
|
-
} finally {
|
|
425
|
-
fs.closeSync(fd)
|
|
426
|
-
}
|
|
427
|
-
return { ok: true, release: () => fs.rmSync(lockPath, { force: true }) }
|
|
428
|
-
} catch (err) {
|
|
429
|
-
// Anything but "already exists" (an unwritable profile dir, say) is a
|
|
430
|
-
// real failure of the run, not contention: let it propagate.
|
|
431
|
-
if (err?.code !== 'EEXIST') throw err
|
|
432
|
-
const holder = readLockHolder(fs, lockPath)
|
|
433
|
-
// An unreadable payload has no age of its own: the file's mtime is the
|
|
434
|
-
// only evidence of who won the create. Inside the grace window another
|
|
435
|
-
// process may still be writing its payload, so the lock is held; only
|
|
436
|
-
// past it is a payload-less file provably garbage.
|
|
437
|
-
if (holder.startedAt === null) {
|
|
438
|
-
if (lockIsInWriteWindow(fs, lockPath, now)) return { ok: false, holder }
|
|
439
|
-
} else if (!isStaleLock(holder, now)) {
|
|
440
|
-
return { ok: false, holder }
|
|
441
|
-
}
|
|
442
|
-
fs.rmSync(lockPath, { force: true })
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
return { ok: false, holder: readLockHolder(fs, lockPath) }
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
// ---------------------------------------------------------------------------
|
|
449
|
-
// Phase: self upgrade
|
|
450
|
-
// ---------------------------------------------------------------------------
|
|
451
|
-
|
|
452
|
-
/**
|
|
453
|
-
* Bring the launcher itself up to `target`, but only when the running copy is
|
|
454
|
-
* the one the npm global prefix owns.
|
|
455
|
-
*
|
|
456
|
-
* `registryPath` decides whether `--registry` is passed on the install: only a
|
|
457
|
-
* registry npm would resolve on its own (i.e. from `~/.npmrc`) is left off
|
|
458
|
-
* argv. A registry from the environment, `$DSH_HOME/.npmrc`, `<profile>/.npmrc`
|
|
459
|
-
* or the default is invisible to npm, so it is forwarded explicitly — the
|
|
460
|
-
* query and the install must reach the same host. See buildSelfInstallArgs.
|
|
461
|
-
*
|
|
462
|
-
* @param {{ self: {name: string, version: string}|null, target: string|null,
|
|
463
|
-
* registry: string, registryPath: string,
|
|
464
|
-
* run: Function, fs: typeof defaultFs, selfPath: string }} input
|
|
465
|
-
* @returns {{ kind: 'skipped', form: string } |
|
|
466
|
-
* { kind: 'latest', version: string } |
|
|
467
|
-
* { kind: 'upgraded', from: string, to: string } |
|
|
468
|
-
* { kind: 'failed', exitCode: 1 }}
|
|
469
|
-
*/
|
|
470
|
-
function upgradeSelf({ self, target, registry, registryPath, run, fs, selfPath }) {
|
|
471
|
-
if (!self || typeof target !== 'string' || target === '') {
|
|
472
|
-
say('self: skipped (install form: unknown)')
|
|
473
|
-
warn(
|
|
474
|
-
'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
|
|
475
|
-
)
|
|
476
|
-
return { kind: 'skipped', form: 'unknown' }
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
// Install form: only a copy under `<npm prefix -g>/lib/node_modules/<name>`
|
|
480
|
-
// is ours to replace. Anything else (source tree, a copy in another prefix)
|
|
481
|
-
// must not be upgraded from here.
|
|
482
|
-
const prefixResult = run('npm', ['prefix', '-g'], { timeout: PREFIX_TIMEOUT_MS })
|
|
483
|
-
let form = 'unknown'
|
|
484
|
-
let globalPkgDir = null
|
|
485
|
-
if (prefixResult && prefixResult.status === 0) {
|
|
486
|
-
const prefix = String(prefixResult.stdout ?? '').trim()
|
|
487
|
-
if (prefix !== '') {
|
|
488
|
-
globalPkgDir = join(prefix, 'lib', 'node_modules', ...self.name.split('/'))
|
|
489
|
-
form = isInside(globalPkgDir, selfPath) ? 'global-npm' : 'foreign'
|
|
52
|
+
const parsed = new URL(url)
|
|
53
|
+
if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || !parsed.host) {
|
|
54
|
+
return '<invalid registry>'
|
|
490
55
|
}
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
say(`self: skipped (install form: ${form})`)
|
|
495
|
-
warn(
|
|
496
|
-
'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
|
|
497
|
-
)
|
|
498
|
-
return { kind: 'skipped', form }
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
if (sameVersion(self.version, target)) {
|
|
502
|
-
say(`self: already up to date (${self.version})`)
|
|
503
|
-
return { kind: 'latest', version: self.version }
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
const installArgs = buildSelfInstallArgs({
|
|
507
|
-
pkg: self.name,
|
|
508
|
-
target,
|
|
509
|
-
registry,
|
|
510
|
-
sourcePath: registryPath,
|
|
511
|
-
})
|
|
512
|
-
const install = run('npm', installArgs, {
|
|
513
|
-
timeout: INSTALL_TIMEOUT_MS,
|
|
514
|
-
})
|
|
515
|
-
if (!install || install.status !== 0) {
|
|
516
|
-
const tail = tailLines(install?.stderr, 10)
|
|
517
|
-
if (tail.length > 0) console.error(tail.join('\n'))
|
|
518
|
-
if (/EACCES|permission denied/i.test(String(install?.stderr ?? ''))) {
|
|
519
|
-
say(`try npm i -g ${self.name}@${target} with a writable prefix`)
|
|
520
|
-
}
|
|
521
|
-
say('upgrade aborted; profile untouched')
|
|
522
|
-
return { kind: 'failed', exitCode: 1 }
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
// Landing check reads the INSTALLED copy, never the running pkgRoot: npm may
|
|
526
|
-
// have replaced the directory this process was loaded from.
|
|
527
|
-
const landed = readJson(fs, join(globalPkgDir, 'package.json'))
|
|
528
|
-
const actual = isPlainObject(landed) && typeof landed.version === 'string' ? landed.version : undefined
|
|
529
|
-
if (actual !== target) {
|
|
530
|
-
say(`installed ${actual ?? 'nothing'}, expected ${target}`)
|
|
531
|
-
say('upgrade aborted; profile untouched')
|
|
532
|
-
return { kind: 'failed', exitCode: 1 }
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
say(`upgraded ${self.name} ${self.version} -> ${target}`)
|
|
536
|
-
say(`this process still runs the old code; quit and re-run \`dsh-opentui\` to start on ${target}`)
|
|
537
|
-
return { kind: 'upgraded', from: self.version, to: target }
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// ---------------------------------------------------------------------------
|
|
541
|
-
// Phase: plugins
|
|
542
|
-
//
|
|
543
|
-
// The install is deliberately ONE `dsh plugin ... add` for every target: the
|
|
544
|
-
// host takes the profile lock once, saves/restores package.json + lock around
|
|
545
|
-
// the run, and pnpm resolves the batch as a whole. Per-package calls would
|
|
546
|
-
// turn one bad version into "3 landed, 1 failed" and leave the profile
|
|
547
|
-
// inconsistent, so a failure rolls the whole batch back instead.
|
|
548
|
-
// ---------------------------------------------------------------------------
|
|
549
|
-
|
|
550
|
-
/** Numeric exit status of an injected run result; missing results count as 1. */
|
|
551
|
-
function runStatus(result) {
|
|
552
|
-
return result && typeof result.status === 'number' ? result.status : 1
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
/** argv tail for the batched install (and for the rollback convergence). */
|
|
556
|
-
function pluginAddArgs(specs, { saveExact = true } = {}) {
|
|
557
|
-
const args = ['plugin', '--profile', PROFILE, 'add']
|
|
558
|
-
if (saveExact) args.push(SAVE_EXACT)
|
|
559
|
-
return [...args, ...specs]
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
/**
|
|
563
|
-
* Copy the files a rollback needs. Only files that EXIST are copied: a file
|
|
564
|
-
* that was never there must be re-absent after a rollback, which the caller
|
|
565
|
-
* infers from the missing key (it deletes the override path in that case).
|
|
566
|
-
*
|
|
567
|
-
* @returns {Record<string, string>} original file name -> backup copy path
|
|
568
|
-
*/
|
|
569
|
-
function createBackup({ fs, profileDir, backupDir }) {
|
|
570
|
-
fs.mkdirSync(backupDir, { recursive: true })
|
|
571
|
-
const copies = {}
|
|
572
|
-
for (const name of BACKUP_FILE_NAMES) {
|
|
573
|
-
const source = join(profileDir, name)
|
|
574
|
-
if (!fs.existsSync(source)) continue
|
|
575
|
-
const target = join(backupDir, name)
|
|
576
|
-
fs.copyFileSync(source, target)
|
|
577
|
-
copies[name] = target
|
|
578
|
-
}
|
|
579
|
-
return copies
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
/**
|
|
583
|
-
* Put the profile back the way the backup found it. `package.json` and the
|
|
584
|
-
* lock are copy-restored; `upgrade-overrides.json` is restored when it was
|
|
585
|
-
* backed up, and REMOVED when it was not (a rollback must not leave behind a
|
|
586
|
-
* file the user never had).
|
|
587
|
-
*/
|
|
588
|
-
function restoreBackup({ fs, profileDir, overridePath, copies }) {
|
|
589
|
-
for (const [name, copy] of Object.entries(copies)) {
|
|
590
|
-
fs.copyFileSync(copy, join(profileDir, name))
|
|
591
|
-
}
|
|
592
|
-
if (!Object.prototype.hasOwnProperty.call(copies, OVERRIDE_FILE)) {
|
|
593
|
-
fs.rmSync(overridePath, { force: true })
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
/**
|
|
598
|
-
* Remove the backup after a fully successful run: the stamp directory first,
|
|
599
|
-
* then its hidden `.upgrade-backup` parent when it is empty. `rmdir` (not
|
|
600
|
-
* `rm -r`) is deliberate — it refuses to touch a parent that still holds
|
|
601
|
-
* another run's backup (ENOTEMPTY is ignored), so concurrent upgrades cannot
|
|
602
|
-
* delete each other's rollback material. The failure paths never call this.
|
|
603
|
-
*/
|
|
604
|
-
function removeSuccessfulBackup({ fs, backupDir }) {
|
|
605
|
-
fs.rmSync(backupDir, { recursive: true, force: true })
|
|
606
|
-
try {
|
|
607
|
-
fs.rmdirSync(dirname(backupDir))
|
|
56
|
+
parsed.username = ''
|
|
57
|
+
parsed.password = ''
|
|
58
|
+
return parsed.toString()
|
|
608
59
|
} catch {
|
|
609
|
-
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
function
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
60
|
+
return '<invalid registry>'
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// --- argv -------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
/** Pure parse of the subcommand's own argv. No process access, no logging. */
|
|
67
|
+
export function parseUpgradeArgs(argv = []) {
|
|
68
|
+
const args = Array.isArray(argv) ? argv : []
|
|
69
|
+
let tag = DEFAULT_TAG
|
|
70
|
+
let tagSeen = false
|
|
71
|
+
let dryRun = false
|
|
72
|
+
let help = false
|
|
73
|
+
const rest = []
|
|
74
|
+
for (let i = 0; i < args.length; i++) {
|
|
75
|
+
const arg = args[i]
|
|
76
|
+
if (arg === '--help' || arg === '-h') {
|
|
77
|
+
help = true
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
if (arg === '--dry-run') {
|
|
81
|
+
dryRun = true
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
if (arg === '--tag') {
|
|
85
|
+
const value = args[i + 1]
|
|
86
|
+
if (value === undefined || value === '' || value.startsWith('-')) {
|
|
87
|
+
return { tag, dryRun, help, rest, error: 'missing-value', errorFlag: '--tag' }
|
|
88
|
+
}
|
|
89
|
+
if (tagSeen) {
|
|
90
|
+
return { tag, dryRun, help, rest, error: 'duplicate-tag', errorValue: value, errorPrevious: tag }
|
|
91
|
+
}
|
|
92
|
+
tag = value
|
|
93
|
+
tagSeen = true
|
|
94
|
+
i++
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
if (arg.startsWith('--tag=')) {
|
|
98
|
+
const value = arg.slice('--tag='.length)
|
|
99
|
+
if (value === '') return { tag, dryRun, help, rest, error: 'missing-value', errorFlag: '--tag' }
|
|
100
|
+
if (tagSeen) {
|
|
101
|
+
return { tag, dryRun, help, rest, error: 'duplicate-tag', errorValue: value, errorPrevious: tag }
|
|
102
|
+
}
|
|
103
|
+
tag = value
|
|
104
|
+
tagSeen = true
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
rest.push(arg)
|
|
108
|
+
}
|
|
109
|
+
if (!help && rest.length > 0) {
|
|
110
|
+
return { tag, dryRun, help, rest, error: 'unknown', errorValue: rest[0] }
|
|
111
|
+
}
|
|
112
|
+
if (!help && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(tag)) {
|
|
113
|
+
return { tag, dryRun, help, rest, error: 'invalid-tag', errorValue: tag }
|
|
114
|
+
}
|
|
115
|
+
return { tag, dryRun, help, rest, error: null }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Dedicated subcommand help (also used by `node scripts/upgrade.mjs --help`). */
|
|
119
|
+
export function formatUpgradeUsage() {
|
|
120
|
+
return [
|
|
121
|
+
'Usage: dsh-opentui upgrade [--tag <dist-tag>] [--dry-run]',
|
|
122
|
+
'',
|
|
123
|
+
'Upgrade the launcher package (@aiwayds/dsh-opentui) itself. Profiles,',
|
|
124
|
+
'companions and migrations are left to the next launch.',
|
|
125
|
+
'',
|
|
126
|
+
' --tag <dist-tag> npm dist-tag to resolve (default: latest)',
|
|
127
|
+
' letters/digits first, then letters, digits, . _ - only',
|
|
128
|
+
' --dry-run resolve and print the command, do not install',
|
|
129
|
+
' (no command is printed when the target is equal/older)',
|
|
130
|
+
' -h, --help print this help and exit',
|
|
131
|
+
'',
|
|
132
|
+
`Requires an npm global install (--dry-run is exempt); otherwise use npm i -g ${PACKAGE_NAME}.`,
|
|
133
|
+
`Set ${REGISTRY_ENV} to pass --registry <url> to both npm view and npm i -g.`,
|
|
134
|
+
'The tag is only a key into npm view\'s dist-tags JSON; it never enters npm argv.',
|
|
135
|
+
].join('\n')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// --- npm helpers (all process access goes through the injected exec) --------
|
|
139
|
+
|
|
140
|
+
const defaultExec = (cmd, args, opts) => spawnSync(cmd, args, opts)
|
|
141
|
+
|
|
142
|
+
/** `npm view @aiwayds/dsh-opentui dist-tags --json` (+ optional --registry). */
|
|
143
|
+
export function npmViewArgs({ registry } = {}) {
|
|
144
|
+
const args = ['view', PACKAGE_NAME, 'dist-tags', '--json']
|
|
145
|
+
if (registry) args.push('--registry', registry)
|
|
146
|
+
return args
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The exact install command we would run (argv form, executable first). */
|
|
150
|
+
export function npmInstallCommand({ targetVersion, registry } = {}) {
|
|
151
|
+
const spec = registry
|
|
152
|
+
? ['i', '-g', `${PACKAGE_NAME}@${targetVersion}`, '--registry', registry]
|
|
153
|
+
: ['i', '-g', `${PACKAGE_NAME}@${targetVersion}`]
|
|
154
|
+
return ['npm', ...spec]
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function registryFailureDetail(registry) {
|
|
158
|
+
if (registry) return displayRegistry(registry)
|
|
159
|
+
// Do not name a hardcoded public URL here: with no override npm uses its own
|
|
160
|
+
// configured registry, which may be a private mirror.
|
|
161
|
+
return `npm 自身配置的 registry(可用 ${REGISTRY_ENV} 指定)`
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Display-only rendering of an argv command: scrub --registry credentials. */
|
|
165
|
+
function formatCommand(command) {
|
|
166
|
+
return command
|
|
167
|
+
.map((arg, i) => (i > 0 && command[i - 1] === '--registry' ? displayRegistry(arg) : arg))
|
|
168
|
+
.join(' ')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const stripV = (value) => String(value).trim().replace(/^v/, '')
|
|
623
172
|
|
|
624
173
|
/**
|
|
625
|
-
*
|
|
626
|
-
*
|
|
174
|
+
* Resolve a dist-tag through npm. Injected `exec` keeps this testable; a failed
|
|
175
|
+
* / malformed / tagless registry query throws with the registry URL in the
|
|
176
|
+
* message so the user can tell where the lookup went.
|
|
627
177
|
*
|
|
628
|
-
*
|
|
629
|
-
*
|
|
630
|
-
* warnings otherwise leaves no trace at all. The caller prints a short tail.
|
|
631
|
-
*
|
|
632
|
-
* @returns {{ status: number, args: string[], stderr: string }}
|
|
178
|
+
* `tag` is only used as a key into the returned dist-tags JSON — it is NEVER
|
|
179
|
+
* appended to the npm argv, so no user-supplied string can reach npm as a flag.
|
|
633
180
|
*/
|
|
634
|
-
function
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
181
|
+
export function resolveTargetVersion({ tag = DEFAULT_TAG, registry, exec = defaultExec } = {}) {
|
|
182
|
+
const args = npmViewArgs({ registry })
|
|
183
|
+
let result
|
|
184
|
+
try {
|
|
185
|
+
result = exec('npm', args, { encoding: 'utf8', timeout: VIEW_TIMEOUT_MS })
|
|
186
|
+
} catch (error) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}';registry: ${registryFailureDetail(registry)}(${error?.message ?? error})`,
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
if (result?.error !== undefined) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}';registry: ${registryFailureDetail(registry)}(${result.error.message ?? result.error})`,
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
if (result?.status !== 0) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
`无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}'(npm view 退出 ${result?.status});registry: ${registryFailureDetail(registry)}`,
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
let tags
|
|
202
|
+
try {
|
|
203
|
+
tags = JSON.parse(String(result?.stdout ?? ''))
|
|
204
|
+
} catch {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`npm view 返回的 dist-tags 不是合法 JSON;registry: ${registryFailureDetail(registry)}`,
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
const raw = tags?.[tag]
|
|
210
|
+
if (typeof raw !== 'string' || raw.trim() === '') {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`${PACKAGE_NAME} 没有 '${tag}' dist-tag;registry: ${registryFailureDetail(registry)}`,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
const version = stripV(raw)
|
|
216
|
+
if (!isExactVersion(version)) {
|
|
217
|
+
throw new Error(`dist-tag '${tag}' 的版本 ${JSON.stringify(raw)} 不是精确 semver;registry: ${registryFailureDetail(registry)}`)
|
|
218
|
+
}
|
|
219
|
+
return version
|
|
664
220
|
}
|
|
665
221
|
|
|
666
222
|
/**
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
* version that is not newer than the shipped pin (stale or downgrade), and a
|
|
673
|
-
* version that does not parse.
|
|
674
|
-
*
|
|
675
|
-
* @returns {{
|
|
676
|
-
* packages: Record<string, unknown>,
|
|
677
|
-
* written: string[],
|
|
678
|
-
* atPin: string[],
|
|
679
|
-
* ineffective: Array<{ name: string, reason: string }>,
|
|
680
|
-
* }}
|
|
223
|
+
* `npm prefix -g` through the injected executor. By default returns undefined
|
|
224
|
+
* on any failure (used by the post-install re-check, where a missing prefix is
|
|
225
|
+
* just one of the reasons verification can fail). With `strict: true` it throws
|
|
226
|
+
* a descriptive error instead: the pre-install guard must not confuse "npm is
|
|
227
|
+
* unavailable / the query failed" with "this is a source-tree checkout".
|
|
681
228
|
*/
|
|
682
|
-
function
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
continue
|
|
705
|
-
}
|
|
706
|
-
next[entry.name] = candidate[entry.name]
|
|
707
|
-
written.push(entry.name)
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
return { packages: next, written, atPin, ineffective }
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
/** The rollback's second half: re-add the pre-upgrade specs so node_modules
|
|
714
|
-
* matches the restored manifest again. A failure here is reported with the
|
|
715
|
-
* exact command the user can run by hand. */
|
|
716
|
-
function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
|
|
717
|
-
const specs = originalSpecs({ fs, copies, manifestPath })
|
|
718
|
-
if (specs.length === 0) return
|
|
719
|
-
|
|
720
|
-
const result = run('dsh', pluginAddArgs(specs), { timeout: INSTALL_TIMEOUT_MS, env })
|
|
721
|
-
const status = runStatus(result)
|
|
722
|
-
if (status === 0) {
|
|
723
|
-
log(`restored the previous plugin versions (${specs.length} spec(s))`)
|
|
724
|
-
return
|
|
725
|
-
}
|
|
726
|
-
warn(`could not restore the previous plugin versions (dsh plugin add exit ${status})`)
|
|
727
|
-
warn(`run this by hand to restore them: dsh plugin --profile ${PROFILE} add ${specs.join(' ')}`)
|
|
229
|
+
export function captureGlobalPrefix(exec = defaultExec, { strict = false } = {}) {
|
|
230
|
+
let result
|
|
231
|
+
try {
|
|
232
|
+
result = exec('npm', ['prefix', '-g'], { encoding: 'utf8', timeout: PREFIX_TIMEOUT_MS })
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 调用失败:${error?.message ?? error})`)
|
|
235
|
+
return undefined
|
|
236
|
+
}
|
|
237
|
+
if (result?.error !== undefined) {
|
|
238
|
+
if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 失败:${result.error.message ?? result.error})`)
|
|
239
|
+
return undefined
|
|
240
|
+
}
|
|
241
|
+
if (result?.status !== 0) {
|
|
242
|
+
if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 退出 ${result?.status})`)
|
|
243
|
+
return undefined
|
|
244
|
+
}
|
|
245
|
+
const prefix = String(result?.stdout ?? '').trim()
|
|
246
|
+
if (!prefix) {
|
|
247
|
+
if (strict) throw new Error('无法确定 npm 全局前缀(npm prefix -g 未返回路径)')
|
|
248
|
+
return undefined
|
|
249
|
+
}
|
|
250
|
+
return prefix
|
|
728
251
|
}
|
|
729
252
|
|
|
730
253
|
/**
|
|
731
|
-
*
|
|
732
|
-
*
|
|
733
|
-
*
|
|
734
|
-
* The lock is held only around the write phase, and released in `finally` so a
|
|
735
|
-
* throw from the backup or the override write still leaves no lock behind. A
|
|
736
|
-
* run that has nothing to install never touches the file, and `--dry-run`
|
|
737
|
-
* returns long before this function is reached.
|
|
738
|
-
*
|
|
739
|
-
* Outcomes (they map 1:1 to the process exit code, see exitCodeAfterPlugins):
|
|
740
|
-
* - another upgrade holds the lock -> nothing written, code 2
|
|
741
|
-
* - all landed, overrides written or unnecessary -> backup deleted, code 0
|
|
742
|
-
* - install failed -> rollback, backup kept, code 1
|
|
743
|
-
* - install ok, some version did not land -> no rollback, code 3
|
|
744
|
-
* - override write failed -> code 3
|
|
745
|
-
*
|
|
746
|
-
* @param {Parameters<typeof installPluginUpgrades>[0]} ctx
|
|
747
|
-
* @returns {ReturnType<typeof installPluginUpgrades> & { lockBusy?: boolean }}
|
|
254
|
+
* A global package dir that is a symlink is an `npm link` development install,
|
|
255
|
+
* not a package npm can upgrade in place. Detect it BEFORE installing so we
|
|
256
|
+
* never mutate the link target (the source tree).
|
|
748
257
|
*/
|
|
749
|
-
function
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
258
|
+
export function findLinkedGlobalInstall(prefix) {
|
|
259
|
+
if (!prefix) return undefined
|
|
260
|
+
for (const candidate of globalPackagePaths(prefix)) {
|
|
261
|
+
try {
|
|
262
|
+
if (lstatSync(candidate).isSymbolicLink()) return candidate
|
|
263
|
+
} catch {
|
|
264
|
+
/* not present — keep looking */
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return undefined
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Where a global install of this package lives under an npm prefix. */
|
|
271
|
+
export function globalPackagePaths(prefix) {
|
|
272
|
+
if (!prefix) return []
|
|
273
|
+
return [
|
|
274
|
+
join(prefix, 'lib', 'node_modules', PACKAGE_NAME),
|
|
275
|
+
join(prefix, 'node_modules', PACKAGE_NAME),
|
|
276
|
+
]
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function normalizePath(path) {
|
|
280
|
+
try {
|
|
281
|
+
return realpathSync(resolve(path))
|
|
282
|
+
} catch {
|
|
283
|
+
return resolve(path)
|
|
284
|
+
}
|
|
771
285
|
}
|
|
772
286
|
|
|
773
287
|
/**
|
|
774
|
-
*
|
|
775
|
-
*
|
|
776
|
-
*
|
|
777
|
-
*
|
|
778
|
-
* profileDir: string, manifestPath: string, overridePath: string,
|
|
779
|
-
* backupDir: string, pluginRows: Array<{name: string, current: string|null, target: string}>,
|
|
780
|
-
* rows: Array<{name: string, action: string}>,
|
|
781
|
-
* counts: {latest: number, excluded: number}, selfName: string|null,
|
|
782
|
-
* env: Record<string, string|undefined>,
|
|
783
|
-
* run: Function, fs: typeof defaultFs,
|
|
784
|
-
* log: (message: string) => void, warn: (message: string) => void,
|
|
785
|
-
* }} ctx
|
|
786
|
-
* @returns {{
|
|
787
|
-
* landed: Array<{name: string, version: string, from: string|null}>,
|
|
788
|
-
* mismatched: Array<{name: string, expected: string, actual: string|null}>,
|
|
789
|
-
* failed: Array<{reason: string, status?: number}>,
|
|
790
|
-
* overridesError?: boolean,
|
|
791
|
-
* upgraded?: number,
|
|
792
|
-
* upToDate?: number,
|
|
793
|
-
* }}
|
|
288
|
+
* Whether the RUNNING copy is the npm-global install of this package. A source
|
|
289
|
+
* tree / pnpm store / custom prefix is not: upgrading it in place would leave
|
|
290
|
+
* the actual global copy untouched. Both values can be injected (pure); with
|
|
291
|
+
* only `exec` injected the prefix is read via `npm prefix -g`.
|
|
794
292
|
*/
|
|
795
|
-
function
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
log(`plugins: installing ${specs.length} package(s)`)
|
|
803
|
-
|
|
804
|
-
const install = installPlugins({ run, env, specs, warn })
|
|
805
|
-
if (install.status !== 0) {
|
|
806
|
-
const tail = tailLines(install.stderr, 10)
|
|
807
|
-
if (tail.length > 0) console.error(tail.join('\n'))
|
|
808
|
-
restoreBackup({ fs, profileDir, overridePath, copies })
|
|
809
|
-
convergeProfile({ fs, run, env, copies, manifestPath, log, warn })
|
|
810
|
-
log(`upgrade failed at plugin install; profile restored from ${backupDir}`)
|
|
811
|
-
log('if the profile still looks wrong, fix it by hand before starting the TUI')
|
|
812
|
-
return { landed: [], mismatched: [], failed: [{ reason: 'install', status: install.status }] }
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
// A successful batch can still have said something worth keeping (pnpm
|
|
816
|
-
// warnings, dedupe notes). Five prefixed lines is enough to be diagnosable
|
|
817
|
-
// without turning the summary into a log dump.
|
|
818
|
-
for (const line of tailLines(install.stderr, 5)) {
|
|
819
|
-
console.error(`${INSTALL_STDERR_PREFIX}${line}`)
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
const { landed, mismatched } = verifyPlugins({ fs, profileDir, rows: pluginRows })
|
|
823
|
-
for (const item of mismatched) {
|
|
824
|
-
log(`mismatch: ${item.name} expected ${item.expected}, installed ${item.actual ?? 'nothing'}`)
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
// --- overrides: read, merge, assert, write -------------------------------
|
|
828
|
-
// A file that is not a usable override document is left UNTOUCHED: it may
|
|
829
|
-
// hold hand-edited entries this module would silently drop. Nothing is
|
|
830
|
-
// recorded in that case (the run reports a partial result), and the file is
|
|
831
|
-
// in the backup if the user wants it back.
|
|
832
|
-
const existingText = readText(fs, overridePath)
|
|
833
|
-
const parsed = existingText === undefined ? null : parseOverrides(existingText)
|
|
834
|
-
const unusable = existingText !== undefined && parsed === null
|
|
835
|
-
if (unusable) {
|
|
836
|
-
warn(
|
|
837
|
-
`${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`,
|
|
838
|
-
)
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
let overridesError = unusable
|
|
842
|
-
let written = []
|
|
843
|
-
let atPin = []
|
|
844
|
-
if (!unusable) {
|
|
845
|
-
const document = parsed ?? { version: 1, packages: {} }
|
|
846
|
-
const updatedAt = new Date().toISOString()
|
|
847
|
-
const plan = planOverrides({ packages: document.packages ?? {}, landed, updatedAt })
|
|
848
|
-
written = plan.written
|
|
849
|
-
atPin = plan.atPin
|
|
850
|
-
|
|
851
|
-
for (const item of plan.ineffective) {
|
|
852
|
-
if (item.shippedPin === null) {
|
|
853
|
-
// The package is not in PLUGIN_SET, so provisioning never installs or
|
|
854
|
-
// converges it: an override would be dead data, not a lost upgrade.
|
|
855
|
-
warn(`${item.name}: not managed by provisioning; no override recorded`)
|
|
856
|
-
continue
|
|
857
|
-
}
|
|
858
|
-
warn(
|
|
859
|
-
`${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`,
|
|
860
|
-
)
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
if (written.length > 0) {
|
|
864
|
-
const nextDocument = { ...document, version: document.version ?? 1, updatedAt, packages: plan.packages }
|
|
865
|
-
// Write-then-rename in the SAME directory: a crash mid-write cannot leave
|
|
866
|
-
// a torn upgrade-overrides.json that provisioning would silently ignore.
|
|
867
|
-
const tmpPath = `${overridePath}.tmp`
|
|
868
|
-
try {
|
|
869
|
-
fs.writeFileSync(tmpPath, serializeOverrides(nextDocument), 'utf8')
|
|
870
|
-
fs.renameSync(tmpPath, overridePath)
|
|
871
|
-
log(`wrote ${written.length} override(s) to ${overridePath}`)
|
|
872
|
-
} catch (err) {
|
|
873
|
-
overridesError = true
|
|
874
|
-
warn(`could not write ${overridePath}: ${err?.message ?? err}`)
|
|
875
|
-
warn('the next start may reinstall the shipped pins and downgrade these plugins')
|
|
876
|
-
log(`override write failed; backup kept at ${backupDir}`)
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
// --- summary + exit-code material ---------------------------------------
|
|
882
|
-
// The launcher has its own row and its own report, so it never counts here.
|
|
883
|
-
const latestPlugins = rows.filter(
|
|
884
|
-
(row) => row.action === 'latest' && (selfName === null || row.name !== selfName),
|
|
885
|
-
).length
|
|
886
|
-
const upgraded = landed.length - atPin.length
|
|
887
|
-
const upToDate = latestPlugins + atPin.length
|
|
888
|
-
log(
|
|
889
|
-
`${upgraded} upgraded, ${upToDate} up to date, ${mismatched.length} mismatched, ${counts.excluded} excluded`,
|
|
890
|
-
)
|
|
891
|
-
log('restart required: exit the TUI and run dsh-opentui again')
|
|
892
|
-
|
|
893
|
-
if (mismatched.length > 0) {
|
|
894
|
-
log(
|
|
895
|
-
'packages without an override will be reinstalled at the shipped pin on the next start (possible downgrade)',
|
|
896
|
-
)
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
if (mismatched.length === 0 && !overridesError) {
|
|
900
|
-
removeSuccessfulBackup({ fs, backupDir })
|
|
901
|
-
log(`upgraded ${upgraded} plugin(s)`)
|
|
902
|
-
} else {
|
|
903
|
-
log(`backup kept at ${backupDir}`)
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
return { landed, mismatched, failed: [], overridesError, upgraded, upToDate }
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
/**
|
|
910
|
-
* Exit code after the plugin phase (plan §1.3):
|
|
911
|
-
* 2 - another upgrade holds `<profile>/.upgrade.lock`; nothing was written;
|
|
912
|
-
* 1 - the batched install failed and the profile was rolled back;
|
|
913
|
-
* 3 - partially applied: the install exited 0 but a package is not at its
|
|
914
|
-
* target version, or the override file could not be written;
|
|
915
|
-
* 0 - every target is on disk at its planned version.
|
|
916
|
-
*/
|
|
917
|
-
function exitCodeAfterPlugins({ pluginResult } = {}) {
|
|
918
|
-
if (!pluginResult) return 0
|
|
919
|
-
if (pluginResult.lockBusy) return 2
|
|
920
|
-
if (Array.isArray(pluginResult.failed) && pluginResult.failed.length > 0) return 1
|
|
921
|
-
if (pluginResult.overridesError) return 3
|
|
922
|
-
if (Array.isArray(pluginResult.mismatched) && pluginResult.mismatched.length > 0) return 3
|
|
923
|
-
return 0
|
|
293
|
+
export function isGlobalInstall({ globalPrefix, runningRoot, exec = defaultExec } = {}) {
|
|
294
|
+
const prefix = globalPrefix ?? captureGlobalPrefix(exec)
|
|
295
|
+
if (!prefix || !runningRoot) return false
|
|
296
|
+
const root = normalizePath(runningRoot)
|
|
297
|
+
// Only the package paths under the global prefix count. The prefix itself
|
|
298
|
+
// being the running root is not a global package install.
|
|
299
|
+
return globalPackagePaths(prefix).some((candidate) => normalizePath(candidate) === root)
|
|
924
300
|
}
|
|
925
301
|
|
|
926
|
-
//
|
|
927
|
-
// Entry point
|
|
928
|
-
// ---------------------------------------------------------------------------
|
|
302
|
+
// --- pure decision ----------------------------------------------------------
|
|
929
303
|
|
|
930
304
|
/**
|
|
931
|
-
*
|
|
932
|
-
*
|
|
933
|
-
*
|
|
934
|
-
* dryRun?: boolean, yes?: boolean, tag?: string, noSelf?: boolean,
|
|
935
|
-
* noPlugins?: boolean, resetOverrides?: boolean, help?: boolean,
|
|
936
|
-
* }} [opts]
|
|
937
|
-
* @param {{
|
|
938
|
-
* pkgRoot?: string,
|
|
939
|
-
* env?: Record<string, string | undefined>,
|
|
940
|
-
* run?: (cmd: string, args: string[], options?: { timeout?: number }) =>
|
|
941
|
-
* { status: number, stdout: string, stderr: string },
|
|
942
|
-
* fs?: typeof defaultFs,
|
|
943
|
-
* selfPath?: string,
|
|
944
|
-
* isTTY?: boolean,
|
|
945
|
-
* readLine?: () => string,
|
|
946
|
-
* prompt?: (text: string) => void,
|
|
947
|
-
* }} [context]
|
|
948
|
-
* @returns {number} 0 done / nothing to do / --dry-run / --help,
|
|
949
|
-
* 1 hard failure or an undetermined target version, 2 non-interactive
|
|
950
|
-
* refusal or another upgrade holding the profile lock (the bin owns the
|
|
951
|
-
* other usage errors), 3 partially applied
|
|
305
|
+
* Decide what to do. Pure: no exec, no fs, no process. `cmp` is -1 / 0 / 1 for
|
|
306
|
+
* target vs current. Dry-run reports the command but never installs, so it
|
|
307
|
+
* deliberately skips the global-install guard.
|
|
952
308
|
*/
|
|
953
|
-
export function
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
)
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
latestByPkg,
|
|
1129
|
-
// Self result
|
|
1130
|
-
selfName: self?.name ?? null,
|
|
1131
|
-
selfResult,
|
|
1132
|
-
// Where the plugin phase writes its backup (created there, not here):
|
|
1133
|
-
// $DSH_HOME/profiles/opentui/.upgrade-backup/<UTC stamp>-<pid>/
|
|
1134
|
-
backupDir: join(profileDir, BACKUP_DIR_NAME, `${backupStamp()}-${process.pid}`),
|
|
1135
|
-
// Injected effects + logging
|
|
1136
|
-
env,
|
|
1137
|
-
run,
|
|
1138
|
-
fs,
|
|
1139
|
-
log: say,
|
|
1140
|
-
warn,
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
const pluginResult = applyPluginUpgrades(ctx)
|
|
1144
|
-
return exitCodeAfterPlugins({ pluginResult })
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
function defaultPkgRoot() {
|
|
1148
|
-
return dirname(dirname(fileURLToPath(import.meta.url)))
|
|
309
|
+
export function planUpgrade({ targetVersion, currentVersion, dryRun = false, registry, isGlobal = false } = {}) {
|
|
310
|
+
const cmp = compareVersions(targetVersion, currentVersion)
|
|
311
|
+
const command = npmInstallCommand({ targetVersion, registry })
|
|
312
|
+
if (dryRun) return { action: 'dry-run', cmp, command, targetVersion, currentVersion }
|
|
313
|
+
if (cmp === 0) return { action: 'up-to-date', cmp, command: null, targetVersion, currentVersion }
|
|
314
|
+
if (cmp < 0) return { action: 'downgrade', cmp, command: null, targetVersion, currentVersion }
|
|
315
|
+
if (!isGlobal) return { action: 'not-global', cmp, command, targetVersion, currentVersion }
|
|
316
|
+
return { action: 'install', cmp, command, targetVersion, currentVersion }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** After a successful install, re-read the version under `npm prefix -g`. */
|
|
320
|
+
export function verifyInstalledVersion({ targetVersion, exec = defaultExec, readVersion = readLauncherVersion } = {}) {
|
|
321
|
+
const prefix = captureGlobalPrefix(exec)
|
|
322
|
+
for (const candidate of globalPackagePaths(prefix)) {
|
|
323
|
+
try {
|
|
324
|
+
if (readVersion(candidate) === targetVersion) return { ok: true, path: candidate, version: targetVersion }
|
|
325
|
+
} catch {
|
|
326
|
+
/* try the next candidate */
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return { ok: false, prefix, version: undefined }
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// --- process-facing entry ---------------------------------------------------
|
|
333
|
+
|
|
334
|
+
/** Run the subcommand; returns an exit code (never calls process.exit itself). */
|
|
335
|
+
export async function runUpgrade(argv = [], ctx = {}) {
|
|
336
|
+
const {
|
|
337
|
+
env = process.env,
|
|
338
|
+
exec = defaultExec,
|
|
339
|
+
pkgRoot = dirname(dirname(fileURLToPath(import.meta.url))),
|
|
340
|
+
readVersion = readLauncherVersion,
|
|
341
|
+
out: rawOut = (line) => console.log(line),
|
|
342
|
+
err: rawErr = (line) => console.error(line),
|
|
343
|
+
} = ctx
|
|
344
|
+
// Every line this command emits passes through the redactor: a registry URL
|
|
345
|
+
// (or an npm error quoting one) must never leak credentials into a terminal
|
|
346
|
+
// or CI log. Arguments handed to `exec` are untouched.
|
|
347
|
+
const out = (line) => rawOut(redactSecrets(line))
|
|
348
|
+
const err = (line) => rawErr(redactSecrets(line))
|
|
349
|
+
|
|
350
|
+
const parsed = parseUpgradeArgs(argv)
|
|
351
|
+
if (parsed.help) {
|
|
352
|
+
out(formatUpgradeUsage())
|
|
353
|
+
return 0
|
|
354
|
+
}
|
|
355
|
+
if (parsed.error === 'missing-value') {
|
|
356
|
+
err(`dsh-opentui upgrade: option '--tag' requires a value`)
|
|
357
|
+
err(formatUpgradeUsage())
|
|
358
|
+
return 2
|
|
359
|
+
}
|
|
360
|
+
if (parsed.error === 'duplicate-tag') {
|
|
361
|
+
err(`dsh-opentui upgrade: option '--tag' given more than once: '${parsed.errorPrevious}' and '${parsed.errorValue}'`)
|
|
362
|
+
err(formatUpgradeUsage())
|
|
363
|
+
return 2
|
|
364
|
+
}
|
|
365
|
+
if (parsed.error === 'invalid-tag') {
|
|
366
|
+
err(`dsh-opentui upgrade: invalid dist-tag '${parsed.errorValue}';只允许字母/数字开头,其后为字母、数字、. _ -(不含空白或 URL 元字符)`)
|
|
367
|
+
err(formatUpgradeUsage())
|
|
368
|
+
return 2
|
|
369
|
+
}
|
|
370
|
+
if (parsed.error) {
|
|
371
|
+
err(`dsh-opentui upgrade: unknown argument '${parsed.errorValue}'`)
|
|
372
|
+
err(formatUpgradeUsage())
|
|
373
|
+
return 2
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// An explicit override must be a real http(s) URL. A typo must fail loudly
|
|
377
|
+
// instead of silently falling back to whatever registry npm has configured.
|
|
378
|
+
const rawRegistry = typeof env?.[REGISTRY_ENV] === 'string' ? env[REGISTRY_ENV].trim() : ''
|
|
379
|
+
let registry
|
|
380
|
+
if (rawRegistry !== '') {
|
|
381
|
+
if (!/^https?:\/\//i.test(rawRegistry)) {
|
|
382
|
+
err(`dsh-opentui upgrade: ${REGISTRY_ENV} 必须以 http:// 或 https:// 开头(合法 URL),收到 ${JSON.stringify(displayRegistry(rawRegistry))};已中止。`)
|
|
383
|
+
return 1
|
|
384
|
+
}
|
|
385
|
+
registry = rawRegistry
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
let targetVersion
|
|
389
|
+
try {
|
|
390
|
+
targetVersion = resolveTargetVersion({ tag: parsed.tag, registry, exec })
|
|
391
|
+
} catch (error) {
|
|
392
|
+
err(`dsh-opentui upgrade: ${error?.message ?? error}`)
|
|
393
|
+
return 1
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const currentVersion = readVersion(pkgRoot)
|
|
397
|
+
if (!currentVersion) {
|
|
398
|
+
err(`dsh-opentui upgrade: 无法从 ${join(pkgRoot, 'package.json')} 读取当前版本,已中止。`)
|
|
399
|
+
return 1
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let cmp
|
|
403
|
+
try {
|
|
404
|
+
cmp = compareVersions(targetVersion, currentVersion)
|
|
405
|
+
} catch (error) {
|
|
406
|
+
err(`dsh-opentui upgrade: 版本比较失败(当前 ${JSON.stringify(currentVersion)},目标 ${JSON.stringify(targetVersion)}):${error?.message ?? error}`)
|
|
407
|
+
return 1
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
let isGlobal = false
|
|
411
|
+
if (!parsed.dryRun && cmp > 0) {
|
|
412
|
+
// Resolve the global prefix strictly: a failed `npm prefix -g` is NOT the
|
|
413
|
+
// same as "running from a source tree", and must never end in an install.
|
|
414
|
+
let prefix
|
|
415
|
+
try {
|
|
416
|
+
prefix = captureGlobalPrefix(exec, { strict: true })
|
|
417
|
+
} catch (error) {
|
|
418
|
+
err(`dsh-opentui upgrade: ${error?.message ?? error};未执行安装。`)
|
|
419
|
+
return 1
|
|
420
|
+
}
|
|
421
|
+
const linked = findLinkedGlobalInstall(prefix)
|
|
422
|
+
if (linked) {
|
|
423
|
+
err(`dsh-opentui upgrade: ${linked} 是 npm link 的符号链接(linked development install),不是 npm 全局安装;升级已中止。请在源码目录更新后重新 link,或重新执行 npm i -g ${PACKAGE_NAME}。`)
|
|
424
|
+
return 1
|
|
425
|
+
}
|
|
426
|
+
isGlobal = isGlobalInstall({ globalPrefix: prefix, runningRoot: pkgRoot })
|
|
427
|
+
}
|
|
428
|
+
const plan = planUpgrade({
|
|
429
|
+
targetVersion,
|
|
430
|
+
currentVersion,
|
|
431
|
+
dryRun: parsed.dryRun,
|
|
432
|
+
registry,
|
|
433
|
+
isGlobal,
|
|
434
|
+
})
|
|
435
|
+
|
|
436
|
+
if (plan.action === 'dry-run') {
|
|
437
|
+
out(`dsh-opentui upgrade: 当前 ${currentVersion},目标(${parsed.tag})${targetVersion}(${plan.cmp > 0 ? '有可用升级' : plan.cmp === 0 ? '已是最新' : '目标版本更旧'})。`)
|
|
438
|
+
out(`dsh-opentui upgrade: --dry-run,不会执行安装。`)
|
|
439
|
+
if (plan.cmp > 0) out(`dsh-opentui upgrade: 将执行: ${formatCommand(plan.command)}`)
|
|
440
|
+
return 0
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (plan.action === 'up-to-date') {
|
|
444
|
+
out(`dsh-opentui upgrade: already up to date (${currentVersion}).`)
|
|
445
|
+
return 0
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
if (plan.action === 'downgrade') {
|
|
449
|
+
err(`dsh-opentui upgrade: refusing to downgrade from ${currentVersion} to ${targetVersion}.`)
|
|
450
|
+
return 1
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
if (plan.action === 'not-global') {
|
|
454
|
+
err(`dsh-opentui upgrade: 当前不是 npm 全局安装,请手动执行 npm i -g ${PACKAGE_NAME}@${targetVersion}${registry ? ` --registry ${displayRegistry(registry)}` : ''}。`)
|
|
455
|
+
return 1
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
out(`dsh-opentui upgrade: ${formatCommand(plan.command)}`)
|
|
459
|
+
// Capture npm output instead of inheriting its file descriptors: every line
|
|
460
|
+
// must pass through this process's redactor before reaching the terminal.
|
|
461
|
+
const install = exec('npm', plan.command.slice(1), {
|
|
462
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
463
|
+
encoding: 'utf8',
|
|
464
|
+
})
|
|
465
|
+
if (install?.stdout) out(String(install.stdout))
|
|
466
|
+
if (install?.stderr) err(String(install.stderr))
|
|
467
|
+
if (install?.error !== undefined || install?.status !== 0) {
|
|
468
|
+
err(`dsh-opentui upgrade: npm 安装失败${install?.status !== undefined ? `(退出 ${install.status})` : ''},已中止。`)
|
|
469
|
+
return 1
|
|
470
|
+
}
|
|
471
|
+
const verified = verifyInstalledVersion({ targetVersion, exec, readVersion })
|
|
472
|
+
if (!verified.ok) {
|
|
473
|
+
err(`dsh-opentui upgrade: 安装后校验失败:${verified.prefix ?? '未知 prefix'} 下找不到版本 ${targetVersion} 的 ${PACKAGE_NAME}。`)
|
|
474
|
+
return 1
|
|
475
|
+
}
|
|
476
|
+
out('dsh-opentui upgrade: 升级完成,退出并重新运行 dsh-opentui。')
|
|
477
|
+
return 0
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Direct invocation only: importing this module (from the bin or tests) must
|
|
481
|
+
// never run a registry query.
|
|
482
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
483
|
+
process.exit(await runUpgrade(process.argv.slice(2)))
|
|
1149
484
|
}
|