dsh-devdock-cloudflare 0.0.0-stage → 3.0.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,1632 @@
1
+ /**
2
+ * dsh-devdock — Cloudflare API v4 client (DevDock 套件的 Cloudflare 模块 · Host 半边).
3
+ *
4
+ * 与 github.js 相同的三条硬约束:
5
+ *
6
+ * 1. 用 `node:https` 而不是 fetch/undici —— 这个 Host 跑在 DSH profile 进程里,
7
+ * 该机器的 undici TLS 栈对 github.com 出过证书错误;对 Cloudflare 同样要自己
8
+ * 掌控 socket、超时和确切错误码,才能给出可执行的中文诊断而不是一句通用失败。
9
+ * 2. 每个请求带硬超时。后台 HTTP 服务器绝不能被死 socket 挂住。
10
+ * 3. 令牌只进 `Authorization: Bearer` 头,绝不进 URL、argv、日志或任何响应。
11
+ *
12
+ * 错误类型复用 `GithubError`(与 npm.js 相同的历史遗留):它已带 code → HTTP 状态
13
+ * 的映射,另起一个类只会多一套重复映射。
14
+ *
15
+ * 部署(Pages Direct Upload / Workers module upload)不走 shell、不调 wrangler:
16
+ * 文件由 fs 读进内存,multipart 在这里手工构造后走 node:https。这样既避免
17
+ * wrangler 的 OAuth 交互,也避免把文件路径/令牌暴露给命令行。
18
+ *
19
+ * @module src/host/cloudflare.js
20
+ */
21
+
22
+ import { request as httpsRequest } from 'node:https';
23
+ import { request as httpRequest } from 'node:http';
24
+ import { readFile } from 'node:fs/promises';
25
+ import { createHash } from 'node:crypto';
26
+ import path from 'node:path';
27
+ // 错误类型由内核提供:平台插件不再依赖 github 包。
28
+ import { DevDockError as GithubError } from 'dsh-devdock-core/src/host/errors.js';
29
+
30
+ /** Cloudflare API v4 基地址;环境变量可指向镜像或测试用假服务器。 */
31
+ const DEFAULT_API_BASE = 'https://api.cloudflare.com/client/v4';
32
+
33
+ /**
34
+ * 当前 API 基地址。
35
+ *
36
+ * 每次调用时读取而不是模块加载时固化:测试要能在同一进程里指向本地假
37
+ * 服务器,固化会让它读到旧值。
38
+ * @returns {string}
39
+ */
40
+ function apiBase() {
41
+ const raw = process.env.DSH_PUSH_CF_API_BASE;
42
+ const value = typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : DEFAULT_API_BASE;
43
+ return value.replace(/\/+$/, '');
44
+ }
45
+
46
+ const DASH_ORIGIN = 'https://dash.cloudflare.com';
47
+ const USER_AGENT = 'dsh-devdock (+https://github.com/QingJing5906/dsh-DevDock)';
48
+ const DEFAULT_TIMEOUT_MS = 20_000;
49
+
50
+ /** Cloudflare 错误码 → 中文缺权限提示的关键词(用于把 403/9109 翻译成人话)。 */
51
+ const PERMISSION_HINTS = [
52
+ [/Pages|pages/i, 'Cloudflare Pages: Edit'],
53
+ [/Workers Scripts|workers scripts|script/i, 'Workers Scripts: Edit'],
54
+ [/Zone|zone/i, 'Zone: Read'],
55
+ [/Account|account|user|member/i, 'Account Settings: Read'],
56
+ ];
57
+
58
+ /**
59
+ * 把低层 socket 错误翻译成 CONTRACT §0 的 NETWORK 码,措辞与 github.js 一致。
60
+ * @param {Error} error
61
+ * @param {string} target
62
+ * @param {number} timeoutMs
63
+ * @returns {GithubError}
64
+ */
65
+ function networkError(error, target, timeoutMs) {
66
+ const code = String(error?.code ?? '');
67
+ const name = String(error?.name ?? '');
68
+ const timedOut = name === 'AbortError' || code === 'ABORT_ERR' || name === 'TimeoutError';
69
+ if (timedOut) {
70
+ return new GithubError(
71
+ 'NETWORK',
72
+ `连接 Cloudflare 超时(${Math.round(timeoutMs / 1000)} 秒):${target}。请检查网络或代理设置。`,
73
+ { cause: error },
74
+ );
75
+ }
76
+ const tls = /CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY|EPROTO|ERR_TLS/i.test(`${code} ${error?.message ?? ''}`);
77
+ const dns = code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EAI_FAIL';
78
+ const refused = code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'EHOSTUNREACH' || code === 'ETIMEDOUT';
79
+ let hint;
80
+ if (tls) {
81
+ hint = '本机 TLS/证书校验未能通过 Cloudflare 的证书(常见于系统时间错误、企业代理或杀毒软件拦截)。';
82
+ } else if (dns) {
83
+ hint = 'DNS 解析失败,请检查网络连接或代理配置。';
84
+ } else if (refused) {
85
+ hint = '网络连接被拒绝或中断,请检查网络、代理或防火墙。';
86
+ } else {
87
+ hint = '请检查网络连接、代理设置和系统时间。';
88
+ }
89
+ return new GithubError(
90
+ 'NETWORK',
91
+ `无法连接 Cloudflare:${target}(${code || '网络错误'})。${hint}`,
92
+ { cause: error },
93
+ );
94
+ }
95
+
96
+ /**
97
+ * 发一个 Cloudflare API 请求。
98
+ *
99
+ * 支持 JSON body(`body`)与原始字节(`rawBody` + `contentType`,用于 multipart)。
100
+ * 响应按内容类型解析 JSON,否则当文本。
101
+ *
102
+ * @param {object} options
103
+ * @param {string} options.method
104
+ * @param {string} options.url 绝对 URL。
105
+ * @param {string} [options.token]
106
+ * @param {object} [options.body] JSON body。
107
+ * @param {Buffer} [options.rawBody] 原始字节(multipart)。
108
+ * @param {Record<string,string>} [options.headers]
109
+ * @param {number} [options.timeoutMs]
110
+ * @returns {Promise<{status: number, headers: object, json: any, text: string}>}
111
+ */
112
+ function request(options) {
113
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_TIMEOUT_MS;
114
+ const headers = {
115
+ 'user-agent': USER_AGENT,
116
+ accept: 'application/json',
117
+ ...(options.headers ?? {}),
118
+ };
119
+ // 两种凭据形态,由 auth 头统一折算:
120
+ // - API Token(可细粒度)-> Authorization: Bearer <token>
121
+ // - Global API Key(全权限,只需邮箱 + Key)-> X-Auth-Email + X-Auth-Key
122
+ // Global Key 省去逐个勾权限的麻烦,代价是它等于账户最高权限。
123
+ if (options.credential) {
124
+ if (options.credential.kind === 'global') {
125
+ if (options.credential.email) headers['x-auth-email'] = options.credential.email;
126
+ if (options.credential.key) headers['x-auth-key'] = options.credential.key;
127
+ } else if (options.credential.token) {
128
+ headers.authorization = 'Bearer ' + options.credential.token;
129
+ }
130
+ }
131
+ let payload;
132
+ if (options.rawBody !== undefined) {
133
+ payload = Buffer.isBuffer(options.rawBody) ? options.rawBody : Buffer.from(options.rawBody);
134
+ headers['content-length'] = String(payload.length);
135
+ } else if (options.body !== undefined) {
136
+ payload = Buffer.from(JSON.stringify(options.body), 'utf8');
137
+ headers['content-type'] = 'application/json; charset=utf-8';
138
+ headers['content-length'] = String(payload.length);
139
+ }
140
+ return new Promise((resolvePromise, reject) => {
141
+ const controller = new AbortController();
142
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
143
+ let settled = false;
144
+ const done = (fn, value) => {
145
+ if (settled) return;
146
+ settled = true;
147
+ clearTimeout(timer);
148
+ fn(value);
149
+ };
150
+ let req;
151
+ try {
152
+ const transport = String(options.url).startsWith('http://') ? httpRequest : httpsRequest;
153
+ req = transport(options.url, { method: options.method, headers, signal: controller.signal }, (res) => {
154
+ const chunks = [];
155
+ res.on('data', (chunk) => chunks.push(chunk));
156
+ res.on('end', () => {
157
+ const text = Buffer.concat(chunks).toString('utf8');
158
+ const contentType = String(res.headers['content-type'] ?? '');
159
+ let json;
160
+ if (text !== '' && /json/i.test(contentType)) {
161
+ try { json = JSON.parse(text); } catch { json = undefined; }
162
+ }
163
+ done(resolvePromise, {
164
+ status: typeof res.statusCode === 'number' ? res.statusCode : 0,
165
+ headers: res.headers,
166
+ json,
167
+ text,
168
+ });
169
+ });
170
+ res.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
171
+ });
172
+ } catch (error) {
173
+ clearTimeout(timer);
174
+ reject(networkError(error, options.url, timeoutMs));
175
+ return;
176
+ }
177
+ req.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
178
+ if (payload !== undefined) req.write(payload);
179
+ req.end();
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Cloudflare 响应 → 统一错误。
185
+ *
186
+ * Cloudflare 用 `{success, errors:[{code,message}]}`;`success:false` 或 HTTP 非 2xx
187
+ * 都要翻译。403/9109 一类权限错误额外给出缺哪个 Permission Group 的中文提示。
188
+ *
189
+ * @param {object} response
190
+ * @param {string} action 中文动作名。
191
+ * @returns {GithubError}
192
+ */
193
+ function cfError(response, action) {
194
+ const status = response.status;
195
+ const errors = Array.isArray(response.json?.errors) ? response.json.errors : [];
196
+ const first = errors[0] || {};
197
+ const code = typeof first.code === 'number' ? String(first.code) : '';
198
+ const message = typeof first.message === 'string' ? first.message : '';
199
+ const detail = message || response.text.slice(0, 300) || '未知错误';
200
+
201
+ // 6003 + error_chain 6111 = 凭据格式不对(令牌没复制全 / 混进空白 /
202
+ // 把 API Token 和 Global API Key 用错了位置)。Cloudflare 只给
203
+ // 「Invalid request headers」这种含糊措辞,这里翻译成能直接照做的话。
204
+ const chainCodes = (Array.isArray(first.error_chain) ? first.error_chain : [])
205
+ .map((e) => String(e && e.code ? e.code : ''));
206
+ // 6102 = X-Auth-Email 头格式非法:邮箱里有空格/全角字符/换行,或根本不是邮箱。
207
+ if (code === '6003' && chainCodes.includes('6102')) {
208
+ return new GithubError(
209
+ 'BAD_REQUEST',
210
+ 'Cloudflare 认为「账户邮箱」格式不对(X-Auth-Email 头非法)。'
211
+ + '请确认填的是 Cloudflare 登录邮箱,且不含空格、全角符号或换行。',
212
+ { status },
213
+ );
214
+ }
215
+ // 6103 = X-Auth-Key 头格式非法:Global API Key 形态不对
216
+ // (新格式 cfk_ 开头;旧格式 37–45 位十六进制)。
217
+ if (code === '6003' && chainCodes.includes('6103')) {
218
+ return new GithubError(
219
+ 'BAD_REQUEST',
220
+ 'Cloudflare 认为「Global API Key」格式不对(X-Auth-Key 头非法)。'
221
+ + '它应为 cfk_ 开头的长串(新版格式),或 37–45 位十六进制(旧格式)。'
222
+ + '若手上是 cfut_ / cfat_ 开头的,那是 API Token,请切换登录方式。',
223
+ { status },
224
+ );
225
+ }
226
+ if (code === '6003' && chainCodes.includes('6111')) {
227
+ return new GithubError(
228
+ 'UNAUTHORIZED',
229
+ 'Cloudflare 拒绝了凭据:请求头格式不对。'
230
+ + '如果你用的是 API Token,请确认它完整复制、没有多余空格;'
231
+ + '如果你填的是 Global API Key,请确认「邮箱 + Key」两项都填了,且 Key 没有和 API Token 弄混。',
232
+ { status },
233
+ );
234
+ }
235
+
236
+ // 1000 = Invalid API Token:令牌被吊销 / 复制不全 / 从未创建成功。
237
+ if (code === '1000') {
238
+ return new GithubError(
239
+ 'UNAUTHORIZED',
240
+ 'Cloudflare 认为这个 API Token 无效(1000 Invalid API Token)。'
241
+ + '常见原因:令牌已被删除或吊销、复制时漏掉了字符、或创建后没有点完最后的「Create Token」。'
242
+ + '也可以改用 Global API Key 登录:在 My Profile › API Tokens › Global API Key 里查看,'
243
+ + '填「邮箱 + Key」即可,无需逐个勾权限。',
244
+ { status },
245
+ );
246
+ }
247
+ if (status === 429) {
248
+ return new GithubError('RATE_LIMITED', `Cloudflare API 触发速率限制(${action}),请稍后重试:${detail}`, { status });
249
+ }
250
+ if (status === 401 || status === 403 || code === '9109' || code === '10000') {
251
+ let permHint = '';
252
+ for (const [re, group] of PERMISSION_HINTS) {
253
+ if (re.test(detail)) { permHint = `;通常需要令牌具备「${group}」权限`; break; }
254
+ }
255
+ return new GithubError(
256
+ 'UNAUTHORIZED',
257
+ `Cloudflare 拒绝了该操作(${action})${code ? `[${code}] ` : ''}:${detail}。`
258
+ + `${permHint || '请确认 API Token 有效且包含所需权限组。'}`,
259
+ { status },
260
+ );
261
+ }
262
+ if (status === 404) {
263
+ return new GithubError('NOT_FOUND', `Cloudflare 上找不到对应资源(${action}):${detail}`, { status });
264
+ }
265
+ if (status >= 400 && status < 500) {
266
+ return new GithubError('BAD_REQUEST', `Cloudflare 请求失败(${action},HTTP ${status}):${detail}`, { status });
267
+ }
268
+ return new GithubError(
269
+ 'NETWORK',
270
+ `Cloudflare 服务异常(HTTP ${status},${action}):${detail || '请稍后重试'}。`,
271
+ { status },
272
+ );
273
+ }
274
+
275
+ /**
276
+ * 一次「期望 success:true」的调用;返回 result。
277
+ * @param {object} options 同 {@link request},另加 `action`。
278
+ * @returns {Promise<any>}
279
+ */
280
+ async function api(options) {
281
+ const response = await request(options);
282
+ // 2xx 且 Cloudflare 信封 success(或没有信封字段时按 2xx 通过)。
283
+ const envelopeOk = response.json && typeof response.json.success === 'boolean'
284
+ ? response.json.success
285
+ : response.status >= 200 && response.status < 300;
286
+ if (response.status < 200 || response.status >= 300 || !envelopeOk) {
287
+ throw cfError(response, options.action ?? '调用 Cloudflare API');
288
+ }
289
+ return response.json?.result;
290
+ }
291
+
292
+ /* ------------------------------------------------------------------ */
293
+ /* 凭据(API Token 或 Global API Key) */
294
+ /* ------------------------------------------------------------------ */
295
+
296
+ /**
297
+ * 把外部传入的凭据收成两种明确形态之一。
298
+ *
299
+ * 支持两种:
300
+ * - `{ kind: 'token', token }` —— API Token,可细粒度授权,用 Bearer 头。
301
+ * - `{ kind: 'global', email, key }` —— Global API Key,账户全权限,
302
+ * 用 X-Auth-Email + X-Auth-Key,不需要逐个勾权限组。
303
+ *
304
+ * 也接受裸字符串(视为 API Token),这样旧调用与测试不用改。
305
+ *
306
+ * @param {string|{kind?: string, token?: string, email?: string, key?: string}} raw
307
+ * @returns {{kind: 'token'|'global', token?: string, email?: string, key?: string}}
308
+ */
309
+ export function normalizeCredential(raw) {
310
+ if (typeof raw === 'string') {
311
+ return { kind: 'token', token: raw.trim() };
312
+ }
313
+ if (raw && typeof raw === 'object') {
314
+ if (raw.kind === 'global' || (raw.key !== undefined && raw.email !== undefined)) {
315
+ return {
316
+ kind: 'global',
317
+ // 粘贴时最容易带进不可见字符(零宽空格、全角空格、换行),
318
+ // 它们会让 X-Auth-Email 变成非法头,Cloudflare 只回一句含糊的 6003。
319
+ email: String(raw.email ?? '').replace(/[\s\u200B-\u200D\uFEFF]/g, ''),
320
+ key: String(raw.key ?? '').replace(/[\s\u200B-\u200D\uFEFF]/g, ''),
321
+ };
322
+ }
323
+ return { kind: 'token', token: String(raw.token ?? '').trim() };
324
+ }
325
+ return { kind: 'token', token: '' };
326
+ }
327
+
328
+ /** 凭据是否「看起来填全了」,用于前端置灰按钮。 */
329
+ export function credentialComplete(raw) {
330
+ const c = normalizeCredential(raw);
331
+ if (c.kind === 'global') return c.email !== '' && c.key !== '';
332
+ return c.token !== '';
333
+ }
334
+
335
+ /**
336
+ * 凭据的字符串标识(仅用于日志/提示,绝不含密钥本体)。
337
+ * @param {string|object} raw
338
+ * @returns {string}
339
+ */
340
+ function credentialString(raw) {
341
+ const c = normalizeCredential(raw);
342
+ if (c.kind === 'global') return c.email !== '' ? `global:${c.email}` : '';
343
+ return c.token ?? '';
344
+ }
345
+
346
+ /**
347
+ * 校验凭据是否可用。
348
+ *
349
+ * API Token 走 `GET /user/tokens/verify`;Global API Key 没有对应的 verify
350
+ * 端点,改用 `GET /user`(它能证明 email+key 组合有效)并同时拿回账户邮箱。
351
+ *
352
+ * @param {string|object} raw
353
+ * @param {{timeoutMs?: number}} [options]
354
+ * @returns {Promise<{kind: string, id: string, status: string, email: string}>}
355
+ */
356
+ /**
357
+ * 判定一段字符串像哪种 Cloudflare 凭据(只做形态判断,不做有效性联网校验)。
358
+ *
359
+ * 依据官方 Token formats:
360
+ * - Global API Key 新格式 `cfk_` + 40 字符 + checksum
361
+ * - 用户 API Token `cfut_` + 40 + checksum
362
+ * - 账户 API Token `cfat_` + 40 + checksum
363
+ * - 2026 年前的旧格式:Global Key 是 37–45 位小写十六进制,Token 是 40 位字母数字
364
+ *
365
+ * @param {string} value
366
+ * @returns {'global'|'apitoken'|'unknown'}
367
+ */
368
+ export function globalKeyShape(value) {
369
+ const text = String(value ?? '').trim();
370
+ if (text === '') return 'unknown';
371
+ // 新格式
372
+ if (/^cfk_[A-Za-z0-9]{20,}$/.test(text)) return 'global';
373
+ if (/^cf(at|ut)_[A-Za-z0-9]{20,}$/.test(text)) return 'apitoken';
374
+ // 旧格式:Global Key 是纯小写十六进制
375
+ if (/^[0-9a-f]{37,45}$/.test(text)) return 'global';
376
+ // 旧格式:API Token 是 40 位字母数字(含 g-z 就不会被判成十六进制)
377
+ if (/^[A-Za-z0-9_-]{40}$/.test(text)) return 'apitoken';
378
+ return 'unknown';
379
+ }
380
+ export async function verifyToken(raw, options = {}) {
381
+ const credential = normalizeCredential(raw);
382
+
383
+ if (credential.kind === 'global') {
384
+ if (credential.email === '' || credential.key === '') {
385
+ throw new GithubError(
386
+ 'BAD_REQUEST',
387
+ 'Global API Key 登录需要同时填写「账户邮箱」和「Global API Key」两项。',
388
+ );
389
+ }
390
+ // 邮箱必须是 ASCII 邮箱形态。全角 @、中文逗号、首尾空格、粘贴带进来的
391
+ // 不可见字符都会让 Cloudflare 回 6003 "Invalid request headers"
392
+ // (error_chain 6102 Invalid format for X-Auth-Email),那条报错看不出是邮箱的问题。
393
+ const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(credential.email)
394
+ && /^[\x20-\x7E]+$/.test(credential.email);
395
+ if (!emailOk) {
396
+ throw new GithubError(
397
+ 'BAD_REQUEST',
398
+ `「账户邮箱」格式不对:${credential.email}。`
399
+ + '它必须是 Cloudflare 登录邮箱(如 name@example.com),'
400
+ + '不能含空格、全角符号或换行;请重新输入后再试。',
401
+ );
402
+ }
403
+ // Global API Key 有两代格式,都必须接受:
404
+ // - 新格式(2026 起):`cfk_` + 40 字符 + checksum
405
+ // - 旧格式:37–45 位小写十六进制
406
+ // 反过来说,`cfut_`(用户 API Token)与 `cfat_`(账户 API Token)出现在
407
+ // Global Key 输入框里时是放错位置了,提前点破,别让 Cloudflare 回 9103。
408
+ const keyShape = globalKeyShape(credential.key);
409
+ if (keyShape === 'apitoken') {
410
+ throw new GithubError(
411
+ 'BAD_REQUEST',
412
+ '这是 Cloudflare 的 API Token(cfut_ / cfat_ 前缀),不是 Global API Key。'
413
+ + '请点上面的「API Token」切换登录方式后再填它。',
414
+ );
415
+ }
416
+ if (keyShape === 'unknown') {
417
+ throw new GithubError(
418
+ 'BAD_REQUEST',
419
+ '「Global API Key」形态不符:应为 cfk_ 开头的长串,或旧格式的 37–45 位十六进制。'
420
+ + '如果手上是 cfut_ / cfat_ 开头的,那是 API Token,请切换登录方式。',
421
+ );
422
+ }
423
+ // /user 是验证 email+key 是否匹配的权威端点;同时把真实邮箱带回来。
424
+ const me = await api({
425
+ method: 'GET',
426
+ url: `${apiBase()}/user`,
427
+ credential,
428
+ timeoutMs: options.timeoutMs,
429
+ action: '校验 Global API Key',
430
+ });
431
+ const email = typeof me?.email === 'string' ? me.email : credential.email;
432
+ return { kind: 'global', id: email, status: 'active', email };
433
+ }
434
+
435
+ const value = credential.token ?? '';
436
+ if (value === '') throw new GithubError('BAD_REQUEST', '请输入 Cloudflare API Token 或 Global API Key');
437
+ // cfk_ 是 Global API Key,不能当 Bearer 用;提示用户切换模式而不是让它 401。
438
+ if (/^cfk_/.test(value)) {
439
+ throw new GithubError(
440
+ 'BAD_REQUEST',
441
+ '这是 Global API Key(cfk_ 前缀),需要按 Global API Key 方式登录:'
442
+ + '请在登录卡点「Global API Key」模式,并用「邮箱 + 这个 Key」提交。',
443
+ );
444
+ }
445
+ const result = await api({
446
+ method: 'GET',
447
+ url: `${apiBase()}/user/tokens/verify`,
448
+ credential,
449
+ timeoutMs: options.timeoutMs,
450
+ action: '校验令牌',
451
+ });
452
+ return {
453
+ kind: 'token',
454
+ id: typeof result?.id === 'string' ? result.id : '',
455
+ status: typeof result?.status === 'string' ? result.status : 'active',
456
+ email: '',
457
+ };
458
+ }
459
+
460
+ /**
461
+ * 列出令牌可访问的账户。
462
+ * @param {string} token
463
+ * @returns {Promise<{id: string, name: string, createdOn: string}[]>}
464
+ */
465
+ export async function listAccounts(credential) {
466
+ const rows = await api({
467
+ method: 'GET',
468
+ url: `${apiBase()}/accounts?per_page=50`,
469
+ credential,
470
+ action: '读取账户列表',
471
+ });
472
+ const list = Array.isArray(rows) ? rows : [];
473
+ return list.map((row) => ({
474
+ id: String(row?.id ?? ''),
475
+ name: typeof row?.name === 'string' ? row.name : String(row?.id ?? ''),
476
+ createdOn: typeof row?.created_on === 'string' ? row.created_on : '',
477
+ })).filter((row) => row.id !== '');
478
+ }
479
+
480
+ /* ------------------------------------------------------------------ */
481
+ /* Pages */
482
+ /* ------------------------------------------------------------------ */
483
+
484
+ /**
485
+ * 一个 Pages 项目的精简投影。
486
+ * @param {object} raw
487
+ * @returns {object}
488
+ */
489
+ function mapPagesProject(raw) {
490
+ const row = raw ?? {};
491
+ const source = row.source ?? {};
492
+ const config = source.config ?? {};
493
+ const latest = row.latest_deployment ?? {};
494
+ return {
495
+ name: String(row.name ?? ''),
496
+ subdomain: String(row.subdomain ?? ''),
497
+ domains: Array.isArray(row.domains) ? row.domains.map((d) => String(d)) : [],
498
+ sourceType: typeof source.type === 'string' ? source.type : '',
499
+ repoOwner: typeof config.owner === 'string' ? config.owner : '',
500
+ repoName: typeof config.repo_name === 'string' ? config.repo_name : '',
501
+ productionBranch: typeof config.production_branch === 'string' ? config.production_branch : '',
502
+ latestUrl: typeof latest.url === 'string' ? latest.url : '',
503
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
504
+ };
505
+ }
506
+
507
+ /**
508
+ * 列出账户下的 Pages 项目。
509
+ * @param {string} token
510
+ * @param {string} accountId
511
+ * @returns {Promise<object[]>}
512
+ */
513
+ export async function listPagesProjects(credential, accountId) {
514
+ const rows = await api({
515
+ method: 'GET',
516
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects`,
517
+ credential,
518
+ action: '读取 Pages 项目列表',
519
+ });
520
+ const list = Array.isArray(rows) ? rows : [];
521
+ return list.map(mapPagesProject).filter((p) => p.name !== '');
522
+ }
523
+
524
+ /**
525
+ * 一个 Pages 部署的精简投影。
526
+ * @param {object} raw
527
+ * @returns {object}
528
+ */
529
+ function mapPagesDeployment(raw) {
530
+ const row = raw ?? {};
531
+ const trigger = row.deployment_trigger ?? {};
532
+ const meta = trigger.metadata ?? {};
533
+ return {
534
+ id: String(row.id ?? ''),
535
+ environment: typeof row.environment === 'string' ? row.environment : '',
536
+ url: typeof row.url === 'string' ? row.url : '',
537
+ branch: typeof meta.branch === 'string' ? meta.branch : '',
538
+ commitMessage: typeof meta.commit_message === 'string' ? meta.commit_message : '',
539
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
540
+ };
541
+ }
542
+
543
+ /**
544
+ * 列出某个 Pages 项目的部署历史。
545
+ * @param {string} token
546
+ * @param {string} accountId
547
+ * @param {string} projectName
548
+ * @returns {Promise<object[]>}
549
+ */
550
+ export async function listPagesDeployments(credential, accountId, projectName) {
551
+ const rows = await api({
552
+ method: 'GET',
553
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments?per_page=25`,
554
+ credential,
555
+ action: '读取 Pages 部署历史',
556
+ });
557
+ const list = Array.isArray(rows) ? rows : [];
558
+ return list.map(mapPagesDeployment).filter((d) => d.id !== '');
559
+ }
560
+
561
+ /**
562
+ * 删除一个 Pages 项目(需上层确认)。
563
+ * @param {string} token
564
+ * @param {string} accountId
565
+ * @param {string} projectName
566
+ * @returns {Promise<{deleted: boolean}>}
567
+ */
568
+ export async function deletePagesProject(credential, accountId, projectName) {
569
+ const response = await request({
570
+ method: 'DELETE',
571
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`,
572
+ credential,
573
+ });
574
+ if (response.status === 200 || response.status === 204) return { deleted: true };
575
+ throw cfError(response, '删除 Pages 项目');
576
+ }
577
+
578
+ /**
579
+ * 创建 Pages 项目(Direct Upload 项目名)。
580
+ * @param {string} token
581
+ * @param {string} accountId
582
+ * @param {string} name
583
+ * @param {string} productionBranch
584
+ * @returns {Promise<object>}
585
+ */
586
+ export async function createPagesProject(credential, accountId, name, productionBranch = 'main') {
587
+ const raw = await api({
588
+ method: 'POST',
589
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects`,
590
+ credential,
591
+ action: '创建 Pages 项目',
592
+ body: { name, production_branch: productionBranch },
593
+ });
594
+ return mapPagesProject(raw);
595
+ }
596
+
597
+ /* ------------------------------------------------------------------ */
598
+ /* Workers */
599
+ /* ------------------------------------------------------------------ */
600
+
601
+ /**
602
+ * 一个 Worker 脚本的精简投影。
603
+ * @param {object} raw
604
+ * @returns {object}
605
+ */
606
+ function mapWorker(raw) {
607
+ const row = raw ?? {};
608
+ return {
609
+ id: String(row.id ?? ''),
610
+ name: typeof row.name === 'string' ? row.name : String(row.id ?? ''),
611
+ modifiedOn: typeof row.modified_on === 'string' ? row.modified_on : '',
612
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
613
+ usageModel: typeof row.usage_model === 'string' ? row.usage_model : '',
614
+ };
615
+ }
616
+
617
+ /**
618
+ * 列出账户下的 Workers 脚本。
619
+ * @param {string} token
620
+ * @param {string} accountId
621
+ * @returns {Promise<object[]>}
622
+ */
623
+ export async function listWorkers(credential, accountId) {
624
+ const rows = await api({
625
+ method: 'GET',
626
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts`,
627
+ credential,
628
+ action: '读取 Workers 列表',
629
+ });
630
+ const list = Array.isArray(rows) ? rows : [];
631
+ return list.map(mapWorker).filter((w) => w.name !== '');
632
+ }
633
+
634
+ /**
635
+ * 读取账户的 workers.dev 子域。
636
+ * @param {string} token
637
+ * @param {string} accountId
638
+ * @returns {Promise<string|null>}
639
+ */
640
+ export async function getWorkerSubdomain(credential, accountId) {
641
+ const result = await api({
642
+ method: 'GET',
643
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/subdomain`,
644
+ credential,
645
+ action: '读取 workers.dev 子域',
646
+ });
647
+ return typeof result?.subdomain === 'string' ? result.subdomain : null;
648
+ }
649
+
650
+ /**
651
+ * 删除一个 Worker(需上层确认)。
652
+ * @param {string} token
653
+ * @param {string} accountId
654
+ * @param {string} name
655
+ * @returns {Promise<{deleted: boolean}>}
656
+ */
657
+ export async function deleteWorker(credential, accountId, name) {
658
+ const response = await request({
659
+ method: 'DELETE',
660
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(name)}`,
661
+ credential,
662
+ });
663
+ if (response.status === 200 || response.status === 204) return { deleted: true };
664
+ throw cfError(response, '删除 Worker');
665
+ }
666
+
667
+ /* ------------------------------------------------------------------ */
668
+ /* Zones(域名) */
669
+ /* ------------------------------------------------------------------ */
670
+
671
+ /**
672
+ * 列出账户下的域名(zones)。
673
+ * @param {string} token
674
+ * @param {string} accountId
675
+ * @returns {Promise<{id: string, name: string, status: string}[]>}
676
+ */
677
+ export async function listZones(credential, accountId) {
678
+ const rows = await api({
679
+ method: 'GET',
680
+ url: `${apiBase()}/zones?account.id=${encodeURIComponent(accountId)}&per_page=50`,
681
+ credential,
682
+ action: '读取域名列表',
683
+ });
684
+ const list = Array.isArray(rows) ? rows : [];
685
+ return list.map((row) => ({
686
+ id: String(row?.id ?? ''),
687
+ name: typeof row?.name === 'string' ? row.name : '',
688
+ status: typeof row?.status === 'string' ? row.status : '',
689
+ })).filter((row) => row.name !== '');
690
+ }
691
+
692
+ /* ------------------------------------------------------------------ */
693
+ /* multipart 构造(Pages Direct Upload 与 Workers module upload 共用) */
694
+ /* ------------------------------------------------------------------ */
695
+
696
+ /**
697
+ * 构造一个 multipart/form-data body。
698
+ *
699
+ * @param {Array<{name: string, value: string|Buffer, contentType?: string, filename?: string}>} parts
700
+ * @param {string} boundary
701
+ * @returns {Buffer}
702
+ */
703
+ function buildMultipart(parts, boundary) {
704
+ const chunks = [];
705
+ for (const part of parts) {
706
+ chunks.push(Buffer.from(`--${boundary}\r\n`, 'utf8'));
707
+ let disposition = `form-data; name="${part.name}"`;
708
+ if (part.filename !== undefined) {
709
+ disposition += `; filename="${part.filename.replace(/["\r\n]/g, '_')}"`;
710
+ }
711
+ chunks.push(Buffer.from(`Content-Disposition: ${disposition}\r\n`, 'utf8'));
712
+ const contentType = part.contentType ?? (Buffer.isBuffer(part.value) ? 'application/octet-stream' : 'text/plain');
713
+ chunks.push(Buffer.from(`Content-Type: ${contentType}\r\n\r\n`, 'utf8'));
714
+ chunks.push(Buffer.isBuffer(part.value) ? part.value : Buffer.from(String(part.value), 'utf8'));
715
+ chunks.push(Buffer.from('\r\n', 'utf8'));
716
+ }
717
+ chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'));
718
+ return Buffer.concat(chunks);
719
+ }
720
+
721
+ /** 一个随机的 multipart boundary。 */
722
+ function randomBoundary() {
723
+ return `----DevDockBoundary${createHash('sha256').update(String(Date.now()) + String(Math.random())).digest('hex').slice(0, 16)}`;
724
+ }
725
+
726
+ /**
727
+ * 计算一段字节的 sha256 十六进制(Pages Direct Upload manifest 需要)。
728
+ * @param {Buffer} bytes
729
+ * @returns {string}
730
+ */
731
+ export function contentHash(bytes) {
732
+ return createHash('sha256').update(bytes).digest('hex');
733
+ }
734
+
735
+ /* ------------------------------------------------------------------ */
736
+ /* Pages Direct Upload:文件收集与部署 */
737
+ /* ------------------------------------------------------------------ */
738
+
739
+ /** 单文件大小上限(Pages Direct Upload:25 MiB)。 */
740
+ export const MAX_UPLOAD_FILE_BYTES = 25 * 1024 * 1024;
741
+ /** 单次部署文件数上限(保守值,低于 Pages 的 20000,避免请求体过大)。 */
742
+ export const MAX_UPLOAD_FILES = 2000;
743
+ /** 单次部署总字节数上限(避免一次请求把内存打爆)。 */
744
+ export const MAX_UPLOAD_TOTAL_BYTES = 200 * 1024 * 1024;
745
+
746
+ /** 打包到 Pages 里必须跳过的目录/文件名。 */
747
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.cache', '.wrangler']);
748
+ const SKIP_PATTERNS = [/^\.env($|\.)/, /^\.DS_Store$/, /^Thumbs\.db$/, /\.map$/, /\.log$/];
749
+
750
+ /** 常见的前端静态产物目录,按优先级。 */
751
+ export const PAGES_OUTPUT_DIRS = ['dist', 'build', 'out', '.vercel/output/static', 'public'];
752
+
753
+ /**
754
+ * 探测一个目录是否为「可部署的 Pages 静态产物目录」。
755
+ * 优先返回已存在、且含 index.html 的目录。
756
+ *
757
+ * @param {string} dir 项目根目录。
758
+ * @returns {Promise<{dir: string, type: 'pages'}|{dir: string, type: 'worker'}|null>}
759
+ */
760
+ export async function detectProjectKind(dir) {
761
+ // Worker 优先:有 wrangler 配置的目录按 Worker 处理。
762
+ for (const name of ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json']) {
763
+ try {
764
+ await readFile(path.join(dir, name), 'utf8');
765
+ return { dir, type: 'worker' };
766
+ } catch { /* 不存在则继续 */ }
767
+ }
768
+ // Pages:找含 index.html 的产物目录。
769
+ for (const rel of PAGES_OUTPUT_DIRS) {
770
+ const candidate = path.join(dir, rel);
771
+ try {
772
+ await readFile(path.join(candidate, 'index.html'), 'utf8');
773
+ return { dir: candidate, type: 'pages' };
774
+ } catch { /* 不存在 index.html */ }
775
+ }
776
+ // 项目根自身含 index.html 也算 Pages。
777
+ try {
778
+ await readFile(path.join(dir, 'index.html'), 'utf8');
779
+ return { dir, type: 'pages' };
780
+ } catch { /* 继续 */ }
781
+ return null;
782
+ }
783
+
784
+ /**
785
+ * 递归收集一个目录里要上传的文件。
786
+ *
787
+ * 应用固定的跳过规则(node_modules/.git/.env 等);任何文件超过单文件上限、
788
+ * 总数超过文件数上限、或总量超过总字节上限时返回 `exceeded`,由上层给中文提示。
789
+ *
790
+ * @param {string} dir 要上传的产物目录。
791
+ * @returns {Promise<{files: {path: string, bytes: Buffer}[],
792
+ * exceeded?: {kind: 'file'|'count'|'total', detail: string}}>}
793
+ */
794
+ export async function collectUploadFiles(dir) {
795
+ const files = [];
796
+ const stack = [''];
797
+ let totalBytes = 0;
798
+ while (stack.length > 0) {
799
+ const rel = stack.pop();
800
+ const abs = rel === '' ? dir : path.join(dir, rel);
801
+ let entries;
802
+ try {
803
+ entries = await import('node:fs/promises').then((fs) => fs.readdir(abs, { withFileTypes: true }));
804
+ } catch {
805
+ continue;
806
+ }
807
+ for (const entry of entries) {
808
+ const childRel = rel === '' ? entry.name : path.join(rel, entry.name);
809
+ if (entry.isDirectory()) {
810
+ if (SKIP_DIRS.has(entry.name)) continue;
811
+ stack.push(childRel);
812
+ continue;
813
+ }
814
+ if (!entry.isFile()) continue;
815
+ if (SKIP_PATTERNS.some((re) => re.test(entry.name))) continue;
816
+ // 统一为前向斜杠,Cloudflare 的 manifest key 用 `/` 分隔。
817
+ const key = childRel.split(path.sep).join('/');
818
+ let bytes;
819
+ try {
820
+ bytes = await readFile(path.join(dir, childRel));
821
+ } catch {
822
+ continue;
823
+ }
824
+ if (bytes.length > MAX_UPLOAD_FILE_BYTES) {
825
+ return {
826
+ files,
827
+ exceeded: { kind: 'file', detail: `${key} 超过 ${MAX_UPLOAD_FILE_BYTES / 1024 / 1024} MiB` },
828
+ };
829
+ }
830
+ totalBytes += bytes.length;
831
+ if (totalBytes > MAX_UPLOAD_TOTAL_BYTES) {
832
+ return { files, exceeded: { kind: 'total', detail: '总上传体积超过 200 MiB' } };
833
+ }
834
+ files.push({ path: key, bytes });
835
+ if (files.length > MAX_UPLOAD_FILES) {
836
+ return { files, exceeded: { kind: 'count', detail: `文件数超过 ${MAX_UPLOAD_FILES} 个` } };
837
+ }
838
+ }
839
+ }
840
+ return { files };
841
+ }
842
+
843
+ /**
844
+ * Direct Upload:把一个目录部署到 Pages 项目。
845
+ *
846
+ * @param {string} token
847
+ * @param {string} accountId
848
+ * @param {string} projectName
849
+ * @param {{directory: string, branch?: string}} options
850
+ * @returns {Promise<{id: string, url: string, environment: string}>}
851
+ */
852
+ export async function createPagesDeployment(credential, accountId, projectName, options) {
853
+ const collected = await collectUploadFiles(options.directory);
854
+ if (collected.exceeded) {
855
+ throw new GithubError('BAD_REQUEST', `无法部署:${collected.exceeded.detail}。请缩小产物或分次部署。`);
856
+ }
857
+ const manifest = collected.files.map((file) => ({
858
+ [file.path]: contentHash(file.bytes),
859
+ }));
860
+
861
+ const boundary = randomBoundary();
862
+ const parts = [
863
+ { name: 'manifest', value: JSON.stringify(manifest), contentType: 'application/json' },
864
+ ...collected.files.map((file) => ({
865
+ name: file.path,
866
+ value: file.bytes,
867
+ filename: path.basename(file.path),
868
+ contentType: contentTypeFor(file.path),
869
+ })),
870
+ ];
871
+ const body = buildMultipart(parts, boundary);
872
+
873
+ const raw = await api({
874
+ method: 'POST',
875
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments`,
876
+ credential,
877
+ timeoutMs: 120_000,
878
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
879
+ rawBody: body,
880
+ action: '部署 Pages',
881
+ });
882
+ return {
883
+ id: String(raw?.id ?? ''),
884
+ url: typeof raw?.url === 'string' ? raw.url : '',
885
+ environment: typeof raw?.environment === 'string' ? raw.environment : '',
886
+ };
887
+ }
888
+
889
+ /** 按扩展名给一个粗略的 content-type;Pages 上传用。 */
890
+ function contentTypeFor(filePath) {
891
+ const ext = path.extname(filePath).toLowerCase();
892
+ const map = {
893
+ '.html': 'text/html',
894
+ '.htm': 'text/html',
895
+ '.css': 'text/css',
896
+ '.js': 'application/javascript',
897
+ '.mjs': 'application/javascript',
898
+ '.json': 'application/json',
899
+ '.svg': 'image/svg+xml',
900
+ '.png': 'image/png',
901
+ '.jpg': 'image/jpeg',
902
+ '.jpeg': 'image/jpeg',
903
+ '.gif': 'image/gif',
904
+ '.webp': 'image/webp',
905
+ '.ico': 'image/x-icon',
906
+ '.txt': 'text/plain',
907
+ '.woff': 'font/woff',
908
+ '.woff2': 'font/woff2',
909
+ '.wasm': 'application/wasm',
910
+ };
911
+ return map[ext] ?? 'application/octet-stream';
912
+ }
913
+
914
+ /* ------------------------------------------------------------------ */
915
+ /* Workers module upload */
916
+ /* ------------------------------------------------------------------ */
917
+
918
+ /**
919
+ * 从 wrangler 配置里读 Worker 入口文件(`main` 字段)。
920
+ *
921
+ * @param {string} dir 项目根。
922
+ * @returns {Promise<string|null>} 入口相对路径。
923
+ */
924
+ export async function resolveWorkerMain(dir) {
925
+ for (const name of ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']) {
926
+ let text;
927
+ try {
928
+ text = await readFile(path.join(dir, name), 'utf8');
929
+ } catch {
930
+ continue;
931
+ }
932
+ if (name.endsWith('.toml')) {
933
+ const match = /^\s*main\s*=\s*["']?([^"'\s]+)["']?\s*$/im.exec(text);
934
+ if (match) return match[1];
935
+ } else {
936
+ // JSON/JSONC:宽松地抓 "main": "..."。
937
+ const match = /"main"\s*:\s*"([^"]+)"/.exec(text);
938
+ if (match) return match[1];
939
+ }
940
+ }
941
+ // 默认入口:src/index.js > worker.js > index.js
942
+ for (const candidate of ['src/index.js', 'worker.js', 'index.js']) {
943
+ try {
944
+ await readFile(path.join(dir, candidate), 'utf8');
945
+ return candidate;
946
+ } catch { /* 继续 */ }
947
+ }
948
+ return null;
949
+ }
950
+
951
+ /**
952
+ * 部署(或创建)一个 module Worker。
953
+ *
954
+ * @param {string} token
955
+ * @param {string} accountId
956
+ * @param {string} name Worker 名。
957
+ * @param {{mainFile: string, bytes: Buffer, compatibilityDate?: string}} options
958
+ * @returns {Promise<{name: string, url: string|null}>}
959
+ */
960
+ export async function deployWorkerModule(credential, accountId, name, options) {
961
+ const moduleName = path.basename(options.mainFile);
962
+ const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);
963
+ const metadata = JSON.stringify({
964
+ main_module: moduleName,
965
+ bindings: [],
966
+ compatibility_date: compatDate,
967
+ compatibility_flags: [],
968
+ });
969
+
970
+ const boundary = randomBoundary();
971
+ const parts = [
972
+ { name: 'metadata', value: metadata, contentType: 'application/json' },
973
+ { name: moduleName, value: options.bytes, filename: moduleName, contentType: 'application/javascript' },
974
+ ];
975
+ const body = buildMultipart(parts, boundary);
976
+
977
+ await api({
978
+ method: 'PUT',
979
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(name)}`,
980
+ credential,
981
+ timeoutMs: 120_000,
982
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
983
+ rawBody: body,
984
+ action: '部署 Worker',
985
+ });
986
+ const subdomain = await getWorkerSubdomain(credential, accountId).catch(() => null);
987
+ const url = subdomain ? `https://${name}.${subdomain}.workers.dev` : null;
988
+ return { name, url };
989
+ }
990
+
991
+ /* ------------------------------------------------------------------ */
992
+ /* 概览(设置页项目概览卡的数据源) */
993
+ /* ------------------------------------------------------------------ */
994
+
995
+ /**
996
+ * 一次并行取 pages / workers / zones 的计数与少量条目,供设置页概览卡。
997
+ *
998
+ * 任一子项失败**不**让整体失败:该子项返回空数组 + `warning`,与 repoManage
999
+ * 的「部分失败是常态」一致。
1000
+ *
1001
+ * @param {string} token
1002
+ * @param {string} accountId
1003
+ * @returns {Promise<{pages: {count: number, items: object[]}, workers: {count: number, items: object[]},
1004
+ * zones: {count: number, items: object[]}, warnings: string[]}>}
1005
+ */
1006
+ export async function cfOverview(credential, accountId) {
1007
+ const warnings = [];
1008
+ const settle = async (label, fn) => {
1009
+ try {
1010
+ const items = await fn();
1011
+ return { count: items.length, items: items.slice(0, 6) };
1012
+ } catch (error) {
1013
+ warnings.push(`${label}:${error?.message ?? error}`);
1014
+ return { count: 0, items: [] };
1015
+ }
1016
+ };
1017
+ const [pages, workers, zones] = await Promise.all([
1018
+ settle('Pages 项目', () => listPagesProjects(credential, accountId)),
1019
+ settle('Workers', () => listWorkers(credential, accountId)),
1020
+ settle('域名', () => listZones(credential, accountId)),
1021
+ ]);
1022
+ return { pages, workers, zones, warnings };
1023
+ }
1024
+
1025
+ /* ------------------------------------------------------------------ */
1026
+ /* DNS:域名记录管理 */
1027
+ /* ------------------------------------------------------------------ */
1028
+
1029
+ /** 常用 DNS 记录类型的展示名。 */
1030
+ export const DNS_RECORD_TYPES = Object.freeze([
1031
+ { id: 'A', label: 'A' },
1032
+ { id: 'AAAA', label: 'AAAA' },
1033
+ { id: 'CNAME', label: 'CNAME' },
1034
+ { id: 'TXT', label: 'TXT' },
1035
+ { id: 'MX', label: 'MX' },
1036
+ { id: 'NS', label: 'NS' },
1037
+ { id: 'SRV', label: 'SRV' },
1038
+ { id: 'CAA', label: 'CAA' },
1039
+ ]);
1040
+
1041
+ /**
1042
+ * 一个 DNS 记录的投影。
1043
+ * @param {object} raw
1044
+ * @returns {object}
1045
+ */
1046
+ function mapDnsRecord(raw) {
1047
+ const row = raw ?? {};
1048
+ return {
1049
+ id: String(row.id ?? ''),
1050
+ type: typeof row.type === 'string' ? row.type : '',
1051
+ name: typeof row.name === 'string' ? row.name : '',
1052
+ content: typeof row.content === 'string' ? row.content : '',
1053
+ proxied: row.proxied === true,
1054
+ ttl: Number.isFinite(row.ttl) ? row.ttl : 1,
1055
+ priority: Number.isFinite(row.priority) ? row.priority : null,
1056
+ locked: row.locked === true,
1057
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
1058
+ modifiedOn: typeof row.modified_on === 'string' ? row.modified_on : '',
1059
+ };
1060
+ }
1061
+
1062
+ /**
1063
+ * 列出某域名的 DNS 记录。
1064
+ *
1065
+ * @param {object} credential
1066
+ * @param {string} zoneId
1067
+ * @param {{type?: string, name?: string, page?: number, perPage?: number}} [options]
1068
+ * @returns {Promise<{items: object[], total: number}>}
1069
+ */
1070
+ export async function listDnsRecords(credential, zoneId, options = {}) {
1071
+ const perPage = Number.isFinite(options.perPage) ? Math.min(100, Math.max(1, options.perPage)) : 50;
1072
+ const page = Number.isFinite(options.page) ? Math.max(1, options.page) : 1;
1073
+ const params = new URLSearchParams({ per_page: String(perPage), page: String(page) });
1074
+ if (typeof options.type === 'string' && options.type !== '') params.set('type', options.type);
1075
+ if (typeof options.name === 'string' && options.name !== '') params.set('name', options.name);
1076
+ const rows = await api({
1077
+ method: 'GET',
1078
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/dns_records?${params.toString()}`,
1079
+ credential,
1080
+ action: '读取 DNS 记录',
1081
+ });
1082
+ const list = Array.isArray(rows) ? rows : [];
1083
+ return { items: list.map(mapDnsRecord), total: list.length };
1084
+ }
1085
+
1086
+ /**
1087
+ * 新增一条 DNS 记录。
1088
+ *
1089
+ * @param {object} credential
1090
+ * @param {string} zoneId
1091
+ * @param {{type: string, name: string, content: string, ttl?: number,
1092
+ * proxied?: boolean, priority?: number}} record
1093
+ * @returns {Promise<object>}
1094
+ */
1095
+ export async function createDnsRecord(credential, zoneId, record) {
1096
+ const type = String(record.type ?? '').trim().toUpperCase();
1097
+ const name = String(record.name ?? '').trim();
1098
+ const content = String(record.content ?? '').trim();
1099
+ if (type === '') throw new GithubError('BAD_REQUEST', '缺少 DNS 记录类型');
1100
+ if (name === '') throw new GithubError('BAD_REQUEST', '缺少 DNS 记录名称');
1101
+ if (content === '') throw new GithubError('BAD_REQUEST', '缺少 DNS 记录内容');
1102
+
1103
+ const body = { type, name, content, ttl: Number.isFinite(record.ttl) ? record.ttl : 1 };
1104
+ // proxied 只对 A/AAAA/CNAME 有意义;其它类型传了会被 Cloudflare 拒绝。
1105
+ if (['A', 'AAAA', 'CNAME'].includes(type)) body.proxied = record.proxied === true;
1106
+ if (type === 'MX' && Number.isFinite(record.priority)) body.priority = record.priority;
1107
+
1108
+ const raw = await api({
1109
+ method: 'POST',
1110
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/dns_records`,
1111
+ credential,
1112
+ body,
1113
+ action: '新增 DNS 记录',
1114
+ });
1115
+ return mapDnsRecord(raw);
1116
+ }
1117
+
1118
+ /**
1119
+ * 修改一条 DNS 记录。
1120
+ * @param {object} credential
1121
+ * @param {string} zoneId
1122
+ * @param {string} recordId
1123
+ * @param {object} patch
1124
+ * @returns {Promise<object>}
1125
+ */
1126
+ export async function updateDnsRecord(credential, zoneId, recordId, patch) {
1127
+ const body = {};
1128
+ if (typeof patch.type === 'string' && patch.type !== '') body.type = patch.type.toUpperCase();
1129
+ if (typeof patch.name === 'string' && patch.name !== '') body.name = patch.name;
1130
+ if (typeof patch.content === 'string' && patch.content !== '') body.content = patch.content;
1131
+ if (Number.isFinite(patch.ttl)) body.ttl = patch.ttl;
1132
+ if (typeof patch.proxied === 'boolean') body.proxied = patch.proxied;
1133
+ if (Number.isFinite(patch.priority)) body.priority = patch.priority;
1134
+ const raw = await api({
1135
+ method: 'PATCH',
1136
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/dns_records/${encodeURIComponent(recordId)}`,
1137
+ credential,
1138
+ body,
1139
+ action: '修改 DNS 记录',
1140
+ });
1141
+ return mapDnsRecord(raw);
1142
+ }
1143
+
1144
+ /**
1145
+ * 删除一条 DNS 记录。
1146
+ * @param {object} credential
1147
+ * @param {string} zoneId
1148
+ * @param {string} recordId
1149
+ * @returns {Promise<{deleted: boolean}>}
1150
+ */
1151
+ export async function deleteDnsRecord(credential, zoneId, recordId) {
1152
+ const response = await request({
1153
+ method: 'DELETE',
1154
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/dns_records/${encodeURIComponent(recordId)}`,
1155
+ credential,
1156
+ });
1157
+ if (response.status === 200 || response.status === 204) return { deleted: true };
1158
+ throw cfError(response, '删除 DNS 记录');
1159
+ }
1160
+
1161
+ /**
1162
+ * 域名详情(含 SSL 设置、开发模式等)。
1163
+ * @param {object} credential
1164
+ * @param {string} zoneId
1165
+ * @returns {Promise<object>}
1166
+ */
1167
+ export async function getZoneDetail(credential, zoneId) {
1168
+ const raw = await api({
1169
+ method: 'GET',
1170
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}`,
1171
+ credential,
1172
+ action: '读取域名详情',
1173
+ });
1174
+ const zone = raw ?? {};
1175
+ const setting = zone.settings ?? {};
1176
+ return {
1177
+ id: String(zone.id ?? ''),
1178
+ name: typeof zone.name === 'string' ? zone.name : '',
1179
+ status: typeof zone.status === 'string' ? zone.status : '',
1180
+ paused: zone.paused === true,
1181
+ type: typeof zone.type === 'string' ? zone.type : '',
1182
+ plan: typeof zone.plan?.name === 'string' ? zone.plan.name : '',
1183
+ nameServers: Array.isArray(zone.name_servers) ? zone.name_servers.map(String) : [],
1184
+ createdOn: typeof zone.created_on === 'string' ? zone.created_on : '',
1185
+ modifiedOn: typeof zone.modified_on === 'string' ? zone.modified_on : '',
1186
+ developmentMode: setting.development_mode === 'on',
1187
+ ssl: typeof setting.ssl === 'string' ? setting.ssl : '',
1188
+ };
1189
+ }
1190
+
1191
+ /**
1192
+ * 清除域名的全部缓存。
1193
+ * @param {object} credential
1194
+ * @param {string} zoneId
1195
+ * @returns {Promise<{purged: boolean}>}
1196
+ */
1197
+ export async function purgeZoneCache(credential, zoneId) {
1198
+ await api({
1199
+ method: 'POST',
1200
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/purge_cache`,
1201
+ credential,
1202
+ body: { purge_everything: true },
1203
+ action: '清除缓存',
1204
+ });
1205
+ return { purged: true };
1206
+ }
1207
+
1208
+ /**
1209
+ * 开关开发模式(改完立即生效,常用于调试)。
1210
+ * @param {object} credential
1211
+ * @param {string} zoneId
1212
+ * @param {boolean} enabled
1213
+ * @returns {Promise<{developmentMode: boolean}>}
1214
+ */
1215
+ export async function setDevelopmentMode(credential, zoneId, enabled) {
1216
+ await api({
1217
+ method: 'PATCH',
1218
+ url: `${apiBase()}/zones/${encodeURIComponent(zoneId)}/settings/development_mode`,
1219
+ credential,
1220
+ body: { value: enabled ? 'on' : 'off' },
1221
+ action: '切换开发模式',
1222
+ });
1223
+ return { developmentMode: enabled === true };
1224
+ }
1225
+
1226
+ /* ------------------------------------------------------------------ */
1227
+ /* Pages:部署详情与回滚 */
1228
+ /* ------------------------------------------------------------------ */
1229
+
1230
+ /**
1231
+ * 一次部署的完整投影(含构建阶段与错误摘要)。
1232
+ * @param {object} raw
1233
+ * @returns {object}
1234
+ */
1235
+ function mapDeploymentDetail(raw) {
1236
+ const row = raw ?? {};
1237
+ const stages = Array.isArray(row.stages) ? row.stages : [];
1238
+ const trigger = row.deployment_trigger ?? {};
1239
+ const meta = trigger.metadata ?? {};
1240
+ return {
1241
+ id: String(row.id ?? ''),
1242
+ shortId: String(row.id ?? '').slice(0, 8),
1243
+ environment: typeof row.environment === 'string' ? row.environment : '',
1244
+ url: typeof row.url === 'string' ? row.url : '',
1245
+ isSkipped: row.is_skipped === true,
1246
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
1247
+ modifiedOn: typeof row.modified_on === 'string' ? row.modified_on : '',
1248
+ branch: typeof meta.branch === 'string' ? meta.branch : '',
1249
+ commitHash: typeof meta.commit_hash === 'string' ? meta.commit_hash : '',
1250
+ commitMessage: typeof meta.commit_message === 'string' ? meta.commit_message : '',
1251
+ commitAuthor: typeof meta.commit_dirty === 'string' ? meta.commit_dirty : '',
1252
+ stages: stages.map((stage) => ({
1253
+ name: typeof stage.name === 'string' ? stage.name : '',
1254
+ status: typeof stage.status === 'string' ? stage.status : '',
1255
+ startedOn: typeof stage.started_on === 'string' ? stage.started_on : '',
1256
+ endedOn: typeof stage.ended_on === 'string' ? stage.ended_on : '',
1257
+ })),
1258
+ };
1259
+ }
1260
+
1261
+ /**
1262
+ * 列出某个 Pages 项目的全部部署(含构建状态)。
1263
+ * @param {object} credential
1264
+ * @param {string} accountId
1265
+ * @param {string} projectName
1266
+ * @param {{perPage?: number}} [options]
1267
+ * @returns {Promise<object[]>}
1268
+ */
1269
+ export async function listPagesDeploymentsDetailed(credential, accountId, projectName, options = {}) {
1270
+ const perPage = Number.isFinite(options.perPage) ? Math.min(25, Math.max(1, options.perPage)) : 15;
1271
+ const rows = await api({
1272
+ method: 'GET',
1273
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments?per_page=${perPage}`,
1274
+ credential,
1275
+ action: '读取部署历史',
1276
+ });
1277
+ const list = Array.isArray(rows) ? rows : [];
1278
+ return list.map(mapDeploymentDetail).filter((d) => d.id !== '');
1279
+ }
1280
+
1281
+ /**
1282
+ * 回滚到某次部署。
1283
+ *
1284
+ * Cloudflare 的「回滚」实际是创建一个新部署,内容指向被回滚的那次。
1285
+ * @param {object} credential
1286
+ * @param {string} accountId
1287
+ * @param {string} projectName
1288
+ * @param {string} deploymentId
1289
+ * @returns {Promise<object>}
1290
+ */
1291
+ export async function rollbackPagesDeployment(credential, accountId, projectName, deploymentId) {
1292
+ const raw = await api({
1293
+ method: 'POST',
1294
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments/${encodeURIComponent(deploymentId)}/rollback`,
1295
+ credential,
1296
+ action: '回滚部署',
1297
+ });
1298
+ return mapDeploymentDetail(raw);
1299
+ }
1300
+
1301
+ /**
1302
+ * 删除一次部署。
1303
+ * @param {object} credential
1304
+ * @param {string} accountId
1305
+ * @param {string} projectName
1306
+ * @param {string} deploymentId
1307
+ * @returns {Promise<{deleted: boolean}>}
1308
+ */
1309
+ export async function deletePagesDeployment(credential, accountId, projectName, deploymentId) {
1310
+ const response = await request({
1311
+ method: 'DELETE',
1312
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments/${encodeURIComponent(deploymentId)}`,
1313
+ credential,
1314
+ });
1315
+ if (response.status === 200 || response.status === 204) return { deleted: true };
1316
+ throw cfError(response, '删除部署');
1317
+ }
1318
+
1319
+ /* ------------------------------------------------------------------ */
1320
+ /* Pages:环境变量与项目配置 */
1321
+ /* ------------------------------------------------------------------ */
1322
+
1323
+ /**
1324
+ * 读取 Pages 项目的环境变量(值会被 Cloudflare 隐藏为占位)。
1325
+ * @param {object} credential
1326
+ * @param {string} accountId
1327
+ * @param {string} projectName
1328
+ * @returns {Promise<{production: object[], preview: object[]}>}
1329
+ */
1330
+ export async function listPagesEnvVars(credential, accountId, projectName) {
1331
+ const raw = await api({
1332
+ method: 'GET',
1333
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deploy_configs`,
1334
+ credential,
1335
+ action: '读取环境变量',
1336
+ });
1337
+ const pick = (table) => (table && typeof table === 'object'
1338
+ ? Object.entries(table).map(([key, meta]) => ({
1339
+ key,
1340
+ // Cloudflare 只回类型,不回明文值。
1341
+ type: typeof meta?.type === 'string' ? meta.type : 'plain_text',
1342
+ }))
1343
+ : []);
1344
+ return {
1345
+ production: pick(raw?.env_vars),
1346
+ preview: pick(raw?.env_vars || {}),
1347
+ };
1348
+ }
1349
+
1350
+ /**
1351
+ * 写入一组环境变量(覆盖同名)。
1352
+ * @param {object} credential
1353
+ * @param {string} accountId
1354
+ * @param {string} projectName
1355
+ * @param {Record<string, {value: string, type?: string}>} vars
1356
+ * @returns {Promise<{saved: number}>}
1357
+ */
1358
+ export async function patchPagesEnvVars(credential, accountId, projectName, vars) {
1359
+ const envVars = {};
1360
+ for (const [key, meta] of Object.entries(vars ?? {})) {
1361
+ if (typeof key !== 'string' || key === '') continue;
1362
+ envVars[key] = { value: String(meta?.value ?? ''), type: meta?.type === 'secret_text' ? 'secret_text' : 'plain_text' };
1363
+ }
1364
+ if (Object.keys(envVars).length === 0) {
1365
+ throw new GithubError('BAD_REQUEST', '没有要保存的环境变量');
1366
+ }
1367
+ await api({
1368
+ method: 'PATCH',
1369
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`,
1370
+ credential,
1371
+ body: { deployment_configs: { production: { env_vars: envVars } } },
1372
+ action: '保存环境变量',
1373
+ });
1374
+ return { saved: Object.keys(envVars).length };
1375
+ }
1376
+
1377
+ /* ------------------------------------------------------------------ */
1378
+ /* Workers:详情与路由 */
1379
+ /* ------------------------------------------------------------------ */
1380
+
1381
+ /**
1382
+ * 一个 Worker 脚本的详情(含绑定与兼容日期)。
1383
+ * @param {object} credential
1384
+ * @param {string} accountId
1385
+ * @param {string} name
1386
+ * @returns {Promise<object>}
1387
+ */
1388
+ export async function getWorkerDetail(credential, accountId, name) {
1389
+ const rows = await api({
1390
+ method: 'GET',
1391
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(name)}`,
1392
+ credential,
1393
+ action: '读取 Worker 详情',
1394
+ });
1395
+ const list = Array.isArray(rows) ? rows : [];
1396
+ // 该端点返回的是脚本内容数组(module 格式),只取元信息。
1397
+ return {
1398
+ name,
1399
+ modules: list.map((m) => ({
1400
+ name: typeof m?.name === 'string' ? m.name : '',
1401
+ contentType: typeof m?.content_type === 'string' ? m.content_type : '',
1402
+ })).filter((m) => m.name !== ''),
1403
+ subdomain: null,
1404
+ };
1405
+ }
1406
+
1407
+ /**
1408
+ * 列出账号下所有 Worker 路由(zone + pattern + script)。
1409
+ * @param {object} credential
1410
+ * @param {string} accountId
1411
+ * @returns {Promise<object[]>}
1412
+ */
1413
+ export async function listWorkerRoutes(credential, accountId) {
1414
+ const rows = await api({
1415
+ method: 'GET',
1416
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/routes`,
1417
+ credential,
1418
+ action: '读取 Worker 路由',
1419
+ });
1420
+ const list = Array.isArray(rows) ? rows : [];
1421
+ return list.map((row) => ({
1422
+ id: String(row?.id ?? ''),
1423
+ pattern: typeof row?.pattern === 'string' ? row.pattern : '',
1424
+ script: typeof row?.script === 'string' ? row.script : '',
1425
+ })).filter((r) => r.pattern !== '');
1426
+ }
1427
+
1428
+ /**
1429
+ * 新增一条 Worker 路由。
1430
+ * @param {object} credential
1431
+ * @param {string} accountId
1432
+ * @param {string} zoneId
1433
+ * @param {string} pattern
1434
+ * @param {string} script
1435
+ * @returns {Promise<object>}
1436
+ */
1437
+ export async function createWorkerRoute(credential, accountId, zoneId, pattern, script) {
1438
+ if (!pattern || !script) {
1439
+ throw new GithubError('BAD_REQUEST', '新增 Worker 路由需要 pattern 与 script');
1440
+ }
1441
+ const raw = await api({
1442
+ method: 'POST',
1443
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/routes`,
1444
+ credential,
1445
+ body: { pattern, script },
1446
+ action: '新增 Worker 路由',
1447
+ });
1448
+ return {
1449
+ id: String(raw?.id ?? ''),
1450
+ pattern: typeof raw?.pattern === 'string' ? raw.pattern : pattern,
1451
+ script: typeof raw?.script === 'string' ? raw.script : script,
1452
+ zoneId,
1453
+ };
1454
+ }
1455
+
1456
+ /**
1457
+ * 删除一条 Worker 路由。
1458
+ * @param {object} credential
1459
+ * @param {string} accountId
1460
+ * @param {string} routeId
1461
+ * @returns {Promise<{deleted: boolean}>}
1462
+ */
1463
+ export async function deleteWorkerRoute(credential, accountId, routeId) {
1464
+ const response = await request({
1465
+ method: 'DELETE',
1466
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/routes/${encodeURIComponent(routeId)}`,
1467
+ credential,
1468
+ });
1469
+ if (response.status === 200 || response.status === 204) return { deleted: true };
1470
+ throw cfError(response, '删除 Worker 路由');
1471
+ }
1472
+
1473
+ /**
1474
+ * 切换 Workers 全局子域(workers.dev 是否启用)。
1475
+ * @param {object} credential
1476
+ * @param {string} accountId
1477
+ * @param {boolean} enabled
1478
+ * @returns {Promise<{enabled: boolean, subdomain: string|null}>}
1479
+ */
1480
+ export async function setWorkersSubdomainEnabled(credential, accountId, enabled) {
1481
+ const raw = await api({
1482
+ method: 'PUT',
1483
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/subdomain`,
1484
+ credential,
1485
+ body: { enabled: enabled === true },
1486
+ action: '切换 workers.dev 子域',
1487
+ });
1488
+ return {
1489
+ enabled: enabled === true,
1490
+ subdomain: typeof raw?.subdomain === 'string' ? raw.subdomain : null,
1491
+ };
1492
+ }
1493
+
1494
+ /* ------------------------------------------------------------------ */
1495
+ /* 用量与分析 */
1496
+ /* ------------------------------------------------------------------ */
1497
+
1498
+ /**
1499
+ * 账号级用量概览:来自 GraphQL 的聚合数据(请求数、带宽、错误)。
1500
+ *
1501
+ * GraphQL 失败不影响其它功能:返回 `unavailable: true` + 中文原因,
1502
+ * 界面据此显示提示而不是错误。
1503
+ *
1504
+ * @param {object} credential
1505
+ * @param {string} accountId
1506
+ * @returns {Promise<object>}
1507
+ */
1508
+ export async function fetchUsage(credential, accountId) {
1509
+ const query = `query($accountTag: String!) {
1510
+ viewer {
1511
+ accounts(filter: { accountTag: $accountTag }) {
1512
+ workersInvocationsAdaptive(limit: 1) {
1513
+ sum { requests errors subrequests }
1514
+ }
1515
+ pagesFunctionsInvocationsAdaptiveGroups(limit: 1) {
1516
+ sum { requests errors }
1517
+ }
1518
+ }
1519
+ }
1520
+ }`;
1521
+ try {
1522
+ const raw = await request({
1523
+ method: 'POST',
1524
+ url: `${apiBase()}/graphql`,
1525
+ credential,
1526
+ body: { query, variables: { accountTag: accountId } },
1527
+ });
1528
+ if (raw.status >= 400) {
1529
+ return { unavailable: true, reason: 'HTTP_' + raw.status, message: '用量数据需要 Analytics: Read 权限。' };
1530
+ }
1531
+ const json = raw.json;
1532
+ if (Array.isArray(json?.errors) && json.errors.length > 0) {
1533
+ return {
1534
+ unavailable: true,
1535
+ reason: 'GRAPHQL',
1536
+ message: '用量数据读取失败:' + String(json.errors[0]?.message ?? '未知原因'),
1537
+ };
1538
+ }
1539
+ const acc = json?.data?.viewer?.accounts?.[0] ?? {};
1540
+ const worker = acc.workersInvocationsAdaptive?.[0]?.sum ?? {};
1541
+ const pagesFn = acc.pagesFunctionsInvocationsAdaptiveGroups?.[0]?.sum ?? {};
1542
+ return {
1543
+ unavailable: false,
1544
+ workers: {
1545
+ requests: Number(worker.requests ?? 0),
1546
+ errors: Number(worker.errors ?? 0),
1547
+ subrequests: Number(worker.subrequests ?? 0),
1548
+ },
1549
+ pagesFunctions: {
1550
+ requests: Number(pagesFn.requests ?? 0),
1551
+ errors: Number(pagesFn.errors ?? 0),
1552
+ },
1553
+ };
1554
+ } catch (error) {
1555
+ return {
1556
+ unavailable: true,
1557
+ reason: error?.code === 'NETWORK' ? 'NETWORK' : 'INTERNAL',
1558
+ message: String(error?.message ?? error).slice(0, 200),
1559
+ };
1560
+ }
1561
+ }
1562
+
1563
+ /**
1564
+ * 账号下的资源总览统计(供设置页多卡展示)。
1565
+ *
1566
+ * 与 cfOverview 的区别:这个给的是「多种维度的数字」,包含部署数、
1567
+ * 域名状态分布、Worker 路由数等,用于设置页的信息面板。
1568
+ *
1569
+ * @param {object} credential
1570
+ * @param {string} accountId
1571
+ * @returns {Promise<object>}
1572
+ */
1573
+ export async function cfDashboard(credential, accountId) {
1574
+ const warnings = [];
1575
+ const settle = async (label, fn, fallback) => {
1576
+ try {
1577
+ return await fn();
1578
+ } catch (error) {
1579
+ warnings.push(`${label}:${String(error?.message ?? error).slice(0, 120)}`);
1580
+ return fallback;
1581
+ }
1582
+ };
1583
+
1584
+ const [projects, workers, zones, routes] = await Promise.all([
1585
+ settle('Pages', () => listPagesProjects(credential, accountId), []),
1586
+ settle('Workers', () => listWorkers(credential, accountId), []),
1587
+ settle('域名', () => listZones(credential, accountId), []),
1588
+ settle('路由', () => listWorkerRoutes(credential, accountId), []),
1589
+ ]);
1590
+
1591
+ // 最近部署:取前 3 个项目的最近一次部署,合并排序。
1592
+ const recent = [];
1593
+ for (const project of projects.slice(0, 3)) {
1594
+ try {
1595
+ const deployments = await listPagesDeploymentsDetailed(credential, accountId, project.name, { perPage: 1 });
1596
+ if (deployments.length > 0) {
1597
+ recent.push({ project: project.name, ...deployments[0] });
1598
+ }
1599
+ } catch { /* 单个项目失败不影响整体 */ }
1600
+ }
1601
+ recent.sort((a, b) => String(b.createdOn).localeCompare(String(a.createdOn)));
1602
+
1603
+ return {
1604
+ counts: {
1605
+ pages: projects.length,
1606
+ workers: workers.length,
1607
+ zones: zones.length,
1608
+ routes: routes.length,
1609
+ },
1610
+ zones: {
1611
+ active: zones.filter((z) => z.status === 'active').length,
1612
+ pending: zones.filter((z) => z.status === 'pending').length,
1613
+ items: zones.slice(0, 8),
1614
+ },
1615
+ projects: projects.slice(0, 8).map((p) => ({
1616
+ name: p.name,
1617
+ subdomain: p.subdomain,
1618
+ latestUrl: p.latestUrl,
1619
+ repoOwner: p.repoOwner,
1620
+ repoName: p.repoName,
1621
+ })),
1622
+ workers: workers.slice(0, 8).map((w) => ({ name: w.name, modifiedOn: w.modifiedOn })),
1623
+ recentDeployments: recent.slice(0, 3),
1624
+ routes: routes.slice(0, 5),
1625
+ warnings,
1626
+ };
1627
+ }
1628
+
1629
+ /** dash.cloudflare.com 上的资源页深度链接。 */
1630
+ export function dashUrl(accountId, resource) {
1631
+ return `${DASH_ORIGIN}/${encodeURIComponent(accountId)}/${resource}`;
1632
+ }