dsh-devdock 2.0.0 → 2.5.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,1027 @@
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
+ import { GithubError } from './github.js';
28
+
29
+ /** Cloudflare API v4 基地址;环境变量可指向镜像或测试用假服务器。 */
30
+ const DEFAULT_API_BASE = 'https://api.cloudflare.com/client/v4';
31
+
32
+ /**
33
+ * 当前 API 基地址。
34
+ *
35
+ * 每次调用时读取而不是模块加载时固化:测试要能在同一进程里指向本地假
36
+ * 服务器,固化会让它读到旧值。
37
+ * @returns {string}
38
+ */
39
+ function apiBase() {
40
+ const raw = process.env.DSH_PUSH_CF_API_BASE;
41
+ const value = typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : DEFAULT_API_BASE;
42
+ return value.replace(/\/+$/, '');
43
+ }
44
+
45
+ const DASH_ORIGIN = 'https://dash.cloudflare.com';
46
+ const USER_AGENT = 'dsh-devdock (+https://github.com/QingJing5906/dsh-DevDock)';
47
+ const DEFAULT_TIMEOUT_MS = 20_000;
48
+
49
+ /** Cloudflare 错误码 → 中文缺权限提示的关键词(用于把 403/9109 翻译成人话)。 */
50
+ const PERMISSION_HINTS = [
51
+ [/Pages|pages/i, 'Cloudflare Pages: Edit'],
52
+ [/Workers Scripts|workers scripts|script/i, 'Workers Scripts: Edit'],
53
+ [/Zone|zone/i, 'Zone: Read'],
54
+ [/Account|account|user|member/i, 'Account Settings: Read'],
55
+ ];
56
+
57
+ /**
58
+ * 把低层 socket 错误翻译成 CONTRACT §0 的 NETWORK 码,措辞与 github.js 一致。
59
+ * @param {Error} error
60
+ * @param {string} target
61
+ * @param {number} timeoutMs
62
+ * @returns {GithubError}
63
+ */
64
+ function networkError(error, target, timeoutMs) {
65
+ const code = String(error?.code ?? '');
66
+ const name = String(error?.name ?? '');
67
+ const timedOut = name === 'AbortError' || code === 'ABORT_ERR' || name === 'TimeoutError';
68
+ if (timedOut) {
69
+ return new GithubError(
70
+ 'NETWORK',
71
+ `连接 Cloudflare 超时(${Math.round(timeoutMs / 1000)} 秒):${target}。请检查网络或代理设置。`,
72
+ { cause: error },
73
+ );
74
+ }
75
+ const tls = /CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY|EPROTO|ERR_TLS/i.test(`${code} ${error?.message ?? ''}`);
76
+ const dns = code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EAI_FAIL';
77
+ const refused = code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'EHOSTUNREACH' || code === 'ETIMEDOUT';
78
+ let hint;
79
+ if (tls) {
80
+ hint = '本机 TLS/证书校验未能通过 Cloudflare 的证书(常见于系统时间错误、企业代理或杀毒软件拦截)。';
81
+ } else if (dns) {
82
+ hint = 'DNS 解析失败,请检查网络连接或代理配置。';
83
+ } else if (refused) {
84
+ hint = '网络连接被拒绝或中断,请检查网络、代理或防火墙。';
85
+ } else {
86
+ hint = '请检查网络连接、代理设置和系统时间。';
87
+ }
88
+ return new GithubError(
89
+ 'NETWORK',
90
+ `无法连接 Cloudflare:${target}(${code || '网络错误'})。${hint}`,
91
+ { cause: error },
92
+ );
93
+ }
94
+
95
+ /**
96
+ * 发一个 Cloudflare API 请求。
97
+ *
98
+ * 支持 JSON body(`body`)与原始字节(`rawBody` + `contentType`,用于 multipart)。
99
+ * 响应按内容类型解析 JSON,否则当文本。
100
+ *
101
+ * @param {object} options
102
+ * @param {string} options.method
103
+ * @param {string} options.url 绝对 URL。
104
+ * @param {string} [options.token]
105
+ * @param {object} [options.body] JSON body。
106
+ * @param {Buffer} [options.rawBody] 原始字节(multipart)。
107
+ * @param {Record<string,string>} [options.headers]
108
+ * @param {number} [options.timeoutMs]
109
+ * @returns {Promise<{status: number, headers: object, json: any, text: string}>}
110
+ */
111
+ function request(options) {
112
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_TIMEOUT_MS;
113
+ const headers = {
114
+ 'user-agent': USER_AGENT,
115
+ accept: 'application/json',
116
+ ...(options.headers ?? {}),
117
+ };
118
+ // 两种凭据形态,由 auth 头统一折算:
119
+ // - API Token(可细粒度)-> Authorization: Bearer <token>
120
+ // - Global API Key(全权限,只需邮箱 + Key)-> X-Auth-Email + X-Auth-Key
121
+ // Global Key 省去逐个勾权限的麻烦,代价是它等于账户最高权限。
122
+ if (options.credential) {
123
+ if (options.credential.kind === 'global') {
124
+ if (options.credential.email) headers['x-auth-email'] = options.credential.email;
125
+ if (options.credential.key) headers['x-auth-key'] = options.credential.key;
126
+ } else if (options.credential.token) {
127
+ headers.authorization = 'Bearer ' + options.credential.token;
128
+ }
129
+ }
130
+ let payload;
131
+ if (options.rawBody !== undefined) {
132
+ payload = Buffer.isBuffer(options.rawBody) ? options.rawBody : Buffer.from(options.rawBody);
133
+ headers['content-length'] = String(payload.length);
134
+ } else if (options.body !== undefined) {
135
+ payload = Buffer.from(JSON.stringify(options.body), 'utf8');
136
+ headers['content-type'] = 'application/json; charset=utf-8';
137
+ headers['content-length'] = String(payload.length);
138
+ }
139
+ return new Promise((resolvePromise, reject) => {
140
+ const controller = new AbortController();
141
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
142
+ let settled = false;
143
+ const done = (fn, value) => {
144
+ if (settled) return;
145
+ settled = true;
146
+ clearTimeout(timer);
147
+ fn(value);
148
+ };
149
+ let req;
150
+ try {
151
+ const transport = String(options.url).startsWith('http://') ? httpRequest : httpsRequest;
152
+ req = transport(options.url, { method: options.method, headers, signal: controller.signal }, (res) => {
153
+ const chunks = [];
154
+ res.on('data', (chunk) => chunks.push(chunk));
155
+ res.on('end', () => {
156
+ const text = Buffer.concat(chunks).toString('utf8');
157
+ const contentType = String(res.headers['content-type'] ?? '');
158
+ let json;
159
+ if (text !== '' && /json/i.test(contentType)) {
160
+ try { json = JSON.parse(text); } catch { json = undefined; }
161
+ }
162
+ done(resolvePromise, {
163
+ status: typeof res.statusCode === 'number' ? res.statusCode : 0,
164
+ headers: res.headers,
165
+ json,
166
+ text,
167
+ });
168
+ });
169
+ res.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
170
+ });
171
+ } catch (error) {
172
+ clearTimeout(timer);
173
+ reject(networkError(error, options.url, timeoutMs));
174
+ return;
175
+ }
176
+ req.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
177
+ if (payload !== undefined) req.write(payload);
178
+ req.end();
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Cloudflare 响应 → 统一错误。
184
+ *
185
+ * Cloudflare 用 `{success, errors:[{code,message}]}`;`success:false` 或 HTTP 非 2xx
186
+ * 都要翻译。403/9109 一类权限错误额外给出缺哪个 Permission Group 的中文提示。
187
+ *
188
+ * @param {object} response
189
+ * @param {string} action 中文动作名。
190
+ * @returns {GithubError}
191
+ */
192
+ function cfError(response, action) {
193
+ const status = response.status;
194
+ const errors = Array.isArray(response.json?.errors) ? response.json.errors : [];
195
+ const first = errors[0] || {};
196
+ const code = typeof first.code === 'number' ? String(first.code) : '';
197
+ const message = typeof first.message === 'string' ? first.message : '';
198
+ const detail = message || response.text.slice(0, 300) || '未知错误';
199
+
200
+ // 6003 + error_chain 6111 = 凭据格式不对(令牌没复制全 / 混进空白 /
201
+ // 把 API Token 和 Global API Key 用错了位置)。Cloudflare 只给
202
+ // 「Invalid request headers」这种含糊措辞,这里翻译成能直接照做的话。
203
+ const chainCodes = (Array.isArray(first.error_chain) ? first.error_chain : [])
204
+ .map((e) => String(e && e.code ? e.code : ''));
205
+ // 6102 = X-Auth-Email 头格式非法:邮箱里有空格/全角字符/换行,或根本不是邮箱。
206
+ if (code === '6003' && chainCodes.includes('6102')) {
207
+ return new GithubError(
208
+ 'BAD_REQUEST',
209
+ 'Cloudflare 认为「账户邮箱」格式不对(X-Auth-Email 头非法)。'
210
+ + '请确认填的是 Cloudflare 登录邮箱,且不含空格、全角符号或换行。',
211
+ { status },
212
+ );
213
+ }
214
+ // 6103 = X-Auth-Key 头格式非法:Global API Key 形态不对
215
+ // (新格式 cfk_ 开头;旧格式 37–45 位十六进制)。
216
+ if (code === '6003' && chainCodes.includes('6103')) {
217
+ return new GithubError(
218
+ 'BAD_REQUEST',
219
+ 'Cloudflare 认为「Global API Key」格式不对(X-Auth-Key 头非法)。'
220
+ + '它应为 cfk_ 开头的长串(新版格式),或 37–45 位十六进制(旧格式)。'
221
+ + '若手上是 cfut_ / cfat_ 开头的,那是 API Token,请切换登录方式。',
222
+ { status },
223
+ );
224
+ }
225
+ if (code === '6003' && chainCodes.includes('6111')) {
226
+ return new GithubError(
227
+ 'UNAUTHORIZED',
228
+ 'Cloudflare 拒绝了凭据:请求头格式不对。'
229
+ + '如果你用的是 API Token,请确认它完整复制、没有多余空格;'
230
+ + '如果你填的是 Global API Key,请确认「邮箱 + Key」两项都填了,且 Key 没有和 API Token 弄混。',
231
+ { status },
232
+ );
233
+ }
234
+
235
+ // 1000 = Invalid API Token:令牌被吊销 / 复制不全 / 从未创建成功。
236
+ if (code === '1000') {
237
+ return new GithubError(
238
+ 'UNAUTHORIZED',
239
+ 'Cloudflare 认为这个 API Token 无效(1000 Invalid API Token)。'
240
+ + '常见原因:令牌已被删除或吊销、复制时漏掉了字符、或创建后没有点完最后的「Create Token」。'
241
+ + '也可以改用 Global API Key 登录:在 My Profile › API Tokens › Global API Key 里查看,'
242
+ + '填「邮箱 + Key」即可,无需逐个勾权限。',
243
+ { status },
244
+ );
245
+ }
246
+ if (status === 429) {
247
+ return new GithubError('RATE_LIMITED', `Cloudflare API 触发速率限制(${action}),请稍后重试:${detail}`, { status });
248
+ }
249
+ if (status === 401 || status === 403 || code === '9109' || code === '10000') {
250
+ let permHint = '';
251
+ for (const [re, group] of PERMISSION_HINTS) {
252
+ if (re.test(detail)) { permHint = `;通常需要令牌具备「${group}」权限`; break; }
253
+ }
254
+ return new GithubError(
255
+ 'UNAUTHORIZED',
256
+ `Cloudflare 拒绝了该操作(${action})${code ? `[${code}] ` : ''}:${detail}。`
257
+ + `${permHint || '请确认 API Token 有效且包含所需权限组。'}`,
258
+ { status },
259
+ );
260
+ }
261
+ if (status === 404) {
262
+ return new GithubError('NOT_FOUND', `Cloudflare 上找不到对应资源(${action}):${detail}`, { status });
263
+ }
264
+ if (status >= 400 && status < 500) {
265
+ return new GithubError('BAD_REQUEST', `Cloudflare 请求失败(${action},HTTP ${status}):${detail}`, { status });
266
+ }
267
+ return new GithubError(
268
+ 'NETWORK',
269
+ `Cloudflare 服务异常(HTTP ${status},${action}):${detail || '请稍后重试'}。`,
270
+ { status },
271
+ );
272
+ }
273
+
274
+ /**
275
+ * 一次「期望 success:true」的调用;返回 result。
276
+ * @param {object} options 同 {@link request},另加 `action`。
277
+ * @returns {Promise<any>}
278
+ */
279
+ async function api(options) {
280
+ const response = await request(options);
281
+ // 2xx 且 Cloudflare 信封 success(或没有信封字段时按 2xx 通过)。
282
+ const envelopeOk = response.json && typeof response.json.success === 'boolean'
283
+ ? response.json.success
284
+ : response.status >= 200 && response.status < 300;
285
+ if (response.status < 200 || response.status >= 300 || !envelopeOk) {
286
+ throw cfError(response, options.action ?? '调用 Cloudflare API');
287
+ }
288
+ return response.json?.result;
289
+ }
290
+
291
+ /* ------------------------------------------------------------------ */
292
+ /* 凭据(API Token 或 Global API Key) */
293
+ /* ------------------------------------------------------------------ */
294
+
295
+ /**
296
+ * 把外部传入的凭据收成两种明确形态之一。
297
+ *
298
+ * 支持两种:
299
+ * - `{ kind: 'token', token }` —— API Token,可细粒度授权,用 Bearer 头。
300
+ * - `{ kind: 'global', email, key }` —— Global API Key,账户全权限,
301
+ * 用 X-Auth-Email + X-Auth-Key,不需要逐个勾权限组。
302
+ *
303
+ * 也接受裸字符串(视为 API Token),这样旧调用与测试不用改。
304
+ *
305
+ * @param {string|{kind?: string, token?: string, email?: string, key?: string}} raw
306
+ * @returns {{kind: 'token'|'global', token?: string, email?: string, key?: string}}
307
+ */
308
+ export function normalizeCredential(raw) {
309
+ if (typeof raw === 'string') {
310
+ return { kind: 'token', token: raw.trim() };
311
+ }
312
+ if (raw && typeof raw === 'object') {
313
+ if (raw.kind === 'global' || (raw.key !== undefined && raw.email !== undefined)) {
314
+ return {
315
+ kind: 'global',
316
+ // 粘贴时最容易带进不可见字符(零宽空格、全角空格、换行),
317
+ // 它们会让 X-Auth-Email 变成非法头,Cloudflare 只回一句含糊的 6003。
318
+ email: String(raw.email ?? '').replace(/[\s\u200B-\u200D\uFEFF]/g, ''),
319
+ key: String(raw.key ?? '').replace(/[\s\u200B-\u200D\uFEFF]/g, ''),
320
+ };
321
+ }
322
+ return { kind: 'token', token: String(raw.token ?? '').trim() };
323
+ }
324
+ return { kind: 'token', token: '' };
325
+ }
326
+
327
+ /** 凭据是否「看起来填全了」,用于前端置灰按钮。 */
328
+ export function credentialComplete(raw) {
329
+ const c = normalizeCredential(raw);
330
+ if (c.kind === 'global') return c.email !== '' && c.key !== '';
331
+ return c.token !== '';
332
+ }
333
+
334
+ /**
335
+ * 凭据的字符串标识(仅用于日志/提示,绝不含密钥本体)。
336
+ * @param {string|object} raw
337
+ * @returns {string}
338
+ */
339
+ function credentialString(raw) {
340
+ const c = normalizeCredential(raw);
341
+ if (c.kind === 'global') return c.email !== '' ? `global:${c.email}` : '';
342
+ return c.token ?? '';
343
+ }
344
+
345
+ /**
346
+ * 校验凭据是否可用。
347
+ *
348
+ * API Token 走 `GET /user/tokens/verify`;Global API Key 没有对应的 verify
349
+ * 端点,改用 `GET /user`(它能证明 email+key 组合有效)并同时拿回账户邮箱。
350
+ *
351
+ * @param {string|object} raw
352
+ * @param {{timeoutMs?: number}} [options]
353
+ * @returns {Promise<{kind: string, id: string, status: string, email: string}>}
354
+ */
355
+ /**
356
+ * 判定一段字符串像哪种 Cloudflare 凭据(只做形态判断,不做有效性联网校验)。
357
+ *
358
+ * 依据官方 Token formats:
359
+ * - Global API Key 新格式 `cfk_` + 40 字符 + checksum
360
+ * - 用户 API Token `cfut_` + 40 + checksum
361
+ * - 账户 API Token `cfat_` + 40 + checksum
362
+ * - 2026 年前的旧格式:Global Key 是 37–45 位小写十六进制,Token 是 40 位字母数字
363
+ *
364
+ * @param {string} value
365
+ * @returns {'global'|'apitoken'|'unknown'}
366
+ */
367
+ export function globalKeyShape(value) {
368
+ const text = String(value ?? '').trim();
369
+ if (text === '') return 'unknown';
370
+ // 新格式
371
+ if (/^cfk_[A-Za-z0-9]{20,}$/.test(text)) return 'global';
372
+ if (/^cf(at|ut)_[A-Za-z0-9]{20,}$/.test(text)) return 'apitoken';
373
+ // 旧格式:Global Key 是纯小写十六进制
374
+ if (/^[0-9a-f]{37,45}$/.test(text)) return 'global';
375
+ // 旧格式:API Token 是 40 位字母数字(含 g-z 就不会被判成十六进制)
376
+ if (/^[A-Za-z0-9_-]{40}$/.test(text)) return 'apitoken';
377
+ return 'unknown';
378
+ }
379
+ export async function verifyToken(raw, options = {}) {
380
+ const credential = normalizeCredential(raw);
381
+
382
+ if (credential.kind === 'global') {
383
+ if (credential.email === '' || credential.key === '') {
384
+ throw new GithubError(
385
+ 'BAD_REQUEST',
386
+ 'Global API Key 登录需要同时填写「账户邮箱」和「Global API Key」两项。',
387
+ );
388
+ }
389
+ // 邮箱必须是 ASCII 邮箱形态。全角 @、中文逗号、首尾空格、粘贴带进来的
390
+ // 不可见字符都会让 Cloudflare 回 6003 "Invalid request headers"
391
+ // (error_chain 6102 Invalid format for X-Auth-Email),那条报错看不出是邮箱的问题。
392
+ const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(credential.email)
393
+ && /^[\x20-\x7E]+$/.test(credential.email);
394
+ if (!emailOk) {
395
+ throw new GithubError(
396
+ 'BAD_REQUEST',
397
+ `「账户邮箱」格式不对:${credential.email}。`
398
+ + '它必须是 Cloudflare 登录邮箱(如 name@example.com),'
399
+ + '不能含空格、全角符号或换行;请重新输入后再试。',
400
+ );
401
+ }
402
+ // Global API Key 有两代格式,都必须接受:
403
+ // - 新格式(2026 起):`cfk_` + 40 字符 + checksum
404
+ // - 旧格式:37–45 位小写十六进制
405
+ // 反过来说,`cfut_`(用户 API Token)与 `cfat_`(账户 API Token)出现在
406
+ // Global Key 输入框里时是放错位置了,提前点破,别让 Cloudflare 回 9103。
407
+ const keyShape = globalKeyShape(credential.key);
408
+ if (keyShape === 'apitoken') {
409
+ throw new GithubError(
410
+ 'BAD_REQUEST',
411
+ '这是 Cloudflare 的 API Token(cfut_ / cfat_ 前缀),不是 Global API Key。'
412
+ + '请点上面的「API Token」切换登录方式后再填它。',
413
+ );
414
+ }
415
+ if (keyShape === 'unknown') {
416
+ throw new GithubError(
417
+ 'BAD_REQUEST',
418
+ '「Global API Key」形态不符:应为 cfk_ 开头的长串,或旧格式的 37–45 位十六进制。'
419
+ + '如果手上是 cfut_ / cfat_ 开头的,那是 API Token,请切换登录方式。',
420
+ );
421
+ }
422
+ // /user 是验证 email+key 是否匹配的权威端点;同时把真实邮箱带回来。
423
+ const me = await api({
424
+ method: 'GET',
425
+ url: `${apiBase()}/user`,
426
+ credential,
427
+ timeoutMs: options.timeoutMs,
428
+ action: '校验 Global API Key',
429
+ });
430
+ const email = typeof me?.email === 'string' ? me.email : credential.email;
431
+ return { kind: 'global', id: email, status: 'active', email };
432
+ }
433
+
434
+ const value = credential.token ?? '';
435
+ if (value === '') throw new GithubError('BAD_REQUEST', '请输入 Cloudflare API Token 或 Global API Key');
436
+ // cfk_ 是 Global API Key,不能当 Bearer 用;提示用户切换模式而不是让它 401。
437
+ if (/^cfk_/.test(value)) {
438
+ throw new GithubError(
439
+ 'BAD_REQUEST',
440
+ '这是 Global API Key(cfk_ 前缀),需要按 Global API Key 方式登录:'
441
+ + '请在登录卡点「Global API Key」模式,并用「邮箱 + 这个 Key」提交。',
442
+ );
443
+ }
444
+ const result = await api({
445
+ method: 'GET',
446
+ url: `${apiBase()}/user/tokens/verify`,
447
+ credential,
448
+ timeoutMs: options.timeoutMs,
449
+ action: '校验令牌',
450
+ });
451
+ return {
452
+ kind: 'token',
453
+ id: typeof result?.id === 'string' ? result.id : '',
454
+ status: typeof result?.status === 'string' ? result.status : 'active',
455
+ email: '',
456
+ };
457
+ }
458
+
459
+ /**
460
+ * 列出令牌可访问的账户。
461
+ * @param {string} token
462
+ * @returns {Promise<{id: string, name: string, createdOn: string}[]>}
463
+ */
464
+ export async function listAccounts(credential) {
465
+ const rows = await api({
466
+ method: 'GET',
467
+ url: `${apiBase()}/accounts?per_page=50`,
468
+ credential,
469
+ action: '读取账户列表',
470
+ });
471
+ const list = Array.isArray(rows) ? rows : [];
472
+ return list.map((row) => ({
473
+ id: String(row?.id ?? ''),
474
+ name: typeof row?.name === 'string' ? row.name : String(row?.id ?? ''),
475
+ createdOn: typeof row?.created_on === 'string' ? row.created_on : '',
476
+ })).filter((row) => row.id !== '');
477
+ }
478
+
479
+ /* ------------------------------------------------------------------ */
480
+ /* Pages */
481
+ /* ------------------------------------------------------------------ */
482
+
483
+ /**
484
+ * 一个 Pages 项目的精简投影。
485
+ * @param {object} raw
486
+ * @returns {object}
487
+ */
488
+ function mapPagesProject(raw) {
489
+ const row = raw ?? {};
490
+ const source = row.source ?? {};
491
+ const config = source.config ?? {};
492
+ const latest = row.latest_deployment ?? {};
493
+ return {
494
+ name: String(row.name ?? ''),
495
+ subdomain: String(row.subdomain ?? ''),
496
+ domains: Array.isArray(row.domains) ? row.domains.map((d) => String(d)) : [],
497
+ sourceType: typeof source.type === 'string' ? source.type : '',
498
+ repoOwner: typeof config.owner === 'string' ? config.owner : '',
499
+ repoName: typeof config.repo_name === 'string' ? config.repo_name : '',
500
+ productionBranch: typeof config.production_branch === 'string' ? config.production_branch : '',
501
+ latestUrl: typeof latest.url === 'string' ? latest.url : '',
502
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
503
+ };
504
+ }
505
+
506
+ /**
507
+ * 列出账户下的 Pages 项目。
508
+ * @param {string} token
509
+ * @param {string} accountId
510
+ * @returns {Promise<object[]>}
511
+ */
512
+ export async function listPagesProjects(credential, accountId) {
513
+ const rows = await api({
514
+ method: 'GET',
515
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects`,
516
+ credential,
517
+ action: '读取 Pages 项目列表',
518
+ });
519
+ const list = Array.isArray(rows) ? rows : [];
520
+ return list.map(mapPagesProject).filter((p) => p.name !== '');
521
+ }
522
+
523
+ /**
524
+ * 一个 Pages 部署的精简投影。
525
+ * @param {object} raw
526
+ * @returns {object}
527
+ */
528
+ function mapPagesDeployment(raw) {
529
+ const row = raw ?? {};
530
+ const trigger = row.deployment_trigger ?? {};
531
+ const meta = trigger.metadata ?? {};
532
+ return {
533
+ id: String(row.id ?? ''),
534
+ environment: typeof row.environment === 'string' ? row.environment : '',
535
+ url: typeof row.url === 'string' ? row.url : '',
536
+ branch: typeof meta.branch === 'string' ? meta.branch : '',
537
+ commitMessage: typeof meta.commit_message === 'string' ? meta.commit_message : '',
538
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
539
+ };
540
+ }
541
+
542
+ /**
543
+ * 列出某个 Pages 项目的部署历史。
544
+ * @param {string} token
545
+ * @param {string} accountId
546
+ * @param {string} projectName
547
+ * @returns {Promise<object[]>}
548
+ */
549
+ export async function listPagesDeployments(credential, accountId, projectName) {
550
+ const rows = await api({
551
+ method: 'GET',
552
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments?per_page=25`,
553
+ credential,
554
+ action: '读取 Pages 部署历史',
555
+ });
556
+ const list = Array.isArray(rows) ? rows : [];
557
+ return list.map(mapPagesDeployment).filter((d) => d.id !== '');
558
+ }
559
+
560
+ /**
561
+ * 删除一个 Pages 项目(需上层确认)。
562
+ * @param {string} token
563
+ * @param {string} accountId
564
+ * @param {string} projectName
565
+ * @returns {Promise<{deleted: boolean}>}
566
+ */
567
+ export async function deletePagesProject(credential, accountId, projectName) {
568
+ const response = await request({
569
+ method: 'DELETE',
570
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`,
571
+ credential,
572
+ });
573
+ if (response.status === 200 || response.status === 204) return { deleted: true };
574
+ throw cfError(response, '删除 Pages 项目');
575
+ }
576
+
577
+ /**
578
+ * 创建 Pages 项目(Direct Upload 项目名)。
579
+ * @param {string} token
580
+ * @param {string} accountId
581
+ * @param {string} name
582
+ * @param {string} productionBranch
583
+ * @returns {Promise<object>}
584
+ */
585
+ export async function createPagesProject(credential, accountId, name, productionBranch = 'main') {
586
+ const raw = await api({
587
+ method: 'POST',
588
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects`,
589
+ credential,
590
+ action: '创建 Pages 项目',
591
+ body: { name, production_branch: productionBranch },
592
+ });
593
+ return mapPagesProject(raw);
594
+ }
595
+
596
+ /* ------------------------------------------------------------------ */
597
+ /* Workers */
598
+ /* ------------------------------------------------------------------ */
599
+
600
+ /**
601
+ * 一个 Worker 脚本的精简投影。
602
+ * @param {object} raw
603
+ * @returns {object}
604
+ */
605
+ function mapWorker(raw) {
606
+ const row = raw ?? {};
607
+ return {
608
+ id: String(row.id ?? ''),
609
+ name: typeof row.name === 'string' ? row.name : String(row.id ?? ''),
610
+ modifiedOn: typeof row.modified_on === 'string' ? row.modified_on : '',
611
+ createdOn: typeof row.created_on === 'string' ? row.created_on : '',
612
+ usageModel: typeof row.usage_model === 'string' ? row.usage_model : '',
613
+ };
614
+ }
615
+
616
+ /**
617
+ * 列出账户下的 Workers 脚本。
618
+ * @param {string} token
619
+ * @param {string} accountId
620
+ * @returns {Promise<object[]>}
621
+ */
622
+ export async function listWorkers(credential, accountId) {
623
+ const rows = await api({
624
+ method: 'GET',
625
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts`,
626
+ credential,
627
+ action: '读取 Workers 列表',
628
+ });
629
+ const list = Array.isArray(rows) ? rows : [];
630
+ return list.map(mapWorker).filter((w) => w.name !== '');
631
+ }
632
+
633
+ /**
634
+ * 读取账户的 workers.dev 子域。
635
+ * @param {string} token
636
+ * @param {string} accountId
637
+ * @returns {Promise<string|null>}
638
+ */
639
+ export async function getWorkerSubdomain(credential, accountId) {
640
+ const result = await api({
641
+ method: 'GET',
642
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/subdomain`,
643
+ credential,
644
+ action: '读取 workers.dev 子域',
645
+ });
646
+ return typeof result?.subdomain === 'string' ? result.subdomain : null;
647
+ }
648
+
649
+ /**
650
+ * 删除一个 Worker(需上层确认)。
651
+ * @param {string} token
652
+ * @param {string} accountId
653
+ * @param {string} name
654
+ * @returns {Promise<{deleted: boolean}>}
655
+ */
656
+ export async function deleteWorker(credential, accountId, name) {
657
+ const response = await request({
658
+ method: 'DELETE',
659
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(name)}`,
660
+ credential,
661
+ });
662
+ if (response.status === 200 || response.status === 204) return { deleted: true };
663
+ throw cfError(response, '删除 Worker');
664
+ }
665
+
666
+ /* ------------------------------------------------------------------ */
667
+ /* Zones(域名) */
668
+ /* ------------------------------------------------------------------ */
669
+
670
+ /**
671
+ * 列出账户下的域名(zones)。
672
+ * @param {string} token
673
+ * @param {string} accountId
674
+ * @returns {Promise<{id: string, name: string, status: string}[]>}
675
+ */
676
+ export async function listZones(credential, accountId) {
677
+ const rows = await api({
678
+ method: 'GET',
679
+ url: `${apiBase()}/zones?account.id=${encodeURIComponent(accountId)}&per_page=50`,
680
+ credential,
681
+ action: '读取域名列表',
682
+ });
683
+ const list = Array.isArray(rows) ? rows : [];
684
+ return list.map((row) => ({
685
+ id: String(row?.id ?? ''),
686
+ name: typeof row?.name === 'string' ? row.name : '',
687
+ status: typeof row?.status === 'string' ? row.status : '',
688
+ })).filter((row) => row.name !== '');
689
+ }
690
+
691
+ /* ------------------------------------------------------------------ */
692
+ /* multipart 构造(Pages Direct Upload 与 Workers module upload 共用) */
693
+ /* ------------------------------------------------------------------ */
694
+
695
+ /**
696
+ * 构造一个 multipart/form-data body。
697
+ *
698
+ * @param {Array<{name: string, value: string|Buffer, contentType?: string, filename?: string}>} parts
699
+ * @param {string} boundary
700
+ * @returns {Buffer}
701
+ */
702
+ function buildMultipart(parts, boundary) {
703
+ const chunks = [];
704
+ for (const part of parts) {
705
+ chunks.push(Buffer.from(`--${boundary}\r\n`, 'utf8'));
706
+ let disposition = `form-data; name="${part.name}"`;
707
+ if (part.filename !== undefined) {
708
+ disposition += `; filename="${part.filename.replace(/["\r\n]/g, '_')}"`;
709
+ }
710
+ chunks.push(Buffer.from(`Content-Disposition: ${disposition}\r\n`, 'utf8'));
711
+ const contentType = part.contentType ?? (Buffer.isBuffer(part.value) ? 'application/octet-stream' : 'text/plain');
712
+ chunks.push(Buffer.from(`Content-Type: ${contentType}\r\n\r\n`, 'utf8'));
713
+ chunks.push(Buffer.isBuffer(part.value) ? part.value : Buffer.from(String(part.value), 'utf8'));
714
+ chunks.push(Buffer.from('\r\n', 'utf8'));
715
+ }
716
+ chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'));
717
+ return Buffer.concat(chunks);
718
+ }
719
+
720
+ /** 一个随机的 multipart boundary。 */
721
+ function randomBoundary() {
722
+ return `----DevDockBoundary${createHash('sha256').update(String(Date.now()) + String(Math.random())).digest('hex').slice(0, 16)}`;
723
+ }
724
+
725
+ /**
726
+ * 计算一段字节的 sha256 十六进制(Pages Direct Upload manifest 需要)。
727
+ * @param {Buffer} bytes
728
+ * @returns {string}
729
+ */
730
+ export function contentHash(bytes) {
731
+ return createHash('sha256').update(bytes).digest('hex');
732
+ }
733
+
734
+ /* ------------------------------------------------------------------ */
735
+ /* Pages Direct Upload:文件收集与部署 */
736
+ /* ------------------------------------------------------------------ */
737
+
738
+ /** 单文件大小上限(Pages Direct Upload:25 MiB)。 */
739
+ export const MAX_UPLOAD_FILE_BYTES = 25 * 1024 * 1024;
740
+ /** 单次部署文件数上限(保守值,低于 Pages 的 20000,避免请求体过大)。 */
741
+ export const MAX_UPLOAD_FILES = 2000;
742
+ /** 单次部署总字节数上限(避免一次请求把内存打爆)。 */
743
+ export const MAX_UPLOAD_TOTAL_BYTES = 200 * 1024 * 1024;
744
+
745
+ /** 打包到 Pages 里必须跳过的目录/文件名。 */
746
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.cache', '.wrangler']);
747
+ const SKIP_PATTERNS = [/^\.env($|\.)/, /^\.DS_Store$/, /^Thumbs\.db$/, /\.map$/, /\.log$/];
748
+
749
+ /** 常见的前端静态产物目录,按优先级。 */
750
+ export const PAGES_OUTPUT_DIRS = ['dist', 'build', 'out', '.vercel/output/static', 'public'];
751
+
752
+ /**
753
+ * 探测一个目录是否为「可部署的 Pages 静态产物目录」。
754
+ * 优先返回已存在、且含 index.html 的目录。
755
+ *
756
+ * @param {string} dir 项目根目录。
757
+ * @returns {Promise<{dir: string, type: 'pages'}|{dir: string, type: 'worker'}|null>}
758
+ */
759
+ export async function detectProjectKind(dir) {
760
+ // Worker 优先:有 wrangler 配置的目录按 Worker 处理。
761
+ for (const name of ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json']) {
762
+ try {
763
+ await readFile(path.join(dir, name), 'utf8');
764
+ return { dir, type: 'worker' };
765
+ } catch { /* 不存在则继续 */ }
766
+ }
767
+ // Pages:找含 index.html 的产物目录。
768
+ for (const rel of PAGES_OUTPUT_DIRS) {
769
+ const candidate = path.join(dir, rel);
770
+ try {
771
+ await readFile(path.join(candidate, 'index.html'), 'utf8');
772
+ return { dir: candidate, type: 'pages' };
773
+ } catch { /* 不存在 index.html */ }
774
+ }
775
+ // 项目根自身含 index.html 也算 Pages。
776
+ try {
777
+ await readFile(path.join(dir, 'index.html'), 'utf8');
778
+ return { dir, type: 'pages' };
779
+ } catch { /* 继续 */ }
780
+ return null;
781
+ }
782
+
783
+ /**
784
+ * 递归收集一个目录里要上传的文件。
785
+ *
786
+ * 应用固定的跳过规则(node_modules/.git/.env 等);任何文件超过单文件上限、
787
+ * 总数超过文件数上限、或总量超过总字节上限时返回 `exceeded`,由上层给中文提示。
788
+ *
789
+ * @param {string} dir 要上传的产物目录。
790
+ * @returns {Promise<{files: {path: string, bytes: Buffer}[],
791
+ * exceeded?: {kind: 'file'|'count'|'total', detail: string}}>}
792
+ */
793
+ export async function collectUploadFiles(dir) {
794
+ const files = [];
795
+ const stack = [''];
796
+ let totalBytes = 0;
797
+ while (stack.length > 0) {
798
+ const rel = stack.pop();
799
+ const abs = rel === '' ? dir : path.join(dir, rel);
800
+ let entries;
801
+ try {
802
+ entries = await import('node:fs/promises').then((fs) => fs.readdir(abs, { withFileTypes: true }));
803
+ } catch {
804
+ continue;
805
+ }
806
+ for (const entry of entries) {
807
+ const childRel = rel === '' ? entry.name : path.join(rel, entry.name);
808
+ if (entry.isDirectory()) {
809
+ if (SKIP_DIRS.has(entry.name)) continue;
810
+ stack.push(childRel);
811
+ continue;
812
+ }
813
+ if (!entry.isFile()) continue;
814
+ if (SKIP_PATTERNS.some((re) => re.test(entry.name))) continue;
815
+ // 统一为前向斜杠,Cloudflare 的 manifest key 用 `/` 分隔。
816
+ const key = childRel.split(path.sep).join('/');
817
+ let bytes;
818
+ try {
819
+ bytes = await readFile(path.join(dir, childRel));
820
+ } catch {
821
+ continue;
822
+ }
823
+ if (bytes.length > MAX_UPLOAD_FILE_BYTES) {
824
+ return {
825
+ files,
826
+ exceeded: { kind: 'file', detail: `${key} 超过 ${MAX_UPLOAD_FILE_BYTES / 1024 / 1024} MiB` },
827
+ };
828
+ }
829
+ totalBytes += bytes.length;
830
+ if (totalBytes > MAX_UPLOAD_TOTAL_BYTES) {
831
+ return { files, exceeded: { kind: 'total', detail: '总上传体积超过 200 MiB' } };
832
+ }
833
+ files.push({ path: key, bytes });
834
+ if (files.length > MAX_UPLOAD_FILES) {
835
+ return { files, exceeded: { kind: 'count', detail: `文件数超过 ${MAX_UPLOAD_FILES} 个` } };
836
+ }
837
+ }
838
+ }
839
+ return { files };
840
+ }
841
+
842
+ /**
843
+ * Direct Upload:把一个目录部署到 Pages 项目。
844
+ *
845
+ * @param {string} token
846
+ * @param {string} accountId
847
+ * @param {string} projectName
848
+ * @param {{directory: string, branch?: string}} options
849
+ * @returns {Promise<{id: string, url: string, environment: string}>}
850
+ */
851
+ export async function createPagesDeployment(credential, accountId, projectName, options) {
852
+ const collected = await collectUploadFiles(options.directory);
853
+ if (collected.exceeded) {
854
+ throw new GithubError('BAD_REQUEST', `无法部署:${collected.exceeded.detail}。请缩小产物或分次部署。`);
855
+ }
856
+ const manifest = collected.files.map((file) => ({
857
+ [file.path]: contentHash(file.bytes),
858
+ }));
859
+
860
+ const boundary = randomBoundary();
861
+ const parts = [
862
+ { name: 'manifest', value: JSON.stringify(manifest), contentType: 'application/json' },
863
+ ...collected.files.map((file) => ({
864
+ name: file.path,
865
+ value: file.bytes,
866
+ filename: path.basename(file.path),
867
+ contentType: contentTypeFor(file.path),
868
+ })),
869
+ ];
870
+ const body = buildMultipart(parts, boundary);
871
+
872
+ const raw = await api({
873
+ method: 'POST',
874
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}/deployments`,
875
+ credential,
876
+ timeoutMs: 120_000,
877
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
878
+ rawBody: body,
879
+ action: '部署 Pages',
880
+ });
881
+ return {
882
+ id: String(raw?.id ?? ''),
883
+ url: typeof raw?.url === 'string' ? raw.url : '',
884
+ environment: typeof raw?.environment === 'string' ? raw.environment : '',
885
+ };
886
+ }
887
+
888
+ /** 按扩展名给一个粗略的 content-type;Pages 上传用。 */
889
+ function contentTypeFor(filePath) {
890
+ const ext = path.extname(filePath).toLowerCase();
891
+ const map = {
892
+ '.html': 'text/html',
893
+ '.htm': 'text/html',
894
+ '.css': 'text/css',
895
+ '.js': 'application/javascript',
896
+ '.mjs': 'application/javascript',
897
+ '.json': 'application/json',
898
+ '.svg': 'image/svg+xml',
899
+ '.png': 'image/png',
900
+ '.jpg': 'image/jpeg',
901
+ '.jpeg': 'image/jpeg',
902
+ '.gif': 'image/gif',
903
+ '.webp': 'image/webp',
904
+ '.ico': 'image/x-icon',
905
+ '.txt': 'text/plain',
906
+ '.woff': 'font/woff',
907
+ '.woff2': 'font/woff2',
908
+ '.wasm': 'application/wasm',
909
+ };
910
+ return map[ext] ?? 'application/octet-stream';
911
+ }
912
+
913
+ /* ------------------------------------------------------------------ */
914
+ /* Workers module upload */
915
+ /* ------------------------------------------------------------------ */
916
+
917
+ /**
918
+ * 从 wrangler 配置里读 Worker 入口文件(`main` 字段)。
919
+ *
920
+ * @param {string} dir 项目根。
921
+ * @returns {Promise<string|null>} 入口相对路径。
922
+ */
923
+ export async function resolveWorkerMain(dir) {
924
+ for (const name of ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']) {
925
+ let text;
926
+ try {
927
+ text = await readFile(path.join(dir, name), 'utf8');
928
+ } catch {
929
+ continue;
930
+ }
931
+ if (name.endsWith('.toml')) {
932
+ const match = /^\s*main\s*=\s*["']?([^"'\s]+)["']?\s*$/im.exec(text);
933
+ if (match) return match[1];
934
+ } else {
935
+ // JSON/JSONC:宽松地抓 "main": "..."。
936
+ const match = /"main"\s*:\s*"([^"]+)"/.exec(text);
937
+ if (match) return match[1];
938
+ }
939
+ }
940
+ // 默认入口:src/index.js > worker.js > index.js
941
+ for (const candidate of ['src/index.js', 'worker.js', 'index.js']) {
942
+ try {
943
+ await readFile(path.join(dir, candidate), 'utf8');
944
+ return candidate;
945
+ } catch { /* 继续 */ }
946
+ }
947
+ return null;
948
+ }
949
+
950
+ /**
951
+ * 部署(或创建)一个 module Worker。
952
+ *
953
+ * @param {string} token
954
+ * @param {string} accountId
955
+ * @param {string} name Worker 名。
956
+ * @param {{mainFile: string, bytes: Buffer, compatibilityDate?: string}} options
957
+ * @returns {Promise<{name: string, url: string|null}>}
958
+ */
959
+ export async function deployWorkerModule(credential, accountId, name, options) {
960
+ const moduleName = path.basename(options.mainFile);
961
+ const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);
962
+ const metadata = JSON.stringify({
963
+ main_module: moduleName,
964
+ bindings: [],
965
+ compatibility_date: compatDate,
966
+ compatibility_flags: [],
967
+ });
968
+
969
+ const boundary = randomBoundary();
970
+ const parts = [
971
+ { name: 'metadata', value: metadata, contentType: 'application/json' },
972
+ { name: moduleName, value: options.bytes, filename: moduleName, contentType: 'application/javascript' },
973
+ ];
974
+ const body = buildMultipart(parts, boundary);
975
+
976
+ await api({
977
+ method: 'PUT',
978
+ url: `${apiBase()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(name)}`,
979
+ credential,
980
+ timeoutMs: 120_000,
981
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
982
+ rawBody: body,
983
+ action: '部署 Worker',
984
+ });
985
+ const subdomain = await getWorkerSubdomain(credential, accountId).catch(() => null);
986
+ const url = subdomain ? `https://${name}.${subdomain}.workers.dev` : null;
987
+ return { name, url };
988
+ }
989
+
990
+ /* ------------------------------------------------------------------ */
991
+ /* 概览(设置页项目概览卡的数据源) */
992
+ /* ------------------------------------------------------------------ */
993
+
994
+ /**
995
+ * 一次并行取 pages / workers / zones 的计数与少量条目,供设置页概览卡。
996
+ *
997
+ * 任一子项失败**不**让整体失败:该子项返回空数组 + `warning`,与 repoManage
998
+ * 的「部分失败是常态」一致。
999
+ *
1000
+ * @param {string} token
1001
+ * @param {string} accountId
1002
+ * @returns {Promise<{pages: {count: number, items: object[]}, workers: {count: number, items: object[]},
1003
+ * zones: {count: number, items: object[]}, warnings: string[]}>}
1004
+ */
1005
+ export async function cfOverview(credential, accountId) {
1006
+ const warnings = [];
1007
+ const settle = async (label, fn) => {
1008
+ try {
1009
+ const items = await fn();
1010
+ return { count: items.length, items: items.slice(0, 6) };
1011
+ } catch (error) {
1012
+ warnings.push(`${label}:${error?.message ?? error}`);
1013
+ return { count: 0, items: [] };
1014
+ }
1015
+ };
1016
+ const [pages, workers, zones] = await Promise.all([
1017
+ settle('Pages 项目', () => listPagesProjects(credential, accountId)),
1018
+ settle('Workers', () => listWorkers(credential, accountId)),
1019
+ settle('域名', () => listZones(credential, accountId)),
1020
+ ]);
1021
+ return { pages, workers, zones, warnings };
1022
+ }
1023
+
1024
+ /** dash.cloudflare.com 上的资源页深度链接。 */
1025
+ export function dashUrl(accountId, resource) {
1026
+ return `${DASH_ORIGIN}/${encodeURIComponent(accountId)}/${resource}`;
1027
+ }