@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.
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerAuth = registerAuth;
4
+ exports.globalJson = globalJson;
5
+ const config_1 = require("../config");
6
+ const client_1 = require("../client");
7
+ const output_1 = require("../output");
8
+ function registerAuth(program) {
9
+ const auth = program.command('auth').description('登录与凭证');
10
+ auth.command('add')
11
+ .description('给当前 baseURL 添加一把 API Key,并切换到它')
12
+ .requiredOption('--name <name>', '这把 Key 的名称,只在当前环境下有效')
13
+ .requiredOption('--token <token>', 'API Key,格式 appId.secret')
14
+ .action((options) => {
15
+ try {
16
+ (0, config_1.addKey)(options.name, options.token);
17
+ const current = (0, config_1.activeTarget)();
18
+ console.log(`已在环境「${current?.name}」下保存 Key「${options.name}」并切换过去`);
19
+ }
20
+ catch (error) {
21
+ (0, client_1.exitOnError)(error);
22
+ }
23
+ });
24
+ auth.command('use')
25
+ .description('切换当前 baseURL 下的 API Key')
26
+ .argument('<name>', 'Key 名称')
27
+ .action((name) => {
28
+ try {
29
+ (0, config_1.useKey)(name);
30
+ console.log(`已切换到 Key「${name}」`);
31
+ }
32
+ catch (error) {
33
+ (0, client_1.exitOnError)(error);
34
+ }
35
+ });
36
+ auth.command('list')
37
+ .description('列出当前 baseURL 下的 API Key')
38
+ .action(function () {
39
+ try {
40
+ const target = (0, config_1.activeTarget)();
41
+ const keys = (0, config_1.listKeys)();
42
+ (0, output_1.emit)(globalJson(this), { environment: target?.name ?? null, baseUrl: target?.baseUrl ?? null, keys }, () => {
43
+ if (target == null) {
44
+ console.log('还没有选择环境');
45
+ return;
46
+ }
47
+ console.log(`环境「${target.name}」 ${target.baseUrl}`);
48
+ if (keys.length === 0) {
49
+ console.log('这个地址下还没有 API Key');
50
+ return;
51
+ }
52
+ for (const key of keys)
53
+ console.log(`${key.current ? '* ' : ' '}${key.name} ${key.appId}`);
54
+ });
55
+ }
56
+ catch (error) {
57
+ (0, client_1.exitOnError)(error);
58
+ }
59
+ });
60
+ auth.command('remove')
61
+ .description('删除当前 baseURL 下的一把 API Key')
62
+ .argument('<name>', 'Key 名称')
63
+ .action((name) => {
64
+ try {
65
+ (0, config_1.removeKey)(name);
66
+ console.log(`已删除 Key「${name}」`);
67
+ }
68
+ catch (error) {
69
+ (0, client_1.exitOnError)(error);
70
+ }
71
+ });
72
+ auth.command('login')
73
+ .description('设备码登录:在浏览器确认后保存登录状态,访问令牌过期会自动刷新')
74
+ .option('--name <name>', '保存时使用的 Key 名称', 'default')
75
+ .option('--with-token <token>', '直接使用已有的 API Key(appId.secret)')
76
+ .action(async function (options) {
77
+ try {
78
+ if (options.withToken != null) {
79
+ (0, config_1.addKey)(options.name, options.withToken);
80
+ console.log(`已在当前环境下保存 Key「${options.name}」`);
81
+ return;
82
+ }
83
+ await deviceLogin(options.name);
84
+ }
85
+ catch (error) {
86
+ (0, client_1.exitOnError)(error);
87
+ }
88
+ });
89
+ auth.command('status')
90
+ .description('查看当前环境、Key,以及绑定的空间和团队')
91
+ .action(async function () {
92
+ try {
93
+ const target = (0, config_1.activeTarget)();
94
+ const keys = (0, config_1.listKeys)();
95
+ const binding = target?.token != null ? await fetchBinding() : null;
96
+ (0, output_1.emit)(globalJson(this), {
97
+ environment: target?.name ?? null,
98
+ baseUrl: target?.baseUrl ?? null,
99
+ web: target?.web ?? null,
100
+ key: target?.keyName ?? null,
101
+ space: binding?.space ?? null,
102
+ team: binding?.team ?? null,
103
+ keys,
104
+ }, () => {
105
+ console.log(`环境:${target?.name ?? '未选择'}`);
106
+ console.log(`baseURL:${target?.baseUrl ?? '未配置'}`);
107
+ console.log(`Web 地址:${target?.web ?? '未配置'}`);
108
+ console.log(`当前 Key:${target?.keyName ?? '未选择'}(这个地址下共 ${keys.length} 把)`);
109
+ console.log(`空间:${formatSide(binding?.space ?? null)}`);
110
+ console.log(`团队:${formatSide(binding?.team ?? null)}`);
111
+ });
112
+ }
113
+ catch (error) {
114
+ (0, client_1.exitOnError)(error);
115
+ }
116
+ });
117
+ auth.command('logout')
118
+ .description('移除当前 baseURL 下正在使用的 API Key 或登录状态')
119
+ .action(async () => {
120
+ try {
121
+ const target = (0, config_1.activeTarget)();
122
+ if (target?.keyName == null)
123
+ throw new Error('当前环境没有选中的 API Key');
124
+ if ((0, config_1.isSession)(target.credential))
125
+ await revokeQuietly(target.baseUrl, target.credential.refreshToken);
126
+ (0, config_1.removeKey)(target.keyName);
127
+ console.log(`已移除环境「${target.name}」下的 Key「${target.keyName}」`);
128
+ }
129
+ catch (error) {
130
+ (0, client_1.exitOnError)(error);
131
+ }
132
+ });
133
+ const config = program.command('config').description('管理 baseURL,每个地址下的 API Key 互相隔离');
134
+ config.command('add')
135
+ .description('添加一个 baseURL')
136
+ .requiredOption('--name <name>', '环境名称,用于切换')
137
+ .requiredOption('--base-url <url>', 'OpenAPI 地址,形如 http://127.0.0.1:9800/api/easyv/open/v1')
138
+ .option('--web <url>', 'Web 站点地址,用于授权页和预览页')
139
+ .option('--use', '添加后立即切换到这个环境')
140
+ .action((options) => {
141
+ try {
142
+ (0, config_1.addEnvironment)({ name: options.name, baseUrl: options.baseUrl, web: options.web, select: options.use === true });
143
+ const current = (0, config_1.activeTarget)();
144
+ console.log(`已添加环境「${options.name}」${current?.name === options.name ? ',并切换过去' : ''}`);
145
+ }
146
+ catch (error) {
147
+ (0, client_1.exitOnError)(error);
148
+ }
149
+ });
150
+ config.command('use')
151
+ .description('切换当前 baseURL,之后只能使用这个地址下的 API Key')
152
+ .argument('<name>', '环境名称')
153
+ .action((name) => {
154
+ try {
155
+ const env = (0, config_1.useEnvironment)(name);
156
+ console.log(`已切换到环境「${env.name}」 ${env.baseUrl}`);
157
+ console.log(env.currentKey != null ? `当前 Key:${env.currentKey}` : '这个地址下还没有选择 API Key');
158
+ }
159
+ catch (error) {
160
+ (0, client_1.exitOnError)(error);
161
+ }
162
+ });
163
+ config.command('list')
164
+ .description('列出全部 baseURL')
165
+ .action(function () {
166
+ const environments = (0, config_1.listEnvironments)();
167
+ (0, output_1.emit)(globalJson(this), { environments }, () => {
168
+ if (environments.length === 0) {
169
+ console.log('还没有环境。运行 easyv-screen config add --name <名称> --base-url <地址>');
170
+ return;
171
+ }
172
+ for (const env of environments) {
173
+ const key = env.currentKey ?? '未选择 Key';
174
+ console.log(`${env.current ? '* ' : ' '}${env.name} ${env.baseUrl} Key ${key}(${env.keys.length})`);
175
+ }
176
+ });
177
+ });
178
+ config.command('remove')
179
+ .description('删除一个 baseURL 及其全部 API Key')
180
+ .argument('<name>', '环境名称')
181
+ .action((name) => {
182
+ try {
183
+ (0, config_1.removeEnvironment)(name);
184
+ console.log(`已删除环境「${name}」及其 API Key`);
185
+ }
186
+ catch (error) {
187
+ (0, client_1.exitOnError)(error);
188
+ }
189
+ });
190
+ config.command('web')
191
+ .description('设置当前 baseURL 对应的 Web 站点地址')
192
+ .argument('<url>')
193
+ .action((url) => {
194
+ try {
195
+ (0, config_1.updateEnvironmentWeb)(url);
196
+ console.log('已更新当前环境的 Web 地址');
197
+ }
198
+ catch (error) {
199
+ (0, client_1.exitOnError)(error);
200
+ }
201
+ });
202
+ }
203
+ async function deviceLogin(keyName) {
204
+ const target = (0, config_1.activeTarget)();
205
+ if (target == null)
206
+ throw new client_1.ApiError('BAD_REQUEST', '还没有选择环境。先运行 easyv-screen config add --name <名称> --base-url <地址> --web <站点>', 0);
207
+ if (target.web == null)
208
+ throw new client_1.ApiError('BAD_REQUEST', '设备码登录需要 Web 地址。运行 easyv-screen config web <站点地址>', 0);
209
+ const client = (0, client_1.createClient)();
210
+ const code = await client.request('POST', '/oauth/device', {
211
+ anonymous: true,
212
+ body: { client_id: client_1.CLI_CLIENT_ID },
213
+ });
214
+ const url = `${target.web.replace(/\/$/, '')}${code.verificationPath}`;
215
+ console.log('在浏览器打开下面的地址并确认授权:');
216
+ console.log(url);
217
+ const deadline = Date.now() + code.expires_in * 1000;
218
+ while (Date.now() < deadline) {
219
+ await sleep(code.interval * 1000);
220
+ try {
221
+ const session = await (0, client_1.exchangeToken)(target.baseUrl, {
222
+ grant_type: client_1.DEVICE_GRANT,
223
+ device_code: code.device_code,
224
+ client_id: client_1.CLI_CLIENT_ID,
225
+ });
226
+ (0, config_1.addSession)(keyName, session);
227
+ const binding = await fetchBinding();
228
+ console.log(`授权成功,已保存为环境「${target.name}」的「${keyName}」。访问令牌会自动刷新,绑定${formatSide(binding.space, '空间')}、${formatSide(binding.team, '团队')}`);
229
+ return;
230
+ }
231
+ catch (error) {
232
+ if (error instanceof client_1.ApiError && error.errorCode === 'authorization_pending')
233
+ continue;
234
+ throw error;
235
+ }
236
+ }
237
+ throw new client_1.ApiError('DEVICE_CODE_EXPIRED', '授权超时,请重新运行 easyv-screen auth login', 400);
238
+ }
239
+ async function revokeQuietly(baseUrl, refreshToken) {
240
+ try {
241
+ await fetch(`${baseUrl.replace(/\/$/, '')}/oauth/revoke`, {
242
+ method: 'POST',
243
+ headers: { 'content-type': 'application/json' },
244
+ body: JSON.stringify({ token: refreshToken, client_id: client_1.CLI_CLIENT_ID }),
245
+ });
246
+ }
247
+ catch {
248
+ // 网络失败时仍然清掉本地登录状态
249
+ }
250
+ }
251
+ /** 向当前 Key 查询绑定的空间和团队。旧服务端没有名称时,name 为 null */
252
+ async function fetchBinding() {
253
+ const meta = await (0, client_1.createClient)().request('GET', '/meta');
254
+ const context = meta.context ?? {};
255
+ return {
256
+ space: { id: context.spaceId ?? null, name: nonempty(context.spaceName) },
257
+ team: { id: context.teamId ?? null, name: nonempty(context.teamName) },
258
+ };
259
+ }
260
+ function nonempty(value) {
261
+ if (value == null || value.trim() === '')
262
+ return null;
263
+ return value;
264
+ }
265
+ function formatSide(side, label) {
266
+ const prefix = label ?? '';
267
+ if (side == null)
268
+ return `${prefix}未查询`;
269
+ if (side.name != null && side.id != null)
270
+ return `${prefix}「${side.name}」(${side.id})`;
271
+ if (side.name != null)
272
+ return `${prefix}「${side.name}」`;
273
+ return `${prefix} ${side.id ?? '未知'}`.trim();
274
+ }
275
+ function sleep(ms) {
276
+ return new Promise(resolve => setTimeout(resolve, ms));
277
+ }
278
+ function globalJson(command) {
279
+ let current = command;
280
+ while (current != null) {
281
+ if (current.opts().json === true)
282
+ return true;
283
+ current = current.parent;
284
+ }
285
+ return false;
286
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerComponent = registerComponent;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const client_1 = require("../client");
8
+ const output_1 = require("../output");
9
+ const auth_1 = require("./auth");
10
+ const PROJECT_DIR = 'easyv-components';
11
+ function registerComponent(program) {
12
+ const component = program.command('component').description('组件:目录、schema,以及从零开发');
13
+ component.command('list')
14
+ .description('列出可用组件')
15
+ .option('--keyword <keyword>', '按名称或 module 过滤')
16
+ .option('--source <source>', 'platform 或 space')
17
+ .action(async function (options) {
18
+ try {
19
+ const result = await (0, client_1.createClient)().request('GET', '/components', {
20
+ query: { keyword: options.keyword },
21
+ });
22
+ const items = (result.components ?? []).filter(item => options.source == null || item.source === options.source);
23
+ (0, output_1.emit)((0, auth_1.globalJson)(this), { components: items }, () => {
24
+ for (const item of items)
25
+ console.log(`${item.source}\t${item.status}\t${item.module}@${item.version}\t${item.name}`);
26
+ });
27
+ }
28
+ catch (error) {
29
+ (0, client_1.exitOnError)(error);
30
+ }
31
+ });
32
+ component.command('schema')
33
+ .description('查看组件的配置结构')
34
+ .argument('<module>')
35
+ .option('--version <version>')
36
+ .action(async function (moduleName, options) {
37
+ try {
38
+ const result = await (0, client_1.createClient)().request('GET', `/components/${moduleName}/schema`, {
39
+ query: { version: options.version },
40
+ });
41
+ (0, output_1.emit)((0, auth_1.globalJson)(this), result, () => console.log(JSON.stringify(result, null, 2)));
42
+ }
43
+ catch (error) {
44
+ (0, client_1.exitOnError)(error);
45
+ }
46
+ });
47
+ component.command('fields')
48
+ .description('按意图查组件配置字段,如 --keyword "图例 宽度";不传关键词只看分组')
49
+ .argument('<module>')
50
+ .option('--keyword <keyword>', '中文标签或路径,空格分隔的多个词需要同时命中')
51
+ .option('--version <version>')
52
+ .option('--limit <limit>', '最多返回多少条,默认 30')
53
+ .action(async function (moduleName, options) {
54
+ try {
55
+ const result = await (0, client_1.createClient)().request('GET', `/components/${moduleName}/config-fields`, {
56
+ query: { keyword: options.keyword, version: options.version, limit: options.limit },
57
+ });
58
+ (0, output_1.emit)((0, auth_1.globalJson)(this), result, () => console.log(JSON.stringify(result, null, 2)));
59
+ }
60
+ catch (error) {
61
+ (0, client_1.exitOnError)(error);
62
+ }
63
+ });
64
+ component.command('init')
65
+ .description('在当前目录创建或复用组件工程 ./easyv-components')
66
+ .action(() => {
67
+ const packageFile = (0, node_path_1.join)(PROJECT_DIR, 'package.json');
68
+ if ((0, node_fs_1.existsSync)(packageFile)) {
69
+ console.log(`${PROJECT_DIR} 已存在,直接使用`);
70
+ return;
71
+ }
72
+ (0, node_fs_1.mkdirSync)((0, node_path_1.join)(PROJECT_DIR, 'src', 'components'), { recursive: true });
73
+ (0, node_fs_1.writeFileSync)(packageFile, JSON.stringify({
74
+ name: 'easyv-components',
75
+ version: '0.1.0',
76
+ private: true,
77
+ scripts: { start: 'easyv dev' },
78
+ easyv: {
79
+ components: 'src/components',
80
+ builder: 'react-component-builder',
81
+ },
82
+ }, null, 2));
83
+ console.log(`已创建 ${PROJECT_DIR}。打包签名需要先配置 easyv-cli 的 Access ID(只需一次)`);
84
+ });
85
+ component.command('create')
86
+ .description('在组件工程里新增一个组件骨架,module 自动加 ai_ 前缀')
87
+ .argument('<name>', '组件名,如 kpi-card')
88
+ .option('--title <title>', '显示名')
89
+ .action((name, options) => {
90
+ const moduleName = name.startsWith('ai_') ? name : `ai_${name.replace(/-/g, '_')}`;
91
+ const dir = (0, node_path_1.join)(PROJECT_DIR, 'src', 'components', moduleName);
92
+ if ((0, node_fs_1.existsSync)(dir)) {
93
+ console.error(`组件 ${moduleName} 已存在`);
94
+ process.exit(2);
95
+ }
96
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(PROJECT_DIR, 'package.json'))) {
97
+ console.error('还没有组件工程。先运行 easyv-screen component init');
98
+ process.exit(2);
99
+ }
100
+ (0, node_fs_1.mkdirSync)((0, node_path_1.join)(dir, 'config'), { recursive: true });
101
+ const config = {
102
+ base: { name: options.title ?? name, module_name: moduleName, version: '1.0.0', show: 1 },
103
+ width: 400,
104
+ height: 300,
105
+ configuration: [],
106
+ triggers: [{ name: '鼠标点击', value: 'click' }],
107
+ actions: [],
108
+ };
109
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'config', 'main.json'), JSON.stringify(config, null, 2));
110
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'config', 'main.data.json'), JSON.stringify({ data: [], fields: [] }, null, 2));
111
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'index.jsx'), componentSource());
112
+ console.log(`已创建组件 ${moduleName},目录 ${dir}`);
113
+ });
114
+ component.command('build')
115
+ .description('用 easyv-cli 打包并签名组件')
116
+ .argument('<name>', '组件目录名')
117
+ .action((name) => {
118
+ const result = (0, node_child_process_1.spawnSync)('easyv', ['pack', name], { cwd: PROJECT_DIR, stdio: 'inherit' });
119
+ if (result.status !== 0)
120
+ process.exit(result.status ?? 1);
121
+ });
122
+ component.command('publish')
123
+ .description('打包并上传组件。版本不高于平台已有版本时自动升一个补丁号')
124
+ .argument('<name>', '组件目录名')
125
+ .action(async (name) => {
126
+ try {
127
+ await publishComponent(name);
128
+ }
129
+ catch (error) {
130
+ (0, client_1.exitOnError)(error);
131
+ }
132
+ });
133
+ }
134
+ async function publishComponent(name) {
135
+ const configFile = (0, node_path_1.join)(PROJECT_DIR, 'src', 'components', name, 'config', 'main.json');
136
+ if (!(0, node_fs_1.existsSync)(configFile))
137
+ throw new Error(`找不到组件 ${name}。先运行 easyv-screen component create`);
138
+ const config = JSON.parse((0, node_fs_1.readFileSync)(configFile, 'utf8'));
139
+ const remote = await remoteVersion(config.base.module_name);
140
+ if (remote != null && compareVersion(config.base.version, remote) <= 0) {
141
+ config.base.version = bumpVersion(remote);
142
+ (0, node_fs_1.writeFileSync)(configFile, JSON.stringify(config, null, 2));
143
+ console.log(`平台已有 ${remote},本地版本提升到 ${config.base.version}`);
144
+ }
145
+ const build = (0, node_child_process_1.spawnSync)('easyv', ['pack', name], { cwd: PROJECT_DIR, stdio: 'inherit' });
146
+ if (build.status !== 0)
147
+ process.exit(build.status ?? 1);
148
+ const constantFile = (0, node_path_1.join)(PROJECT_DIR, 'build', `${name}.${config.base.version}.constant`);
149
+ if (!(0, node_fs_1.existsSync)(constantFile))
150
+ throw new Error(`没有找到打包产物 ${constantFile}`);
151
+ const uploaded = await (0, client_1.createClient)().request('POST', '/components', {
152
+ file: {
153
+ field: 'file',
154
+ filename: `${name}.constant`,
155
+ contentType: 'application/octet-stream',
156
+ data: (0, node_fs_1.readFileSync)(constantFile),
157
+ },
158
+ });
159
+ console.log(`已上传 ${uploaded.module}@${uploaded.version}(${uploaded.status})`);
160
+ }
161
+ async function remoteVersion(moduleName) {
162
+ const result = await (0, client_1.createClient)().request('GET', '/components', {
163
+ query: { keyword: moduleName },
164
+ });
165
+ const matched = (result.components ?? []).find(item => item.module === moduleName && item.source === 'space');
166
+ return matched?.version;
167
+ }
168
+ function compareVersion(left, right) {
169
+ const a = left.split('.').map(Number);
170
+ const b = right.split('.').map(Number);
171
+ for (let index = 0; index < 3; index++) {
172
+ const diff = (a[index] ?? 0) - (b[index] ?? 0);
173
+ if (diff !== 0)
174
+ return diff;
175
+ }
176
+ return 0;
177
+ }
178
+ function bumpVersion(version) {
179
+ const parts = version.split('.').map(Number);
180
+ parts[2] = (parts[2] ?? 0) + 1;
181
+ return parts.join('.');
182
+ }
183
+ function componentSource() {
184
+ return `import React from 'react';
185
+
186
+ export default function (props) {
187
+ const { left, top, width, height, id, data, configuration, emit } = props;
188
+
189
+ return (
190
+ <div className="__easyv-component" id={id} style={{ position: 'absolute', left, top, width, height }}>
191
+ {/* configuration 是按 main.json 的 configuration 归约后的配置 */}
192
+ {/* 触发事件:emit('click', data) */}
193
+ </div>
194
+ );
195
+ }
196
+ `;
197
+ }
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerData = registerData;
4
+ const client_1 = require("../client");
5
+ const output_1 = require("../output");
6
+ const auth_1 = require("./auth");
7
+ /**
8
+ * 数据源命令。
9
+ * 密码只接受环境变量或标准输入,不接受命令行参数,避免留在 shell 历史里。
10
+ */
11
+ function registerData(program) {
12
+ const data = program.command('data').description('数据源');
13
+ const source = data.command('source').description('数据源连接');
14
+ source.command('list')
15
+ .description('列出数据源')
16
+ .option('--type <dataType>', '按类型过滤,如 mysql')
17
+ .action(async function (options) {
18
+ await run(this, () => (0, client_1.createClient)().request('GET', '/data-sources', { query: { dataType: options.type } }));
19
+ });
20
+ source.command('get')
21
+ .argument('<dataId>')
22
+ .description('查看数据源详情(密码已掩码)')
23
+ .action(async function (dataId) {
24
+ await run(this, () => (0, client_1.createClient)().request('GET', `/data-sources/${dataId}`));
25
+ });
26
+ source.command('create')
27
+ .description('新建数据源')
28
+ .requiredOption('--name <name>')
29
+ .requiredOption('--type <dataType>', '如 mysql、postgresql、api')
30
+ .option('--addr <addr>')
31
+ .option('--port <port>')
32
+ .option('--username <username>')
33
+ .option('--database <database>')
34
+ .option('--base-url <baseURL>', 'API、MQTT、WebSocket 的地址')
35
+ .option('--password-env <env>', '从环境变量读取密码')
36
+ .option('--password-stdin', '从标准输入读取密码')
37
+ .action(async function (options) {
38
+ try {
39
+ const body = await toInput(options);
40
+ const result = await (0, client_1.createClient)().request('POST', '/data-sources', { body });
41
+ (0, output_1.emit)((0, auth_1.globalJson)(this), result, () => console.log(JSON.stringify(result, null, 2)));
42
+ }
43
+ catch (error) {
44
+ (0, client_1.exitOnError)(error);
45
+ }
46
+ });
47
+ source.command('update')
48
+ .argument('<dataId>')
49
+ .description('更新数据源,不传密码则保留原密码')
50
+ .option('--name <name>')
51
+ .option('--addr <addr>')
52
+ .option('--port <port>')
53
+ .option('--username <username>')
54
+ .option('--database <database>')
55
+ .option('--base-url <baseURL>')
56
+ .option('--password-env <env>')
57
+ .option('--password-stdin')
58
+ .action(async function (dataId, options) {
59
+ try {
60
+ const body = await toInput(options);
61
+ const result = await (0, client_1.createClient)().request('PATCH', `/data-sources/${dataId}`, { body });
62
+ (0, output_1.emit)((0, auth_1.globalJson)(this), result, () => console.log('已更新'));
63
+ }
64
+ catch (error) {
65
+ (0, client_1.exitOnError)(error);
66
+ }
67
+ });
68
+ source.command('delete')
69
+ .argument('<dataId>')
70
+ .description('删除数据源')
71
+ .action(async (dataId) => {
72
+ try {
73
+ await (0, client_1.createClient)().request('DELETE', `/data-sources/${dataId}`);
74
+ console.log('已删除');
75
+ }
76
+ catch (error) {
77
+ (0, client_1.exitOnError)(error);
78
+ }
79
+ });
80
+ source.command('test')
81
+ .argument('<dataId>')
82
+ .description('测试连接')
83
+ .action(async function (dataId) {
84
+ await run(this, () => (0, client_1.createClient)().request('POST', `/data-sources/${dataId}/test`));
85
+ });
86
+ source.command('tables')
87
+ .argument('<dataId>')
88
+ .description('列出表')
89
+ .action(async function (dataId) {
90
+ await run(this, () => (0, client_1.createClient)().request('GET', `/data-sources/${dataId}/tables`));
91
+ });
92
+ source.command('columns')
93
+ .argument('<dataId>')
94
+ .requiredOption('--table <table>', '表名')
95
+ .description('列出表字段')
96
+ .action(async function (dataId, options) {
97
+ await run(this, () => (0, client_1.createClient)().request('POST', `/data-sources/${dataId}/columns`, {
98
+ body: { tables: [{ tableName: options.table }] },
99
+ }));
100
+ });
101
+ source.command('preview')
102
+ .argument('<dataId>')
103
+ .description('预览数据')
104
+ .option('--sql <sql>', 'SQL 查询')
105
+ .action(async function (dataId, options) {
106
+ await run(this, () => (0, client_1.createClient)().request('POST', `/data-sources/${dataId}/preview`, {
107
+ body: { ...(options.sql != null ? { sql: options.sql } : {}) },
108
+ }));
109
+ });
110
+ }
111
+ async function toInput(options) {
112
+ const password = await resolvePassword(options);
113
+ return {
114
+ ...(options.name != null ? { name: options.name } : {}),
115
+ ...(options.type != null ? { dataType: options.type } : {}),
116
+ ...(options.addr != null ? { addr: options.addr } : {}),
117
+ ...(options.port != null ? { port: Number(options.port) } : {}),
118
+ ...(options.username != null ? { username: options.username } : {}),
119
+ ...(options.database != null ? { database: options.database } : {}),
120
+ ...(options.baseUrl != null ? { baseURL: options.baseUrl } : {}),
121
+ ...(password != null ? { password } : {}),
122
+ };
123
+ }
124
+ async function resolvePassword(options) {
125
+ if (options.passwordEnv != null) {
126
+ const value = process.env[options.passwordEnv];
127
+ if (value == null)
128
+ throw new Error(`环境变量 ${options.passwordEnv} 没有值`);
129
+ return value;
130
+ }
131
+ if (options.passwordStdin === true) {
132
+ const chunks = [];
133
+ for await (const chunk of process.stdin)
134
+ chunks.push(chunk);
135
+ return Buffer.concat(chunks).toString('utf8').trim();
136
+ }
137
+ return undefined;
138
+ }
139
+ async function run(command, call) {
140
+ try {
141
+ const result = await call();
142
+ (0, output_1.emit)((0, auth_1.globalJson)(command), result, () => console.log(JSON.stringify(result, null, 2)));
143
+ }
144
+ catch (error) {
145
+ (0, client_1.exitOnError)(error);
146
+ }
147
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDebug = registerDebug;
4
+ const node_fs_1 = require("node:fs");
5
+ const analyzer_1 = require("../analyzer");
6
+ const client_1 = require("../client");
7
+ const output_1 = require("../output");
8
+ const auth_1 = require("./auth");
9
+ function registerDebug(program) {
10
+ const debug = program.command('debug').description('排查大屏问题');
11
+ debug.command('inspect')
12
+ .description('查看一个组件的显隐、交互和数据状态')
13
+ .argument('<screenId>')
14
+ .argument('<key>', '组件 key,如 c-88')
15
+ .action(async function (screenId, key) {
16
+ await report(this, screenId, document => (0, analyzer_1.inspect)(document, key).findings);
17
+ });
18
+ debug.command('why-hidden')
19
+ .description('为什么一个组件不显示')
20
+ .argument('<screenId>')
21
+ .argument('<key>')
22
+ .action(async function (screenId, key) {
23
+ await report(this, screenId, document => (0, analyzer_1.whyHidden)(document, key));
24
+ });
25
+ debug.command('why-no-response')
26
+ .description('为什么点击一个组件没有反应')
27
+ .argument('<screenId>')
28
+ .argument('<key>')
29
+ .option('--trigger <trigger>', '触发方式', 'click')
30
+ .action(async function (screenId, key, options) {
31
+ await report(this, screenId, document => (0, analyzer_1.whyNoResponse)(document, key, options.trigger));
32
+ });
33
+ }
34
+ async function report(command, screenId, analyze) {
35
+ try {
36
+ const document = await loadDocument(screenId);
37
+ const findings = analyze(document);
38
+ (0, output_1.emit)((0, auth_1.globalJson)(command), { findings }, () => {
39
+ for (const finding of findings)
40
+ console.log(`[${finding.level}] ${finding.code}: ${finding.message}`);
41
+ });
42
+ }
43
+ catch (error) {
44
+ (0, client_1.exitOnError)(error);
45
+ }
46
+ }
47
+ async function loadDocument(screenId) {
48
+ if (screenId.endsWith('.json'))
49
+ return JSON.parse((0, node_fs_1.readFileSync)(screenId, 'utf8'));
50
+ return await (0, client_1.createClient)().request('GET', `/screens/${screenId}/document`);
51
+ }