@sixzjd/dsh-workbuddy-connect 0.3.0 → 0.3.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/lib/updates.js DELETED
@@ -1,325 +0,0 @@
1
- /**
2
- * Whether this checkout is behind its git remote, and how it got installed.
3
- *
4
- * The harness only offers an "Update" button for the *official* on-demand
5
- * catalog: `updateAvailable()` requires a `pkg.installTarget`, and the plugin
6
- * manager computes one exclusively from `OFFICIAL_ON_DEMAND_CATALOG`. A
7
- * community bundle installed from `github:…` therefore has no `installTarget`
8
- * and never shows the button, however far behind it is.
9
- *
10
- * This module answers the two questions the card needs to stand in for that
11
- * missing button: *what am I pinned to* (read from the profile manifest and the
12
- * pnpm lockfile, never from network state) and *what does the remote say now*
13
- * (`git ls-remote`, the cheapest call that names a commit without cloning).
14
- *
15
- * It deliberately never writes anything. Installing is the plugin manager's
16
- * job — it owns the profile lock, the pnpm invocation and the reload lifecycle
17
- * — so this only produces a report for the card to act on.
18
- *
19
- * @module dsh-workbuddy-connect/updates
20
- */
21
- import { execFile } from 'node:child_process'
22
- import { readFileSync } from 'node:fs'
23
- import { join } from 'node:path'
24
- import { promisify } from 'node:util'
25
-
26
- const run = promisify(execFile)
27
-
28
- /** The package this repository publishes; the manifest key and the git repo share the name. */
29
- export const PACKAGE_NAME = '@sixzjd/dsh-workbuddy-connect'
30
-
31
- /**
32
- * Names this package may still appear under in an existing profile.
33
- *
34
- * Only affects *reading*: both the manifest lookup and the lockfile scan accept
35
- * any of these, so a profile installed before the rename still reports its real
36
- * commit instead of "unknown".
37
- */
38
- export const LEGACY_PACKAGE_NAMES = ['dsh-workbuddy-connect']
39
-
40
- /** How long a `git ls-remote` may take before the card reports "unknown". */
41
- export const LS_REMOTE_TIMEOUT_MS = 15_000
42
-
43
- /**
44
- * The branch an unpinned `github:` spec resolves to.
45
- *
46
- * pnpm resolves a bare git spec to the remote's HEAD, which for every
47
- * repository this plugin has ever been installed from is `main`.
48
- */
49
- const DEFAULT_BRANCH = 'main'
50
-
51
- /**
52
- * Parse a dependency spec into what the update check needs.
53
- *
54
- * Understands the three shapes a git-hosted bundle can be installed as, and
55
- * reports `local` for anything else (`file:`, `link:`, a registry range) so the
56
- * card can say "this copy cannot be updated from here" rather than offering a
57
- * button that would install something else over it.
58
- *
59
- * @param {string} spec The `dependencies[PACKAGE_NAME]` value.
60
- * @returns {{kind: 'git', url: string, ref?: string} | {kind: 'local'}}
61
- */
62
- export function parseInstallSpec(spec) {
63
- if (typeof spec !== 'string') return { kind: 'local' }
64
- const trimmed = spec.trim()
65
- // `github:owner/repo`, `gitlab:…`, `bitbucket:…` — pnpm's host shorthands.
66
- const shorthand = /^(github|gitlab|bitbucket|gist):([^#]+)(?:#(.*))?$/i.exec(trimmed)
67
- if (shorthand !== null) {
68
- const host = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org', gist: 'gist.github.com' }[shorthand[1].toLowerCase()]
69
- const repo = shorthand[2].replace(/^\/+/, '')
70
- return withRef(`https://${host}/${repo}.git`, shorthand[3])
71
- }
72
- // `git+https://…`, `git+ssh://…`, `git://…`
73
- const gitUrl = /^git\+(https?|ssh):\/\/(.+)$/i.exec(trimmed)
74
- if (gitUrl !== null) {
75
- const rest = gitUrl[2]
76
- const hash = rest.indexOf('#')
77
- const repo = hash === -1 ? rest : rest.slice(0, hash)
78
- const ref = hash === -1 ? undefined : rest.slice(hash + 1)
79
- return withRef(`${gitUrl[1].toLowerCase()}://${repo}`, ref)
80
- }
81
- // A plain HTTPS repository URL (no `.git` suffix required).
82
- const plain = /^(https?):\/\/([^#]+?)(?:#(.*))?$/i.exec(trimmed)
83
- if (plain !== null && /\.git$/i.test(plain[2])) return withRef(`${plain[1]}://${plain[2]}`, plain[3])
84
- return { kind: 'local' }
85
- }
86
-
87
- /** Attach a ref only when one was written; an empty `#` means "the default branch". */
88
- function withRef(url, ref) {
89
- return ref === undefined || ref.trim() === '' ? { kind: 'git', url } : { kind: 'git', url, ref: ref.trim() }
90
- }
91
-
92
- /**
93
- * The commit a spec pins, if it pins one.
94
- *
95
- * A full or abbreviated object id is a pin; a branch or tag name is not, because
96
- * the question the card answers is "did upstream move past what I have", which
97
- * only a commit id can be compared against.
98
- *
99
- * @param {string} installSpec
100
- * @returns {string|undefined}
101
- */
102
- export function pinnedCommit(installSpec) {
103
- const parsed = parseInstallSpec(installSpec)
104
- if (parsed.kind !== 'git' || parsed.ref === undefined) return undefined
105
- return /^[0-9a-f]{7,40}$/i.test(parsed.ref) ? parsed.ref.toLowerCase() : undefined
106
- }
107
-
108
- /**
109
- * The lines of one package's entry in a lockfile's importer block.
110
- *
111
- * Hand-rolled rather than a single regex because indentation is not fixed
112
- * (pnpm writes six spaces, a hand-edited lock has fewer) and because a regex
113
- * that misses the header has an obvious failure mode that is very hard to
114
- * notice: the search silently widens to the whole file and picks up a
115
- * *neighbouring* package's commit. That mistake reports another plugin's
116
- * version as this one's, which is exactly the kind of wrong answer a user
117
- * cannot sanity-check.
118
- *
119
- * The entry is the header line plus every following line that is indented
120
- * deeper than the header or blank.
121
- *
122
- * @param {string} lockText
123
- * @param {string} packageName
124
- * @returns {string} The entry's text, or '' when the package has no entry.
125
- */
126
- function importerBlockOf(lockText, packageName) {
127
- const lines = lockText.split('\n')
128
- for (let index = 0; index < lines.length; index += 1) {
129
- const line = lines[index]
130
- const header = /^([ \t]*)([^\s:#][^:]*):[ \t]*$/.exec(line)
131
- if (header === null || header[2].trim() !== packageName) continue
132
- const indent = header[1].length
133
- const collected = [line]
134
- for (let next = index + 1; next < lines.length; next += 1) {
135
- const candidate = lines[next]
136
- if (candidate.trim() === '') {
137
- collected.push(candidate)
138
- continue
139
- }
140
- const leading = /^[ \t]*/.exec(candidate)[0].length
141
- if (leading <= indent) break
142
- collected.push(candidate)
143
- }
144
- return collected.join('\n')
145
- }
146
- return ''
147
- }
148
-
149
- /**
150
- * The commit pnpm actually installed, as recorded in the lockfile.
151
- *
152
- * The manifest states the *request*, which can be a branch; the lockfile states
153
- * the *result*, which is always a resolved commit for a git dependency. Reading
154
- * the lockfile matters because `packages[].gitHead` is not written for git
155
- * dependencies, so this is the only on-disk record of what is running.
156
- *
157
- * @param {string} lockText The text of the profile's `pnpm-lock.yaml`.
158
- * @returns {string|undefined}
159
- */
160
- export function installedCommitFromLock(lockText) {
161
- if (typeof lockText !== 'string') return undefined
162
- // The importer block names the package, then `version:` carries the resolved
163
- // git URL ending in `#<commit>`. Both `git+https://…` and the codeload
164
- // `https://…/tar.gz/<commit>` form appear in the wild.
165
- let scope = ''
166
- for (const name of [PACKAGE_NAME, ...LEGACY_PACKAGE_NAMES]) {
167
- scope = importerBlockOf(lockText, name)
168
- if (scope !== '') break
169
- }
170
- const byHash = /version:\s*[^\s#]+#([0-9a-f]{7,40})\b/i.exec(scope)
171
- if (byHash !== null) return byHash[1].toLowerCase()
172
- const byPath = /version:\s*\S*?\/tar\.gz\/([0-9a-f]{7,40})\b/i.exec(scope)
173
- if (byPath !== null) return byPath[1].toLowerCase()
174
- return undefined
175
- }
176
-
177
- /**
178
- * Read what this profile has installed, without touching the network.
179
- *
180
- * @param {string} profileDir The profile directory.
181
- * @returns {{installSpec?: string, pinned?: string, installed?: string}}
182
- */
183
- export function readLocalState(profileDir) {
184
- let installSpec
185
- try {
186
- const manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'))
187
- for (const name of [PACKAGE_NAME, ...LEGACY_PACKAGE_NAMES]) {
188
- const value = manifest.dependencies?.[name] ?? manifest.devDependencies?.[name]
189
- if (typeof value === 'string') { installSpec = value; break }
190
- }
191
- } catch {}
192
- let installed
193
- try {
194
- installed = installedCommitFromLock(readFileSync(join(profileDir, 'pnpm-lock.yaml'), 'utf8'))
195
- } catch {}
196
- const pinned = installSpec === undefined ? undefined : pinnedCommit(installSpec)
197
- return {
198
- ...installSpec === undefined ? {} : { installSpec },
199
- ...pinned === undefined ? {} : { pinned },
200
- ...installed === undefined ? {} : { installed },
201
- }
202
- }
203
-
204
- /**
205
- * Ask the remote which commit its branch now names.
206
- *
207
- * @param {string} url The repository URL.
208
- * @param {string} [branch] Branch to resolve; the remote's default when omitted.
209
- * @param {{timeoutMs?: number, runner?: Function}} [options]
210
- * @returns {Promise<{sha: string} | {error: string}>}
211
- */
212
- export async function remoteHead(url, branch = DEFAULT_BRANCH, options = {}) {
213
- const runner = options.runner ?? run
214
- try {
215
- const { stdout } = await runner('git', ['ls-remote', url, `refs/heads/${branch}`], {
216
- timeout: options.timeoutMs ?? LS_REMOTE_TIMEOUT_MS,
217
- // A stalled remote must not hold the card open; `git` is also stopped by
218
- // its own timeout, but the signal makes the kill prompt.
219
- killSignal: 'SIGKILL',
220
- maxBuffer: 1024 * 1024,
221
- })
222
- const line = String(stdout).trim().split('\n')[0] ?? ''
223
- const sha = line.split('\t')[0]?.trim().toLowerCase()
224
- if (!/^[0-9a-f]{7,40}$/.test(sha ?? '')) return { error: 'the remote answered no commit for that branch' }
225
- return { sha }
226
- } catch (error) {
227
- const message = error?.killed || error?.signal !== undefined && error.signal !== null
228
- ? `git ls-remote timed out after ${options.timeoutMs ?? LS_REMOTE_TIMEOUT_MS}ms`
229
- : String(error?.stderr ?? error?.message ?? error)
230
- return { error: message.trim().split('\n').slice(0, 3).join(' ').slice(0, 300) }
231
- }
232
- }
233
-
234
- /**
235
- * The whole report: what is installed, what upstream has, and whether they differ.
236
- *
237
- * `state` is the card's whole input, and it is deliberately explicit about the
238
- * cases the button must stay disabled for:
239
- *
240
- * - `local-copy` — installed from a path; there is no remote to compare with.
241
- * - `unknown` — the remote could not be asked this time.
242
- * - `current` / `behind` — the two states the card acts on.
243
- *
244
- * @param {string} profileDir
245
- * @param {{branch?: string, timeoutMs?: number, runner?: Function}} [options]
246
- * @returns {Promise<object>}
247
- */
248
- export async function checkForUpdate(profileDir, options = {}) {
249
- const local = readLocalState(profileDir)
250
- if (local.installSpec === undefined) return { state: 'unknown', reason: 'the profile does not declare this plugin' }
251
- const parsed = parseInstallSpec(local.installSpec)
252
- if (parsed.kind !== 'git') {
253
- return {
254
- state: 'local-copy',
255
- reason: 'installed from a local path, so there is no remote to compare with',
256
- installSpec: local.installSpec,
257
- }
258
- }
259
- // A pin names the branch's future: compare against the branch it came from,
260
- // not the commit, or the remote would always answer "current".
261
- const branch = options.branch ?? DEFAULT_BRANCH
262
- const remote = await remoteHead(parsed.url, branch, options)
263
- if (remote.error !== undefined) {
264
- return {
265
- state: 'unknown',
266
- reason: remote.error,
267
- installSpec: local.installSpec,
268
- ...local.installed === undefined ? {} : { installed: local.installed },
269
- }
270
- }
271
- const installed = local.installed
272
- if (installed === undefined) {
273
- return { state: 'unknown', reason: 'the lockfile records no resolved commit for this package', remote: remote.sha, installSpec: local.installSpec, branch }
274
- }
275
- const behind = !sameCommit(installed, remote.sha)
276
- return {
277
- state: behind ? 'behind' : 'current',
278
- branch,
279
- installed,
280
- remote: remote.sha,
281
- installSpec: local.installSpec,
282
- // What a one-click update would install: the same repository, repinned to
283
- // the commit the remote names right now.
284
- ...behind ? { targetSpec: `${baseSpecOf(local.installSpec)}#${remote.sha}` } : {},
285
- }
286
- }
287
-
288
- /**
289
- * Whether two commit ids name the same commit.
290
- *
291
- * A lockfile can carry an abbreviated id where the manifest carried a full one,
292
- * so a prefix match counts — but only in that direction, and only for ids long
293
- * enough to be unambiguous.
294
- */
295
- export function sameCommit(a, b) {
296
- if (typeof a !== 'string' || typeof b !== 'string') return false
297
- const left = a.trim().toLowerCase()
298
- const right = b.trim().toLowerCase()
299
- if (left === '' || right === '') return false
300
- if (left === right) return true
301
- const [shorter, longer] = left.length <= right.length ? [left, right] : [right, left]
302
- return shorter.length >= 7 && longer.startsWith(shorter)
303
- }
304
-
305
- /** The spec with any ref removed, so a new commit can be appended. */
306
- export function baseSpecOf(installSpec) {
307
- const trimmed = String(installSpec).trim()
308
- const hash = trimmed.lastIndexOf('#')
309
- return hash === -1 ? trimmed : trimmed.slice(0, hash)
310
- }
311
-
312
- /**
313
- * The spec a one-click update should install.
314
- *
315
- * Repinning to a commit (rather than installing the branch) keeps the profile
316
- * reproducible and keeps the next update check meaningful: a branch spec would
317
- * leave `installed` and `remote` indistinguishable.
318
- *
319
- * @param {object} report A report from {@link checkForUpdate}.
320
- * @returns {string|undefined}
321
- */
322
- export function updateSpecFrom(report) {
323
- if (report?.state !== 'behind' || typeof report.remote !== 'string') return undefined
324
- return `${baseSpecOf(report.installSpec)}#${report.remote}`
325
- }