@autocodeflow/cli 1.7.0 → 1.9.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/config.js CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import Conf from 'conf';
19
19
  import * as fs from 'fs';
20
+ import chalk from 'chalk';
20
21
  /** Owner-only (rw-------). Mirrors the private-credential intent of ADR-012. */
21
22
  const CONFIG_FILE_MODE = 0o600;
22
23
  /**
@@ -32,6 +33,14 @@ const configDir = process.env.ACF_CONFIG_DIR;
32
33
  * contention in tests, read-only mounts) the constructor can throw. Fall back to
33
34
  * a mode-less store rather than crashing the CLI — `hardenConfigPermissions()`
34
35
  * repairs the on-disk mode separately when the platform allows it.
36
+ *
37
+ * UX 打磨(本轮):mode-less 兜底仍失败时只有两种现实解释——
38
+ * 1. 配置文件损坏(conf 构造时反序列化,坏 JSON 直接抛裸 SyntaxError 堆栈,
39
+ * 用户看不到任何可操作指引);
40
+ * 2. 存储位置读写不了(只读挂载等)。
41
+ * 借 `deserialize` 钩子在 conf 抛出前把坏内容留证:确属损坏则备份坏内容、
42
+ * 告警并携默认配置继续 CLI(凭据可从备份手工找回,或 acf login 重登);
43
+ * 否则抛出带指引的错误,替代 conf 内部堆栈。
35
44
  */
36
45
  function createStore() {
37
46
  const base = {
@@ -50,11 +59,65 @@ function createStore() {
50
59
  refreshToken: '',
51
60
  },
52
61
  };
62
+ // conf 用 clearInvalidConfig 兜损坏时会「静默」返回空对象并在构造期把坏文件
63
+ // 覆写成 defaults——凭据无提示丢失。因此不用它做常规路径,只在已留证坏内容
64
+ // 之后的恢复存储上启用(那时覆写无妨,坏内容已在内存里)。
65
+ let corruptRaw = null;
66
+ const withDeserialize = {
67
+ ...base,
68
+ deserialize: (value) => {
69
+ try {
70
+ return JSON.parse(value);
71
+ }
72
+ catch {
73
+ corruptRaw = value;
74
+ throw new SyntaxError('config file is not valid JSON');
75
+ }
76
+ },
77
+ };
53
78
  try {
54
- return new Conf({ ...base, configFileMode: CONFIG_FILE_MODE });
79
+ return new Conf({ ...withDeserialize, configFileMode: CONFIG_FILE_MODE });
55
80
  }
56
81
  catch {
57
- return new Conf(base);
82
+ try {
83
+ return new Conf(withDeserialize);
84
+ }
85
+ catch {
86
+ if (corruptRaw === null) {
87
+ // 反序列化没被触发 → 不是坏 JSON,而是存储位置本身读写不了。
88
+ throw new Error('Cannot initialize the CLI config store (permission or IO problem). ' +
89
+ 'Set ACF_CONFIG_DIR to a writable directory and retry.');
90
+ }
91
+ // 损坏恢复:坏内容已留证;此时 conf 的常规构造必然再抛,改用
92
+ // clearInvalidConfig 让这次构造成功(原文件被覆写也无妨),随后把
93
+ // 留证内容写到 <path>.corrupt,用户随时可手工找回旧凭据。
94
+ try {
95
+ const recovered = new Conf({
96
+ ...withDeserialize,
97
+ configFileMode: CONFIG_FILE_MODE,
98
+ clearInvalidConfig: true,
99
+ });
100
+ const backupPath = `${recovered.path}.corrupt`;
101
+ try {
102
+ fs.writeFileSync(backupPath, corruptRaw, { mode: CONFIG_FILE_MODE });
103
+ process.stderr.write(chalk.yellow(`⚠ Config file is corrupted: ${recovered.path}\n` +
104
+ ' (invalid JSON — the CLI cannot read its own credentials from it.)\n' +
105
+ ` The previous content was preserved at ${backupPath}; inspect it if you need the old credentials.\n` +
106
+ ' Continuing with default settings. Run "acf login" to sign in again.\n'));
107
+ }
108
+ catch {
109
+ process.stderr.write(chalk.yellow(`⚠ Config file is corrupted: ${recovered.path} (invalid JSON), and the backup could not be written.\n` +
110
+ ' Continuing with default settings. Run "acf login" to sign in again.\n'));
111
+ }
112
+ return recovered;
113
+ }
114
+ catch (err) {
115
+ // 连恢复存储都建不出来(目录读写不了):给出可操作指引而非裸堆栈。
116
+ throw new Error('Cannot initialize the CLI config store (permission or IO problem). ' +
117
+ `Underlying error: ${err instanceof Error ? err.message : String(err)}. ` +
118
+ 'Set ACF_CONFIG_DIR to a writable directory and retry.');
119
+ }
120
+ }
58
121
  }
59
122
  }
