@aiwayds/dsh-opentui 0.18.1 → 0.18.2
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 +13 -0
- package/bin/lib/launcher.mjs +1 -1
- package/dist/client/index.js +1 -1
- package/package.json +6 -1
- package/scripts/lib/upgrade-plan.mjs +120 -37
- package/scripts/upgrade.mjs +234 -32
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.18.2] - 2026-11-16
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- **The self-upgrade no longer forces a registry onto `npm i -g`.** `--registry` is passed only when the registry came from `DSH_UPGRADE_REGISTRY`; a registry read from an `.npmrc` is left to npm's own configuration, which resolves the same place without overriding the user's per-scope or per-package settings.
|
|
13
|
+
- **Two upgrades can no longer run over one profile at once.** The write phase (backup, install, override write) holds `<profile>/.upgrade.lock`; a second run reports the holder and exits 2 without writing anything: `upgrade: another upgrade is running (pid <pid>, started <iso>)`. A lock older than 30 minutes is treated as stale and reclaimed, and `--dry-run` never creates one.
|
|
14
|
+
- **Unknown or malformed entries in `upgrade-overrides.json` survive a rewrite.** The parser keeps entries it cannot interpret (no version string) and the serializer writes them back unchanged, so a hand-written entry is no longer silently deleted when the upgrade command records a new pin. They still never affect the effective pin.
|
|
15
|
+
- **The tail of `dsh plugin add` stderr is shown after a successful batch install.** Up to five lines are printed with a `dsh plugin add: ` prefix, so pnpm warnings from an install that exited 0 are no longer lost. The failure path is unchanged.
|
|
16
|
+
|
|
17
|
+
### Internal
|
|
18
|
+
|
|
19
|
+
- **`repository` field added to `packages/shell/package.json`** so `npm publish --provenance` can generate provenance.
|
|
20
|
+
|
|
8
21
|
## [0.18.1] - 2026-11-16
|
|
9
22
|
|
|
10
23
|
### Fixed
|
package/bin/lib/launcher.mjs
CHANGED
|
@@ -405,7 +405,7 @@ export function formatUpgradeUsage() {
|
|
|
405
405
|
'Exit codes:',
|
|
406
406
|
' 0 already up to date, nothing to do, --dry-run, or --help',
|
|
407
407
|
' 1 hard failure (e.g. self-upgrade did not verify); profile untouched/rolled back',
|
|
408
|
-
' 2 usage error',
|
|
408
|
+
' 2 usage error, or another upgrade is already running (profile lock held)',
|
|
409
409
|
' 3 partial: a package did not reach the target version, or overrides could not be recorded',
|
|
410
410
|
].join('\n')
|
|
411
411
|
}
|
package/dist/client/index.js
CHANGED
|
@@ -59745,7 +59745,7 @@ var init_subagents_viewer = __esm(() => {
|
|
|
59745
59745
|
import { TextAttributes as TextAttributes12 } from "@opentui/core";
|
|
59746
59746
|
function resolveVersion() {
|
|
59747
59747
|
try {
|
|
59748
|
-
return "0.18.
|
|
59748
|
+
return "0.18.2";
|
|
59749
59749
|
} catch {
|
|
59750
59750
|
return "dev";
|
|
59751
59751
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiwayds/dsh-opentui",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/fan56/dsh-opentui.git",
|
|
8
|
+
"directory": "packages/shell"
|
|
9
|
+
},
|
|
5
10
|
"type": "module",
|
|
6
11
|
"bin": {
|
|
7
12
|
"dsh-opentui": "bin/dsh-opentui.mjs"
|
|
@@ -16,6 +16,14 @@ import { compareVersions, parseVersion, resolveEffectivePin } from './provision-
|
|
|
16
16
|
|
|
17
17
|
export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
|
|
18
18
|
|
|
19
|
+
// Identities of the .npmrc files the upgrade command reads, least specific
|
|
20
|
+
// first. They are labels, not paths: the caller turns them into real paths and
|
|
21
|
+
// keeps them in the resolved registry so the install rule can tell npm's own
|
|
22
|
+
// file (~/.npmrc) from the ones npm never reads.
|
|
23
|
+
export const NPMRC_HOME = '~/.npmrc'
|
|
24
|
+
export const NPMRC_DSH_HOME = '$DSH_HOME/.npmrc'
|
|
25
|
+
export const NPMRC_PROFILE = '<profile>/.npmrc'
|
|
26
|
+
|
|
19
27
|
// ---------------------------------------------------------------------------
|
|
20
28
|
// Registry resolution
|
|
21
29
|
// ---------------------------------------------------------------------------
|
|
@@ -36,19 +44,23 @@ function stripTrailingSlashes(value) {
|
|
|
36
44
|
return String(value).replace(/\/+$/, '')
|
|
37
45
|
}
|
|
38
46
|
|
|
39
|
-
/** Last `registry=` line across all
|
|
47
|
+
/** Last `registry=` line across all files wins: later files override earlier
|
|
40
48
|
* ones, and inside one file the last assignment wins, which is how npm's
|
|
41
|
-
* own config layering behaves.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
49
|
+
* own config layering behaves. Returns the value together with the identity
|
|
50
|
+
* of the file it came from, so the install rule can tell npm's own file from
|
|
51
|
+
* the ones npm never reads. */
|
|
52
|
+
function registryFromNpmrcFiles(npmrcFiles) {
|
|
53
|
+
let found = null
|
|
54
|
+
for (const file of npmrcFiles) {
|
|
55
|
+
if (typeof file?.text !== 'string') continue
|
|
56
|
+
let value = ''
|
|
57
|
+
for (const line of file.text.split(/\r?\n/)) {
|
|
47
58
|
const match = /^\s*registry\s*=\s*(.+)$/i.exec(line)
|
|
48
59
|
if (!match) continue
|
|
49
|
-
const
|
|
50
|
-
if (
|
|
60
|
+
const parsed = cleanRegistryValue(match[1])
|
|
61
|
+
if (parsed) value = parsed
|
|
51
62
|
}
|
|
63
|
+
if (value) found = { registry: value, path: file.path }
|
|
52
64
|
}
|
|
53
65
|
return found
|
|
54
66
|
}
|
|
@@ -57,25 +69,57 @@ function registryFromNpmrcTexts(npmrcTexts) {
|
|
|
57
69
|
* Where the `npm view` query should go.
|
|
58
70
|
*
|
|
59
71
|
* Priority: DSH_UPGRADE_REGISTRY (explicit operator override) -> the npmrc
|
|
60
|
-
*
|
|
72
|
+
* files the caller read, last one winning -> the public registry.
|
|
61
73
|
*
|
|
62
|
-
* `
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
74
|
+
* `npmrcFiles` is a list of `{ path, text }` where `path` names the file
|
|
75
|
+
* (`~/.npmrc`, `$DSH_HOME/.npmrc`, `<profile>/.npmrc`): this module does no
|
|
76
|
+
* IO, and the caller decides which files apply (user, DSH home, profile).
|
|
77
|
+
* `sourcePath` is that identity (or `env` / `default`); `source` stays the
|
|
78
|
+
* coarse bucket callers already print. The returned registry never ends with
|
|
79
|
+
* `/` so argv and string comparisons stay canonical.
|
|
66
80
|
*
|
|
67
|
-
* @param {{ env?: Record<string, string|undefined>,
|
|
68
|
-
*
|
|
81
|
+
* @param {{ env?: Record<string, string|undefined>,
|
|
82
|
+
* npmrcFiles?: Array<{ path: string, text: string }> }} [input]
|
|
83
|
+
* @returns {{ registry: string, source: 'env'|'npmrc'|'default', sourcePath: string }}
|
|
69
84
|
*/
|
|
70
|
-
export function resolveRegistry({ env = {},
|
|
85
|
+
export function resolveRegistry({ env = {}, npmrcFiles = [] } = {}) {
|
|
71
86
|
const rawEnv = env && typeof env === 'object' ? env.DSH_UPGRADE_REGISTRY : undefined
|
|
72
87
|
const fromEnv = typeof rawEnv === 'string' ? stripTrailingSlashes(cleanRegistryValue(rawEnv)) : ''
|
|
73
|
-
if (fromEnv) return { registry: fromEnv, source: 'env' }
|
|
88
|
+
if (fromEnv) return { registry: fromEnv, source: 'env', sourcePath: 'env' }
|
|
89
|
+
|
|
90
|
+
const fromNpmrc = registryFromNpmrcFiles(Array.isArray(npmrcFiles) ? npmrcFiles : [])
|
|
91
|
+
if (fromNpmrc) {
|
|
92
|
+
const registry = stripTrailingSlashes(fromNpmrc.registry)
|
|
93
|
+
// An unnamed text cannot be attributed to npm's own file, so it is
|
|
94
|
+
// forwarded explicitly: over-specifying is harmless, under-specifying
|
|
95
|
+
// sends the install to a different registry than the query used.
|
|
96
|
+
const named = typeof fromNpmrc.path === 'string' && fromNpmrc.path !== ''
|
|
97
|
+
const sourcePath = named ? fromNpmrc.path : 'npmrc'
|
|
98
|
+
return { registry, source: 'npmrc', sourcePath }
|
|
99
|
+
}
|
|
74
100
|
|
|
75
|
-
|
|
76
|
-
|
|
101
|
+
return { registry: OFFICIAL_REGISTRY, source: 'default', sourcePath: 'default' }
|
|
102
|
+
}
|
|
77
103
|
|
|
78
|
-
|
|
104
|
+
/**
|
|
105
|
+
* argv for `npm i -g <pkg>@<target>`.
|
|
106
|
+
*
|
|
107
|
+
* npm reads `~/.npmrc` (plus the project and global files) itself, so a
|
|
108
|
+
* registry that came from there is already what this install resolves: passing
|
|
109
|
+
* it again would only override per-scope / per-package configuration the user
|
|
110
|
+
* wrote. Every other source is invisible to npm — `DSH_UPGRADE_REGISTRY` is
|
|
111
|
+
* this command's own variable, and `$DSH_HOME/.npmrc` / `<profile>/.npmrc` are
|
|
112
|
+
* files npm never looks at — so the install must be told explicitly, or the
|
|
113
|
+
* version query hits the mirror while the install goes to the default
|
|
114
|
+
* registry.
|
|
115
|
+
*
|
|
116
|
+
* @param {{ pkg: string, target: string, registry: string, sourcePath: string }} input
|
|
117
|
+
* @returns {string[]}
|
|
118
|
+
*/
|
|
119
|
+
export function buildSelfInstallArgs({ pkg, target, registry, sourcePath } = {}) {
|
|
120
|
+
const args = ['i', '-g', `${pkg}@${target}`]
|
|
121
|
+
if (sourcePath !== NPMRC_HOME) args.push('--registry', registry)
|
|
122
|
+
return args
|
|
79
123
|
}
|
|
80
124
|
|
|
81
125
|
/**
|
|
@@ -268,11 +312,18 @@ function entryVersion(entry) {
|
|
|
268
312
|
|
|
269
313
|
/** The name -> entry map of an override document. Both shapes are accepted
|
|
270
314
|
* because the reader that feeds provisioning returns the inner map while the
|
|
271
|
-
* command works with the whole document; `packages` wins when both exist.
|
|
315
|
+
* command works with the whole document; `packages` wins when both exist.
|
|
316
|
+
* Entries parseOverrides could not interpret are carried in `raw` and are
|
|
317
|
+
* folded back in here: to a pin decision they are simply entries that lose
|
|
318
|
+
* (invalid), which is exactly what this map represented before `raw` existed. */
|
|
272
319
|
function overridePackageMap(overrides) {
|
|
273
320
|
if (!isPlainObject(overrides)) return {}
|
|
274
|
-
if (isPlainObject(overrides.packages)) return overrides
|
|
275
|
-
|
|
321
|
+
if (!isPlainObject(overrides.packages)) return overrides
|
|
322
|
+
const packages = overrides.packages
|
|
323
|
+
if (!isPlainObject(overrides.raw)) return packages
|
|
324
|
+
const merged = { ...overrides.raw }
|
|
325
|
+
for (const [name, entry] of Object.entries(packages)) merged[name] = entry
|
|
326
|
+
return merged
|
|
276
327
|
}
|
|
277
328
|
|
|
278
329
|
/**
|
|
@@ -280,16 +331,25 @@ function overridePackageMap(overrides) {
|
|
|
280
331
|
* is unusable (bad JSON, not an object, no usable `packages` object) — the
|
|
281
332
|
* caller maps null to "no overrides", never to an error.
|
|
282
333
|
*
|
|
283
|
-
* A single malformed entry (no version string)
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
334
|
+
* A single malformed entry (no version string) does not fail the file, and it
|
|
335
|
+
* is NOT dropped either: it lands in `raw` verbatim. The command rewrites the
|
|
336
|
+
* whole `packages` map after every upgrade, so dropping an entry it cannot
|
|
337
|
+
* interpret would silently delete a hand-written pin. Uninterpretable means
|
|
338
|
+
* "this module cannot use it" (pickEffectivePin ignores it), not "the user did
|
|
339
|
+
* not mean it".
|
|
340
|
+
*
|
|
341
|
+
* Interpreted entries keep their shape — a string stays a string, an object
|
|
342
|
+
* keeps its metadata (`shippedPin`, `updatedAt`) — so a read/serialize round
|
|
343
|
+
* trip does not destroy fields this module does not interpret. Neither
|
|
344
|
+
* `version` nor the entry's semver validity is enforced here (pickEffectivePin
|
|
345
|
+
* judges validity, so a bad version can still be reported and cleaned up).
|
|
290
346
|
*
|
|
291
347
|
* @param {string} text
|
|
292
|
-
* @returns {{
|
|
348
|
+
* @returns {{
|
|
349
|
+
* version: number,
|
|
350
|
+
* packages: Record<string, string|{version: string}>,
|
|
351
|
+
* raw: Record<string, unknown>,
|
|
352
|
+
* } | null}
|
|
293
353
|
*/
|
|
294
354
|
export function parseOverrides(text) {
|
|
295
355
|
let doc
|
|
@@ -302,14 +362,18 @@ export function parseOverrides(text) {
|
|
|
302
362
|
if (!isPlainObject(doc.packages)) return null
|
|
303
363
|
|
|
304
364
|
const packages = {}
|
|
365
|
+
const raw = {}
|
|
305
366
|
for (const [name, entry] of Object.entries(doc.packages)) {
|
|
306
367
|
if (name === '') continue
|
|
307
368
|
const version = entryVersion(entry)
|
|
308
|
-
if (version === null || version === '')
|
|
369
|
+
if (version === null || version === '') {
|
|
370
|
+
raw[name] = entry
|
|
371
|
+
continue
|
|
372
|
+
}
|
|
309
373
|
packages[name] = typeof entry === 'string' ? version : { ...entry, version }
|
|
310
374
|
}
|
|
311
375
|
|
|
312
|
-
return { version: Number.isInteger(doc.version) ? doc.version : 1, packages }
|
|
376
|
+
return { version: Number.isInteger(doc.version) ? doc.version : 1, packages, raw }
|
|
313
377
|
}
|
|
314
378
|
|
|
315
379
|
/**
|
|
@@ -318,15 +382,34 @@ export function parseOverrides(text) {
|
|
|
318
382
|
* every upgrade and lives in a directory users inspect and diff; insertion
|
|
319
383
|
* order must not leak into the bytes.
|
|
320
384
|
*
|
|
321
|
-
*
|
|
385
|
+
* `raw` (from parseOverrides) is written back into `packages` under its
|
|
386
|
+
* original name and value, and is never emitted as a key of its own: that is
|
|
387
|
+
* what makes a rewrite lossless for entries the parser could not interpret.
|
|
388
|
+
* An interpreted entry always wins over a raw one with the same name.
|
|
389
|
+
*
|
|
390
|
+
* @param {{ packages?: Record<string, unknown>, raw?: Record<string, unknown>, [key: string]: unknown }} obj
|
|
322
391
|
* @returns {string}
|
|
323
392
|
*/
|
|
324
393
|
export function serializeOverrides(obj) {
|
|
325
394
|
if (!isPlainObject(obj)) throw new TypeError('serializeOverrides: expected a plain object')
|
|
326
395
|
const packages = isPlainObject(obj.packages) ? obj.packages : {}
|
|
396
|
+
const raw = isPlainObject(obj.raw) ? obj.raw : {}
|
|
397
|
+
|
|
398
|
+
const merged = {}
|
|
399
|
+
for (const [name, entry] of Object.entries(raw)) {
|
|
400
|
+
if (!Object.prototype.hasOwnProperty.call(packages, name)) merged[name] = entry
|
|
401
|
+
}
|
|
402
|
+
for (const [name, entry] of Object.entries(packages)) merged[name] = entry
|
|
403
|
+
|
|
327
404
|
const sorted = {}
|
|
328
|
-
for (const name of Object.keys(
|
|
329
|
-
|
|
405
|
+
for (const name of Object.keys(merged).sort()) sorted[name] = merged[name]
|
|
406
|
+
|
|
407
|
+
// Everything but `raw` is document metadata and passes through untouched.
|
|
408
|
+
const document = {}
|
|
409
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
410
|
+
if (key !== 'raw') document[key] = value
|
|
411
|
+
}
|
|
412
|
+
return `${JSON.stringify({ ...document, packages: sorted }, null, 2)}\n`
|
|
330
413
|
}
|
|
331
414
|
|
|
332
415
|
/**
|
package/scripts/upgrade.mjs
CHANGED
|
@@ -13,17 +13,19 @@
|
|
|
13
13
|
// install form is skipped with a warning — installing into a different
|
|
14
14
|
// prefix would create a shadow copy that `dsh-opentui` never resolves.
|
|
15
15
|
// A hard failure here aborts BEFORE anything touches the profile.
|
|
16
|
-
// 4. Plugins: `applyPluginUpgrades(ctx)` —
|
|
17
|
-
// batched `dsh plugin add`, verify each package on
|
|
18
|
-
// landed versions in upgrade-overrides.json. An
|
|
19
|
-
// the backup and re-adds the pre-upgrade specs;
|
|
20
|
-
// land is reported but never rolls back a
|
|
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.
|
|
21
22
|
//
|
|
22
23
|
// Exit codes: 0 done/nothing to do/dry-run/help; 1 hard failure OR any package
|
|
23
24
|
// whose target version could not be determined (a query failure means the
|
|
24
25
|
// target is unknown, which is not "up to date"; nothing is written in that
|
|
25
|
-
// case); 2 usage refusal
|
|
26
|
-
//
|
|
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).
|
|
27
29
|
//
|
|
28
30
|
// Dependency injection: every child process goes through `run(cmd, args, {
|
|
29
31
|
// timeout })` and every file operation through `fs`, both overridable from the
|
|
@@ -31,16 +33,20 @@
|
|
|
31
33
|
// and abort paths without npm, a TTY, or a real profile.
|
|
32
34
|
import { execFileSync } from 'node:child_process'
|
|
33
35
|
import {
|
|
36
|
+
closeSync,
|
|
34
37
|
copyFileSync,
|
|
35
38
|
existsSync,
|
|
36
39
|
mkdirSync,
|
|
40
|
+
openSync,
|
|
37
41
|
readFileSync,
|
|
38
42
|
readSync,
|
|
39
43
|
realpathSync,
|
|
40
44
|
renameSync,
|
|
41
45
|
rmdirSync,
|
|
42
46
|
rmSync,
|
|
47
|
+
statSync,
|
|
43
48
|
writeFileSync,
|
|
49
|
+
writeSync,
|
|
44
50
|
} from 'node:fs'
|
|
45
51
|
import { homedir } from 'node:os'
|
|
46
52
|
import { dirname, join, resolve, sep } from 'node:path'
|
|
@@ -54,6 +60,10 @@ import {
|
|
|
54
60
|
resolveEffectivePin,
|
|
55
61
|
} from './lib/provision-plan.mjs'
|
|
56
62
|
import {
|
|
63
|
+
NPMRC_DSH_HOME,
|
|
64
|
+
NPMRC_HOME,
|
|
65
|
+
NPMRC_PROFILE,
|
|
66
|
+
buildSelfInstallArgs,
|
|
57
67
|
buildUpgradePlan,
|
|
58
68
|
buildViewArgs,
|
|
59
69
|
isOfficialRegistry,
|
|
@@ -73,6 +83,19 @@ const PREFIX_TIMEOUT_MS = 10 * 1000
|
|
|
73
83
|
const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
|
|
74
84
|
const OVERRIDE_FILE = 'upgrade-overrides.json'
|
|
75
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: '
|
|
76
99
|
// pnpm-workspace.yaml belongs here because users hand-write allowBuilds in it:
|
|
77
100
|
// a host rollback that restored only the manifest and the lock would leave the
|
|
78
101
|
// rewritten workspace file in place.
|
|
@@ -158,6 +181,13 @@ export const defaultFs = {
|
|
|
158
181
|
rmdirSync: (path) => rmdirSync(path),
|
|
159
182
|
copyFileSync: (from, to) => copyFileSync(from, to),
|
|
160
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),
|
|
161
191
|
}
|
|
162
192
|
|
|
163
193
|
/** A synchronous one-line read from stdin (the confirmation prompt). */
|
|
@@ -217,19 +247,25 @@ function readText(fs, path) {
|
|
|
217
247
|
}
|
|
218
248
|
|
|
219
249
|
/**
|
|
220
|
-
* npmrc
|
|
221
|
-
* Only files that exist are passed,
|
|
222
|
-
* one: profile/.npmrc >
|
|
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.
|
|
223
255
|
*/
|
|
224
|
-
function
|
|
256
|
+
function collectNpmrcFiles({ fs, dshHome, profileDir, env }) {
|
|
225
257
|
const home = env.HOME || homedir()
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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 })
|
|
231
267
|
}
|
|
232
|
-
return
|
|
268
|
+
return files
|
|
233
269
|
}
|
|
234
270
|
|
|
235
271
|
/** The version on disk for a profile dependency, when readable. */
|
|
@@ -305,6 +341,110 @@ function backupStamp(now = new Date()) {
|
|
|
305
341
|
return now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
|
|
306
342
|
}
|
|
307
343
|
|
|
344
|
+
// ---------------------------------------------------------------------------
|
|
345
|
+
// Concurrency: <profileDir>/.upgrade.lock
|
|
346
|
+
//
|
|
347
|
+
// Two upgrades racing over one profile both back up, both install, and both
|
|
348
|
+
// rewrite package.json / upgrade-overrides.json — the loser's backup then
|
|
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
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Is the stamp older than LOCK_STALE_MS? Only a readable `startedAt` can answer
|
|
372
|
+
* that; an unreadable payload carries no age, so the caller rules out the
|
|
373
|
+
* create->write window by mtime first (see lockIsInWriteWindow).
|
|
374
|
+
*/
|
|
375
|
+
function isStaleLock(holder, now) {
|
|
376
|
+
if (holder?.startedAt === null || holder?.startedAt === undefined) return false
|
|
377
|
+
const started = Date.parse(holder.startedAt)
|
|
378
|
+
if (Number.isNaN(started)) return true
|
|
379
|
+
return now - started > LOCK_STALE_MS
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Is the lock file young enough to be a claim mid-create? Ages the create and
|
|
384
|
+
* the payload write together, so a writer that was descheduled between them is
|
|
385
|
+
* still respected: past the grace window the creator is gone and the file is
|
|
386
|
+
* garbage nothing else would ever clear.
|
|
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.
|
|
390
|
+
*/
|
|
391
|
+
function lockIsInWriteWindow(fs, lockPath, now) {
|
|
392
|
+
let mtimeMs
|
|
393
|
+
try {
|
|
394
|
+
mtimeMs = Number(fs.statSync(lockPath)?.mtimeMs)
|
|
395
|
+
} catch {
|
|
396
|
+
return false
|
|
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
|
+
|
|
308
448
|
// ---------------------------------------------------------------------------
|
|
309
449
|
// Phase: self upgrade
|
|
310
450
|
// ---------------------------------------------------------------------------
|
|
@@ -313,12 +453,21 @@ function backupStamp(now = new Date()) {
|
|
|
313
453
|
* Bring the launcher itself up to `target`, but only when the running copy is
|
|
314
454
|
* the one the npm global prefix owns.
|
|
315
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
|
|
316
465
|
* @returns {{ kind: 'skipped', form: string } |
|
|
317
466
|
* { kind: 'latest', version: string } |
|
|
318
467
|
* { kind: 'upgraded', from: string, to: string } |
|
|
319
468
|
* { kind: 'failed', exitCode: 1 }}
|
|
320
469
|
*/
|
|
321
|
-
function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
|
|
470
|
+
function upgradeSelf({ self, target, registry, registryPath, run, fs, selfPath }) {
|
|
322
471
|
if (!self || typeof target !== 'string' || target === '') {
|
|
323
472
|
say('self: skipped (install form: unknown)')
|
|
324
473
|
warn(
|
|
@@ -354,7 +503,13 @@ function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
|
|
|
354
503
|
return { kind: 'latest', version: self.version }
|
|
355
504
|
}
|
|
356
505
|
|
|
357
|
-
const
|
|
506
|
+
const installArgs = buildSelfInstallArgs({
|
|
507
|
+
pkg: self.name,
|
|
508
|
+
target,
|
|
509
|
+
registry,
|
|
510
|
+
sourcePath: registryPath,
|
|
511
|
+
})
|
|
512
|
+
const install = run('npm', installArgs, {
|
|
358
513
|
timeout: INSTALL_TIMEOUT_MS,
|
|
359
514
|
})
|
|
360
515
|
if (!install || install.status !== 0) {
|
|
@@ -470,13 +625,17 @@ function originalSpecs({ fs, copies, manifestPath }) {
|
|
|
470
625
|
* One batched install. A host that rejects `--save-exact` gets exactly one
|
|
471
626
|
* retry without it; every other failure is final (no per-package retry).
|
|
472
627
|
*
|
|
628
|
+
* On success the captured stderr is kept instead of thrown away: pnpm writes
|
|
629
|
+
* progress and warnings there, and a batch that succeeded slowly or with
|
|
630
|
+
* warnings otherwise leaves no trace at all. The caller prints a short tail.
|
|
631
|
+
*
|
|
473
632
|
* @returns {{ status: number, args: string[], stderr: string }}
|
|
474
633
|
*/
|
|
475
634
|
function installPlugins({ run, env, specs, warn }) {
|
|
476
635
|
let args = pluginAddArgs(specs)
|
|
477
636
|
let result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
|
|
478
637
|
let status = runStatus(result)
|
|
479
|
-
if (status === 0) return { status, args, stderr: '' }
|
|
638
|
+
if (status === 0) return { status, args, stderr: String(result?.stderr ?? '') }
|
|
480
639
|
|
|
481
640
|
const stderr = String(result?.stderr ?? '')
|
|
482
641
|
if (SAVE_EXACT_REJECTED.test(stderr)) {
|
|
@@ -484,7 +643,7 @@ function installPlugins({ run, env, specs, warn }) {
|
|
|
484
643
|
args = pluginAddArgs(specs, { saveExact: false })
|
|
485
644
|
result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
|
|
486
645
|
status = runStatus(result)
|
|
487
|
-
if (status === 0) return { status, args, stderr: '' }
|
|
646
|
+
if (status === 0) return { status, args, stderr: String(result?.stderr ?? '') }
|
|
488
647
|
}
|
|
489
648
|
return { status, args, stderr }
|
|
490
649
|
}
|
|
@@ -569,15 +728,52 @@ function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
|
|
|
569
728
|
}
|
|
570
729
|
|
|
571
730
|
/**
|
|
572
|
-
* Phase 4: install every planned plugin upgrade,
|
|
573
|
-
* the landed versions in `upgrade-overrides.json`.
|
|
731
|
+
* Phase 4: claim the profile lock, then install every planned plugin upgrade,
|
|
732
|
+
* verify it landed, and record the landed versions in `upgrade-overrides.json`.
|
|
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.
|
|
574
738
|
*
|
|
575
739
|
* Outcomes (they map 1:1 to the process exit code, see exitCodeAfterPlugins):
|
|
740
|
+
* - another upgrade holds the lock -> nothing written, code 2
|
|
576
741
|
* - all landed, overrides written or unnecessary -> backup deleted, code 0
|
|
577
742
|
* - install failed -> rollback, backup kept, code 1
|
|
578
743
|
* - install ok, some version did not land -> no rollback, code 3
|
|
579
744
|
* - override write failed -> code 3
|
|
580
745
|
*
|
|
746
|
+
* @param {Parameters<typeof installPluginUpgrades>[0]} ctx
|
|
747
|
+
* @returns {ReturnType<typeof installPluginUpgrades> & { lockBusy?: boolean }}
|
|
748
|
+
*/
|
|
749
|
+
function applyPluginUpgrades(ctx) {
|
|
750
|
+
const { profileDir, pluginRows, fs, log } = ctx
|
|
751
|
+
|
|
752
|
+
if (pluginRows.length === 0) {
|
|
753
|
+
log('plugins: already up to date')
|
|
754
|
+
return { landed: [], mismatched: [], failed: [] }
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const lock = acquireUpgradeLock({ fs, lockPath: join(profileDir, LOCK_FILE) })
|
|
758
|
+
if (!lock.ok) {
|
|
759
|
+
const pid = lock.holder.pid ?? 'unknown'
|
|
760
|
+
const startedAt = lock.holder.startedAt ?? 'unknown'
|
|
761
|
+
console.error(`${LOCK_PREFIX}another upgrade is running (pid ${pid}, started ${startedAt})`)
|
|
762
|
+
log('nothing changed')
|
|
763
|
+
return { landed: [], mismatched: [], failed: [], lockBusy: true }
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
try {
|
|
767
|
+
return installPluginUpgrades(ctx)
|
|
768
|
+
} finally {
|
|
769
|
+
lock.release()
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* The write phase proper: backup, one batched install, verify, override write.
|
|
775
|
+
* Callers go through applyPluginUpgrades, which owns the profile lock.
|
|
776
|
+
*
|
|
581
777
|
* @param {{
|
|
582
778
|
* profileDir: string, manifestPath: string, overridePath: string,
|
|
583
779
|
* backupDir: string, pluginRows: Array<{name: string, current: string|null, target: string}>,
|
|
@@ -596,15 +792,10 @@ function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
|
|
|
596
792
|
* upToDate?: number,
|
|
597
793
|
* }}
|
|
598
794
|
*/
|
|
599
|
-
function
|
|
795
|
+
function installPluginUpgrades(ctx) {
|
|
600
796
|
const { profileDir, manifestPath, overridePath, backupDir, rows, pluginRows, counts, selfName, env, run, fs, log, warn } =
|
|
601
797
|
ctx
|
|
602
798
|
|
|
603
|
-
if (pluginRows.length === 0) {
|
|
604
|
-
log('plugins: already up to date')
|
|
605
|
-
return { landed: [], mismatched: [], failed: [] }
|
|
606
|
-
}
|
|
607
|
-
|
|
608
799
|
const specs = pluginRows.map((row) => `${row.name}@${row.target}`)
|
|
609
800
|
const copies = createBackup({ fs, profileDir, backupDir })
|
|
610
801
|
log(`backup: ${backupDir}`)
|
|
@@ -621,6 +812,13 @@ function applyPluginUpgrades(ctx) {
|
|
|
621
812
|
return { landed: [], mismatched: [], failed: [{ reason: 'install', status: install.status }] }
|
|
622
813
|
}
|
|
623
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
|
+
|
|
624
822
|
const { landed, mismatched } = verifyPlugins({ fs, profileDir, rows: pluginRows })
|
|
625
823
|
for (const item of mismatched) {
|
|
626
824
|
log(`mismatch: ${item.name} expected ${item.expected}, installed ${item.actual ?? 'nothing'}`)
|
|
@@ -710,6 +908,7 @@ function applyPluginUpgrades(ctx) {
|
|
|
710
908
|
|
|
711
909
|
/**
|
|
712
910
|
* Exit code after the plugin phase (plan §1.3):
|
|
911
|
+
* 2 - another upgrade holds `<profile>/.upgrade.lock`; nothing was written;
|
|
713
912
|
* 1 - the batched install failed and the profile was rolled back;
|
|
714
913
|
* 3 - partially applied: the install exited 0 but a package is not at its
|
|
715
914
|
* target version, or the override file could not be written;
|
|
@@ -717,6 +916,7 @@ function applyPluginUpgrades(ctx) {
|
|
|
717
916
|
*/
|
|
718
917
|
function exitCodeAfterPlugins({ pluginResult } = {}) {
|
|
719
918
|
if (!pluginResult) return 0
|
|
919
|
+
if (pluginResult.lockBusy) return 2
|
|
720
920
|
if (Array.isArray(pluginResult.failed) && pluginResult.failed.length > 0) return 1
|
|
721
921
|
if (pluginResult.overridesError) return 3
|
|
722
922
|
if (Array.isArray(pluginResult.mismatched) && pluginResult.mismatched.length > 0) return 3
|
|
@@ -747,7 +947,8 @@ function exitCodeAfterPlugins({ pluginResult } = {}) {
|
|
|
747
947
|
* }} [context]
|
|
748
948
|
* @returns {number} 0 done / nothing to do / --dry-run / --help,
|
|
749
949
|
* 1 hard failure or an undetermined target version, 2 non-interactive
|
|
750
|
-
* refusal
|
|
950
|
+
* refusal or another upgrade holding the profile lock (the bin owns the
|
|
951
|
+
* other usage errors), 3 partially applied
|
|
751
952
|
*/
|
|
752
953
|
export function runUpgrade(
|
|
753
954
|
opts = {},
|
|
@@ -799,9 +1000,9 @@ export function runUpgrade(
|
|
|
799
1000
|
warn(`could not read ${manifestPath}; treating the profile as having no plugin dependencies`)
|
|
800
1001
|
}
|
|
801
1002
|
|
|
802
|
-
const { registry, source } = resolveRegistry({
|
|
1003
|
+
const { registry, source, sourcePath } = resolveRegistry({
|
|
803
1004
|
env,
|
|
804
|
-
|
|
1005
|
+
npmrcFiles: collectNpmrcFiles({ fs, dshHome, profileDir, env }),
|
|
805
1006
|
})
|
|
806
1007
|
|
|
807
1008
|
const tag = opts.tag ?? 'latest'
|
|
@@ -889,6 +1090,7 @@ export function runUpgrade(
|
|
|
889
1090
|
self,
|
|
890
1091
|
target: selfRow?.target ?? null,
|
|
891
1092
|
registry,
|
|
1093
|
+
registryPath: sourcePath,
|
|
892
1094
|
run,
|
|
893
1095
|
fs,
|
|
894
1096
|
selfPath,
|