@spikonado/sprocket 0.3.3 → 0.3.4-dev.0723ea286bd91244bffbfa3258490e0176dbd64a

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.
Files changed (43) hide show
  1. package/README.md +15 -0
  2. package/bin/sprocket.js +1 -1
  3. package/lib/launcher.js +36 -10
  4. package/lib/update-api.js +5 -0
  5. package/lib/update.js +1036 -0
  6. package/package.json +6 -6
  7. package/web/_app/immutable/assets/0.D9kFaRQb.css +2 -0
  8. package/web/_app/immutable/assets/2.CMU7pdv8.css +1 -0
  9. package/web/_app/immutable/chunks/2EswWPt9.js +70 -0
  10. package/web/_app/immutable/chunks/Bb3byk3I.js +1 -0
  11. package/web/_app/immutable/chunks/CH-DwAqy.js +1 -0
  12. package/web/_app/immutable/chunks/CirtoWSJ.js +3 -0
  13. package/web/_app/immutable/chunks/{mPrToSgq.js → CrHmoVyY.js} +1 -1
  14. package/web/_app/immutable/chunks/D9pQdF5A.js +6 -0
  15. package/web/_app/immutable/chunks/{PSXYTcvE.js → VSK6LhsJ.js} +1 -1
  16. package/web/_app/immutable/chunks/{CeNjyCLa.js → aSUXxYi9.js} +2 -2
  17. package/web/_app/immutable/chunks/mWKhuXx1.js +1 -0
  18. package/web/_app/immutable/entry/app.BBG1Yap2.js +2 -0
  19. package/web/_app/immutable/entry/start.Cvp5ASMH.js +1 -0
  20. package/web/_app/immutable/nodes/0.CgqhmoX9.js +1 -0
  21. package/web/_app/immutable/nodes/1.Bww2K8_U.js +1 -0
  22. package/web/_app/immutable/nodes/2.Duq09sCo.js +127 -0
  23. package/web/_app/immutable/nodes/3.DxMC56lQ.js +1 -0
  24. package/web/_app/immutable/nodes/4.DNmFN8Yx.js +1 -0
  25. package/web/_app/version.json +1 -1
  26. package/web/callback.html +16 -16
  27. package/web/index.html +13 -13
  28. package/web/pair.html +16 -17
  29. package/web/_app/immutable/assets/0.Btn1dfCy.css +0 -2
  30. package/web/_app/immutable/chunks/BQbJFoq8.js +0 -1
  31. package/web/_app/immutable/chunks/BxbMz3h1.js +0 -1
  32. package/web/_app/immutable/chunks/CrsnnmTA.js +0 -1
  33. package/web/_app/immutable/chunks/D-3DgMVM.js +0 -3
  34. package/web/_app/immutable/chunks/D_7QcTZV.js +0 -6
  35. package/web/_app/immutable/chunks/Dtk4_9sS.js +0 -64
  36. package/web/_app/immutable/chunks/OmCPj9EG.js +0 -7
  37. package/web/_app/immutable/entry/app.D45zMGUe.js +0 -2
  38. package/web/_app/immutable/entry/start.DjZ5YK4X.js +0 -1
  39. package/web/_app/immutable/nodes/0.mG7tw7cg.js +0 -1
  40. package/web/_app/immutable/nodes/1.C19uY9DR.js +0 -1
  41. package/web/_app/immutable/nodes/2.Bq6t6SjB.js +0 -127
  42. package/web/_app/immutable/nodes/3.DBnPhkDo.js +0 -1
  43. package/web/_app/immutable/nodes/4.C52Ki53w.js +0 -1
