@shardflux/cli 0.15.0 → 0.15.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 +21 -0
- package/README.md +5 -3
- package/dist/account-args.js +3 -3
- package/dist/account-commands.d.ts +2 -0
- package/dist/account-commands.js +18 -3
- package/dist/agent-commands.js +22 -8
- package/dist/agent-target-commands.d.ts +14 -0
- package/dist/agent-target-commands.js +73 -32
- package/dist/args.d.ts +1 -1
- package/dist/args.js +5 -2
- package/dist/commands.d.ts +1 -1
- package/dist/format.js +3 -1
- package/dist/main.js +30 -12
- package/dist/menubar.d.ts +57 -0
- package/dist/menubar.js +264 -45
- package/dist/registry.d.ts +48 -0
- package/dist/registry.js +102 -0
- package/dist/update-check.d.ts +9 -1
- package/dist/update-check.js +55 -17
- package/dist/update.d.ts +2 -0
- package/dist/update.js +26 -8
- package/package.json +2 -2
package/dist/menubar.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
2
|
-
import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync } from 'node:fs';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
5
|
import { dirname, join } from 'node:path';
|
|
6
6
|
import { promisify } from 'node:util';
|
|
7
|
+
import { compareVersions } from '@shardflux/sdk';
|
|
7
8
|
import { AgentStateStore } from "./agent-state.js";
|
|
8
9
|
import { UsageError } from "./errors.js";
|
|
9
10
|
import { json } from "./format.js";
|
|
@@ -27,6 +28,61 @@ export function compareBundleVersions(left, right) {
|
|
|
27
28
|
}
|
|
28
29
|
return 0;
|
|
29
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Marketing versions (CFBundleShortVersionString) compare as semver: 0.3.10 > 0.3.9, 0.4.0-rc.1 < 0.4.0. A version that
|
|
33
|
+
* is not semver compares as a numeric bundle version.
|
|
34
|
+
*/
|
|
35
|
+
export function compareAppVersions(left, right) {
|
|
36
|
+
return compareVersions(left, right) ?? compareBundleVersions(left, right);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The first app that swaps itself in when the npm package next to the CLI carries a newer one (it knows when no window
|
|
40
|
+
* is open and nothing is in progress). The CLI leaves a running app of this version or later to do that itself.
|
|
41
|
+
*/
|
|
42
|
+
export const SELF_UPDATING_APP = '0.3.2';
|
|
43
|
+
/** CFBundleShortVersionString of a Shardflux app from its XML Info.plist, read without any tool (null: not readable). */
|
|
44
|
+
export function plistVersion(app) {
|
|
45
|
+
try {
|
|
46
|
+
const text = readFileSync(join(app, 'Contents', 'Info.plist'), 'utf8');
|
|
47
|
+
const value = (key) => new RegExp(`<key>${key}</key>\\s*<string>([^<]+)</string>`).exec(text)?.[1]?.trim() ?? null;
|
|
48
|
+
if (value('CFBundleIdentifier') !== BUNDLE_ID)
|
|
49
|
+
return null;
|
|
50
|
+
const version = value('CFBundleShortVersionString') ?? value('CFBundleVersion');
|
|
51
|
+
return version && compareVersions(version, version) !== null ? version : null;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const WINDOW_PROBE = `ObjC.import('CoreGraphics');
|
|
58
|
+
function run(argv) {
|
|
59
|
+
const pids = argv.map(Number);
|
|
60
|
+
const list = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionOnScreenOnly, $.kCGNullWindowID))) || [];
|
|
61
|
+
return JSON.stringify(list.filter(w => pids.includes(w.kCGWindowOwnerPID)).map(w => ({ pid: w.kCGWindowOwnerPID, layer: w.kCGWindowLayer,
|
|
62
|
+
x: w.kCGWindowBounds.X, y: w.kCGWindowBounds.Y, width: w.kCGWindowBounds.Width, height: w.kCGWindowBounds.Height, alpha: w.kCGWindowAlpha })));
|
|
63
|
+
}`;
|
|
64
|
+
/**
|
|
65
|
+
* Whether any of these processes shows a window: the menu, the launcher, Settings, onboarding, an approval. The status
|
|
66
|
+
* item itself (a strip at the top of the screen on the status layer, owned by the app before macOS 26) does not count.
|
|
67
|
+
* Null when the probe could not answer: then nothing may be replaced.
|
|
68
|
+
*/
|
|
69
|
+
export function windowsOpen(text) {
|
|
70
|
+
let rows;
|
|
71
|
+
try {
|
|
72
|
+
rows = JSON.parse(text);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(rows))
|
|
78
|
+
return null;
|
|
79
|
+
const windows = rows;
|
|
80
|
+
if (!windows.every(w => w && typeof w === 'object' && ['layer', 'y', 'width', 'height'].every(k => typeof w[k] === 'number')))
|
|
81
|
+
return null;
|
|
82
|
+
// A status item is a strip on the status layer at the top of the screen (39 pt high on a notched display).
|
|
83
|
+
const statusItem = (w) => w.layer === 25 && w.y <= 0 && w.height <= 50;
|
|
84
|
+
return windows.some(w => w.layer >= 0 && !statusItem(w) && (w.alpha ?? 1) > 0 && w.width > 1 && w.height > 1);
|
|
85
|
+
}
|
|
30
86
|
export function parseNativeStatus(text) {
|
|
31
87
|
const value = JSON.parse(text);
|
|
32
88
|
if (!value || typeof value !== 'object')
|
|
@@ -68,12 +124,10 @@ export class MenubarManager {
|
|
|
68
124
|
this.#platform = options.platform ?? process.platform;
|
|
69
125
|
this.#run = options.run ?? ((tool, args) => nativeTools.run(tool, args, options.signal));
|
|
70
126
|
this.#packageApp = options.packageApp ?? (() => {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
catch {
|
|
127
|
+
const app = packagedAppPath();
|
|
128
|
+
if (!app)
|
|
75
129
|
throw new UsageError('The macOS app package is missing. Reinstall shard with optional dependencies enabled, then run shard menubar start.');
|
|
76
|
-
|
|
130
|
+
return app;
|
|
77
131
|
});
|
|
78
132
|
}
|
|
79
133
|
get platform() { return this.#platform; }
|
|
@@ -86,10 +140,25 @@ export class MenubarManager {
|
|
|
86
140
|
const id = (await this.#run('/usr/bin/plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', file])).trim();
|
|
87
141
|
if (id !== BUNDLE_ID || lstatSync(app).isSymbolicLink())
|
|
88
142
|
throw new UsageError(`Refusing to replace an unrelated app at ${app}.`);
|
|
143
|
+
// The marketing version (0.15.2+), compared as semver; an app without one has its numeric bundle version.
|
|
144
|
+
const marketing = await this.#run('/usr/bin/plutil', ['-extract', 'CFBundleShortVersionString', 'raw', '-o', '-', file]).then(v => v.trim(), () => '');
|
|
145
|
+
if (marketing && compareVersions(marketing, marketing) !== null)
|
|
146
|
+
return marketing;
|
|
89
147
|
const version = (await this.#run('/usr/bin/plutil', ['-extract', 'CFBundleVersion', 'raw', '-o', '-', file])).trim();
|
|
90
148
|
compareBundleVersions(version, version);
|
|
91
149
|
return version;
|
|
92
150
|
}
|
|
151
|
+
/** Whether the app shows any window (see windowsOpen); null when that could not be read. */
|
|
152
|
+
async windowsOpen(pids) {
|
|
153
|
+
if (!pids.length)
|
|
154
|
+
return false;
|
|
155
|
+
try {
|
|
156
|
+
return windowsOpen(await this.#run('/usr/bin/osascript', ['-l', 'JavaScript', '-e', WINDOW_PROBE, ...pids.map(String)]));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
93
162
|
async #control(action, ...args) {
|
|
94
163
|
makeExecutable(this.app);
|
|
95
164
|
return parseNativeStatus(await this.#run(join(this.app, 'Contents', 'MacOS', 'ShardfluxMenuBar'), ['--control', action, ...args]));
|
|
@@ -125,46 +194,49 @@ export class MenubarManager {
|
|
|
125
194
|
await this.#control('login', value);
|
|
126
195
|
return this.status();
|
|
127
196
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
197
|
+
/** Replaces the installed app with `source` (verified first), stopping it while it is swapped. */
|
|
198
|
+
async #install(source, current) {
|
|
199
|
+
// Verify the source before stopping or replacing any existing app.
|
|
200
|
+
await this.#run('/usr/bin/codesign', ['--verify', '--deep', '--strict', source]);
|
|
201
|
+
mkdirSync(dirname(this.app), { recursive: true });
|
|
202
|
+
const stage = mkdtempSync(join(dirname(this.app), '.Shardflux-install-'));
|
|
203
|
+
const staged = join(stage, 'Shardflux.app'), backup = join(stage, 'previous.app');
|
|
204
|
+
let committed = false, restored = false;
|
|
205
|
+
try {
|
|
206
|
+
cpSync(source, staged, { recursive: true, dereference: false });
|
|
207
|
+
if (current.running)
|
|
208
|
+
await this.stop();
|
|
209
|
+
if (current.installed)
|
|
210
|
+
renameSync(this.app, backup);
|
|
211
|
+
makeExecutable(staged);
|
|
139
212
|
try {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (existsSync(backup)) {
|
|
152
|
-
try {
|
|
153
|
-
renameSync(backup, this.app);
|
|
154
|
-
restored = true;
|
|
155
|
-
}
|
|
156
|
-
catch {
|
|
157
|
-
throw new UsageError(`Could not restore the previous app. It is preserved at ${backup}.`);
|
|
158
|
-
}
|
|
213
|
+
renameSync(staged, this.app);
|
|
214
|
+
committed = true;
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (existsSync(backup)) {
|
|
218
|
+
try {
|
|
219
|
+
renameSync(backup, this.app);
|
|
220
|
+
restored = true;
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
throw new UsageError(`Could not restore the previous app. It is preserved at ${backup}.`);
|
|
159
224
|
}
|
|
160
|
-
throw error;
|
|
161
225
|
}
|
|
226
|
+
throw error;
|
|
162
227
|
}
|
|
163
|
-
finally {
|
|
164
|
-
if (committed || restored || !existsSync(backup))
|
|
165
|
-
rmSync(stage, { recursive: true, force: true });
|
|
166
|
-
}
|
|
167
228
|
}
|
|
229
|
+
finally {
|
|
230
|
+
if (committed || restored || !existsSync(backup))
|
|
231
|
+
rmSync(stage, { recursive: true, force: true });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async start(configDir, apiUrl) {
|
|
235
|
+
this.#requireMac();
|
|
236
|
+
const source = this.#packageApp(), sourceVersion = await this.#version(source);
|
|
237
|
+
const current = await this.status();
|
|
238
|
+
if (!current.installed || compareAppVersions(current.version, sourceVersion) < 0)
|
|
239
|
+
await this.#install(source, current);
|
|
168
240
|
await this.#stripQuarantine();
|
|
169
241
|
if (!(await this.status()).running) {
|
|
170
242
|
mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
@@ -179,6 +251,45 @@ export class MenubarManager {
|
|
|
179
251
|
}
|
|
180
252
|
throw new UsageError(`Shardflux did not start. Check ${join(configDir, 'menubar.log')}.`);
|
|
181
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Brings an installed app up to the one this CLI's npm package carries, without disturbing the person: nothing when
|
|
256
|
+
* the versions are equal (each swap of an ad-hoc signed app costs its privacy grants), the copy on disk alone when it
|
|
257
|
+
* is not running, and a running app only when it shows no window and no `shard update` runs. A running app that
|
|
258
|
+
* swaps itself in (SELF_UPDATING_APP or later) is left to do so: it also knows when it is in the middle of something.
|
|
259
|
+
*/
|
|
260
|
+
async refresh(configDir, apiUrl) {
|
|
261
|
+
this.#requireMac();
|
|
262
|
+
const current = await this.status();
|
|
263
|
+
if (!current.installed || !current.version)
|
|
264
|
+
return { result: 'not_installed', from: null, to: null };
|
|
265
|
+
const to = await this.packagedVersion(), from = current.version;
|
|
266
|
+
if (compareAppVersions(from, to) >= 0)
|
|
267
|
+
return { result: 'current', from, to };
|
|
268
|
+
if (current.running) {
|
|
269
|
+
if (compareAppVersions(from, SELF_UPDATING_APP) >= 0)
|
|
270
|
+
return { result: 'deferred', from, to };
|
|
271
|
+
if (updateRunning(configDir) || (await this.windowsOpen(current.pids)) !== false)
|
|
272
|
+
return { result: 'busy', from, to };
|
|
273
|
+
await this.start(configDir, apiUrl);
|
|
274
|
+
return { result: 'restarted', from, to };
|
|
275
|
+
}
|
|
276
|
+
await this.#install(this.#packageApp(), current);
|
|
277
|
+
await this.#stripQuarantine();
|
|
278
|
+
return { result: 'installed', from, to };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/** A `shard update` holds update.lock while it runs (update.ts); a lock of a process that is gone does not count. */
|
|
282
|
+
function updateRunning(dir) {
|
|
283
|
+
try {
|
|
284
|
+
const pid = Number(readFileSync(join(dir, 'update.lock'), 'utf8'));
|
|
285
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
286
|
+
return false;
|
|
287
|
+
process.kill(pid, 0);
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
182
293
|
}
|
|
183
294
|
/** On macOS, `shard` brings the menu bar up by itself (with launch at login) unless the user ran `shard menubar stop`.
|
|
184
295
|
* It never fails the command center: a missing optional package or a refused start just leaves it off. */
|
|
@@ -190,8 +301,9 @@ export async function ensureMenubar(dir, apiUrl, manager = new MenubarManager(),
|
|
|
190
301
|
return undefined;
|
|
191
302
|
try {
|
|
192
303
|
const status = await manager.status();
|
|
193
|
-
// A running app
|
|
194
|
-
|
|
304
|
+
// A running app is brought up to the one this CLI carries (after `npm i -g shardflux`) by the background refresh
|
|
305
|
+
// every command starts (refreshMenubarInBackground), at a moment when it shows no window.
|
|
306
|
+
if (status.running)
|
|
195
307
|
return undefined;
|
|
196
308
|
const started = await manager.start(dir, apiUrl);
|
|
197
309
|
if (!started.running)
|
|
@@ -204,7 +316,114 @@ export async function ensureMenubar(dir, apiUrl, manager = new MenubarManager(),
|
|
|
204
316
|
return undefined;
|
|
205
317
|
}
|
|
206
318
|
}
|
|
207
|
-
|
|
319
|
+
const REFRESH_MARK = 'menubar-refresh.json';
|
|
320
|
+
const REFRESH_LOCK = 'menubar-refresh.lock';
|
|
321
|
+
/** How often a command may start a background refresh while the app is busy (a window open). */
|
|
322
|
+
export const REFRESH_RETRY_MS = 5 * 60_000;
|
|
323
|
+
/** Where this CLI's npm package keeps the app it carries, or null when the optional package is missing. */
|
|
324
|
+
export function packagedAppPath() {
|
|
325
|
+
try {
|
|
326
|
+
return join(dirname(createRequire(import.meta.url).resolve('@shardflux/menubar-darwin/package.json')), 'Shardflux.app');
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Every `shard` command (0.15.2+): when the npm package carries a newer app than the installed one (two Info.plist
|
|
334
|
+
* reads, no network, no tool), `shard menubar refresh` runs detached, so the command never waits for it. It is started
|
|
335
|
+
* at most every 5 minutes while the app is busy, and not at all after `shard menubar stop`. Returns whether it started.
|
|
336
|
+
*/
|
|
337
|
+
export function refreshMenubarInBackground(o) {
|
|
338
|
+
try {
|
|
339
|
+
if ((o.platform ?? process.platform) !== 'darwin')
|
|
340
|
+
return false;
|
|
341
|
+
const installed = plistVersion(join(o.home, 'Applications', 'Shardflux.app'));
|
|
342
|
+
const source = (o.packageApp ?? packagedAppPath)();
|
|
343
|
+
const packaged = source ? plistVersion(source) : null;
|
|
344
|
+
if (!installed || !packaged || compareAppVersions(installed, packaged) >= 0)
|
|
345
|
+
return false;
|
|
346
|
+
if (new AgentStateStore(o.dir).read().menubar_stopped === true)
|
|
347
|
+
return false;
|
|
348
|
+
const now = (o.now ?? Date.now)(), mark = join(o.dir, REFRESH_MARK);
|
|
349
|
+
try {
|
|
350
|
+
const last = JSON.parse(readFileSync(mark, 'utf8'));
|
|
351
|
+
if (last.to === packaged && typeof last.at === 'number' && now - last.at < REFRESH_RETRY_MS && last.at <= now)
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
catch { /* never started */ }
|
|
355
|
+
mkdirSync(o.dir, { recursive: true, mode: 0o700 });
|
|
356
|
+
const fd = openSync(mark, 'w', 0o600);
|
|
357
|
+
try {
|
|
358
|
+
writeSync(fd, `${JSON.stringify({ at: now, from: installed, to: packaged })}\n`);
|
|
359
|
+
}
|
|
360
|
+
finally {
|
|
361
|
+
closeSync(fd);
|
|
362
|
+
}
|
|
363
|
+
const env = { ...o.env, SHARDFLUX_CONFIG_DIR: o.dir, SHARDFLUX_NO_UPDATE_CHECK: '1' };
|
|
364
|
+
(o.spawn ?? spawnDetached)(o.runtime.node, [o.runtime.script, 'menubar', 'refresh'], env);
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function spawnDetached(node, args, env) {
|
|
372
|
+
const child = spawn(node, args, { detached: true, stdio: 'ignore', env });
|
|
373
|
+
child.on('error', () => undefined);
|
|
374
|
+
child.unref();
|
|
375
|
+
}
|
|
376
|
+
/** One refresh at a time per config directory; the lock of a process that is gone is taken over. */
|
|
377
|
+
function refreshLock(dir) {
|
|
378
|
+
const file = join(dir, REFRESH_LOCK);
|
|
379
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
380
|
+
try {
|
|
381
|
+
const fd = openSync(file, 'wx', 0o600);
|
|
382
|
+
writeSync(fd, String(process.pid));
|
|
383
|
+
closeSync(fd);
|
|
384
|
+
return () => rmSync(file, { force: true });
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
if (error.code !== 'EEXIST')
|
|
388
|
+
return null;
|
|
389
|
+
let alive = false;
|
|
390
|
+
try {
|
|
391
|
+
const pid = Number(readFileSync(file, 'utf8'));
|
|
392
|
+
if (Number.isInteger(pid) && pid > 0) {
|
|
393
|
+
process.kill(pid, 0);
|
|
394
|
+
alive = true;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
catch { /* gone */ }
|
|
398
|
+
if (alive)
|
|
399
|
+
return null;
|
|
400
|
+
rmSync(file, { force: true });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
/** `shard menubar refresh` (not listed in help, so not in HANDLERS): what refreshMenubarInBackground starts. */
|
|
406
|
+
export const runMenubarRefresh = async (ctx) => {
|
|
407
|
+
const manager = new MenubarManager({ home: ctx.io.env.HOME || homedir(), signal: ctx.signal });
|
|
408
|
+
let outcome;
|
|
409
|
+
if (new AgentStateStore(ctx.store.dir).read().menubar_stopped === true)
|
|
410
|
+
outcome = { result: 'off', from: null, to: null };
|
|
411
|
+
else {
|
|
412
|
+
const unlock = refreshLock(ctx.store.dir);
|
|
413
|
+
if (!unlock)
|
|
414
|
+
outcome = { result: 'locked', from: null, to: null };
|
|
415
|
+
else
|
|
416
|
+
try {
|
|
417
|
+
outcome = await manager.refresh(ctx.store.dir, ctx.apiUrl);
|
|
418
|
+
}
|
|
419
|
+
finally {
|
|
420
|
+
unlock();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
ctx.io.stdout.write(ctx.json ? json(outcome) : `Menu bar: ${outcome.result}${outcome.from ? ` · app ${outcome.from}${outcome.to && outcome.to !== outcome.from ? ` → ${outcome.to}` : ''}` : ''}\n`);
|
|
424
|
+
return 0;
|
|
425
|
+
};
|
|
426
|
+
export const MENUBAR_HANDLERS = Object.fromEntries(['start', 'stop', 'status'].map((action) => {
|
|
208
427
|
const handler = async (ctx, values) => {
|
|
209
428
|
if (values.login !== undefined && !['on', 'off'].includes(String(values.login)))
|
|
210
429
|
throw new UsageError('--login must be on or off.');
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export declare const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
2
|
+
/** Each registry request's timeout (ms). */
|
|
3
|
+
export declare const REGISTRY_TIMEOUT_MS = 3000;
|
|
4
|
+
/** The npm packages whose versions `shard update` compares. */
|
|
5
|
+
export declare const NPM_CLIENTS: readonly ["shardflux", "@shardflux/cli", "@shardflux/sdk", "@shardflux/mcp", "@shardflux/menubar-darwin"];
|
|
6
|
+
export interface RegistryAnswer {
|
|
7
|
+
latest: string | null;
|
|
8
|
+
/** The registry's validator for the next request (npm's dist-tags endpoint sends none today). */
|
|
9
|
+
etag: string | null;
|
|
10
|
+
/** 304: what the caller cached under `etag` is still current. */
|
|
11
|
+
notModified: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface RegistryOptions {
|
|
14
|
+
fetch: typeof fetch;
|
|
15
|
+
/** Default https://registry.npmjs.org (SHARDFLUX_NPM_REGISTRY overrides it for the CLI). */
|
|
16
|
+
registry?: string;
|
|
17
|
+
etag?: string | null;
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
userAgent?: string;
|
|
21
|
+
}
|
|
22
|
+
/** The registry to ask: SHARDFLUX_NPM_REGISTRY, else npm's public registry. */
|
|
23
|
+
export declare function npmRegistry(env: Record<string, string | undefined>): string;
|
|
24
|
+
/** `latest` of an npm package from `<registry>/-/package/<name>/dist-tags`, or null when the registry did not answer. */
|
|
25
|
+
export declare function npmLatest(pkg: string, opts: RegistryOptions): Promise<RegistryAnswer | null>;
|
|
26
|
+
/** `latest` of every package in `packages`, asked in parallel; a package the registry did not answer is absent. */
|
|
27
|
+
export declare function npmLatestAll(packages: readonly string[], opts: RegistryOptions): Promise<Record<string, string>>;
|
|
28
|
+
export interface CatalogEntry {
|
|
29
|
+
package: string;
|
|
30
|
+
ecosystem: string;
|
|
31
|
+
latest: string | null;
|
|
32
|
+
minimum_supported: string | null;
|
|
33
|
+
upgrade_command: string | null;
|
|
34
|
+
release_notes_url: string | null;
|
|
35
|
+
hold?: string | null;
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A GET /v1/client-versions body whose npm entries carry the registry's `latest` (`registry`: package -> version; an
|
|
40
|
+
* absent package keeps the catalog's). Works with every catalog shape the API has served: no `hold` field, `latest`
|
|
41
|
+
* null, a package missing from the list, or no catalog at all (`catalog` null: the API did not answer).
|
|
42
|
+
*
|
|
43
|
+
* `hold`: when the registry's latest is that version, it is not recommended; the catalog's own `latest` is, when it is
|
|
44
|
+
* older, else `minimum_supported` (so "no longer supported" still works and nobody is told to update).
|
|
45
|
+
*/
|
|
46
|
+
export declare function withRegistryLatest(catalog: unknown, registry: Record<string, string | null | undefined>): {
|
|
47
|
+
clients: CatalogEntry[];
|
|
48
|
+
};
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The latest version of each Shardflux client comes from its registry (0.15.2+), so a release is known the moment it
|
|
3
|
+
* is published: npm's `latest` dist-tag, which is what `npm i -g shardflux` and `shard update` install. (`stable` is an
|
|
4
|
+
* opt-in tag for installs behind a release-age gate, docs/progress/packaging.md; it never drives the update notice.)
|
|
5
|
+
*
|
|
6
|
+
* The API catalog (GET /v1/client-versions) still says which versions it serves (`minimum_supported`) and may name a
|
|
7
|
+
* version to stop recommending (`hold`, an emergency brake). Its `latest` is only the fallback when the registry does
|
|
8
|
+
* not answer. Every request here is bounded and never throws: offline means "no answer".
|
|
9
|
+
*/
|
|
10
|
+
import { compareVersions } from '@shardflux/sdk';
|
|
11
|
+
export const NPM_REGISTRY = 'https://registry.npmjs.org';
|
|
12
|
+
/** Each registry request's timeout (ms). */
|
|
13
|
+
export const REGISTRY_TIMEOUT_MS = 3_000;
|
|
14
|
+
/** The npm packages whose versions `shard update` compares. */
|
|
15
|
+
export const NPM_CLIENTS = ['shardflux', '@shardflux/cli', '@shardflux/sdk', '@shardflux/mcp', '@shardflux/menubar-darwin'];
|
|
16
|
+
const str = (v) => (typeof v === 'string' && v.length > 0 ? v : null);
|
|
17
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
18
|
+
/** The registry to ask: SHARDFLUX_NPM_REGISTRY, else npm's public registry. */
|
|
19
|
+
export function npmRegistry(env) {
|
|
20
|
+
const own = env.SHARDFLUX_NPM_REGISTRY?.trim();
|
|
21
|
+
return own ? own.replace(/\/+$/, '') : NPM_REGISTRY;
|
|
22
|
+
}
|
|
23
|
+
/** `latest` of an npm package from `<registry>/-/package/<name>/dist-tags`, or null when the registry did not answer. */
|
|
24
|
+
export async function npmLatest(pkg, opts) {
|
|
25
|
+
try {
|
|
26
|
+
const timeout = AbortSignal.timeout(opts.timeoutMs ?? REGISTRY_TIMEOUT_MS);
|
|
27
|
+
const headers = { accept: 'application/json' };
|
|
28
|
+
if (opts.userAgent)
|
|
29
|
+
headers['user-agent'] = opts.userAgent;
|
|
30
|
+
if (opts.etag)
|
|
31
|
+
headers['if-none-match'] = opts.etag;
|
|
32
|
+
const res = await opts.fetch(`${(opts.registry ?? NPM_REGISTRY).replace(/\/+$/, '')}/-/package/${encodeURIComponent(pkg)}/dist-tags`, {
|
|
33
|
+
method: 'GET',
|
|
34
|
+
headers,
|
|
35
|
+
signal: opts.signal ? AbortSignal.any([timeout, opts.signal]) : timeout,
|
|
36
|
+
});
|
|
37
|
+
const etag = res.headers.get('etag');
|
|
38
|
+
if (res.status === 304) {
|
|
39
|
+
await res.body?.cancel().catch(() => undefined);
|
|
40
|
+
return { latest: null, etag: etag ?? opts.etag ?? null, notModified: true };
|
|
41
|
+
}
|
|
42
|
+
if (!res.ok) {
|
|
43
|
+
await res.body?.cancel().catch(() => undefined);
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
const body = JSON.parse(await res.text());
|
|
47
|
+
const latest = isObj(body) ? str(body.latest) : null;
|
|
48
|
+
// A tag that is not a version (a broken registry mirror) is no answer.
|
|
49
|
+
if (latest === null || compareVersions(latest, latest) === null)
|
|
50
|
+
return null;
|
|
51
|
+
return { latest, etag, notModified: false };
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** `latest` of every package in `packages`, asked in parallel; a package the registry did not answer is absent. */
|
|
58
|
+
export async function npmLatestAll(packages, opts) {
|
|
59
|
+
const answers = await Promise.all(packages.map(async (pkg) => [pkg, await npmLatest(pkg, { ...opts, etag: null })]));
|
|
60
|
+
return Object.fromEntries(answers.flatMap(([pkg, a]) => (a?.latest ? [[pkg, a.latest]] : [])));
|
|
61
|
+
}
|
|
62
|
+
const DEFAULT_UPGRADE = {
|
|
63
|
+
shardflux: 'npm i -g shardflux',
|
|
64
|
+
'@shardflux/cli': 'npm i -g shardflux',
|
|
65
|
+
'@shardflux/menubar-darwin': 'shard update',
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* A GET /v1/client-versions body whose npm entries carry the registry's `latest` (`registry`: package -> version; an
|
|
69
|
+
* absent package keeps the catalog's). Works with every catalog shape the API has served: no `hold` field, `latest`
|
|
70
|
+
* null, a package missing from the list, or no catalog at all (`catalog` null: the API did not answer).
|
|
71
|
+
*
|
|
72
|
+
* `hold`: when the registry's latest is that version, it is not recommended; the catalog's own `latest` is, when it is
|
|
73
|
+
* older, else `minimum_supported` (so "no longer supported" still works and nobody is told to update).
|
|
74
|
+
*/
|
|
75
|
+
export function withRegistryLatest(catalog, registry) {
|
|
76
|
+
const listed = isObj(catalog) && Array.isArray(catalog.clients) ? catalog.clients.filter(isObj) : [];
|
|
77
|
+
const entries = listed.map((c) => ({
|
|
78
|
+
...c,
|
|
79
|
+
package: String(c.package),
|
|
80
|
+
ecosystem: String(c.ecosystem),
|
|
81
|
+
latest: str(c.latest),
|
|
82
|
+
minimum_supported: str(c.minimum_supported),
|
|
83
|
+
upgrade_command: str(c.upgrade_command),
|
|
84
|
+
release_notes_url: str(c.release_notes_url),
|
|
85
|
+
hold: str(c.hold),
|
|
86
|
+
}));
|
|
87
|
+
for (const pkg of Object.keys(registry)) {
|
|
88
|
+
if (!entries.some((e) => e.ecosystem === 'npm' && e.package === pkg)) {
|
|
89
|
+
entries.push({ package: pkg, ecosystem: 'npm', latest: null, minimum_supported: null, upgrade_command: DEFAULT_UPGRADE[pkg] ?? null, release_notes_url: `https://www.npmjs.com/package/${pkg}?activeTab=versions`, hold: null });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
clients: entries.map((e) => {
|
|
94
|
+
const fromRegistry = e.ecosystem === 'npm' ? str(registry[e.package]) : null;
|
|
95
|
+
let latest = fromRegistry ?? e.latest;
|
|
96
|
+
if (latest !== null && e.hold && compareVersions(latest, e.hold) === 0) {
|
|
97
|
+
latest = e.latest !== null && compareVersions(e.latest, e.hold) === -1 ? e.latest : e.minimum_supported;
|
|
98
|
+
}
|
|
99
|
+
return { ...e, latest };
|
|
100
|
+
}),
|
|
101
|
+
};
|
|
102
|
+
}
|
package/dist/update-check.d.ts
CHANGED
|
@@ -11,10 +11,16 @@ export interface Distribution {
|
|
|
11
11
|
export declare const CLI_DISTRIBUTION: Distribution;
|
|
12
12
|
interface CacheEntry {
|
|
13
13
|
checked_at: string;
|
|
14
|
+
/** What the notice compares with: the registry's latest, unless the catalog holds it (registry.ts). */
|
|
14
15
|
latest: string | null;
|
|
15
16
|
minimum_supported: string | null;
|
|
16
17
|
upgrade_command: string | null;
|
|
17
18
|
release_notes_url: string | null;
|
|
19
|
+
/** The catalog's own `latest` and `hold`, and the registry's answer with its ETag (0.15.2+). */
|
|
20
|
+
catalog_latest?: string | null;
|
|
21
|
+
hold?: string | null;
|
|
22
|
+
registry_latest?: string | null;
|
|
23
|
+
registry_etag?: string | null;
|
|
18
24
|
}
|
|
19
25
|
/** The `update` object of `shard version --json`. */
|
|
20
26
|
export interface UpdateView {
|
|
@@ -37,6 +43,8 @@ export interface UpdateCheckOptions {
|
|
|
37
43
|
distribution: Distribution;
|
|
38
44
|
fetch: typeof fetch;
|
|
39
45
|
userAgent: string;
|
|
46
|
+
/** The npm registry (default https://registry.npmjs.org). */
|
|
47
|
+
registry?: string;
|
|
40
48
|
now?: () => number;
|
|
41
49
|
}
|
|
42
50
|
/**
|
|
@@ -51,7 +59,7 @@ export declare class UpdateCheck {
|
|
|
51
59
|
status: ClientVersionStatus;
|
|
52
60
|
checkedAt: string | null;
|
|
53
61
|
} | null;
|
|
54
|
-
/** Starts the check: from the cache when it is younger than
|
|
62
|
+
/** Starts the check: from the cache when it is younger than 12 h (unless `force`), else the registry and the API. */
|
|
55
63
|
start(force?: boolean): void;
|
|
56
64
|
/** The status (with when it was fetched), or null when not started or still running after `waitMs`. */
|
|
57
65
|
result(waitMs: number): Promise<{
|