nx-kv 0.45.1 → 0.47.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/CHANGELOG.md +57 -0
- package/README.md +11 -5
- package/assets/kv-get/SKILL.md +1 -1
- package/assets/kv-get/references/timegoal-workflow.md +7 -7
- package/assets/kv-get/references/timegoal.md +6 -6
- package/bin/{cli.mjs → kv.mjs} +13 -2
- package/package.json +23 -11
- package/src/core/{command-table.js → command-table.ts} +16 -5
- package/src/core/{config.js → config.ts} +46 -27
- package/src/core/db/quiet.js +4 -0
- package/src/core/{errors.js → errors.ts} +35 -18
- package/src/core/{open.js → open.ts} +3 -3
- package/src/core/{paths.js → paths.ts} +18 -9
- package/src/core/{serve-port.js → serve-port.ts} +43 -17
- package/src/index.js +11 -9
- package/src/index.ts +10 -0
- package/src/modules/localtask/action-lifecycle.js +3 -6
- package/src/modules/localtask/repo/goals.js +5 -6
- package/src/modules/localtask/task-lifecycle.js +2 -2
- package/src/modules/system/actions/_manifest.generated.ts +23 -0
- package/src/modules/system/actions/bootstrap.ts +74 -0
- package/src/modules/system/actions/health.ts +57 -0
- package/src/modules/system/actions/routes.ts +26 -0
- package/src/modules/system/index.ts +29 -0
- package/src/modules/system/{routes.js → routes.ts} +22 -26
- package/src/modules/system/schemas.ts +29 -0
- package/src/modules/tasktool/index.js +4 -7
- package/src/modules/tasktool/panel-escort.js +1 -1
- package/src/modules/tasktool/plugins/goal-template.js +2 -2
- package/src/modules/tasktool/plugins/taskgoal-store.js +1 -1
- package/src/modules/tasktool/plugins/timegoal-cwd-store.js +8 -11
- package/src/modules/tasktool/plugins/timegoal-task-store.js +9 -12
- package/src/runtime/action-base.ts +14 -0
- package/src/runtime/action-decorator.ts +176 -0
- package/src/runtime/api.ts +146 -0
- package/src/runtime/{cli.js → cli.ts} +241 -161
- package/src/runtime/codegen.ts +243 -0
- package/src/runtime/container.ts +53 -0
- package/src/runtime/{cors.js → cors.ts} +35 -28
- package/src/runtime/help.ts +77 -0
- package/src/runtime/registry.ts +139 -0
- package/src/runtime/{server.js → server.ts} +65 -24
- package/src/runtime/{spec.js → spec.ts} +122 -31
- package/src/runtime/types/module.ts +43 -0
- package/src/runtime/zod-bridge.ts +198 -0
- package/src/shared/prompt-blocks.js +1 -1
- package/src/web/frontend/api/cli-tree.json +49 -0
- package/src/web/frontend/api/client.generated.ts +39 -0
- package/src/web/public/assets/{Introduction-EHroxF1H.js → Introduction-BI8Ohz1l.js} +1 -1
- package/src/web/public/assets/{bar-BvS_Jfi4.js → bar-Jfji2mz3.js} +1 -1
- package/src/web/public/assets/{cloud-DlWk0wnP.js → cloud-cFewR3CF.js} +1 -1
- package/src/web/public/assets/{composer-panel-D3w-CjhN.js → composer-panel-CcK0D4Gd.js} +1 -1
- package/src/web/public/assets/{deleted-panel-BMJEEBWD.js → deleted-panel-oN8YlGvq.js} +1 -1
- package/src/web/public/assets/{dir-BtjHgH4Q.js → dir-BuAtw08k.js} +1 -1
- package/src/web/public/assets/{group-Bxq8JamU.js → group-FRUv4mQ6.js} +1 -1
- package/src/web/public/assets/{index-ChlZPTea.js → index-CyF6nNWE.js} +2 -2
- package/src/web/public/assets/{md-history-CBqcR086.js → md-history-DErcpXhC.js} +1 -1
- package/src/web/public/assets/{overview-BP5sB1WX.js → overview-DZHcrz4u.js} +1 -1
- package/src/web/public/assets/{refs-Dt7DQIOo.js → refs-BXIwmL5W.js} +1 -1
- package/src/web/public/assets/{repos-Zl1_SfPX.js → repos-DYugJZpl.js} +1 -1
- package/src/web/public/assets/{route-crumb-PqhQSVWL.js → route-crumb-C3Ce0rzR.js} +1 -1
- package/src/web/public/assets/{settings-CXWFvvvv.js → settings-Bpazt87u.js} +2 -2
- package/src/web/public/assets/{status-tag-BK-45ld2.js → status-tag-CHCpOgMP.js} +1 -1
- package/src/web/public/assets/{task-COFIPegR.js → task-G58spmPC.js} +1 -1
- package/src/web/public/assets/{templates-CIxgTTt-.js → templates-Dr0CunY8.js} +1 -1
- package/src/web/public/assets/{tool-bar-TIqYxsQl.js → tool-bar-BSIlsHln.js} +1 -1
- package/src/web/public/index.html +1 -1
- package/src/modules/system/index.js +0 -96
- package/src/runtime/api.js +0 -101
- package/src/runtime/registry.js +0 -89
|
@@ -2,25 +2,45 @@
|
|
|
2
2
|
//
|
|
3
3
|
// 改造前这里是一个 400 行的 switch,每条命令要在 BOOL_FLAGS / helpText / case /
|
|
4
4
|
// renderXxx 四处重复登记。现在命令表、help 文本、参数校验全部由 action 声明派生,
|
|
5
|
-
// 新增命令只需在所属模块的 actions
|
|
5
|
+
// 新增命令只需在所属模块的 actions 里加一条(或按模板形态写一个 @action 装饰类)。
|
|
6
|
+
//
|
|
7
|
+
// **迁移期双通道**:@action 装饰的 zod action 走 zod-bridge(归一化 + zod 校验),
|
|
8
|
+
// legacy action 走 flags 表契约(parseRest / applySpec)。token 扫描一层两通道共用
|
|
9
|
+
// (`--` / `---` 的语义只有一份),只在「归一化 + 校验」处分叉。
|
|
6
10
|
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
7
12
|
import { APP_NAME, DEFAULT_PORT } from '../core/paths.js';
|
|
8
13
|
import { configPathFromEnv } from '../core/config.js';
|
|
9
14
|
import { toErrorPayload, exitCodeOf, badInput } from '../core/errors.js';
|
|
10
|
-
import { ACTIONS,
|
|
11
|
-
import {
|
|
15
|
+
import { ACTIONS, registry } from './registry.js';
|
|
16
|
+
import type { Registry } from './registry.js';
|
|
17
|
+
import {
|
|
18
|
+
cliPathsOf,
|
|
19
|
+
argSpecsOf,
|
|
20
|
+
flagSpecsOf,
|
|
21
|
+
applySpec,
|
|
22
|
+
usageOf,
|
|
23
|
+
entryOf,
|
|
24
|
+
type AnyAction,
|
|
25
|
+
type ArgSpecInput,
|
|
26
|
+
} from './spec.js';
|
|
27
|
+
import { normalizeCliValue, parseZodInput, type FieldDesc } from './zod-bridge.js';
|
|
28
|
+
import type { ZodBoundAction } from './action-decorator.js';
|
|
29
|
+
import { helpEntries, renderHelp, printCommandHelp } from './help.js';
|
|
12
30
|
import { publishCommandTable } from '../core/command-table.js';
|
|
13
|
-
// `routes` 的数据源是本文件的 ALL_COMMANDS,所以在**这里**装配、逻辑留在模块里。
|
|
14
|
-
// 方向是 runtime → modules(允许);模块反过来 import 本文件会成环。
|
|
15
|
-
import { ROUTES_FLAGS, filterRoutes, renderRoutes } from '../modules/system/routes.js';
|
|
16
31
|
|
|
17
|
-
const VERSION = JSON.parse(
|
|
18
|
-
readFileSync(new URL('../../package.json', import.meta.url), 'utf8')
|
|
32
|
+
const VERSION: string = JSON.parse(
|
|
33
|
+
readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
|
|
19
34
|
).version;
|
|
20
35
|
|
|
21
36
|
// ---- 平台命令:不属于任何功能域,不参与 action 表 ----
|
|
22
37
|
// 用与 action 相同的形状声明,好让参数解析与 help 生成保持同一套逻辑。
|
|
23
|
-
|
|
38
|
+
//
|
|
39
|
+
// `routes` 已迁入 system 模块(它消费的命令表来自 core 的快照格子,不再依赖本文件)。
|
|
40
|
+
// serve / help / version 暂留这里:help 与 version 要看注册表与命令表全集(模块
|
|
41
|
+
// import runtime 会成环),serve 要挂 localtask 的面板占位——迁入 platform 模块
|
|
42
|
+
// 列入后续阶段(见 plan/174 的偏离表)。
|
|
43
|
+
const BUILTINS: AnyAction[] = [
|
|
24
44
|
{
|
|
25
45
|
id: 'serve',
|
|
26
46
|
cli: ['serve'],
|
|
@@ -38,35 +58,24 @@ const BUILTINS = [
|
|
|
38
58
|
// 内网穿透 / 移动端访问(任务 #57)。收紧时只放行指定来源。
|
|
39
59
|
'allow-origin': { type: 'string', hint: '跨域来源白名单(逗号分隔);缺省放行全部' },
|
|
40
60
|
},
|
|
41
|
-
run: (ctx) => cmdServe(ctx),
|
|
61
|
+
run: (ctx) => cmdServe(ctx as ServeCtx),
|
|
42
62
|
},
|
|
43
63
|
{
|
|
44
64
|
id: 'help',
|
|
45
65
|
cli: ['help'],
|
|
46
66
|
summary: '显示帮助(可跟模块名或命令组,如 nx-kv help todo)',
|
|
47
|
-
args: [{ name: 'topic', required: false }],
|
|
67
|
+
args: [{ name: 'topic', required: false }] as ArgSpecInput[],
|
|
48
68
|
// 走标准 action 形态:--json 时 emit 会序列化返回的条目,
|
|
49
69
|
// 于是 `help --json` 输出的是可解析的命令表而非帮助文本
|
|
50
|
-
run: (ctx) => helpEntries(ctx.topic),
|
|
51
|
-
render: (entries, ctx) => renderHelp(entries, ctx.topic),
|
|
52
|
-
},
|
|
53
|
-
// 命令表对照。归 system 模块(`routes --module system` 能找到它),
|
|
54
|
-
// 但它描述的是「本文件这张表」,所以由本文件装配、不进 ACTIONS。
|
|
55
|
-
{
|
|
56
|
-
id: 'system.routes',
|
|
57
|
-
module: 'system',
|
|
58
|
-
cli: ['routes'],
|
|
59
|
-
summary: '命令 ↔ 路由对照表(--module 过滤;--http 反查命令)',
|
|
60
|
-
flags: ROUTES_FLAGS,
|
|
61
|
-
run: async (ctx) => filterRoutes(ALL_COMMANDS.map(entryOf), ctx),
|
|
62
|
-
render: renderRoutes,
|
|
70
|
+
run: (ctx) => helpEntries(ALL_COMMANDS, (ctx as { topic?: unknown }).topic),
|
|
71
|
+
render: (entries, ctx) => renderHelp(entries as ReturnType<typeof entryOf>[], (ctx as { topic?: unknown }).topic, VERSION),
|
|
63
72
|
},
|
|
64
73
|
// render 让 `nx-kv version` 输出裸版本号(脚本里可 `V=$(nx-kv version)`),
|
|
65
74
|
// 而 `--json` 仍走序列化,保持机器可读
|
|
66
|
-
{ id: 'version', cli: ['version'], summary: '显示版本', run: () => VERSION, render: (v) => v },
|
|
75
|
+
{ id: 'version', cli: ['version'], summary: '显示版本', run: () => VERSION, render: (v) => String(v) },
|
|
67
76
|
];
|
|
68
77
|
|
|
69
|
-
export const ALL_COMMANDS = [...BUILTINS, ...ACTIONS];
|
|
78
|
+
export const ALL_COMMANDS: readonly AnyAction[] = [...BUILTINS, ...ACTIONS];
|
|
70
79
|
|
|
71
80
|
// 命令表快照:registry 已经发布过「action 版」,这里覆盖成**含平台命令的完整版**。
|
|
72
81
|
// 面板(/api/bootstrap)读的是同一个格子,所以 CLI 跑起来后两边看到的是同一张表。
|
|
@@ -74,16 +83,38 @@ publishCommandTable(ALL_COMMANDS.map(entryOf));
|
|
|
74
83
|
|
|
75
84
|
// ---- 参数解析 ----
|
|
76
85
|
|
|
86
|
+
interface ServeCtx extends Record<string, unknown> {
|
|
87
|
+
port?: number;
|
|
88
|
+
'no-open'?: boolean;
|
|
89
|
+
'auto-exit'?: boolean;
|
|
90
|
+
idle?: number;
|
|
91
|
+
'allow-origin'?: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @action 装饰的 zod 通道 action(channel 标记由 zodActionsOf 写入)。 */
|
|
95
|
+
function isZodAction(cmd: AnyAction): cmd is ZodBoundAction & AnyAction {
|
|
96
|
+
return cmd.channel === 'zod';
|
|
97
|
+
}
|
|
98
|
+
|
|
77
99
|
// 全局 flag 先摘掉:它们可以出现在 argv 任意位置,不属于任何 action 的声明。
|
|
78
|
-
function splitGlobals(argv) {
|
|
79
|
-
const rest = [];
|
|
100
|
+
function splitGlobals(argv: string[]): { rest: string[]; json: boolean; cfgPath?: string } {
|
|
101
|
+
const rest: string[] = [];
|
|
80
102
|
let json = false;
|
|
81
|
-
let cfgPath;
|
|
103
|
+
let cfgPath: string | undefined;
|
|
82
104
|
for (let i = 0; i < argv.length; i++) {
|
|
83
|
-
const a = argv[i]
|
|
84
|
-
if (a === '--json') {
|
|
85
|
-
|
|
86
|
-
|
|
105
|
+
const a = argv[i]!;
|
|
106
|
+
if (a === '--json') {
|
|
107
|
+
json = true;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (a === '--config') {
|
|
111
|
+
cfgPath = argv[++i];
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (a.startsWith('--config=')) {
|
|
115
|
+
cfgPath = a.slice('--config='.length);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
87
118
|
rest.push(a);
|
|
88
119
|
}
|
|
89
120
|
return { rest, json, cfgPath };
|
|
@@ -94,45 +125,69 @@ function splitGlobals(argv) {
|
|
|
94
125
|
// 逐 token 比较(而非只取「开头连续的非 flag token」)是必需的——有些命令路径
|
|
95
126
|
// 本身就含 flag,例如 `skill install --list` 是「列出内置包」而非「安装」。
|
|
96
127
|
// 最长优先则让 ['skill','central','add'] 压过 ['skill','central'],子命令与别名因此共存。
|
|
97
|
-
export function resolveCommand(argv) {
|
|
98
|
-
let best = null;
|
|
99
|
-
let bestLen = -1;
|
|
128
|
+
export function resolveCommand(argv: string[]): { cmd: AnyAction; path: string[]; rest: string[] } | null {
|
|
129
|
+
let best: { cmd: AnyAction; path: string[]; len: number } | null = null;
|
|
100
130
|
for (const cmd of ALL_COMMANDS) {
|
|
101
131
|
for (const path of cliPathsOf(cmd)) {
|
|
102
|
-
if (path.length > argv.length || path.length <=
|
|
132
|
+
if (path.length > argv.length || path.length <= (best?.len ?? -1)) continue;
|
|
103
133
|
if (path.every((seg, i) => seg === argv[i])) {
|
|
104
|
-
best = { cmd, path };
|
|
105
|
-
bestLen = path.length;
|
|
134
|
+
best = { cmd, path, len: path.length };
|
|
106
135
|
}
|
|
107
136
|
}
|
|
108
137
|
}
|
|
109
|
-
return best ? {
|
|
138
|
+
return best ? { cmd: best.cmd, path: best.path, rest: argv.slice(best.len) } : null;
|
|
110
139
|
}
|
|
111
140
|
|
|
112
141
|
// 「像 flag」的 token:-- 后跟字母/数字才算。
|
|
113
142
|
// `---` 开头的是**正文**(markdown frontmatter / 分隔线),`--` 是「后面全是位置参数」
|
|
114
143
|
// 的约定——两者都不是 flag。任务正文以 frontmatter 开头时(`localtask add "---
|
|
115
144
|
// board: …"`)正需要这条,否则会被当成未知参数报错。
|
|
116
|
-
function looksLikeFlag(tok) {
|
|
145
|
+
function looksLikeFlag(tok: unknown): boolean {
|
|
117
146
|
return /^--[A-Za-z0-9]/.test(String(tok ?? ''));
|
|
118
147
|
}
|
|
119
148
|
|
|
120
149
|
// 解析剩余 token。布尔 flag 不吞下一个 token —— 否则 `skill install --force demo`
|
|
121
150
|
// 会把 force 解析成字符串 'demo',而 demo 本该是位置参数。
|
|
122
|
-
// 任务文本带空格时给 `--ref` 加引号(见 spec.
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
151
|
+
// 任务文本带空格时给 `--ref` 加引号(见 spec.ts 关于 rest flag 的说明)。
|
|
152
|
+
//
|
|
153
|
+
// 双通道共用这一层:bools 由调用方按通道算好传入(legacy 来自 flags 表,
|
|
154
|
+
// zod 来自 fields 的 kind)。保留 (rest, cmd) 兼容签名供单测直接调用。
|
|
155
|
+
export function parseRest(
|
|
156
|
+
rest: readonly string[],
|
|
157
|
+
cmd: AnyAction | { flags?: AnyAction['flags'] },
|
|
158
|
+
): { positionals: string[]; flags: Record<string, unknown> } {
|
|
159
|
+
const bools = booleanNamesOf(cmd as AnyAction);
|
|
160
|
+
return scanTokens(rest, bools);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function booleanNamesOf(cmd: AnyAction): Set<string> {
|
|
164
|
+
const names = new Set(flagSpecsOf(cmd).filter((f) => (f.type || 'string') === 'boolean').map((f) => f.name));
|
|
165
|
+
if (cmd.channel === 'zod') {
|
|
166
|
+
for (const f of (cmd.fields || []) as FieldDesc[]) {
|
|
167
|
+
if (!f.positional && f.kind === 'boolean') names.add(f.name);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return names;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function scanTokens(rest: readonly string[], bools: Set<string>): { positionals: string[]; flags: Record<string, unknown> } {
|
|
174
|
+
const positionals: string[] = [];
|
|
175
|
+
const flags: Record<string, unknown> = {};
|
|
127
176
|
for (let i = 0; i < rest.length; i++) {
|
|
128
|
-
const a = rest[i]
|
|
177
|
+
const a = rest[i]!;
|
|
129
178
|
if (a === '--') {
|
|
130
179
|
positionals.push(...rest.slice(i + 1));
|
|
131
180
|
break;
|
|
132
181
|
}
|
|
133
|
-
if (!looksLikeFlag(a)) {
|
|
182
|
+
if (!looksLikeFlag(a)) {
|
|
183
|
+
positionals.push(a);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
134
186
|
const eq = a.indexOf('=');
|
|
135
|
-
if (eq > 2) {
|
|
187
|
+
if (eq > 2) {
|
|
188
|
+
flags[a.slice(2, eq)] = a.slice(eq + 1);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
136
191
|
const key = a.slice(2);
|
|
137
192
|
const next = rest[i + 1];
|
|
138
193
|
if (!bools.has(key) && next !== undefined && !looksLikeFlag(next)) {
|
|
@@ -145,34 +200,79 @@ export function parseRest(rest, cmd) {
|
|
|
145
200
|
return { positionals, flags };
|
|
146
201
|
}
|
|
147
202
|
|
|
148
|
-
// 位置参数按声明顺序映射成具名输入;末尾声明 { rest: true }
|
|
149
|
-
|
|
150
|
-
|
|
203
|
+
// 位置参数按声明顺序映射成具名输入;末尾声明 { rest: true } 的收集剩余全部。
|
|
204
|
+
// zod 通道走 fields(positional 顺序)+ restArg 收尾,语义一致。
|
|
205
|
+
function mapPositionals(
|
|
206
|
+
positionals: readonly string[],
|
|
207
|
+
specs: readonly { name: string; required: boolean; rest?: boolean }[],
|
|
208
|
+
): Record<string, unknown> {
|
|
209
|
+
const out: Record<string, unknown> = {};
|
|
151
210
|
let i = 0;
|
|
152
|
-
for (const spec of
|
|
153
|
-
if (spec.rest) {
|
|
211
|
+
for (const spec of specs) {
|
|
212
|
+
if (spec.rest) {
|
|
213
|
+
out[spec.name] = positionals.slice(i);
|
|
214
|
+
i = positionals.length;
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
154
217
|
if (positionals[i] !== undefined) out[spec.name] = positionals[i];
|
|
155
218
|
i++;
|
|
156
219
|
}
|
|
157
220
|
if (i < positionals.length) {
|
|
158
|
-
throw
|
|
221
|
+
throw tooManyPositionals(positionals.slice(i));
|
|
159
222
|
}
|
|
160
223
|
return out;
|
|
161
224
|
}
|
|
162
225
|
|
|
163
226
|
// 未知 flag 直接报错——`--fiile` 这类拼写错误应该立刻被指出来,而不是被静默忽略
|
|
164
|
-
function assertKnownFlags(flags, cmd) {
|
|
227
|
+
function assertKnownFlags(flags: Record<string, unknown>, cmd: AnyAction): void {
|
|
165
228
|
const known = new Set(flagSpecsOf(cmd).map((f) => f.name));
|
|
166
229
|
for (const k of Object.keys(flags)) {
|
|
167
|
-
if (!known.has(k)) throw badInput(`未知参数 --${k}(用法见
|
|
230
|
+
if (!known.has(k)) throw badInput(`未知参数 --${k}(用法见 ${APP_NAME} help)`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function tooManyPositionals(extra: readonly string[]): Error {
|
|
235
|
+
return badInput(`多余的参数: ${extra.join(' ')}(用法见 ${APP_NAME} help)`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ---- zod 通道的输入解析(模板同款,token 扫描与 legacy 共用) ----
|
|
239
|
+
|
|
240
|
+
function parseZodChannel(cmd: ZodBoundAction, tail: readonly string[]): Record<string, unknown> {
|
|
241
|
+
const fields = cmd.fields as FieldDesc[];
|
|
242
|
+
const bools = booleanNamesOf(cmd);
|
|
243
|
+
const { positionals, flags } = scanTokens(tail, bools);
|
|
244
|
+
const usage = usageOf(cmd);
|
|
245
|
+
|
|
246
|
+
// 位置参数:按 fields 的 positional 顺序消费;restArg 收剩余全部。
|
|
247
|
+
const positionalFields = fields.filter((f) => f.positional);
|
|
248
|
+
const restCount = cmd.restArg ? 1 : 0;
|
|
249
|
+
if (positionals.length > positionalFields.length + restCount) {
|
|
250
|
+
throw badInput(`多余的参数: ${positionals.slice(positionalFields.length + restCount).join(' ')}(用法见 ${APP_NAME} help)`);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const raw: Record<string, unknown> = {};
|
|
254
|
+
positionalFields.forEach((f, i) => {
|
|
255
|
+
const v = positionals[i];
|
|
256
|
+
if (v !== undefined) raw[f.name] = normalizeCliValue(f, v);
|
|
257
|
+
});
|
|
258
|
+
if (cmd.restArg) {
|
|
259
|
+
const rest = positionals.slice(positionalFields.length);
|
|
260
|
+
const field = fields.find((f) => f.name === cmd.restArg);
|
|
261
|
+
raw[cmd.restArg] = field ? normalizeCliValue(field, rest) : rest;
|
|
168
262
|
}
|
|
263
|
+
for (const [k, v] of Object.entries(flags)) {
|
|
264
|
+
const f = fields.find((x) => x.name === k);
|
|
265
|
+
if (!f) throw badInput(`未知参数 --${k}(用法: ${usage})`);
|
|
266
|
+
raw[k] = normalizeCliValue(f, v);
|
|
267
|
+
}
|
|
268
|
+
return parseZodInput(cmd.input, raw, usage) as Record<string, unknown>;
|
|
169
269
|
}
|
|
170
270
|
|
|
171
271
|
// ---- 输出 ----
|
|
172
272
|
|
|
173
273
|
// render 拿到 (data, ctx),可以是 async——有些渲染需要补一点上下文才能标注
|
|
174
274
|
// (例如候选清单要标出哪一项是「当前」),而 `--json` 必须保持纯数据的旧形状。
|
|
175
|
-
async function emit(cmd, data, json, ctx) {
|
|
275
|
+
async function emit(cmd: AnyAction, data: unknown, json: boolean, ctx: unknown): Promise<void> {
|
|
176
276
|
// 无返回值的命令(help / serve 这类)不该打印任何东西:落进 JSON.stringify(undefined)
|
|
177
277
|
// 会打出字面量 "undefined",让 `help --json` 的 stdout 不再是合法 JSON。
|
|
178
278
|
if (data === undefined && !cmd.render) return;
|
|
@@ -194,10 +294,10 @@ async function emit(cmd, data, json, ctx) {
|
|
|
194
294
|
// 失败一律 exit 1;--json 下输出可解析的错误对象。
|
|
195
295
|
// 注意 error 保持字符串(历史契约),code 是新增字段——agent 可据此分支,
|
|
196
296
|
// 老消费方按字符串匹配「用法:」「未设置」「不存在」仍然可用。
|
|
197
|
-
function fail(err, json) {
|
|
297
|
+
function fail(err: unknown, json: boolean): void {
|
|
198
298
|
const p = toErrorPayload(err);
|
|
199
299
|
if (json) {
|
|
200
|
-
const payload = { ok: false, error: p.message, code: p.code };
|
|
300
|
+
const payload: Record<string, unknown> = { ok: false, error: p.message, code: p.code };
|
|
201
301
|
if (p.details !== undefined) payload.details = p.details;
|
|
202
302
|
console.log(JSON.stringify(payload, null, 2));
|
|
203
303
|
} else {
|
|
@@ -206,76 +306,9 @@ function fail(err, json) {
|
|
|
206
306
|
process.exitCode = exitCodeOf(p.code);
|
|
207
307
|
}
|
|
208
308
|
|
|
209
|
-
// ----
|
|
210
|
-
|
|
211
|
-
// 命令表的一行见 spec.js 的 entryOf —— 纯「声明 → 文本」,runtime/spec 之外没有副本。
|
|
212
|
-
|
|
213
|
-
// 解析帮助主题。既接受模块 id(repos),也接受命令组(repo)——
|
|
214
|
-
// 用户脑子里想的是「repo 相关的东西」,不会去记内部模块名。
|
|
215
|
-
// 这条路径不能报错退出:`nx-kv help <随便什么>` 失败会让最需要帮助的人卡住。
|
|
216
|
-
function helpEntries(topic) {
|
|
217
|
-
const all = ALL_COMMANDS.map(entryOf);
|
|
218
|
-
if (!topic) return all;
|
|
219
|
-
|
|
220
|
-
const t = String(topic);
|
|
221
|
-
if (MODULES.some((m) => m.id === t)) return all.filter((e) => e.module === t);
|
|
222
|
-
|
|
223
|
-
const byRoot = all.filter((e) => e.command.split(' ')[1] === t);
|
|
224
|
-
if (byRoot.length) return byRoot;
|
|
225
|
-
|
|
226
|
-
// 命令本身的 id 也认(如 `nx-kv help repo.add`)
|
|
227
|
-
const byId = all.filter((e) => e.id === t);
|
|
228
|
-
if (byId.length) return byId;
|
|
309
|
+
// ---- serve ----
|
|
229
310
|
|
|
230
|
-
|
|
231
|
-
throw badInput(`未知帮助主题: ${t}(可用模块: ${topics};或命令组如 repo / skill / gh)`);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function renderHelp(entries, topic) {
|
|
235
|
-
const lines = [];
|
|
236
|
-
if (!topic) {
|
|
237
|
-
lines.push(`nx-kv · nx-kv v${VERSION}`);
|
|
238
|
-
lines.push('KV 清单管理中枢:serve 驱动 CLI 与 Web,同源同构。');
|
|
239
|
-
lines.push(`配置: ${configPathFromEnv()} (环境变量 NX_KV_CONFIG 或 --config 覆盖)`);
|
|
240
|
-
lines.push('');
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
const groups = new Map();
|
|
244
|
-
for (const e of entries) {
|
|
245
|
-
if (!groups.has(e.module)) groups.set(e.module, []);
|
|
246
|
-
groups.get(e.module).push(e);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
for (const [mod, list] of groups) {
|
|
250
|
-
const title =
|
|
251
|
-
MODULES.find((m) => m.id === mod)?.title || (mod === 'platform' ? '平台命令' : mod);
|
|
252
|
-
lines.push(title + ':');
|
|
253
|
-
const width = Math.max(...list.map((e) => e.usage.length));
|
|
254
|
-
for (const e of list) lines.push(' ' + e.usage.padEnd(width + 2) + e.summary);
|
|
255
|
-
lines.push('');
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
lines.push('通用:');
|
|
259
|
-
lines.push(' --json 机器可读输出(agent 模式)');
|
|
260
|
-
lines.push(' --config 本次运行覆盖配置文件路径');
|
|
261
|
-
return lines.join('\n');
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// `nx-kv <命令> --help`:只打印这一条,而不是整个模块——
|
|
265
|
-
// 之前这里传的是 cmd.cli[0],对别名 action(cli 是数组的数组)会拼出 "bundled,list"。
|
|
266
|
-
function printCommandHelp(cmd) {
|
|
267
|
-
const lines = [usageOf(cmd)];
|
|
268
|
-
if (cmd.summary) lines.push(' ' + cmd.summary);
|
|
269
|
-
lines.push('');
|
|
270
|
-
|
|
271
|
-
const aliases = cliPathsOf(cmd).slice(1).map((p) => 'nx-kv ' + p.join(' '));
|
|
272
|
-
if (aliases.length) lines.push('别名: ' + aliases.join(' · '));
|
|
273
|
-
if (cmd.http) lines.push('对应路由: ' + cmd.http[0] + ' ' + cmd.http[1]);
|
|
274
|
-
lines.push('所属模块: ' + (cmd.module || 'platform'));
|
|
275
|
-
console.log(lines.join('\n'));
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
async function cmdServe(ctx) {
|
|
311
|
+
async function cmdServe(ctx: ServeCtx): Promise<void> {
|
|
279
312
|
const { startServer } = await import('./server.js');
|
|
280
313
|
const { startPanelIdleGuard } = await import('../modules/localtask/panel-guard.js');
|
|
281
314
|
const { registerPanel, unregisterPanel, notePanelRequest } = await import(
|
|
@@ -318,7 +351,7 @@ async function cmdServe(ctx) {
|
|
|
318
351
|
try {
|
|
319
352
|
server = await startServer({ port, host, onRequest, allowOrigin });
|
|
320
353
|
} catch (err) {
|
|
321
|
-
if (!err || err.code !== 'EADDRINUSE') throw err;
|
|
354
|
+
if (!err || (err as { code?: string }).code !== 'EADDRINUSE') throw err;
|
|
322
355
|
|
|
323
356
|
// 端口被占:先问一句「上面跑的是不是我」。
|
|
324
357
|
const decision = await resolvePortConflict(port, APP_NAME, host);
|
|
@@ -334,16 +367,19 @@ async function cmdServe(ctx) {
|
|
|
334
367
|
|
|
335
368
|
// 别人占的:顺延到下一个空闲端口,再起自己的面板。
|
|
336
369
|
console.log(
|
|
337
|
-
`端口 ${port} 已被占用(占用者: ${describeOccupant(decision.occupant)}),改用 ${decision.port}
|
|
370
|
+
`端口 ${port} 已被占用(占用者: ${describeOccupant(decision.occupant)}),改用 ${decision.port}`,
|
|
338
371
|
);
|
|
339
372
|
server = await startServer({ port: decision.port, host, onRequest, allowOrigin });
|
|
340
373
|
}
|
|
341
374
|
|
|
342
|
-
|
|
375
|
+
// server.address() 在 listening 状态下必有值且是对象(host 落地的端口);
|
|
376
|
+
// 字符串形状只出现在 unix socket(本项目不用),保守收窄一下。
|
|
377
|
+
const address = server!.address();
|
|
378
|
+
const boundPort = typeof address === 'object' && address ? address.port : 0;
|
|
379
|
+
const addr = `http://127.0.0.1:${boundPort}`;
|
|
343
380
|
|
|
344
|
-
// 登记自己:presence
|
|
381
|
+
// 登记自己:presence 要能问**所有**跑着面板的端口(只问默认端口会看不见
|
|
345
382
|
// `serve --port` 或端口被占自动顺延出来的面板 → wait 会多开窗口)。
|
|
346
|
-
const boundPort = server.address().port;
|
|
347
383
|
try {
|
|
348
384
|
registerPanel(boundPort);
|
|
349
385
|
} catch {
|
|
@@ -369,49 +405,93 @@ async function cmdServe(ctx) {
|
|
|
369
405
|
|
|
370
406
|
const shutdown = () => {
|
|
371
407
|
console.log('\n正在停止...');
|
|
372
|
-
server
|
|
408
|
+
server!.close(() => process.exit(0));
|
|
373
409
|
};
|
|
374
410
|
process.on('SIGINT', shutdown);
|
|
375
411
|
process.on('SIGTERM', shutdown);
|
|
376
412
|
|
|
377
413
|
// 启动空闲看门狗(仅 --auto-exit 模式)
|
|
378
414
|
if (autoExit) {
|
|
379
|
-
const guard = startPanelIdleGuard({ server
|
|
415
|
+
const guard = startPanelIdleGuard({ server: server!, idleSec: ctx.idle });
|
|
380
416
|
// 接上活动钩子:此后每个面板请求都会刷新「最后一次活动时间」,
|
|
381
417
|
// 空闲时长终于反映**真实使用**而不是进程启动时间。
|
|
382
418
|
noteActivity = guard.noteActivity;
|
|
383
419
|
}
|
|
384
420
|
}
|
|
385
421
|
|
|
386
|
-
// ----
|
|
422
|
+
// ---- CliApp ----
|
|
387
423
|
|
|
388
|
-
export
|
|
389
|
-
|
|
390
|
-
if (cfgPath) process.env.NX_KV_CONFIG = cfgPath;
|
|
424
|
+
export class CliApp {
|
|
425
|
+
constructor(private reg: Registry) {}
|
|
391
426
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
if (!hit) {
|
|
396
|
-
if (!rest.length) { console.log(renderHelp(helpEntries(), '')); return; }
|
|
397
|
-
console.error(`未知命令: ${rest.join(' ')}`);
|
|
398
|
-
console.error('运行 nx-kv help 查看用法');
|
|
399
|
-
process.exitCode = 1;
|
|
400
|
-
return;
|
|
427
|
+
/** 全量命令表(help / bootstrap / 面板「CLI 等价」提示共用)。 */
|
|
428
|
+
get commands(): readonly AnyAction[] {
|
|
429
|
+
return [...BUILTINS, ...this.reg.actions];
|
|
401
430
|
}
|
|
402
431
|
|
|
403
|
-
|
|
432
|
+
/** 唯一对外入口:bin/kv.mjs 与 dev(tsx 直跑)都从 run(argv) 进。 */
|
|
433
|
+
async run(argv: string[]): Promise<void> {
|
|
434
|
+
const { rest, json, cfgPath } = splitGlobals(argv);
|
|
435
|
+
if (cfgPath) process.env.NX_KV_CONFIG = cfgPath;
|
|
404
436
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
437
|
+
const hit = resolveCommand(rest);
|
|
438
|
+
|
|
439
|
+
// 无参数、或只有全局 flag:显示帮助(与历史行为一致,退出码 0)
|
|
440
|
+
if (!hit) {
|
|
441
|
+
if (!rest.length) {
|
|
442
|
+
console.log(renderHelp(helpEntries(this.commands, undefined), '', VERSION));
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
console.error(`未知命令: ${rest.join(' ')}`);
|
|
446
|
+
console.error('运行 ' + APP_NAME + ' help 查看用法');
|
|
447
|
+
process.exitCode = 1;
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const { cmd, rest: tail } = hit;
|
|
452
|
+
|
|
453
|
+
try {
|
|
454
|
+
if (tail.includes('--help')) {
|
|
455
|
+
printCommandHelp(cmd);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// 双通道分叉点:zod 走归一化 + zod 校验;legacy 走 flags 表(parseRest +
|
|
460
|
+
// assertKnownFlags + mapPositionals + applySpec)。token 扫描两层共用。
|
|
461
|
+
const input = isZodAction(cmd)
|
|
462
|
+
? parseZodChannel(cmd, tail)
|
|
463
|
+
: parseLegacyChannel(cmd, tail);
|
|
464
|
+
|
|
465
|
+
const data = await cmd.run!(input, { transport: 'cli' });
|
|
466
|
+
await emit(cmd, data, json, input);
|
|
467
|
+
} catch (err) {
|
|
468
|
+
fail(err, json);
|
|
469
|
+
}
|
|
416
470
|
}
|
|
417
471
|
}
|
|
472
|
+
|
|
473
|
+
function parseLegacyChannel(cmd: AnyAction, tail: readonly string[]): Record<string, unknown> {
|
|
474
|
+
const bools = booleanNamesOf(cmd);
|
|
475
|
+
const { positionals, flags } = scanTokens(tail, bools);
|
|
476
|
+
assertKnownFlags(flags, cmd);
|
|
477
|
+
const input = { ...mapPositionals(positionals, argSpecsOf(cmd)), ...flags };
|
|
478
|
+
return applySpec(cmd, input);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** 全项目唯一 CLI 实例(与 registry 单例配套)。 */
|
|
482
|
+
export const cliApp = new CliApp(registry);
|
|
483
|
+
|
|
484
|
+
// 兼容入口:bin/kv.mjs 与既有调用方都用它。
|
|
485
|
+
export async function runCli(argv: string[]): Promise<void> {
|
|
486
|
+
return cliApp.run(argv);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ---- 直接运行本文件时进入 CLI ----
|
|
490
|
+
// dev:`node --import tsx src/runtime/cli.ts ...`(改码即跑,无需构建);
|
|
491
|
+
// prod:bin/kv.mjs 调 runCli,argv[1] 是 bin → 此处不重复执行;被 import 时不触发。
|
|
492
|
+
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
|
493
|
+
runCli(process.argv.slice(2)).catch((err) => {
|
|
494
|
+
console.error(err && err.stack ? err.stack : String(err));
|
|
495
|
+
process.exitCode = 1;
|
|
496
|
+
});
|
|
497
|
+
}
|