@aiwayds/dsh-opentui 0.27.1 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,489 +0,0 @@
1
- // Pure planning logic for the `upgrade` subcommand and for the downgrade
2
- // guard that provisioning shares with it.
3
- //
4
- // Same split as provision-plan.mjs (see its header): no filesystem, no
5
- // child_process, no network. The caller reads `.npmrc` files, spawns
6
- // `npm view`, and writes the override file; this module only decides what
7
- // those actions should be, so every decision is unit-testable from plain
8
- // fixtures.
9
- //
10
- // Version ordering is NOT re-implemented here. provision-plan.mjs already
11
- // exports parseVersion/compareVersions (a deliberately small semver subset)
12
- // and owns the shipped pins, so both the upgrade command and provisioning
13
- // must judge "newer" with the same rule; a second copy would be free to drift.
14
-
15
- import { compareVersions, parseVersion, resolveEffectivePin } from './provision-plan.mjs'
16
-
17
- export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
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
-
27
- // ---------------------------------------------------------------------------
28
- // Registry resolution
29
- // ---------------------------------------------------------------------------
30
-
31
- /** A .npmrc value ends at a `#` comment; surrounding quotes are optional.
32
- * npm allows `key = "value"` and `registry=https://host/` alike. */
33
- function cleanRegistryValue(raw) {
34
- let text = String(raw)
35
- const comment = text.indexOf('#')
36
- if (comment !== -1) text = text.slice(0, comment)
37
- text = text.trim()
38
- const quoted = /^(['"])(.*)\1$/.exec(text)
39
- if (quoted) text = quoted[2].trim()
40
- return text
41
- }
42
-
43
- function stripTrailingSlashes(value) {
44
- return String(value).replace(/\/+$/, '')
45
- }
46
-
47
- /** Last `registry=` line across all files wins: later files override earlier
48
- * ones, and inside one file the last assignment wins, which is how npm's
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/)) {
58
- const match = /^\s*registry\s*=\s*(.+)$/i.exec(line)
59
- if (!match) continue
60
- const parsed = cleanRegistryValue(match[1])
61
- if (parsed) value = parsed
62
- }
63
- if (value) found = { registry: value, path: file.path }
64
- }
65
- return found
66
- }
67
-
68
- /**
69
- * Where the `npm view` query should go.
70
- *
71
- * Priority: DSH_UPGRADE_REGISTRY (explicit operator override) -> the npmrc
72
- * files the caller read, last one winning -> the public registry.
73
- *
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.
80
- *
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 }}
84
- */
85
- export function resolveRegistry({ env = {}, npmrcFiles = [] } = {}) {
86
- const rawEnv = env && typeof env === 'object' ? env.DSH_UPGRADE_REGISTRY : undefined
87
- const fromEnv = typeof rawEnv === 'string' ? stripTrailingSlashes(cleanRegistryValue(rawEnv)) : ''
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
- }
100
-
101
- return { registry: OFFICIAL_REGISTRY, source: 'default', sourcePath: 'default' }
102
- }
103
-
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
123
- }
124
-
125
- /**
126
- * Is this the public npm registry (as opposed to a mirror)? A mirror can lag
127
- * behind upstream, which is worth a warning line in the plan output.
128
- * Accepts the bare host and both URL spellings, with or without a trailing
129
- * slash; the path and protocol are otherwise ignored.
130
- */
131
- export function isOfficialRegistry(registry) {
132
- if (typeof registry !== 'string') return false
133
- return /^(?:https?:\/\/)?registry\.npmjs\.org\/*$/i.test(registry.trim())
134
- }
135
-
136
- /**
137
- * argv for `npm view <pkg> dist-tags --json`.
138
- *
139
- * `dist-tags` returns every tag (latest, next, ...) in one call, so a single
140
- * invocation answers "what would --tag next resolve to" as well.
141
- *
142
- * `--prefer-online` is mandatory: without it npm answers from its local cache
143
- * (including negative cache entries), so a freshly published version can be
144
- * invisible for hours. `--registry` is mandatory too, because the machine's
145
- * configured registry may be a lagging mirror.
146
- *
147
- * `--fetch-retries 0` and `--fetch-timeout 20000` are part of the query, not a
148
- * tuning afterthought: an unreachable registry otherwise costs npm's default
149
- * retry ladder (2 retries with backoff) per package, which made a `--dry-run`
150
- * against a dead host take minutes before reporting `query-failed`. An
151
- * unreachable host is answered either way — only the wait differs, and no
152
- * retry can turn it into an answer.
153
- *
154
- * @param {{ pkg: string, registry: string }} input
155
- * @returns {string[]}
156
- */
157
- export function buildViewArgs({ pkg, registry } = {}) {
158
- if (typeof pkg !== 'string' || pkg === '') {
159
- throw new TypeError('buildViewArgs: pkg must be a non-empty string')
160
- }
161
- if (typeof registry !== 'string' || registry === '') {
162
- throw new TypeError('buildViewArgs: registry must be a non-empty string')
163
- }
164
- return [
165
- 'view',
166
- pkg,
167
- 'dist-tags',
168
- '--json',
169
- '--registry',
170
- registry,
171
- '--prefer-online',
172
- '--fetch-retries',
173
- '0',
174
- '--fetch-timeout',
175
- '20000',
176
- ]
177
- }
178
-
179
- // ---------------------------------------------------------------------------
180
- // Which dependencies the upgrade command may touch
181
- // ---------------------------------------------------------------------------
182
-
183
- const NON_REGISTRY_SPEC = /^(?:link|file|workspace|portal):|^(?:git\+|https?:)/i
184
-
185
- /**
186
- * May the upgrade command replace this dependency's spec with a registry
187
- * version?
188
- *
189
- * Never: host-closure packages (`@deepseek-ai/*`) — the host pins those and a
190
- * profile-local upgrade would fight it — and specs that do not point at a
191
- * registry (`link:`, `file:`, `workspace:`, `portal:`, `git+`, `http(s):`),
192
- * e.g. the profile's local `link:` dev dependency.
193
- * Everything else (caret, tilde, exact, `*`) is upgradable; a non-string spec
194
- * is not, because there is nothing to resolve.
195
- */
196
- export function isUpgradableDependency(name, spec) {
197
- if (typeof name !== 'string' || name.startsWith('@deepseek-ai/')) return false
198
- if (typeof spec !== 'string') return false
199
- return !NON_REGISTRY_SPEC.test(spec.trim())
200
- }
201
-
202
- /** The exact version a spec names, if it names one (`1.2.3`, `=1.2.3`);
203
- * ranges (`^1.2.3`, `~1.2.3`, `*`) answer null. */
204
- function exactVersionFromSpec(spec) {
205
- if (typeof spec !== 'string') return null
206
- const text = spec.trim().replace(/^=\s*/, '')
207
- return parseVersion(text) ? text : null
208
- }
209
-
210
- function byName(a, b) {
211
- if (a.name === b.name) return 0
212
- return a.name < b.name ? -1 : 1
213
- }
214
-
215
- const ACTION_ORDER = ['upgrade', 'latest', 'excluded', 'query-failed']
216
- const COUNT_KEY = {
217
- upgrade: 'upgrade',
218
- latest: 'latest',
219
- excluded: 'excluded',
220
- 'query-failed': 'queryFailed',
221
- }
222
-
223
- /**
224
- * Turn "manifest deps + installed versions + registry answers" into the plan
225
- * table the command prints and executes.
226
- *
227
- * Per dependency:
228
- * - `excluded` — isUpgradableDependency says no (checked first)
229
- * - `query-failed` — the caller has no dist-tag answer for the package
230
- * - `latest` — installed version equals the registry target
231
- * - `upgrade` — everything else, including "installed unknown"
232
- *
233
- * `current` prefers the version on disk (`installedVersions`); when the caller
234
- * could not read it, the exact version in the spec is the best available
235
- * truth. `null` means unknown and is never treated as up to date.
236
- * `target` is null only for rows that have no registry answer (`query-failed`).
237
- *
238
- * Row order is stable: upgrades first (by name), then latest, excluded, and
239
- * query-failed, each sorted by name, so two runs over the same inputs print
240
- * the same table.
241
- *
242
- * `tag` names the dist-tag the caller queried; its value already lives in
243
- * `latestByPkg`, so this function does not need it. It stays in the signature
244
- * because the plan header reports it.
245
- *
246
- * @param {{
247
- * deps: Record<string, string>,
248
- * installedVersions?: Record<string, string>,
249
- * latestByPkg?: Record<string, string>,
250
- * tag?: string,
251
- * }} input
252
- * @returns {{
253
- * rows: Array<{ name: string, currentSpec: string, current: string|null, target: string|null, action: 'upgrade'|'latest'|'excluded'|'query-failed' }>,
254
- * counts: { upgrade: number, latest: number, excluded: number, queryFailed: number },
255
- * }}
256
- */
257
- export function buildUpgradePlan({ deps, installedVersions = {}, latestByPkg = {}, tag = 'latest' } = {}) {
258
- const dependencies = deps && typeof deps === 'object' ? deps : {}
259
- const installed = installedVersions && typeof installedVersions === 'object' ? installedVersions : {}
260
- const latest = latestByPkg && typeof latestByPkg === 'object' ? latestByPkg : {}
261
- void tag // documented above: the caller has already resolved it into latestByPkg
262
-
263
- const rows = []
264
- for (const [name, spec] of Object.entries(dependencies)) {
265
- const currentSpec = typeof spec === 'string' ? spec : null
266
- const rawInstalled = installed[name]
267
- const current =
268
- typeof rawInstalled === 'string' && rawInstalled !== ''
269
- ? rawInstalled
270
- : exactVersionFromSpec(currentSpec)
271
- const rawTarget = latest[name]
272
- const target = typeof rawTarget === 'string' && rawTarget !== '' ? rawTarget : null
273
-
274
- let action
275
- if (!isUpgradableDependency(name, currentSpec)) action = 'excluded'
276
- else if (target === null) action = 'query-failed'
277
- else if (current !== null && current === target) action = 'latest'
278
- else action = 'upgrade'
279
-
280
- rows.push({ name, currentSpec, current, target, action })
281
- }
282
-
283
- const counts = { upgrade: 0, latest: 0, excluded: 0, queryFailed: 0 }
284
- for (const row of rows) counts[COUNT_KEY[row.action]] += 1
285
-
286
- const ordered = []
287
- for (const action of ACTION_ORDER) {
288
- ordered.push(...rows.filter((row) => row.action === action).sort(byName))
289
- }
290
-
291
- return { rows: ordered, counts }
292
- }
293
-
294
- // ---------------------------------------------------------------------------
295
- // upgrade-overrides.json — the file that stops the next start from
296
- // downgrading a package the upgrade command raised above the shipped pin.
297
- // ---------------------------------------------------------------------------
298
-
299
- function isPlainObject(value) {
300
- return typeof value === 'object' && value !== null && !Array.isArray(value)
301
- }
302
-
303
- /** An entry is either the bare version string or an object carrying a
304
- * `version` (e.g. `{ version, shippedPin, updatedAt }`). The bare form is
305
- * accepted for hand-written files; the object form is what the command
306
- * writes and what provisioning reads. */
307
- function entryVersion(entry) {
308
- if (typeof entry === 'string') return entry.trim()
309
- if (isPlainObject(entry) && typeof entry.version === 'string') return entry.version.trim()
310
- return null
311
- }
312
-
313
- /** The name -> entry map of an override document. Both shapes are accepted
314
- * because the reader that feeds provisioning returns the inner map while the
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. */
319
- function overridePackageMap(overrides) {
320
- if (!isPlainObject(overrides)) return {}
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
327
- }
328
-
329
- /**
330
- * Parse the override document text. Returns null when the document as a whole
331
- * is unusable (bad JSON, not an object, no usable `packages` object) — the
332
- * caller maps null to "no overrides", never to an error.
333
- *
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).
346
- *
347
- * @param {string} text
348
- * @returns {{
349
- * version: number,
350
- * packages: Record<string, string|{version: string}>,
351
- * raw: Record<string, unknown>,
352
- * } | null}
353
- */
354
- export function parseOverrides(text) {
355
- let doc
356
- try {
357
- doc = JSON.parse(String(text ?? ''))
358
- } catch {
359
- return null
360
- }
361
- if (!isPlainObject(doc)) return null
362
- if (!isPlainObject(doc.packages)) return null
363
-
364
- const packages = {}
365
- const raw = {}
366
- for (const [name, entry] of Object.entries(doc.packages)) {
367
- if (name === '') continue
368
- const version = entryVersion(entry)
369
- if (version === null || version === '') {
370
- raw[name] = entry
371
- continue
372
- }
373
- packages[name] = typeof entry === 'string' ? version : { ...entry, version }
374
- }
375
-
376
- return { version: Number.isInteger(doc.version) ? doc.version : 1, packages, raw }
377
- }
378
-
379
- /**
380
- * Stable serialization: two-space JSON, trailing newline, `packages` keys in
381
- * lexicographic order. Stability matters because the file is written after
382
- * every upgrade and lives in a directory users inspect and diff; insertion
383
- * order must not leak into the bytes.
384
- *
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
391
- * @returns {string}
392
- */
393
- export function serializeOverrides(obj) {
394
- if (!isPlainObject(obj)) throw new TypeError('serializeOverrides: expected a plain object')
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
-
404
- const sorted = {}
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`
413
- }
414
-
415
- /**
416
- * Should an override be written for this package?
417
- *
418
- * Only when the override is strictly newer than the shipped pin. Equal means
419
- * the product has caught up (the pin now does the job), older means the
420
- * override would downgrade, and an unparsable version cannot be judged at
421
- * all. In all three cases writing would either be useless or harmful.
422
- *
423
- * This is the single verdict both writers and readers share: provisioning
424
- * must ignore an override under exactly the same conditions, or the upgrade
425
- * command writes pins that the next start silently rejects (or honours when
426
- * it should not).
427
- *
428
- * @param {{ overrideVersion?: string, shippedPin?: string }} input
429
- * @returns {boolean}
430
- */
431
- export function shouldWriteOverride({ overrideVersion, shippedPin } = {}) {
432
- if (!parseVersion(overrideVersion) || !parseVersion(shippedPin)) return false
433
- return compareVersions(overrideVersion, shippedPin) > 0
434
- }
435
-
436
- /**
437
- * Which version provisioning should require for one plugin.
438
- *
439
- * DELEGATES the decision to provision-plan's `resolveEffectivePin`: that
440
- * function is the single authority, and a second copy here would be free to
441
- * drift and let the upgrade command write pins the next start ignores. This
442
- * wrapper only keeps the richer `{ pin, overridden, ignoredReason }` shape the
443
- * command logs, by classifying *why* a present entry did not win.
444
- *
445
- * `overrides` is the parsed document ({ version, packages }) or the inner
446
- * name -> entry map that a reader returns; both are accepted. Behaviour (all
447
- * inherited from resolveEffectivePin):
448
- * - name absent -> shipped pin, overridden: false
449
- * - override equal to / older than pin -> shipped pin, ignoredReason 'stale'
450
- * - override or entry shape invalid -> shipped pin, ignoredReason 'invalid'
451
- * - name outside PLUGIN_SET (allowlist) -> shipped pin, ignoredReason 'unmanaged'
452
- * - otherwise -> override version, overridden: true
453
- *
454
- * `ignoredReason` is only present when an override existed and was ignored;
455
- * `pin` is always safe to use. 'unmanaged' exists because the allowlist lives
456
- * in provision-plan: an otherwise valid, newer entry for a package the
457
- * launcher does not manage can never take effect, and that is worth saying
458
- * instead of mislabelling it 'stale'.
459
- *
460
- * @param {{
461
- * name: string,
462
- * shippedPin: string,
463
- * overrides?: { version?: number, packages?: Record<string, string|{version?: string}> } | Record<string, string|{version?: string}> | null,
464
- * }} input
465
- * @returns {{ pin: string, overridden: boolean, ignoredReason?: 'stale'|'invalid'|'unmanaged' }}
466
- */
467
- export function pickEffectivePin({ name, shippedPin, overrides } = {}) {
468
- const packages = overridePackageMap(overrides)
469
- const pin = resolveEffectivePin({ name, shippedPin, overrides: packages })
470
- if (pin !== shippedPin) return { pin, overridden: true }
471
-
472
- // The entry exists but provisioning did not honour it — say why.
473
- if (!Object.prototype.hasOwnProperty.call(packages, name)) {
474
- return { pin, overridden: false }
475
- }
476
- const entry = packages[name]
477
- // resolveEffectivePin requires the object form; a bare string (and any
478
- // entry without a version string) is unusable to it, whatever this
479
- // module's own reader tolerates.
480
- const overrideVersion =
481
- isPlainObject(entry) && typeof entry.version === 'string' ? entry.version.trim() : ''
482
- if (overrideVersion === '' || !parseVersion(overrideVersion) || !parseVersion(shippedPin)) {
483
- return { pin, overridden: false, ignoredReason: 'invalid' }
484
- }
485
- if (compareVersions(overrideVersion, shippedPin) <= 0) {
486
- return { pin, overridden: false, ignoredReason: 'stale' }
487
- }
488
- return { pin, overridden: false, ignoredReason: 'unmanaged' }
489
- }