@easyv/screen-cli 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @easyv/screen-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 用命令驱动 EasyV 大屏,给 AI Agent(Cursor、Claude、Codex)调用。能做三件事:
4
+
5
+ - 从零搭建一个大屏,没有合适的组件就从零开发并上传
6
+ - 修改已有大屏:改配置、配交互、接数据源、调图层
7
+ - 排查大屏:一个组件为什么不显示、点击为什么没反应
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ npm install
13
+ npm run build
14
+ npm link
15
+ ```
16
+
17
+ 安装技能到各 AI 工具的技能目录:
18
+
19
+ ```bash
20
+ easyv-screen skills install
21
+ ```
22
+
23
+ ## 配置与登录
24
+
25
+ 一个 baseURL 是一个环境。每个环境下可以有多把 API Key,环境之间的 Key 互相隔离。切到某个环境后,只能使用和切换这个环境下的 Key。
26
+
27
+ ```bash
28
+ easyv-screen config add --name dev \
29
+ --base-url http://127.0.0.1:9800/api/easyv/open/v1 \
30
+ --web http://workspace.easyv.test --use
31
+
32
+ easyv-screen config add --name test \
33
+ --base-url http://workspace.saas-test.k8s.dtstack.cn/api/easyv/open/v1 \
34
+ --web http://workspace.saas-test.k8s.dtstack.cn
35
+
36
+ easyv-screen config list
37
+ easyv-screen config use dev
38
+
39
+ easyv-screen auth add --name personal --token <appId.secret>
40
+ easyv-screen auth add --name ci --token <appId.secret>
41
+ easyv-screen auth list
42
+ easyv-screen auth use personal
43
+ easyv-screen auth login # 浏览器确认后,保存到当前环境
44
+ easyv-screen auth status # 当前环境、Key,以及绑定的空间和团队
45
+ ```
46
+
47
+ Key 在 macOS 上存进钥匙串,配置文件里只留名称。
48
+
49
+ ## 常用命令
50
+
51
+ ```bash
52
+ easyv-screen screen groups --json
53
+ easyv-screen screen create --name "销售看板" --group 1 --json
54
+ easyv-screen screen document get <id> -o doc.json
55
+ easyv-screen screen document put <id> -f doc.json --if-match <revision>
56
+ easyv-screen screen apply <id> -f ops.json --if-match <revision>
57
+ easyv-screen screen validate <id>
58
+ easyv-screen screen snapshot <id> -o preview.png
59
+
60
+ easyv-screen component list --keyword 折线
61
+ easyv-screen component fields basicLineV2 --keyword "图例"
62
+ easyv-screen component init
63
+ easyv-screen component create kpi-card --title "指标卡"
64
+ easyv-screen component publish ai_kpi_card
65
+
66
+ easyv-screen data source list --json
67
+ easyv-screen data source create --name 业务库 --type mysql --addr 10.0.0.8 \
68
+ --username app --database biz --password-env DB_PASSWORD
69
+
70
+ easyv-screen debug why-hidden <id> <key> --json
71
+ easyv-screen debug why-no-response <id> <key> --json
72
+ ```
73
+
74
+ 命令输出默认是 JSON。退出码:`0` 成功、`1` 业务错误、`2` 参数错误、`3` 认证失败、`4` 版本冲突。
75
+
76
+ ## 组件信息
77
+
78
+ 不随包维护组件文档,全部从平台实时读取:
79
+
80
+ - `component list`:组件目录,含中文名、分类和缩略图
81
+ - `component schema <module>`:从组件包静态解析出的数据字段、事件、动作、默认尺寸和全部配置字段
82
+ - `component fields <module> --keyword "图例 宽度"`:按意图查少量配置字段,拿到的 `path` 用于 `addComponent` / `setComponentConfig`
83
+
84
+ 新增组件时服务端会以组件包的默认配置为底,只叠加传入的字段。
85
+
86
+ ## 技能
87
+
88
+ | 技能 | 用途 |
89
+ | --- | --- |
90
+ | `easyv-screen-shared` | 登录、输出、乐观锁等共用规则 |
91
+ | `easyv-screen-build` | 从零搭建大屏 |
92
+ | `easyv-screen-edit` | 修改大屏、配置交互 |
93
+ | `easyv-screen-data` | 给组件接数据源 |
94
+ | `easyv-screen-debug` | 排查显隐和交互问题 |
95
+ | `easyv-component-dev` | 从零开发并上传组件 |
96
+
97
+ ## 依赖的后端
98
+
99
+ 接口契约以后端仓库 `dtstack-account` 的 `openapi/spec/openapi.v1.yaml` 为准,对应 `/api/easyv/open/v1`。
100
+ `npm run sync-spec` 把它同步到本仓库的 `spec/`(不入库,打包时自动同步);后端仓库不在同级目录时用 `EASYV_BACKEND_DIR` 指定。
101
+ 组件打包签名使用 `@easyv/cli` 提供的 `easyv` 命令,Access ID 和 Secret Key 的配置见 `easyv-component-dev` 技能。
102
+ 截图需要 `playwright` 和 Chromium。
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../dist/index.js')
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ /**
3
+ * 大屏文档的确定性排查。
4
+ *
5
+ * 只根据文档本身下结论:某个组件为什么不显示、点击为什么没反应。
6
+ * 运行时问题(数据没返回、脚本报错)不在这里。
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.locateLayer = locateLayer;
10
+ exports.whyHidden = whyHidden;
11
+ exports.whyNoResponse = whyNoResponse;
12
+ exports.inspect = inspect;
13
+ const COMPONENT_REF = /\$component\((\d+)\)/;
14
+ /** 在图层树里定位一个 key,带上所有祖先 */
15
+ function locateLayer(layers, key, ancestors = []) {
16
+ for (const node of layers) {
17
+ if (node.key === key)
18
+ return { node, ancestors };
19
+ if (node.children != null) {
20
+ const found = locateLayer(node.children, key, [...ancestors, node]);
21
+ if (found != null)
22
+ return found;
23
+ }
24
+ }
25
+ return undefined;
26
+ }
27
+ /** 一个组件为什么不显示 */
28
+ function whyHidden(document, key) {
29
+ const findings = [];
30
+ const element = document.elements?.[key];
31
+ if (element == null) {
32
+ findings.push({ level: 'error', code: 'ELEMENT_MISSING', message: `文档里没有 ${key} 这个元素` });
33
+ return findings;
34
+ }
35
+ const location = locateLayer(document.layers ?? [], key);
36
+ if (location == null) {
37
+ findings.push({ level: 'error', code: 'NOT_IN_LAYERS', message: `${key} 没有出现在图层树里,不会被渲染` });
38
+ return findings;
39
+ }
40
+ if (location.node.visible === false) {
41
+ findings.push({ level: 'warn', code: 'SELF_HIDDEN', message: `${nameOf(element, key)} 自身被设置为隐藏` });
42
+ }
43
+ for (const ancestor of location.ancestors) {
44
+ if (ancestor.visible === false) {
45
+ findings.push({
46
+ level: 'warn',
47
+ code: 'ANCESTOR_HIDDEN',
48
+ message: `被上层「${ancestor.name ?? ancestor.key}」(${ancestor.key})隐藏`,
49
+ });
50
+ }
51
+ }
52
+ if (findings.length === 0)
53
+ findings.push({ level: 'info', code: 'VISIBLE', message: `${nameOf(element, key)} 在图层树里是可见的,隐藏原因不在显隐配置` });
54
+ return findings;
55
+ }
56
+ /**
57
+ * 点击一个组件为什么没有反应。
58
+ * 默认看 trigger 为 click 的事件;可以用 trigger 指定别的触发方式。
59
+ */
60
+ function whyNoResponse(document, key, trigger = 'click') {
61
+ const findings = [];
62
+ const element = document.elements?.[key];
63
+ if (element == null) {
64
+ findings.push({ level: 'error', code: 'ELEMENT_MISSING', message: `文档里没有 ${key} 这个元素` });
65
+ return findings;
66
+ }
67
+ if (element.kind !== 'component') {
68
+ findings.push({ level: 'warn', code: 'NOT_COMPONENT', message: `${key} 是 ${element.kind},交互事件配置在组件上` });
69
+ return findings;
70
+ }
71
+ const events = (element.interactions?.events ?? []).filter(event => (event.trigger ?? 'click') === trigger);
72
+ if (events.length === 0) {
73
+ findings.push({ level: 'warn', code: 'NO_EVENT', message: `${nameOf(element, key)} 没有配置「${trigger}」事件` });
74
+ return findings;
75
+ }
76
+ for (const event of events) {
77
+ const actions = event.actions ?? [];
78
+ if (actions.length === 0) {
79
+ findings.push({ level: 'warn', code: 'NO_ACTION', message: `事件 ${event.id ?? trigger} 没有配置动作` });
80
+ continue;
81
+ }
82
+ for (const action of actions)
83
+ findings.push(...checkAction(document, event, action));
84
+ }
85
+ return findings;
86
+ }
87
+ /** 汇总一个组件的状态,作为排查入口 */
88
+ function inspect(document, key) {
89
+ const element = document.elements?.[key];
90
+ const findings = [
91
+ ...whyHidden(document, key),
92
+ ...(element?.kind === 'component' ? whyNoResponse(document, key) : []),
93
+ ];
94
+ if (element?.kind === 'component') {
95
+ const binding = element.dataBinding;
96
+ if (binding == null || binding.dataType === 'static') {
97
+ const rows = Array.isArray(element.staticData?.data) ? element.staticData?.data.length : 0;
98
+ findings.push({ level: 'info', code: 'STATIC_DATA', message: `使用静态数据,${rows} 行` });
99
+ }
100
+ else if (typeof binding.data?.['data_id'] !== 'string') {
101
+ findings.push({ level: 'error', code: 'DATA_ID_MISSING', message: `绑定类型为 ${binding.dataType},但缺少 data_id` });
102
+ }
103
+ else {
104
+ findings.push({ level: 'info', code: 'DATA_BOUND', message: `绑定 ${binding.dataType} 数据源 ${binding.data['data_id']}` });
105
+ }
106
+ }
107
+ return { element, findings };
108
+ }
109
+ function checkAction(document, event, action) {
110
+ const label = `事件 ${event.id ?? event.trigger} 的动作 ${action.action ?? '(未命名)'}`;
111
+ const targets = action.component ?? [];
112
+ if (targets.length === 0)
113
+ return [{ level: 'warn', code: 'NO_TARGET', message: `${label} 没有目标组件` }];
114
+ return targets.map((target) => {
115
+ const match = COMPONENT_REF.exec(target);
116
+ if (match == null)
117
+ return { level: 'info', code: 'TARGET_UNRESOLVED', message: `${label} 的目标 ${target} 不是组件引用,需人工确认` };
118
+ const targetKey = `c-${match[1]}`;
119
+ const targetElement = document.elements?.[targetKey];
120
+ if (targetElement == null)
121
+ return { level: 'error', code: 'TARGET_MISSING', message: `${label} 指向 ${target},但文档里没有 ${targetKey}` };
122
+ const hidden = whyHidden(document, targetKey).filter(item => item.level !== 'info');
123
+ if (hidden.length > 0)
124
+ return { level: 'warn', code: 'TARGET_HIDDEN', message: `${label} 指向 ${nameOf(targetElement, targetKey)},但它不可见:${hidden.map(item => item.message).join(';')}` };
125
+ return { level: 'info', code: 'TARGET_OK', message: `${label} 指向 ${nameOf(targetElement, targetKey)},目标存在且可见` };
126
+ });
127
+ }
128
+ function nameOf(element, key) {
129
+ return element.name != null ? `${element.name}(${key})` : key;
130
+ }
package/dist/client.js ADDED
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = exports.ApiError = exports.DEVICE_GRANT = exports.CLI_CLIENT_ID = void 0;
4
+ exports.exchangeToken = exchangeToken;
5
+ exports.createClient = createClient;
6
+ exports.exitOnError = exitOnError;
7
+ const config_1 = require("./config");
8
+ /** 和后端 `OAUTH_CLI_CLIENT_ID` 保持一致 */
9
+ exports.CLI_CLIENT_ID = 'easyv-screen-cli';
10
+ exports.DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
11
+ class ApiError extends Error {
12
+ errorCode;
13
+ status;
14
+ details;
15
+ constructor(errorCode, message, status, details) {
16
+ super(message);
17
+ this.errorCode = errorCode;
18
+ this.status = status;
19
+ this.details = details;
20
+ }
21
+ /** 0 成功、1 业务错误、2 参数错误、3 认证失败、4 冲突 */
22
+ get exitCode() {
23
+ if (this.errorCode === 'UNAUTHORIZED' || this.errorCode === 'TOKEN_EXPIRED')
24
+ return 3;
25
+ if (this.status === 409 || this.errorCode === 'REVISION_CONFLICT')
26
+ return 4;
27
+ if (this.status === 400 && this.errorCode === 'BAD_REQUEST')
28
+ return 2;
29
+ return 1;
30
+ }
31
+ }
32
+ exports.ApiError = ApiError;
33
+ class Client {
34
+ endpoint;
35
+ credential;
36
+ constructor(endpoint, credential) {
37
+ this.endpoint = endpoint;
38
+ this.credential = credential;
39
+ }
40
+ async request(method, path, options = {}) {
41
+ if (!options.anonymous)
42
+ await this.ensureFresh();
43
+ let response = await this.send(method, path, options);
44
+ if (response.status === 401 && (0, config_1.isSession)(this.credential) && !options.anonymous) {
45
+ await this.refresh();
46
+ response = await this.send(method, path, options);
47
+ }
48
+ return await readBody(response);
49
+ }
50
+ async ensureFresh() {
51
+ if (!(0, config_1.isSession)(this.credential))
52
+ return;
53
+ if (this.credential.expiresAt > Date.now() + 30_000)
54
+ return;
55
+ await this.refresh();
56
+ }
57
+ async refresh() {
58
+ if (!(0, config_1.isSession)(this.credential))
59
+ throw new ApiError('UNAUTHORIZED', '登录已失效,请重新运行 easyv-screen auth login', 401);
60
+ const next = await exchangeToken(this.endpoint, {
61
+ grant_type: 'refresh_token',
62
+ refresh_token: this.credential.refreshToken,
63
+ client_id: exports.CLI_CLIENT_ID,
64
+ });
65
+ this.credential = next;
66
+ (0, config_1.saveCurrentSession)(next);
67
+ }
68
+ async send(method, path, options) {
69
+ const url = new URL(`${this.endpoint.replace(/\/$/, '')}${path}`);
70
+ for (const [key, value] of Object.entries(options.query ?? {})) {
71
+ if (value != null)
72
+ url.searchParams.set(key, String(value));
73
+ }
74
+ const headers = {};
75
+ if (!options.anonymous) {
76
+ const token = (0, config_1.isSession)(this.credential) ? this.credential.accessToken : this.credential;
77
+ if (token == null)
78
+ throw new ApiError('UNAUTHORIZED', '当前环境还没有选择 API Key。运行 easyv-screen auth list 查看,或 easyv-screen auth add --name <名称> --token <appId.secret>', 401);
79
+ headers['authorization'] = `Bearer ${token}`;
80
+ }
81
+ if (options.ifMatch != null)
82
+ headers['if-match'] = options.ifMatch;
83
+ let body;
84
+ if (options.file != null) {
85
+ const encoded = encodeMultipart(options.file);
86
+ headers['content-type'] = `multipart/form-data; boundary=${encoded.boundary}`;
87
+ body = encoded.body;
88
+ }
89
+ else if (options.body !== undefined) {
90
+ headers['content-type'] = 'application/json';
91
+ body = JSON.stringify(options.body);
92
+ }
93
+ try {
94
+ return await fetch(url, { method, headers, body });
95
+ }
96
+ catch (error) {
97
+ throw new ApiError('NETWORK', `无法连接 ${url.origin}:${error.message}`, 0);
98
+ }
99
+ }
100
+ }
101
+ exports.Client = Client;
102
+ /** 调用 `/oauth/token`。失败时 errorCode 是 OAuth 的 error,例如 authorization_pending */
103
+ async function exchangeToken(endpoint, body) {
104
+ const url = `${endpoint.replace(/\/$/, '')}/oauth/token`;
105
+ let response;
106
+ try {
107
+ response = await fetch(url, {
108
+ method: 'POST',
109
+ headers: { 'content-type': 'application/json' },
110
+ body: JSON.stringify(body),
111
+ });
112
+ }
113
+ catch (error) {
114
+ throw new ApiError('NETWORK', `无法连接 ${url}:${error.message}`, 0);
115
+ }
116
+ const payload = await response.json().catch(() => ({}));
117
+ if (!response.ok) {
118
+ throw new ApiError(typeof payload['error'] === 'string' ? payload['error'] : `HTTP_${response.status}`, typeof payload['error_description'] === 'string' ? payload['error_description'] : `请求失败(${response.status})`, response.status);
119
+ }
120
+ const accessToken = payload['access_token'];
121
+ const refreshToken = payload['refresh_token'];
122
+ const expiresIn = payload['expires_in'];
123
+ if (typeof accessToken !== 'string' || typeof refreshToken !== 'string' || typeof expiresIn !== 'number')
124
+ throw new ApiError('BAD_REQUEST', '授权服务返回的令牌不完整', response.status);
125
+ return {
126
+ accessToken,
127
+ refreshToken,
128
+ expiresAt: Date.now() + Math.max(0, expiresIn - 30) * 1000,
129
+ };
130
+ }
131
+ async function readBody(response) {
132
+ const payload = await response.json().catch(() => ({}));
133
+ if (!response.ok) {
134
+ throw new ApiError(typeof payload['code'] === 'string'
135
+ ? payload['code']
136
+ : typeof payload['error'] === 'string' ? payload['error'] : `HTTP_${response.status}`, typeof payload['message'] === 'string'
137
+ ? payload['message']
138
+ : typeof payload['error_description'] === 'string' ? payload['error_description'] : `请求失败(${response.status})`, response.status, payload['details']);
139
+ }
140
+ return payload;
141
+ }
142
+ function encodeMultipart(file) {
143
+ const boundary = `----easyvscreen${Date.now().toString(16)}`;
144
+ const head = Buffer.from(`--${boundary}\r\n`
145
+ + `Content-Disposition: form-data; name="${file.field}"; filename="${file.filename}"\r\n`
146
+ + `Content-Type: ${file.contentType}\r\n\r\n`);
147
+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
148
+ return { boundary, body: Buffer.concat([head, file.data, tail]) };
149
+ }
150
+ function createClient(overrides = {}) {
151
+ const target = (0, config_1.activeTarget)();
152
+ const endpoint = overrides.endpoint ?? target?.baseUrl;
153
+ if (endpoint == null || endpoint.length === 0) {
154
+ throw new ApiError('BAD_REQUEST', '没有选择环境。运行 easyv-screen config add --name <名称> --base-url <地址>', 0);
155
+ }
156
+ return new Client(endpoint, target?.credential);
157
+ }
158
+ /** 打印错误并按约定退出码退出 */
159
+ function exitOnError(error) {
160
+ if (error instanceof ApiError) {
161
+ console.error(`${error.errorCode}: ${error.message}`);
162
+ if (error.details != null)
163
+ console.error(JSON.stringify(error.details, null, 2));
164
+ process.exit(error.exitCode);
165
+ }
166
+ console.error(error.message);
167
+ process.exit(1);
168
+ }