nx-kv 0.46.0 → 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.
Files changed (39) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +10 -4
  3. package/bin/{cli.mjs → kv.mjs} +13 -2
  4. package/package.json +23 -11
  5. package/src/core/{command-table.js → command-table.ts} +16 -5
  6. package/src/core/{config.js → config.ts} +46 -27
  7. package/src/core/db/quiet.js +4 -0
  8. package/src/core/{errors.js → errors.ts} +35 -18
  9. package/src/core/{open.js → open.ts} +3 -3
  10. package/src/core/{paths.js → paths.ts} +18 -9
  11. package/src/core/{serve-port.js → serve-port.ts} +43 -17
  12. package/src/index.js +11 -9
  13. package/src/index.ts +10 -0
  14. package/src/modules/system/actions/_manifest.generated.ts +23 -0
  15. package/src/modules/system/actions/bootstrap.ts +74 -0
  16. package/src/modules/system/actions/health.ts +57 -0
  17. package/src/modules/system/actions/routes.ts +26 -0
  18. package/src/modules/system/index.ts +29 -0
  19. package/src/modules/system/{routes.js → routes.ts} +22 -26
  20. package/src/modules/system/schemas.ts +29 -0
  21. package/src/modules/tasktool/panel-escort.js +1 -1
  22. package/src/runtime/action-base.ts +14 -0
  23. package/src/runtime/action-decorator.ts +176 -0
  24. package/src/runtime/api.ts +146 -0
  25. package/src/runtime/{cli.js → cli.ts} +241 -161
  26. package/src/runtime/codegen.ts +243 -0
  27. package/src/runtime/container.ts +53 -0
  28. package/src/runtime/{cors.js → cors.ts} +35 -28
  29. package/src/runtime/help.ts +77 -0
  30. package/src/runtime/registry.ts +139 -0
  31. package/src/runtime/{server.js → server.ts} +65 -24
  32. package/src/runtime/{spec.js → spec.ts} +122 -31
  33. package/src/runtime/types/module.ts +43 -0
  34. package/src/runtime/zod-bridge.ts +198 -0
  35. package/src/web/frontend/api/cli-tree.json +49 -0
  36. package/src/web/frontend/api/client.generated.ts +39 -0
  37. package/src/modules/system/index.js +0 -96
  38. package/src/runtime/api.js +0 -101
  39. package/src/runtime/registry.js +0 -89
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "",
3
+ "path": [],
4
+ "action": null,
5
+ "children": [
6
+ {
7
+ "name": "bootstrap",
8
+ "path": [
9
+ "bootstrap"
10
+ ],
11
+ "action": {
12
+ "id": "system.bootstrap",
13
+ "module": "system",
14
+ "summary": "聚合上下文:版本 / 登录态 / 工作空间 / 命令表",
15
+ "usage": "bootstrap",
16
+ "http": "GET /api/bootstrap"
17
+ },
18
+ "children": []
19
+ },
20
+ {
21
+ "name": "health",
22
+ "path": [
23
+ "health"
24
+ ],
25
+ "action": {
26
+ "id": "system.health",
27
+ "module": "system",
28
+ "summary": "健康检查(本机配置 + 后端可达性)",
29
+ "usage": "health",
30
+ "http": "GET /api/health"
31
+ },
32
+ "children": []
33
+ },
34
+ {
35
+ "name": "routes",
36
+ "path": [
37
+ "routes"
38
+ ],
39
+ "action": {
40
+ "id": "system.routes",
41
+ "module": "system",
42
+ "summary": "命令 ↔ 路由对照表(--module 过滤;--http 反查命令)",
43
+ "usage": "routes",
44
+ "http": null
45
+ },
46
+ "children": []
47
+ }
48
+ ]
49
+ }
@@ -0,0 +1,39 @@
1
+ // AUTO-GENERATED —— 由 scripts/gen-api-client.mjs(runtime/codegen.ts)生成,勿手改。
2
+ //
3
+ // 类型来自 zod schema(import type,zod 运行时不进浏览器包);运行时校验在服务端
4
+ //(runtime/zod-bridge.ts,CLI 与 HTTP 共用同一份 schema)。传输层是手写的那一半:
5
+ // 调 createApiClient 时传入 api/client.ts 的 api() 即可。
6
+ // 重新生成:pnpm gen:api。新鲜度由 tests/unit/api-client.test.mjs 对账。
7
+
8
+
9
+ import type {
10
+ BootstrapAction,
11
+ HealthAction,
12
+ } from '../../../modules/system/actions/_manifest.generated.js';
13
+
14
+ /** 传输层契约(手写的那一半):返回 data(错误信封由 api() 拆好,失败即 throw)。 */
15
+ export interface Transport {
16
+ request(method: string, path: string, body?: unknown): Promise<unknown>;
17
+ }
18
+
19
+ export interface ApiClient {
20
+ /** 聚合上下文:版本 / 登录态 / 工作空间 / 命令表 */
21
+ bootstrap(): Promise<Awaited<ReturnType<InstanceType<typeof BootstrapAction>['bootstrap']>>>;
22
+ /** 健康检查(本机配置 + 后端可达性) */
23
+ health(): Promise<Awaited<ReturnType<InstanceType<typeof HealthAction>['health']>>>;
24
+ }
25
+
26
+ export function createApiClient(transport: Transport): ApiClient {
27
+ return {
28
+ // action: system.bootstrap
29
+ async bootstrap() {
30
+ const path = `/api/bootstrap`;
31
+ return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof BootstrapAction>['bootstrap']>>;
32
+ },
33
+ // action: system.health
34
+ async health() {
35
+ const path = `/api/health`;
36
+ return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof HealthAction>['health']>>;
37
+ },
38
+ };
39
+ }
@@ -1,96 +0,0 @@
1
- // 系统模块:聚合与自检。没有业务状态,也没有面板视图。
2
- //
3
- // 分层例外:本模块是刻意的聚合器,允许 import 其他模块的 service。
4
- //
5
- // `routes`(命令表对照)不在这里:它的数据源 ALL_COMMANDS 只有 runtime 知道,
6
- // 放在模块里就得反着依赖 runtime。逻辑在 ./routes.js(纯函数,表由调用方传入),
7
- // 命令本身作为平台命令挂在 runtime/cli.js 的 BUILTINS 上。
8
- import { readFileSync } from 'node:fs';
9
- import { configPathFromEnv, loadConfig } from '../../core/config.js';
10
- import { commandTable } from '../../core/command-table.js';
11
- import { listGroups } from '../../core/kvapi.js';
12
- import { APP_NAME, DEFAULT_PORT } from '../../core/paths.js';
13
-
14
- const VERSION = JSON.parse(
15
- readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')
16
- ).version;
17
-
18
- // 面板启动上下文。groups 失败不致命——未登录时面板仍应能打开并提示去登录,
19
- // 所以这里降级成空数组而不抛。
20
- async function bootstrap() {
21
- const cfg = await loadConfig();
22
- let groups = [];
23
- let groupsError = '';
24
- if (cfg.token) {
25
- try {
26
- groups = await listGroups();
27
- } catch (e) {
28
- groupsError = String(e.message || e);
29
- }
30
- }
31
- return {
32
- // app 段是跨项目的认领签名:serve 端口被占时靠 app.name 判断
33
- // 「上面跑的是不是本项目的面板」——相等则复用,不等则顺延端口。
34
- app: { name: APP_NAME, version: VERSION },
35
- version: VERSION,
36
- configPath: configPathFromEnv(),
37
- baseUrl: cfg.baseUrl,
38
- loggedIn: !!cfg.token,
39
- email: cfg.email,
40
- userId: cfg.userId,
41
- groupId: cfg.groupId,
42
- groups,
43
- groupsError,
44
- defaultPort: DEFAULT_PORT,
45
- // serve 进程的工作目录:仓库页「扫描」的缺省根目录用它(面板进程 cwd 即宿主项目)
46
- projectRoot: process.cwd(),
47
- // 命令表由 runtime 写进 core 的快照(见 core/command-table.js)。
48
- // 没有快照时给空数组:面板照常打开,只是没有「CLI 等价」提示。
49
- commands: commandTable(),
50
- };
51
- }
52
-
53
- export default {
54
- id: 'system',
55
- title: '系统',
56
- order: 0,
57
-
58
- actions: [
59
- {
60
- id: 'system.bootstrap',
61
- cli: ['bootstrap'],
62
- http: ['GET', '/api/bootstrap'],
63
- summary: '聚合上下文:版本 / 登录态 / 工作空间 / 命令表',
64
- run: bootstrap,
65
- },
66
- {
67
- id: 'system.health',
68
- cli: ['health'],
69
- http: ['GET', '/api/health'],
70
- summary: '健康检查(本机配置 + 后端可达性)',
71
- run: async () => {
72
- const cfg = await loadConfig();
73
- let backend = 'unreachable';
74
- let backendError = '';
75
- try {
76
- const res = await fetch(cfg.baseUrl.replace(/\/$/, '') + '/api/v1/user/info', {
77
- headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
78
- signal: AbortSignal.timeout(6000),
79
- });
80
- backend = res.ok ? 'reachable' : `http ${res.status}`;
81
- } catch (e) {
82
- backendError = String(e.message || e);
83
- }
84
- return {
85
- status: 'ok',
86
- version: VERSION,
87
- baseUrl: cfg.baseUrl,
88
- configPath: configPathFromEnv(),
89
- loggedIn: !!cfg.token,
90
- backend,
91
- backendError,
92
- };
93
- },
94
- },
95
- ],
96
- };
@@ -1,101 +0,0 @@
1
- // HTTP 路由表:由 action.http 编译而来,与 CLI 同源。
2
- //
3
- // 这里没有手写路由 —— 每条路由都来自某个模块的 action 声明,
4
- // 所以「面板上有按钮、CLI 里没命令」在结构上不可能发生。
5
- import { ACTIONS } from './registry.js';
6
- import { compileRoute, applySpec } from './spec.js';
7
- import { toErrorPayload, httpStatusOf } from '../core/errors.js';
8
-
9
- // 逐段比较两条模式,决定谁该先匹配:**字面量段优先于参数段**,段数多的优先。
10
- //
11
- // 为什么要排序而不是按声明顺序:`GET /api/repos/status` 与 `GET /api/repos/:id`
12
- // 都能匹配 `/api/repos/status`,谁先声明谁赢。一旦有人调整 actions 顺序,
13
- // 前者就会被后者抢走——这种 bug 只在运行时、且只在特定路径上出现,极难排查。
14
- // 排序后,声明顺序不再影响匹配结果。
15
- function routeSpecificity([, pattern]) {
16
- return pattern.split('/').filter(Boolean);
17
- }
18
-
19
- function compareRoutes(a, b) {
20
- const pa = routeSpecificity(a.action.http);
21
- const pb = routeSpecificity(b.action.http);
22
- for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
23
- const litA = !pa[i].startsWith(':');
24
- const litB = !pb[i].startsWith(':');
25
- if (litA !== litB) return litA ? -1 : 1; // 字面量在前
26
- }
27
- return pb.length - pa.length; // 更长的(更具体)在前
28
- }
29
-
30
- const ROUTES = ACTIONS.filter((a) => a.http)
31
- .map((action) => ({ action, route: compileRoute(action) }))
32
- .sort(compareRoutes);
33
-
34
- export function sendJson(res, status, obj) {
35
- res.writeHead(status, {
36
- 'content-type': 'application/json; charset=utf-8',
37
- 'cache-control': 'no-store',
38
- });
39
- res.end(JSON.stringify(obj));
40
- }
41
-
42
- // 请求体上限。定得比较宽是因为**附件上传走 base64 JSON**(面板选图 → data URL →
43
- // 这里),base64 有 ~33% 膨胀,10MB 的图片会变成 ~13MB 的 JSON。
44
- // 仍然有上限:本机单用户工具,但没有上限就等于「一个请求能吃掉全部内存」。
45
- const MAX_BODY_BYTES = 24 * 1024 * 1024;
46
-
47
- async function readBody(req) {
48
- const chunks = [];
49
- let size = 0;
50
- for await (const c of req) {
51
- size += c.length;
52
- if (size > MAX_BODY_BYTES) throw new Error(`请求体过大(上限 ${MAX_BODY_BYTES / 1024 / 1024}MB)`);
53
- chunks.push(c);
54
- }
55
- if (!chunks.length) return {};
56
- return JSON.parse(Buffer.concat(chunks).toString('utf8'));
57
- }
58
-
59
- export async function handleApi(req, res, url) {
60
- const method = (req.method || 'GET').toUpperCase();
61
-
62
- for (const { action, route } of ROUTES) {
63
- if (route.method !== method) continue;
64
- const m = route.regex.exec(url.pathname);
65
- if (!m) continue;
66
-
67
- // 这里不再按 Origin 拒绝写请求(任务 #57)。
68
- // 原先那道校验比对 Origin 主机名是不是 127.0.0.1——但浏览器对 POST 一律带
69
- // Origin(哪怕同源),于是走内网穿透从手机访问时 Origin 是隧道域名,
70
- // 自己面板的同源写请求被判成跨站 → 403,任务提交不了。
71
- // 跨域改由标准 CORS 头处理(预检 + allow-origin),见 runtime/cors.js。
72
-
73
- try {
74
- const raw = {};
75
- route.keys.forEach((k, i) => {
76
- raw[k] = decodeURIComponent(m[i + 1]);
77
- });
78
- if (method === 'GET' || method === 'HEAD') {
79
- for (const [k, v] of url.searchParams) raw[k] = v;
80
- } else {
81
- Object.assign(raw, await readBody(req).catch(() => ({})));
82
- }
83
- // stream 模式:把 req/res/url 透传给 run,让 action 自己接管响应(SSE 等)
84
- if (action.stream) {
85
- await action.run({ ...applySpec(action, raw), __raw: { req, res, url } }, { transport: 'http' });
86
- return;
87
- }
88
- const data = await action.run(applySpec(action, raw), { transport: 'http' });
89
- sendJson(res, 200, { ok: true, data });
90
- } catch (err) {
91
- // 错误码 → HTTP 状态只在这一处映射(core/errors.js 提供表)
92
- const p = toErrorPayload(err);
93
- const payload = { ok: false, error: p.message, code: p.code };
94
- if (p.details !== undefined) payload.details = p.details;
95
- sendJson(res, httpStatusOf(p.code), payload);
96
- }
97
- return;
98
- }
99
-
100
- sendJson(res, 404, { ok: false, error: '接口不存在: ' + method + ' ' + url.pathname });
101
- }
@@ -1,89 +0,0 @@
1
- // 模块注册表:所有功能域的 action 在此汇合。
2
- //
3
- // CLI 命令表、HTTP 路由表、help 文本三者全部由此派生 —— 这是
4
- // 「Web 上每个操作都有等价 CLI 命令」得以成为**结构性保证**而非口头约定的原因:
5
- // 一条 action 同时声明 cli 与 http,二者写在同一处,不可能分叉。
6
- //
7
- // 新增功能域:
8
- // 1. 写 src/modules/<name>/(index.js 声明 actions,service.js 写业务)
9
- // 2. 在下面 import 并加进 MODULES
10
- // 3. 需要面板的话,到 web/frontend/page/<name>/ 写视图,并在
11
- // web/frontend/registry.js 登记 —— **这一步不经过后端**
12
- //
13
- // 前端怎么呈现,后端不知道也不该知道:本文件里没有任何前端路径。
14
- // 后端只提供 `/api/*`,前端只消费 `/api/*`,跨端的唯一例外是同构纯函数
15
- // (src/shared/,见 eslint.config.js 的分层规则)。
16
- // tests/unit/registry.test.mjs 会断言两侧的模块集合对齐,漏登记直接测试失败。
17
- import { cliPathsOf, entryOf } from './spec.js';
18
- import { publishCommandTable } from '../core/command-table.js';
19
- import system from '../modules/system/index.js';
20
- import setting from '../modules/setting/index.js';
21
- import auth from '../modules/auth/index.js';
22
- import localtask from '../modules/localtask/index.js';
23
- import tasktool from '../modules/tasktool/index.js';
24
- import todo from '../modules/todo/index.js';
25
- import repos from '../modules/repos/index.js';
26
- import docs from '../modules/docs/index.js';
27
- import file from '../modules/file/index.js';
28
- import templates from '../modules/templates/index.js';
29
- import bundled from '../modules/bundled/index.js';
30
- import db from '../modules/db/index.js';
31
-
32
- // 工作空间(group)已于 2026-10-23 并入 todo 模块:它是**清单的设置**,
33
- // 不该单独占一个模块/一个 tab。命令与路由一字未改。
34
- export const MODULES = [system, setting, auth, localtask, tasktool, todo, repos, docs, file, templates, bundled, db].sort(
35
- (a, b) => (a.order ?? 100) - (b.order ?? 100)
36
- );
37
-
38
- export const ACTIONS = MODULES.flatMap((m) =>
39
- (m.actions || []).map((a) => ({ ...a, module: m.id }))
40
- );
41
-
42
- // 装载期自检:把「两个模块声明了同名命令」这类问题暴露在启动瞬间,
43
- // 而不是等某个用户敲到那条命令时才发现。
44
- //
45
- // 方向性约定(刻意的不对称):
46
- // - 每条 action 都必须有 cli —— 保证「Web 上能做的,CLI 都能做」
47
- // - http 允许为 null(纯 CLI 命令),但**不允许**声明 http 却没有 cli
48
- const seenIds = new Set();
49
- const seenCli = new Set();
50
- const seenHttp = new Set();
51
- for (const a of ACTIONS) {
52
- if (seenIds.has(a.id)) throw new Error('action id 重复: ' + a.id);
53
- seenIds.add(a.id);
54
-
55
- const paths = cliPathsOf(a);
56
- if (!paths.length) throw new Error(`action 没有声明 CLI 命令(Web 操作必须有 CLI 等价): ${a.id}`);
57
- for (const path of paths) {
58
- const key = path.join(' ');
59
- if (seenCli.has(key)) throw new Error(`CLI 命令重复: ${key}(action ${a.id})`);
60
- seenCli.add(key);
61
- }
62
-
63
- if (a.http) {
64
- const httpKey = a.http[0] + ' ' + a.http[1];
65
- if (seenHttp.has(httpKey)) throw new Error(`HTTP 路由重复: ${httpKey}(action ${a.id})`);
66
- seenHttp.add(httpKey);
67
- } else if (a.http !== null) {
68
- throw new Error(`action 的 http 必须是路由数组或显式 null: ${a.id}`);
69
- }
70
-
71
- if (!a.run) throw new Error(`action 缺少 run: ${a.id}`);
72
-
73
- // rest flag(吃掉其后全部 token,见 spec.js)必须在声明里排最后:
74
- // CLI 是「谁的路径最长谁赢」,flag 的先后由声明顺序决定;一旦后面还跟着别的 flag,
75
- // 它就会被当成值的一部分静默吞掉——命令照跑,参数却没了。
76
- const flagNames = Object.keys(a.flags || {});
77
- const restAt = flagNames.findIndex((n) => a.flags[n].rest);
78
- if (restAt >= 0 && restAt !== flagNames.length - 1) {
79
- throw new Error(
80
- `rest flag 必须声明在 flags 的最后(其后还有: ${flagNames.slice(restAt + 1).join(', ')}): ${a.id}`
81
- );
82
- }
83
- }
84
-
85
- // 命令表快照:模块(system.bootstrap 要给面板下发「CLI 等价」)只读这份,
86
- // 不再 import runtime —— registry → modules → cli → registry 正是那条要避开的环。
87
- // cli.js 在装配出 ALL_COMMANDS 后会再覆盖一次(含 serve / help / version / routes
88
- // 这类平台命令),所以「从 CLI 跑」拿到的是完整表,纯 HTTP 场景拿到的是 action 表。
89
- publishCommandTable(ACTIONS.map(entryOf));