@sixzjd/dsh-workbuddy-connect 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -73,16 +73,7 @@ window.__ModuleLoader__.load({
73
73
  signedOutHint: "登录后才会出现模型分组。",
74
74
  sessionStale: "上游拒绝了这份凭据:桌面 App 换过会话了。点「从桌面 App 导入」重新接入,或重新登录。",
75
75
  updateTitle: "插件更新",
76
- updateCheck: "检查更新",
77
- updateChecking: "检查中…",
78
- updateAvailable: "有新版本",
79
- updateCurrent: "已是最新",
80
- updateApply: "更新到此版本",
81
- updateRunning: "正在更新…",
82
- updateLocalCopy: "这个安装来自本地目录,没有可比较的远程仓库。",
83
- updateUnknown: "暂时查不到远程状态:",
84
76
  updateHint: "git 版本可以在这里一键检查并更新到上游最新提交;DSH 自己只给官方插件显示「更新」。",
85
- updateDone: "已更新,重启 App 后生效。",
86
77
  accountRestricted: "上游已限制这个账号(不是凭据问题,重新登录或重新导入都无效)。只有申诉才能解除:在 WorkBuddy 里提交反馈。",
87
78
  tabGlobal: "国际版",
88
79
  tabCN: "国内版",
@@ -135,16 +126,7 @@ window.__ModuleLoader__.load({
135
126
  signedOutHint: "The model group appears after you sign in.",
136
127
  sessionStale: "The upstream refused this credential — the desktop app rotated its session. Press “Import from the desktop app” again, or sign in once more.",
137
128
  updateTitle: "Plugin update",
138
- updateCheck: "Check for updates",
139
- updateChecking: "Checking…",
140
- updateAvailable: "Update available",
141
- updateCurrent: "Up to date",
142
- updateApply: "Update to this commit",
143
- updateRunning: "Updating…",
144
- updateLocalCopy: "This install comes from a local path, so there is no remote to compare with.",
145
- updateUnknown: "Cannot read the remote right now: ",
146
129
  updateHint: "For a git install this checks upstream and updates to its latest commit in one click; DSH itself only shows Update for official plugins.",
147
- updateDone: "Updated. Restart the app to load it.",
148
130
  accountRestricted: "The upstream has restricted this account — this is not a credential problem, so signing in or importing again will not help. Only an appeal lifts it: submit feedback in WorkBuddy.",
149
131
  tabGlobal: "Global",
150
132
  tabCN: "China",
@@ -543,147 +525,7 @@ window.__ModuleLoader__.load({
543
525
  /** Names an existing profile may still declare from before the rename. */
544
526
  const LEGACY_PACKAGE_NAMES = ["dsh-workbuddy-connect"];
545
527
 
546
- /**
547
- * The per-process control key for the update route.
548
- *
549
- * Read from the status document, the same place `authKey` and `modelsKey`
550
- * come from, and cached for the page's lifetime: it is minted once per host
551
- * process, and a failed read is retried rather than remembered as "no key"
552
- * (which would render as a permanent 403).
553
- */
554
- let updateKeyPromise;
555
- function updateKeyOf() {
556
- updateKeyPromise ??= fetch(STATUS_PATH)
557
- .then((res) => (res.ok ? res.json() : undefined))
558
- .then((doc) => {
559
- const key = doc?.updateKey;
560
- return typeof key === "string" && key !== "" ? key : undefined;
561
- })
562
- .catch(() => {
563
- updateKeyPromise = undefined;
564
- return undefined;
565
- });
566
- return updateKeyPromise;
567
- }
568
-
569
- /**
570
- * The contribution to the plugin page's own detail actions.
571
- *
572
- * DSH offers an "Update" button only for the official on-demand catalog —
573
- * `updateAvailable()` in the plugin page requires an `installTarget`, and
574
- * the manager derives that from `OFFICIAL_ON_DEMAND_CATALOG` alone, so a
575
- * community bundle installed from `github:…` never gets one however far
576
- * behind it is. The page does declare `plugins.detail.actions` for exactly
577
- * this situation, so this card supplies the missing button for its own
578
- * package and nothing else.
579
- *
580
- * Installing stays the manager's job: `ctx.remote.pluginManager` owns the
581
- * profile lock, the pnpm run and the reload lifecycle, so this never writes
582
- * to the profile itself.
583
- */
584
- function UpdateActions({ subject, L, manager }) {
585
- const pkg = subject?.kind === "bundle" ? subject.pkg : undefined
586
- const mine = (pkg?.name === PACKAGE_NAME || LEGACY_PACKAGE_NAMES.includes(pkg?.name)) && pkg?.installed === true;
587
- const [report, setReport] = React.useState(null);
588
- const [busy, setBusy] = React.useState(false);
589
- const [message, setMessage] = React.useState(null);
590
- const alive = React.useRef(true);
591
- React.useEffect(() => () => { alive.current = false; }, []);
592
-
593
- const check = React.useCallback(async (force) => {
594
- setBusy(true);
595
- setMessage(null);
596
- try {
597
- // The route is guarded like every other card route, and the key
598
- // arrives with the status document the card already fetches — so it
599
- // is read here rather than assumed absent (this component does not
600
- // receive the settings card's `status` prop).
601
- const key = await updateKeyOf();
602
- const res = await fetch(`${UPDATE_PATH}${force ? "?refresh=1" : ""}`, {
603
- headers: key === undefined ? {} : { "x-dsh-workbuddy-connect-key": key },
604
- });
605
- if (!res.ok) throw new Error(String(res.status));
606
- const doc = await res.json();
607
- if (alive.current) setReport(doc);
608
- } catch (error) {
609
- if (alive.current) setReport({ state: "unknown", reason: String(error?.message ?? error) });
610
- } finally {
611
- if (alive.current) setBusy(false);
612
- }
613
- }, []);
614
-
615
- // Only the package's own page pays for a network round trip, and only
616
- // once: the host caches the answer for six hours anyway.
617
- React.useEffect(() => {
618
- if (mine && report === null && !busy) void check(false);
619
- }, [mine, report, busy, check]);
620
-
621
- const apply = React.useCallback(async () => {
622
- if (report?.targetSpec === undefined) return;
623
- setBusy(true);
624
- setMessage(null);
625
- try {
626
- await reinstallThroughManager(manager, report.targetSpec);
627
- if (alive.current) setMessage(L.updateDone);
628
- } catch (error) {
629
- if (alive.current) setMessage(String(error?.message ?? error));
630
- } finally {
631
- if (alive.current) setBusy(false);
632
- }
633
- }, [report, manager, L]);
634
-
635
- // Nothing to say on another package's page.
636
- if (!mine) return null;
637
-
638
- const state = report?.state;
639
- // The page's own Update control is `Button variant="outline" size="sm"`
640
- // with the refresh glyph; an available version is offered as `primary`.
641
- // Matching both keeps this action reading as part of the page.
642
- const behind = state === "behind";
643
- return h("span", { className: "wb-update-action" },
644
- h(Button, {
645
- variant: behind ? "primary" : "outline",
646
- size: "sm",
647
- icon: h(IconRefreshOutlineRegular, { size: 13 }),
648
- disabled: busy,
649
- title: behind ? (report.targetSpec ?? undefined) : undefined,
650
- "aria-label": behind ? L.updateApply : L.updateCheck,
651
- onClick: () => void (behind ? apply() : check(true)),
652
- }, busy ? (behind ? L.updateRunning : L.updateChecking) : (behind ? L.updateApply : L.updateCheck)),
653
- // The badge carries the same meaning the page's own "Update available"
654
- // tag does, so it is rendered as text beside the action rather than as
655
- // a second control.
656
- behind ? h("span", { className: "wb-update-note wb-update-note-info" }, L.updateAvailable) : null,
657
- state === "current" ? h("span", { className: "wb-update-note" }, L.updateCurrent) : null,
658
- message !== null ? h("span", { className: "wb-update-note" }, message) : null,
659
- state === "local-copy" ? h("span", { className: "wb-update-note" }, L.updateLocalCopy) : null,
660
- state === "unknown" ? h("span", { className: "wb-update-note" }, `${L.updateUnknown}${report.reason ?? ""}`) : null,
661
- );
662
- }
663
-
664
- /**
665
- * Reinstall this package at `spec` through the plugin manager.
666
- *
667
- * `installBundle` refuses a package that is already present
668
- * (`already-installed`), so an update is a removal followed by an install
669
- * pinned to the commit the check resolved — the same pair the page's own
670
- * official Update button performs, on the same remote service. Doing it
671
- * here rather than in the host half is deliberate: the manager owns the
672
- * profile lock, the pnpm run and the reload lifecycle, and reaching it over
673
- * the remote keeps that ownership in one place.
674
- */
675
- async function reinstallThroughManager(manager, spec) {
676
- if (manager === undefined) throw new Error("the plugin manager service is unavailable");
677
- const removed = await manager.removeBundle(PACKAGE_NAME);
678
- if (removed?.ok !== true) throw new Error(removed?.error?.message ?? "the manager refused to remove the package");
679
- const installed = await manager.installBundle(spec, {});
680
- if (installed?.ok !== true) throw new Error(installed?.error?.message ?? "the manager refused to install the package");
681
- }
682
-
683
- // `remote.pluginManager` is the service the plugin page itself injects; a
684
- // card that wants the page's own Update behaviour has to ask for the same
685
- // namespace rather than reaching for a global.
686
- const inject = ["slots", "remote.pluginManager"]
528
+ const inject = ["slots"]
687
529
 
688
530
  function apply(ctx) {
689
531
  try {
@@ -742,23 +584,6 @@ window.__ModuleLoader__.load({
742
584
  note("section-inject", error)
743
585
  }
744
586
  })
745
- // The plugin page's per-package action row. Registered separately and
746
- // defensively: a host without this slot (an older page, or a surface
747
- // that never opens the page) must still get the settings card above.
748
- try {
749
- const manager = ctx.get("remote.pluginManager")
750
- const disposeActions = ctx.slots.inject("plugins.detail.actions", () => ctx.slots.register({
751
- name: "plugins.detail.actions",
752
- id: `${PACKAGE_NAME}-update`,
753
- order: 10,
754
- }, (props) => h(UpdateActions, { ...props, L, manager })))
755
- ctx.effect(() => () => {
756
- disposeActions?.()
757
- }, "dsh-workbuddy-connect: plugin page actions")
758
- } catch (error) {
759
- console.error("[dsh-workbuddy-connect] could not register the plugin page actions:", error)
760
- note("detail-actions", error)
761
- }
762
587
  } catch (error) {
763
588
  console.error("[dsh-workbuddy-connect] could not register the settings card:", error)
764
589
  note("apply", error)
package/lib/index.js CHANGED
@@ -30,7 +30,6 @@ import { createWorkBuddyShim } from './shim.js'
30
30
  import { WorkBuddyUpstreamClient, modelWithCurrentPromotion, prepareChatBody, prepareInternationalChatBody, realmOf, regionOf } from './upstream.js'
31
31
  import { readDesktopCredential, findDesktopExecutable } from './atrest.js'
32
32
  import { discoverProfileDir, workbuddyPluginDataDir, workbuddyStateDir } from './paths.js'
33
- import { checkForUpdate, updateSpecFrom } from './updates.js'
34
33
  import { WORKBUDDY_VARIANTS, variantFor } from './variants.js'
35
34
 
36
35
  export const name = 'llm-workbuddy'
@@ -474,63 +473,6 @@ export async function apply(ctx, config = {}) {
474
473
  })
475
474
 
476
475
  //#region card routes
477
- /**
478
- * The last update report plus when it was taken.
479
- *
480
- * A `git ls-remote` costs a round trip, and the card polls its status for
481
- * unrelated reasons (credits, catalog), so the answer is cached for a while
482
- * and refreshed only when the user asks or the cache ages out. Both callers
483
- * share one in-flight promise: two panels opening at once must not launch two
484
- * checks.
485
- */
486
- const updateCache = { report: undefined, at: 0, inFlight: undefined }
487
- const UPDATE_TTL_MS = 6 * 60 * 60 * 1000
488
-
489
- async function updateReport(profileDir, force) {
490
- const fresh = updateCache.report !== undefined && Date.now() - updateCache.at < UPDATE_TTL_MS
491
- if (fresh && force !== true) return updateCache.report
492
- if (updateCache.inFlight !== undefined) return updateCache.inFlight
493
- updateCache.inFlight = (async () => {
494
- try {
495
- // The profile that hosts this plugin, not the one the card happens to
496
- // be drawn in: the two are the same for a normal install, and the
497
- // discovered directory is the one whose lockfile records this copy.
498
- const report = await checkForUpdate(profileDir)
499
- updateCache.report = report
500
- updateCache.at = Date.now()
501
- return report
502
- } finally {
503
- updateCache.inFlight = undefined
504
- }
505
- })()
506
- return updateCache.inFlight
507
- }
508
-
509
- const updateHandler = async (req, res) => {
510
- if (req.method !== 'GET' || !routeGuard(req, updateKey)) {
511
- res.statusCode = req.method === 'GET' ? 403 : 405
512
- res.end()
513
- return
514
- }
515
- let report
516
- try {
517
- report = await updateReport(profileDir, new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('refresh') === '1')
518
- } catch (error) {
519
- report = { state: 'unknown', reason: safeMessage(error) }
520
- }
521
- // No key is echoed here: this route only *reads*, and the install it
522
- // enables goes through the plugin manager's own remote service, which
523
- // carries its own authorization. Returning a control key would hand any
524
- // reader of the card a credential it does not need.
525
- const spec = updateSpecFrom(report)
526
- const body = JSON.stringify({
527
- ...report,
528
- ...spec === undefined ? {} : { targetSpec: spec },
529
- })
530
- res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
531
- res.end(body)
532
- }
533
-
534
476
  const statusHandler = (req, res) => {
535
477
  if (req.method !== 'GET') {
536
478
  res.statusCode = 405
@@ -841,13 +783,11 @@ export async function apply(ctx, config = {}) {
841
783
  const b = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/login`, handler: loginHandler })
842
784
  const c = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/models`, handler: modelsHandler })
843
785
  const d = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/auth`, handler: authHandler })
844
- const e = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/update`, handler: updateHandler })
845
786
  return () => {
846
787
  a()
847
788
  b()
848
789
  c()
849
790
  d()
850
- e()
851
791
  }
852
792
  }, 'dsh-workbuddy-connect: web routes')
853
793
  })
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "WorkBuddy",
4
4
  "description": "将 WorkBuddy(国际版 / 国内版)的模型接入 DeepSeek Harness — bring WorkBuddy (Global & CN) models into DeepSeek Harness.",
5
5
  "icon": "./assets/icon.svg",
6
- "version": "0.3.0",
6
+ "version": "0.3.1",
7
7
  "author": "sunzhengnan",
8
8
  "keywords": [
9
9
  "dsh-plugin",
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
- }