@dmall-inc/wd-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 +365 -2
- package/bin/wd-cli.js +106 -0
- package/docs/design-references.md +75 -0
- package/lib/args.js +299 -0
- package/lib/auth.js +77 -0
- package/lib/commands/agent.js +385 -0
- package/lib/commands/api.js +122 -0
- package/lib/commands/auth.js +314 -0
- package/lib/commands/automation.js +92 -0
- package/lib/commands/completion.js +141 -0
- package/lib/commands/config.js +120 -0
- package/lib/commands/credential.js +108 -0
- package/lib/commands/dataset.js +144 -0
- package/lib/commands/evaluate.js +170 -0
- package/lib/commands/help.js +81 -0
- package/lib/commands/index.js +46 -0
- package/lib/commands/kb.js +449 -0
- package/lib/commands/observability.js +140 -0
- package/lib/commands/session.js +189 -0
- package/lib/commands/skill.js +341 -0
- package/lib/commands/workspace.js +110 -0
- package/lib/config.js +269 -0
- package/lib/data.js +128 -0
- package/lib/http.js +396 -0
- package/lib/jq.js +342 -0
- package/lib/keyring.js +125 -0
- package/lib/oidc.js +344 -0
- package/lib/output.js +249 -0
- package/package.json +22 -4
package/lib/oidc.js
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 统一身份登录(OAuth2 授权码 + PKCE + 回环回调)。
|
|
5
|
+
*
|
|
6
|
+
* 流程与 gcloud auth login 一致:
|
|
7
|
+
* 1. 本机起一个 HTTP 服务监听 127.0.0.1 的随机端口,作为 redirect_uri;
|
|
8
|
+
* 2. 生成 code_verifier / S256 challenge / state / nonce,拼出授权地址;
|
|
9
|
+
* 3. 打开浏览器(打不开就把地址打出来);
|
|
10
|
+
* 4. 用户登录后认证中心带 code 回调到本机;
|
|
11
|
+
* 5. 用 code + verifier 换 access / refresh / id token。
|
|
12
|
+
*
|
|
13
|
+
* 回环地址(127.0.0.1)按 RFC 8252 允许端口浮动,所以认证中心只登记了
|
|
14
|
+
* http://127.0.0.1/callback 一条,本机每次用什么端口都能匹配。必须用 IP 字面量,
|
|
15
|
+
* 不能写 localhost —— RFC 8252 明确不推荐,认证中心会拒。
|
|
16
|
+
*
|
|
17
|
+
* 无浏览器环境(SSH / 容器)用 --no-browser:打印地址,用户在别处登录后把回调 URL 贴回来。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const crypto = require('node:crypto');
|
|
21
|
+
const http = require('node:http');
|
|
22
|
+
const { execFile } = require('node:child_process');
|
|
23
|
+
const readline = require('node:readline/promises');
|
|
24
|
+
|
|
25
|
+
const { CliError, EXIT } = require('./output');
|
|
26
|
+
|
|
27
|
+
/** 回调路径,与认证中心登记的 redirect_uri 路径一致。 */
|
|
28
|
+
const CALLBACK_PATH = '/callback';
|
|
29
|
+
|
|
30
|
+
/** 登记在认证中心的回调地址(端口浮动由 RFC 8252 回环豁免覆盖)。 */
|
|
31
|
+
const REGISTERED_REDIRECT_HOST = '127.0.0.1';
|
|
32
|
+
|
|
33
|
+
function base64url(buffer) {
|
|
34
|
+
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function randomToken(bytes = 32) {
|
|
38
|
+
return base64url(crypto.randomBytes(bytes));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** PKCE 一组参数:verifier + S256 challenge。 */
|
|
42
|
+
function createPkce() {
|
|
43
|
+
const verifier = randomToken(32);
|
|
44
|
+
const challenge = base64url(crypto.createHash('sha256').update(verifier, 'ascii').digest());
|
|
45
|
+
return { verifier, challenge, method: 'S256' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function buildAuthorizeUrl({ authorizeEndpoint, clientId, redirectUri, scopes, state, nonce, challenge }) {
|
|
49
|
+
const url = new URL(authorizeEndpoint);
|
|
50
|
+
url.searchParams.set('response_type', 'code');
|
|
51
|
+
url.searchParams.set('client_id', clientId);
|
|
52
|
+
url.searchParams.set('redirect_uri', redirectUri);
|
|
53
|
+
url.searchParams.set('scope', (scopes || ['openid', 'profile']).join(' '));
|
|
54
|
+
url.searchParams.set('state', state);
|
|
55
|
+
url.searchParams.set('nonce', nonce);
|
|
56
|
+
url.searchParams.set('code_challenge', challenge);
|
|
57
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
58
|
+
return url.toString();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 起本机回环回调服务。返回 { redirectUri, waitForCode, close }。
|
|
63
|
+
* 只接收一次回调;页面上给用户一句「可以关掉了」(借鉴 Stripe / Vercel CLI)。
|
|
64
|
+
*/
|
|
65
|
+
async function startLoopbackServer(expectedState) {
|
|
66
|
+
let resolveCode;
|
|
67
|
+
let rejectCode;
|
|
68
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
69
|
+
resolveCode = resolve;
|
|
70
|
+
rejectCode = reject;
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const server = http.createServer((req, res) => {
|
|
74
|
+
const url = new URL(req.url, `http://${REGISTERED_REDIRECT_HOST}`);
|
|
75
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
76
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
77
|
+
res.end('not found');
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const error = url.searchParams.get('error');
|
|
81
|
+
const code = url.searchParams.get('code');
|
|
82
|
+
const state = url.searchParams.get('state');
|
|
83
|
+
const ok = !error && code && state === expectedState;
|
|
84
|
+
res.writeHead(ok ? 200 : 400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
85
|
+
res.end(renderCallbackPage(ok, error || (state !== expectedState ? 'state 不匹配' : '未收到授权码')));
|
|
86
|
+
if (ok) {
|
|
87
|
+
resolveCode(code);
|
|
88
|
+
} else if (error) {
|
|
89
|
+
rejectCode(new CliError(`授权被拒绝:${error}`, EXIT.AUTH));
|
|
90
|
+
} else if (state !== expectedState) {
|
|
91
|
+
rejectCode(new CliError('state 不匹配,疑似回调被伪造,已中止登录', EXIT.AUTH));
|
|
92
|
+
} else {
|
|
93
|
+
rejectCode(new CliError('回调未携带授权码', EXIT.AUTH));
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
await new Promise((resolve, reject) => {
|
|
98
|
+
server.once('error', reject);
|
|
99
|
+
server.listen(0, REGISTERED_REDIRECT_HOST, resolve);
|
|
100
|
+
});
|
|
101
|
+
const { port } = server.address();
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
redirectUri: `http://${REGISTERED_REDIRECT_HOST}:${port}${CALLBACK_PATH}`,
|
|
105
|
+
waitForCode: (timeoutMs = 300_000) =>
|
|
106
|
+
Promise.race([
|
|
107
|
+
codePromise,
|
|
108
|
+
new Promise((_, reject) =>
|
|
109
|
+
setTimeout(
|
|
110
|
+
() => reject(new CliError('等待浏览器回调超时,登录已取消', EXIT.AUTH, {
|
|
111
|
+
hint: '无法打开浏览器时改用 wd-cli auth login --no-browser',
|
|
112
|
+
})),
|
|
113
|
+
timeoutMs
|
|
114
|
+
).unref?.()
|
|
115
|
+
),
|
|
116
|
+
]),
|
|
117
|
+
close: () => new Promise((resolve) => server.close(resolve)),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderCallbackPage(ok, message) {
|
|
122
|
+
const title = ok ? '登录成功' : '登录失败';
|
|
123
|
+
const body = ok ? '已回到命令行继续,可以关闭本页面。' : `原因:${message}`;
|
|
124
|
+
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>${title}</title>
|
|
125
|
+
<style>body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;
|
|
126
|
+
align-items:center;justify-content:center;height:100vh;margin:0;background:#f6f8fa;color:#1f2328}
|
|
127
|
+
.card{background:#fff;border:1px solid #d0d7de;border-radius:12px;padding:32px 40px;text-align:center;
|
|
128
|
+
box-shadow:0 1px 3px rgba(0,0,0,.06)}h1{font-size:18px;margin:0 0 8px}p{margin:0;color:#59636e;font-size:14px}
|
|
129
|
+
</style></head><body><div class="card"><h1>${title}</h1><p>${body}</p></div></body></html>`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 尽力打开浏览器;失败不算错误,调用方回落为打印地址。
|
|
134
|
+
*
|
|
135
|
+
* 尊重 `BROWSER` / `WD_CLI_BROWSER` 环境变量(Unix 惯例):
|
|
136
|
+
* 设为 none / false 即完全不启动浏览器(无头环境、自动化测试);
|
|
137
|
+
* 设为其它值则把它当命令执行,参数为授权地址。
|
|
138
|
+
*/
|
|
139
|
+
function openBrowser(url, env = process.env) {
|
|
140
|
+
const override = env.WD_CLI_BROWSER || env.BROWSER;
|
|
141
|
+
if (override) {
|
|
142
|
+
const value = String(override).trim();
|
|
143
|
+
if (!value || value === 'none' || value === 'false' || value === '0') {
|
|
144
|
+
return Promise.resolve(false);
|
|
145
|
+
}
|
|
146
|
+
return new Promise((resolve) => {
|
|
147
|
+
execFile(value, [url], (error) => resolve(!error));
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const commands =
|
|
151
|
+
process.platform === 'darwin'
|
|
152
|
+
? [['open', [url]]]
|
|
153
|
+
: process.platform === 'win32'
|
|
154
|
+
? [['cmd', ['/c', 'start', '', url]]]
|
|
155
|
+
: [
|
|
156
|
+
['xdg-open', [url]],
|
|
157
|
+
['gio', ['open', url]],
|
|
158
|
+
['wslview', [url]],
|
|
159
|
+
];
|
|
160
|
+
return new Promise((resolve) => {
|
|
161
|
+
let index = 0;
|
|
162
|
+
const tryNext = () => {
|
|
163
|
+
if (index >= commands.length) {
|
|
164
|
+
resolve(false);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const [cmd, args] = commands[index];
|
|
168
|
+
index += 1;
|
|
169
|
+
execFile(cmd, args, (error) => (error ? tryNext() : resolve(true)));
|
|
170
|
+
};
|
|
171
|
+
tryNext();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** --no-browser:让用户把浏览器地址栏里的回调 URL 整段贴回来。 */
|
|
176
|
+
async function promptForCallbackUrl(expectedState) {
|
|
177
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
178
|
+
try {
|
|
179
|
+
const answer = (await rl.question('在浏览器完成登录后,把地址栏里的完整回调地址粘贴到这里:\n> ')).trim();
|
|
180
|
+
if (!answer) throw new CliError('未收到回调地址,登录已取消', EXIT.USAGE);
|
|
181
|
+
let url;
|
|
182
|
+
try {
|
|
183
|
+
url = new URL(answer);
|
|
184
|
+
} catch {
|
|
185
|
+
throw new CliError('这不是一个合法的回调地址', EXIT.USAGE, {
|
|
186
|
+
hint: '需要形如 http://127.0.0.1:53127/callback?code=...&state=... 的整段地址',
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
const error = url.searchParams.get('error');
|
|
190
|
+
if (error) throw new CliError(`授权被拒绝:${error}`, EXIT.AUTH);
|
|
191
|
+
const code = url.searchParams.get('code');
|
|
192
|
+
const state = url.searchParams.get('state');
|
|
193
|
+
if (!code) throw new CliError('回调地址里没有 code 参数', EXIT.USAGE);
|
|
194
|
+
if (state !== expectedState) throw new CliError('state 不匹配,疑似回调被伪造,已中止登录', EXIT.AUTH);
|
|
195
|
+
return code;
|
|
196
|
+
} finally {
|
|
197
|
+
rl.close();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function postForm(url, form, timeoutMs = 20_000) {
|
|
202
|
+
const controller = new AbortController();
|
|
203
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
204
|
+
try {
|
|
205
|
+
const response = await fetch(url, {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
headers: {
|
|
208
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
209
|
+
Accept: 'application/json',
|
|
210
|
+
},
|
|
211
|
+
body: new URLSearchParams(form).toString(),
|
|
212
|
+
signal: controller.signal,
|
|
213
|
+
});
|
|
214
|
+
const text = await response.text();
|
|
215
|
+
let json = null;
|
|
216
|
+
try {
|
|
217
|
+
json = JSON.parse(text);
|
|
218
|
+
} catch {
|
|
219
|
+
json = null;
|
|
220
|
+
}
|
|
221
|
+
return { ok: response.ok, status: response.status, json, text };
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error && error.name === 'AbortError') {
|
|
224
|
+
throw new CliError(`请求认证中心超时(${timeoutMs}ms):${url}`, EXIT.NETWORK);
|
|
225
|
+
}
|
|
226
|
+
throw new CliError(`无法连接认证中心:${error.message}`, EXIT.NETWORK);
|
|
227
|
+
} finally {
|
|
228
|
+
clearTimeout(timer);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 授权码换令牌(公开客户端:表单带 client_id,不带 secret)。 */
|
|
233
|
+
async function exchangeCode({ tokenEndpoint, clientId, code, verifier, redirectUri }, timeoutMs) {
|
|
234
|
+
const result = await postForm(
|
|
235
|
+
tokenEndpoint,
|
|
236
|
+
{
|
|
237
|
+
grant_type: 'authorization_code',
|
|
238
|
+
code,
|
|
239
|
+
redirect_uri: redirectUri,
|
|
240
|
+
client_id: clientId,
|
|
241
|
+
code_verifier: verifier,
|
|
242
|
+
},
|
|
243
|
+
timeoutMs
|
|
244
|
+
);
|
|
245
|
+
if (!result.ok || !result.json || !result.json.access_token) {
|
|
246
|
+
throw new CliError(tokenErrorMessage('兑换令牌失败', result), EXIT.AUTH);
|
|
247
|
+
}
|
|
248
|
+
return normalizeTokenSet(result.json);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** refresh token 轮转换新(SAS 一次一换,必须保存返回的新 refresh token)。 */
|
|
252
|
+
async function refreshTokens({ tokenEndpoint, clientId, refreshToken }, timeoutMs) {
|
|
253
|
+
const result = await postForm(
|
|
254
|
+
tokenEndpoint,
|
|
255
|
+
{
|
|
256
|
+
grant_type: 'refresh_token',
|
|
257
|
+
refresh_token: refreshToken,
|
|
258
|
+
client_id: clientId,
|
|
259
|
+
},
|
|
260
|
+
timeoutMs
|
|
261
|
+
);
|
|
262
|
+
if (!result.ok || !result.json || !result.json.access_token) {
|
|
263
|
+
throw new CliError(tokenErrorMessage('登录已失效', result), EXIT.AUTH, {
|
|
264
|
+
hint: '请重新执行 wd-cli auth login',
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return normalizeTokenSet(result.json);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** 撤销 refresh token(登出)。失败不阻断本地清理。 */
|
|
271
|
+
async function revokeToken({ revokeEndpoint, clientId, token }, timeoutMs) {
|
|
272
|
+
if (!revokeEndpoint || !token) return false;
|
|
273
|
+
try {
|
|
274
|
+
const result = await postForm(
|
|
275
|
+
revokeEndpoint,
|
|
276
|
+
{ token, token_type_hint: 'refresh_token', client_id: clientId },
|
|
277
|
+
timeoutMs
|
|
278
|
+
);
|
|
279
|
+
return result.ok;
|
|
280
|
+
} catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function tokenErrorMessage(prefix, result) {
|
|
286
|
+
const detail =
|
|
287
|
+
(result.json && (result.json.error_description || result.json.error)) ||
|
|
288
|
+
(result.text ? result.text.slice(0, 200) : '');
|
|
289
|
+
return `${prefix}(HTTP ${result.status})${detail ? `:${detail}` : ''}`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function normalizeTokenSet(json) {
|
|
293
|
+
const expiresIn = Number(json.expires_in);
|
|
294
|
+
return {
|
|
295
|
+
accessToken: json.access_token,
|
|
296
|
+
refreshToken: json.refresh_token || null,
|
|
297
|
+
idToken: json.id_token || null,
|
|
298
|
+
expiresAt: Number.isFinite(expiresIn) ? Date.now() + expiresIn * 1000 : null,
|
|
299
|
+
scope: json.scope || null,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 解码 JWT 载荷(不验签:签名由服务端校验,这里只是读 nonce / aud / 名字)。 */
|
|
304
|
+
function decodeJwtPayload(jwt) {
|
|
305
|
+
try {
|
|
306
|
+
const [, payload] = String(jwt).split('.');
|
|
307
|
+
return JSON.parse(Buffer.from(payload.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
308
|
+
} catch {
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** 校验 id_token 的 nonce 与 aud:防重放与错发。 */
|
|
314
|
+
function assertIdToken(idToken, { nonce, clientId }) {
|
|
315
|
+
if (!idToken) return null;
|
|
316
|
+
const payload = decodeJwtPayload(idToken);
|
|
317
|
+
if (!payload) throw new CliError('认证中心返回的 id_token 无法解析', EXIT.AUTH);
|
|
318
|
+
if (nonce && payload.nonce && payload.nonce !== nonce) {
|
|
319
|
+
throw new CliError('id_token 的 nonce 不匹配,已中止登录', EXIT.AUTH);
|
|
320
|
+
}
|
|
321
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
322
|
+
if (clientId && !aud.includes(clientId)) {
|
|
323
|
+
throw new CliError('id_token 的 aud 与本客户端不符,已中止登录', EXIT.AUTH);
|
|
324
|
+
}
|
|
325
|
+
return payload;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
module.exports = {
|
|
329
|
+
CALLBACK_PATH,
|
|
330
|
+
REGISTERED_REDIRECT_HOST,
|
|
331
|
+
base64url,
|
|
332
|
+
randomToken,
|
|
333
|
+
createPkce,
|
|
334
|
+
buildAuthorizeUrl,
|
|
335
|
+
startLoopbackServer,
|
|
336
|
+
openBrowser,
|
|
337
|
+
promptForCallbackUrl,
|
|
338
|
+
exchangeCode,
|
|
339
|
+
refreshTokens,
|
|
340
|
+
revokeToken,
|
|
341
|
+
decodeJwtPayload,
|
|
342
|
+
assertIdToken,
|
|
343
|
+
renderCallbackPage,
|
|
344
|
+
};
|
package/lib/output.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 输出与退出码(借鉴 gh 的 --json/--jq、kubectl 的 -o,以及 clig.dev 的 stdout/stderr 分工)。
|
|
5
|
+
*
|
|
6
|
+
* 三条硬规矩:
|
|
7
|
+
* 1. 标准输出只放数据。提示、进度、警告、错误一律走标准错误——管道里只应拿到数据。
|
|
8
|
+
* 2. 缺省格式看输出是不是终端:是 -> table(给人看),不是 -> json(给脚本看)。
|
|
9
|
+
* 3. 错误信息要带下一步动作,不是只报个码。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const EXIT = {
|
|
13
|
+
/** 成功 */
|
|
14
|
+
OK: 0,
|
|
15
|
+
/** 业务失败(服务端返回了明确的业务错误) */
|
|
16
|
+
BUSINESS: 1,
|
|
17
|
+
/** 用法错误(参数、主体不匹配、本地文件缺失) */
|
|
18
|
+
USAGE: 2,
|
|
19
|
+
/** 鉴权失败(401 / 403,且刷新令牌后仍失败) */
|
|
20
|
+
AUTH: 3,
|
|
21
|
+
/** 网络错误、超时、响应不可解析 */
|
|
22
|
+
NETWORK: 4,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** CLI 统一异常:带退出码,顶层捕获后决定进程返回值。 */
|
|
26
|
+
class CliError extends Error {
|
|
27
|
+
constructor(message, exitCode = EXIT.USAGE, extra = {}) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = 'CliError';
|
|
30
|
+
this.exitCode = exitCode;
|
|
31
|
+
this.code = extra.code;
|
|
32
|
+
this.errorCode = extra.errorCode;
|
|
33
|
+
this.hint = extra.hint;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isTty(stream = process.stdout) {
|
|
38
|
+
return Boolean(stream && stream.isTTY);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 颜色开关:非 TTY、NO_COLOR、TERM=dumb、--no-color 任一命中即关闭(clig.dev)。 */
|
|
42
|
+
function colorEnabled(flags = {}) {
|
|
43
|
+
if (flags.noColor) return false;
|
|
44
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') return false;
|
|
45
|
+
if ((process.env.TERM || '').toLowerCase() === 'dumb') return false;
|
|
46
|
+
return isTty(process.stdout);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function paint(text, code, flags) {
|
|
50
|
+
return colorEnabled(flags) ? `[${code}m${text}[0m` : text;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const style = {
|
|
54
|
+
bold: (t, f) => paint(t, '1', f),
|
|
55
|
+
dim: (t, f) => paint(t, '2', f),
|
|
56
|
+
green: (t, f) => paint(t, '32', f),
|
|
57
|
+
yellow: (t, f) => paint(t, '33', f),
|
|
58
|
+
red: (t, f) => paint(t, '31', f),
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** 缺省输出格式:显式 --output 优先,否则 TTY -> table、管道 -> json。 */
|
|
62
|
+
function resolveFormat(flags = {}) {
|
|
63
|
+
if (flags.output) return flags.output;
|
|
64
|
+
return isTty(process.stdout) ? 'table' : 'json';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 东亚宽字符按两列计(中文表格对齐的最低要求)。 */
|
|
68
|
+
function displayWidth(text) {
|
|
69
|
+
let width = 0;
|
|
70
|
+
for (const ch of String(text)) {
|
|
71
|
+
const cp = ch.codePointAt(0);
|
|
72
|
+
const wide =
|
|
73
|
+
(cp >= 0x1100 && cp <= 0x115f) ||
|
|
74
|
+
(cp >= 0x2e80 && cp <= 0xa4cf) ||
|
|
75
|
+
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
76
|
+
(cp >= 0xf900 && cp <= 0xfaff) ||
|
|
77
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) ||
|
|
78
|
+
(cp >= 0xff00 && cp <= 0xff60) ||
|
|
79
|
+
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
|
80
|
+
(cp >= 0x1f300 && cp <= 0x1f9ff);
|
|
81
|
+
width += wide ? 2 : 1;
|
|
82
|
+
}
|
|
83
|
+
return width;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function padEnd(text, width) {
|
|
87
|
+
const pad = width - displayWidth(text);
|
|
88
|
+
return pad > 0 ? text + ' '.repeat(pad) : text;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function cellText(value) {
|
|
92
|
+
if (value === null || value === undefined) return '';
|
|
93
|
+
if (typeof value === 'object') return JSON.stringify(value);
|
|
94
|
+
return String(value);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 渲染表格;columns 为 [{key, label}],缺省取第一行的键。 */
|
|
98
|
+
function renderTable(rows, columns, flags) {
|
|
99
|
+
if (!rows.length) return '';
|
|
100
|
+
const cols =
|
|
101
|
+
columns && columns.length
|
|
102
|
+
? columns
|
|
103
|
+
: Object.keys(rows[0]).map((key) => ({ key, label: key }));
|
|
104
|
+
const widths = cols.map((col) =>
|
|
105
|
+
Math.max(
|
|
106
|
+
displayWidth(col.label),
|
|
107
|
+
...rows.map((row) => displayWidth(cellText(row[col.key])))
|
|
108
|
+
)
|
|
109
|
+
);
|
|
110
|
+
const header = cols.map((col, i) => padEnd(style.bold(col.label, flags), widths[i] + (colorEnabled(flags) ? 8 : 0)));
|
|
111
|
+
const lines = [header.join(' ').trimEnd()];
|
|
112
|
+
for (const row of rows) {
|
|
113
|
+
lines.push(cols.map((col, i) => padEnd(cellText(row[col.key]), widths[i])).join(' ').trimEnd());
|
|
114
|
+
}
|
|
115
|
+
return lines.join('\n');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 单对象按 key: value 渲染。 */
|
|
119
|
+
function renderObject(value) {
|
|
120
|
+
return Object.entries(value)
|
|
121
|
+
.map(([key, val]) => `${key}: ${cellText(val)}`)
|
|
122
|
+
.join('\n');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** --json a,b,c:只保留指定字段(对数组逐项应用)。 */
|
|
126
|
+
function selectFields(data, fieldsRaw) {
|
|
127
|
+
const fields = String(fieldsRaw)
|
|
128
|
+
.split(',')
|
|
129
|
+
.map((f) => f.trim())
|
|
130
|
+
.filter(Boolean);
|
|
131
|
+
if (!fields.length) return data;
|
|
132
|
+
const pick = (obj) => {
|
|
133
|
+
if (!obj || typeof obj !== 'object') return obj;
|
|
134
|
+
const out = {};
|
|
135
|
+
for (const f of fields) out[f] = obj[f];
|
|
136
|
+
return out;
|
|
137
|
+
};
|
|
138
|
+
return Array.isArray(data) ? data.map(pick) : pick(data);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function writeOut(text) {
|
|
142
|
+
if (text === '' || text === undefined || text === null) return;
|
|
143
|
+
process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 提示信息一律走 stderr,管道里不会污染数据。 */
|
|
147
|
+
function info(message, flags = {}) {
|
|
148
|
+
if (flags.quiet) return;
|
|
149
|
+
process.stderr.write(`${message}\n`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function success(message, flags = {}) {
|
|
153
|
+
if (flags.quiet) return;
|
|
154
|
+
process.stderr.write(`${style.green('✓', flags)} ${message}\n`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function warn(message, flags = {}) {
|
|
158
|
+
process.stderr.write(`${style.yellow('!', flags)} ${message}\n`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 输出一次命令结果。
|
|
163
|
+
*
|
|
164
|
+
* @param {*} data 服务端 Result.data(或本地构造的数据)
|
|
165
|
+
* @param {object} opts.flags 全局标志
|
|
166
|
+
* @param {Array} opts.columns table 模式的列定义 [{key,label}]
|
|
167
|
+
* @param {string} opts.empty 空列表时的提示(走 stderr)
|
|
168
|
+
*/
|
|
169
|
+
function print(data, opts = {}) {
|
|
170
|
+
const flags = opts.flags || {};
|
|
171
|
+
const format = resolveFormat(flags);
|
|
172
|
+
let value = data;
|
|
173
|
+
|
|
174
|
+
if (flags.json) value = selectFields(value, flags.json);
|
|
175
|
+
if (flags.jq) {
|
|
176
|
+
// 延迟加载:只有用到 --jq 才付出解析器的启动成本
|
|
177
|
+
value = require('./jq').applyJq(value, flags.jq);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (format === 'raw') {
|
|
181
|
+
writeOut(typeof value === 'string' ? value : JSON.stringify(value));
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (format === 'json' || flags.json || flags.jq) {
|
|
185
|
+
writeOut(JSON.stringify(value, null, isTty(process.stdout) ? 2 : 0));
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
// table
|
|
189
|
+
if (Array.isArray(value)) {
|
|
190
|
+
if (!value.length) {
|
|
191
|
+
if (opts.empty) info(opts.empty, flags);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (typeof value[0] !== 'object' || value[0] === null) {
|
|
195
|
+
writeOut(value.map(cellText).join('\n'));
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
writeOut(renderTable(value, opts.columns, flags));
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (value && typeof value === 'object') {
|
|
202
|
+
writeOut(renderObject(value));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
writeOut(cellText(value));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 顶层错误输出:stderr 一行人话 + json 模式下追加一行机器可读。 */
|
|
209
|
+
function printError(error, flags = {}) {
|
|
210
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
211
|
+
const parts = [`[wd-cli] ${message}`];
|
|
212
|
+
if (error && error.code !== undefined && error.code !== null) {
|
|
213
|
+
const codeBits = [`code=${error.code}`];
|
|
214
|
+
if (error.errorCode) codeBits.push(`errorCode=${error.errorCode}`);
|
|
215
|
+
parts.push(`(${codeBits.join(', ')})`);
|
|
216
|
+
}
|
|
217
|
+
process.stderr.write(`${style.red(parts.join(' '), flags)}\n`);
|
|
218
|
+
if (error && error.hint) {
|
|
219
|
+
process.stderr.write(`${style.dim(` ${error.hint}`, flags)}\n`);
|
|
220
|
+
}
|
|
221
|
+
if (resolveFormat(flags) === 'json' || flags.json || flags.jq) {
|
|
222
|
+
process.stderr.write(
|
|
223
|
+
`${JSON.stringify({
|
|
224
|
+
error: true,
|
|
225
|
+
code: error && error.code !== undefined ? error.code : null,
|
|
226
|
+
errorCode: (error && error.errorCode) || null,
|
|
227
|
+
message,
|
|
228
|
+
})}\n`
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
module.exports = {
|
|
234
|
+
EXIT,
|
|
235
|
+
CliError,
|
|
236
|
+
style,
|
|
237
|
+
isTty,
|
|
238
|
+
colorEnabled,
|
|
239
|
+
resolveFormat,
|
|
240
|
+
displayWidth,
|
|
241
|
+
renderTable,
|
|
242
|
+
renderObject,
|
|
243
|
+
selectFields,
|
|
244
|
+
print,
|
|
245
|
+
printError,
|
|
246
|
+
info,
|
|
247
|
+
success,
|
|
248
|
+
warn,
|
|
249
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dmall-inc/wd-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Waterdrop platform CLI: sign in with your unified identity, pick a workspace, and use the open platform resources from your terminal",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"bin": {
|
|
8
|
+
"wd-cli": "bin/wd-cli.js"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=18"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin",
|
|
15
|
+
"lib",
|
|
16
|
+
"docs",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"lint": "node --check bin/wd-cli.js && node -e \"require('node:fs').readdirSync('lib',{recursive:true}).filter(f=>f.endsWith('.js')).forEach(f=>require('node:child_process').execFileSync(process.execPath,['--check','lib/'+f]))\"",
|
|
21
|
+
"test": "node --test test/*.test.js test/**/*.test.js",
|
|
22
|
+
"start": "node bin/wd-cli.js"
|
|
23
|
+
}
|
|
24
|
+
}
|