@hit-sudomaker/ccw 0.4.0 → 0.5.0

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/dist/programs.js DELETED
@@ -1,778 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import path from 'node:path';
3
- import { knownTitle } from './titles.js';
4
- import { officeIntegration } from './management-catalog.js';
5
- import { errorCode, isObject, succeeded } from './machine.js';
6
- import { cancelled, claudeEnvironment, claudeRunning, success } from './model.js';
7
- import { npmInstallArgs, npmUninstallArgs, NPM_OFFICIAL, resolveNpmView } from './npm-registry.js';
8
- import { channelCanPinVersion, containsPath, freezeNpmScope, freezeProgramScope, identifyProgramChannel, maintainProgramChannel, npmBinary, npmGlobalRoot, npmScopeArgs, npmVersion, officeBinary, PROGRAM_PACKAGES, programPackageAbsent, removeProgramChannel, samePath, } from './program-channels.js';
9
- export async function programs(ctx, kind) {
10
- const values = new Map();
11
- const problems = [];
12
- const canonicalPaths = [];
13
- const native = kind === 'claude'
14
- ? path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'claude.exe' : 'claude')
15
- : officeBinary(ctx);
16
- const add = (value) => values.set(`${kind}:${value.channel}:${value.binary}`, value);
17
- try {
18
- const version = await npmVersion(ctx, PROGRAM_PACKAGES[kind]);
19
- if (version !== null) {
20
- const root = await npmGlobalRoot(ctx);
21
- const binary = await npmBinary(ctx, kind, root);
22
- add({
23
- kind,
24
- channel: 'npm',
25
- binary,
26
- version,
27
- npmRoot: root,
28
- packageName: PROGRAM_PACKAGES[kind],
29
- isMissing: (await ctx.machine.treeStamp(binary)) === null,
30
- });
31
- canonicalPaths.push((await ctx.machine.realpath(binary)) ?? binary);
32
- }
33
- }
34
- catch (error) {
35
- if (errorCode(error) === 'npm-changed')
36
- throw error;
37
- problems.push(errorCode(error));
38
- }
39
- const candidates = new Set([native, ...(await ctx.machine.locate(kind))]);
40
- for (const candidate of candidates) {
41
- let binary = candidate;
42
- if (ctx.platform === 'win32' && binary.endsWith('.exe')) {
43
- const shim = await ctx.machine.read(binary.slice(0, -4) + '.shim');
44
- const target = shim === null ? undefined : /^path\s*=\s*"([^"]+)"/m.exec(shim)?.[1];
45
- if (target !== undefined &&
46
- path.isAbsolute(target) &&
47
- /\/apps\/officecli\/[^/]+\/(?:[^/]+\/)*officecli(?:\.exe)?$/.test(target.replaceAll('\\', '/').toLowerCase()))
48
- binary = target;
49
- }
50
- const canonical = await ctx.machine.realpath(binary);
51
- if (canonical === null ||
52
- canonicalPaths.some(file => samePath(ctx, file, canonical)) ||
53
- [...values.values()].some(program => program.npmRoot !== undefined &&
54
- containsPath(ctx, path.join(program.npmRoot, program.packageName), canonical)))
55
- continue;
56
- if ([kind, `${kind}.cmd`, `${kind}.ps1`].includes(path.basename(binary).toLowerCase()) &&
57
- [...values.values()].some(program => program.npmRoot !== undefined &&
58
- samePath(ctx, program.npmRoot, path.join(path.dirname(binary), 'node_modules'))))
59
- continue;
60
- add({ kind, binary, version: null, ...(await identifyProgramChannel(ctx, kind, binary, canonical, native)) });
61
- canonicalPaths.push(canonical);
62
- }
63
- return {
64
- values,
65
- problems,
66
- items: [...values.entries()].map(([id, value]) => ({
67
- id,
68
- name: kind,
69
- title: knownTitle(kind),
70
- kind,
71
- canInstall: true,
72
- location: value.binary,
73
- facts: [
74
- // 渠道与版本各占一条事实;展示层直读结构化字段,不反解拼接文本
75
- { code: value.isMissing ? 'program-missing' : 'program-exists', detail: value.channel },
76
- ...(value.version ? [{ code: 'program-version', detail: value.version }] : []),
77
- ],
78
- actions: value.channel === 'manual'
79
- ? kind === 'officecli'
80
- ? ['connect']
81
- : []
82
- : [
83
- ...(value.isMissing
84
- ? ['install']
85
- : [
86
- 'update',
87
- 'reinstall',
88
- ...(kind === 'officecli' ? ['connect'] : ['login']),
89
- ]),
90
- 'uninstall',
91
- ],
92
- })),
93
- };
94
- }
95
- export async function claudeCommand(ctx, args, isInteractive = false) {
96
- const candidates = await programs(ctx, 'claude');
97
- const program = [...candidates.values.values()].find(value => !value.isMissing && !value.binary.endsWith('.cmd'));
98
- if (program === undefined)
99
- throw new Error('claude-not-installed');
100
- return executeClaude(ctx, program.binary, args, { isInteractive });
101
- }
102
- function executeClaude(ctx, binary, args, options = {}) {
103
- return ctx.machine.execute(binary.endsWith('.js') ? process.execPath : binary, binary.endsWith('.js') ? [binary, ...args] : args, { env: claudeEnvironment(ctx), cwd: ctx.home, ...options });
104
- }
105
- /** 计划预览变更码按动作显式枚举:模板串会产生字典外码,登录复用既有官方登录入口码 */
106
- const PROGRAM_ACTION_CHANGE = {
107
- install: 'program-install',
108
- update: 'program-update',
109
- reinstall: 'program-reinstall',
110
- login: 'login-browser',
111
- };
112
- export async function prepareProgram(ctx, kind, selection, program) {
113
- if (selection.action === 'uninstall')
114
- return prepareProgramRemoval(ctx, kind, program, !selection.removeData);
115
- if (kind === 'claude' && program === undefined && selection.action === 'install')
116
- return prepareClaudeInstall(ctx);
117
- if (kind === 'officecli' && (program === undefined || program.channel === 'native'))
118
- return prepareOfficeNative(ctx, selection, program);
119
- const action = selection.action;
120
- if (program === undefined)
121
- throw new Error('program-changed');
122
- const channel = program.channel;
123
- if (channel === 'manual')
124
- throw new Error('channel-not-supported');
125
- if (action !== 'install' && action !== 'update' && action !== 'reinstall' && action !== 'login')
126
- throw new Error('action-unavailable');
127
- if (program.channel === 'npm' && action === 'install' && !program.isMissing)
128
- throw new Error('program-changed');
129
- const stamp = await ctx.machine.treeStamp(program.binary);
130
- let targetVersion = null;
131
- let targetRegistry;
132
- if (kind === 'claude' && action !== 'login') {
133
- if (!channelCanPinVersion(channel))
134
- throw new Error('pinned-version-channel-unsupported');
135
- const release = await stableClaudeVersion(ctx);
136
- targetVersion = release.value;
137
- targetRegistry = release.registry;
138
- const current = program.version ?? (await claudeVersion(ctx, program.binary));
139
- if (current === null)
140
- throw new Error('program-version-unconfirmed');
141
- if (current !== null && compareVersions(current, targetVersion) > 0)
142
- throw new Error('newer-version-preserved');
143
- }
144
- if (channel === 'npm' && action !== 'login') {
145
- const release = kind === 'claude' && targetVersion !== null && targetRegistry !== undefined
146
- ? { value: targetVersion, registry: targetRegistry }
147
- : await resolveNpmView(ctx.machine, `${PROGRAM_PACKAGES[kind]}@latest`, 'version', exactVersion);
148
- if (release === null)
149
- throw new Error('invalid-release');
150
- targetVersion = release.value;
151
- targetRegistry = release.registry;
152
- if (program.version && compareVersions(program.version, release.value) > 0)
153
- throw new Error('newer-version-preserved');
154
- }
155
- const scope = await freezeProgramScope(ctx, program);
156
- let isComplete = false;
157
- let isCommandCompleted = false;
158
- let commandStamp;
159
- let verifiedBinary;
160
- let verifiedStamp = null;
161
- const operation = {
162
- targetVersion,
163
- ...(targetRegistry !== undefined ? { targetRegistry } : {}),
164
- get changes() {
165
- return [
166
- {
167
- code: isCommandCompleted ? 'program-installation-confirm' : PROGRAM_ACTION_CHANGE[action],
168
- detail: `${program.binary} · ${channel}${targetVersion ? ` · ${targetVersion}` : ''}`,
169
- },
170
- { code: 'keep-user-data' },
171
- ];
172
- },
173
- async run(report, signal) {
174
- cancelled(signal);
175
- if (isCommandCompleted) {
176
- if (commandStamp === undefined)
177
- throw new Error('program-installation-unconfirmed');
178
- if ((await ctx.machine.treeStamp(program.binary)) !== commandStamp)
179
- throw new Error('program-changed');
180
- }
181
- else {
182
- if ((await ctx.machine.treeStamp(program.binary)) !== stamp)
183
- throw new Error('program-changed');
184
- await scope.verify();
185
- }
186
- if (action === 'login') {
187
- success(await executeClaude(ctx, program.binary, ['auth', 'login'], { isInteractive: true }), 'login-failed');
188
- const status = JSON.parse(success(await executeClaude(ctx, program.binary, ['auth', 'status', '--json'])));
189
- if (!isObject(status) || status.loggedIn !== true)
190
- throw new Error('login-unconfirmed');
191
- isComplete = true;
192
- report({ state: 'done', code: 'logged-in' });
193
- return;
194
- }
195
- if (!isCommandCompleted)
196
- await maintainProgramChannel(ctx, program, scope, action, targetVersion, targetRegistry, async () => {
197
- isCommandCompleted = true;
198
- report({ state: 'done', code: 'package-command-completed' });
199
- try {
200
- commandStamp = await ctx.machine.treeStamp(program.binary);
201
- }
202
- catch (error) {
203
- throw new Error('program-installation-unconfirmed', { cause: error });
204
- }
205
- });
206
- if (channel === 'npm' || channel === 'brew')
207
- await scope.verify();
208
- const found = await programs(ctx, kind);
209
- let selected;
210
- for (const value of found.values.values())
211
- if (await scope.matches(value)) {
212
- selected = value;
213
- break;
214
- }
215
- if (selected === undefined || (await ctx.machine.treeStamp(selected.binary)) === null)
216
- throw new Error('program-not-ready');
217
- if (channel === 'npm' && selected.version !== targetVersion)
218
- throw new Error('program-not-ready');
219
- if (kind === 'claude' && (await claudeVersion(ctx, selected.binary)) !== targetVersion)
220
- throw new Error('program-not-ready');
221
- verifiedBinary = selected.binary;
222
- verifiedStamp = await ctx.machine.treeStamp(selected.binary);
223
- isComplete = true;
224
- report({ state: 'done', code: 'program-ready' });
225
- cancelled(signal);
226
- },
227
- remaining: () => (isComplete ? undefined : operation),
228
- async verify() {
229
- if (isCommandCompleted && commandStamp === undefined)
230
- throw new Error('program-installation-unconfirmed');
231
- if (verifiedBinary && (await ctx.machine.treeStamp(verifiedBinary)) !== verifiedStamp)
232
- throw new Error('program-changed');
233
- },
234
- };
235
- return operation;
236
- }
237
- async function claudeVersion(ctx, binary) {
238
- const output = await executeClaude(ctx, binary, ['--version'], { timeoutMs: 10_000 });
239
- const version = /\b(\d+\.\d+\.\d+)\b/.exec(output.stdout)?.[1];
240
- return !output.failed && output.code === 0 ? (version ?? null) : null;
241
- }
242
- function exactVersion(value) {
243
- return typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value) ? value : null;
244
- }
245
- async function stableClaudeVersion(ctx) {
246
- const release = await resolveNpmView(ctx.machine, `${PROGRAM_PACKAGES.claude}@stable`, 'version', exactVersion);
247
- if (release !== null)
248
- return release;
249
- try {
250
- const metadata = JSON.parse(await ctx.machine.fetchText(`${NPM_OFFICIAL}/@anthropic-ai%2Fclaude-code/stable`, { timeoutMs: 5_000 }));
251
- if (!isObject(metadata))
252
- throw new Error('invalid-release');
253
- const version = exactVersion(metadata.version);
254
- if (version === null)
255
- throw new Error('invalid-release');
256
- return { value: version, registry: NPM_OFFICIAL };
257
- }
258
- catch {
259
- throw new Error('stable-release-unavailable');
260
- }
261
- }
262
- async function installedClaude(ctx, channel, expected) {
263
- const found = await programs(ctx, 'claude');
264
- if (found.problems.length)
265
- throw new Error('installation-state-unconfirmed');
266
- const program = [...found.values.values()].find(value => value.channel === channel);
267
- return program !== undefined &&
268
- (await ctx.machine.treeStamp(program.binary)) !== null &&
269
- (await claudeVersion(ctx, program.binary)) === expected
270
- ? program
271
- : undefined;
272
- }
273
- /** 新装优先 npm;Windows 在确认无可用安装和 npm 残留后尝试一次 CMD */
274
- async function prepareClaudeInstall(ctx) {
275
- const release = await stableClaudeVersion(ctx);
276
- const targetVersion = release.value;
277
- const targetRegistry = release.registry;
278
- let stage = 'npm';
279
- let isComplete = false;
280
- let binary;
281
- let stamp = null;
282
- let npmScope;
283
- let npmFailure = null;
284
- let npmSnapshot;
285
- let isCleanupCompleted = false;
286
- let cmdStamp;
287
- let isCmdFailed = false;
288
- let installerCleanup;
289
- const native = path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'claude.exe' : 'claude');
290
- try {
291
- npmScope = await freezeNpmScope(ctx);
292
- }
293
- catch (error) {
294
- if (errorCode(error) !== 'npm-not-found')
295
- throw error;
296
- npmFailure = 'npm-install-failed';
297
- }
298
- const npmRoot = npmScope?.npmRoot;
299
- const verifyNpmSnapshot = async () => {
300
- if (npmRoot === undefined)
301
- return;
302
- if (npmSnapshot === undefined)
303
- throw new Error('program-installation-unconfirmed');
304
- if ((await ctx.machine.treeStamp(path.join(npmRoot, PROGRAM_PACKAGES.claude, 'package.json'))) !==
305
- npmSnapshot.manifestStamp)
306
- throw new Error('program-changed');
307
- if (npmSnapshot.binary && (await ctx.machine.treeStamp(npmSnapshot.binary.file)) !== npmSnapshot.binary.stamp)
308
- throw new Error('program-changed');
309
- };
310
- const cleanInstaller = async () => {
311
- if (installerCleanup === undefined)
312
- return;
313
- const current = await ctx.machine.treeStamp(installerCleanup.directory);
314
- if (current !== null) {
315
- if (installerCleanup.stamp !== undefined && current !== installerCleanup.stamp)
316
- throw new Error('installer-conflict');
317
- installerCleanup.stamp = current;
318
- await ctx.machine.removeTree(installerCleanup.directory, current);
319
- }
320
- installerCleanup = undefined;
321
- };
322
- const confirm = async (program) => {
323
- binary = program.binary;
324
- stamp = await ctx.machine.treeStamp(binary);
325
- isComplete = true;
326
- };
327
- const operation = {
328
- targetVersion,
329
- targetRegistry,
330
- get changes() {
331
- return [
332
- {
333
- code: stage === 'npm-confirm' || stage === 'cmd-confirm'
334
- ? 'program-installation-confirm'
335
- : ctx.platform === 'win32'
336
- ? 'program-install-cmd'
337
- : 'program-install',
338
- detail: `${stage === 'cmd-confirm' ? 'CMD' : 'npm'} · ${targetVersion}`,
339
- },
340
- { code: 'keep-user-data' },
341
- ];
342
- },
343
- async run(report, signal) {
344
- cancelled(signal);
345
- if (stage === 'npm') {
346
- const before = await programs(ctx, 'claude');
347
- if (before.values.size)
348
- throw new Error('program-changed');
349
- if (before.problems.length)
350
- throw new Error('installation-state-unconfirmed');
351
- await npmScope?.verify();
352
- stage = 'npm-confirm';
353
- report({ state: 'kept', code: 'npm-install-started' });
354
- if (npmRoot !== undefined) {
355
- try {
356
- const args = npmInstallArgs([
357
- 'install',
358
- '-g',
359
- ...npmScopeArgs(ctx, npmRoot),
360
- '--ignore-scripts=false',
361
- `--allow-scripts=${PROGRAM_PACKAGES.claude}`,
362
- '--include=optional',
363
- `${PROGRAM_PACKAGES.claude}@${targetVersion}`,
364
- ], targetRegistry);
365
- success(await ctx.machine.npm(args), 'npm-install-failed');
366
- report({ state: 'done', code: 'package-command-completed' });
367
- }
368
- catch (error) {
369
- if (errorCode(error) === 'npm-changed')
370
- throw error;
371
- npmFailure = errorCode(error);
372
- }
373
- const manifest = path.join(npmRoot, PROGRAM_PACKAGES.claude, 'package.json');
374
- try {
375
- const manifestStamp = await ctx.machine.treeStamp(manifest);
376
- if (manifestStamp === null)
377
- npmSnapshot = { manifestStamp };
378
- else {
379
- const file = await npmBinary(ctx, 'claude', npmRoot);
380
- npmSnapshot = { manifestStamp, binary: { file, stamp: await ctx.machine.treeStamp(file) } };
381
- }
382
- }
383
- catch (error) {
384
- throw new Error('program-installation-unconfirmed', { cause: error });
385
- }
386
- }
387
- }
388
- if (stage === 'npm-confirm') {
389
- await npmScope?.verify();
390
- await verifyNpmSnapshot();
391
- const installed = await installedClaude(ctx, 'npm', targetVersion);
392
- if (installed !== undefined) {
393
- await confirm(installed);
394
- report({ state: 'done', code: 'program-ready', detail: `npm · ${targetVersion}` });
395
- cancelled(signal);
396
- return;
397
- }
398
- cancelled(signal);
399
- npmFailure ??= 'program-not-ready';
400
- report({ state: 'kept', code: npmFailure });
401
- if (ctx.platform !== 'win32')
402
- throw new Error(npmFailure);
403
- stage = 'cleanup';
404
- }
405
- if (stage === 'cleanup') {
406
- await npmScope?.verify();
407
- if (!isCleanupCompleted)
408
- await verifyNpmSnapshot();
409
- const remainder = await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot);
410
- if (remainder !== null) {
411
- if (remainder !== targetVersion || isCleanupCompleted)
412
- throw new Error('program-changed');
413
- success(await ctx.machine.npm(npmUninstallArgs(['uninstall', '-g', ...npmScopeArgs(ctx, npmRoot), PROGRAM_PACKAGES.claude])), 'failed-install-cleanup-failed');
414
- isCleanupCompleted = true;
415
- if ((await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot)) !== null)
416
- throw new Error('failed-install-cleanup-failed');
417
- report({ state: 'kept', code: 'failed-install-cleaned' });
418
- }
419
- stage = 'cmd';
420
- }
421
- if (stage === 'cmd') {
422
- const current = await programs(ctx, 'claude');
423
- if (current.values.size)
424
- throw new Error('program-changed');
425
- if (current.problems.length)
426
- throw new Error('installation-state-unconfirmed');
427
- cancelled(signal);
428
- report({ state: 'kept', code: 'cmd-install-started' });
429
- const script = await ctx.machine.fetchText('https://claude.ai/install.cmd');
430
- if (/^\s*</.test(script) || !script.trim())
431
- throw new Error('installer-unavailable');
432
- const directory = path.join(ctx.storage, `install-claude-${randomUUID()}`);
433
- const file = path.join(directory, 'install.cmd');
434
- if (!(await ctx.machine.initialize(file, script)))
435
- throw new Error('installer-conflict');
436
- installerCleanup = { directory };
437
- try {
438
- cancelled(signal);
439
- stage = 'cmd-confirm';
440
- const result = await ctx.machine.execute('cmd.exe', ['/d', '/v:off', '/s', '/c', '.\\install.cmd', targetVersion], { env: claudeEnvironment(ctx), cwd: directory });
441
- isCmdFailed = !succeeded(result);
442
- if (!isCmdFailed)
443
- report({ state: 'done', code: 'package-command-completed' });
444
- try {
445
- cmdStamp = await ctx.machine.treeStamp(native);
446
- }
447
- catch (error) {
448
- throw new Error('program-installation-unconfirmed', { cause: error });
449
- }
450
- }
451
- finally {
452
- await cleanInstaller();
453
- }
454
- }
455
- if (stage === 'cmd-confirm') {
456
- await cleanInstaller();
457
- if (cmdStamp === undefined)
458
- throw new Error('program-installation-unconfirmed');
459
- if ((await ctx.machine.treeStamp(native)) !== cmdStamp)
460
- throw new Error('program-changed');
461
- const installed = await installedClaude(ctx, 'native', targetVersion);
462
- if (installed === undefined)
463
- throw new Error(isCmdFailed ? 'cmd-install-failed' : 'program-not-ready');
464
- await confirm(installed);
465
- report({ state: 'done', code: 'program-ready', detail: `CMD · ${targetVersion}` });
466
- cancelled(signal);
467
- }
468
- },
469
- remaining: () => (isComplete ? undefined : operation),
470
- async verify() {
471
- if ((stage === 'cmd-confirm' && cmdStamp === undefined) ||
472
- (stage !== 'npm' && npmRoot !== undefined && npmSnapshot === undefined))
473
- throw new Error('program-installation-unconfirmed');
474
- if (binary && (await ctx.machine.treeStamp(binary)) !== stamp)
475
- throw new Error('program-changed');
476
- },
477
- };
478
- return operation;
479
- }
480
- function officeAsset(ctx) {
481
- const arch = ctx.arch ?? process.arch;
482
- if (arch !== 'x64' && arch !== 'arm64')
483
- throw new Error('unsupported-architecture');
484
- if (ctx.platform === 'win32')
485
- return `officecli-win-${arch}.exe`;
486
- if (ctx.platform === 'darwin')
487
- return `officecli-mac-${arch}`;
488
- return `officecli-linux-${ctx.libc === 'musl' ? 'alpine-' : ''}${arch}`;
489
- }
490
- export async function officeVersion(ctx, binary) {
491
- const deadlineMs = performance.now() + 5_000;
492
- const probe = (argument) => ctx.machine.execute(binary, [argument], {
493
- env: { ...officeIntegration.suppressSelfUpdate },
494
- cwd: ctx.home,
495
- timeoutMs: Math.max(1, Math.ceil(deadlineMs - performance.now())),
496
- });
497
- const output = await probe('--version');
498
- const version = /\b(\d+\.\d+\.\d+)\b/.exec(output.stdout)?.[1];
499
- if (!succeeded(output) || version === undefined)
500
- return null;
501
- if (/\bofficecli\b/i.test(output.stdout))
502
- return version;
503
- if (performance.now() >= deadlineMs)
504
- return null;
505
- const help = await probe('--help');
506
- return succeeded(help) && /\bofficecli\b/i.test(help.stdout) ? version : null;
507
- }
508
- async function officeUpdates(ctx, binary) {
509
- const files = ['.update', '.update.partial', '.old'].map(suffix => binary + suffix);
510
- const entries = await ctx.machine.entries(path.dirname(binary));
511
- return Promise.all(files.map(async (file) => {
512
- if (entries.some(entry => entry.name === path.basename(file) && entry.kind === 'directory'))
513
- throw new Error('program-update-conflict');
514
- return { file, stamp: await ctx.machine.treeStamp(file), isDone: false };
515
- }));
516
- }
517
- async function prepareOfficeNative(ctx, selection, program) {
518
- const action = selection.action;
519
- if (action !== 'install' && action !== 'update' && action !== 'reinstall')
520
- throw new Error('action-unavailable');
521
- const binary = program?.binary ?? officeBinary(ctx);
522
- if (!samePath(ctx, binary, officeBinary(ctx)))
523
- throw new Error('channel-not-supported');
524
- const before = await ctx.machine.fingerprint(binary);
525
- if (!program && before !== null)
526
- throw new Error('program-changed');
527
- const updates = await officeUpdates(ctx, binary);
528
- const assetName = officeAsset(ctx);
529
- const release = JSON.parse(await ctx.machine.fetchText('https://api.github.com/repos/iOfficeAI/OfficeCLI/releases/latest'));
530
- if (!isObject(release) ||
531
- release.draft !== false ||
532
- release.prerelease !== false ||
533
- typeof release.tag_name !== 'string' ||
534
- !/^v\d+\.\d+\.\d+$/.test(release.tag_name) ||
535
- !Array.isArray(release.assets))
536
- throw new Error('invalid-release');
537
- const targetVersion = release.tag_name.slice(1);
538
- const baseUrl = `https://github.com/iOfficeAI/OfficeCLI/releases/download/${release.tag_name}/`;
539
- const assets = release.assets.filter(isObject);
540
- const asset = assets.find(value => value.name === assetName);
541
- const manifest = assets.find(value => value.name === 'SHA256SUMS');
542
- if (!asset ||
543
- asset.browser_download_url !== `${baseUrl}${assetName}` ||
544
- !manifest ||
545
- manifest.browser_download_url !== `${baseUrl}SHA256SUMS`)
546
- throw new Error('release-asset-unavailable');
547
- const checksums = await ctx.machine.fetchText(`${baseUrl}SHA256SUMS`);
548
- const matching = checksums
549
- .split(/\r?\n/)
550
- .map(line => line.trim().split(/\s+/))
551
- .filter(parts => parts[1]?.replace(/^\*/, '') === assetName);
552
- const digest = matching.length === 1 ? matching[0]?.[0]?.toLowerCase() : undefined;
553
- if (digest === undefined ||
554
- !/^[a-f0-9]{64}$/.test(digest) ||
555
- (asset.digest !== undefined && asset.digest !== null && asset.digest !== `sha256:${digest}`))
556
- throw new Error('release-checksum-unavailable');
557
- if (before !== null) {
558
- const currentVersion = program?.version ?? (await officeVersion(ctx, binary));
559
- if (currentVersion === null)
560
- throw new Error('program-version-unconfirmed');
561
- if (compareVersions(currentVersion, targetVersion) > 0)
562
- throw new Error('newer-version-preserved');
563
- }
564
- const bytes = await ctx.machine.fetchBytes(`${baseUrl}${assetName}`);
565
- if (createHash('sha256').update(bytes).digest('hex') !== digest)
566
- throw new Error('release-checksum-mismatch');
567
- let isDeployed = false;
568
- let isProgramReady = false;
569
- let isComplete = false;
570
- const operation = {
571
- targetVersion,
572
- targetBinary: binary,
573
- changes: [
574
- { code: PROGRAM_ACTION_CHANGE[action], detail: `OfficeCLI · native · ${targetVersion} · ${binary}` },
575
- ...updates
576
- .filter(value => value.stamp !== null)
577
- .map(value => ({ code: 'program-copy-remove', detail: value.file })),
578
- { code: 'program-user-path', detail: path.dirname(binary) },
579
- { code: 'keep-user-data' },
580
- ],
581
- async run(report, signal) {
582
- cancelled(signal);
583
- if ((await ctx.machine.fingerprint(binary)) !== (isDeployed ? digest : before))
584
- throw new Error('program-changed');
585
- for (const update of updates) {
586
- if ((await ctx.machine.treeStamp(update.file)) !== (update.isDone ? null : update.stamp))
587
- throw new Error('program-changed');
588
- if (update.isDone)
589
- continue;
590
- if (update.stamp !== null) {
591
- await ctx.machine.removeTree(update.file, update.stamp);
592
- report({ state: 'done', code: 'program-copy-removed', detail: update.file });
593
- }
594
- update.isDone = true;
595
- cancelled(signal);
596
- }
597
- if (!isDeployed) {
598
- await ctx.machine.replaceFile(binary, bytes, before, true);
599
- isDeployed = true;
600
- report({ state: 'done', code: 'program-file-ready', detail: binary });
601
- }
602
- if (!isProgramReady) {
603
- if ((await officeVersion(ctx, binary)) !== targetVersion)
604
- throw new Error('program-not-ready');
605
- isProgramReady = true;
606
- report({ state: 'done', code: 'program-ready', detail: `native · ${targetVersion}` });
607
- }
608
- cancelled(signal);
609
- await ctx.machine.ensureUserPath(path.dirname(binary));
610
- if ((await ctx.machine.fingerprint(binary)) !== digest)
611
- throw new Error('program-changed');
612
- for (const update of updates)
613
- if ((await ctx.machine.treeStamp(update.file)) !== null)
614
- throw new Error('program-changed');
615
- isComplete = true;
616
- report({ state: 'done', code: 'program-user-path', detail: path.dirname(binary) });
617
- cancelled(signal);
618
- },
619
- remaining: () => (isComplete ? undefined : operation),
620
- async verify() {
621
- if (isDeployed && (await ctx.machine.fingerprint(binary)) !== digest)
622
- throw new Error('program-changed');
623
- for (const update of updates)
624
- if ((await ctx.machine.treeStamp(update.file)) !== null)
625
- throw new Error('program-changed');
626
- },
627
- };
628
- return operation;
629
- }
630
- async function prepareProgramRemoval(ctx, kind, program, shouldPreserveData = true) {
631
- if (!program)
632
- throw new Error('program-not-installed');
633
- if (program.channel === 'manual')
634
- throw new Error('channel-not-supported');
635
- if (kind === 'claude') {
636
- const isClaudeActive = await claudeRunning(ctx.machine);
637
- if (isClaudeActive !== false)
638
- throw new Error(isClaudeActive ? 'claude-running' : 'process-state-unconfirmed');
639
- }
640
- const before = await ctx.machine.treeStamp(program.binary);
641
- const scope = await freezeProgramScope(ctx, program);
642
- if (kind === 'officecli' &&
643
- program.channel === 'native' &&
644
- before !== null &&
645
- (await officeVersion(ctx, program.binary)) === null)
646
- throw new Error('program-identity-unconfirmed');
647
- const nativeFiles = program.channel === 'native'
648
- ? [program.binary, ...(kind === 'claude' ? [path.join(ctx.home, '.local/share/claude')] : [])]
649
- : [];
650
- const removals = [
651
- ...(await Promise.all(nativeFiles.map(async (file) => ({ file, stamp: await ctx.machine.treeStamp(file), isDone: false })))),
652
- ...(program.channel === 'native' && kind === 'officecli' ? await officeUpdates(ctx, program.binary) : []),
653
- ];
654
- let isComplete = false;
655
- let hasAttemptedCommand = false;
656
- let isCommandFailed = false;
657
- let isBinaryRemoved = false;
658
- const verifyRemoved = async () => {
659
- if (program.channel === 'npm') {
660
- await scope.verify();
661
- if ((await npmVersion(ctx, PROGRAM_PACKAGES[kind], scope.npmRoot)) !== null)
662
- throw new Error('program-still-installed');
663
- }
664
- if ((await ctx.machine.treeStamp(program.binary)) !== null)
665
- throw new Error('program-still-installed');
666
- for (const target of removals)
667
- if ((await ctx.machine.treeStamp(target.file)) !== null)
668
- throw new Error('program-still-installed');
669
- };
670
- const operation = {
671
- targetVersion: null,
672
- get changes() {
673
- const pending = removals.filter(value => !value.isDone && value.stamp !== null);
674
- return [
675
- ...(removals.length
676
- ? pending.length
677
- ? pending.map(value => ({
678
- code: value.file === program.binary ? 'program-uninstall' : 'program-copy-remove',
679
- detail: value.file,
680
- }))
681
- : [{ code: 'program-removal-confirm' }]
682
- : hasAttemptedCommand
683
- ? [{ code: 'program-removal-confirm' }]
684
- : [{ code: 'program-uninstall', detail: `${program.channel} · ${program.binary}` }]),
685
- ...(shouldPreserveData ? [{ code: 'keep-user-data' }] : []),
686
- ];
687
- },
688
- async run(report, signal) {
689
- cancelled(signal);
690
- if (kind === 'claude') {
691
- const isClaudeActive = await claudeRunning(ctx.machine);
692
- if (isClaudeActive !== false)
693
- throw new Error(isClaudeActive ? 'claude-running' : 'process-state-unconfirmed');
694
- }
695
- if (removals.length) {
696
- for (const target of removals) {
697
- if (target.isDone) {
698
- if ((await ctx.machine.treeStamp(target.file)) !== null)
699
- throw new Error('program-changed');
700
- continue;
701
- }
702
- cancelled(signal);
703
- if ((await ctx.machine.treeStamp(target.file)) !== target.stamp)
704
- throw new Error('program-changed');
705
- if (target.stamp !== null)
706
- await ctx.machine.removeTree(target.file, target.stamp);
707
- target.isDone = true;
708
- report({ state: target.stamp === null ? 'kept' : 'done', code: 'program-copy-removed', detail: target.file });
709
- cancelled(signal);
710
- }
711
- }
712
- else {
713
- const isConfirming = hasAttemptedCommand;
714
- if (!hasAttemptedCommand) {
715
- if ((await ctx.machine.treeStamp(program.binary)) !== before)
716
- throw new Error('program-changed');
717
- await scope.verify();
718
- const result = await removeProgramChannel(ctx, program, scope);
719
- hasAttemptedCommand = true;
720
- isCommandFailed = !succeeded(result);
721
- if (!isCommandFailed)
722
- report({ state: 'kept', code: 'program-uninstall-command-completed' });
723
- }
724
- const current = await ctx.machine.treeStamp(program.binary);
725
- if (current === null && before !== null && !isBinaryRemoved) {
726
- isBinaryRemoved = true;
727
- report({ state: 'done', code: 'program-copy-removed', detail: program.binary });
728
- }
729
- try {
730
- await verifyRemoved();
731
- }
732
- catch (error) {
733
- const code = errorCode(error);
734
- if (code === 'program-still-installed' && current === before)
735
- hasAttemptedCommand = false;
736
- throw new Error(code === 'program-still-installed'
737
- ? isCommandFailed
738
- ? 'program-uninstall-failed'
739
- : code
740
- : 'program-removal-unconfirmed', { cause: error });
741
- }
742
- if (isCommandFailed && program.channel !== 'npm') {
743
- if (!isConfirming || (await programPackageAbsent(ctx, program, scope)) !== true)
744
- throw new Error('program-removal-unconfirmed');
745
- }
746
- }
747
- await verifyRemoved();
748
- isComplete = true;
749
- report({ state: 'done', code: 'program-removed', detail: program.binary });
750
- if (shouldPreserveData)
751
- report({ state: 'kept', code: 'keep-user-data' });
752
- try {
753
- const found = await programs(ctx, kind);
754
- for (const value of found.values.values())
755
- report({ state: 'kept', code: 'program-other-copies-kept', detail: value.binary });
756
- for (const code of found.problems)
757
- report({ state: 'kept', code: 'program-inspection-warning', detail: code });
758
- }
759
- catch (error) {
760
- report({ state: 'kept', code: 'program-inspection-warning', detail: errorCode(error) });
761
- }
762
- cancelled(signal);
763
- },
764
- remaining: () => (isComplete ? undefined : operation),
765
- verify: verifyRemoved,
766
- };
767
- return operation;
768
- }
769
- function compareVersions(left, right) {
770
- const a = left.split('.').map(Number);
771
- const b = right.split('.').map(Number);
772
- for (let index = 0; index < 3; index++) {
773
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
774
- if (difference !== 0)
775
- return difference;
776
- }
777
- return 0;
778
- }