@hit-sudomaker/ccw 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugins.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { knownTitle } from './titles.js';
3
+ import { ENABLED_PLUGINS_KEY } from './claude-config.js';
3
4
  import { marketplaceSources, pluginSpecs } from './management-catalog.js';
4
5
  import { errorCode, isObject } from './machine.js';
5
6
  import { cancelled, editFields, json, object, restOf, success, unchanged } from './model.js';
@@ -26,13 +27,25 @@ function pluginSource(name, markets) {
26
27
  ? { repository: expected.repository, marketName }
27
28
  : null;
28
29
  }
30
+ /** 插件名的市场段:name@market 形态 */
31
+ function marketOf(name) {
32
+ return name.split('@')[1];
33
+ }
34
+ /** 非目录插件的既存市场:用户自选来源只验市场记录在场,不做仓库白名单比对;
35
+ * 目录内插件一律返回 null,保持来源冲突防护 */
36
+ function declaredMarketSource(name, markets) {
37
+ if (Object.hasOwn(pluginSpecs, name))
38
+ return null;
39
+ const marketName = marketOf(name);
40
+ return marketName !== undefined && isObject(markets[marketName]) ? { marketName } : null;
41
+ }
29
42
  /** 解析插件标题:未安装方案入口用官方名;实际对象须市场记录在场且来源匹配,证据不足保留原始键名 */