package/lib/update.js ADDED
@@ -0,0 +1,1036 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { promises as fsPromises, readFileSync, realpathSync, statSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ export const PACKAGE_NAME = '@spikonado/sprocket';
8
+ export const UPDATE_API_FILENAME = 'update-api.js';
9
+ export const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
10
+ export const RELAUNCH_MESSAGE =
11
+ 'Wait for active agents to finish, then stop Sprocket and launch it again.';
12
+ export const UNSUPPORTED_MESSAGE =
13
+ 'This copy of Sprocket was not installed globally with npm, bun, pnpm, or yarn, so it cannot be updated in place.';
14
+
15
+ const STABLE_VERSION = /^[0-9]+\.[0-9]+\.[0-9]+$/;
16
+ const CANARY_VERSION = /^[0-9]+\.[0-9]+\.[0-9]+-canary\.[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*$/;
17
+ const DEV_VERSION = /^[0-9]+\.[0-9]+\.[0-9]+-dev\.[0-9a-f]{40}$/;
18
+ const NUMERIC_IDENTIFIER = /^[0-9]+$/;
19
+ const QUERY_TIMEOUT_MS = 10_000;
20
+ const INSTALL_TIMEOUT_MS = 5 * 60 * 1000;
21
+ const FETCH_TIMEOUT_MS = 15_000;
22
+ const KILL_WAIT_MS = 5_000;
23
+ const OUTPUT_LIMIT = 1_000_000;
24
+
25
+ export const PACKAGE_ROOT = path.resolve(import.meta.dirname, '..');
26
+
27
+ const HELP = `Usage: sprocket update [--check]
28
+
29
+ Update a global ${PACKAGE_NAME} install.
30
+
31
+ --check Report whether an update is available, without installing
32
+
33
+ \`sprocket upgrade\` is the same command.
34
+
35
+ Updates stay on the current channel: latest, canary, or dev.
36
+ Only global installs from npm, bun, pnpm, or yarn can be updated this way.
37
+ `;
38
+
39
+ const MANAGERS = [
40
+ {
41
+ name: 'bun',
42
+ queryArgs: ['pm', 'bin', '--global'],
43
+ installArgs: (version) => ['add', '--global', packageSpec(version)],
44
+ globalRoot(queryStdout) {
45
+ const binDir = firstAbsolutePath(queryStdout);
46
+ return binDir ? path.resolve(binDir, '..', 'install', 'global', 'node_modules') : '';
47
+ }
48
+ },
49
+ {
50
+ name: 'pnpm',
51
+ queryArgs: ['root', '-g'],
52
+ installArgs: (version) => ['add', '--global', packageSpec(version)],
53
+ globalRoot(queryStdout) {
54
+ return firstAbsolutePath(queryStdout);
55
+ }
56
+ },
57
+ {
58
+ name: 'yarn',
59
+ queryArgs: ['global', 'dir'],
60
+ installArgs: (version) => ['global', 'add', packageSpec(version)],
61
+ globalRoot(queryStdout) {
62
+ const dir = firstAbsolutePath(queryStdout);
63
+ return dir ? path.join(dir, 'node_modules') : '';
64
+ }
65
+ },
66
+ {
67
+ name: 'npm',
68
+ queryArgs: ['root', '-g'],
69
+ installArgs: (version) => ['install', '--global', packageSpec(version)],
70
+ globalRoot(queryStdout) {
71
+ return firstAbsolutePath(queryStdout);
72
+ }
73
+ }
74
+ ];
75
+
76
+ export function packageSpec(version) {
77
+ return `${PACKAGE_NAME}@${version}`;
78
+ }
79
+
80
+ export function asText(value) {
81
+ if (value == null) {
82
+ return '';
83
+ }
84
+ return `${value}`;
85
+ }
86
+
87
+ export function parseVersionField(value) {
88
+ const text = asText(value).trim();
89
+ if (!text || text.length > 128) {
90
+ return '';
91
+ }
92
+ return text;
93
+ }
94
+
95
+ export function releaseChannel(version) {
96
+ const text = asText(version);
97
+ if (text.includes('-canary.')) {
98
+ return 'canary';
99
+ }
100
+ if (text.includes('-dev.')) {
101
+ return 'dev';
102
+ }
103
+ return 'latest';
104
+ }
105
+
106
+ export function isAllowedVersion(version, channel) {
107
+ const text = parseVersionField(version);
108
+ if (!text) {
109
+ return false;
110
+ }
111
+ if (channel === 'canary') {
112
+ return CANARY_VERSION.test(text);
113
+ }
114
+ if (channel === 'dev') {
115
+ return DEV_VERSION.test(text);
116
+ }
117
+ return STABLE_VERSION.test(text);
118
+ }
119
+
120
+ export function compareReleaseVersions(left, right) {
121
+ const parsedLeft = parseComparable(left);
122
+ const parsedRight = parseComparable(right);
123
+ if (!parsedLeft || !parsedRight) {
124
+ return null;
125
+ }
126
+ for (let index = 0; index < 3; index += 1) {
127
+ if (parsedLeft.core[index] < parsedRight.core[index]) {
128
+ return -1;
129
+ }
130
+ if (parsedLeft.core[index] > parsedRight.core[index]) {
131
+ return 1;
132
+ }
133
+ }
134
+ return comparePrerelease(parsedLeft.pre, parsedRight.pre);
135
+ }
136
+
137
+ export function channelUpdate(currentVersion, registryVersion) {
138
+ if (currentVersion === registryVersion) {
139
+ return { status: 'idle' };
140
+ }
141
+ if (releaseChannel(currentVersion) === 'dev') {
142
+ return { status: 'available', version: registryVersion };
143
+ }
144
+ const comparison = compareReleaseVersions(registryVersion, currentVersion);
145
+ if (comparison == null) {
146
+ throw new Error('Could not compare the installed version with the registry version.');
147
+ }
148
+ if (comparison <= 0) {
149
+ return { status: 'idle' };
150
+ }
151
+ return { status: 'available', version: registryVersion };
152
+ }
153
+
154
+ export function makePayload(fields) {
155
+ return {
156
+ status: fields.status,
157
+ currentVersion: fields.currentVersion,
158
+ version: fields.version ?? null,
159
+ error: fields.error ?? null,
160
+ method: 'package',
161
+ message: fields.message ?? null
162
+ };
163
+ }
164
+
165
+ export function parseUpdateArgs(args) {
166
+ const command = args[0];
167
+ if (command !== 'update' && command !== 'upgrade') {
168
+ return { kind: 'none' };
169
+ }
170
+ let check = false;
171
+ for (const arg of args.slice(1)) {
172
+ if (arg === '--help' || arg === '-h') {
173
+ return { kind: 'help' };
174
+ }
175
+ if (arg === '--check') {
176
+ check = true;
177
+ continue;
178
+ }
179
+ return { kind: 'invalid', error: `Unknown option '${arg}'.` };
180
+ }
181
+ return { kind: 'run', check };
182
+ }
183
+
184
+ export function globalPackageDir(globalRoot) {
185
+ return path.join(globalRoot, '@spikonado', 'sprocket');
186
+ }
187
+
188
+ export function isManagedUpdate(env = {}) {
189
+ return asText(env.SPROCKET_UPDATE_MANAGED) === '1';
190
+ }
191
+
192
+ export function taskkillPath(env = {}) {
193
+ const root = asText(env.SystemRoot || env.SYSTEMROOT);
194
+ if (!path.win32.isAbsolute(root))
195
+ throw new Error('SystemRoot is unavailable; cannot stop the update process tree.');
196
+ return path.win32.join(root, 'System32', 'taskkill.exe');
197
+ }
198
+
199
+ export function timeoutRecoveryMessage(lockPath) {
200
+ return `Timed out while installing the update. Confirm no package manager is still running, delete ${lockPath}, then retry.`;
201
+ }
202
+
203
+ export function updateLockPath(host, globalRoot) {
204
+ const resolved = path.resolve(globalPackageDir(globalRoot));
205
+ const identity = host.platform === 'win32' ? resolved.toLowerCase() : resolved;
206
+ const id = createHash('sha256').update(identity).digest('hex').slice(0, 16);
207
+ return path.join(host.tmpdir(), `sprocket-update-${id}.lock`);
208
+ }
209
+
210
+ export function waitForClose(child, deadlineMs) {
211
+ return new Promise((resolve, reject) => {
212
+ if (child.exitCode != null || child.signalCode != null) {
213
+ resolve();
214
+ return;
215
+ }
216
+ const finish = () => {
217
+ clearTimeout(timer);
218
+ child.off?.('error', fail);
219
+ resolve();
220
+ };
221
+ const fail = (error) => {
222
+ clearTimeout(timer);
223
+ child.off?.('close', finish);
224
+ reject(error);
225
+ };
226
+ const timer = setTimeout(() => {
227
+ child.off?.('close', finish);
228
+ child.off?.('error', fail);
229
+ reject(new Error('process did not exit'));
230
+ }, deadlineMs);
231
+ if (child.once) {
232
+ child.once('close', finish);
233
+ child.once('error', fail);
234
+ return;
235
+ }
236
+ if (child.on) {
237
+ child.on('close', finish);
238
+ child.on('error', fail);
239
+ return;
240
+ }
241
+ clearTimeout(timer);
242
+ resolve();
243
+ });
244
+ }
245
+
246
+ export async function killProcessTree(child, platform = process.platform, extras = {}) {
247
+ const pid = child?.pid;
248
+ if (pid == null || pid <= 0) {
249
+ return;
250
+ }
251
+ const deadlineMs = extras.deadlineMs ?? KILL_WAIT_MS;
252
+ if (platform === 'win32') {
253
+ const spawnImpl = extras.spawn ?? spawn;
254
+ const killer = spawnImpl(
255
+ extras.taskkillPath ?? taskkillPath(extras.env),
256
+ ['/PID', String(pid), '/T', '/F'],
257
+ {
258
+ shell: false,
259
+ windowsHide: true,
260
+ stdio: 'ignore',
261
+ timeout: deadlineMs,
262
+ killSignal: 'SIGKILL'
263
+ }
264
+ );
265
+ await Promise.all([waitForClose(killer, deadlineMs), waitForClose(child, deadlineMs)]);
266
+ if (killer.exitCode !== 0) throw new Error('taskkill could not stop the update process tree.');
267
+ return;
268
+ }
269
+ try {
270
+ process.kill(-pid, 'SIGKILL');
271
+ } catch {
272
+ try {
273
+ child.kill('SIGKILL');
274
+ } catch {
275
+ try {
276
+ process.kill(pid, 'SIGKILL');
277
+ } catch {
278
+ // The process already exited.
279
+ }
280
+ }
281
+ }
282
+ }
283
+
284
+ export function createRunCommand(spawnImpl, treeKiller = killProcessTree, selfKill) {
285
+ const killHelperGroup = selfKill ?? ((groupPid) => process.kill(groupPid, 'SIGKILL'));
286
+ return function runCommand(command, args, options = {}) {
287
+ return new Promise((resolve) => {
288
+ let settled = false;
289
+ let timingOut = false;
290
+ let timer;
291
+ let stdout = '';
292
+ let stderr = '';
293
+ const platform = options.platform ?? process.platform;
294
+ const managed = isManagedUpdate(options.env);
295
+ const killWaitMs = options.killWaitMs ?? KILL_WAIT_MS;
296
+ const done = (result) => {
297
+ if (settled) {
298
+ return;
299
+ }
300
+ settled = true;
301
+ clearTimeout(timer);
302
+ resolve(result);
303
+ };
304
+
305
+ let child;
306
+ try {
307
+ child = spawnImpl(command, args, {
308
+ cwd: options.cwd,
309
+ env: options.env,
310
+ shell: false,
311
+ windowsHide: true,
312
+ detached: platform !== 'win32' && !managed,
313
+ stdio: ['ignore', 'pipe', 'pipe']
314
+ });
315
+ } catch (error) {
316
+ done({
317
+ status: 1,
318
+ stdout: '',
319
+ stderr: publicError(error),
320
+ error,
321
+ timedOut: false
322
+ });
323
+ return;
324
+ }
325
+
326
+ child.stdout?.setEncoding('utf8');
327
+ child.stderr?.setEncoding('utf8');
328
+ child.stdout?.on('data', (chunk) => {
329
+ stdout = appendBounded(stdout, chunk);
330
+ });
331
+ child.stderr?.on('data', (chunk) => {
332
+ stderr = appendBounded(stderr, chunk);
333
+ });
334
+ child.on('error', (error) => {
335
+ if (timingOut) return;
336
+ done({
337
+ status: 1,
338
+ stdout,
339
+ stderr: appendBounded(stderr, publicError(error)),
340
+ error,
341
+ timedOut: false
342
+ });
343
+ });
344
+ child.on('close', (status) => {
345
+ if (!timingOut) done({ status: status ?? 1, stdout, stderr, timedOut: false });
346
+ });
347
+
348
+ if (options.timeout) {
349
+ timer = setTimeout(() => {
350
+ void finishTimeout();
351
+ }, options.timeout);
352
+ }
353
+
354
+ async function finishTimeout() {
355
+ if (settled) {
356
+ return;
357
+ }
358
+ timingOut = true;
359
+ if (managed && platform !== 'win32') {
360
+ try {
361
+ killHelperGroup(-process.pid);
362
+ } catch {
363
+ // Tests inject a no-op killer; production SIGKILL does not return.
364
+ }
365
+ done({
366
+ status: 1,
367
+ stdout,
368
+ stderr: appendBounded(stderr, 'Timed out.'),
369
+ timedOut: true,
370
+ uncertain: true
371
+ });
372
+ return;
373
+ }
374
+ let uncertain = false;
375
+ try {
376
+ await treeKiller(child, platform, {
377
+ spawn: spawnImpl,
378
+ env: options.env,
379
+ deadlineMs: killWaitMs
380
+ });
381
+ } catch {
382
+ uncertain = true;
383
+ }
384
+ child.stdout?.destroy();
385
+ child.stderr?.destroy();
386
+ try {
387
+ await waitForClose(child, killWaitMs);
388
+ } catch {
389
+ uncertain = true;
390
+ }
391
+ done({
392
+ status: 1,
393
+ stdout,
394
+ stderr: appendBounded(stderr, 'Timed out.'),
395
+ timedOut: true,
396
+ uncertain
397
+ });
398
+ }
399
+ });
400
+ };
401
+ }
402
+
403
+ export function createHost(overrides = {}) {
404
+ const env = overrides.env ?? process.env;
405
+ const platform = overrides.platform ?? process.platform;
406
+ const execPath = overrides.execPath ?? process.execPath;
407
+ const packageRoot = overrides.packageRoot ?? PACKAGE_ROOT;
408
+ const readFile = overrides.readFile ?? ((file, encoding) => readFileSync(file, encoding));
409
+ const isFile = overrides.isFile ?? defaultIsFile;
410
+ const host = {
411
+ env,
412
+ platform,
413
+ execPath,
414
+ pid: overrides.pid ?? process.pid,
415
+ packageRoot,
416
+ currentVersion: overrides.currentVersion,
417
+ tmpdir: overrides.tmpdir ?? (() => os.tmpdir()),
418
+ homedir: overrides.homedir ?? (() => os.homedir()),
419
+ fetch: overrides.fetch ?? globalThis.fetch.bind(globalThis),
420
+ runCommand: overrides.runCommand ?? createRunCommand(overrides.spawn ?? spawn),
421
+ isFile,
422
+ readFile,
423
+ realpath: overrides.realpath ?? defaultRealpath,
424
+ findExecutable:
425
+ overrides.findExecutable ?? ((name) => findExecutable(name, env, platform, isFile)),
426
+ open: overrides.open ?? ((file, flags) => fsPromises.open(file, flags)),
427
+ unlink: overrides.unlink ?? ((file) => fsPromises.unlink(file)),
428
+ writeStdout: overrides.writeStdout ?? ((text) => process.stdout.write(text)),
429
+ writeStderr: overrides.writeStderr ?? ((text) => process.stderr.write(text))
430
+ };
431
+ if (host.currentVersion === undefined) {
432
+ host.currentVersion = readCurrentVersion(host);
433
+ }
434
+ return host;
435
+ }
436
+
437
+ export function readCurrentVersion(host) {
438
+ const configured = parseVersionField(host.currentVersion);
439
+ if (configured) {
440
+ return configured;
441
+ }
442
+ try {
443
+ const manifest = JSON.parse(host.readFile(path.join(host.packageRoot, 'package.json'), 'utf8'));
444
+ return parseVersionField(manifest?.version);
445
+ } catch {
446
+ return '';
447
+ }
448
+ }
449
+
450
+ export async function detectInstall(host) {
451
+ const packageRoot = path.resolve(host.packageRoot);
452
+ for (const manager of MANAGERS) {
453
+ const invocation = resolveManagerInvocation(manager.name, host);
454
+ if (!invocation) {
455
+ continue;
456
+ }
457
+ const globalRoot = await queryGlobalRoot(manager, invocation, host);
458
+ if (!globalRoot) {
459
+ continue;
460
+ }
461
+ if (isExactGlobalPackage(packageRoot, globalRoot, host)) {
462
+ return {
463
+ supported: true,
464
+ manager: manager.name,
465
+ command: invocation.command,
466
+ argsPrefix: invocation.argsPrefix,
467
+ globalRoot,
468
+ installArgs: manager.installArgs
469
+ };
470
+ }
471
+ }
472
+ return { supported: false };
473
+ }
474
+
475
+ export async function checkForUpdate(host) {
476
+ const currentVersion = readCurrentVersion(host);
477
+ const install = await detectInstall(host);
478
+ if (!install.supported) {
479
+ return makePayload({
480
+ status: 'unavailable',
481
+ currentVersion,
482
+ message: UNSUPPORTED_MESSAGE
483
+ });
484
+ }
485
+ const channel = releaseChannel(currentVersion);
486
+ const registryVersion = await fetchChannelVersion(host, channel, currentVersion);
487
+ const decision = channelUpdate(currentVersion, registryVersion);
488
+ if (decision.status === 'idle') {
489
+ return makePayload({ status: 'idle', currentVersion });
490
+ }
491
+ return makePayload({
492
+ status: 'available',
493
+ currentVersion,
494
+ version: decision.version
495
+ });
496
+ }
497
+
498
+ export async function installUpdate(host) {
499
+ const currentVersion = readCurrentVersion(host);
500
+ const detected = await detectInstall(host);
501
+ if (!detected.supported) {
502
+ return makePayload({
503
+ status: 'unavailable',
504
+ currentVersion,
505
+ message: UNSUPPORTED_MESSAGE
506
+ });
507
+ }
508
+ const lockPath = updateLockPath(host, detected.globalRoot);
509
+ try {
510
+ return await withUpdateLock(host, lockPath, async () => {
511
+ const checked = await checkForUpdate(host);
512
+ if (checked.status !== 'available') {
513
+ return { payload: checked };
514
+ }
515
+ const install = await detectInstall(host);
516
+ if (!install.supported) {
517
+ return {
518
+ payload: makePayload({
519
+ status: 'unavailable',
520
+ currentVersion,
521
+ message: UNSUPPORTED_MESSAGE
522
+ })
523
+ };
524
+ }
525
+ if (!isAllowedVersion(checked.version, releaseChannel(currentVersion))) {
526
+ return {
527
+ payload: makePayload({
528
+ status: 'error',
529
+ currentVersion,
530
+ version: checked.version,
531
+ error: 'Refusing to install a version that failed validation.'
532
+ })
533
+ };
534
+ }
535
+ if (updateLockPath(host, install.globalRoot) !== lockPath) {
536
+ throw new Error('The installation location changed during the update check. Try again.');
537
+ }
538
+ const result = await host.runCommand(
539
+ install.command,
540
+ [...install.argsPrefix, ...install.installArgs(checked.version)],
541
+ {
542
+ cwd: host.homedir(),
543
+ env: host.env,
544
+ platform: host.platform,
545
+ timeout: INSTALL_TIMEOUT_MS
546
+ }
547
+ );
548
+ if (result.timedOut || result.uncertain) {
549
+ return {
550
+ retainLock: true,
551
+ payload: makePayload({
552
+ status: 'error',
553
+ currentVersion,
554
+ version: checked.version,
555
+ error: timeoutRecoveryMessage(lockPath)
556
+ })
557
+ };
558
+ }
559
+ if ((result.status ?? 1) !== 0) {
560
+ return {
561
+ payload: makePayload({
562
+ status: 'error',
563
+ currentVersion,
564
+ version: checked.version,
565
+ error: installFailureMessage(
566
+ `${result.stderr ?? ''}\n${result.stdout ?? ''}`,
567
+ host.platform
568
+ )
569
+ })
570
+ };
571
+ }
572
+ return {
573
+ payload: makePayload({
574
+ status: 'installed',
575
+ currentVersion,
576
+ version: checked.version,
577
+ message: RELAUNCH_MESSAGE
578
+ })
579
+ };
580
+ });
581
+ } catch (error) {
582
+ return makePayload({
583
+ status: 'error',
584
+ currentVersion,
585
+ error: publicError(error)
586
+ });
587
+ }
588
+ }
589
+
590
+ export async function runUpdateApi(command, host = createHost()) {
591
+ const currentVersion = readCurrentVersion(host);
592
+ try {
593
+ if (command !== 'check' && command !== 'install') {
594
+ return {
595
+ exitCode: 1,
596
+ payload: makePayload({
597
+ status: 'error',
598
+ currentVersion,
599
+ error: 'Usage: check or install.'
600
+ })
601
+ };
602
+ }
603
+ const payload = command === 'check' ? await checkForUpdate(host) : await installUpdate(host);
604
+ return {
605
+ exitCode: payload.status === 'error' ? 1 : 0,
606
+ payload
607
+ };
608
+ } catch (error) {
609
+ return {
610
+ exitCode: 1,
611
+ payload: makePayload({
612
+ status: 'error',
613
+ currentVersion,
614
+ error: publicError(error)
615
+ })
616
+ };
617
+ }
618
+ }
619
+
620
+ export async function runUpdateCli(parsed, host = createHost()) {
621
+ if (parsed.kind === 'help') {
622
+ host.writeStdout(HELP);
623
+ return 0;
624
+ }
625
+ if (parsed.kind === 'invalid') {
626
+ host.writeStderr(`sprocket: ${parsed.error}\nTry \`sprocket update --help\`.\n`);
627
+ return 1;
628
+ }
629
+ try {
630
+ const payload = parsed.check ? await checkForUpdate(host) : await installUpdate(host);
631
+ if (payload.status === 'error') {
632
+ host.writeStderr(`sprocket: ${payload.error}\n`);
633
+ return 1;
634
+ }
635
+ host.writeStdout(formatCli(payload, parsed.check));
636
+ return payload.status === 'unavailable' ? 1 : 0;
637
+ } catch (error) {
638
+ host.writeStderr(`sprocket: ${publicError(error)}\n`);
639
+ return 1;
640
+ }
641
+ }
642
+
643
+ export function registryUrl(env = {}) {
644
+ const values = [env.npm_config_registry, env.NPM_CONFIG_REGISTRY]
645
+ .map((value) => asText(value).trim())
646
+ .filter(Boolean);
647
+ for (const value of values) {
648
+ let url;
649
+ try {
650
+ url = new URL(value);
651
+ } catch {
652
+ throw new Error('Package updates require a valid HTTPS npm registry URL.');
653
+ }
654
+ if (url.protocol !== 'https:' || /\s/.test(value) || url.search || url.hash) {
655
+ throw new Error('Package updates require a valid HTTPS npm registry URL.');
656
+ }
657
+ }
658
+ return values[0]?.replace(/\/$/, '') ?? DEFAULT_REGISTRY;
659
+ }
660
+
661
+ export function channelManifestUrl(registry, channel, name = PACKAGE_NAME) {
662
+ const base = registry.replace(/\/$/, '');
663
+ const encodedName = encodeURIComponent(name);
664
+ return `${base}/${encodedName}/${encodeURIComponent(channel)}`;
665
+ }
666
+
667
+ export async function withUpdateLock(host, lockPath, operation) {
668
+ let handle;
669
+ try {
670
+ handle = await host.open(lockPath, 'wx');
671
+ } catch (error) {
672
+ if (error?.code === 'EEXIST') {
673
+ throw new Error(
674
+ `Another Sprocket update is already running. If it is not, delete ${lockPath} and retry.`
675
+ );
676
+ }
677
+ if (error?.code === 'EACCES' || error?.code === 'EPERM') {
678
+ throw new Error(`Cannot write the update lock at ${lockPath}. Check permissions and retry.`);
679
+ }
680
+ throw error;
681
+ }
682
+ let retainLock = false;
683
+ try {
684
+ await handle.writeFile(String(host.pid));
685
+ const outcome = await operation();
686
+ retainLock = outcome?.retainLock === true;
687
+ return outcome?.payload ?? outcome;
688
+ } finally {
689
+ await handle.close().catch(() => {});
690
+ if (!retainLock) {
691
+ await host.unlink(lockPath).catch(() => {});
692
+ }
693
+ }
694
+ }
695
+
696
+ function formatCli(payload, check) {
697
+ if (payload.status === 'unavailable') {
698
+ return `${payload.message ?? UNSUPPORTED_MESSAGE}\n`;
699
+ }
700
+ if (payload.status === 'idle') {
701
+ return `Sprocket ${payload.currentVersion} is up to date (${releaseChannel(payload.currentVersion)} channel).\n`;
702
+ }
703
+ if (payload.status === 'available') {
704
+ const lines = [
705
+ `Sprocket ${payload.version} is available (currently ${payload.currentVersion}).`
706
+ ];
707
+ if (check) {
708
+ lines.push('Run `sprocket update` to install it.');
709
+ }
710
+ return `${lines.join('\n')}\n`;
711
+ }
712
+ if (payload.status === 'installed') {
713
+ return `Updated Sprocket to ${payload.version}.\n${payload.message ?? RELAUNCH_MESSAGE}\n`;
714
+ }
715
+ return '';
716
+ }
717
+
718
+ async function fetchChannelVersion(host, channel, currentVersion) {
719
+ const url = channelManifestUrl(registryUrl(host.env), channel);
720
+ let response;
721
+ try {
722
+ response = await host.fetch(url, {
723
+ redirect: 'error',
724
+ headers: {
725
+ accept: 'application/json',
726
+ 'user-agent': `sprocket/${currentVersion || '0'}`
727
+ },
728
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
729
+ });
730
+ } catch {
731
+ throw new Error('Could not reach the npm registry. Try again.');
732
+ }
733
+ if (!response.ok) {
734
+ throw new Error(`npm registry returned HTTP ${response.status}.`);
735
+ }
736
+ let body;
737
+ try {
738
+ body = await response.json();
739
+ } catch {
740
+ throw new Error('npm registry returned an invalid package document.');
741
+ }
742
+ const version = parseVersionField(body?.version);
743
+ if (!isAllowedVersion(version, channel)) {
744
+ throw new Error(`npm dist-tag '${channel}' does not point at a valid ${channel} release.`);
745
+ }
746
+ return version;
747
+ }
748
+
749
+ function isExactGlobalPackage(packageRoot, globalRoot, host) {
750
+ const expected = globalPackageDir(globalRoot);
751
+ const actual = pathIdentities(host, packageRoot);
752
+ for (const candidate of pathIdentities(host, expected)) {
753
+ if (actual.has(candidate)) {
754
+ return true;
755
+ }
756
+ }
757
+ return false;
758
+ }
759
+
760
+ function pathIdentities(host, file) {
761
+ const identities = new Set([normalizePath(file, host.platform)]);
762
+ identities.add(normalizePath(tryRealpath(host, file), host.platform));
763
+ return identities;
764
+ }
765
+
766
+ function normalizePath(file, platform) {
767
+ const resolved = path.resolve(file);
768
+ return platform === 'win32' ? resolved.toLowerCase() : resolved;
769
+ }
770
+
771
+ function resolveManagerInvocation(manager, host) {
772
+ const execDir = path.dirname(host.execPath);
773
+ const execBase = path.basename(host.execPath, '.exe').toLowerCase();
774
+ if (manager === 'bun' && execBase === 'bun') {
775
+ return { command: host.execPath, argsPrefix: [] };
776
+ }
777
+ if (manager === 'npm') {
778
+ const npmCli = path.join(execDir, 'node_modules', 'npm', 'bin', 'npm-cli.js');
779
+ if (host.isFile(npmCli)) {
780
+ return { command: host.execPath, argsPrefix: [npmCli] };
781
+ }
782
+ const npmExecPath = asText(host.env.npm_execpath);
783
+ if (
784
+ npmExecPath &&
785
+ isAbsolutePath(npmExecPath, host.platform) &&
786
+ host.isFile(npmExecPath) &&
787
+ /npm-cli\.js$/i.test(npmExecPath)
788
+ ) {
789
+ return { command: host.execPath, argsPrefix: [npmExecPath] };
790
+ }
791
+ }
792
+ const found = host.findExecutable(manager);
793
+ if (!found) {
794
+ return null;
795
+ }
796
+ return spawnPlan(found, manager, host);
797
+ }
798
+
799
+ function spawnPlan(binary, manager, host) {
800
+ if (/\.(cjs|js|mjs)$/i.test(binary)) {
801
+ return { command: host.execPath, argsPrefix: [binary] };
802
+ }
803
+ if (host.platform === 'win32' && /\.(cmd|bat)$/i.test(binary)) {
804
+ const jsCli = jsCliBesideShim(binary, manager, host);
805
+ if (jsCli) {
806
+ return { command: host.execPath, argsPrefix: [jsCli] };
807
+ }
808
+ return null;
809
+ }
810
+ return { command: binary, argsPrefix: [] };
811
+ }
812
+
813
+ function jsCliBesideShim(binary, manager, host) {
814
+ const dir = path.dirname(binary);
815
+ const candidates =
816
+ manager === 'npm'
817
+ ? [path.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'), path.join(dir, 'npm-cli.js')]
818
+ : manager === 'pnpm'
819
+ ? [path.join(dir, 'pnpm.cjs'), path.join(dir, 'node_modules', 'pnpm', 'bin', 'pnpm.cjs')]
820
+ : manager === 'yarn'
821
+ ? [path.join(dir, 'yarn.js'), path.join(dir, 'node_modules', 'yarn', 'bin', 'yarn.js')]
822
+ : [];
823
+ return candidates.find((candidate) => host.isFile(candidate));
824
+ }
825
+
826
+ async function queryGlobalRoot(manager, invocation, host) {
827
+ const result = await host.runCommand(
828
+ invocation.command,
829
+ [...invocation.argsPrefix, ...manager.queryArgs],
830
+ {
831
+ cwd: host.homedir(),
832
+ env: {
833
+ ...host.env,
834
+ COREPACK_ENABLE_NETWORK: '0',
835
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0'
836
+ },
837
+ platform: host.platform,
838
+ timeout: QUERY_TIMEOUT_MS
839
+ }
840
+ );
841
+ if ((result.status ?? 1) !== 0) {
842
+ return '';
843
+ }
844
+ const globalRoot = manager.globalRoot(result.stdout ?? '');
845
+ if (!globalRoot || globalRoot.includes('\0')) {
846
+ return '';
847
+ }
848
+ return path.resolve(globalRoot);
849
+ }
850
+
851
+ function parseComparable(version) {
852
+ const text = asText(version);
853
+ if (STABLE_VERSION.test(text)) {
854
+ const [major, minor, patch] = text.split('.');
855
+ return { core: [Number(major), Number(minor), Number(patch)], pre: [] };
856
+ }
857
+ if (!CANARY_VERSION.test(text)) {
858
+ return null;
859
+ }
860
+ const marker = '-canary.';
861
+ const index = text.indexOf(marker);
862
+ const [major, minor, patch] = text.slice(0, index).split('.');
863
+ return {
864
+ core: [Number(major), Number(minor), Number(patch)],
865
+ pre: ['canary', ...text.slice(index + marker.length).split('.')]
866
+ };
867
+ }
868
+
869
+ function comparePrerelease(left, right) {
870
+ if (left.length === 0 && right.length === 0) {
871
+ return 0;
872
+ }
873
+ if (left.length === 0) {
874
+ return 1;
875
+ }
876
+ if (right.length === 0) {
877
+ return -1;
878
+ }
879
+ const length = Math.max(left.length, right.length);
880
+ for (let index = 0; index < length; index += 1) {
881
+ if (index >= left.length) {
882
+ return -1;
883
+ }
884
+ if (index >= right.length) {
885
+ return 1;
886
+ }
887
+ const comparison = compareIdentifier(left[index], right[index]);
888
+ if (comparison !== 0) {
889
+ return comparison;
890
+ }
891
+ }
892
+ return 0;
893
+ }
894
+
895
+ function compareIdentifier(left, right) {
896
+ const leftNumeric = NUMERIC_IDENTIFIER.test(left);
897
+ const rightNumeric = NUMERIC_IDENTIFIER.test(right);
898
+ if (leftNumeric && rightNumeric) {
899
+ const delta = Number(left) - Number(right);
900
+ if (delta < 0) {
901
+ return -1;
902
+ }
903
+ if (delta > 0) {
904
+ return 1;
905
+ }
906
+ return 0;
907
+ }
908
+ if (leftNumeric) {
909
+ return -1;
910
+ }
911
+ if (rightNumeric) {
912
+ return 1;
913
+ }
914
+ if (left < right) {
915
+ return -1;
916
+ }
917
+ if (left > right) {
918
+ return 1;
919
+ }
920
+ return 0;
921
+ }
922
+
923
+ function installFailureMessage(output, platform) {
924
+ if (isWindowsBusyExecutable(output, platform)) {
925
+ return 'Windows cannot replace Sprocket while it is running. Stop Sprocket, then run `sprocket update` again.';
926
+ }
927
+ const lines = output
928
+ .split(/\r?\n/)
929
+ .map((line) => line.trim())
930
+ .filter(Boolean);
931
+ const useful = lines
932
+ .filter((line) => /npm ERR!|error|ERR!|EACCES|EPERM|EBUSY|denied|ELIFECYCLE/i.test(line))
933
+ .slice(-5);
934
+ const detail = useful.join(' ') || 'the package manager failed';
935
+ return `Failed to install the update: ${sanitize(detail)}`;
936
+ }
937
+
938
+ export function isWindowsBusyExecutable(output, platform) {
939
+ if (platform !== 'win32') {
940
+ return false;
941
+ }
942
+ return (
943
+ /sprocket\.exe/i.test(output) &&
944
+ /(?:EBUSY|EPERM|EACCES|being used by another process|resource busy|locked)/i.test(output)
945
+ );
946
+ }
947
+
948
+ function publicError(error) {
949
+ if (error instanceof Error) {
950
+ return sanitize(error.message);
951
+ }
952
+ return sanitize(asText(error));
953
+ }
954
+
955
+ function sanitize(text) {
956
+ return asText(text).replace(/\s+/g, ' ').trim().slice(0, 500);
957
+ }
958
+
959
+ function isAbsolutePath(file, platform) {
960
+ if (platform === 'win32') {
961
+ return path.win32.isAbsolute(file) || /^[a-zA-Z]:[\\/]/.test(file) || file.startsWith('\\\\');
962
+ }
963
+ return path.isAbsolute(file);
964
+ }
965
+
966
+ function findExecutable(name, env, platform, isFile) {
967
+ const pathValue = asText(env.PATH || env.Path || env.path);
968
+ const directories = pathValue.split(path.delimiter);
969
+ const extensions =
970
+ platform === 'win32'
971
+ ? asText(env.PATHEXT || '.EXE;.CMD;.BAT;.COM')
972
+ .split(';')
973
+ .filter(Boolean)
974
+ : [''];
975
+ for (const directory of directories) {
976
+ if (!directory || !isAbsolutePath(directory, platform)) {
977
+ continue;
978
+ }
979
+ if (platform === 'win32') {
980
+ const exact = path.join(directory, name);
981
+ if (isFile(exact)) {
982
+ return exact;
983
+ }
984
+ for (const extension of extensions) {
985
+ const candidate = path.join(directory, name + extension);
986
+ if (isFile(candidate)) {
987
+ return candidate;
988
+ }
989
+ }
990
+ continue;
991
+ }
992
+ const candidate = path.join(directory, name);
993
+ if (isFile(candidate)) {
994
+ return candidate;
995
+ }
996
+ }
997
+ return undefined;
998
+ }
999
+
1000
+ function defaultIsFile(file) {
1001
+ try {
1002
+ return statSync(file).isFile();
1003
+ } catch {
1004
+ return false;
1005
+ }
1006
+ }
1007
+
1008
+ function defaultRealpath(file) {
1009
+ return realpathSync(file);
1010
+ }
1011
+
1012
+ function tryRealpath(host, file) {
1013
+ try {
1014
+ return host.realpath(file);
1015
+ } catch {
1016
+ return file;
1017
+ }
1018
+ }
1019
+
1020
+ function firstAbsolutePath(text) {
1021
+ for (const line of asText(text).split(/\r?\n/)) {
1022
+ const trimmed = line.trim();
1023
+ if (!trimmed || trimmed.includes('\0')) {
1024
+ continue;
1025
+ }
1026
+ if (path.isAbsolute(trimmed) || /^[a-zA-Z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\\\')) {
1027
+ return trimmed;
1028
+ }
1029
+ }
1030
+ return '';
1031
+ }
1032
+
1033
+ function appendBounded(previous, chunk) {
1034
+ const next = previous + chunk;
1035
+ return next.length > OUTPUT_LIMIT ? next.slice(next.length - OUTPUT_LIMIT) : next;
1036
+ }