dsh-version-manager 0.0.0-stage → 0.1.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.
@@ -0,0 +1,231 @@
1
+ /**
2
+ * One row per thing that can have a version, built from facts that were read
3
+ * rather than inferred.
4
+ *
5
+ * The four questions a version manager has to keep apart are:
6
+ *
7
+ * - is it declared in the profile at all → `availability`
8
+ * - is the user's saved choice "on" → `enabled`
9
+ * - did it actually load in this process → `phase`
10
+ * - is it the version the profile declares → `installedVersion`
11
+ *
12
+ * Collapsing any two of them produces the classic wrong answer: "enabled" shown
13
+ * as "working", or "installed" shown as "loaded". Each field below is filled
14
+ * from exactly one source and carries its own reason when it is empty.
15
+ *
16
+ * @module dsh-version-manager/lib/host/inventory
17
+ */
18
+
19
+ import { classifySpec, isPrerelease, updateRefusal } from './spec.js'
20
+
21
+ /**
22
+ * The loader's fiber phase, as a stable name.
23
+ *
24
+ * Copied deliberately from the shape `dsh-host-plugin-inventory` uses, so two
25
+ * panels in the same host cannot disagree about what "failed" means.
26
+ */
27
+ const FIBER_PHASE = Object.freeze({
28
+ 0: 'pending',
29
+ 1: 'loading',
30
+ 2: 'active',
31
+ 3: 'failed',
32
+ 4: 'null',
33
+ 5: 'unloading',
34
+ })
35
+
36
+ /**
37
+ * Map a numeric fiber phase onto a name.
38
+ *
39
+ * @param {number | undefined} state
40
+ * @returns {string | null}
41
+ */
42
+ export function phaseName(state) {
43
+ if (typeof state !== 'number') return null
44
+ return FIBER_PHASE[state] ?? 'unknown'
45
+ }
46
+
47
+ /**
48
+ * Read the entry phases out of the loader without assuming the loader exists.
49
+ *
50
+ * The loader keys entries by module name. A bundle can be composed into several
51
+ * rows, so the map is name → list of phases and the inventory reports the worst
52
+ * one: a bundle with one active row and one failed row is not healthy.
53
+ *
54
+ * @param {{ loader?: { entries?: () => Iterable<any> } } | undefined} ctx
55
+ * @returns {Promise<{ byName: Map<string, string[]>, available: boolean }>}
56
+ */
57
+ export async function readLoaderPhases(ctx) {
58
+ const byName = new Map()
59
+ const loader = ctx?.loader
60
+ if (loader === undefined || loader === null || typeof loader.entries !== 'function') {
61
+ return { byName, available: false }
62
+ }
63
+
64
+ let entries
65
+ try {
66
+ entries = Array.from(loader.entries())
67
+ } catch {
68
+ return { byName, available: false }
69
+ }
70
+
71
+ const pending = []
72
+ for (const entry of entries) {
73
+ // Group rows are containers, not plugins: they carry no fiber of their own.
74
+ if (entry?.options?.group !== undefined) continue
75
+ const name = entry?.options?.name
76
+ if (typeof name !== 'string') continue
77
+ const phase = phaseName(entry?.fiber?.state)
78
+ if (phase === null) continue
79
+ const list = byName.get(name)
80
+ if (list === undefined) byName.set(name, [phase])
81
+ else list.push(phase)
82
+
83
+ if (phase === 'failed' && typeof entry.fiber?.await === 'function') {
84
+ pending.push(
85
+ entry.fiber
86
+ .await()
87
+ .then(() => null)
88
+ .catch((error) => describeFailure(error)),
89
+ )
90
+ }
91
+ }
92
+
93
+ const diagnostics = await Promise.all(pending)
94
+ const first = diagnostics.find((value) => value !== null) ?? null
95
+ return { byName, available: true, diagnostic: first }
96
+ }
97
+
98
+ /**
99
+ * Turn a rejected fiber into a short, non-secret sentence.
100
+ *
101
+ * Loader errors can embed absolute paths and sometimes a stack. The panel shows
102
+ * this in the section that is allowed to contain local paths, so it is passed
103
+ * through, but the trailing stack is dropped: a stack is noise to a user and a
104
+ * second place for a path to leak into a copyable report.
105
+ *
106
+ * @param {unknown} error
107
+ * @returns {string}
108
+ */
109
+ function describeFailure(error) {
110
+ if (error === null || error === undefined) return 'The plugin failed to load.'
111
+ const message = error instanceof Error ? error.message : String(error)
112
+ const newline = message.indexOf('\n')
113
+ return newline === -1 ? message : message.slice(0, newline)
114
+ }
115
+
116
+ /**
117
+ * The worst phase in a list, in the order a user cares about.
118
+ *
119
+ * @param {string[] | undefined} phases
120
+ * @returns {string | null}
121
+ */
122
+ export function worstPhase(phases) {
123
+ if (phases === undefined || phases.length === 0) return null
124
+ const rank = { failed: 0, unloading: 1, pending: 2, loading: 3, unknown: 4, active: 5 }
125
+ return [...phases].sort((a, b) => (rank[a] ?? 9) - (rank[b] ?? 9))[0]
126
+ }
127
+
128
+ /**
129
+ * Why a row has no load phase, when it has none.
130
+ *
131
+ * Three different situations produce an empty `loadState` and they must not be
132
+ * reported as one: the loader is unreadable in this process, the loader is
133
+ * readable but tracks no entry under this name (bundles are applied as patches,
134
+ * so their name need not appear), or the row simply has no fiber.
135
+ *
136
+ * @param {boolean} phaseAvailable
137
+ * @param {string[] | undefined} phases
138
+ * @returns {string | null}
139
+ */
140
+ function loadStateReason(phaseAvailable, phases) {
141
+ if (phaseAvailable !== true) return 'loader-unavailable'
142
+ if (phases === undefined || phases.length === 0) return 'no-loader-entry'
143
+ return null
144
+ }
145
+
146
+ /**
147
+ * Build the plugin half of the inventory.
148
+ *
149
+ * @param {object} input
150
+ * @param {object[]} input.bundles - rows from pluginManager.listBundles()
151
+ * @param {Map<string, string[]>} input.phases
152
+ * @param {boolean} input.phaseAvailable
153
+ * @param {string | undefined} input.phaseDiagnostic
154
+ * @param {string} input.profileId
155
+ * @param {string | undefined} input.runtimeVersion
156
+ * @returns {object[]}
157
+ */
158
+ export function buildPluginRows(input) {
159
+ const { bundles, phases, phaseAvailable, phaseDiagnostic, profileId, runtimeVersion } = input
160
+ const observedAt = new Date().toISOString()
161
+
162
+ return bundles.map((row) => {
163
+ const parsed = classifySpec(row.source, { official: row.official })
164
+ const refusal = updateRefusal(row, parsed)
165
+ const rowPhases = phases.get(row.name)
166
+ const phase = phaseAvailable ? worstPhase(rowPhases) : null
167
+
168
+ return {
169
+ profileId,
170
+ kind: 'plugin',
171
+ targetId: row.name,
172
+ declaredSpec: typeof row.source === 'string' ? row.source : null,
173
+ installedVersion: typeof row.version === 'string' ? row.version : null,
174
+ source: {
175
+ kind: parsed.kind,
176
+ // The detail is a path, a URL or a package name. It is shown in the
177
+ // local view and stripped from a shared report.
178
+ detail: parsed.detail,
179
+ registryName: parsed.name,
180
+ registryRange: parsed.range,
181
+ },
182
+ enabledState: row.enabled === true ? 'enabled' : row.enabled === false ? 'disabled' : 'unknown',
183
+ loadState: phase,
184
+ loadStateAvailable: phaseAvailable,
185
+ // Why a phase is missing is itself a fact worth keeping apart from "the
186
+ // loader could not be read": a bundle is a composition, and the loader
187
+ // tracks the plugin entries inside it rather than the bundle name, so an
188
+ // unknown phase for a bundle is expected rather than a failure.
189
+ loadStateReason: loadStateReason(phaseAvailable, rowPhases),
190
+ loadError: phase === 'failed' ? (phaseDiagnostic ?? row.error ?? null) : (row.error ?? null),
191
+ // Filled in by the caller from the installed manifest. Left `unknown`
192
+ // here on purpose: a row without a manifest is not a passing row.
193
+ compatibility: {
194
+ verdict: 'unknown',
195
+ requirements: [],
196
+ unmet: [],
197
+ runtimeVersion: runtimeVersion ?? null,
198
+ reason: 'The installed package manifest has not been read yet.',
199
+ detail: typeof row.error === 'string' ? row.error : null,
200
+ },
201
+ // "Writable" is the only claim this row supports: the host would accept an
202
+ // update for it. Whether a newer version actually exists is a different
203
+ // question, answered per target by the version check and never assumed.
204
+ recoverability: refusal === null ? 'writable' : 'read_only',
205
+ updateRefusal: refusal,
206
+ official: row.official === true,
207
+ availability: row.availability ?? 'unknown',
208
+ prerelease: isPrerelease(row.version),
209
+ observedAt,
210
+ }
211
+ })
212
+ }
213
+
214
+ /**
215
+ * Read the declared specs out of a profile `package.json`.
216
+ *
217
+ * @param {unknown} manifest
218
+ * @returns {{ dependencies: Record<string, string>, bundles: string[] }}
219
+ */
220
+ export function readProfileManifest(manifest) {
221
+ const dependencies = {}
222
+ const raw = manifest?.dependencies
223
+ if (raw !== null && typeof raw === 'object') {
224
+ for (const [name, spec] of Object.entries(raw)) {
225
+ if (typeof spec === 'string') dependencies[name] = spec
226
+ }
227
+ }
228
+ const selected = manifest?.dsh?.profile?.bundles
229
+ const bundles = Array.isArray(selected) ? selected.filter((name) => typeof name === 'string') : []
230
+ return { dependencies, bundles }
231
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Where the running DSH actually lives.
3
+ *
4
+ * The host that loads this plugin does not hand it a directory, and a profile
5
+ * directory holds third-party bundles only — the `@deepseek-ai/*` packages that
6
+ * make up DSH itself sit next to the process that started it. The version the
7
+ * host compares plugin manifests against is the version of
8
+ * `@deepseek-ai/dsh-app-boot`'s own package, so that is what we look for.
9
+ *
10
+ * Nothing here is required for the plugin to work: every function returns
11
+ * `null` rather than throwing, and callers turn `null` into "unknown".
12
+ *
13
+ * @module dsh-version-manager/lib/host/locate
14
+ */
15
+
16
+ import { readFileSync, statSync } from 'node:fs'
17
+ import { dirname, join, parse, resolve } from 'node:path'
18
+ import { createRequire } from 'node:module'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ /** The package whose own version the host uses as the runtime version. */
22
+ export const APP_BOOT_PACKAGE = '@deepseek-ai/dsh-app-boot'
23
+
24
+ /** How far up from a starting directory to look for the host's node_modules. */
25
+ const MAX_WALK = 12
26
+
27
+ /**
28
+ * @param {string} path
29
+ * @returns {string | null}
30
+ */
31
+ function readJson(path) {
32
+ try {
33
+ return JSON.parse(readFileSync(path, 'utf8'))
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ /**
40
+ * @param {string} path
41
+ * @returns {boolean}
42
+ */
43
+ function isDirectory(path) {
44
+ try {
45
+ return statSync(path).isDirectory()
46
+ } catch {
47
+ return false
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Candidate directories that may sit beside DSH's own `node_modules`.
53
+ *
54
+ * Two sources are tried, in order of how directly they describe the running
55
+ * host: the script the host was started from, then this module's own location
56
+ * (which is inside the host tree when the plugin was installed with it, and
57
+ * inside a profile when it was not).
58
+ *
59
+ * @returns {string[]}
60
+ */
61
+ function candidateRoots() {
62
+ const roots = []
63
+ const argv1 = process.argv[1]
64
+ if (typeof argv1 === 'string' && argv1 !== '') {
65
+ try {
66
+ roots.push(dirname(resolve(argv1)))
67
+ } catch {
68
+ // An unreadable argv is only a missing hint.
69
+ }
70
+ }
71
+ try {
72
+ roots.push(dirname(fileURLToPath(import.meta.url)))
73
+ } catch {
74
+ // A non-file module URL simply yields no hint.
75
+ }
76
+ const execPath = process.execPath
77
+ if (typeof execPath === 'string' && execPath !== '') {
78
+ roots.push(dirname(execPath))
79
+ }
80
+ return roots
81
+ }
82
+
83
+ /**
84
+ * Walk up from each candidate looking for a directory that contains
85
+ * `node_modules/@deepseek-ai`.
86
+ *
87
+ * @returns {string | null} the directory that owns the `node_modules`
88
+ */
89
+ export function findHostRoot() {
90
+ for (const start of candidateRoots()) {
91
+ let current = start
92
+ for (let step = 0; step < MAX_WALK; step += 1) {
93
+ if (isDirectory(join(current, 'node_modules', '@deepseek-ai'))) return current
94
+ const parent = dirname(current)
95
+ if (parent === current || parent === parse(current).root) break
96
+ current = parent
97
+ }
98
+ }
99
+ return null
100
+ }
101
+
102
+ /**
103
+ * Resolve a package manifest through the module resolver as a fallback.
104
+ *
105
+ * @param {string} name
106
+ * @returns {any}
107
+ */
108
+ function resolveManifest(name) {
109
+ try {
110
+ const require = createRequire(import.meta.url)
111
+ return readJson(require.resolve(`${name}/package.json`))
112
+ } catch {
113
+ return null
114
+ }
115
+ }
116
+
117
+ let cachedHost = null
118
+
119
+ /**
120
+ * The host's own location and version, discovered once.
121
+ *
122
+ * @returns {{ root: string | null, runtimeVersion: string | null, source: string | null }}
123
+ */
124
+ export function hostInfo() {
125
+ if (cachedHost !== null) return cachedHost
126
+
127
+ const root = findHostRoot()
128
+ if (root !== null) {
129
+ const manifest = readJson(join(root, 'node_modules', APP_BOOT_PACKAGE, 'package.json'))
130
+ if (manifest !== null && typeof manifest.version === 'string') {
131
+ cachedHost = { root, runtimeVersion: manifest.version, source: `${APP_BOOT_PACKAGE}/package.json` }
132
+ return cachedHost
133
+ }
134
+ }
135
+
136
+ const resolved = resolveManifest(APP_BOOT_PACKAGE)
137
+ if (resolved !== null && typeof resolved.version === 'string') {
138
+ cachedHost = { root, runtimeVersion: resolved.version, source: 'module resolution' }
139
+ return cachedHost
140
+ }
141
+
142
+ cachedHost = { root, runtimeVersion: null, source: null }
143
+ return cachedHost
144
+ }
145
+
146
+ /**
147
+ * Read an installed package manifest from the two places a bundle can live.
148
+ *
149
+ * @param {string} name
150
+ * @param {{ profileDir?: string | null, hostRoot?: string | null }} where
151
+ * @returns {any}
152
+ */
153
+ export function readInstalledManifest(name, where) {
154
+ const { profileDir, hostRoot } = where
155
+ if (typeof name !== 'string' || name === '') return null
156
+ for (const base of [profileDir, hostRoot]) {
157
+ if (typeof base !== 'string' || base === '') continue
158
+ const manifest = readJson(join(base, 'node_modules', name, 'package.json'))
159
+ if (manifest !== null) return manifest
160
+ }
161
+ return resolveManifest(name)
162
+ }
163
+
164
+ /**
165
+ * Forget the cached host. Only tests need this.
166
+ */
167
+ export function resetHostCache() {
168
+ cachedHost = null
169
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * A deliberately small reader for the facts a pnpm lockfile does record.
3
+ *
4
+ * A full YAML parser is not worth carrying here: the panel needs one field, and
5
+ * pnpm lockfiles are written in a shape where a targeted line scan is both
6
+ * simpler and easier to reason about than a general parser. Everything this
7
+ * module cannot find is reported as absent, never guessed.
8
+ *
9
+ * What pnpm v9 actually records:
10
+ *
11
+ * - `importers.<id>.dependencies.<name>.version` — the resolved version (or the
12
+ * `file:`/`link:` target) for a profile dependency.
13
+ * - `packages.<name>@<version>.resolution.tarball` — only for installs that did
14
+ * not come from the default registry.
15
+ *
16
+ * So for an ordinary npm install the registry host is genuinely unrecorded. The
17
+ * panel says "unknown" there rather than assuming npmjs, because a bundle the
18
+ * user pinned to a mirror must not be described as coming from npm.
19
+ *
20
+ * @module dsh-version-manager/lib/host/lockfile
21
+ */
22
+
23
+ /**
24
+ * Extract the `resolution.tarball` recorded for one package, if any.
25
+ *
26
+ * @param {unknown} text
27
+ * @param {string} name
28
+ * @returns {string | null}
29
+ */
30
+ export function lockfileTarball(text, name) {
31
+ if (typeof text !== 'string' || text === '') return null
32
+ if (typeof name !== 'string' || name === '') return null
33
+
34
+ const lines = text.split(/\r?\n/)
35
+ // Package keys live in the `packages:` block, indented by two spaces, and end
36
+ // with a colon. The block ends at the next top-level key.
37
+ let inPackages = false
38
+ let currentIsTarget = false
39
+
40
+ for (const line of lines) {
41
+ if (/^[A-Za-z]/.test(line)) {
42
+ inPackages = line.startsWith('packages:')
43
+ currentIsTarget = false
44
+ continue
45
+ }
46
+ if (!inPackages) continue
47
+
48
+ const keyMatch = /^ {2}(\S.*):\s*$/.exec(line)
49
+ if (keyMatch !== null) {
50
+ const key = keyMatch[1].replace(/^['"]|['"]$/g, '')
51
+ // `dsh-version-manager@file:...` and `@scope/name@1.2.3` both name the
52
+ // package before the last `@`.
53
+ const at = key.lastIndexOf('@')
54
+ const keyName = at > 0 ? key.slice(0, at) : key
55
+ currentIsTarget = keyName === name
56
+ continue
57
+ }
58
+ if (!currentIsTarget) continue
59
+
60
+ const tarballMatch = /\btarball:\s*['"]?([^,'"\s}]+)['"]?/.exec(line)
61
+ if (tarballMatch !== null) return tarballMatch[1]
62
+ }
63
+ return null
64
+ }
65
+
66
+ /**
67
+ * The registry identity of a tarball URL: scheme, host, and trailing slash.
68
+ *
69
+ * @param {unknown} tarball
70
+ * @returns {string | null}
71
+ */
72
+ export function registryOfTarball(tarball) {
73
+ if (typeof tarball !== 'string' || tarball === '') return null
74
+ try {
75
+ const url = new URL(tarball)
76
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
77
+ return `${url.protocol}//${url.host}/`
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Resolve one package's registry, with a reason when it cannot be known.
85
+ *
86
+ * @param {object} input
87
+ * @param {string} input.name
88
+ * @param {string | null} input.lockText
89
+ * @param {string | null} input.declaredSpec
90
+ * @param {boolean} input.lockfileReadable
91
+ * @returns {{ registry: string | null, reason: string | null }}
92
+ */
93
+ export function registryFor(input) {
94
+ const { name, lockText, declaredSpec, lockfileReadable } = input
95
+
96
+ const tarball = lockfileTarball(lockText, name)
97
+ if (tarball !== null) {
98
+ const registry = registryOfTarball(tarball)
99
+ if (registry !== null) return { registry, reason: null }
100
+ }
101
+
102
+ if (typeof declaredSpec === 'string') {
103
+ // An explicit `--registry` install ends up in the lockfile as an https
104
+ // tarball, which the branch above already handled. Anything left is either
105
+ // a default-registry install (host unrecorded) or a non-registry source.
106
+ if (/^(file|link|workspace|portal):/i.test(declaredSpec)) {
107
+ return { registry: null, reason: 'Installed from a local path, not a registry.' }
108
+ }
109
+ if (/^(git|github|gitlab|bitbucket|gist)[:+]|^git@|^https?:\/\/[^/]+\/[^/]+\/[^/#]+(?:\.git)?/i.test(declaredSpec)) {
110
+ return { registry: null, reason: 'Installed from Git, not a registry.' }
111
+ }
112
+ if (/\.(?:tgz|tar\.gz)(?:#.*)?$/i.test(declaredSpec)) {
113
+ return { registry: null, reason: 'Installed from a tarball, not a registry.' }
114
+ }
115
+ }
116
+
117
+ if (lockfileReadable !== true) {
118
+ return { registry: null, reason: 'No lockfile was readable for this profile.' }
119
+ }
120
+ return {
121
+ registry: null,
122
+ reason: 'The lockfile records no tarball URL, so the registry host is not stored for this package.',
123
+ }
124
+ }