60
123
  const store = createStore();
package/dist/help.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 集中式 help 体系:全 CLI 的命令示例表。
3
+ *
4
+ * 为什么集中:commander 15 已提供层级 help(用途一行 = description、参数表 =
5
+ * usage/options、逐级 --help),这部分直接收编、不重造。缺的只有「每个命令
6
+ * 至少一个示例」——若散在各命令文件里用 addHelpText 拼接,永远查不齐、也没法
7
+ * 守卫。这里用一张以命令路径为键的表('task list' → 示例行数组),由
8
+ * `applyExamples` 在 index.ts 的命令分发处统一走树注入,src/__tests__/
9
+ * ux-uniform.test.ts 再用真实命令树断言「每个叶子命令都有 Examples 块」——
10
+ * 新增命令忘写示例会直接红。
11
+ *
12
+ * 键约定:空串 = 顶层 acf;其余为 'login'、'task list' 这样的空格分隔路径。
13
+ */
14
+ import type { Command } from 'commander';
15
+ export declare const EXAMPLES: Record<string, string[]>;
16
+ /**
17
+ * Walk the whole command tree and attach the matching Examples block to every
18
+ * command that has one (leaf commands and the root). Called once from index.ts
19
+ * after all commands are registered — the single wiring point.
20
+ */
21
+ export declare function applyExamples(program: Command): void;
package/dist/help.js ADDED
@@ -0,0 +1,151 @@
1
+ export const EXAMPLES = {
2
+ '': [
3
+ 'acf login',
4
+ 'acf task trigger <taskId> --wait',
5
+ 'acf exec tail <execId>',
6
+ ],
7
+ login: [
8
+ 'acf login',
9
+ 'acf login --url https://acf.example.com --user admin',
10
+ 'ACF_PASSWORD=... acf login --user admin # CI: password via env, not argv',
11
+ 'acf login --user admin --code 123456 # TOTP-enabled account (second factor)',
12
+ ],
13
+ 'task list': [
14
+ 'acf task list --status active --page 1',
15
+ 'acf task list --json',
16
+ ],
17
+ 'task get': ['acf task get <taskId>', 'acf task get <taskId> --json'],
18
+ 'task trigger': [
19
+ 'acf task trigger <taskId> --wait --wait-timeout 900',
20
+ ],
21
+ 'task executions': [
22
+ 'acf task executions <taskId> -n 5',
23
+ 'acf task executions <taskId> --json',
24
+ ],
25
+ 'task logs': [
26
+ 'acf task logs <execId> --tail 100',
27
+ 'acf task logs <execId> --from-line 200 -n 100',
28
+ ],
29
+ 'task analyze': ['acf task analyze <taskId> <execId>'],
30
+ 'task suggest-schedule': ['acf task suggest-schedule <taskId>'],
31
+ 'task stats': ['acf task stats <taskId> --json'],
32
+ 'task versions': ['acf task versions <taskId> --json'],
33
+ 'task rollback': [
34
+ 'acf task rollback <taskId> --version <versionId> # versionId from: acf task versions <taskId>',
35
+ ],
36
+ 'task compare': ['acf task compare <taskId> <versionId1> <versionId2>'],
37
+ 'task create': [
38
+ 'acf task create --file task.json # required: name, version, runtime, triggerType',
39
+ "acf task create --json '{\"name\":\"nightly\",\"version\":\"1.0.0\",\"runtime\":\"node\",\"triggerType\":\"cron\",\"cronExpression\":\"0 2 * * *\"}'",
40
+ ],
41
+ 'task update': ['acf task update <taskId> --file patch.json'],
42
+ 'task delete': ['acf task delete <taskId> -y'],
43
+ 'task pause': ['acf task pause <taskId>'],
44
+ 'task resume': ['acf task resume <taskId>'],
45
+ 'task export': [
46
+ 'acf task export <taskId>',
47
+ 'acf task export <taskId> -o task.json # payload is accepted verbatim by: acf task import task.json',
48
+ ],
49
+ 'task import': [
50
+ 'acf task import task.json',
51
+ 'cat task.json | acf task import - # "-" reads stdin; the new task starts paused',
52
+ ],
53
+ 'task batch': [
54
+ 'acf task batch trigger --ids id1,id2,id3',
55
+ 'acf task batch pause <id1> <id2>',
56
+ ],
57
+ 'task kill': ['acf task kill <taskId> <execId>'],
58
+ 'task webhook': [
59
+ 'acf task webhook enable <taskId> # prints the webhook URL + secret ONCE',
60
+ 'acf task webhook rotate <taskId> # old secret dies immediately, new one printed once',
61
+ 'acf task webhook status <taskId> # url + enabled, without touching the secret',
62
+ 'acf task webhook disable <taskId>',
63
+ ],
64
+ 'task glue': [
65
+ 'acf task glue <taskId> -f glue.js # language inferred from the extension (.js → javascript)',
66
+ 'cat glue.py | acf task glue <taskId> --stdin --language python',
67
+ ],
68
+ 'task lint': [
69
+ 'acf task lint glue.js',
70
+ 'acf task lint script.py --language python',
71
+ ],
72
+ 'app list': ['acf app list', 'acf app list --json'],
73
+ 'app get': ['acf app get <appId> --json'],
74
+ 'app create': [
75
+ 'acf app create --file app.json # required: name, version, runtime',
76
+ ],
77
+ 'app update': [
78
+ 'acf app update <appId> --json \'{"version":"2.0.0"}\' # renaming is not supported by the backend',
79
+ ],
80
+ 'app delete': ['acf app delete <appId> -y'],
81
+ 'app analyze': ['acf app analyze <appId>'],
82
+ 'app deploy': [
83
+ "acf app deploy <appId> -e <executorId> -m daemon --env '{\"KEY\":\"value\"}'",
84
+ ],
85
+ 'app deployments': ['acf app deployments <appId> -n 50 --json'],
86
+ 'app versions': ['acf app versions <appId> --json'],
87
+ 'app upload': [
88
+ 'acf app upload ./dist/app.zip --name my-app',
89
+ 'acf app upload ./dist/app.zip --name my-app --runtime python --version 1.2.0 --json',
90
+ ],
91
+ 'app upgrade-all': [
92
+ 'acf app upgrade-all <appId> # full rolling upgrade (default, no body)',
93
+ 'acf app upgrade-all <appId> --strategy canary --percentage 20 # canary first, auto-promote after probe',
94
+ ],
95
+ 'executor list': ['acf executor list', 'acf executor list --json'],
96
+ 'executor get': ['acf executor get <executorId> --json'],
97
+ 'executor rotate': [
98
+ 'acf executor rotate executor-node --reason "quarterly rotation"',
99
+ ],
100
+ 'executor offline': ['acf executor offline executor-node'],
101
+ 'deploy upgrade': ['acf deploy upgrade <deploymentId>'],
102
+ 'deploy stop': ['acf deploy stop <deploymentId>'],
103
+ 'audit list': [
104
+ 'acf audit list --action task.trigger --start-time 2026-01-01T00:00:00Z',
105
+ 'acf audit list --json',
106
+ ],
107
+ 'exec tail': ['acf exec tail <execId>', 'acf exec tail <execId> --json'],
108
+ 'project list': ['acf project list', 'acf project list --json'],
109
+ 'project members': ['acf project members <projectId> --json'],
110
+ 'sop list': ['acf sop list --status published', 'acf sop list --json'],
111
+ 'sop show': ['acf sop show <sopId> --json'],
112
+ 'agent sessions': [
113
+ 'acf agent sessions --status waiting_input',
114
+ 'acf agent sessions --json',
115
+ ],
116
+ 'apikey create': [
117
+ 'acf apikey create --name ci-deploy --scope trigger',
118
+ 'acf apikey create --name nightly --scope readonly --expires 90 # plaintext is echoed ONCE',
119
+ ],
120
+ 'apikey list': ['acf apikey list', 'acf apikey list --json'],
121
+ 'apikey revoke': ['acf apikey revoke 3'],
122
+ 'approval list': [
123
+ 'acf approval list # pending queue (default)',
124
+ 'acf approval list --status rejected --json',
125
+ ],
126
+ 'approval approve': [
127
+ 'acf approval approve <deploymentId> --note "change window approved" # second person: approver ≠ requester',
128
+ ],
129
+ 'approval reject': ['acf approval reject <deploymentId> --note "wrong version"'],
130
+ 'approval cancel': ['acf approval cancel <deploymentId> # withdraw your own pending request'],
131
+ 'config show': ['acf config show'],
132
+ 'config set-url': ['acf config set-url http://localhost:3105'],
133
+ 'config set-token': ['acf config set-token <token> # prefer: acf login'],
134
+ };
135
+ /**
136
+ * Walk the whole command tree and attach the matching Examples block to every
137
+ * command that has one (leaf commands and the root). Called once from index.ts
138
+ * after all commands are registered — the single wiring point.
139
+ */
140
+ export function applyExamples(program) {
141
+ const walk = (cmd, path) => {
142
+ const lines = EXAMPLES[path];
143
+ if (lines?.length) {
144
+ cmd.addHelpText('after', `\nExamples:\n ${lines.join('\n ')}`);
145
+ }
146
+ for (const sub of cmd.commands) {
147
+ walk(sub, path ? `${path} ${sub.name()}` : sub.name());
148
+ }
149
+ };
150
+ walk(program, '');
151
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,42 @@
1
1
  #!/usr/bin/env node
2
- export {};
2
+ /**
3
+ * ACF CLI — AutoCodeFlow command-line interface
4
+ *
5
+ * Usage:
6
+ * acf login # TOTP accounts: add --code <6 digits> (or prompt)
7
+ * acf task list
8
+ * acf task trigger <id> --wait
9
+ * acf task export <id> [-o file] | import <file> | batch <trigger|pause|resume|delete> --ids id1,id2
10
+ * acf task versions <id> | compare <id> <v1> <v2> | rollback <id> --version <vid>
11
+ * acf task analyze <taskId> <execId>
12
+ * acf task suggest-schedule <id>
13
+ * acf app list | create | update <id> | delete <id>
14
+ * acf app upload <pkg.zip> --name <name>
15
+ * acf app upgrade-all <appId> [--strategy canary --percentage N]
16
+ * acf app analyze <id>
17
+ * acf task webhook <enable|rotate|disable|status> <taskId>
18
+ * acf task glue <taskId> -f <file>
19
+ * acf approval list | approve <id> --note … | reject <id> | cancel <id>
20
+ * acf deploy upgrade <deploymentId> | stop <deploymentId>
21
+ * acf executor list | get <id> | rotate <name|id> | offline <name|id>
22
+ * acf exec tail <execId>
23
+ * acf task lint <file>
24
+ * acf audit list
25
+ * acf sop list | show <sopId>
26
+ * acf agent sessions
27
+ * acf apikey create --name <name> --scope <readonly|trigger|manage> [--expires <days>]
28
+ * acf apikey list | revoke <id>
29
+ * acf config show
30
+ *
31
+ * 退出码表(docs 详见 README.md「Exit codes」,单一事实源在 src/ui.ts 的
32
+ * EXIT_CODES):0 成功;1 运行失败;2 用法/参数错误;3 认证失败;
33
+ * 4 网络失败;130 中断(SIGINT)。
34
+ */
35
+ import { Command } from 'commander';
36
+ export declare const program: Command;
37
+ /**
38
+ * Map a commander parse outcome to the CLI exit code.
39
+ * `--help` / `--version` / `acf help <cmd>` 是用户主动要的正常出口 → 0;
40
+ * 其余解析错误(缺参/未知命令/未知选项/非法取值)= 用法错误 → 2。
41
+ */
42
+ export declare function parseErrorExitCode(e: unknown): number;
package/dist/index.js CHANGED
@@ -3,14 +3,20 @@
3
3
  * ACF CLI — AutoCodeFlow command-line interface
4
4
  *
5
5
  * Usage:
6
- * acf login
6
+ * acf login # TOTP accounts: add --code <6 digits> (or prompt)
7
7
  * acf task list
8
8
  * acf task trigger <id> --wait
9
+ * acf task export <id> [-o file] | import <file> | batch <trigger|pause|resume|delete> --ids id1,id2
9
10
  * acf task versions <id> | compare <id> <v1> <v2> | rollback <id> --version <vid>
10
11
  * acf task analyze <taskId> <execId>
11
12
  * acf task suggest-schedule <id>
12
13
  * acf app list | create | update <id> | delete <id>
14
+ * acf app upload <pkg.zip> --name <name>
15
+ * acf app upgrade-all <appId> [--strategy canary --percentage N]
13
16
  * acf app analyze <id>
17
+ * acf task webhook <enable|rotate|disable|status> <taskId>
18
+ * acf task glue <taskId> -f <file>
19
+ * acf approval list | approve <id> --note … | reject <id> | cancel <id>
14
20
  * acf deploy upgrade <deploymentId> | stop <deploymentId>
15
21
  * acf executor list | get <id> | rotate <name|id> | offline <name|id>
16
22
  * acf exec tail <execId>
@@ -18,9 +24,16 @@
18
24
  * acf audit list
19
25
  * acf sop list | show <sopId>
20
26
  * acf agent sessions
27
+ * acf apikey create --name <name> --scope <readonly|trigger|manage> [--expires <days>]
28
+ * acf apikey list | revoke <id>
21
29
  * acf config show
30
+ *
31
+ * 退出码表(docs 详见 README.md「Exit codes」,单一事实源在 src/ui.ts 的
32
+ * EXIT_CODES):0 成功;1 运行失败;2 用法/参数错误;3 认证失败;
33
+ * 4 网络失败;130 中断(SIGINT)。
22
34
  */
23
- import { Command } from 'commander';
35
+ import { Command, CommanderError } from 'commander';
36
+ import { pathToFileURL } from 'node:url';
24
37
  import chalk from 'chalk';
25
38
  import { loginCommand } from './commands/login.js';
26
39
  import { tasksCommand } from './commands/tasks.js';
@@ -32,7 +45,11 @@ import { execCommand } from './commands/exec.js';
32
45
  import { projectsCommand } from './commands/projects.js';
33
46
  import { sopCommand } from './commands/sop.js';
34
47
  import { agentCommand } from './commands/agent.js';
48
+ import { apikeysCommand } from './commands/apikeys.js';
49
+ import { approvalCommand } from './commands/approval.js';
35
50
  import { showConfig, setApiUrl, setToken } from './config.js';
51
+ import { applyExamples } from './help.js';
52
+ import { EXIT_CODES, interruptExit } from './ui.js';
36
53
  // 版本号单一事实源:直接读 package.json,而不是硬编码字面量。
37
54
  //
38
55
  // 原实现写死 `.version('1.0.0')`,而 package.json 是 `version-guard` 与
@@ -44,11 +61,16 @@ import { showConfig, setApiUrl, setToken } from './config.js';
44
61
  // 视为 src 之外的输入,故走运行时解析(发布物里 package.json 与 dist/ 同级,
45
62
  // 路径稳定)。本包为 ESM(type: module),JSON 导入须带 import attribute。
46
63
  import pkg from '../package.json' with { type: 'json' };
47
- const program = new Command();
64
+ // 导出命令树供测试复用(结构守卫:每个叶子命令都必须有 Examples)。配合底部
65
+ // 的 main-guard,import 本文件不会触发 parseAsync。
66
+ export const program = new Command();
48
67
  program
49
68
  .name('acf')
50
69
  .description('AutoCodeFlow CLI — manage tasks, executions, applications and projects')
51
70
  .version(pkg.version);
71
+ // ---------------------------------------------------------------------------
72
+ // 解析期行为统一(全树,见下方 applyParseErrorBehavior 的说明)
73
+ // ---------------------------------------------------------------------------
52
74
  // Global options that override stored config
53
75
  program
54
76
  .option('--api-url <url>', 'Override API URL for this invocation (or set ACF_API_URL env var)')
@@ -71,6 +93,8 @@ program.addCommand(execCommand());
71
93
  program.addCommand(projectsCommand());
72
94
  program.addCommand(sopCommand());
73
95
  program.addCommand(agentCommand());
96
+ program.addCommand(apikeysCommand());
97
+ program.addCommand(approvalCommand());
74
98
  // acf config show / set
75
99
  const configCmd = new Command('config').description('View or update CLI configuration');
76
100
  configCmd.command('show').description('Show current config').action(() => showConfig());
@@ -81,13 +105,68 @@ configCmd.command('set-url <url>').description('Set API base URL').action((url)
81
105
  configCmd.command('set-token <token>').description('Set auth token directly').action((token) => {
82
106
  setToken(token);
83
107
  console.log(chalk.green('✔ Token saved'));
108
+ // 安全提示(与 login 的 --password 告警同风格):命令行明文 token 会留在
109
+ // shell history 与进程列表里;login(交互隐藏输入 + 落 0600 配置文件)或
110
+ // ACF_TOKEN 环境变量(不进 argv)是更安全的通路。
111
+ process.stderr.write(chalk.yellow('⚠ A token passed on the command line can leak into shell history and the process list — prefer `acf login` or the ACF_TOKEN environment variable.\n'));
84
112
  });
85
113
  program.addCommand(configCmd);
86
- // Better error display
87
- program.configureOutput({
88
- outputError: (str, write) => write(chalk.red(str)),
89
- });
90
- program.parseAsync(process.argv).catch((e) => {
91
- console.error(chalk.red('Error:'), e instanceof Error ? e.message : String(e));
92
- process.exit(1);
93
- });
114
+ // 集中式 help:把 help.ts 的 EXAMPLES 表按命令路径走树注入(每个命令至少一个
115
+ // 示例;覆盖面由 ux-uniform.test.ts 用本树做结构守卫)。
116
+ applyExamples(program);
117
+ /**
118
+ * 解析期行为统一到整棵命令树:
119
+ * - exitOverride:解析错误不再让 commander 内部直接 process.exit(1),而是抛
120
+ * CommanderError 到 runCli 的 catch 统一映射退出码(--help/--version → 0,
121
+ * 其余 → 2 用法错误)。--version 的行为由 release-metadata.test.ts 真实
122
+ * 执行构建产物钉死,改动后跑全量测试即可发现回归。
123
+ * - showHelpAfterError:缺参/未知命令/未知选项时在 error 行之后打印**该命令
124
+ * 的完整 help**(含 Examples)——用户在报错现场就能拿到可操作的用法。
125
+ * - configureOutput:error 行染红。
126
+ *
127
+ * 为什么走树补设而不是只在 program 上设一次:commander 只在 addCommand 时把
128
+ * 这些设置拷贝给**直接子命令**(copyInheritedSettings),而孙子级(task get /
129
+ * config show 等)在各命令工厂函数里创建,早于 addCommand——实测它们拿不到
130
+ * exitOverride,深层缺参错误会绕过退出码映射直接 process.exit(1),error 行也
131
+ * 不染红。在整棵树装配完成后逐命令补设是唯一覆盖全深度的方式。
132
+ */
133
+ function applyParseErrorBehavior(cmd) {
134
+ cmd.exitOverride();
135
+ cmd.showHelpAfterError();
136
+ cmd.configureOutput({
137
+ outputError: (str, write) => write(chalk.red(str)),
138
+ });
139
+ for (const sub of cmd.commands)
140
+ applyParseErrorBehavior(sub);
141
+ }
142
+ applyParseErrorBehavior(program);
143
+ /**
144
+ * Map a commander parse outcome to the CLI exit code.
145
+ * `--help` / `--version` / `acf help <cmd>` 是用户主动要的正常出口 → 0;
146
+ * 其余解析错误(缺参/未知命令/未知选项/非法取值)= 用法错误 → 2。
147
+ */
148
+ export function parseErrorExitCode(e) {
149
+ if (e instanceof CommanderError) {
150
+ return e.exitCode === 0 ? EXIT_CODES.OK : EXIT_CODES.USAGE;
151
+ }
152
+ return EXIT_CODES.GENERIC;
153
+ }
154
+ // 仅当本文件是进程入口时才启动解析。测试需要 import 本文件复用**真实**命令树
155
+ // (example 覆盖守卫不能靠复刻一份会漂移的镜像树),main-guard 让 import 无
156
+ // 副作用;正常执行路径(node dist/index.js、tsx src/index.ts、npm bin)下
157
+ // argv[1] 与本模块 URL 指向同一文件,守卫恒真。
158
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
159
+ // SIGINT 统一出口:Ctrl+C 补换行(spinner 帧不留半行)并以 128+SIGINT 惯例
160
+ // 码 130 退出。交互 readline 的 raw 模式不走进程信号,由各 prompt 内的
161
+ // rl.on('SIGINT') 接住后也汇入同一个 interruptExit。
162
+ process.on('SIGINT', () => interruptExit());
163
+ program.parseAsync(process.argv).catch((e) => {
164
+ if (e instanceof CommanderError) {
165
+ // error 行与 help 已由 commander 经 outputError/print 写出,这里只做
166
+ // 退出码映射,不重复打印。
167
+ process.exit(parseErrorExitCode(e));
168
+ }
169
+ console.error(chalk.red('Error:'), e instanceof Error ? e.message : String(e));
170
+ process.exit(EXIT_CODES.GENERIC);
171
+ });
172
+ }
package/dist/ui.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * CLI 退出码表(README.md「Exit codes」为同一张表的人读版,两处必须同步改):
3
+ * 0 成功(含 --help / --version)
4
+ * 1 运行失败:服务端拒绝(400/403/404/409/5xx)、失败终态(--wait)、
5
+ * lint 语法错误、非 UsageError 的本地错误
6
+ * 2 用法/参数错误:缺参、未知命令/选项、非法取值(commander 解析层),
7
+ * 以及本地参数派生错误(lint 无法推断语言、JSON payload 解析失败)
8
+ * 3 认证失败:401(凭据缺失/过期且 401 自愈失败)→ 运行 acf login
9
+ * 4 网络失败:连接不通/超时/DNS → 检查 --api-url / ACF_API_URL
10
+ * 130 中断(SIGINT / Ctrl+C,128+2 惯例)
11
+ */
12
+ export declare const EXIT_CODES: {
13
+ readonly OK: 0;
14
+ readonly GENERIC: 1;
15
+ readonly USAGE: 2;
16
+ readonly AUTH: 3;
17
+ readonly NETWORK: 4;
18
+ readonly INTERRUPTED: 130;
19
+ };
20
+ /**
21
+ * 本地参数/负载层面的用法错误。与服务端拒绝区分开,让脚本能区分
22
+ * 「我的命令写错了(2)」和「服务端没答应(1)」。命令层抛出本类型,
23
+ * exitCodeFor 统一识别,不需要每个 catch 各自判断。
24
+ */
25
+ export declare class UsageError extends Error {
26
+ }
27
+ /** spinner 的最小结构面(ora 实例天然满足),避免 ui 层反向依赖 ora。 */
28
+ interface Failable {
29
+ fail(message?: string): unknown;
30
+ }
31
+ /**
32
+ * Map a thrown error to its exit code. `UsageError`(本地用法错误)优先——
33
+ * 它不是 axios 错误,若先走 classifyApiError 会被误归为 GENERIC。
34
+ */
35
+ export declare function exitCodeFor(e: unknown): number;
36
+ /**
37
+ * 统一错误出口。有 spinner 时 `spinner.fail(scope)`(失败行与进行中的转圈
38
+ * 原位收尾);无 spinner 时打 `✗ scope`。错误详情一律走 formatApiError,
39
+ * 保证 401/网络/后端 message 的呈现全 CLI 一致。
40
+ */
41
+ export declare function emitError(scope: string, e: unknown, opts?: {
42
+ spinner?: Failable;
43
+ }): never;
44
+ /**
45
+ * 本地用法错误出口(不涉及 API 调用)。第二条提示固定指向 `--help`——
46
+ * 每个叶子命令的帮助里都有示例,用户不需要去翻文档。
47
+ */
48
+ export declare function emitUsageError(message: string): never;
49
+ /**
50
+ * 中断(SIGINT / Ctrl+C)统一出口:补一个换行让被 spinner/提示符啃掉一半的
51
+ * 输出行完整落地,退出码 130。进程级 handler 与交互 readline 的 raw 模式
52
+ * `rl.on('SIGINT')` 共用这一个出口。
53
+ */
54
+ export declare function interruptExit(): never;
55
+ export {};
package/dist/ui.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Unified terminal-output / exit-code layer for the CLI.
3
+ *
4
+ * 背景:10 个命令文件此前各自复制同一套「spinner.fail → console.error(red) →
5
+ * process.exit(1)」三连(约 40 处),失败类别(认证/网络/服务端/参数)全部挤在
6
+ * 退出码 1 里,CI 无法分类处理。本层把出口收敛为一个帮手:
7
+ * - 错误分类在 client 层做一次(classifyApiError),这里只负责映射退出码;
8
+ * - 人读文案沿用 formatApiError(含后端 message 与「下一步动作」提示);
9
+ * - spinner 的 scope 文案由调用方传入,保持各命令既有的失败措辞。
10
+ */
11
+ import chalk from 'chalk';
12
+ import { classifyApiError, formatApiError } from './client.js';
13
+ /**
14
+ * CLI 退出码表(README.md「Exit codes」为同一张表的人读版,两处必须同步改):
15
+ * 0 成功(含 --help / --version)
16
+ * 1 运行失败:服务端拒绝(400/403/404/409/5xx)、失败终态(--wait)、
17
+ * lint 语法错误、非 UsageError 的本地错误
18
+ * 2 用法/参数错误:缺参、未知命令/选项、非法取值(commander 解析层),
19
+ * 以及本地参数派生错误(lint 无法推断语言、JSON payload 解析失败)
20
+ * 3 认证失败:401(凭据缺失/过期且 401 自愈失败)→ 运行 acf login
21
+ * 4 网络失败:连接不通/超时/DNS → 检查 --api-url / ACF_API_URL
22
+ * 130 中断(SIGINT / Ctrl+C,128+2 惯例)
23
+ */
24
+ export const EXIT_CODES = {
25
+ OK: 0,
26
+ GENERIC: 1,
27
+ USAGE: 2,
28
+ AUTH: 3,
29
+ NETWORK: 4,
30
+ INTERRUPTED: 130,
31
+ };
32
+ /**
33
+ * 本地参数/负载层面的用法错误。与服务端拒绝区分开,让脚本能区分
34
+ * 「我的命令写错了(2)」和「服务端没答应(1)」。命令层抛出本类型,
35
+ * exitCodeFor 统一识别,不需要每个 catch 各自判断。
36
+ */
37
+ export class UsageError extends Error {
38
+ }
39
+ /**
40
+ * Map a thrown error to its exit code. `UsageError`(本地用法错误)优先——
41
+ * 它不是 axios 错误,若先走 classifyApiError 会被误归为 GENERIC。
42
+ */
43
+ export function exitCodeFor(e) {
44
+ if (e instanceof UsageError)
45
+ return EXIT_CODES.USAGE;
46
+ switch (classifyApiError(e)) {
47
+ case 'auth':
48
+ return EXIT_CODES.AUTH;
49
+ case 'network':
50
+ return EXIT_CODES.NETWORK;
51
+ default:
52
+ return EXIT_CODES.GENERIC;
53
+ }
54
+ }
55
+ /**
56
+ * 统一错误出口。有 spinner 时 `spinner.fail(scope)`(失败行与进行中的转圈
57
+ * 原位收尾);无 spinner 时打 `✗ scope`。错误详情一律走 formatApiError,
58
+ * 保证 401/网络/后端 message 的呈现全 CLI 一致。
59
+ */
60
+ export function emitError(scope, e, opts = {}) {
61
+ if (opts.spinner) {
62
+ opts.spinner.fail(scope);
63
+ }
64
+ else {
65
+ console.error(chalk.red(`✗ ${scope}`));
66
+ }
67
+ console.error(chalk.red(formatApiError(e)));
68
+ process.exit(exitCodeFor(e));
69
+ }
70
+ /**
71
+ * 本地用法错误出口(不涉及 API 调用)。第二条提示固定指向 `--help`——
72
+ * 每个叶子命令的帮助里都有示例,用户不需要去翻文档。
73
+ */
74
+ export function emitUsageError(message) {
75
+ console.error(chalk.red(`✗ ${message}`));
76
+ console.error(chalk.gray("Run the command with '--help' to see usage and examples."));
77
+ process.exit(EXIT_CODES.USAGE);
78
+ }
79
+ /**
80
+ * 中断(SIGINT / Ctrl+C)统一出口:补一个换行让被 spinner/提示符啃掉一半的
81
+ * 输出行完整落地,退出码 130。进程级 handler 与交互 readline 的 raw 模式
82
+ * `rl.on('SIGINT')` 共用这一个出口。
83
+ */
84
+ export function interruptExit() {
85
+ process.stderr.write('\n');
86
+ process.exit(EXIT_CODES.INTERRUPTED);
87
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autocodeflow/cli",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "description": "AutoCodeFlow CLI — manage tasks, executions and applications from the terminal",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",