30
43
  function pluginTitle(name, markets, isInstalled) {
31
44
  if (!isInstalled)
32
45
  return knownTitle(`plugin:${name}`, name);
33
46
  if (markets === null)
34
47
  return name;
35
- const marketName = name.split('@')[1];
48
+ const marketName = marketOf(name);
36
49
  return marketName !== undefined && markets[marketName] !== undefined && pluginSource(name, markets) !== null
37
50
  ? knownTitle(`plugin:${name}`, name)
38
51
  : name;
@@ -80,7 +93,7 @@ async function inspectPlugins(ctx) {
80
93
  let recordsProblem;
81
94
  let marketsProblem;
82
95
  try {
83
- enabled = object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins);
96
+ enabled = object((await json(ctx.machine, ctx.settingsFile))[ENABLED_PLUGINS_KEY]);
84
97
  }
85
98
  catch (error) {
86
99
  settingsProblem = errorCode(error);
@@ -145,6 +158,8 @@ async function inspectPlugins(ctx) {
145
158
  ? ['update', 'reinstall', 'connect']
146
159
  : ['install']
147
160
  : []),
161
+ // 非目录插件停用后不是死对象:文件在场时提供恢复启用入口(经安装页复用启用通道)
162
+ ...(!isOffered && !problem && enabled[name] === false && hasFilesPresent ? ['connect'] : []),
148
163
  ...(!settingsProblem && (enabled[name] === true || (enabled[name] === undefined && isInstalled))
149
164
  ? ['detach']
150
165
  : []),
@@ -173,9 +188,11 @@ async function preparePlugin(ctx, name, selection, describe) {
173
188
  const marketplaceFile = path.join(ctx.claudeRoot, 'plugins/known_marketplaces.json');
174
189
  let markets = null;
175
190
  let source = null;
191
+ let declared = null;
176
192
  try {
177
193
  markets = await json(ctx.machine, marketplaceFile);
178
194
  source = pluginSource(name, markets);
195
+ declared = source === null ? declaredMarketSource(name, markets) : null;
179
196
  }
180
197
  catch (error) {
181
198
  // 解除声明不依赖市场文件可读;取消仍由准备作用域向外传播
@@ -183,9 +200,11 @@ async function preparePlugin(ctx, name, selection, describe) {
183
200
  throw error;
184
201
  }
185
202
  const settings = await json(ctx.machine, ctx.settingsFile);
186
- const before = object(settings.enabledPlugins);
203
+ const before = object(settings[ENABLED_PLUGINS_KEY]);
204
+ const recordsNow = async () => userPluginRecords((await pluginRecords(ctx))[name]);
205
+ const enabledNow = async () => object((await json(ctx.machine, ctx.settingsFile))[ENABLED_PLUGINS_KEY]);
187
206
  if (action === 'detach') {
188
- const installed = before[name] === true ? null : userPluginRecords((await pluginRecords(ctx))[name]);
207
+ const installed = before[name] === true ? null : await recordsNow();
189
208
  if (before[name] !== true && (before[name] !== undefined || !installed?.length))
190
209
  throw new Error('no-connection');
191
210
  describe?.(pluginTitle(name, markets, before[name] !== undefined || (installed?.length ?? 0) > 0));
@@ -194,21 +213,21 @@ async function preparePlugin(ctx, name, selection, describe) {
194
213
  changes: [{ code: 'plugin-disable', detail: name }, { code: 'keep-plugin-files' }],
195
214
  async run(report) {
196
215
  if (installed !== null)
197
- unchanged(userPluginRecords((await pluginRecords(ctx))[name]), installed);
198
- await editFields(ctx, ctx.settingsFile, before, { [name]: false }, 'enabledPlugins');
216
+ unchanged(await recordsNow(), installed);
217
+ await editFields(ctx, ctx.settingsFile, before, { [name]: false }, ENABLED_PLUGINS_KEY);
199
218
  report({ state: 'done', code: 'plugin-disabled', detail: name });
200
219
  },
201
220
  };
202
221
  }
203
- if (source === null)
222
+ if (source === null && declared === null)
204
223
  throw new Error('marketplace-source-conflict');
205
- const records = userPluginRecords((await pluginRecords(ctx))[name]);
224
+ const records = await recordsNow();
206
225
  describe?.(pluginTitle(name, markets, records.length > 0 || before[name] !== undefined));
207
226
  const canReuse = action === 'install' &&
208
227
  records.length > 0 &&
209
228
  (await Promise.all(records.map(record => pluginFilePresent(ctx, record)))).every(Boolean);
210
229
  const help = action === 'reinstall' ? await claudeCommand(ctx, ['plugin', 'uninstall', '--help']) : null;
211
- // 探测失败保持未知:不以「不支持保留」代替,阻断重装以免官方卸载删除插件数据
230
+ // 探测失败保持未知:不以「不支持保留」代替;重装一律阻断(官方卸载可能删除插件数据)
212
231
  if (help !== null && (help.failed || help.code !== 0))
213
232
  throw new Error('plugin-keep-data-unconfirmed');
214
233
  const shouldKeepData = help !== null && help.stdout.includes('--keep-data');
@@ -219,8 +238,15 @@ async function preparePlugin(ctx, name, selection, describe) {
219
238
  let expectedRecords = records;
220
239
  let expectedEnabled = before[name];
221
240
  const validateSource = async () => {
222
- const current = pluginSource(name, await json(ctx.machine, marketplaceFile));
223
- if (current === null || current.marketName !== source.marketName || current.repository !== source.repository)
241
+ const marketsNow = await json(ctx.machine, marketplaceFile);
242
+ if (source !== null) {
243
+ const current = pluginSource(name, marketsNow);
244
+ if (current === null || current.marketName !== source.marketName || current.repository !== source.repository)
245
+ throw new Error('marketplace-source-conflict');
246
+ return;
247
+ }
248
+ const current = declaredMarketSource(name, marketsNow);
249
+ if (current === null || declared === null || current.marketName !== declared.marketName)
224
250
  throw new Error('marketplace-source-conflict');
225
251
  };
226
252
  return {
@@ -245,8 +271,8 @@ async function preparePlugin(ctx, name, selection, describe) {
245
271
  if (isCommandDone && !hasCommandSnapshot)
246
272
  throw new Error('program-installation-unconfirmed');
247
273
  await validateSource();
248
- unchanged(object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins)[name], expectedEnabled);
249
- unchanged(userPluginRecords((await pluginRecords(ctx))[name]), expectedRecords);
274
+ unchanged((await enabledNow())[name], expectedEnabled);
275
+ unchanged(await recordsNow(), expectedRecords);
250
276
  if (action === 'reinstall' && !isRemoved) {
251
277
  success(await claudeCommand(ctx, [
252
278
  'plugin',
@@ -256,11 +282,10 @@ async function preparePlugin(ctx, name, selection, describe) {
256
282
  'user',
257
283
  ...(shouldKeepData ? ['--keep-data'] : []),
258
284
  ]), 'plugin-command-failed');
259
- if (userPluginRecords((await pluginRecords(ctx))[name]).length > 0 ||
260
- object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins)[name] === true)
285
+ if ((await recordsNow()).length > 0 || (await enabledNow())[name] === true)
261
286
  throw new Error('plugin-remains');
262
- expectedRecords = userPluginRecords((await pluginRecords(ctx))[name]);
263
- expectedEnabled = object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins)[name];
287
+ expectedRecords = await recordsNow();
288
+ expectedEnabled = (await enabledNow())[name];
264
289
  isRemoved = true;
265
290
  report({ state: 'done', code: 'plugin-removed' });
266
291
  cancelled(signal);
@@ -268,7 +293,7 @@ async function preparePlugin(ctx, name, selection, describe) {
268
293
  if (!isCommandDone && (action === 'install' || action === 'reinstall')) {
269
294
  await validateSource();
270
295
  const markets = await json(ctx.machine, marketplaceFile);
271
- if (markets[source.marketName] === undefined)
296
+ if (source !== null && markets[source.marketName] === undefined)
272
297
  success(await claudeCommand(ctx, ['plugin', 'marketplace', 'add', source.repository]), 'marketplace-command-failed');
273
298
  }
274
299
  const verb = action === 'connect' || canReuse ? 'enable' : action === 'update' ? 'update' : 'install';
@@ -278,8 +303,8 @@ async function preparePlugin(ctx, name, selection, describe) {
278
303
  isCommandDone = true;
279
304
  report({ state: 'done', code: 'plugin-command-completed' });
280
305
  try {
281
- expectedRecords = userPluginRecords((await pluginRecords(ctx))[name]);
282
- expectedEnabled = object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins)[name];
306
+ expectedRecords = await recordsNow();
307
+ expectedEnabled = (await enabledNow())[name];
283
308
  hasCommandSnapshot = true;
284
309
  }
285
310
  catch (error) {
@@ -295,13 +320,13 @@ async function preparePlugin(ctx, name, selection, describe) {
295
320
  else
296
321
  unchanged(object((await json(ctx.machine, ctx.settingsFile)).env).GITHUB_PERSONAL_ACCESS_TOKEN, selection.fields.secret);
297
322
  }
298
- const after = userPluginRecords((await pluginRecords(ctx))[name]);
323
+ const after = await recordsNow();
299
324
  if (after.length === 0)
300
325
  throw new Error('plugin-not-ready');
301
326
  for (const record of after)
302
327
  if (!(await pluginFilePresent(ctx, record)))
303
328
  throw new Error('plugin-not-ready');
304
- if (action !== 'update' && object((await json(ctx.machine, ctx.settingsFile)).enabledPlugins)[name] !== true)
329
+ if (action !== 'update' && (await enabledNow())[name] !== true)
305
330
  throw new Error('plugin-not-enabled');
306
331
  report({ state: 'done', code: 'plugin-ready' });
307
332
  },
@@ -1,15 +1,28 @@
1
1
  import path from 'node:path';
2
2
  import { isObject, succeeded } from './machine.js';
3
- import { claudeEnvironment, json, normalizePath, success } from './model.js';
3
+ import { claudeEnvironment, json, normalizePath, success, userBinDirectory } from './model.js';
4
+ import { OFFICECLI_REPO_SLUG } from './management-catalog.js';
4
5
  import { npmInstallArgs, npmUninstallArgs, NPM_READ_TIMEOUT_MS } from './npm-registry.js';
6
+ import { NPM_ENABLE_SCRIPTS } from './npm-registry.js';
5
7
  export const PROGRAM_PACKAGES = {
6
8
  claude: '@anthropic-ai/claude-code',
7
9
  officecli: '@officecli/officecli',
8
10
  };
11
+ /** 包管理器包标识与定位旗标:安装/卸载/清点与输出校验共用,字面量不得散布 */
12
+ const WINGET_CLAUDE_ID = 'Anthropic.ClaudeCode';
13
+ const OFFICECLI_PACKAGE_ID = 'officecli';
14
+ const WINGET_ID_FLAGS = ['--id', WINGET_CLAUDE_ID];
15
+ const WINGET_MATCH_FLAGS = ['--exact', '--disable-interactivity'];
16
+ /** npm 安装的脚本放行旗标:恒开 ignore-scripts,claude 另放行自身脚本与可选依赖 */
17
+ export const npmScriptFlags = (kind) => kind === 'claude'
18
+ ? [...NPM_ENABLE_SCRIPTS, `--allow-scripts=${PROGRAM_PACKAGES.claude}`, '--include=optional']
19
+ : [...NPM_ENABLE_SCRIPTS];
20
+ /** OfficeCLI 官方主页的认可形状(仓库标识单一出处) */
21
+ const officecliHomepage = new RegExp(`^https://(?:github\\.com/${OFFICECLI_REPO_SLUG.replaceAll('.', '\\.')}/?|officecli\\.ai/?)$`);
9
22
  export function officeBinary(ctx) {
10
23
  const root = ctx.platform === 'win32'
11
24
  ? path.join(ctx.localAppData ?? path.join(ctx.home, 'AppData/Local'), 'OfficeCli')
12
- : path.join(ctx.home, '.local/bin');
25
+ : userBinDirectory(ctx);
13
26
  if (!path.isAbsolute(root) || path.resolve(root) === path.parse(path.resolve(root)).root)
14
27
  throw new Error('invalid-config-root');
15
28
  return path.join(root, ctx.platform === 'win32' ? 'officecli.exe' : 'officecli');
@@ -140,7 +153,7 @@ export async function identifyProgramChannel(ctx, kind, binary, canonical, nativ
140
153
  appParent !== undefined &&
141
154
  samePath(ctx, appParent, path.join(scoopRoot, 'apps/officecli')) &&
142
155
  typeof manifest.homepage === 'string' &&
143
- /^https:\/\/(?:github\.com\/iOfficeAI\/OfficeCLI\/?|officecli\.ai\/?)$/.test(manifest.homepage))
156
+ officecliHomepage.test(manifest.homepage))
144
157
  channel = 'scoop';
145
158
  }
146
159
  if (ctx.platform === 'linux' && channel === 'manual') {
@@ -174,14 +187,14 @@ export async function identifyProgramChannel(ctx, kind, binary, canonical, nativ
174
187
  ? 'claude-code@latest'
175
188
  : kind === 'claude'
176
189
  ? 'claude-code'
177
- : 'officecli',
190
+ : OFFICECLI_PACKAGE_ID,
178
191
  };
179
192
  }
180
193
  export function channelCanPinVersion(channel) {
181
194
  return channel === 'npm' || channel === 'native' || channel === 'winget';
182
195
  }
183
196
  async function scoopTarget(ctx, program) {
184
- const result = await ctx.machine.execute('scoop', ['prefix', 'officecli']);
197
+ const result = await ctx.machine.execute('scoop', ['prefix', OFFICECLI_PACKAGE_ID]);
185
198
  const prefix = result.stdout.trim();
186
199
  if (!succeeded(result) || !path.isAbsolute(prefix) || /[\r\n]/.test(prefix))
187
200
  throw new Error('program-scope-unconfirmed');
@@ -281,20 +294,35 @@ export async function freezeProgramScope(ctx, program) {
281
294
  }
282
295
  return { verify: async () => { }, matches };
283
296
  }
297
+ /** npm 渠道占用前复核:版本与二进制位都未变才继续 */
298
+ async function ensureNpmProgramUnchanged(ctx, program, scope) {
299
+ if ((await npmVersion(ctx, PROGRAM_PACKAGES[program.kind], scope.npmRoot)) !== program.version ||
300
+ !samePath(ctx, await npmBinary(ctx, program.kind, scope.npmRoot), program.binary))
301
+ throw new Error('program-changed');
302
+ }
303
+ /** 渠道命令分发尾:解包校验命令并先行 brew 包裹,执行与成功判据由调用方决定 */
304
+ async function dispatchChannelCommand(ctx, program, commands) {
305
+ const command = commands[program.channel];
306
+ if (command === undefined)
307
+ throw new Error('channel-not-supported');
308
+ const [executable, ...args] = command;
309
+ if (!executable)
310
+ throw new Error('channel-not-supported');
311
+ if (program.channel === 'brew')
312
+ await brewPackage(ctx, program, executable);
313
+ return { executable, args };
314
+ }
284
315
  export async function maintainProgramChannel(ctx, program, scope, action, targetVersion, targetRegistry, packageCommandCompleted) {
285
316
  if (program.channel === 'manual')
286
317
  throw new Error('channel-not-supported');
287
318
  if (program.channel === 'npm') {
288
- if ((await npmVersion(ctx, PROGRAM_PACKAGES[program.kind], scope.npmRoot)) !== program.version ||
289
- !samePath(ctx, await npmBinary(ctx, program.kind, scope.npmRoot), program.binary))
290
- throw new Error('program-changed');
319
+ await ensureNpmProgramUnchanged(ctx, program, scope);
291
320
  const args = npmInstallArgs([
292
321
  'install',
293
322
  '-g',
294
323
  ...npmScopeArgs(ctx, scope.npmRoot),
295
324
  ...(action === 'reinstall' ? ['--force'] : []),
296
- '--ignore-scripts=false',
297
- ...(program.kind === 'claude' ? [`--allow-scripts=${PROGRAM_PACKAGES.claude}`, '--include=optional'] : []),
325
+ ...npmScriptFlags(program.kind),
298
326
  `${PROGRAM_PACKAGES[program.kind]}@${targetVersion}`,
299
327
  ], targetRegistry ?? null);
300
328
  success(await ctx.machine.npm(args));
@@ -319,13 +347,11 @@ export async function maintainProgramChannel(ctx, program, scope, action, target
319
347
  'winget',
320
348
  action === 'reinstall' ? 'install' : 'upgrade',
321
349
  ...(action === 'reinstall' ? ['--force'] : []),
322
- '--id',
323
- 'Anthropic.ClaudeCode',
350
+ ...WINGET_ID_FLAGS,
324
351
  ...(targetVersion !== null ? ['--version', targetVersion] : []),
325
- '--exact',
326
- '--disable-interactivity',
352
+ ...WINGET_MATCH_FLAGS,
327
353
  ],
328
- scoop: ['scoop', 'update', ...(action === 'reinstall' ? ['--force'] : []), 'officecli'],
354
+ scoop: ['scoop', 'update', ...(action === 'reinstall' ? ['--force'] : []), OFFICECLI_PACKAGE_ID],
329
355
  apt: [
330
356
  'apt-get',
331
357
  'install',
@@ -336,40 +362,24 @@ export async function maintainProgramChannel(ctx, program, scope, action, target
336
362
  dnf: ['dnf', action === 'reinstall' ? 'reinstall' : 'upgrade', '--assumeyes', program.packageName],
337
363
  apk: ['apk', action === 'reinstall' ? 'fix' : 'upgrade', program.packageName],
338
364
  };
339
- const command = commands[program.channel];
340
- if (command === undefined)
341
- throw new Error('channel-not-supported');
342
- const [executable, ...args] = command;
343
- if (!executable)
344
- throw new Error('channel-not-supported');
345
- if (program.channel === 'brew')
346
- await brewPackage(ctx, program, executable);
365
+ const { executable, args } = await dispatchChannelCommand(ctx, program, commands);
347
366
  success(await ctx.machine.execute(executable, args, program.channel === 'brew' ? { env: BREW_ENV } : undefined));
348
367
  await packageCommandCompleted();
349
368
  }
350
369
  export async function removeProgramChannel(ctx, program, scope) {
351
370
  if (program.channel === 'npm') {
352
- if ((await npmVersion(ctx, PROGRAM_PACKAGES[program.kind], scope.npmRoot)) !== program.version ||
353
- !samePath(ctx, await npmBinary(ctx, program.kind, scope.npmRoot), program.binary))
354
- throw new Error('program-changed');
371
+ await ensureNpmProgramUnchanged(ctx, program, scope);
355
372
  return ctx.machine.npm(npmUninstallArgs(['uninstall', '-g', ...npmScopeArgs(ctx, scope.npmRoot), PROGRAM_PACKAGES[program.kind]]));
356
373
  }
357
374
  const commands = {
358
375
  brew: [scope.manager ?? '', 'uninstall', ...(program.kind === 'claude' ? ['--cask'] : []), program.packageName],
359
- winget: ['winget', 'uninstall', '--id', 'Anthropic.ClaudeCode', '--exact', '--disable-interactivity'],
360
- scoop: ['scoop', 'uninstall', 'officecli'],
376
+ winget: ['winget', 'uninstall', ...WINGET_ID_FLAGS, ...WINGET_MATCH_FLAGS],
377
+ scoop: ['scoop', 'uninstall', OFFICECLI_PACKAGE_ID],
361
378
  apt: ['apt-get', 'remove', '--yes', program.packageName],
362
379
  dnf: ['dnf', 'remove', '--assumeyes', program.packageName],
363
380
  apk: ['apk', 'del', program.packageName],
364
381
  };
365
- const command = commands[program.channel];
366
- if (command === undefined)
367
- throw new Error('channel-not-supported');
368
- const [executable, ...args] = command;
369
- if (!executable)
370
- throw new Error('channel-not-supported');
371
- if (program.channel === 'brew')
372
- await brewPackage(ctx, program, executable);
382
+ const { executable, args } = await dispatchChannelCommand(ctx, program, commands);
373
383
  return ctx.machine.execute(executable, args, program.channel === 'brew' ? { env: BREW_ENV } : undefined);
374
384
  }
375
385
  export async function programPackageAbsent(ctx, program, scope) {
@@ -383,22 +393,21 @@ export async function programPackageAbsent(ctx, program, scope) {
383
393
  : !result.stdout.split(/\r?\n/).some(line => line.trim().split(/\s+/)[0] === program.packageName);
384
394
  }
385
395
  if (program.channel === 'winget') {
386
- const result = await ctx.machine.execute('winget', [
387
- 'list',
388
- '--id',
389
- 'Anthropic.ClaudeCode',
390
- '--exact',
391
- '--disable-interactivity',
392
- ]);
396
+ const result = await ctx.machine.execute('winget', ['list', ...WINGET_ID_FLAGS, ...WINGET_MATCH_FLAGS]);
393
397
  if (result.failed || result.code === null)
394
398
  return null;
395
399
  if (result.code >>> 0 === 0x8a150014)
396
400
  return true;
397
- return result.code !== 0 ? null : !/\bAnthropic\.ClaudeCode\b/i.test(result.stdout);
401
+ // 点号转义:包标识按字面匹配,形近 ID 不得计为仍在
402
+ return result.code !== 0
403
+ ? null
404
+ : !new RegExp(`\\b${WINGET_CLAUDE_ID.replaceAll('.', '\\.')}\\b`, 'i').test(result.stdout);
398
405
  }
399
406
  if (program.channel === 'scoop') {
400
- const result = await ctx.machine.execute('scoop', ['list', 'officecli']);
401
- return !succeeded(result) ? null : !result.stdout.split(/\r?\n/).some(line => /^\s*officecli\s/i.test(line));
407
+ const result = await ctx.machine.execute('scoop', ['list', OFFICECLI_PACKAGE_ID]);
408
+ return !succeeded(result)
409
+ ? null
410
+ : !result.stdout.split(/\r?\n/).some(line => new RegExp(`^\\s*${OFFICECLI_PACKAGE_ID}\\s`, 'i').test(line));
402
411
  }
403
412
  if (program.channel === 'apt') {
404
413
  const result = await ctx.machine.execute('dpkg-query', ['-W', '-f=${Package} ${db:Status-Status}\n']);