@huoye/app-ship 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,4167 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AdHocUploader: () => AdHocUploader,
34
+ AppleJWTGenerator: () => AppleJWTGenerator,
35
+ AppleStoreUploader: () => AppleStoreUploader,
36
+ ConfigValidator: () => ConfigValidator,
37
+ DEFAULT_RETRY_CONFIG: () => DEFAULT_RETRY_CONFIG,
38
+ EnvValidator: () => EnvValidator,
39
+ ErrorCategory: () => ErrorCategory,
40
+ HarmonyUploader: () => HarmonyUploader,
41
+ HuaweiUploader: () => HuaweiUploader,
42
+ OppoUploader: () => OppoUploader,
43
+ PgyerUploader: () => PgyerUploader,
44
+ RetryStrategy: () => RetryStrategy,
45
+ TencentUploader: () => TencentUploader,
46
+ TestFlightUploader: () => TestFlightUploader,
47
+ UploadManager: () => UploadManager,
48
+ VivoUploader: () => VivoUploader,
49
+ XiaomiUploader: () => XiaomiUploader,
50
+ createUploadManager: () => createUploadManager,
51
+ createUploadRetryStrategy: () => createUploadRetryStrategy,
52
+ parsePackageInfo: () => parsePackageInfo
53
+ });
54
+ module.exports = __toCommonJS(index_exports);
55
+
56
+ // src/utils/logger.ts
57
+ var import_chalk = __toESM(require("chalk"), 1);
58
+ var ConsoleLogger = class {
59
+ info(message) {
60
+ console.log(import_chalk.default.blue("\u2139\uFE0F " + message));
61
+ }
62
+ success(message) {
63
+ console.log(import_chalk.default.green("\u2705 " + message));
64
+ }
65
+ warn(message) {
66
+ console.log(import_chalk.default.yellow("\u26A0\uFE0F " + message));
67
+ }
68
+ error(message) {
69
+ console.log(import_chalk.default.red("\u274C " + message));
70
+ }
71
+ title(message) {
72
+ console.log(import_chalk.default.bold.cyan("\n" + message + "\n"));
73
+ }
74
+ newLine() {
75
+ console.log("");
76
+ }
77
+ };
78
+ var logger = new ConsoleLogger();
79
+
80
+ // src/validators/env_validator.ts
81
+ var EnvValidator = class {
82
+ /**
83
+ * 验证环境变量
84
+ * @param requiredVars 必需的环境变量列表
85
+ */
86
+ static validate(requiredVars) {
87
+ const missing = requiredVars.filter((v) => !process.env[v]);
88
+ if (missing.length > 0) {
89
+ logger.error(`Missing environment variables: ${missing.join(", ")}`);
90
+ return false;
91
+ }
92
+ return true;
93
+ }
94
+ };
95
+
96
+ // src/validators/config_validator.ts
97
+ var import_fs_extra = __toESM(require("fs-extra"), 1);
98
+ var import_js_yaml = __toESM(require("js-yaml"), 1);
99
+ var ConfigValidator = class {
100
+ /**
101
+ * 加载并验证配置文件
102
+ * @param filePath 配置文件路径
103
+ */
104
+ static loadAndValidate(filePath) {
105
+ if (!import_fs_extra.default.existsSync(filePath)) {
106
+ logger.error(`Config file not found: ${filePath}`);
107
+ return null;
108
+ }
109
+ let content = import_fs_extra.default.readFileSync(filePath, "utf8");
110
+ const envRegex = /\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
111
+ const matches = [...content.matchAll(envRegex)];
112
+ const requiredEnvs = Array.from(new Set(matches.map((m) => m[1])));
113
+ if (!EnvValidator.validate(requiredEnvs)) {
114
+ return null;
115
+ }
116
+ content = content.replace(envRegex, (_, varName) => process.env[varName] || "");
117
+ try {
118
+ const config = import_js_yaml.default.load(content);
119
+ if (!this.validateSchema(config)) {
120
+ return null;
121
+ }
122
+ return config;
123
+ } catch (e) {
124
+ logger.error(`Failed to parse YAML: ${e.message}`);
125
+ return null;
126
+ }
127
+ }
128
+ /**
129
+ * 验证配置 Schema
130
+ * @param config 配置对象
131
+ */
132
+ static validateSchema(config) {
133
+ if (config.publish?.app_store?.enable) {
134
+ const auth = config.publish.app_store.auth;
135
+ if (!auth?.apiKeyId || !auth?.apiIssuerId) {
136
+ logger.error("App Store enabled but missing auth info (apiKeyId, apiIssuerId)");
137
+ return false;
138
+ }
139
+ }
140
+ if (config.publish?.huawei?.enable) {
141
+ const auth = config.publish.huawei.auth;
142
+ if (!auth?.clientId || !auth?.clientSecret) {
143
+ logger.error("Huawei enabled but missing auth info (clientId, clientSecret)");
144
+ return false;
145
+ }
146
+ }
147
+ if (config.publish?.xiaomi?.enable) {
148
+ const auth = config.publish.xiaomi.auth;
149
+ if (!auth?.userName || !auth?.privateKey) {
150
+ logger.error("Xiaomi enabled but missing auth info (userName, privateKey)");
151
+ return false;
152
+ }
153
+ }
154
+ if (config.publish?.oppo?.enable) {
155
+ const auth = config.publish.oppo.auth;
156
+ if (!auth?.clientId || !auth?.clientSecret) {
157
+ logger.error("OPPO enabled but missing auth info (clientId, clientSecret)");
158
+ return false;
159
+ }
160
+ }
161
+ if (config.publish?.vivo?.enable) {
162
+ const auth = config.publish.vivo.auth;
163
+ if (!auth?.accessKey || !auth?.accessSecret) {
164
+ logger.error("vivo enabled but missing auth info (accessKey, accessSecret)");
165
+ return false;
166
+ }
167
+ }
168
+ if (config.publish?.tencent?.enable) {
169
+ const auth = config.publish.tencent.auth;
170
+ if (!auth?.userId || !auth?.appId || !auth?.accessSecret) {
171
+ logger.error("Tencent enabled but missing auth info (userId, appId, accessSecret)");
172
+ return false;
173
+ }
174
+ }
175
+ if (config.publish?.harmony?.enable) {
176
+ const auth = config.publish.harmony.auth;
177
+ if (!auth?.clientId || !auth?.clientSecret) {
178
+ logger.error("Harmony enabled but missing auth info (clientId, clientSecret)");
179
+ return false;
180
+ }
181
+ }
182
+ return true;
183
+ }
184
+ };
185
+
186
+ // src/adapters/pgyer_uploader.ts
187
+ var import_fs_extra3 = __toESM(require("fs-extra"), 1);
188
+ var import_axios = __toESM(require("axios"), 1);
189
+ var import_form_data = __toESM(require("form-data"), 1);
190
+
191
+ // src/utils/retry-strategy.ts
192
+ var ErrorCategory = /* @__PURE__ */ ((ErrorCategory2) => {
193
+ ErrorCategory2["NETWORK_ERROR"] = "NETWORK_ERROR";
194
+ ErrorCategory2["TEMPORARY_ERROR"] = "TEMPORARY_ERROR";
195
+ ErrorCategory2["SERVER_ERROR"] = "SERVER_ERROR";
196
+ ErrorCategory2["AUTH_ERROR"] = "AUTH_ERROR";
197
+ ErrorCategory2["CLIENT_ERROR"] = "CLIENT_ERROR";
198
+ ErrorCategory2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
199
+ return ErrorCategory2;
200
+ })(ErrorCategory || {});
201
+ var RetryStrategy = class {
202
+ config;
203
+ constructor(config = {}) {
204
+ this.config = {
205
+ maxRetries: config.maxRetries ?? 3,
206
+ initialDelayMs: config.initialDelayMs ?? 1e3,
207
+ backoffMultiplier: config.backoffMultiplier ?? 2,
208
+ maxDelayMs: config.maxDelayMs ?? 3e4
209
+ };
210
+ }
211
+ /**
212
+ * 根据错误类型判断是否应该重试
213
+ */
214
+ shouldRetry(error, retryCount) {
215
+ if (retryCount >= this.config.maxRetries) {
216
+ return false;
217
+ }
218
+ const category = this.classifyError(error);
219
+ return this.isRetryableCategory(category);
220
+ }
221
+ /**
222
+ * 对错误进行分类
223
+ */
224
+ classifyError(error) {
225
+ const message = error.message.toLowerCase();
226
+ const errorStr = JSON.stringify(error).toLowerCase();
227
+ if (message.includes("econnrefused") || message.includes("enotfound") || message.includes("etimedout") || message.includes("network") || message.includes("socket hang up") || message.includes("socket") || message.includes("econnreset") || message.includes("epipe") || message.includes("hang up")) {
228
+ return "NETWORK_ERROR" /* NETWORK_ERROR */;
229
+ }
230
+ if (message.includes("401") || message.includes("403") || message.includes("unauthorized") || message.includes("forbidden") || message.includes("invalid") || message.includes("token")) {
231
+ return "AUTH_ERROR" /* AUTH_ERROR */;
232
+ }
233
+ if (message.includes("500") || message.includes("502") || message.includes("503") || message.includes("504") || message.includes("server error") || message.includes("\u670D\u52A1\u5668\u7AEF\u5F02\u5E38")) {
234
+ return "SERVER_ERROR" /* SERVER_ERROR */;
235
+ }
236
+ if (message.includes("400") || message.includes("404") || message.includes("bad request") || message.includes("not found")) {
237
+ return "CLIENT_ERROR" /* CLIENT_ERROR */;
238
+ }
239
+ if (message.includes("timeout") || message.includes("rate limit") || message.includes("too many") || message.includes("429")) {
240
+ return "TEMPORARY_ERROR" /* TEMPORARY_ERROR */;
241
+ }
242
+ return "UNKNOWN_ERROR" /* UNKNOWN_ERROR */;
243
+ }
244
+ /**
245
+ * 判断错误类别是否可重试
246
+ */
247
+ isRetryableCategory(category) {
248
+ const retryableCategories = [
249
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
250
+ "TEMPORARY_ERROR" /* TEMPORARY_ERROR */,
251
+ "SERVER_ERROR" /* SERVER_ERROR */
252
+ ];
253
+ return retryableCategories.includes(category);
254
+ }
255
+ /**
256
+ * 计算延迟时间(使用指数退避策略)
257
+ */
258
+ calculateDelay(retryCount) {
259
+ const exponentialDelay = this.config.initialDelayMs * Math.pow(this.config.backoffMultiplier, retryCount);
260
+ const jitter = exponentialDelay * (Math.random() * 0.2);
261
+ const delay = Math.min(exponentialDelay + jitter, this.config.maxDelayMs);
262
+ return Math.round(delay);
263
+ }
264
+ /**
265
+ * 等待指定时间
266
+ */
267
+ async sleep(ms) {
268
+ return new Promise((resolve) => setTimeout(resolve, ms));
269
+ }
270
+ /**
271
+ * 执行带重试的异步函数
272
+ */
273
+ async execute(fn, operationName = "Operation") {
274
+ let lastError;
275
+ let attempt = 0;
276
+ while (attempt <= this.config.maxRetries) {
277
+ attempt++;
278
+ try {
279
+ logger.info(`${operationName} (Attempt ${attempt}/${this.config.maxRetries + 1})`);
280
+ const result = await fn();
281
+ if (attempt > 1) {
282
+ logger.success(`${operationName} succeeded after ${attempt} attempts`);
283
+ }
284
+ return {
285
+ success: true,
286
+ data: result,
287
+ totalAttempts: attempt
288
+ };
289
+ } catch (error) {
290
+ lastError = error;
291
+ const errorMessage = error.message || String(error);
292
+ const category = this.classifyError(error);
293
+ logger.warn(`${operationName} failed (Attempt ${attempt}): ${errorMessage} [${category}]`);
294
+ if (!this.shouldRetry(error, attempt)) {
295
+ logger.error(`${operationName} failed with non-retryable error: ${errorMessage}`);
296
+ return {
297
+ success: false,
298
+ error,
299
+ totalAttempts: attempt,
300
+ lastError: errorMessage
301
+ };
302
+ }
303
+ if (attempt <= this.config.maxRetries) {
304
+ const delayMs = this.calculateDelay(attempt - 1);
305
+ logger.info(
306
+ `Retrying ${operationName} after ${delayMs}ms (${this.config.maxRetries - attempt + 1} retries left)...`
307
+ );
308
+ await this.sleep(delayMs);
309
+ }
310
+ }
311
+ }
312
+ return {
313
+ success: false,
314
+ error: lastError || new Error(`${operationName} failed after all retries`),
315
+ totalAttempts: attempt,
316
+ lastError: lastError?.message
317
+ };
318
+ }
319
+ };
320
+ var DEFAULT_RETRY_CONFIG = {
321
+ maxRetries: 3,
322
+ initialDelayMs: 1e3,
323
+ backoffMultiplier: 2,
324
+ maxDelayMs: 3e4
325
+ };
326
+ function createUploadRetryStrategy(config) {
327
+ return new RetryStrategy({
328
+ ...DEFAULT_RETRY_CONFIG,
329
+ ...config
330
+ });
331
+ }
332
+
333
+ // src/utils/upload-manager.ts
334
+ var import_path2 = __toESM(require("path"), 1);
335
+
336
+ // src/utils/package-parser.ts
337
+ var import_path = __toESM(require("path"), 1);
338
+ var import_fs = __toESM(require("fs"), 1);
339
+ var import_crypto = __toESM(require("crypto"), 1);
340
+ async function parsePackageInfo(filePath, options) {
341
+ const ext = import_path.default.extname(filePath).toLowerCase();
342
+ try {
343
+ switch (ext) {
344
+ case ".apk":
345
+ return await parseApk(filePath, options);
346
+ case ".ipa":
347
+ return await parseIpa(filePath);
348
+ case ".hap":
349
+ return await parseHap(filePath);
350
+ default:
351
+ logger.warn(`[PackageParser] \u4E0D\u652F\u6301\u7684\u6587\u4EF6\u683C\u5F0F: ${ext}`);
352
+ return null;
353
+ }
354
+ } catch (error) {
355
+ logger.warn(`[PackageParser] \u89E3\u6790\u5931\u8D25: ${error.message}`);
356
+ return null;
357
+ }
358
+ }
359
+ function exec(cmd, args, timeoutMs = 15e3) {
360
+ const { execFile } = require("child_process");
361
+ return new Promise((resolve, reject) => {
362
+ execFile(
363
+ cmd,
364
+ args,
365
+ { timeout: timeoutMs, maxBuffer: 1024 * 1024 },
366
+ (error, stdout, stderr) => {
367
+ if (error) {
368
+ reject(error);
369
+ } else {
370
+ resolve(stdout);
371
+ }
372
+ }
373
+ );
374
+ });
375
+ }
376
+ async function getAaptPath(options) {
377
+ if (options?.androidSdkPath && import_fs.default.existsSync(options.androidSdkPath)) {
378
+ const buildToolsDir = import_path.default.join(options.androidSdkPath, "build-tools");
379
+ if (import_fs.default.existsSync(buildToolsDir)) {
380
+ const tool = findInBuildTools(buildToolsDir);
381
+ if (tool) return tool;
382
+ }
383
+ }
384
+ if (await commandExists("aapt2")) return "aapt2";
385
+ if (await commandExists("aapt")) return "aapt";
386
+ const sdkRoot = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || import_path.default.join(process.env.HOME || "", "Library/Android/sdk");
387
+ if (sdkRoot && import_fs.default.existsSync(sdkRoot)) {
388
+ const buildToolsDir = import_path.default.join(sdkRoot, "build-tools");
389
+ if (import_fs.default.existsSync(buildToolsDir)) {
390
+ const tool = findInBuildTools(buildToolsDir);
391
+ if (tool) return tool;
392
+ }
393
+ }
394
+ return null;
395
+ }
396
+ function findInBuildTools(buildToolsDir) {
397
+ const versions = import_fs.default.readdirSync(buildToolsDir).filter((dir) => import_fs.default.lstatSync(import_path.default.join(buildToolsDir, dir)).isDirectory()).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
398
+ for (const version of versions) {
399
+ const aapt2 = import_path.default.join(buildToolsDir, version, "aapt2");
400
+ if (import_fs.default.existsSync(aapt2)) return aapt2;
401
+ const aapt = import_path.default.join(buildToolsDir, version, "aapt");
402
+ if (import_fs.default.existsSync(aapt)) return aapt;
403
+ }
404
+ return null;
405
+ }
406
+ async function commandExists(cmd) {
407
+ try {
408
+ await exec("which", [cmd], 3e3);
409
+ return true;
410
+ } catch {
411
+ return false;
412
+ }
413
+ }
414
+ async function parseApk(filePath, options) {
415
+ const tool = await getAaptPath(options);
416
+ if (!tool) {
417
+ logger.warn(
418
+ "[PackageParser] \u26A0\uFE0F aapt2/aapt \u4E0D\u53EF\u7528 (\u8BF7\u68C0\u67E5 ANDROID_HOME \u6216\u52A0\u5165 PATH)\uFF0C\u65E0\u6CD5\u89E3\u6790 APK \u7248\u672C\u4FE1\u606F"
419
+ );
420
+ return null;
421
+ }
422
+ const output = await exec(tool, ["dump", "badging", filePath]);
423
+ const packageMatch = output.match(
424
+ /package:\s+name='([^']*)'.*?versionCode='([^']*)'.*?versionName='([^']*)'/
425
+ );
426
+ if (!packageMatch) {
427
+ logger.warn("[PackageParser] APK badging \u8F93\u51FA\u4E2D\u672A\u627E\u5230\u7248\u672C\u4FE1\u606F");
428
+ return null;
429
+ }
430
+ const info = {
431
+ packageName: packageMatch[1] || void 0,
432
+ versionCode: packageMatch[2] || void 0,
433
+ versionName: packageMatch[3] || void 0
434
+ };
435
+ const nativeCodeMatch = output.match(/native-code:\s+((?:'[^']*'\s*)*)/);
436
+ if (nativeCodeMatch) {
437
+ info.nativeCode = nativeCodeMatch[1].split(/\s+/).filter((s) => s.startsWith("'") && s.endsWith("'")).map((s) => s.slice(1, -1));
438
+ }
439
+ try {
440
+ const fileBuffer = import_fs.default.readFileSync(filePath);
441
+ info.md5 = import_crypto.default.createHash("md5").update(fileBuffer).digest("hex").toLowerCase();
442
+ } catch (e) {
443
+ logger.warn(`[PackageParser] \u8BA1\u7B97 MD5 \u5931\u8D25: ${e.message}`);
444
+ }
445
+ logger.info(
446
+ `[PackageParser] APK: ${info.packageName} v${info.versionName}+${info.versionCode} arch:${info.nativeCode?.join(",") || "none"}`
447
+ );
448
+ return info;
449
+ }
450
+ async function parseIpa(filePath) {
451
+ if (!await commandExists("plutil")) {
452
+ logger.warn("[PackageParser] plutil \u4E0D\u53EF\u7528\uFF08\u975E macOS\uFF1F\uFF09\uFF0C\u65E0\u6CD5\u89E3\u6790 IPA");
453
+ return null;
454
+ }
455
+ const listOutput = await exec("unzip", ["-Z1", filePath]);
456
+ const plistPath = listOutput.split("\n").find((line) => /^Payload\/[^/]+\.app\/Info\.plist$/.test(line.trim()));
457
+ if (!plistPath) {
458
+ logger.warn("[PackageParser] IPA \u4E2D\u672A\u627E\u5230 Info.plist");
459
+ return null;
460
+ }
461
+ const plistData = await exec("unzip", ["-p", filePath, plistPath.trim()]);
462
+ const jsonStr = await new Promise((resolve, reject) => {
463
+ const child = require("child_process").spawn("plutil", ["-convert", "json", "-o", "-", "-"], {
464
+ timeout: 1e4
465
+ });
466
+ let stdout = "";
467
+ let stderr = "";
468
+ child.stdout.on("data", (d) => stdout += d.toString());
469
+ child.stderr.on("data", (d) => stderr += d.toString());
470
+ child.on("close", (code) => {
471
+ if (code === 0) resolve(stdout);
472
+ else reject(new Error(`plutil \u5931\u8D25: ${stderr}`));
473
+ });
474
+ child.stdin.write(plistData);
475
+ child.stdin.end();
476
+ });
477
+ const plist = JSON.parse(jsonStr);
478
+ const info = {
479
+ versionName: plist.CFBundleShortVersionString || void 0,
480
+ versionCode: plist.CFBundleVersion || void 0,
481
+ packageName: plist.CFBundleIdentifier || void 0
482
+ };
483
+ logger.info(`[PackageParser] IPA: ${info.packageName} v${info.versionName}+${info.versionCode}`);
484
+ return info;
485
+ }
486
+ async function parseHap(filePath) {
487
+ let jsonStr = null;
488
+ try {
489
+ jsonStr = await exec("unzip", ["-p", filePath, "module.json"]);
490
+ } catch {
491
+ try {
492
+ jsonStr = await exec("unzip", ["-p", filePath, "config.json"]);
493
+ } catch {
494
+ logger.warn("[PackageParser] HAP \u4E2D\u672A\u627E\u5230 module.json \u6216 config.json");
495
+ return null;
496
+ }
497
+ }
498
+ const config = JSON.parse(jsonStr);
499
+ const app = config.app || {};
500
+ const info = {
501
+ versionName: app.versionName || app.version?.name || void 0,
502
+ versionCode: String(app.versionCode ?? app.version?.code ?? ""),
503
+ packageName: app.bundleName || void 0
504
+ };
505
+ if (!info.versionCode) info.versionCode = void 0;
506
+ logger.info(`[PackageParser] HAP: ${info.packageName} v${info.versionName}+${info.versionCode}`);
507
+ return info;
508
+ }
509
+
510
+ // src/utils/upload-manager.ts
511
+ var UploadManager = class {
512
+ uploaders;
513
+ config;
514
+ constructor(config = {}) {
515
+ this.uploaders = /* @__PURE__ */ new Map();
516
+ this.config = {
517
+ maxConcurrent: config.maxConcurrent ?? 3,
518
+ continueOnError: config.continueOnError ?? true,
519
+ verbose: config.verbose ?? false,
520
+ cancellationToken: config.cancellationToken
521
+ };
522
+ this.registerUploader("pgyer", new PgyerUploader());
523
+ this.registerUploader("huawei", new HuaweiUploader());
524
+ this.registerUploader("xiaomi", new XiaomiUploader());
525
+ this.registerUploader("app_store", new AppleStoreUploader());
526
+ this.registerUploader("testflight", new TestFlightUploader());
527
+ this.registerUploader("adhoc", new AdHocUploader());
528
+ this.registerUploader("harmony", new HarmonyUploader());
529
+ this.registerUploader("oppo", new OppoUploader());
530
+ this.registerUploader("vivo", new VivoUploader());
531
+ this.registerUploader("tencent", new TencentUploader());
532
+ }
533
+ /**
534
+ * 注册上传器
535
+ */
536
+ registerUploader(platform, uploader) {
537
+ this.uploaders.set(platform, uploader);
538
+ }
539
+ /**
540
+ * 获取启用的平台列表(根据配置)
541
+ */
542
+ getEnabledPlatforms(config) {
543
+ const enabled = [];
544
+ if (config?.publish?.pgyer?.enable) enabled.push("pgyer");
545
+ if (config?.publish?.huawei?.enable) enabled.push("huawei");
546
+ if (config?.publish?.xiaomi?.enable) enabled.push("xiaomi");
547
+ if (config?.publish?.oppo?.enable) enabled.push("oppo");
548
+ if (config?.publish?.vivo?.enable) enabled.push("vivo");
549
+ if (config?.publish?.tencent?.enable) enabled.push("tencent");
550
+ if (config?.publish?.app_store?.enable) {
551
+ const mode = config.publish.app_store.mode || "app_store";
552
+ enabled.push(mode);
553
+ }
554
+ return enabled;
555
+ }
556
+ /**
557
+ * 获取可用的平台列表
558
+ */
559
+ getAvailablePlatforms() {
560
+ return Array.from(this.uploaders.keys());
561
+ }
562
+ /**
563
+ * 执行并行上传(支持多文件智能分发)
564
+ */
565
+ async uploadToMultiplePlatforms(filePaths, config, metadata, targetPlatforms) {
566
+ const startTime = Date.now();
567
+ let platforms = targetPlatforms && targetPlatforms.length > 0 ? targetPlatforms : this.getEnabledPlatforms(config);
568
+ if (platforms.length === 0) {
569
+ logger.warn("No platforms enabled for upload");
570
+ return {
571
+ totalUploads: 0,
572
+ successCount: 0,
573
+ failureCount: 0,
574
+ successPlatforms: [],
575
+ failurePlatforms: [],
576
+ results: [],
577
+ totalDurationMs: 0,
578
+ summary: "No platforms configured for upload"
579
+ };
580
+ }
581
+ logger.info(
582
+ `Starting parallel uploads to ${platforms.length} platform(s): ${platforms.join(", ")}`
583
+ );
584
+ const validPlatforms = platforms.filter((platform) => {
585
+ const uploader = this.uploaders.get(platform);
586
+ if (!uploader) {
587
+ logger.warn(`Platform '${platform}' is not supported`);
588
+ return false;
589
+ }
590
+ if (!uploader.validateConfig(config)) {
591
+ logger.warn(`Configuration for '${platform}' is invalid`);
592
+ return false;
593
+ }
594
+ return true;
595
+ });
596
+ if (validPlatforms.length === 0) {
597
+ logger.error("No valid platforms to upload to");
598
+ return {
599
+ totalUploads: platforms.length,
600
+ successCount: 0,
601
+ failureCount: platforms.length,
602
+ successPlatforms: [],
603
+ failurePlatforms: platforms,
604
+ results: [],
605
+ totalDurationMs: Date.now() - startTime,
606
+ summary: "All platforms failed configuration validation"
607
+ };
608
+ }
609
+ const files = Array.isArray(filePaths) ? filePaths : [filePaths];
610
+ logger.info(`Processing ${files.length} file(s) for ${validPlatforms.length} platform(s)`);
611
+ const uploadPromises = validPlatforms.map((platform) => {
612
+ const uploader = this.uploaders.get(platform);
613
+ const targetFile = files.find((f) => uploader.canHandle(f));
614
+ if (!targetFile) {
615
+ logger.warn(`[${platform}] No compatible file found in provided files`);
616
+ return Promise.resolve({
617
+ platform,
618
+ success: false,
619
+ message: `No compatible file found for ${platform}`
620
+ });
621
+ }
622
+ logger.info(`[${platform}] Matched file: ${import_path2.default.basename(targetFile)}`);
623
+ return this.uploadToPlatform(platform, targetFile, config, metadata);
624
+ });
625
+ const results = await Promise.all(uploadPromises);
626
+ const report = this.aggregateResults(results, validPlatforms.length, startTime);
627
+ this.printReport(report);
628
+ return report;
629
+ }
630
+ /**
631
+ * 上传到单个平台
632
+ */
633
+ async uploadToPlatform(platform, filePath, config, metadata) {
634
+ if (this.config.cancellationToken?.isCancelled) {
635
+ logger.warn(`[${platform.toUpperCase()}] Upload skipped due to cancellation`);
636
+ return {
637
+ platform,
638
+ success: false,
639
+ message: "Upload cancelled by user"
640
+ };
641
+ }
642
+ const uploader = this.uploaders.get(platform);
643
+ if (!uploader) {
644
+ return {
645
+ platform,
646
+ success: false,
647
+ message: `Platform '${platform}' is not supported`
648
+ };
649
+ }
650
+ try {
651
+ if (this.config.verbose) {
652
+ logger.info(`[${platform.toUpperCase()}] Starting upload...`);
653
+ }
654
+ const pkgInfo = await parsePackageInfo(filePath, {
655
+ androidSdkPath: metadata.globalSettings?.androidSdkPath
656
+ });
657
+ if (pkgInfo) {
658
+ if (pkgInfo.versionName) {
659
+ metadata.version = pkgInfo.versionName;
660
+ }
661
+ if (pkgInfo.versionCode) {
662
+ metadata.buildNumber = pkgInfo.versionCode;
663
+ }
664
+ if (pkgInfo.packageName) {
665
+ ;
666
+ metadata.packageName = pkgInfo.packageName;
667
+ }
668
+ logger.info(
669
+ `[${platform.toUpperCase()}] \u5DF2\u6821\u51C6\u7248\u672C\u4FE1\u606F: v${metadata.version}+${metadata.buildNumber}`
670
+ );
671
+ }
672
+ const result = await uploader.upload(filePath, config, metadata);
673
+ return result;
674
+ } catch (error) {
675
+ const errorMessage = error.message || String(error);
676
+ logger.error(`[${platform.toUpperCase()}] Upload error: ${errorMessage}`);
677
+ return {
678
+ platform,
679
+ success: false,
680
+ message: errorMessage,
681
+ error
682
+ };
683
+ }
684
+ }
685
+ /**
686
+ * 聚合上传结果
687
+ */
688
+ aggregateResults(results, totalPlatforms, startTime) {
689
+ const successResults = results.filter((r) => r.success);
690
+ const failureResults = results.filter((r) => !r.success);
691
+ const successPlatforms = successResults.map((r) => r.platform || "unknown");
692
+ const failurePlatforms = failureResults.map((r) => r.platform || "unknown");
693
+ const totalDurationMs = Date.now() - startTime;
694
+ let summary = "";
695
+ if (successResults.length === totalPlatforms) {
696
+ summary = `\u2705 All ${totalPlatforms} platforms uploaded successfully!`;
697
+ } else if (failureResults.length === totalPlatforms) {
698
+ summary = `\u274C Upload failed on all ${totalPlatforms} platforms`;
699
+ } else {
700
+ summary = `\u26A0\uFE0F Partial success: ${successResults.length} succeeded, ${failureResults.length} failed`;
701
+ }
702
+ return {
703
+ totalUploads: totalPlatforms,
704
+ successCount: successResults.length,
705
+ failureCount: failureResults.length,
706
+ successPlatforms,
707
+ failurePlatforms,
708
+ results,
709
+ totalDurationMs,
710
+ summary
711
+ };
712
+ }
713
+ /**
714
+ * 输出上传报告
715
+ */
716
+ printReport(report) {
717
+ logger.info("");
718
+ logger.info("\u2550".repeat(60));
719
+ logger.info("\u{1F4CA} Upload Report");
720
+ logger.info("\u2550".repeat(60));
721
+ logger.info(`Total Platforms: ${report.totalUploads}`);
722
+ logger.info(`\u2705 Success: ${report.successCount}`);
723
+ logger.info(`\u274C Failure: ${report.failureCount}`);
724
+ if (report.successPlatforms.length > 0) {
725
+ logger.info(`Successful: ${report.successPlatforms.join(", ")}`);
726
+ }
727
+ if (report.failurePlatforms.length > 0) {
728
+ logger.info(`Failed: ${report.failurePlatforms.join(", ")}`);
729
+ }
730
+ logger.info(`Total Duration: ${this.formatDuration(report.totalDurationMs)}`);
731
+ logger.info("");
732
+ logger.info(report.summary);
733
+ logger.info("\u2550".repeat(60));
734
+ logger.info("");
735
+ logger.info("\u{1F4CB} Detailed Results:");
736
+ report.results.forEach((result) => {
737
+ if (result.success) {
738
+ if (this.config.verbose) {
739
+ logger.success(`[${result.platform}] \u2705 ${result.message}`);
740
+ if (result.url) {
741
+ logger.info(` Download: ${result.url}`);
742
+ }
743
+ }
744
+ } else {
745
+ logger.error(`[${result.platform}] \u274C ${result.message}`);
746
+ if (result.error && result.error.stack && this.config.verbose) {
747
+ logger.error(result.error.stack);
748
+ }
749
+ }
750
+ });
751
+ logger.info("");
752
+ }
753
+ /**
754
+ * 格式化持续时间
755
+ */
756
+ formatDuration(ms) {
757
+ if (ms < 1e3) {
758
+ return `${ms}ms`;
759
+ }
760
+ if (ms < 6e4) {
761
+ return `${(ms / 1e3).toFixed(1)}s`;
762
+ }
763
+ return `${(ms / 6e4).toFixed(1)}m`;
764
+ }
765
+ /**
766
+ * 获取可重试的失败平台
767
+ */
768
+ getRetryablePlatforms(report) {
769
+ return report.failurePlatforms;
770
+ }
771
+ /**
772
+ * 重试失败的平台
773
+ */
774
+ async retryFailedPlatforms(failedPlatforms, filePath, config, metadata) {
775
+ if (failedPlatforms.length === 0) {
776
+ logger.info("No platforms to retry");
777
+ return {
778
+ totalUploads: 0,
779
+ successCount: 0,
780
+ failureCount: 0,
781
+ successPlatforms: [],
782
+ failurePlatforms: [],
783
+ results: [],
784
+ totalDurationMs: 0,
785
+ summary: "No platforms to retry"
786
+ };
787
+ }
788
+ logger.info(`Retrying ${failedPlatforms.length} failed platform(s)...`);
789
+ return this.uploadToMultiplePlatforms(filePath, config, metadata, failedPlatforms);
790
+ }
791
+ };
792
+ function createUploadManager(config) {
793
+ return new UploadManager(config);
794
+ }
795
+
796
+ // src/utils/apple-jwt-generator.ts
797
+ var import_crypto2 = __toESM(require("crypto"), 1);
798
+ var import_fs_extra2 = __toESM(require("fs-extra"), 1);
799
+ var AppleJWTGenerator = class _AppleJWTGenerator {
800
+ issuerId;
801
+ keyId;
802
+ privateKey;
803
+ constructor(issuerId, keyId, privateKey) {
804
+ this.issuerId = issuerId;
805
+ this.keyId = keyId;
806
+ this.privateKey = privateKey;
807
+ }
808
+ /**
809
+ * 从文件路径加载私钥内容
810
+ */
811
+ static async fromFile(issuerId, keyId, privateKeyPath) {
812
+ try {
813
+ const privateKey = await import_fs_extra2.default.readFile(privateKeyPath, "utf-8");
814
+ return new _AppleJWTGenerator(issuerId, keyId, privateKey);
815
+ } catch (error) {
816
+ throw new Error(`Failed to load Apple private key from ${privateKeyPath}: ${error.message}`);
817
+ }
818
+ }
819
+ /**
820
+ * 从内容字符串创建生成器
821
+ */
822
+ static fromContent(issuerId, keyId, privateKeyContent) {
823
+ return new _AppleJWTGenerator(issuerId, keyId, privateKeyContent);
824
+ }
825
+ /**
826
+ * 生成 JWT 令牌
827
+ * @returns Base64URL 编码的 JWT 字符串
828
+ */
829
+ generate() {
830
+ try {
831
+ const header = this.createHeader();
832
+ const headerEncoded = this.base64urlEncode(JSON.stringify(header));
833
+ const payload = this.createPayload();
834
+ const payloadEncoded = this.base64urlEncode(JSON.stringify(payload));
835
+ const signatureInput = `${headerEncoded}.${payloadEncoded}`;
836
+ const signature = this.sign(signatureInput);
837
+ return `${signatureInput}.${signature}`;
838
+ } catch (error) {
839
+ logger.error(`Failed to generate Apple JWT: ${error.message}`);
840
+ throw error;
841
+ }
842
+ }
843
+ /**
844
+ * 创建 JWT Header
845
+ */
846
+ createHeader() {
847
+ return {
848
+ alg: "ES256",
849
+ kid: this.keyId,
850
+ typ: "JWT"
851
+ };
852
+ }
853
+ /**
854
+ * 创建 JWT Payload
855
+ * 有效期: 20 分钟(1200 秒)
856
+ */
857
+ createPayload() {
858
+ const now = Math.floor(Date.now() / 1e3);
859
+ return {
860
+ iss: this.issuerId,
861
+ aud: "appstoreconnect-v1",
862
+ exp: now + 1200,
863
+ // 20 minutes
864
+ iat: now
865
+ };
866
+ }
867
+ /**
868
+ * 使用 ES256 算法签名
869
+ * ES256 = ECDSA with SHA-256
870
+ */
871
+ sign(data) {
872
+ const sign = import_crypto2.default.createSign("SHA256");
873
+ sign.update(data);
874
+ sign.end();
875
+ const signature = sign.sign({
876
+ key: this.privateKey,
877
+ format: "pem"
878
+ });
879
+ const { r, s } = this.parseDERSignature(signature);
880
+ const combined = Buffer.concat([r, s]);
881
+ return this.base64urlEncode(combined);
882
+ }
883
+ /**
884
+ * 解析 DER 格式的签名并提取 r 和 s
885
+ */
886
+ parseDERSignature(derSignature) {
887
+ let offset = 0;
888
+ offset += 2;
889
+ if (derSignature[offset] === 129 || derSignature[offset] === 130) {
890
+ offset += 1;
891
+ } else {
892
+ offset += 1;
893
+ }
894
+ offset += 1;
895
+ const rLength = derSignature[offset];
896
+ offset += 1;
897
+ let r = derSignature.subarray(offset, offset + rLength);
898
+ offset += rLength;
899
+ if (r[0] === 0 && r.length > 32) {
900
+ r = r.subarray(1);
901
+ }
902
+ r = this.padBuffer(r, 32);
903
+ offset += 1;
904
+ const sLength = derSignature[offset];
905
+ offset += 1;
906
+ let s = derSignature.subarray(offset, offset + sLength);
907
+ if (s[0] === 0 && s.length > 32) {
908
+ s = s.subarray(1);
909
+ }
910
+ s = this.padBuffer(s, 32);
911
+ return { r: Buffer.from(r), s: Buffer.from(s) };
912
+ }
913
+ /**
914
+ * 将 Buffer 填充或截断到指定长度
915
+ */
916
+ padBuffer(buf, length) {
917
+ if (buf.length === length) return buf;
918
+ if (buf.length > length) return buf.subarray(buf.length - length);
919
+ const padded = Buffer.alloc(length);
920
+ buf.copy(padded, length - buf.length);
921
+ return padded;
922
+ }
923
+ /**
924
+ * Base64URL 编码 (RFC 4648)
925
+ */
926
+ base64urlEncode(data) {
927
+ const base64 = Buffer.from(data).toString("base64");
928
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
929
+ }
930
+ };
931
+
932
+ // src/adapters/pgyer_uploader.ts
933
+ var PgyerUploader = class _PgyerUploader {
934
+ name = "Pgyer";
935
+ static UPLOAD_API = "https://www.pgyer.com/apiv2/app/upload";
936
+ /**
937
+ * 验证配置
938
+ * @param config 配置对象
939
+ */
940
+ validateConfig(config) {
941
+ if (!config?.publish?.pgyer?.enable) {
942
+ return false;
943
+ }
944
+ if (!config.publish.pgyer.apiKey) {
945
+ logger.error("Pgyer apiKey is missing in config");
946
+ return false;
947
+ }
948
+ return true;
949
+ }
950
+ /**
951
+ * 判断是否支持该文件
952
+ * @param filePath 文件路径
953
+ */
954
+ canHandle(filePath) {
955
+ const ext = filePath.split(".").pop()?.toLowerCase();
956
+ return ext === "apk" || ext === "ipa" || ext === "aab";
957
+ }
958
+ /**
959
+ * 上传文件到蒲公英
960
+ * @param filePath 文件路径
961
+ * @param config 配置
962
+ * @param metadata 元数据
963
+ */
964
+ async upload(filePath, config, metadata) {
965
+ const pgyerConfig = config.publish?.pgyer;
966
+ const apiKey = pgyerConfig?.apiKey;
967
+ const desc = metadata.changelog || pgyerConfig?.description || "";
968
+ const retryConfig = config.retry;
969
+ if (!import_fs_extra3.default.existsSync(filePath)) {
970
+ return {
971
+ platform: "pgyer",
972
+ success: false,
973
+ message: `File not found: ${filePath}`
974
+ };
975
+ }
976
+ logger.info(`Uploading to Pgyer...`);
977
+ logger.info(`File: ${filePath}`);
978
+ logger.info(`Changelog: ${desc.replace(/\n/g, " ")}`);
979
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
980
+ const result = await retryStrategy.execute(
981
+ () => this.performUpload(filePath, apiKey, desc),
982
+ "Pgyer upload"
983
+ );
984
+ if (result.success) {
985
+ const pgyerData = result.data;
986
+ return {
987
+ platform: "pgyer",
988
+ success: true,
989
+ message: "Upload success",
990
+ url: pgyerData.fullUrl,
991
+ link: pgyerData.fullUrl,
992
+ qrCode: pgyerData.qrCodeUrl,
993
+ data: pgyerData,
994
+ consoleUrl: "https://www.pgyer.com/my"
995
+ };
996
+ } else {
997
+ const lastError = result.lastError;
998
+ const errorMsg = lastError instanceof Error ? lastError.message : String(lastError || "Upload failed");
999
+ return {
1000
+ platform: "pgyer",
1001
+ success: false,
1002
+ message: errorMsg,
1003
+ // ✅ 必填且为字符串
1004
+ error: result.error
1005
+ };
1006
+ }
1007
+ }
1008
+ /**
1009
+ * 执行实际上传操作
1010
+ * @param filePath 文件路径
1011
+ * @param apiKey API Key
1012
+ * @param desc 描述
1013
+ */
1014
+ async performUpload(filePath, apiKey, desc) {
1015
+ const form = new import_form_data.default();
1016
+ form.append("_api_key", apiKey);
1017
+ form.append("buildUpdateDescription", desc);
1018
+ form.append("file", import_fs_extra3.default.createReadStream(filePath));
1019
+ const response = await import_axios.default.post(_PgyerUploader.UPLOAD_API, form, {
1020
+ headers: {
1021
+ ...form.getHeaders()
1022
+ },
1023
+ maxContentLength: Infinity,
1024
+ maxBodyLength: Infinity
1025
+ });
1026
+ const data = response.data;
1027
+ if (data.code !== 0) {
1028
+ logger.error(`Pgyer API Error: ${data.message}`);
1029
+ throw new Error(`Pgyer API Error: ${data.message}`);
1030
+ }
1031
+ const shortcutUrl = data.data.buildShortcutUrl;
1032
+ let qrCodeUrl = data.data.buildQRCodeURL;
1033
+ const fullUrl = `https://www.pgyer.com/${shortcutUrl}`;
1034
+ if (qrCodeUrl && qrCodeUrl.startsWith("//")) {
1035
+ qrCodeUrl = `https:${qrCodeUrl}`;
1036
+ } else if (qrCodeUrl && !qrCodeUrl.startsWith("http")) {
1037
+ }
1038
+ logger.success(`Upload to Pgyer success!`);
1039
+ logger.info(`Download URL: ${fullUrl}`);
1040
+ return {
1041
+ fullUrl,
1042
+ qrCodeUrl,
1043
+ shortcutUrl
1044
+ };
1045
+ }
1046
+ };
1047
+
1048
+ // src/adapters/huawei_uploader.ts
1049
+ var import_fs_extra4 = __toESM(require("fs-extra"), 1);
1050
+ var import_path3 = __toESM(require("path"), 1);
1051
+ var import_util = require("util");
1052
+ var import_axios2 = __toESM(require("axios"), 1);
1053
+ var import_form_data2 = __toESM(require("form-data"), 1);
1054
+ var HUAWEI_SUPPORTED_SUFFIXES = {
1055
+ image: ["jpg", "jpeg", "png", "bmp"],
1056
+ video: ["mp4", "mov"],
1057
+ package: ["apk", "aab", "rpk"]
1058
+ };
1059
+ var HuaweiUploader = class _HuaweiUploader {
1060
+ name = "Huawei";
1061
+ // 华为上传器默认 API 基础地址
1062
+ static DEFAULT_API_BASE = "https://connect-api.cloud.huawei.com";
1063
+ // 华为上传器获取 Token 路径
1064
+ static TOKEN_PATH = "/api/oauth2/v1/token";
1065
+ // 华为上传器发布 API 根路径
1066
+ static PUBLISH_API_PATH = "/api/publish/v2";
1067
+ /** 获取 API 基础地址 */
1068
+ getApiBase(config) {
1069
+ return config?.publish?.huawei?.apiBaseUrl || _HuaweiUploader.DEFAULT_API_BASE;
1070
+ }
1071
+ /** 获取 Token URL */
1072
+ getTokenUrl(config) {
1073
+ return `${this.getApiBase(config)}${_HuaweiUploader.TOKEN_PATH}`;
1074
+ }
1075
+ /** 获取 Publish API 根路径 */
1076
+ getApiRoot(config) {
1077
+ return `${this.getApiBase(config)}${_HuaweiUploader.PUBLISH_API_PATH}`;
1078
+ }
1079
+ /** 创建 API 请求头(消除 7 处重复) */
1080
+ headers(ctx) {
1081
+ return {
1082
+ Authorization: `Bearer ${ctx.token}`,
1083
+ client_id: ctx.clientId
1084
+ };
1085
+ }
1086
+ /** 检查 API 响应(消除 6 处重复) */
1087
+ checkResponse(res, operation) {
1088
+ const code = res.data.ret?.code ?? res.data.code;
1089
+ if (code !== 0) {
1090
+ throw new Error(`${operation} failed: ${res.data.ret?.msg || res.data.msg}`);
1091
+ }
1092
+ return res.data;
1093
+ }
1094
+ /**
1095
+ * 验证配置
1096
+ * @param config 配置对象
1097
+ * @returns 是否有效
1098
+ */
1099
+ validateConfig(config) {
1100
+ if (!config?.publish?.huawei?.enable) return false;
1101
+ const h = config.publish.huawei;
1102
+ if (!h.auth?.clientId || !h.auth?.clientSecret || !h.appId) {
1103
+ logger.error("Huawei config missing: clientId, clientSecret, or appId");
1104
+ return false;
1105
+ }
1106
+ return true;
1107
+ }
1108
+ /**
1109
+ * 判断是否支持该文件
1110
+ * @param filePath 文件路径
1111
+ * @returns 是否支持
1112
+ */
1113
+ canHandle(filePath) {
1114
+ const ext = filePath.split(".").pop()?.toLowerCase();
1115
+ return ext === "apk" || ext === "aab";
1116
+ }
1117
+ /**
1118
+ * 执行上传
1119
+ * @param filePath 文件路径
1120
+ * @param config 配置
1121
+ * @param metadata 元数据
1122
+ */
1123
+ async upload(filePath, config, metadata) {
1124
+ const hwConfig = config.publish.huawei;
1125
+ const clientId = hwConfig.auth.clientId;
1126
+ const clientSecret = hwConfig.auth.clientSecret;
1127
+ const appId = hwConfig.appId;
1128
+ const releaseType = hwConfig.releaseType || "draft";
1129
+ const suffix = import_path3.default.extname(filePath).substring(1);
1130
+ const retryConfig = config.retry;
1131
+ const tokenUrl = this.getTokenUrl(config);
1132
+ const publishApiRoot = this.getApiRoot(config);
1133
+ logger.info("Starting Huawei AppGallery upload...");
1134
+ try {
1135
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
1136
+ logger.info("Authenticating...");
1137
+ const tokenResult = await retryStrategy.execute(
1138
+ () => this.getAccessToken(tokenUrl, clientId, clientSecret),
1139
+ "Huawei authentication"
1140
+ );
1141
+ if (!tokenResult.success || !tokenResult.data) {
1142
+ throw tokenResult.error || new Error("Failed to get access token");
1143
+ }
1144
+ const ctx = {
1145
+ apiRoot: publishApiRoot,
1146
+ token: tokenResult.data,
1147
+ clientId,
1148
+ appId
1149
+ };
1150
+ logger.info("Requesting upload URL...");
1151
+ const uploadInfoResult = await retryStrategy.execute(
1152
+ () => this.getUploadUrl(ctx, suffix),
1153
+ "Huawei get upload URL"
1154
+ );
1155
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
1156
+ throw uploadInfoResult.error || new Error("Failed to get upload URL");
1157
+ }
1158
+ const uploadInfo = uploadInfoResult.data;
1159
+ logger.info("Uploading file (this may take a while)...");
1160
+ const uploadFileResult = await retryStrategy.execute(
1161
+ () => this.uploadFile(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
1162
+ "Huawei file upload"
1163
+ );
1164
+ if (!uploadFileResult.success || !uploadFileResult.data) {
1165
+ throw uploadFileResult.error || new Error("File upload failed");
1166
+ }
1167
+ const fileDestUrl = uploadFileResult.data.fileDestUrl;
1168
+ logger.info("Linking file to app...");
1169
+ const updateInfoResult = await retryStrategy.execute(
1170
+ () => this.updateAppFileInfo(ctx, fileDestUrl, filePath),
1171
+ "Huawei update file info"
1172
+ );
1173
+ if (!updateInfoResult.success) {
1174
+ throw updateInfoResult.error || new Error("Failed to update file info");
1175
+ }
1176
+ if (metadata.changelog) {
1177
+ try {
1178
+ logger.info("Updating release notes...");
1179
+ await retryStrategy.execute(
1180
+ () => this.updateReleaseNotes(ctx, metadata.changelog, metadata.version),
1181
+ "Huawei update release notes"
1182
+ );
1183
+ } catch (error) {
1184
+ logger.warn(`Failed to update release notes: ${error.message}. Continuing...`);
1185
+ }
1186
+ }
1187
+ const assets = hwConfig.assets;
1188
+ if (assets) {
1189
+ await this.uploadStoreAssets(ctx, assets, retryStrategy);
1190
+ }
1191
+ if (releaseType === "submit") {
1192
+ try {
1193
+ logger.info("Submitting app for review...");
1194
+ const submitResult = await retryStrategy.execute(
1195
+ () => this.submitForReview(ctx, metadata.version),
1196
+ "Huawei submit for review"
1197
+ );
1198
+ if (!submitResult.success) {
1199
+ throw submitResult.error || new Error("Failed to submit for review");
1200
+ }
1201
+ logger.success("Huawei upload successful and submitted for review!");
1202
+ return {
1203
+ platform: "huawei",
1204
+ success: true,
1205
+ message: "Upload and review submission successful",
1206
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1207
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1208
+ };
1209
+ } catch (error) {
1210
+ logger.warn(
1211
+ `Failed to submit for review: ${error.message}. App uploaded but not submitted.`
1212
+ );
1213
+ return {
1214
+ platform: "huawei",
1215
+ success: true,
1216
+ message: "Upload successful but review submission failed. Please submit manually.",
1217
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1218
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1219
+ };
1220
+ }
1221
+ }
1222
+ logger.success("Huawei upload successful (Draft status).");
1223
+ return {
1224
+ platform: "huawei",
1225
+ success: true,
1226
+ message: "Upload success (Draft)",
1227
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1228
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1229
+ };
1230
+ } catch (error) {
1231
+ logger.error(`Huawei upload failed: ${error.message}`);
1232
+ const safeError = {
1233
+ message: error.message,
1234
+ name: error.name,
1235
+ code: error.code,
1236
+ status: error.response?.status
1237
+ };
1238
+ if (error.response?.data) {
1239
+ safeError.responseData = error.response.data;
1240
+ logger.info(`Error Data: ${JSON.stringify(error.response.data)}`);
1241
+ }
1242
+ return {
1243
+ platform: "huawei",
1244
+ success: false,
1245
+ message: error.message,
1246
+ error: safeError
1247
+ };
1248
+ }
1249
+ }
1250
+ /**
1251
+ * 查询审核状态
1252
+ * @param clientId 客户端 ID
1253
+ * @param clientSecret 客户端密钥
1254
+ * @param appId 应用 ID
1255
+ * @param apiBaseUrl API 基础地址(可选)
1256
+ */
1257
+ async queryReviewStatus(clientId, clientSecret, appId, apiBaseUrl) {
1258
+ const baseUrl = apiBaseUrl || _HuaweiUploader.DEFAULT_API_BASE;
1259
+ const tokenUrl = `${baseUrl}${_HuaweiUploader.TOKEN_PATH}`;
1260
+ const apiRoot = `${baseUrl}${_HuaweiUploader.PUBLISH_API_PATH}`;
1261
+ try {
1262
+ logger.info("Querying review status...");
1263
+ const token = await this.getAccessToken(tokenUrl, clientId, clientSecret);
1264
+ const ctx = { apiRoot, token, clientId, appId };
1265
+ const res = await import_axios2.default.get(`${apiRoot}/app-information`, {
1266
+ params: { appId },
1267
+ headers: this.headers(ctx)
1268
+ });
1269
+ this.checkResponse(res, "Query review status");
1270
+ const status = res.data.data?.app?.auditStatus || "unknown";
1271
+ logger.info(`Current review status: ${status}`);
1272
+ return status;
1273
+ } catch (error) {
1274
+ logger.error(`Failed to query review status: ${error.message}`);
1275
+ throw error;
1276
+ }
1277
+ }
1278
+ /**
1279
+ * 获取 Access Token
1280
+ * @param tokenUrl Token URL
1281
+ * @param clientId 客户端 ID
1282
+ * @param clientSecret 客户端密钥
1283
+ */
1284
+ async getAccessToken(tokenUrl, clientId, clientSecret) {
1285
+ const data = {
1286
+ client_id: clientId,
1287
+ client_secret: clientSecret,
1288
+ grant_type: "client_credentials"
1289
+ };
1290
+ logger.info(`[Huawei Auth] Requesting token with clientId: ${clientId}`);
1291
+ try {
1292
+ const res = await import_axios2.default.post(tokenUrl, data, {
1293
+ headers: {
1294
+ "Content-Type": "application/json"
1295
+ }
1296
+ });
1297
+ logger.info(
1298
+ `[Huawei Auth] Token response received, keys: ${Object.keys(res.data).join(", ")}`
1299
+ );
1300
+ const token = res.data.access_token || res.data.token;
1301
+ if (!token) {
1302
+ logger.error(
1303
+ `[Huawei Auth] No token in response. Full response: ${JSON.stringify(res.data)}`
1304
+ );
1305
+ throw new Error(`Invalid token response: ${JSON.stringify(res.data)}`);
1306
+ }
1307
+ logger.info(`[Huawei Auth] Token obtained successfully`);
1308
+ return token;
1309
+ } catch (error) {
1310
+ logger.error(`[Huawei Auth] Token request failed: ${error.message}`);
1311
+ if (error.response?.data) {
1312
+ logger.error(`[Huawei Auth] Error response: ${JSON.stringify(error.response.data)}`);
1313
+ }
1314
+ throw error;
1315
+ }
1316
+ }
1317
+ /** 获取上传 URL */
1318
+ async getUploadUrl(ctx, suffix) {
1319
+ logger.info(`[Huawei Upload] Requesting upload URL for appId: ${ctx.appId}, suffix: ${suffix}`);
1320
+ const res = await import_axios2.default.get(`${ctx.apiRoot}/upload-url`, {
1321
+ params: { appId: ctx.appId, suffix },
1322
+ headers: this.headers(ctx)
1323
+ });
1324
+ this.checkResponse(res, "Get upload URL");
1325
+ return {
1326
+ uploadUrl: res.data.uploadUrl,
1327
+ authCode: res.data.authCode
1328
+ };
1329
+ }
1330
+ /** 通用文件上传(FormData 方式,无需 API 认证头) */
1331
+ async executeUploadRequest(uploadUrl, authCode, filePath) {
1332
+ const fileName = import_path3.default.basename(filePath);
1333
+ const fileSize = import_fs_extra4.default.statSync(filePath).size;
1334
+ const form = new import_form_data2.default();
1335
+ form.append("file", import_fs_extra4.default.createReadStream(filePath), {
1336
+ filename: fileName,
1337
+ contentType: "application/octet-stream",
1338
+ knownLength: fileSize
1339
+ });
1340
+ form.append("authCode", authCode);
1341
+ form.append("fileCount", "1");
1342
+ form.append("parseType", "1");
1343
+ const length = await (0, import_util.promisify)(form.getLength).bind(form)();
1344
+ logger.info(
1345
+ `[Huawei Upload] Uploading: ${fileName} (${(fileSize / 1024 / 1024).toFixed(2)} MB)`
1346
+ );
1347
+ const res = await import_axios2.default.post(uploadUrl, form, {
1348
+ headers: { ...form.getHeaders(), "Content-Length": length },
1349
+ maxContentLength: Infinity,
1350
+ maxBodyLength: Infinity
1351
+ });
1352
+ if (res.data.result?.resultCode !== "0") {
1353
+ throw new Error(`File upload failed: ${JSON.stringify(res.data.result)}`);
1354
+ }
1355
+ const fileInfoList = res.data.result?.UploadFileRsp?.fileInfoList || res.data.result?.uploadFileRsp?.fileInfoList || [];
1356
+ if (fileInfoList.length === 0) {
1357
+ throw new Error("No file info returned from upload");
1358
+ }
1359
+ return fileInfoList.map((f) => ({
1360
+ fileName: f.name || fileName,
1361
+ fileDestUrl: f.fileDestUlr || f.fileDestUrl || authCode
1362
+ }));
1363
+ }
1364
+ /** 上传文件 (APK/AAB) */
1365
+ async uploadFile(uploadUrl, authCode, filePath) {
1366
+ const files = await this.executeUploadRequest(uploadUrl, authCode, filePath);
1367
+ if (files.length > 0 && files[0].fileDestUrl) {
1368
+ logger.info(`[Huawei Upload] App package uploaded, fileDestUrl: ${files[0].fileDestUrl}`);
1369
+ return { fileDestUrl: files[0].fileDestUrl };
1370
+ }
1371
+ throw new Error("Upload succeeded but fileDestUrl not found in response");
1372
+ }
1373
+ /** 更新应用文件信息 */
1374
+ async updateAppFileInfo(ctx, fileDestUrl, filePath) {
1375
+ const fileName = import_path3.default.basename(filePath);
1376
+ const fileType = import_path3.default.extname(filePath).toLowerCase() === ".aab" ? 7 : 5;
1377
+ const res = await import_axios2.default.put(
1378
+ `${ctx.apiRoot}/app-file-info`,
1379
+ {
1380
+ fileType,
1381
+ files: [{ fileName, fileDestUrl }]
1382
+ },
1383
+ {
1384
+ params: { appId: ctx.appId },
1385
+ headers: this.headers(ctx)
1386
+ }
1387
+ );
1388
+ this.checkResponse(res, "Update file info");
1389
+ }
1390
+ /** 更新发布说明(支持多语言) */
1391
+ async updateReleaseNotes(ctx, changelog, version) {
1392
+ const notes = typeof changelog === "string" ? { zh_CN: changelog, en_US: changelog } : changelog;
1393
+ const body = {
1394
+ defaultLanguage: "zh_CN",
1395
+ languages: [
1396
+ {
1397
+ lang: "zh_CN",
1398
+ appName: "",
1399
+ appDesc: "",
1400
+ newFeatures: notes["zh_CN"] || ""
1401
+ },
1402
+ {
1403
+ lang: "en_US",
1404
+ appName: "",
1405
+ appDesc: "",
1406
+ newFeatures: notes["en_US"] || ""
1407
+ }
1408
+ ]
1409
+ };
1410
+ const res = await import_axios2.default.put(`${ctx.apiRoot}/app-info`, body, {
1411
+ params: { appId: ctx.appId },
1412
+ headers: this.headers(ctx)
1413
+ });
1414
+ this.checkResponse(res, "Update release notes");
1415
+ logger.info("Release notes updated successfully");
1416
+ }
1417
+ /** 提交审核 */
1418
+ async submitForReview(ctx, version) {
1419
+ const appInfo = await this.getAppInfo(ctx);
1420
+ if (!appInfo?.releaseId) {
1421
+ throw new Error("Could not get release ID for submission");
1422
+ }
1423
+ try {
1424
+ const res = await import_axios2.default.post(
1425
+ `${ctx.apiRoot}/app-submit`,
1426
+ {
1427
+ releaseId: appInfo.releaseId,
1428
+ auditDesc: `Version ${version}`
1429
+ },
1430
+ {
1431
+ params: { appId: ctx.appId },
1432
+ headers: this.headers(ctx)
1433
+ }
1434
+ );
1435
+ this.checkResponse(res, "Submit for review");
1436
+ logger.success("App submitted for review successfully");
1437
+ } catch (error) {
1438
+ if (error.response?.status === 404) {
1439
+ logger.warn("Huawei review submission API not yet available. Please submit manually.");
1440
+ } else {
1441
+ throw error;
1442
+ }
1443
+ }
1444
+ }
1445
+ /** 获取应用信息 */
1446
+ async getAppInfo(ctx) {
1447
+ const res = await import_axios2.default.get(`${ctx.apiRoot}/app-information`, {
1448
+ params: { appId: ctx.appId },
1449
+ headers: this.headers(ctx)
1450
+ });
1451
+ this.checkResponse(res, "Get app info");
1452
+ return res.data.data;
1453
+ }
1454
+ /** 上传商店素材(图标、截图、视频) */
1455
+ async uploadStoreAssets(ctx, assets, retryStrategy) {
1456
+ const tasks = [];
1457
+ if (assets.icon) {
1458
+ tasks.push({
1459
+ label: "icon",
1460
+ files: [assets.icon],
1461
+ type: 0 /* ICON */
1462
+ });
1463
+ }
1464
+ if (assets.screenshots?.length) {
1465
+ tasks.push({
1466
+ label: `${assets.screenshots.length} screenshot(s)`,
1467
+ files: assets.screenshots,
1468
+ type: 1 /* SCREENSHOT */
1469
+ });
1470
+ }
1471
+ if (assets.video) {
1472
+ tasks.push({
1473
+ label: "preview video",
1474
+ files: [assets.video],
1475
+ type: 2 /* VIDEO */
1476
+ });
1477
+ }
1478
+ for (const task of tasks) {
1479
+ try {
1480
+ logger.info(`Uploading ${task.label}...`);
1481
+ await this.uploadAssetFiles(ctx, task.files, task.type, retryStrategy);
1482
+ logger.success(`${task.label} uploaded successfully`);
1483
+ } catch (error) {
1484
+ logger.warn(`Failed to upload ${task.label}: ${error.message}`);
1485
+ }
1486
+ }
1487
+ }
1488
+ /** 批量上传素材文件 */
1489
+ async uploadAssetFiles(ctx, filePaths, fileType, retryStrategy) {
1490
+ const allFileInfos = [];
1491
+ for (const filePath of filePaths) {
1492
+ if (!await import_fs_extra4.default.pathExists(filePath)) {
1493
+ logger.warn(`Asset file not found, skipping: ${filePath}`);
1494
+ continue;
1495
+ }
1496
+ const suffix = import_path3.default.extname(filePath).substring(1).toLowerCase();
1497
+ if (!HUAWEI_SUPPORTED_SUFFIXES.image.includes(suffix)) {
1498
+ logger.warn(`Unsupported file type ${suffix}, skipping: ${filePath}`);
1499
+ continue;
1500
+ }
1501
+ const uploadInfoResult = await retryStrategy.execute(
1502
+ () => this.getUploadUrl(ctx, suffix),
1503
+ "Huawei get upload URL for asset"
1504
+ );
1505
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
1506
+ logger.warn(`Failed to get upload URL for: ${filePath}`);
1507
+ continue;
1508
+ }
1509
+ const uploadInfo = uploadInfoResult.data;
1510
+ const uploadResult = await retryStrategy.execute(
1511
+ () => this.executeUploadRequest(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
1512
+ "Huawei upload asset"
1513
+ );
1514
+ if (!uploadResult.success || !uploadResult.data) {
1515
+ logger.warn(`Failed to upload: ${filePath}`);
1516
+ continue;
1517
+ }
1518
+ allFileInfos.push(...uploadResult.data);
1519
+ }
1520
+ if (allFileInfos.length === 0) {
1521
+ throw new Error("No assets were uploaded successfully");
1522
+ }
1523
+ await retryStrategy.execute(
1524
+ () => this.updateAssetFileInfo(ctx, allFileInfos, fileType),
1525
+ "Huawei update asset file info"
1526
+ );
1527
+ }
1528
+ /** 更新素材文件信息(关联到应用) */
1529
+ async updateAssetFileInfo(ctx, files, fileType) {
1530
+ const res = await import_axios2.default.put(
1531
+ `${ctx.apiRoot}/app-file-info`,
1532
+ {
1533
+ fileType,
1534
+ lang: "zh-CN",
1535
+ files: files.map((f) => ({
1536
+ fileName: f.fileName,
1537
+ fileDestUrl: f.fileDestUrl
1538
+ }))
1539
+ },
1540
+ {
1541
+ params: { appId: ctx.appId },
1542
+ headers: this.headers(ctx)
1543
+ }
1544
+ );
1545
+ this.checkResponse(res, "Update asset file info");
1546
+ }
1547
+ };
1548
+
1549
+ // src/adapters/xiaomi_uploader.ts
1550
+ var import_fs_extra5 = __toESM(require("fs-extra"), 1);
1551
+ var import_axios3 = __toESM(require("axios"), 1);
1552
+ var import_form_data3 = __toESM(require("form-data"), 1);
1553
+ var import_crypto3 = __toESM(require("crypto"), 1);
1554
+ var XiaomiUploader = class _XiaomiUploader {
1555
+ name = "Xiaomi";
1556
+ static API_BASE = "https://api.developer.xiaomi.com/devupload";
1557
+ static PUSH_API = `${_XiaomiUploader.API_BASE}/dev/push`;
1558
+ static QUERY_API = `${_XiaomiUploader.API_BASE}/dev/query`;
1559
+ static CATEGORY_API = `${_XiaomiUploader.API_BASE}/dev/category`;
1560
+ /**
1561
+ * RSA 公钥分段加密 (PKCS1Padding)
1562
+ *
1563
+ * 小米要求: 使用平台分配的 RSA 公钥加密 SIG JSON,
1564
+ * 输出小写十六进制字符串。RSA 1024-bit 密钥单次最多加密 117 字节,
1565
+ * 超出需分段加密后拼接。
1566
+ */
1567
+ rsaEncryptWithPublicKey(data, publicKey) {
1568
+ const buffer = Buffer.from(data, "utf-8");
1569
+ const maxBlock = 117;
1570
+ const chunks = [];
1571
+ for (let offset = 0; offset < buffer.length; offset += maxBlock) {
1572
+ const chunk = buffer.subarray(offset, offset + maxBlock);
1573
+ const encrypted = import_crypto3.default.publicEncrypt(
1574
+ {
1575
+ key: publicKey,
1576
+ padding: import_crypto3.default.constants.RSA_PKCS1_PADDING
1577
+ },
1578
+ chunk
1579
+ );
1580
+ chunks.push(encrypted);
1581
+ }
1582
+ return Buffer.concat(chunks).toString("hex");
1583
+ }
1584
+ /**
1585
+ * 从 X.509 证书或 PEM 公钥中提取可用于加密的公钥
1586
+ * 优先使用 crypto.X509Certificate,因为它能同时处理 DER 和 PEM 格式的证书
1587
+ */
1588
+ extractPublicKey(buffer) {
1589
+ try {
1590
+ const x509 = new import_crypto3.default.X509Certificate(buffer);
1591
+ return x509.publicKey;
1592
+ } catch (e) {
1593
+ try {
1594
+ const content = buffer.toString();
1595
+ if (content.includes("-----BEGIN")) {
1596
+ return import_crypto3.default.createPublicKey(content);
1597
+ }
1598
+ return import_crypto3.default.createPublicKey(this.normalizePEM(content));
1599
+ } catch (e2) {
1600
+ throw new Error(`\u65E0\u6CD5\u63D0\u53D6\u516C\u94A5: ${e instanceof Error ? e.message : "\u672A\u77E5\u9519\u8BEF"}`);
1601
+ }
1602
+ }
1603
+ }
1604
+ /**
1605
+ * 计算文件 MD5 (小写十六进制)
1606
+ */
1607
+ async calculateFileMD5(filePath) {
1608
+ return new Promise((resolve, reject) => {
1609
+ const hash = import_crypto3.default.createHash("md5");
1610
+ const stream = import_fs_extra5.default.createReadStream(filePath);
1611
+ stream.on("data", (data) => hash.update(data));
1612
+ stream.on("end", () => resolve(hash.digest("hex")));
1613
+ stream.on("error", reject);
1614
+ });
1615
+ }
1616
+ /**
1617
+ * 计算字符串 MD5 (小写十六进制)
1618
+ */
1619
+ calculateStringMD5(str) {
1620
+ return import_crypto3.default.createHash("md5").update(str, "utf-8").digest("hex");
1621
+ }
1622
+ /**
1623
+ * 构建 RequestData JSON
1624
+ */
1625
+ buildRequestData(params) {
1626
+ const { userName, packageName, appName, updateDesc, uploadType } = params;
1627
+ const synchroType = uploadType === "new" ? 0 : 1;
1628
+ const appInfo = {
1629
+ appName,
1630
+ packageName
1631
+ };
1632
+ if (uploadType === "new") {
1633
+ if (params.category != null) appInfo.category = params.category;
1634
+ if (params.keyWords) appInfo.keyWords = params.keyWords;
1635
+ if (params.desc) appInfo.desc = params.desc;
1636
+ if (params.brief) appInfo.brief = params.brief;
1637
+ if (params.privacyUrl) appInfo.privacyUrl = params.privacyUrl;
1638
+ }
1639
+ if (updateDesc) {
1640
+ appInfo.updateDesc = updateDesc;
1641
+ }
1642
+ const requestDataObj = {
1643
+ userName,
1644
+ appInfo,
1645
+ synchroType
1646
+ };
1647
+ const result = JSON.stringify(requestDataObj);
1648
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - RequestData \u5B57\u7B26\u4E32: ${result}`);
1649
+ return result;
1650
+ }
1651
+ /**
1652
+ * 生成只包含 RequestData 的 SIG(用于查询接口)
1653
+ */
1654
+ generateQuerySIG(requestDataMD5, privateKey, publicKey) {
1655
+ const sigObj = {
1656
+ sig: [{ name: "RequestData", hash: requestDataMD5 }],
1657
+ password: privateKey.trim()
1658
+ };
1659
+ const sigJson = JSON.stringify(sigObj);
1660
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - Query SIG \u5F85\u52A0\u5BC6\u5B57\u7B26\u4E32: ${sigJson}`);
1661
+ const encrypted = this.rsaEncryptWithPublicKey(sigJson, publicKey);
1662
+ logger.info(
1663
+ `[XIAOMI] \u8C03\u8BD5 - Query SIG \u52A0\u5BC6\u7ED3\u679C (Hex, \u524D 20\u4F4D): ${encrypted.substring(0, 20)}...`
1664
+ );
1665
+ return encrypted;
1666
+ }
1667
+ /**
1668
+ * 生成包含 RequestData + apk 的加密 SIG 字符串(用于上传接口)
1669
+ */
1670
+ generateUploadSIG(requestDataMD5, apkFileMD5, privateKey, publicKey, extraFiles) {
1671
+ const sigItems = [
1672
+ { name: "RequestData", hash: requestDataMD5 },
1673
+ { name: "apk", hash: apkFileMD5 }
1674
+ ];
1675
+ if (extraFiles) {
1676
+ sigItems.push(...extraFiles);
1677
+ }
1678
+ const sigObj = {
1679
+ sig: sigItems,
1680
+ password: privateKey.trim()
1681
+ };
1682
+ const sigJson = JSON.stringify(sigObj);
1683
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - Upload SIG \u5F85\u52A0\u5BC6\u5B57\u7B26\u4E32: ${sigJson}`);
1684
+ const encrypted = this.rsaEncryptWithPublicKey(sigJson, publicKey);
1685
+ logger.info(
1686
+ `[XIAOMI] \u8C03\u8BD5 - Upload SIG \u52A0\u5BC6\u7ED3\u679C (Hex, \u524D 20\u4F4D): ${encrypted.substring(0, 20)}...`
1687
+ );
1688
+ return encrypted;
1689
+ }
1690
+ /**
1691
+ * 将用户输入的公钥字符串规范化为 PEM 格式
1692
+ */
1693
+ normalizePEM(publicKey) {
1694
+ if (publicKey.includes("-----BEGIN")) {
1695
+ return publicKey.trim();
1696
+ }
1697
+ const clean = publicKey.replace(/[\s\n\r]+/g, "");
1698
+ const lines = clean.match(/.{1,64}/g) || [];
1699
+ return `-----BEGIN PUBLIC KEY-----
1700
+ ${lines.join("\n")}
1701
+ -----END PUBLIC KEY-----`;
1702
+ }
1703
+ validateConfig(config) {
1704
+ if (!config?.publish?.xiaomi?.enable) return false;
1705
+ const x = config.publish.xiaomi;
1706
+ if (!x.auth?.userName || !x.auth?.privateKey) {
1707
+ logger.error("Xiaomi config missing: userName or privateKey");
1708
+ return false;
1709
+ }
1710
+ if (!x.auth?.publicKeyPath) {
1711
+ logger.error("Xiaomi config missing: publicKeyPath");
1712
+ return false;
1713
+ }
1714
+ return true;
1715
+ }
1716
+ canHandle(filePath) {
1717
+ const ext = filePath.split(".").pop()?.toLowerCase();
1718
+ return ext === "apk";
1719
+ }
1720
+ /**
1721
+ * 查询应用状态
1722
+ * 使用 POST /dev/query 接口,需要 SIG 签名认证
1723
+ *
1724
+ * 返回值说明:
1725
+ * - create: true → 需要通过新增方式上传 (synchroType=0)
1726
+ * - updateVersion: true → 可以更新包 (synchroType=1)
1727
+ * - updateInfo: true → 可以仅更新信息 (synchroType=2)
1728
+ */
1729
+ async queryAppStatus(userName, packageName, privateKey, publicKeyObj) {
1730
+ try {
1731
+ const queryData = {
1732
+ packageName,
1733
+ userName
1734
+ };
1735
+ const requestData = JSON.stringify(queryData);
1736
+ logger.info(`Query RequestData: ${requestData}`);
1737
+ const requestDataMD5 = this.calculateStringMD5(requestData);
1738
+ logger.info(`Query RequestData MD5: ${requestDataMD5}`);
1739
+ const sig = this.generateQuerySIG(requestDataMD5, privateKey, publicKeyObj);
1740
+ const params = new URLSearchParams();
1741
+ params.append("RequestData", requestData);
1742
+ params.append("SIG", sig);
1743
+ const response = await import_axios3.default.post(_XiaomiUploader.QUERY_API, params.toString(), {
1744
+ headers: {
1745
+ "Content-Type": "application/x-www-form-urlencoded"
1746
+ },
1747
+ timeout: 15e3
1748
+ });
1749
+ const data = response.data;
1750
+ logger.info(`\u67E5\u8BE2\u5E94\u7528\u54CD\u5E94: ${JSON.stringify(data)}`);
1751
+ if (data?.result === -20014) {
1752
+ throw new Error(
1753
+ `\u5C0F\u7C73\u8BA4\u8BC1\u5931\u8D25: \u5BC6\u7801\u9519\u8BEF (result=-20014)\u3002\u8BF7\u68C0\u67E5 publish.xiaomi.auth.privateKey \u662F\u5426\u4E3A\u6700\u65B0\u7684 API \u79C1\u94A5\u3002`
1754
+ );
1755
+ }
1756
+ if (data?.result !== 0) {
1757
+ logger.warn(`\u67E5\u8BE2\u8FD4\u56DE\u975E\u96F6: result=${data?.result}, ${data?.message}`);
1758
+ return { type: "new", queried: false };
1759
+ }
1760
+ const appInfo = data.appInfo || null;
1761
+ if (data.updateVersion === true) {
1762
+ return { type: "update", queried: true, appInfo };
1763
+ }
1764
+ if (data.create === true) {
1765
+ logger.info("\u5E94\u7528\u5DF2\u5728\u540E\u53F0\u521B\u5EFA\u4F46\u5C1A\u672A\u4E0A\u4F20\u8FC7\u5305\uFF0C\u5C06\u8FDB\u5165\u9996\u6B21\u63D0\u5BA1\u6A21\u5F0F");
1766
+ return { type: "new", queried: true, appInfo };
1767
+ }
1768
+ return { type: "update", queried: true, appInfo };
1769
+ } catch (error) {
1770
+ if (error.message.includes("\u5C0F\u7C73\u8BA4\u8BC1\u5931\u8D25")) {
1771
+ throw error;
1772
+ }
1773
+ logger.warn(`\u67E5\u8BE2\u5E94\u7528\u8FDE\u63A5\u5F02\u5E38: ${error.message}\uFF0C\u5C06\u63A8\u6D4B\u4E3A\u65B0\u589E\u5E94\u7528\u6A21\u5F0F`);
1774
+ return { type: "new", queried: false };
1775
+ }
1776
+ }
1777
+ /**
1778
+ * 查询小米应用商店分类列表
1779
+ * POST /dev/category, 无需参数
1780
+ */
1781
+ async queryCategories() {
1782
+ try {
1783
+ const response = await import_axios3.default.post(_XiaomiUploader.CATEGORY_API, null, {
1784
+ timeout: 1e4
1785
+ });
1786
+ const data = response.data;
1787
+ if (data?.result === 0 && Array.isArray(data.categories)) {
1788
+ return data.categories;
1789
+ }
1790
+ logger.warn(`\u83B7\u53D6\u5206\u7C7B\u5217\u8868\u5931\u8D25: ${JSON.stringify(data)}`);
1791
+ return null;
1792
+ } catch (error) {
1793
+ logger.warn(`\u83B7\u53D6\u5206\u7C7B\u5217\u8868\u5F02\u5E38: ${error.message}`);
1794
+ return null;
1795
+ }
1796
+ }
1797
+ async upload(filePath, config, metadata) {
1798
+ const xiaomiConfig = config.publish?.xiaomi;
1799
+ const { userName, privateKey, publicKeyPath } = xiaomiConfig.auth;
1800
+ const updateDesc = metadata.changelog || xiaomiConfig?.description || "App Update";
1801
+ const retryConfig = config.retry;
1802
+ if (!import_fs_extra5.default.existsSync(filePath)) {
1803
+ return {
1804
+ platform: "xiaomi",
1805
+ success: false,
1806
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`
1807
+ };
1808
+ }
1809
+ const resolvedPublicKey = await this.resolvePublicKey(publicKeyPath);
1810
+ if (!resolvedPublicKey) {
1811
+ return {
1812
+ platform: "xiaomi",
1813
+ success: false,
1814
+ message: "\u65E0\u6CD5\u83B7\u53D6 RSA \u516C\u94A5: publicKeyPath \u672A\u63D0\u4F9B\u6216\u6587\u4EF6\u4E0D\u5B58\u5728"
1815
+ };
1816
+ }
1817
+ const packageName = xiaomiConfig.packageName || this.inferPackageName(filePath);
1818
+ if (!packageName) {
1819
+ return {
1820
+ platform: "xiaomi",
1821
+ success: false,
1822
+ message: "\u7F3A\u5C11 packageName \u914D\u7F6E, \u4E14\u65E0\u6CD5\u4ECE\u6587\u4EF6\u540D\u63A8\u65AD\u5E94\u7528\u5305\u540D"
1823
+ };
1824
+ }
1825
+ const appName = xiaomiConfig.appName || this.inferAppName(packageName);
1826
+ if (!appName) {
1827
+ return {
1828
+ platform: "xiaomi",
1829
+ success: false,
1830
+ message: "\u7F3A\u5C11 appName \u914D\u7F6E, \u4E14\u65E0\u6CD5\u4ECE\u5305\u540D\u63A8\u65AD\u5E94\u7528\u540D\u79F0"
1831
+ };
1832
+ }
1833
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230\u5C0F\u7C73\u5E94\u7528\u5546\u5E97...");
1834
+ logger.info(`\u6587\u4EF6: ${filePath}`);
1835
+ logger.info(`\u5305\u540D: ${packageName}`);
1836
+ logger.info(`\u5E94\u7528\u540D: ${appName}`);
1837
+ const publicKeyObj = this.extractPublicKey(resolvedPublicKey);
1838
+ const configUploadType = xiaomiConfig.uploadType || "auto";
1839
+ let uploadType;
1840
+ let existingAppInfo = null;
1841
+ if (configUploadType === "auto") {
1842
+ logger.info("\u6B63\u5728\u67E5\u8BE2\u5E94\u7528\u4FE1\u606F...");
1843
+ const status = await this.queryAppStatus(userName, packageName, privateKey, publicKeyObj);
1844
+ uploadType = status.type;
1845
+ existingAppInfo = status.appInfo;
1846
+ } else {
1847
+ uploadType = configUploadType;
1848
+ }
1849
+ const uploadTypeDesc = uploadType === "update" ? "\u5E94\u7528\u66F4\u65B0 (synchroType=1)" : "\u65B0\u589E\u5E94\u7528 (synchroType=0)";
1850
+ logger.info(`\u4E0A\u4F20\u7C7B\u578B: ${uploadTypeDesc}`);
1851
+ if (uploadType === "new" && xiaomiConfig.uploadType === "new") {
1852
+ const missing = [];
1853
+ if (xiaomiConfig.category == null) missing.push("category (\u5206\u7C7BID)");
1854
+ if (!xiaomiConfig.desc) missing.push("desc (\u5E94\u7528\u4ECB\u7ECD)");
1855
+ if (missing.length > 0) {
1856
+ return {
1857
+ platform: "xiaomi",
1858
+ success: false,
1859
+ message: `\u9996\u6B21\u63D0\u5BA1\u6A21\u5F0F\u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5: ${missing.join(", ")}\u3002\u8BF7\u5728\u540E\u53F0\u8865\u5168\u6216\u5728\u914D\u7F6E\u4E2D\u6DFB\u52A0\u3002`
1860
+ };
1861
+ }
1862
+ }
1863
+ try {
1864
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
1865
+ const result = await retryStrategy.execute(
1866
+ () => this.performUpload({
1867
+ filePath,
1868
+ userName,
1869
+ privateKey,
1870
+ publicKey: resolvedPublicKey,
1871
+ packageName,
1872
+ appName,
1873
+ updateDesc,
1874
+ uploadType,
1875
+ category: xiaomiConfig.category || existingAppInfo?.category,
1876
+ keyWords: xiaomiConfig.keyWords || existingAppInfo?.keyWords,
1877
+ desc: xiaomiConfig.desc || existingAppInfo?.desc,
1878
+ brief: xiaomiConfig.brief || existingAppInfo?.brief,
1879
+ privacyUrl: xiaomiConfig.privacyUrl || existingAppInfo?.privacyUrl,
1880
+ assets: xiaomiConfig.assets
1881
+ }),
1882
+ "Xiaomi push upload"
1883
+ );
1884
+ if (!result.success) {
1885
+ throw result.error || new Error("Upload failed");
1886
+ }
1887
+ logger.success("\u4E0A\u4F20\u5230\u5C0F\u7C73\u5E94\u7528\u5546\u5E97\u6210\u529F!");
1888
+ return {
1889
+ platform: "xiaomi",
1890
+ success: true,
1891
+ message: "\u4E0A\u4F20\u6210\u529F, \u7B49\u5F85\u5BA1\u6838",
1892
+ data: result.data,
1893
+ consoleUrl: "https://dev.mi.com/distribute/app/details"
1894
+ };
1895
+ } catch (error) {
1896
+ logger.error(`\u4E0A\u4F20\u5230\u5C0F\u7C73\u5931\u8D25: ${error.message}`);
1897
+ if (error.response?.data) {
1898
+ logger.info(`\u9519\u8BEF\u8BE6\u60C5: ${JSON.stringify(error.response.data)}`);
1899
+ }
1900
+ return {
1901
+ platform: "xiaomi",
1902
+ success: false,
1903
+ message: error.message,
1904
+ error
1905
+ };
1906
+ }
1907
+ }
1908
+ /**
1909
+ * 执行实际的上传操作
1910
+ */
1911
+ async performUpload(params) {
1912
+ const {
1913
+ filePath,
1914
+ userName,
1915
+ privateKey,
1916
+ publicKey,
1917
+ packageName,
1918
+ appName,
1919
+ updateDesc,
1920
+ uploadType,
1921
+ category,
1922
+ keyWords,
1923
+ desc,
1924
+ brief,
1925
+ privacyUrl,
1926
+ assets
1927
+ } = params;
1928
+ const publicKeyObj = this.extractPublicKey(publicKey);
1929
+ const requestData = this.buildRequestData({
1930
+ userName,
1931
+ packageName,
1932
+ appName,
1933
+ updateDesc,
1934
+ uploadType,
1935
+ category,
1936
+ keyWords,
1937
+ desc,
1938
+ brief,
1939
+ privacyUrl
1940
+ });
1941
+ logger.info("RequestData \u5DF2\u6784\u5EFA");
1942
+ logger.info(`RequestData: ${requestData}`);
1943
+ const requestDataMD5 = this.calculateStringMD5(requestData);
1944
+ const apkFileMD5 = await this.calculateFileMD5(filePath);
1945
+ logger.info(`APK MD5: ${apkFileMD5}`);
1946
+ const extraSigItems = [];
1947
+ let iconPath;
1948
+ if (assets?.icon && import_fs_extra5.default.existsSync(assets.icon)) {
1949
+ iconPath = assets.icon;
1950
+ const iconMD5 = await this.calculateFileMD5(iconPath);
1951
+ extraSigItems.push({ name: "icon", hash: iconMD5 });
1952
+ }
1953
+ const screenshotPaths = [];
1954
+ if (assets?.screenshots) {
1955
+ for (let i = 0; i < assets.screenshots.length && i < 4; i++) {
1956
+ const ssPath = assets.screenshots[i];
1957
+ if (import_fs_extra5.default.existsSync(ssPath)) {
1958
+ screenshotPaths.push(ssPath);
1959
+ const ssMD5 = await this.calculateFileMD5(ssPath);
1960
+ extraSigItems.push({ name: `screenshot_${i + 1}`, hash: ssMD5 });
1961
+ }
1962
+ }
1963
+ }
1964
+ const sig = this.generateUploadSIG(
1965
+ requestDataMD5,
1966
+ apkFileMD5,
1967
+ privateKey,
1968
+ publicKeyObj,
1969
+ extraSigItems.length > 0 ? extraSigItems : void 0
1970
+ );
1971
+ logger.info("SIG \u7B7E\u540D\u5DF2\u751F\u6210");
1972
+ const form = new import_form_data3.default();
1973
+ form.append("RequestData", requestData);
1974
+ form.append("SIG", sig);
1975
+ form.append("apk", import_fs_extra5.default.createReadStream(filePath));
1976
+ if (iconPath) {
1977
+ form.append("icon", import_fs_extra5.default.createReadStream(iconPath));
1978
+ logger.info(`\u9644\u52A0 icon: ${iconPath}`);
1979
+ }
1980
+ for (let i = 0; i < screenshotPaths.length; i++) {
1981
+ form.append(`screenshot_${i + 1}`, import_fs_extra5.default.createReadStream(screenshotPaths[i]));
1982
+ logger.info(`\u9644\u52A0 screenshot_${i + 1}: ${screenshotPaths[i]}`);
1983
+ }
1984
+ logger.info(`POST ${_XiaomiUploader.PUSH_API}`);
1985
+ const response = await import_axios3.default.post(_XiaomiUploader.PUSH_API, form, {
1986
+ headers: {
1987
+ ...form.getHeaders()
1988
+ },
1989
+ maxContentLength: Infinity,
1990
+ maxBodyLength: Infinity,
1991
+ timeout: 6e4
1992
+ // 60 秒请求超时
1993
+ });
1994
+ const data = response.data;
1995
+ logger.info(`\u5C0F\u7C73 API \u539F\u59CB\u54CD\u5E94: ${JSON.stringify(data)}`);
1996
+ if (data?.result !== 0) {
1997
+ const errMsg = data?.message || data?.msg || JSON.stringify(data);
1998
+ throw new Error(`\u5C0F\u7C73 API \u8FD4\u56DE\u9519\u8BEF (result=${data?.result}): ${errMsg}`);
1999
+ }
2000
+ logger.info(`\u5C0F\u7C73 API \u54CD\u5E94: ${JSON.stringify(data)}`);
2001
+ return data;
2002
+ }
2003
+ /**
2004
+ * 解析公钥: 优先使用内容字段, 其次从文件路径读取
2005
+ */
2006
+ async resolvePublicKey(publicKeyPath) {
2007
+ if (publicKeyPath) {
2008
+ if (!import_fs_extra5.default.existsSync(publicKeyPath)) {
2009
+ logger.error(`\u516C\u94A5\u6587\u4EF6\u4E0D\u5B58\u5728: ${publicKeyPath}`);
2010
+ return null;
2011
+ }
2012
+ return await import_fs_extra5.default.readFile(publicKeyPath);
2013
+ }
2014
+ return null;
2015
+ }
2016
+ /**
2017
+ * 尝试从文件名推断包名
2018
+ * 例如: com.example.app-release.apk → com.example.app
2019
+ */
2020
+ inferPackageName(filePath) {
2021
+ const fileName = filePath.split("/").pop()?.split("\\").pop() || "";
2022
+ const match = fileName.match(/^([\w.]+?)(?:-(?:release|debug|unsigned))?\.apk$/i);
2023
+ if (match && match[1].includes(".")) {
2024
+ return match[1];
2025
+ }
2026
+ return null;
2027
+ }
2028
+ /**
2029
+ * 从包名推断应用名称
2030
+ * 例如: com.example.app → app 或 com.app → app
2031
+ */
2032
+ inferAppName(packageName) {
2033
+ const parts = packageName.split(".");
2034
+ if (parts.length === 0) return null;
2035
+ const lastPart = parts[parts.length - 1];
2036
+ const humanized = lastPart.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase());
2037
+ return humanized || null;
2038
+ }
2039
+ };
2040
+
2041
+ // src/adapters/apple_store_uploader.ts
2042
+ var import_fs_extra6 = __toESM(require("fs-extra"), 1);
2043
+ var import_path4 = __toESM(require("path"), 1);
2044
+ var import_child_process = require("child_process");
2045
+ var import_util2 = require("util");
2046
+ var import_axios4 = __toESM(require("axios"), 1);
2047
+ var execAsync = (0, import_util2.promisify)(import_child_process.exec);
2048
+ var APP_STORE_CONNECT_API = "https://api.appstoreconnect.apple.com/v1";
2049
+ var TRANSPORTER_APP_PATH = "/Applications/Transporter.app/Contents/itms/bin/iTMSTransporter";
2050
+ var AppleStoreUploader = class {
2051
+ name = "AppStore";
2052
+ /**
2053
+ * 验证配置是否有效
2054
+ * 至少需要一种认证方式:
2055
+ * - appleId + appPassword(CLI 上传)
2056
+ * - apiKeyId + apiIssuerId + privateKey(API 调用,也可用于 CLI 上传)
2057
+ */
2058
+ validateConfig(config) {
2059
+ if (!config?.publish?.app_store?.enable) return false;
2060
+ const auth = config.publish.app_store?.auth;
2061
+ const hasCliAuth = auth?.appleId && auth?.appPassword;
2062
+ const hasApiAuth = this.hasApiCredentials(auth);
2063
+ if (!hasCliAuth && !hasApiAuth) {
2064
+ logger.error(
2065
+ "Apple \u914D\u7F6E\u7F3A\u5931\uFF1A\u9700\u8981 (appleId + appPassword) \u6216 (apiKeyId + apiIssuerId + privateKey) \u4E2D\u7684\u4E00\u79CD\u3002"
2066
+ );
2067
+ return false;
2068
+ }
2069
+ return true;
2070
+ }
2071
+ /**
2072
+ * 判断是否支持处理该文件
2073
+ */
2074
+ canHandle(filePath) {
2075
+ const ext = filePath.split(".").pop()?.toLowerCase();
2076
+ return ext === "ipa";
2077
+ }
2078
+ /**
2079
+ * 执行上传流程
2080
+ */
2081
+ async upload(filePath, config, metadata) {
2082
+ const appConfig = config.publish.app_store;
2083
+ const auth = appConfig.auth;
2084
+ const retryConfig = config.retry;
2085
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 App Store...");
2086
+ try {
2087
+ const exists = await import_fs_extra6.default.pathExists(filePath);
2088
+ if (!exists) {
2089
+ throw new Error(`IPA \u6587\u4EF6\u672A\u627E\u5230: ${filePath}`);
2090
+ }
2091
+ const fileSize = (await import_fs_extra6.default.stat(filePath)).size;
2092
+ logger.info(`IPA \u6587\u4EF6\u5927\u5C0F: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2093
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2094
+ const uploadResult = await retryStrategy.execute(
2095
+ () => this.uploadWithAvailableTool(filePath, auth),
2096
+ "App Store \u4E0A\u4F20"
2097
+ );
2098
+ if (!uploadResult.success) {
2099
+ throw uploadResult.error || new Error("\u4E0A\u4F20\u5931\u8D25");
2100
+ }
2101
+ logger.success("App Store IPA \u4E0A\u4F20\u6210\u529F\uFF01");
2102
+ if (metadata.changelog && this.hasApiCredentials(auth)) {
2103
+ await this.tryUpdateReleaseNotes(auth, appConfig.appId, metadata.changelog, retryStrategy);
2104
+ } else if (metadata.changelog && !this.hasApiCredentials(auth)) {
2105
+ logger.info(
2106
+ "\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\uFF1A\u672A\u914D\u7F6E API Key \u51ED\u636E\u3002\u5982\u9700\u542F\u7528\uFF0C\u8BF7\u5728\u914D\u7F6E\u4E2D\u6DFB\u52A0 apiKeyId + apiIssuerId + privateKeyPath\u3002"
2107
+ );
2108
+ }
2109
+ return {
2110
+ platform: "app_store",
2111
+ success: true,
2112
+ message: "\u4E0A\u4F20\u6210\u529F\u3002\u8BF7\u524D\u5F80 App Store Connect \u67E5\u770B\u3002",
2113
+ url: "https://appstoreconnect.apple.com/apps",
2114
+ consoleUrl: "https://appstoreconnect.apple.com/apps"
2115
+ };
2116
+ } catch (error) {
2117
+ return {
2118
+ platform: "app_store",
2119
+ success: false,
2120
+ message: error.message,
2121
+ error
2122
+ };
2123
+ }
2124
+ }
2125
+ // ───── CLI 上传 ─────
2126
+ /**
2127
+ * 使用可用的工具上传
2128
+ * 策略: 优先 Transporter → 降级 altool → 都失败
2129
+ */
2130
+ async uploadWithAvailableTool(ipaPath, auth) {
2131
+ const appleId = auth.appleId;
2132
+ const appPassword = auth.appPassword;
2133
+ try {
2134
+ logger.info("\u6B63\u5728\u5C1D\u8BD5\u4F7F\u7528 Transporter CLI...");
2135
+ const transporterTool = await this.resolveToolPath("transporter");
2136
+ if (transporterTool) {
2137
+ await this.uploadViaTransporter(transporterTool, ipaPath, appleId, appPassword);
2138
+ logger.success("\u901A\u8FC7 Transporter \u4E0A\u4F20\u5B8C\u6210");
2139
+ return;
2140
+ }
2141
+ } catch (error) {
2142
+ logger.warn(`Transporter \u8C03\u7528\u5931\u8D25: ${error.message}\u3002\u5C1D\u8BD5\u964D\u7EA7\u5230 altool...`);
2143
+ }
2144
+ let altoolTool = null;
2145
+ try {
2146
+ logger.info("\u6B63\u5728\u5C1D\u8BD5\u4F7F\u7528 xcrun altool...");
2147
+ altoolTool = await this.resolveToolPath("altool");
2148
+ } catch (error) {
2149
+ logger.warn(`altool \u68C0\u6D4B\u5931\u8D25: ${error.message}`);
2150
+ }
2151
+ if (altoolTool) {
2152
+ await this.uploadViaAltool(altoolTool, ipaPath, appleId, appPassword);
2153
+ logger.success("\u901A\u8FC7 altool \u4E0A\u4F20\u5B8C\u6210");
2154
+ return;
2155
+ }
2156
+ throw new Error(this.getToolInstallationGuide());
2157
+ }
2158
+ /**
2159
+ * 解析工具路径结果
2160
+ */
2161
+ async resolveToolPath(tool) {
2162
+ if (tool === "transporter") {
2163
+ try {
2164
+ await execAsync("transporter -version", { timeout: 5e3 });
2165
+ return { command: "transporter", useShell: false };
2166
+ } catch {
2167
+ }
2168
+ if (await import_fs_extra6.default.pathExists(TRANSPORTER_APP_PATH)) {
2169
+ return { command: `"${TRANSPORTER_APP_PATH}"`, useShell: false };
2170
+ }
2171
+ } else {
2172
+ const xcrunPath = await import_fs_extra6.default.pathExists("/usr/bin/xcrun") ? "/usr/bin/xcrun" : "xcrun";
2173
+ try {
2174
+ await execAsync(`${xcrunPath} altool --version`, {
2175
+ timeout: 1e4
2176
+ });
2177
+ return { command: `${xcrunPath} altool`, useShell: false };
2178
+ } catch (error) {
2179
+ logger.warn(
2180
+ `[AppleStore] Direct altool check failed: ${error.message}. Trying shell mode...`
2181
+ );
2182
+ }
2183
+ try {
2184
+ await execAsync(`bash -l -c "xcrun altool --version"`, {
2185
+ timeout: 1e4
2186
+ });
2187
+ return { command: "xcrun altool", useShell: true };
2188
+ } catch (error) {
2189
+ logger.warn(`[AppleStore] Shell altool check failed: ${error.message}`);
2190
+ }
2191
+ return null;
2192
+ }
2193
+ return null;
2194
+ }
2195
+ /**
2196
+ * 通过 Transporter CLI 上传
2197
+ */
2198
+ async uploadViaTransporter(tool, ipaPath, appleId, appPassword) {
2199
+ const command = [
2200
+ tool.command,
2201
+ "-uploadFile",
2202
+ `"${ipaPath}"`,
2203
+ "-username",
2204
+ appleId,
2205
+ "-password",
2206
+ appPassword,
2207
+ "-showTransferRate"
2208
+ ].join(" ");
2209
+ logger.info(`[Transporter] Uploading: ${import_path4.default.basename(ipaPath)}`);
2210
+ try {
2211
+ const { stdout, stderr } = await execAsync(command, {
2212
+ timeout: 30 * 60 * 1e3,
2213
+ // 30 分钟
2214
+ maxBuffer: 10 * 1024 * 1024
2215
+ // 10MB
2216
+ });
2217
+ if (stdout) {
2218
+ logger.info(`[Transporter] ${stdout}`);
2219
+ }
2220
+ if (stderr && (stderr.includes("error") || stderr.includes("failed") || stderr.includes("ERROR"))) {
2221
+ const errorMessage = this.parseAltoolError(stderr);
2222
+ throw new Error(errorMessage);
2223
+ }
2224
+ } catch (error) {
2225
+ throw new Error(`Transporter upload failed: ${error.message}
2226
+ Stderr: ${error.stderr || ""}`);
2227
+ }
2228
+ }
2229
+ /**
2230
+ * 通过 altool 上传
2231
+ */
2232
+ async uploadViaAltool(tool, ipaPath, appleId, appPassword) {
2233
+ const args = [
2234
+ "xcrun altool",
2235
+ // 占位符
2236
+ "--upload-app",
2237
+ "-f",
2238
+ "__IPA_PATH__",
2239
+ // 占位符
2240
+ "-t",
2241
+ "ios",
2242
+ "-u",
2243
+ appleId,
2244
+ "-p",
2245
+ appPassword
2246
+ // '--verbose', // 禁用 verbose
2247
+ ];
2248
+ let command = "";
2249
+ if (tool.useShell) {
2250
+ const innerCommand = args.slice(1).join(" ").replace("__IPA_PATH__", `\\"${ipaPath}\\"`);
2251
+ command = `bash -l -c "${tool.command} ${innerCommand}"`;
2252
+ } else {
2253
+ const innerArgs = args.map((arg) => {
2254
+ if (arg === "xcrun altool") return tool.command;
2255
+ if (arg === "__IPA_PATH__") return `"${ipaPath}"`;
2256
+ return arg;
2257
+ });
2258
+ command = innerArgs.join(" ");
2259
+ }
2260
+ logger.info(`[altool] Uploading: ${import_path4.default.basename(ipaPath)}`);
2261
+ logger.info(`[altool] Command prefix: ${tool.command}`);
2262
+ try {
2263
+ const { stdout, stderr } = await execAsync(command, {
2264
+ timeout: 30 * 60 * 1e3,
2265
+ maxBuffer: 10 * 1024 * 1024
2266
+ });
2267
+ if (stdout) {
2268
+ if (stdout.includes("No errors uploading") || stdout.includes("Request UUID")) {
2269
+ logger.info(`[altool] ${stdout}`);
2270
+ }
2271
+ }
2272
+ if (stderr && (stderr.includes("error") || stderr.includes("failed") || stderr.includes("ERROR"))) {
2273
+ const errorMessage = this.parseAltoolError(stderr);
2274
+ throw new Error(errorMessage);
2275
+ }
2276
+ } catch (error) {
2277
+ const errorMsg = this.parseAltoolError(error.stderr || error.message);
2278
+ throw new Error(errorMsg);
2279
+ }
2280
+ }
2281
+ /**
2282
+ * 解析 altool/Transporter 错误信息,翻译为用户友好的语言
2283
+ */
2284
+ parseAltoolError(stderr) {
2285
+ if (!stderr) return "Unknown error";
2286
+ if (stderr.includes("previousBundleVersion") || stderr.includes("ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE") || stderr.includes("Redundant Binary Upload") || stderr.includes("already been used")) {
2287
+ const match = stderr.match(/previously uploaded version: ‘(.*?)’/);
2288
+ const prevVersion = match ? match[1] : "unknown";
2289
+ return `\u7248\u672C\u53F7\u51B2\u7A81 (Version Conflict): \u6784\u5EFA\u7248\u672C ${prevVersion} \u5DF2\u5B58\u5728\u4E8E App Store Connect\u3002
2290
+ \u89E3\u51B3\u65B9\u6848: \u8BF7\u5728 pubspec.yaml \u4E2D\u589E\u52A0 'version: x.y.z+N' \u4E2D\u7684 N (build number)\uFF0C\u7136\u540E\u91CD\u65B0\u6784\u5EFA IPA\u3002`;
2291
+ }
2292
+ if (stderr.includes("Authentication failed") || stderr.includes("password is incorrect") || stderr.includes("NOT_AUTHORIZED")) {
2293
+ return `\u8BA4\u8BC1\u5931\u8D25 (Auth Failed): Apple ID \u6216 App-specific Password \u9519\u8BEF\u3002
2294
+ \u89E3\u51B3\u65B9\u6848: \u8BF7\u68C0\u67E5\u914D\u7F6E\u3002\u6CE8\u610F\u5FC5\u987B\u4F7F\u7528 App \u4E13\u7528\u5BC6\u7801\uFF0C\u4E0D\u80FD\u4F7F\u7528 Apple ID \u767B\u5F55\u5BC6\u7801\u3002`;
2295
+ }
2296
+ if (stderr.includes("Asset validation failed")) {
2297
+ return `\u8D44\u4EA7\u9A8C\u8BC1\u5931\u8D25 (Validation Failed): IPA \u6587\u4EF6\u53EF\u80FD\u4E0D\u7B26\u5408 App Store \u8981\u6C42\u3002
2298
+ \u8BE6\u7EC6\u9519\u8BEF: ${stderr}`;
2299
+ }
2300
+ return `\u4E0A\u4F20\u5DE5\u5177\u62A5\u9519: ${stderr.substring(0, 800)}...`;
2301
+ }
2302
+ // ───── 发行说明 API ─────
2303
+ /**
2304
+ * 检查是否配置了 API Key 凭据
2305
+ */
2306
+ hasApiCredentials(auth) {
2307
+ return !!(auth?.apiKeyId && auth?.apiIssuerId && (auth?.privateKeyPath || auth?.privateKeyContent));
2308
+ }
2309
+ /**
2310
+ * 创建 JWT 生成器
2311
+ */
2312
+ async createJWTGenerator(auth) {
2313
+ if (auth.privateKeyContent) {
2314
+ return AppleJWTGenerator.fromContent(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyContent);
2315
+ }
2316
+ return AppleJWTGenerator.fromFile(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyPath);
2317
+ }
2318
+ /**
2319
+ * 获取 API 请求头
2320
+ */
2321
+ apiHeaders(token) {
2322
+ return {
2323
+ Authorization: `Bearer ${token}`,
2324
+ "Content-Type": "application/json"
2325
+ };
2326
+ }
2327
+ /**
2328
+ * 尝试更新发行说明(失败不影响上传结果)
2329
+ */
2330
+ async tryUpdateReleaseNotes(auth, appId, changelog, retryStrategy) {
2331
+ if (!appId) {
2332
+ logger.info(
2333
+ "\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\uFF1A\u672A\u914D\u7F6E App ID\u3002\u8BF7\u6DFB\u52A0 app_store.appId \u4EE5\u542F\u7528\u81EA\u52A8\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002"
2334
+ );
2335
+ return;
2336
+ }
2337
+ try {
2338
+ logger.info("\u6B63\u5728\u901A\u8FC7 App Store Connect API \u66F4\u65B0\u53D1\u884C\u8BF4\u660E...");
2339
+ const jwtGenerator = await this.createJWTGenerator(auth);
2340
+ const token = jwtGenerator.generate();
2341
+ const version = await this.getPrepareForSubmissionVersion(token, appId);
2342
+ if (!version) {
2343
+ logger.warn(
2344
+ '\u672A\u627E\u5230\u5904\u4E8E"\u51C6\u5907\u63D0\u4EA4 (PREPARE_FOR_SUBMISSION)"\u72B6\u6001\u7684\u7248\u672C\u3002\u5DF2\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002\u8BF7\u5728 App Store Connect \u624B\u52A8\u66F4\u65B0\u3002'
2345
+ );
2346
+ return;
2347
+ }
2348
+ const localizations = await this.getVersionLocalizations(token, version.id);
2349
+ if (localizations.length === 0) {
2350
+ logger.warn("\u8BE5\u7248\u672C\u6CA1\u6709\u627E\u5230\u672C\u5730\u5316\u4FE1\u606F\u3002\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002");
2351
+ return;
2352
+ }
2353
+ for (const loc of localizations) {
2354
+ const locale = loc.attributes?.locale || "unknown";
2355
+ await retryStrategy.execute(
2356
+ () => this.updateLocalizationWhatsNew(token, loc.id, changelog),
2357
+ `\u66F4\u65B0\u53D1\u884C\u8BF4\u660E (${locale})`
2358
+ );
2359
+ logger.info(`\u5DF2\u66F4\u65B0\u53D1\u884C\u8BF4\u660E: ${locale}`);
2360
+ }
2361
+ logger.success("\u6240\u6709\u53D1\u884C\u8BF4\u660E\u66F4\u65B0\u6210\u529F\uFF01");
2362
+ } catch (error) {
2363
+ logger.warn(`\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u5931\u8D25: ${error.message}\u3002IPA \u4E0A\u4F20\u5DF2\u6210\u529F\u3002\u8BF7\u624B\u52A8\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002`);
2364
+ }
2365
+ }
2366
+ /**
2367
+ * 获取处于"准备提交"状态的版本
2368
+ * 只有此状态下的版本才能修改发行说明
2369
+ */
2370
+ async getPrepareForSubmissionVersion(token, appId) {
2371
+ const res = await import_axios4.default.get(`${APP_STORE_CONNECT_API}/apps/${appId}/appStoreVersions`, {
2372
+ params: {
2373
+ "filter[appStoreState]": "PREPARE_FOR_SUBMISSION",
2374
+ limit: 1
2375
+ },
2376
+ headers: this.apiHeaders(token)
2377
+ });
2378
+ const versions = res.data?.data;
2379
+ if (versions && versions.length > 0) {
2380
+ logger.info(
2381
+ `Found version: ${versions[0].attributes?.versionString} (PREPARE_FOR_SUBMISSION)`
2382
+ );
2383
+ return versions[0];
2384
+ }
2385
+ return null;
2386
+ }
2387
+ /**
2388
+ * 获取版本的本地化信息列表
2389
+ */
2390
+ async getVersionLocalizations(token, versionId) {
2391
+ const res = await import_axios4.default.get(
2392
+ `${APP_STORE_CONNECT_API}/appStoreVersions/${versionId}/appStoreVersionLocalizations`,
2393
+ {
2394
+ headers: this.apiHeaders(token)
2395
+ }
2396
+ );
2397
+ return res.data?.data || [];
2398
+ }
2399
+ /**
2400
+ * 更新本地化版本的 What's New 内容
2401
+ */
2402
+ async updateLocalizationWhatsNew(token, localizationId, whatsNew) {
2403
+ await import_axios4.default.patch(
2404
+ `${APP_STORE_CONNECT_API}/appStoreVersionLocalizations/${localizationId}`,
2405
+ {
2406
+ data: {
2407
+ type: "appStoreVersionLocalizations",
2408
+ id: localizationId,
2409
+ attributes: {
2410
+ whatsNew
2411
+ }
2412
+ }
2413
+ },
2414
+ {
2415
+ headers: this.apiHeaders(token)
2416
+ }
2417
+ );
2418
+ }
2419
+ // ───── 工具安装指引 ─────
2420
+ /**
2421
+ * 获取工具安装指引
2422
+ */
2423
+ getToolInstallationGuide() {
2424
+ return `
2425
+ Neither Transporter nor altool CLI found. Please install one:
2426
+
2427
+ \u3010\u63A8\u8350\u3011 Transporter CLI (\u5B98\u65B9\u63A8\u8350):
2428
+ Mac: https://apps.apple.com/app/transporter/id1450874784
2429
+ Windows: https://www.microsoft.com/store/apps/9NBLGGH52RM5
2430
+
2431
+ \u3010\u5907\u9009\u3011 xcrun altool (Xcode \u81EA\u5E26):
2432
+ Install Xcode Command Line Tools:
2433
+ xcode-select --install
2434
+
2435
+ Note:
2436
+ - \u9700\u8981\u4F7F\u7528 Apple ID \u548C App-specific Password (\u5728 appleid.apple.com \u751F\u6210)
2437
+ - \u4E0D\u80FD\u4F7F\u7528\u666E\u901A Apple ID \u5BC6\u7801
2438
+ `.trim();
2439
+ }
2440
+ };
2441
+
2442
+ // src/adapters/testflight_uploader.ts
2443
+ var import_fs_extra7 = __toESM(require("fs-extra"), 1);
2444
+ var import_axios5 = __toESM(require("axios"), 1);
2445
+ var import_form_data4 = __toESM(require("form-data"), 1);
2446
+ var TestFlightUploader = class _TestFlightUploader {
2447
+ name = "TestFlight";
2448
+ static API_ROOT = "https://api.appstoreconnect.apple.com/v1";
2449
+ static API_TIMEOUT = 3e4;
2450
+ static BUILD_PROCESSING_TIMEOUT = 10 * 60 * 1e3;
2451
+ // 10 minutes
2452
+ static BUILD_POLLING_INTERVAL = 10 * 1e3;
2453
+ // 10 seconds
2454
+ /**
2455
+ * 验证配置
2456
+ * @param config 配置对象
2457
+ */
2458
+ validateConfig(config) {
2459
+ if (!config?.publish?.app_store?.enable) return false;
2460
+ if (config.publish.app_store.mode !== "testflight") return false;
2461
+ const auth = config.publish.app_store.auth;
2462
+ if (!auth?.apiKeyId || !auth?.apiIssuerId) {
2463
+ logger.error("TestFlight config missing: apiKeyId or apiIssuerId");
2464
+ return false;
2465
+ }
2466
+ if (!auth.privateKeyPath && !auth.privateKeyContent) {
2467
+ logger.error("TestFlight config missing: privateKeyPath or privateKeyContent");
2468
+ return false;
2469
+ }
2470
+ return true;
2471
+ }
2472
+ /**
2473
+ * 判断是否支持该文件
2474
+ * @param filePath 文件路径
2475
+ */
2476
+ canHandle(filePath) {
2477
+ const ext = filePath.split(".").pop()?.toLowerCase();
2478
+ return ext === "ipa";
2479
+ }
2480
+ /**
2481
+ * 执行上传到 TestFlight
2482
+ * @param filePath 文件路径
2483
+ * @param config 配置
2484
+ * @param metadata 元数据
2485
+ */
2486
+ async upload(filePath, config, metadata) {
2487
+ const appConfig = config.publish.app_store;
2488
+ const auth = appConfig.auth;
2489
+ const testflightConfig = appConfig.testflight;
2490
+ const retryConfig = config.retry;
2491
+ logger.info("Starting TestFlight upload...");
2492
+ try {
2493
+ const exists = await import_fs_extra7.default.pathExists(filePath);
2494
+ if (!exists) {
2495
+ throw new Error(`IPA file not found: ${filePath}`);
2496
+ }
2497
+ const fileSize = (await import_fs_extra7.default.stat(filePath)).size;
2498
+ logger.info(`IPA file size: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2499
+ const jwtGenerator = await this.loadJWTGenerator(auth);
2500
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2501
+ logger.info("Generating JWT token...");
2502
+ const jwt = jwtGenerator.generate();
2503
+ const bundleId = metadata.platform?.includes("ios") ? this.extractBundleId(filePath) : null;
2504
+ if (!bundleId) {
2505
+ throw new Error("Could not determine app bundle ID from IPA");
2506
+ }
2507
+ logger.info(`App bundle ID: ${bundleId}`);
2508
+ logger.info("Creating build record for TestFlight...");
2509
+ const buildResult = await retryStrategy.execute(
2510
+ () => this.createBuild(jwt, bundleId, metadata.version),
2511
+ "TestFlight create build"
2512
+ );
2513
+ if (!buildResult.success || !buildResult.data) {
2514
+ throw buildResult.error || new Error("Failed to create build record");
2515
+ }
2516
+ const buildId = buildResult.data;
2517
+ logger.info(`Build created: ${buildId}`);
2518
+ logger.info("Uploading IPA file to TestFlight (this may take a while)...");
2519
+ const uploadResult = await retryStrategy.execute(
2520
+ () => this.uploadIPAFile(jwt, buildId, filePath),
2521
+ "TestFlight upload file"
2522
+ );
2523
+ if (!uploadResult.success) {
2524
+ throw uploadResult.error || new Error("IPA upload failed");
2525
+ }
2526
+ logger.info("Waiting for build processing (this may take 5-10 minutes)...");
2527
+ await this.waitForBuildProcessing(jwt, buildId, _TestFlightUploader.BUILD_PROCESSING_TIMEOUT);
2528
+ logger.success("Build processing completed");
2529
+ logger.info("Creating Beta Build Version...");
2530
+ const betaBuildResult = await retryStrategy.execute(
2531
+ () => this.createBetaBuildVersion(jwt, buildId),
2532
+ "TestFlight create beta version"
2533
+ );
2534
+ if (!betaBuildResult.success) {
2535
+ logger.warn("Could not create Beta Build Version automatically");
2536
+ }
2537
+ if (testflightConfig?.betaTesters && testflightConfig.betaTesters.length > 0) {
2538
+ logger.info("Adding beta testers...");
2539
+ await this.addBetaTesters(jwt, buildId, testflightConfig.betaTesters, retryStrategy);
2540
+ logger.success("Beta testers added");
2541
+ }
2542
+ if (testflightConfig?.betaBuildLocalization && testflightConfig.betaBuildLocalization.length > 0) {
2543
+ logger.info("Adding beta build localization...");
2544
+ await this.addBetaBuildLocalization(
2545
+ jwt,
2546
+ buildId,
2547
+ testflightConfig.betaBuildLocalization,
2548
+ retryStrategy
2549
+ );
2550
+ logger.success("Beta build localization added");
2551
+ }
2552
+ if (testflightConfig?.autoNotify !== false && testflightConfig?.betaTesters?.length) {
2553
+ logger.info("Notifying beta testers...");
2554
+ await this.notifyBetaTesters(jwt, buildId, metadata.changelog || "New TestFlight build");
2555
+ logger.success("Beta testers notified");
2556
+ }
2557
+ logger.success("TestFlight upload successful!");
2558
+ return {
2559
+ platform: "testflight",
2560
+ success: true,
2561
+ message: "Build uploaded to TestFlight and configured for beta testing",
2562
+ url: `https://appstoreconnect.apple.com/apps/${bundleId}/testflight/builds`
2563
+ };
2564
+ } catch (error) {
2565
+ logger.error(`TestFlight upload failed: ${error.message}`);
2566
+ if (error.response?.data) {
2567
+ logger.info(`Error Data: ${JSON.stringify(error.response.data)}`);
2568
+ }
2569
+ return {
2570
+ platform: "testflight",
2571
+ success: false,
2572
+ message: error.message,
2573
+ error
2574
+ };
2575
+ }
2576
+ }
2577
+ /**
2578
+ * 加载 JWT 生成器
2579
+ * @param auth 认证信息
2580
+ */
2581
+ async loadJWTGenerator(auth) {
2582
+ if (auth.privateKeyContent) {
2583
+ return AppleJWTGenerator.fromContent(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyContent);
2584
+ } else if (auth.privateKeyPath) {
2585
+ return await AppleJWTGenerator.fromFile(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyPath);
2586
+ } else {
2587
+ throw new Error("No Apple private key provided");
2588
+ }
2589
+ }
2590
+ /**
2591
+ * 提取 Bundle ID
2592
+ * @param ipaPath IPA 路径
2593
+ */
2594
+ extractBundleId(ipaPath) {
2595
+ return null;
2596
+ }
2597
+ /**
2598
+ * 创建构建记录
2599
+ * @param jwt JWT
2600
+ * @param bundleId Bundle ID
2601
+ * @param version 版本号
2602
+ */
2603
+ async createBuild(jwt, bundleId, version) {
2604
+ try {
2605
+ const response = await import_axios5.default.post(
2606
+ `${_TestFlightUploader.API_ROOT}/builds`,
2607
+ {
2608
+ data: {
2609
+ type: "builds",
2610
+ attributes: {
2611
+ version,
2612
+ uploadedDate: (/* @__PURE__ */ new Date()).toISOString()
2613
+ },
2614
+ relationships: {
2615
+ app: {
2616
+ data: {
2617
+ type: "apps",
2618
+ id: bundleId
2619
+ }
2620
+ }
2621
+ }
2622
+ }
2623
+ },
2624
+ {
2625
+ headers: {
2626
+ Authorization: `Bearer ${jwt}`,
2627
+ "Content-Type": "application/json"
2628
+ },
2629
+ timeout: _TestFlightUploader.API_TIMEOUT
2630
+ }
2631
+ );
2632
+ return response.data.data.id;
2633
+ } catch (error) {
2634
+ if (error.response?.status === 401) {
2635
+ throw new Error("Authentication failed: Invalid JWT or API credentials");
2636
+ }
2637
+ throw error;
2638
+ }
2639
+ }
2640
+ /**
2641
+ * 上传 IPA 文件
2642
+ * @param jwt JWT
2643
+ * @param buildId 构建 ID
2644
+ * @param filePath 文件路径
2645
+ */
2646
+ async uploadIPAFile(jwt, buildId, filePath) {
2647
+ const form = new import_form_data4.default();
2648
+ form.append("file", import_fs_extra7.default.createReadStream(filePath));
2649
+ try {
2650
+ await import_axios5.default.post(
2651
+ `${_TestFlightUploader.API_ROOT}/builds/${buildId}/appStoreVersionExternalTestingBuilds`,
2652
+ form,
2653
+ {
2654
+ headers: {
2655
+ Authorization: `Bearer ${jwt}`,
2656
+ ...form.getHeaders()
2657
+ },
2658
+ timeout: 5 * 60 * 1e3,
2659
+ maxContentLength: Infinity,
2660
+ maxBodyLength: Infinity
2661
+ }
2662
+ );
2663
+ } catch (error) {
2664
+ throw new Error(`Failed to upload IPA: ${error.message}`);
2665
+ }
2666
+ }
2667
+ /**
2668
+ * 等待构建处理
2669
+ * @param jwt JWT
2670
+ * @param buildId 构建 ID
2671
+ * @param timeoutMs 超时时间
2672
+ */
2673
+ async waitForBuildProcessing(jwt, buildId, timeoutMs) {
2674
+ const startTime = Date.now();
2675
+ let lastStatus = "PROCESSING";
2676
+ while (Date.now() - startTime < timeoutMs) {
2677
+ try {
2678
+ const response = await import_axios5.default.get(`${_TestFlightUploader.API_ROOT}/builds/${buildId}`, {
2679
+ headers: {
2680
+ Authorization: `Bearer ${jwt}`,
2681
+ "Content-Type": "application/json"
2682
+ },
2683
+ timeout: _TestFlightUploader.API_TIMEOUT
2684
+ });
2685
+ const processingState = response.data.data.attributes.processingState;
2686
+ if (processingState === "READY_FOR_DISTRIBUTION") {
2687
+ logger.success("Build ready for distribution");
2688
+ return;
2689
+ }
2690
+ if (processingState === "FAILED" || processingState === "INVALID") {
2691
+ throw new Error(`Build processing failed with status: ${processingState}`);
2692
+ }
2693
+ if (processingState !== lastStatus) {
2694
+ logger.info(`Build status: ${processingState}`);
2695
+ lastStatus = processingState;
2696
+ }
2697
+ await new Promise(
2698
+ (resolve) => setTimeout(resolve, _TestFlightUploader.BUILD_POLLING_INTERVAL)
2699
+ );
2700
+ } catch (error) {
2701
+ logger.warn(`Error checking build status: ${error.message}`);
2702
+ await new Promise(
2703
+ (resolve) => setTimeout(resolve, _TestFlightUploader.BUILD_POLLING_INTERVAL)
2704
+ );
2705
+ }
2706
+ }
2707
+ throw new Error(`Build processing timeout after ${(timeoutMs / 1e3 / 60).toFixed(1)} minutes.`);
2708
+ }
2709
+ /**
2710
+ * 创建 Beta 版本(使其可测试)
2711
+ * @param jwt JWT
2712
+ * @param buildId 构建 ID
2713
+ */
2714
+ async createBetaBuildVersion(jwt, buildId) {
2715
+ try {
2716
+ const response = await import_axios5.default.post(
2717
+ `${_TestFlightUploader.API_ROOT}/betaBuildVersions`,
2718
+ {
2719
+ data: {
2720
+ type: "betaBuildVersions",
2721
+ attributes: {},
2722
+ relationships: {
2723
+ build: {
2724
+ data: {
2725
+ type: "builds",
2726
+ id: buildId
2727
+ }
2728
+ }
2729
+ }
2730
+ }
2731
+ },
2732
+ {
2733
+ headers: {
2734
+ Authorization: `Bearer ${jwt}`,
2735
+ "Content-Type": "application/json"
2736
+ },
2737
+ timeout: _TestFlightUploader.API_TIMEOUT
2738
+ }
2739
+ );
2740
+ return response.data.data.id;
2741
+ } catch (error) {
2742
+ throw new Error(`Failed to create Beta Build Version: ${error.message}`);
2743
+ }
2744
+ }
2745
+ /**
2746
+ * Add beta testers to the build
2747
+ */
2748
+ async addBetaTesters(jwt, buildId, testers, retryStrategy) {
2749
+ for (const testerEmail of testers) {
2750
+ try {
2751
+ await retryStrategy.execute(
2752
+ () => this.addBetaTesterToGroup(jwt, testerEmail, buildId),
2753
+ `TestFlight add tester ${testerEmail}`
2754
+ );
2755
+ logger.info(`\u2713 Added tester: ${testerEmail}`);
2756
+ } catch (error) {
2757
+ logger.warn(`Failed to add tester ${testerEmail}: ${error.message}`);
2758
+ }
2759
+ }
2760
+ }
2761
+ /**
2762
+ * 添加单个测试员到组
2763
+ * @param jwt JWT
2764
+ * @param testerEmail 测试员邮箱
2765
+ * @param buildId 构建 ID
2766
+ */
2767
+ async addBetaTesterToGroup(jwt, testerEmail, buildId) {
2768
+ try {
2769
+ logger.info(`Attempting to add ${testerEmail} to beta testers...`);
2770
+ } catch (error) {
2771
+ throw new Error(`Failed to add beta tester: ${error.message}`);
2772
+ }
2773
+ }
2774
+ /**
2775
+ * Add localization for beta build
2776
+ */
2777
+ async addBetaBuildLocalization(jwt, buildId, localizations, retryStrategy) {
2778
+ for (const localization of localizations) {
2779
+ try {
2780
+ await retryStrategy.execute(
2781
+ () => this.addLocalizationToBuilder(jwt, buildId, localization),
2782
+ `TestFlight add localization ${localization.locale}`
2783
+ );
2784
+ logger.info(`\u2713 Added localization: ${localization.locale}`);
2785
+ } catch (error) {
2786
+ logger.warn(`Failed to add localization ${localization.locale}: ${error.message}`);
2787
+ }
2788
+ }
2789
+ }
2790
+ /**
2791
+ * Add single localization
2792
+ */
2793
+ async addLocalizationToBuilder(jwt, buildId, localization) {
2794
+ try {
2795
+ await import_axios5.default.post(
2796
+ `${_TestFlightUploader.API_ROOT}/betaBuildLocalizations`,
2797
+ {
2798
+ data: {
2799
+ type: "betaBuildLocalizations",
2800
+ attributes: {
2801
+ locale: localization.locale,
2802
+ description: localization.description,
2803
+ keywords: localization.keywords?.join(",") || ""
2804
+ },
2805
+ relationships: {
2806
+ build: {
2807
+ data: {
2808
+ type: "betaBuildVersions",
2809
+ id: buildId
2810
+ }
2811
+ }
2812
+ }
2813
+ }
2814
+ },
2815
+ {
2816
+ headers: {
2817
+ Authorization: `Bearer ${jwt}`,
2818
+ "Content-Type": "application/json"
2819
+ },
2820
+ timeout: _TestFlightUploader.API_TIMEOUT
2821
+ }
2822
+ );
2823
+ } catch (error) {
2824
+ throw new Error(`Failed to add localization: ${error.message}`);
2825
+ }
2826
+ }
2827
+ /**
2828
+ * 通知测试员
2829
+ * @param jwt JWT
2830
+ * @param buildId 构建 ID
2831
+ * @param message 消息
2832
+ */
2833
+ async notifyBetaTesters(jwt, buildId, message) {
2834
+ try {
2835
+ logger.info("Sending notification to beta testers...");
2836
+ } catch (error) {
2837
+ logger.warn(`Failed to notify testers: ${error.message}`);
2838
+ }
2839
+ }
2840
+ };
2841
+
2842
+ // src/adapters/adhoc_uploader.ts
2843
+ var import_fs_extra8 = __toESM(require("fs-extra"), 1);
2844
+ var import_path5 = __toESM(require("path"), 1);
2845
+ var import_child_process2 = require("child_process");
2846
+ var AdHocUploader = class {
2847
+ name = "AdHoc";
2848
+ /**
2849
+ * 验证配置
2850
+ * @param config 配置对象
2851
+ * @returns 是否有效
2852
+ */
2853
+ validateConfig(config) {
2854
+ if (!config?.publish?.app_store?.enable) return false;
2855
+ const appConfig = config.publish.app_store;
2856
+ const mode = appConfig?.mode;
2857
+ if (mode !== "adhoc") return false;
2858
+ const adhocConfig = appConfig?.adhoc;
2859
+ if (!adhocConfig) {
2860
+ logger.error("Ad Hoc config missing: adhoc configuration");
2861
+ return false;
2862
+ }
2863
+ return true;
2864
+ }
2865
+ /**
2866
+ * 判断是否支持该文件
2867
+ * @param filePath 文件路径
2868
+ * @returns 是否支持
2869
+ */
2870
+ canHandle(filePath) {
2871
+ const ext = filePath.split(".").pop()?.toLowerCase();
2872
+ return ext === "ipa";
2873
+ }
2874
+ /**
2875
+ * 执行上传(生成 Ad Hoc 分发包)
2876
+ * @param filePath 文件路径
2877
+ * @param config 配置
2878
+ * @param metadata 元数据
2879
+ */
2880
+ async upload(filePath, config, metadata) {
2881
+ const appConfig = config.publish.app_store;
2882
+ const adhocConfig = appConfig.adhoc;
2883
+ const retryConfig = config.retry;
2884
+ logger.info("Starting Ad Hoc distribution setup...");
2885
+ try {
2886
+ const exists = await import_fs_extra8.default.pathExists(filePath);
2887
+ if (!exists) {
2888
+ throw new Error(`IPA file not found: ${filePath}`);
2889
+ }
2890
+ const fileSize = (await import_fs_extra8.default.stat(filePath)).size;
2891
+ logger.info(`IPA file size: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2892
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2893
+ const bundleId = this.extractBundleId(filePath);
2894
+ if (!bundleId) {
2895
+ logger.warn("Could not determine app bundle ID from IPA");
2896
+ } else {
2897
+ logger.info(`App bundle ID: ${bundleId}`);
2898
+ }
2899
+ logger.info("Verifying Ad Hoc provisioning profile...");
2900
+ const profileInfo = this.verifyProvisioningProfile(
2901
+ adhocConfig.provisioningProfileSpecifier,
2902
+ adhocConfig.teamId
2903
+ );
2904
+ logger.info("Creating Ad Hoc distribution manifest...");
2905
+ const manifestPath = await this.createManifest(
2906
+ filePath,
2907
+ metadata.version,
2908
+ bundleId,
2909
+ metadata.changelog
2910
+ );
2911
+ logger.info("Setting up distribution directory...");
2912
+ const distributionPath = await this.setupDistributionDirectory(filePath, manifestPath);
2913
+ logger.info("Generating installation links...");
2914
+ const installUrl = this.generateInstallUrl(distributionPath, bundleId);
2915
+ const qrCodePath = await this.generateQRCode(installUrl, distributionPath);
2916
+ this.outputDistributionInfo(installUrl, qrCodePath, distributionPath, profileInfo);
2917
+ logger.success("Ad Hoc distribution setup completed!");
2918
+ return {
2919
+ platform: "adhoc",
2920
+ success: true,
2921
+ message: `Ad Hoc package ready for distribution. Install link and QR code generated.`,
2922
+ url: installUrl
2923
+ };
2924
+ } catch (error) {
2925
+ logger.error(`Ad Hoc setup failed: ${error.message}`);
2926
+ return {
2927
+ platform: "adhoc",
2928
+ success: false,
2929
+ message: error.message,
2930
+ error
2931
+ };
2932
+ }
2933
+ }
2934
+ /**
2935
+ * 从 IPA 提取 Bundle ID
2936
+ * @param ipaPath IPA 路径
2937
+ */
2938
+ extractBundleId(ipaPath) {
2939
+ try {
2940
+ return null;
2941
+ } catch (error) {
2942
+ logger.warn(`Failed to extract bundle ID: ${error.message}`);
2943
+ return null;
2944
+ }
2945
+ }
2946
+ /**
2947
+ * 验证 Provisioning Profile
2948
+ * @param profileSpecifier Profile 名称
2949
+ * @param teamId 团队 ID
2950
+ */
2951
+ verifyProvisioningProfile(profileSpecifier, teamId) {
2952
+ if (!profileSpecifier) {
2953
+ logger.warn("No provisioning profile specified, will use automatic signing");
2954
+ return {
2955
+ name: "Automatic",
2956
+ teamId: teamId || "Unknown",
2957
+ capacity: 100,
2958
+ usedSlots: 0
2959
+ };
2960
+ }
2961
+ logger.info(`Using provisioning profile: ${profileSpecifier}`);
2962
+ return {
2963
+ name: profileSpecifier,
2964
+ teamId: teamId || "Unknown",
2965
+ capacity: 100,
2966
+ usedSlots: 0
2967
+ };
2968
+ }
2969
+ /**
2970
+ * 创建 manifest.plist 文件
2971
+ * @param ipaPath IPA 路径
2972
+ * @param version 版本号
2973
+ * @param bundleId Bundle ID
2974
+ * @param changelog 更新日志
2975
+ */
2976
+ async createManifest(ipaPath, version, bundleId, changelog) {
2977
+ const ipaFileName = import_path5.default.basename(ipaPath);
2978
+ const appName = bundleId || import_path5.default.parse(ipaFileName).name;
2979
+ const ipaUrl = `itms-services://?action=download-manifest&url=https://your-distribution-server.com/manifests/${ipaFileName}.plist`;
2980
+ const manifestContent = `<?xml version="1.0" encoding="UTF-8"?>
2981
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2982
+ <plist version="1.0">
2983
+ <dict>
2984
+ <key>items</key>
2985
+ <array>
2986
+ <dict>
2987
+ <key>assets</key>
2988
+ <array>
2989
+ <dict>
2990
+ <key>kind</key>
2991
+ <string>software-package</string>
2992
+ <key>url</key>
2993
+ <string>https://your-distribution-server.com/apps/${ipaFileName}</string>
2994
+ </dict>
2995
+ <dict>
2996
+ <key>kind</key>
2997
+ <string>display-image</string>
2998
+ <key>url</key>
2999
+ <string>https://your-distribution-server.com/icons/app-icon.png</string>
3000
+ </dict>
3001
+ <dict>
3002
+ <key>kind</key>
3003
+ <string>full-size-image</string>
3004
+ <key>url</key>
3005
+ <string>https://your-distribution-server.com/icons/app-icon-large.png</string>
3006
+ </dict>
3007
+ </array>
3008
+ <key>metadata</key>
3009
+ <dict>
3010
+ <key>bundle-identifier</key>
3011
+ <string>${bundleId || "com.example.app"}</string>
3012
+ <key>bundle-version</key>
3013
+ <string>${version}</string>
3014
+ <key>kind</key>
3015
+ <string>software</string>
3016
+ <key>title</key>
3017
+ <string>${appName}</string>
3018
+ <key>subtitle</key>
3019
+ <string>${changelog || "New release"}</string>
3020
+ </dict>
3021
+ </dict>
3022
+ </array>
3023
+ </dict>
3024
+ </plist>`;
3025
+ const manifestPath = `${ipaPath}.plist`;
3026
+ await import_fs_extra8.default.writeFile(manifestPath, manifestContent);
3027
+ logger.info(`Manifest created: ${manifestPath}`);
3028
+ return manifestPath;
3029
+ }
3030
+ /**
3031
+ * 设置分发目录结构
3032
+ * @param ipaPath IPA 路径
3033
+ * @param manifestPath Manifest 路径
3034
+ */
3035
+ async setupDistributionDirectory(ipaPath, manifestPath) {
3036
+ const projectRoot = process.cwd();
3037
+ const distributionDir = import_path5.default.join(projectRoot, "build", "adhoc-distribution");
3038
+ await import_fs_extra8.default.ensureDir(distributionDir);
3039
+ await import_fs_extra8.default.ensureDir(import_path5.default.join(distributionDir, "apps"));
3040
+ await import_fs_extra8.default.ensureDir(import_path5.default.join(distributionDir, "manifests"));
3041
+ await import_fs_extra8.default.ensureDir(import_path5.default.join(distributionDir, "icons"));
3042
+ const ipaFileName = import_path5.default.basename(ipaPath);
3043
+ await import_fs_extra8.default.copy(ipaPath, import_path5.default.join(distributionDir, "apps", ipaFileName));
3044
+ await import_fs_extra8.default.copy(manifestPath, import_path5.default.join(distributionDir, "manifests", `${ipaFileName}.plist`));
3045
+ logger.info(`Distribution directory: ${distributionDir}`);
3046
+ return distributionDir;
3047
+ }
3048
+ /**
3049
+ * 生成安装链接 (itms-services)
3050
+ * @param distributionPath 分发目录
3051
+ * @param bundleId Bundle ID
3052
+ */
3053
+ generateInstallUrl(distributionPath, bundleId) {
3054
+ const manifestPath = import_path5.default.join(distributionPath, "manifests", `*.plist`);
3055
+ return `itms-services://?action=download-manifest&url=file://${manifestPath}`;
3056
+ }
3057
+ /**
3058
+ * 生成二维码
3059
+ * @param url 安装链接
3060
+ * @param distributionPath 分发目录
3061
+ */
3062
+ async generateQRCode(url, distributionPath) {
3063
+ const qrCodePath = import_path5.default.join(distributionPath, "install-qrcode.png");
3064
+ try {
3065
+ logger.info(`QR code would be saved to: ${qrCodePath}`);
3066
+ logger.info(`Install URL: ${url}`);
3067
+ return qrCodePath;
3068
+ } catch (error) {
3069
+ logger.warn(`Failed to generate QR code: ${error.message}`);
3070
+ return "";
3071
+ }
3072
+ }
3073
+ /**
3074
+ * 输出分发信息
3075
+ * @param installUrl 安装链接
3076
+ * @param qrCodePath 二维码路径
3077
+ * @param distributionPath 分发目录
3078
+ * @param profileInfo Profile 信息
3079
+ */
3080
+ outputDistributionInfo(installUrl, qrCodePath, distributionPath, profileInfo) {
3081
+ logger.newLine();
3082
+ logger.title("\u{1F4F1} Ad Hoc Distribution Setup Complete");
3083
+ logger.info(`App Name: ${profileInfo.name}`);
3084
+ logger.info(`Team ID: ${profileInfo.teamId}`);
3085
+ logger.info(`Device Capacity: ${profileInfo.capacity}`);
3086
+ logger.info(`Used Slots: ${profileInfo.usedSlots}/${profileInfo.capacity}`);
3087
+ logger.newLine();
3088
+ logger.info("\u{1F4E6} Distribution Files:");
3089
+ logger.info(` Directory: ${distributionPath}`);
3090
+ logger.info(` IPA: ${import_path5.default.join(distributionPath, "apps", "*.ipa")}`);
3091
+ logger.info(` Manifest: ${import_path5.default.join(distributionPath, "manifests", "*.plist")}`);
3092
+ logger.info(` QR Code: ${qrCodePath}`);
3093
+ logger.newLine();
3094
+ logger.info("\u{1F517} Installation Link:");
3095
+ logger.info(` ${installUrl}`);
3096
+ logger.newLine();
3097
+ logger.info("\u{1F4E4} Distribution Options:");
3098
+ logger.info(" 1. Share via\u84B2\u516C\u82F1: Upload to Pgyer for easy distribution");
3099
+ logger.info(" 2. Share QR code with testers");
3100
+ logger.info(" 3. Host manifest and IPA on your server");
3101
+ logger.info(" 4. Use enterprise distribution service");
3102
+ logger.newLine();
3103
+ logger.info("\u26A0\uFE0F Important:");
3104
+ logger.info(" \u2022 Devices must be registered in your Apple Developer account");
3105
+ logger.info(" \u2022 Maximum 100 devices per app, per year");
3106
+ logger.info(" \u2022 App must be signed with Ad Hoc provisioning profile");
3107
+ logger.info(" \u2022 Cannot be distributed via App Store");
3108
+ }
3109
+ /**
3110
+ * 检查是否安装了 Xcode
3111
+ * @returns 是否安装
3112
+ */
3113
+ checkXcodeInstalled() {
3114
+ try {
3115
+ (0, import_child_process2.execSync)("xcode-select -p", { stdio: "pipe" });
3116
+ return true;
3117
+ } catch {
3118
+ return false;
3119
+ }
3120
+ }
3121
+ /**
3122
+ * 生成 Ad Hoc 导出选项 (ExportOptions.plist)
3123
+ * @param teamId 团队 ID
3124
+ * @param signingIdentity 签名证书
3125
+ * @param provisioningProfile Profile 名称
3126
+ */
3127
+ generateExportOptions(teamId, signingIdentity, provisioningProfile) {
3128
+ const options = `<?xml version="1.0" encoding="UTF-8"?>
3129
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3130
+ <plist version="1.0">
3131
+ <dict>
3132
+ <key>method</key>
3133
+ <string>ad-hoc</string>
3134
+ <key>signingStyle</key>
3135
+ <string>automatic</string>
3136
+ <key>stripSwiftSymbols</key>
3137
+ <true/>
3138
+ <key>teamID</key>
3139
+ <string>${teamId || ""}</string>
3140
+ ${signingIdentity ? `<key>signingCertificate</key><string>${signingIdentity}</string>` : ""}
3141
+ ${provisioningProfile ? `<key>provisioningProfileSpecifier</key><string>${provisioningProfile}</string>` : ""}
3142
+ </dict>
3143
+ </plist>`;
3144
+ return options;
3145
+ }
3146
+ };
3147
+
3148
+ // src/adapters/harmony_uploader.ts
3149
+ var import_fs_extra9 = __toESM(require("fs-extra"), 1);
3150
+ var import_path6 = __toESM(require("path"), 1);
3151
+ var import_axios6 = __toESM(require("axios"), 1);
3152
+ var import_form_data5 = __toESM(require("form-data"), 1);
3153
+ var HarmonyUploader = class _HarmonyUploader {
3154
+ name = "HarmonyOS";
3155
+ static TOKEN_URL = "https://connect-api.cloud.huawei.com/api/oauth2/v1/token";
3156
+ static PUBLISH_API_ROOT = "https://connect-api.cloud.huawei.com/api/publish/v2";
3157
+ validateConfig(config) {
3158
+ if (!config?.publish?.harmony?.enable) return false;
3159
+ const h = config.publish.harmony;
3160
+ if (!h.auth?.clientId || !h.auth?.clientSecret || !h.appId) {
3161
+ logger.error("Harmony config missing: clientId, clientSecret, or appId");
3162
+ return false;
3163
+ }
3164
+ return true;
3165
+ }
3166
+ /**
3167
+ * 判断是否支持该文件
3168
+ * @param filePath 文件路径
3169
+ */
3170
+ canHandle(filePath) {
3171
+ const ext = filePath.split(".").pop()?.toLowerCase();
3172
+ return ext === "hap" || ext === "app";
3173
+ }
3174
+ async upload(filePath, config, metadata) {
3175
+ const harmonyConfig = config.publish.harmony;
3176
+ const clientId = harmonyConfig.auth.clientId;
3177
+ const clientSecret = harmonyConfig.auth.clientSecret;
3178
+ const appId = harmonyConfig.appId;
3179
+ const releaseType = harmonyConfig.releaseType || "draft";
3180
+ const suffix = import_path6.default.extname(filePath).substring(1);
3181
+ const retryConfig = config.retry;
3182
+ logger.info("Starting HarmonyOS AppGallery upload...");
3183
+ try {
3184
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3185
+ logger.info("Authenticating...");
3186
+ const tokenResult = await retryStrategy.execute(
3187
+ () => this.getAccessToken(clientId, clientSecret),
3188
+ "Harmony authentication"
3189
+ );
3190
+ if (!tokenResult.success || !tokenResult.data) {
3191
+ throw tokenResult.error || new Error("Failed to get access token");
3192
+ }
3193
+ const token = tokenResult.data;
3194
+ logger.info("Requesting upload URL...");
3195
+ const uploadInfoResult = await retryStrategy.execute(
3196
+ () => this.getUploadUrl(token, appId, suffix),
3197
+ "Harmony get upload URL"
3198
+ );
3199
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
3200
+ throw uploadInfoResult.error || new Error("Failed to get upload URL");
3201
+ }
3202
+ const uploadInfo = uploadInfoResult.data;
3203
+ logger.info("Uploading HarmonyOS package...");
3204
+ const uploadFileResult = await retryStrategy.execute(
3205
+ () => this.uploadFile(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
3206
+ "Harmony file upload"
3207
+ );
3208
+ if (!uploadFileResult.success) {
3209
+ throw uploadFileResult.error || new Error("File upload failed");
3210
+ }
3211
+ logger.info("Linking file to app...");
3212
+ const updateInfoResult = await retryStrategy.execute(
3213
+ () => this.updateAppFileInfo(token, appId, uploadInfo.authCode, filePath),
3214
+ "Harmony update file info"
3215
+ );
3216
+ if (!updateInfoResult.success) {
3217
+ throw updateInfoResult.error || new Error("Failed to update file info");
3218
+ }
3219
+ if (releaseType === "submit") {
3220
+ logger.info("Submitting to review...");
3221
+ }
3222
+ logger.success("HarmonyOS upload successful!");
3223
+ return {
3224
+ platform: "harmony",
3225
+ success: true,
3226
+ message: "Upload success",
3227
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
3228
+ };
3229
+ } catch (error) {
3230
+ logger.error(`HarmonyOS upload failed: ${error.message}`);
3231
+ return {
3232
+ platform: "harmony",
3233
+ success: false,
3234
+ message: error.message,
3235
+ error
3236
+ };
3237
+ }
3238
+ }
3239
+ /**
3240
+ * 获取 Access Token
3241
+ * @param clientId 客户端 ID
3242
+ * @param clientSecret 客户端密钥
3243
+ */
3244
+ async getAccessToken(clientId, clientSecret) {
3245
+ const data = {
3246
+ client_id: clientId,
3247
+ client_secret: clientSecret,
3248
+ grant_type: "client_credentials"
3249
+ };
3250
+ const res = await import_axios6.default.post(_HarmonyUploader.TOKEN_URL, data);
3251
+ if (!res.data.access_token) {
3252
+ throw new Error("Failed to get access token");
3253
+ }
3254
+ return res.data.access_token;
3255
+ }
3256
+ /**
3257
+ * 获取上传 URL
3258
+ * @param token Token
3259
+ * @param appId 应用 ID
3260
+ * @param suffix 后缀
3261
+ */
3262
+ async getUploadUrl(token, appId, suffix) {
3263
+ const res = await import_axios6.default.get(`${_HarmonyUploader.PUBLISH_API_ROOT}/upload-url`, {
3264
+ params: { appId, suffix },
3265
+ headers: { Authorization: `Bearer ${token}`, client_id: appId }
3266
+ });
3267
+ if (res.data.code != "0") {
3268
+ throw new Error(`Get upload url failed: ${res.data.msg}`);
3269
+ }
3270
+ return {
3271
+ uploadUrl: res.data.uploadUrl,
3272
+ authCode: res.data.authCode
3273
+ };
3274
+ }
3275
+ async uploadFile(uploadUrl, authCode, filePath) {
3276
+ const form = new import_form_data5.default();
3277
+ form.append("file", import_fs_extra9.default.createReadStream(filePath));
3278
+ form.append("authCode", authCode);
3279
+ form.append("fileCount", "1");
3280
+ const res = await import_axios6.default.post(uploadUrl, form, {
3281
+ headers: { ...form.getHeaders() },
3282
+ maxContentLength: Infinity,
3283
+ maxBodyLength: Infinity
3284
+ });
3285
+ if (res.data.result.resultCode != "0") {
3286
+ throw new Error(`File upload failed: ${JSON.stringify(res.data.result)}`);
3287
+ }
3288
+ }
3289
+ /**
3290
+ * 更新应用文件信息
3291
+ * @param token Token
3292
+ * @param appId 应用 ID
3293
+ * @param authCode 授权码
3294
+ * @param filePath 文件路径
3295
+ */
3296
+ async updateAppFileInfo(token, appId, authCode, filePath) {
3297
+ const fileName = import_path6.default.basename(filePath);
3298
+ const body = {
3299
+ fileType: 7,
3300
+ // 鸿蒙包的 fileType(需要根据华为最新文档确认)
3301
+ files: [
3302
+ {
3303
+ fileName,
3304
+ fileDestUrl: authCode
3305
+ }
3306
+ ]
3307
+ };
3308
+ const res = await import_axios6.default.put(`${_HarmonyUploader.PUBLISH_API_ROOT}/app-file-info`, body, {
3309
+ params: { appId },
3310
+ headers: { Authorization: `Bearer ${token}`, client_id: appId }
3311
+ });
3312
+ if (res.data.ret.code != 0) {
3313
+ throw new Error(`Update file info failed: ${res.data.ret.msg}`);
3314
+ }
3315
+ }
3316
+ };
3317
+
3318
+ // src/adapters/oppo_uploader.ts
3319
+ var import_fs_extra10 = __toESM(require("fs-extra"), 1);
3320
+ var import_path7 = __toESM(require("path"), 1);
3321
+ var import_axios7 = __toESM(require("axios"), 1);
3322
+ var import_form_data6 = __toESM(require("form-data"), 1);
3323
+ var import_crypto4 = __toESM(require("crypto"), 1);
3324
+ var OppoUploader = class _OppoUploader {
3325
+ name = "OPPO";
3326
+ /** OPPO 开放 API 基础地址 */
3327
+ static API_BASE = "https://oop-openapi-cn.heytapmobi.com";
3328
+ /** 获取 token 接口 */
3329
+ static TOKEN_API = `${_OppoUploader.API_BASE}/developer/v1/token`;
3330
+ /** 获取上传 URL 接口 */
3331
+ static UPLOAD_URL_API = `${_OppoUploader.API_BASE}/resource/v1/upload/get-upload-url`;
3332
+ /** 上传完成后提交版本 */
3333
+ static SUBMIT_API = `${_OppoUploader.API_BASE}/resource/v1/app/upd`;
3334
+ /** 查询应详情接口 */
3335
+ static APP_INFO_API = `${_OppoUploader.API_BASE}/resource/v1/app/info`;
3336
+ /**
3337
+ * OPPO API 签名生成
3338
+ * OPPO 使用 HMAC-SHA256 签名机制
3339
+ */
3340
+ generateSign(params, clientSecret) {
3341
+ const sorted = Object.keys(params).sort().filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3342
+ return import_crypto4.default.createHmac("sha256", clientSecret).update(sorted).digest("hex");
3343
+ }
3344
+ validateConfig(config) {
3345
+ if (!config?.publish?.oppo?.enable) return false;
3346
+ const oppo = config.publish.oppo;
3347
+ if (!oppo.auth?.clientId || !oppo.auth?.clientSecret) {
3348
+ logger.error("OPPO config missing: clientId or clientSecret");
3349
+ return false;
3350
+ }
3351
+ return true;
3352
+ }
3353
+ canHandle(filePath) {
3354
+ const ext = filePath.split(".").pop()?.toLowerCase();
3355
+ return ext === "apk";
3356
+ }
3357
+ /**
3358
+ * 尝试从文件名推断包名
3359
+ */
3360
+ inferPackageName(filePath) {
3361
+ const fileName = import_path7.default.basename(filePath);
3362
+ const match = fileName.match(/^([\w.]+?)(?:-(?:release|debug|unsigned))?\.apk$/i);
3363
+ if (match && match[1].includes(".")) {
3364
+ return match[1];
3365
+ }
3366
+ return null;
3367
+ }
3368
+ /**
3369
+ * 从包名推断应用名称
3370
+ */
3371
+ inferAppName(packageName) {
3372
+ const parts = packageName.split(".");
3373
+ if (parts.length === 0) return null;
3374
+ const lastPart = parts[parts.length - 1];
3375
+ return lastPart.charAt(0).toUpperCase() + lastPart.slice(1);
3376
+ }
3377
+ async upload(filePath, config, metadata) {
3378
+ const oppoConfig = config.publish.oppo;
3379
+ const clientId = oppoConfig.auth.clientId;
3380
+ const clientSecret = oppoConfig.auth.clientSecret;
3381
+ const packageName = oppoConfig.packageName || this.inferPackageName(filePath);
3382
+ if (!packageName) {
3383
+ return {
3384
+ platform: "oppo",
3385
+ success: false,
3386
+ message: "\u65E0\u6CD5\u83B7\u53D6\u5305\u540D (packageName)\uFF0C\u8BF7\u5728\u914D\u7F6E\u4E2D\u6307\u5B9A\u6216\u786E\u4FDD\u6587\u4EF6\u540D\u5305\u542B\u5305\u540D",
3387
+ consoleUrl: "https://open.oppomobile.com/new/ecology/app"
3388
+ };
3389
+ }
3390
+ const retryConfig = config.retry;
3391
+ const consoleUrl = "https://open.oppomobile.com/new/ecology/app";
3392
+ if (!import_fs_extra10.default.existsSync(filePath)) {
3393
+ return {
3394
+ platform: "oppo",
3395
+ success: false,
3396
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`,
3397
+ consoleUrl
3398
+ };
3399
+ }
3400
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 OPPO \u5E94\u7528\u5546\u5E97...");
3401
+ logger.info(`\u6587\u4EF6: ${filePath}`);
3402
+ try {
3403
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3404
+ logger.info("\u6B63\u5728\u83B7\u53D6 access_token...");
3405
+ const tokenResult = await retryStrategy.execute(
3406
+ () => this.getAccessToken(clientId, clientSecret),
3407
+ "OPPO authentication"
3408
+ );
3409
+ if (!tokenResult.success || !tokenResult.data) {
3410
+ throw tokenResult.error || new Error("Failed to get access token");
3411
+ }
3412
+ const accessToken = tokenResult.data;
3413
+ logger.info("\u6B63\u5728\u83B7\u53D6\u73B0\u6709\u5E94\u7528\u8BE6\u60C5...");
3414
+ const appInfoResult = await retryStrategy.execute(
3415
+ () => this.getAppInfo(accessToken, clientSecret, packageName),
3416
+ "OPPO get app info"
3417
+ );
3418
+ const onlineAppInfo = appInfoResult.data || {};
3419
+ if (onlineAppInfo) {
3420
+ logger.info(
3421
+ `\u83B7\u53D6\u5230\u7EBF\u4E0A\u4FE1\u606F: ${onlineAppInfo.app_name} (Category: ${onlineAppInfo.second_category_id})`
3422
+ );
3423
+ logger.info(`[OPPO AppInfo Full] ${JSON.stringify(onlineAppInfo)}`);
3424
+ }
3425
+ logger.info("\u6B63\u5728\u83B7\u53D6\u4E0A\u4F20\u5730\u5740...");
3426
+ const uploadUrlResult = await retryStrategy.execute(
3427
+ () => this.getUploadUrl(accessToken, clientSecret),
3428
+ "OPPO get upload URL"
3429
+ );
3430
+ if (!uploadUrlResult.success || !uploadUrlResult.data) {
3431
+ throw uploadUrlResult.error || new Error("Failed to get upload URL");
3432
+ }
3433
+ const { uploadUrl, sign: uploadSign } = uploadUrlResult.data;
3434
+ logger.info("\u6B63\u5728\u4E0A\u4F20 APK \u6587\u4EF6...");
3435
+ const uploadFileResult = await retryStrategy.execute(
3436
+ () => this.uploadFile(uploadUrl, uploadSign, filePath),
3437
+ "OPPO file upload"
3438
+ );
3439
+ if (!uploadFileResult.success || !uploadFileResult.data) {
3440
+ throw uploadFileResult.error || new Error("File upload failed");
3441
+ }
3442
+ const rawUrl = uploadFileResult.data.url;
3443
+ const fileUrl = rawUrl.replace(/^http:\/\//i, "https://").replace("storedl1.nearme.com.cn", "storedl.nearme.com.cn");
3444
+ const md5 = uploadFileResult.data.md5;
3445
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u7248\u672C\u4FE1\u606F...");
3446
+ const submitResult = await retryStrategy.execute(
3447
+ () => this.submitVersion({
3448
+ accessToken,
3449
+ clientSecret,
3450
+ packageName,
3451
+ appName: oppoConfig.appName || metadata.appName || onlineAppInfo.app_name || this.inferAppName(packageName),
3452
+ fileUrl,
3453
+ fileMd5: md5,
3454
+ versionName: metadata.version,
3455
+ versionCode: metadata.buildNumber,
3456
+ updateDesc: metadata.changelog || "App Update",
3457
+ onlineType: oppoConfig.onlineType,
3458
+ // 从配置读取
3459
+ onlineAppInfo
3460
+ // 传入线上信息
3461
+ }),
3462
+ "OPPO submit version"
3463
+ );
3464
+ if (!submitResult.success) {
3465
+ throw submitResult.error || new Error("Submit version failed");
3466
+ }
3467
+ logger.success("\u4E0A\u4F20\u5230 OPPO \u5E94\u7528\u5546\u5E97\u6210\u529F!");
3468
+ return {
3469
+ platform: "oppo",
3470
+ success: true,
3471
+ message: "\u4E0A\u4F20\u6210\u529F, \u8BF7\u524D\u5F80\u540E\u53F0\u786E\u8BA4\u5E76\u63D0\u4EA4\u5BA1\u6838",
3472
+ consoleUrl
3473
+ };
3474
+ } catch (error) {
3475
+ logger.error(`\u4E0A\u4F20\u5230 OPPO \u5931\u8D25: ${error.message}`);
3476
+ return {
3477
+ platform: "oppo",
3478
+ success: false,
3479
+ message: this.formatError(error),
3480
+ error,
3481
+ consoleUrl
3482
+ };
3483
+ }
3484
+ }
3485
+ /**
3486
+ * 获取 access_token
3487
+ * 官方文档: https://open.oppomobile.com/documentation/page/info?id=10998
3488
+ */
3489
+ async getAccessToken(clientId, clientSecret) {
3490
+ const params = {
3491
+ client_id: clientId,
3492
+ client_secret: clientSecret
3493
+ };
3494
+ logger.info(`[OPPO Auth Debug] clientId: ${clientId}`);
3495
+ logger.info(`[OPPO Auth Debug] clientSecret length: ${clientSecret?.length || 0}`);
3496
+ logger.info(`[OPPO Auth Debug] params: ${JSON.stringify(params)}`);
3497
+ const res = await import_axios7.default.get(_OppoUploader.TOKEN_API, {
3498
+ params,
3499
+ timeout: 15e3
3500
+ });
3501
+ logger.info(`[OPPO Auth Response] status: ${res.status}, data: ${JSON.stringify(res.data)}`);
3502
+ if (res.data.errno !== 0) {
3503
+ throw new Error(`\u83B7\u53D6 token \u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3504
+ }
3505
+ return res.data.data.access_token;
3506
+ }
3507
+ /**
3508
+ * 获取应用详情
3509
+ */
3510
+ async getAppInfo(accessToken, clientSecret, packageName) {
3511
+ const timestamp = Math.floor(Date.now() / 1e3);
3512
+ const params = {
3513
+ access_token: accessToken,
3514
+ pkg_name: packageName,
3515
+ timestamp
3516
+ };
3517
+ const apiSign = this.generateSign(params, clientSecret);
3518
+ try {
3519
+ const res = await import_axios7.default.get(_OppoUploader.APP_INFO_API, {
3520
+ params: {
3521
+ ...params,
3522
+ api_sign: apiSign
3523
+ },
3524
+ timeout: 15e3
3525
+ });
3526
+ if (res.data.errno !== 0) {
3527
+ logger.warn(`\u83B7\u53D6\u5E94\u7528\u8BE6\u60C5\u5931\u8D25 (\u975E\u81F4\u547D): ${JSON.stringify(res.data)}`);
3528
+ return null;
3529
+ }
3530
+ return res.data.data;
3531
+ } catch (error) {
3532
+ logger.warn(`\u83B7\u53D6\u5E94\u7528\u8BE6\u60C5\u8BF7\u6C42\u5F02\u5E38 (\u975E\u81F4\u547D): ${error.message}`);
3533
+ return null;
3534
+ }
3535
+ }
3536
+ /**
3537
+ * 获取上传地址
3538
+ */
3539
+ async getUploadUrl(accessToken, clientSecret) {
3540
+ const timestamp = Math.floor(Date.now() / 1e3);
3541
+ const params = {
3542
+ access_token: accessToken,
3543
+ timestamp
3544
+ };
3545
+ const apiSign = this.generateSign(params, clientSecret);
3546
+ const res = await import_axios7.default.get(_OppoUploader.UPLOAD_URL_API, {
3547
+ params: {
3548
+ ...params,
3549
+ api_sign: apiSign
3550
+ },
3551
+ timeout: 15e3
3552
+ });
3553
+ if (res.data.errno !== 0) {
3554
+ throw new Error(`\u83B7\u53D6\u4E0A\u4F20\u5730\u5740\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3555
+ }
3556
+ return {
3557
+ uploadUrl: res.data.data.upload_url,
3558
+ sign: res.data.data.sign
3559
+ };
3560
+ }
3561
+ /**
3562
+ * 上传 APK 文件
3563
+ */
3564
+ async uploadFile(uploadUrl, sign, filePath) {
3565
+ const form = new import_form_data6.default();
3566
+ form.append("file", import_fs_extra10.default.createReadStream(filePath));
3567
+ form.append("sign", sign);
3568
+ form.append("type", "apk");
3569
+ const res = await import_axios7.default.post(uploadUrl, form, {
3570
+ headers: form.getHeaders(),
3571
+ maxContentLength: Infinity,
3572
+ maxBodyLength: Infinity,
3573
+ timeout: 3e5
3574
+ // 5 分钟超时
3575
+ });
3576
+ if (res.data.errno !== 0) {
3577
+ throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3578
+ }
3579
+ return {
3580
+ url: res.data.data.url,
3581
+ md5: res.data.data.md5
3582
+ };
3583
+ }
3584
+ /**
3585
+ * 提交版本信息
3586
+ */
3587
+ async submitVersion(params) {
3588
+ logger.info(`[OPPO Submit Params] ${JSON.stringify(params)}`);
3589
+ const timestamp = Math.floor(Date.now() / 1e3);
3590
+ const online = params.onlineAppInfo || {};
3591
+ let vCode = params.versionCode;
3592
+ if (!vCode || vCode === "0" || vCode === "") {
3593
+ const parts = params.versionName.split("+");
3594
+ if (parts.length > 1) {
3595
+ vCode = parts[1];
3596
+ } else {
3597
+ vCode = "1";
3598
+ }
3599
+ }
3600
+ const signParams = {
3601
+ access_token: params.accessToken,
3602
+ timestamp,
3603
+ // OPPO 官方要求 apk_url 为 JSON 数组格式:[{url, md5, cpu_code}]
3604
+ // cpu_code: 0=通用包, 3=arm64-v8a, 4=armeabi-v7a, 5=x86_64
3605
+ apk_url: JSON.stringify([
3606
+ {
3607
+ url: params.fileUrl,
3608
+ md5: params.fileMd5,
3609
+ cpu_code: 0
3610
+ // 通用包
3611
+ }
3612
+ ]),
3613
+ version_name: params.versionName.split("+")[0],
3614
+ // 仅保留版本名部分
3615
+ version_code: vCode,
3616
+ update_desc: params.updateDesc,
3617
+ pkg_name: params.packageName,
3618
+ app_name: params.appName,
3619
+ // 补充 OPPO 提交审核的必填项 (优先复用线上数据)
3620
+ summary: online.summary || params.updateDesc.slice(0, 15),
3621
+ detail_desc: online.detail_desc || (params.updateDesc.length >= 20 ? params.updateDesc : `${params.updateDesc}, \u6B64\u7248\u672C\u4F18\u5316\u4E86\u7528\u6237\u4F53\u9A8C\u5E76\u4FEE\u590D\u4E86\u5DF2\u77E5\u95EE\u9898\u3002`),
3622
+ privacy_source_url: online.privacy_source_url || `https://open.oppomobile.com/privacy/${params.packageName}`
3623
+ };
3624
+ const mapField = (key, onlineKey) => {
3625
+ const val = online[onlineKey || key];
3626
+ if (val !== void 0 && val !== null && val !== "") {
3627
+ signParams[key] = val;
3628
+ }
3629
+ };
3630
+ mapField("first_category_id");
3631
+ mapField("second_category_id");
3632
+ mapField("third_category_id");
3633
+ if (params.onlineType) {
3634
+ signParams.online_type = params.onlineType;
3635
+ } else {
3636
+ mapField("online_type");
3637
+ }
3638
+ if (!signParams.online_type) {
3639
+ signParams.online_type = "1";
3640
+ }
3641
+ mapField("version_type");
3642
+ mapField("adaptive_equipment");
3643
+ {
3644
+ const val = online["adaptive_type"];
3645
+ if (val !== void 0 && val !== null && val !== "" && String(val) !== "0") {
3646
+ signParams.adaptive_type = val;
3647
+ }
3648
+ }
3649
+ mapField("test_desc");
3650
+ if (!signParams.test_desc) {
3651
+ signParams.test_desc = "\u65E0\u7279\u6B8A\u6D4B\u8BD5\u8BF4\u660E";
3652
+ }
3653
+ mapField("business_username");
3654
+ mapField("business_email");
3655
+ mapField("business_mobile");
3656
+ mapField("customer_contact");
3657
+ if (!signParams.business_username) signParams.business_username = "\u5F00\u53D1\u8D1F\u8D23\u4EBA";
3658
+ if (!signParams.business_email) signParams.business_email = "developer@example.com";
3659
+ if (!signParams.business_mobile) signParams.business_mobile = "13800138000";
3660
+ mapField("copyright_url");
3661
+ mapField("age_level");
3662
+ if (!signParams.age_level) {
3663
+ signParams.age_level = "18";
3664
+ }
3665
+ mapField("icon_url");
3666
+ if (online.pic_url_material && Array.isArray(online.pic_url_material)) {
3667
+ const MAX_SIZE = 1 * 1024 * 1024;
3668
+ const validPicUrls = online.pic_url_material.filter((item) => {
3669
+ return !item.size || Number(item.size) <= MAX_SIZE;
3670
+ }).map((item) => item.url).filter(Boolean);
3671
+ if (validPicUrls.length > 0) {
3672
+ signParams.pic_url = validPicUrls.join(",");
3673
+ } else {
3674
+ mapField("pic_url");
3675
+ }
3676
+ } else {
3677
+ mapField("pic_url");
3678
+ }
3679
+ mapField("is_safe_check");
3680
+ const apiSign = this.generateSign(signParams, params.clientSecret);
3681
+ const data = new URLSearchParams();
3682
+ Object.entries(signParams).forEach(([key, value]) => {
3683
+ data.append(key, String(value));
3684
+ });
3685
+ data.append("api_sign", apiSign);
3686
+ logger.info(`[OPPO Submit Debug] URL: ${_OppoUploader.SUBMIT_API}`);
3687
+ logger.info(`[OPPO Submit Debug] Body: ${data.toString()}`);
3688
+ const res = await import_axios7.default.post(_OppoUploader.SUBMIT_API, data.toString(), {
3689
+ headers: {
3690
+ "Content-Type": "application/x-www-form-urlencoded"
3691
+ },
3692
+ timeout: 3e4
3693
+ });
3694
+ logger.info(`[OPPO Submit Response] status: ${res.status}, data: ${JSON.stringify(res.data)}`);
3695
+ if (res.data.errno !== 0) {
3696
+ throw new Error(`\u63D0\u4EA4\u7248\u672C\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3697
+ }
3698
+ logger.info("\u7248\u672C\u4FE1\u606F\u5DF2\u63D0\u4EA4");
3699
+ }
3700
+ /**
3701
+ * 格式化错误信息
3702
+ */
3703
+ formatError(error) {
3704
+ if (error.response?.data) {
3705
+ const data = error.response.data;
3706
+ return data.data?.message || data.message || error.message;
3707
+ }
3708
+ return error.message;
3709
+ }
3710
+ };
3711
+
3712
+ // src/adapters/vivo_uploader.ts
3713
+ var import_fs_extra11 = __toESM(require("fs-extra"), 1);
3714
+ var import_path8 = __toESM(require("path"), 1);
3715
+ var import_axios8 = __toESM(require("axios"), 1);
3716
+ var import_form_data7 = __toESM(require("form-data"), 1);
3717
+ var import_crypto5 = __toESM(require("crypto"), 1);
3718
+ var VivoUploader = class _VivoUploader {
3719
+ name = "vivo";
3720
+ /** vivo 开放 API 基础地址 */
3721
+ static API_BASE = "https://developer-api.vivo.com.cn/router/rest";
3722
+ /**
3723
+ * vivo API 签名生成
3724
+ * 规则: 所有参数按 ASCII 码排序后拼接为 key=val&... 字符串,
3725
+ * 以 accessSecret 为密钥进行 HMAC-SHA256 加密,结果转为小写 16 进制字符串
3726
+ */
3727
+ generateSign(params, accessSecret) {
3728
+ const sorted = Object.keys(params).sort().filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3729
+ const sign = import_crypto5.default.createHmac("sha256", accessSecret).update(sorted).digest("hex");
3730
+ logger.info(`[VIVO DEBUG] \u5F85\u7B7E\u540D\u4E32: ${sorted}
3731
+ -> \u7B7E\u540D\u7ED3\u679C: ${sign}`);
3732
+ return sign;
3733
+ }
3734
+ validateConfig(config) {
3735
+ if (!config?.publish?.vivo?.enable) return false;
3736
+ const vivo = config.publish.vivo;
3737
+ if (!vivo.auth?.accessKey || !vivo.auth?.accessSecret) {
3738
+ logger.error("vivo config missing: accessKey or accessSecret");
3739
+ return false;
3740
+ }
3741
+ return true;
3742
+ }
3743
+ canHandle(filePath) {
3744
+ const ext = filePath.split(".").pop()?.toLowerCase();
3745
+ return ext === "apk";
3746
+ }
3747
+ async upload(filePath, config, metadata) {
3748
+ const vivoConfig = config.publish.vivo;
3749
+ const accessKey = vivoConfig.auth.accessKey;
3750
+ const accessSecret = vivoConfig.auth.accessSecret;
3751
+ const retryConfig = config.retry;
3752
+ const consoleUrl = "https://dev.vivo.com.cn/manage/app";
3753
+ if (!import_fs_extra11.default.existsSync(filePath)) {
3754
+ return {
3755
+ platform: "vivo",
3756
+ success: false,
3757
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`,
3758
+ consoleUrl
3759
+ };
3760
+ }
3761
+ const fileSize = import_fs_extra11.default.statSync(filePath).size;
3762
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 vivo \u5E94\u7528\u5546\u5E97...");
3763
+ logger.info(`\u6587\u4EF6: ${filePath} (${(fileSize / 1024 / 1024).toFixed(2)} MB)`);
3764
+ try {
3765
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3766
+ const fileMd5 = await this.calculateFileMD5(filePath);
3767
+ logger.info("\u6B63\u5728\u4E0A\u4F20 APK \u6587\u4EF6...");
3768
+ const packageName = vivoConfig.packageName || "";
3769
+ const uploadFileResult = await retryStrategy.execute(
3770
+ () => this.uploadApk(accessKey, accessSecret, filePath, packageName, fileMd5),
3771
+ "vivo file upload"
3772
+ );
3773
+ if (!uploadFileResult.success || !uploadFileResult.data) {
3774
+ throw uploadFileResult.error || new Error("File upload failed or no serialnumber returned");
3775
+ }
3776
+ const serialnumber = uploadFileResult.data;
3777
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u7248\u672C\u4FE1\u606F...");
3778
+ const submitResult = await retryStrategy.execute(
3779
+ () => this.submitVersion(accessKey, accessSecret, {
3780
+ serialnumber,
3781
+ packageName: vivoConfig.packageName,
3782
+ versionCode: parseInt(metadata.buildNumber) || 1,
3783
+ fileMd5,
3784
+ updateDesc: metadata.changelog || "App Update"
3785
+ }),
3786
+ "vivo submit version"
3787
+ );
3788
+ if (!submitResult.success) {
3789
+ throw submitResult.error || new Error("Submit version failed");
3790
+ }
3791
+ logger.success("\u4E0A\u4F20\u5230 vivo \u5E94\u7528\u5546\u5E97\u6210\u529F!");
3792
+ return {
3793
+ platform: "vivo",
3794
+ success: true,
3795
+ message: "\u4E0A\u4F20\u6210\u529F, \u8BF7\u524D\u5F80\u540E\u53F0\u786E\u8BA4\u5E76\u63D0\u4EA4\u5BA1\u6838",
3796
+ consoleUrl
3797
+ };
3798
+ } catch (error) {
3799
+ logger.error(`\u4E0A\u4F20\u5230 vivo \u5931\u8D25: ${error.message}`);
3800
+ return {
3801
+ platform: "vivo",
3802
+ success: false,
3803
+ message: this.formatError(error),
3804
+ error,
3805
+ consoleUrl
3806
+ };
3807
+ }
3808
+ }
3809
+ /**
3810
+ * 计算文件 MD5
3811
+ */
3812
+ calculateFileMD5(filePath) {
3813
+ return new Promise((resolve, reject) => {
3814
+ const hash = import_crypto5.default.createHash("md5");
3815
+ const stream = import_fs_extra11.default.createReadStream(filePath);
3816
+ stream.on("data", (data) => hash.update(data));
3817
+ stream.on("end", () => resolve(hash.digest("hex")));
3818
+ stream.on("error", reject);
3819
+ });
3820
+ }
3821
+ /**
3822
+ * 上传 APK 文件并获取流水号
3823
+ * 将公共参数与业务参数放入一个 multipart 请求中直接上传至 API_BASE
3824
+ */
3825
+ async uploadApk(accessKey, accessSecret, filePath, packageName, fileMd5) {
3826
+ const timestamp = String(Date.now());
3827
+ const paramsForSign = {
3828
+ // 公共参数
3829
+ access_key: accessKey,
3830
+ timestamp,
3831
+ format: "json",
3832
+ v: "1.0",
3833
+ sign_method: "hmac",
3834
+ target_app_key: "developer",
3835
+ method: "app.upload.apk.app",
3836
+ // 业务参数
3837
+ packageName,
3838
+ fileMd5
3839
+ };
3840
+ const sign = this.generateSign(paramsForSign, accessSecret);
3841
+ const form = new import_form_data7.default();
3842
+ for (const [key, value] of Object.entries(paramsForSign)) {
3843
+ form.append(key, value);
3844
+ }
3845
+ form.append("sign", sign);
3846
+ form.append("file", import_fs_extra11.default.createReadStream(filePath), {
3847
+ filename: import_path8.default.basename(filePath),
3848
+ contentType: "application/vnd.android.package-archive"
3849
+ });
3850
+ logger.info(
3851
+ `[VIVO DEBUG] \u5F00\u59CB\u4E0A\u4F20 APK (API\u8BF7\u6C42) \u53C2\u6570(\u4E0D\u542B\u6587\u4EF6): ${JSON.stringify({ ...paramsForSign, sign })}`
3852
+ );
3853
+ const res = await import_axios8.default.post(_VivoUploader.API_BASE, form, {
3854
+ headers: form.getHeaders(),
3855
+ maxContentLength: Infinity,
3856
+ maxBodyLength: Infinity,
3857
+ timeout: 3e5
3858
+ });
3859
+ logger.info(`[VIVO DEBUG] \u4E0A\u4F20\u54CD\u5E94: ${JSON.stringify(res.data)}`);
3860
+ if (res.data.code !== 0) {
3861
+ throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${res.data.msg || JSON.stringify(res.data)}`);
3862
+ }
3863
+ const serialnumber = res.data.data?.serialnumber || res.data.data;
3864
+ logger.info(`APK \u6587\u4EF6\u4E0A\u4F20\u5B8C\u6210\uFF0C\u6D41\u6C34\u53F7: ${serialnumber}`);
3865
+ return serialnumber;
3866
+ }
3867
+ /**
3868
+ * 提交版本更新信息
3869
+ */
3870
+ async submitVersion(accessKey, accessSecret, params) {
3871
+ const timestamp = String(Date.now());
3872
+ const reqParams = {
3873
+ access_key: accessKey,
3874
+ timestamp,
3875
+ format: "json",
3876
+ v: "1.0",
3877
+ sign_method: "hmac",
3878
+ target_app_key: "developer",
3879
+ method: "app.sync.update.app",
3880
+ packageName: params.packageName || "",
3881
+ // 文档必填
3882
+ versionCode: String(params.versionCode),
3883
+ // 文档必填 (Integer)
3884
+ apk: params.serialnumber,
3885
+ // 文档中的 apk 字段即为上传接口返回的 serialnumber
3886
+ fileMd5: params.fileMd5,
3887
+ // 文档必填
3888
+ onlineType: "1",
3889
+ // 1:立即上架 2:定时上架 (必填)
3890
+ compatibleDevice: "1",
3891
+ // 1:手机 2:手机和平板 3:平板 (必填)
3892
+ updateDesc: params.updateDesc
3893
+ };
3894
+ reqParams.sign = this.generateSign(reqParams, accessSecret);
3895
+ const formData = new URLSearchParams();
3896
+ for (const [key, value] of Object.entries(reqParams)) {
3897
+ formData.append(key, value);
3898
+ }
3899
+ const res = await import_axios8.default.post(_VivoUploader.API_BASE, formData.toString(), {
3900
+ headers: {
3901
+ "Content-Type": "application/x-www-form-urlencoded"
3902
+ },
3903
+ timeout: 3e4
3904
+ });
3905
+ if (res.data.code !== 0) {
3906
+ throw new Error(`\u63D0\u4EA4\u7248\u672C\u5931\u8D25: ${res.data.msg || JSON.stringify(res.data)}`);
3907
+ }
3908
+ logger.info("\u7248\u672C\u4FE1\u606F\u5DF2\u63D0\u4EA4");
3909
+ }
3910
+ /**
3911
+ * 格式化错误信息
3912
+ */
3913
+ formatError(error) {
3914
+ if (error.response?.data) {
3915
+ const data = error.response.data;
3916
+ return data.msg || data.message || error.message;
3917
+ }
3918
+ return error.message;
3919
+ }
3920
+ };
3921
+
3922
+ // src/adapters/tencent_uploader.ts
3923
+ var import_fs_extra12 = __toESM(require("fs-extra"), 1);
3924
+ var import_path9 = __toESM(require("path"), 1);
3925
+ var import_axios9 = __toESM(require("axios"), 1);
3926
+ var import_crypto6 = __toESM(require("crypto"), 1);
3927
+ var TencentUploader = class _TencentUploader {
3928
+ name = "Tencent";
3929
+ /** 腾讯开放平台 API 基础地址 */
3930
+ static API_BASE = "https://p.open.qq.com/open_file/developer_api";
3931
+ /**
3932
+ * 接口签名生成 (HmacSHA256)
3933
+ * 规则: 所有参数按字典序排序拼接为 k1=v1&k2=v2... (不要进行 URL 编码)
3934
+ * 使用 accessSecret 计算 HmacSHA256,转小写 16 进制
3935
+ */
3936
+ generateSign(params, accessSecret) {
3937
+ const sortedKeys = Object.keys(params).sort();
3938
+ const signStr = sortedKeys.filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3939
+ return import_crypto6.default.createHmac("sha256", accessSecret).update(signStr).digest("hex").toLowerCase();
3940
+ }
3941
+ validateConfig(config) {
3942
+ if (!config?.publish?.tencent?.enable) return false;
3943
+ const auth = config.publish.tencent.auth;
3944
+ if (!auth?.userId || !auth?.appId || !auth?.accessSecret) {
3945
+ logger.error("Tencent config missing: userId, appId or accessSecret");
3946
+ return false;
3947
+ }
3948
+ return true;
3949
+ }
3950
+ canHandle(filePath) {
3951
+ return filePath.toLowerCase().endsWith(".apk");
3952
+ }
3953
+ async upload(filePath, config, metadata) {
3954
+ const tencentConfig = config.publish.tencent;
3955
+ const auth = tencentConfig.auth;
3956
+ logger.info(`Tencent \u8FD0\u884C\u65F6\u914D\u7F6E: ${JSON.stringify(tencentConfig)}`);
3957
+ const consoleUrl = "https://app.open.qq.com";
3958
+ if (!import_fs_extra12.default.existsSync(filePath)) {
3959
+ return { platform: "tencent", success: false, message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`, consoleUrl };
3960
+ }
3961
+ try {
3962
+ const stats = import_fs_extra12.default.statSync(filePath);
3963
+ const fileName = import_path9.default.basename(filePath);
3964
+ logger.info("\u6B63\u5728\u83B7\u53D6\u9884\u7B7E\u540D\u4E0A\u4F20\u5730\u5740...");
3965
+ const pkgName = tencentConfig.packageName || "";
3966
+ const uploadInfo = await this.getFileUploadInfo(auth, stats.size, fileName, pkgName);
3967
+ logger.info(`\u83B7\u53D6\u6587\u4EF6\u4E0A\u4F20\u4FE1\u606F\u7ED3\u679C ${JSON.stringify(uploadInfo)}`);
3968
+ logger.info("\u6B63\u5728\u4E0A\u4F20\u6587\u4EF6\u5230\u817E\u8BAF\u4E91 COS (\u7ED5\u8FC7 API \u7F51\u5173\u9650\u5236)...");
3969
+ await this.uploadToCos(uploadInfo.pre_sign_url, filePath, stats.size);
3970
+ logger.info("\u6B63\u5728\u83B7\u53D6\u7EBF\u4E0A\u5E94\u7528\u8BE6\u60C5\u4EE5\u4FDD\u7559\u73B0\u6709\u914D\u7F6E...");
3971
+ const pkgInfo = await parsePackageInfo(filePath, {
3972
+ androidSdkPath: config.globalSettings?.androidSdkPath
3973
+ });
3974
+ const nativeCodes = pkgInfo?.nativeCode || [];
3975
+ const has64Bit = nativeCodes.includes("arm64-v8a") || nativeCodes.includes("x86_64");
3976
+ const has32Bit = nativeCodes.includes("armeabi-v7a") || nativeCodes.includes("armeabi") || nativeCodes.includes("x86");
3977
+ const is64Bit = has64Bit && !has32Bit;
3978
+ const md5 = pkgInfo?.md5;
3979
+ const onlineDetail = await this.queryAppDetail(
3980
+ auth,
3981
+ tencentConfig.packageName || pkgInfo?.packageName || ""
3982
+ );
3983
+ logger.info(`\u83B7\u53D6\u7EBF\u4E0A\u8BE6\u60C5\u6210\u529F: ${onlineDetail.app_name || "\u672A\u547D\u540D"}`);
3984
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u6D41\u6C34\u53F7\u5B8C\u6210\u5BA1\u6838\u7533\u62A5...");
3985
+ const submitResult = await this.submitModifyAppInfo(
3986
+ auth,
3987
+ {
3988
+ ...onlineDetail,
3989
+ // 以前序详情为蓝本
3990
+ pkg_name: tencentConfig.packageName || pkgInfo?.packageName || onlineDetail.pkg_name || "",
3991
+ serial_number: uploadInfo.serial_number,
3992
+ update_desc: metadata.changelog || "\u7248\u672C\u66F4\u65B0",
3993
+ is64Bit,
3994
+ md5
3995
+ },
3996
+ { timeout: tencentConfig.timeout || 6e4 }
3997
+ );
3998
+ logger.info(`\u63D0\u4EA4\u6D41\u6C34\u53F7\u5B8C\u6210\u5BA1\u6838\u7533\u62A5\u7ED3\u679C: ${JSON.stringify(submitResult)}`);
3999
+ logger.success("\u817E\u8BAF\u5E94\u7528\u5B9D\u4E0A\u4F20\u5E76\u63D0\u4EA4\u6210\u529F!");
4000
+ return { platform: "tencent", success: true, message: "\u4E0A\u4F20\u5E76\u63D0\u4EA4\u5BA1\u6838\u6210\u529F", consoleUrl };
4001
+ } catch (error) {
4002
+ logger.error(`\u817E\u8BAF\u4E0A\u4F20\u5931\u8D25: ${JSON.stringify(error)}`);
4003
+ logger.error(`\u817E\u8BAF\u4E0A\u4F20\u5931\u8D25: ${error.stack}`);
4004
+ return { platform: "tencent", success: false, message: error.message, error, consoleUrl };
4005
+ }
4006
+ }
4007
+ /**
4008
+ * 阶段 1: 获取文件上传信息
4009
+ */
4010
+ async getFileUploadInfo(auth, fileSize, fileName, pkgName) {
4011
+ logger.info(`Tencent getFileUploadInfo: ${JSON.stringify(auth)}`);
4012
+ const userId = String(auth.userId || "");
4013
+ const accessSecret = String(auth.accessSecret || "");
4014
+ const signParams = {
4015
+ user_id: userId,
4016
+ timestamp: String(Math.floor(Date.now() / 1e3)),
4017
+ pkg_name: pkgName,
4018
+ app_id: String(auth.appId || ""),
4019
+ file_size: String(fileSize),
4020
+ file_name: fileName,
4021
+ file_type: "apk"
4022
+ };
4023
+ const sign = this.generateSign(signParams, accessSecret);
4024
+ const formParams = {
4025
+ ...signParams,
4026
+ sign
4027
+ };
4028
+ const url = `${_TencentUploader.API_BASE}/get_file_upload_info`;
4029
+ logger.info(`\u6B63\u5728\u8BF7\u6C42 Tencent API: ${url}`);
4030
+ logger.info(`formParams: ${JSON.stringify(formParams)}`);
4031
+ const res = await import_axios9.default.post(url, new URLSearchParams(formParams).toString(), {
4032
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
4033
+ });
4034
+ if (res.data.ret !== 0) {
4035
+ throw new Error(`\u83B7\u53D6\u4E0A\u4F20\u4FE1\u606F\u5931\u8D25: ${res.data.msg} (ret:${res.data.ret})`);
4036
+ }
4037
+ return res.data;
4038
+ }
4039
+ /**
4040
+ * 获取应用详情
4041
+ */
4042
+ async queryAppDetail(auth, pkgName) {
4043
+ const userId = auth.userId || "";
4044
+ const accessSecret = auth.accessSecret || "";
4045
+ const signParams = {
4046
+ user_id: userId,
4047
+ timestamp: String(Math.floor(Date.now() / 1e3)),
4048
+ app_id: String(auth.appId || ""),
4049
+ pkg_name: pkgName
4050
+ };
4051
+ const sign = this.generateSign(signParams, accessSecret);
4052
+ const formParams = { ...signParams, sign };
4053
+ const url = `${_TencentUploader.API_BASE}/query_app_detail`;
4054
+ const res = await import_axios9.default.post(url, new URLSearchParams(formParams).toString(), {
4055
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
4056
+ });
4057
+ if (res.data.ret !== 0) {
4058
+ logger.warn(`\u67E5\u8BE2\u5E94\u7528\u8BE6\u60C5\u5931\u8D25: ${res.data.msg}\uFF0C\u5C06\u4F7F\u7528\u7A7A\u914D\u7F6E\u7EE7\u7EED`);
4059
+ return {};
4060
+ }
4061
+ return res.data;
4062
+ }
4063
+ /**
4064
+ * 阶段 2: 直接上传到 COS (PUT)
4065
+ */
4066
+ async uploadToCos(url, filePath, size) {
4067
+ await import_axios9.default.put(url, import_fs_extra12.default.createReadStream(filePath), {
4068
+ headers: {
4069
+ "Content-Type": "application/octet-stream",
4070
+ "Content-Length": size
4071
+ },
4072
+ maxContentLength: Infinity,
4073
+ maxBodyLength: Infinity,
4074
+ timeout: 9e5,
4075
+ // 15 分钟
4076
+ onUploadProgress: (p) => {
4077
+ if (p.total) {
4078
+ const percent = Math.round(p.loaded * 100 / p.total);
4079
+ if (percent % 20 === 0) logger.info(`\u4E0A\u4F20\u8FDB\u5EA6: ${percent}%`);
4080
+ }
4081
+ }
4082
+ });
4083
+ }
4084
+ /**
4085
+ * 阶段 3: 提交流水号信息
4086
+ */
4087
+ async submitModifyAppInfo(auth, data, options) {
4088
+ const userId = auth.userId || "";
4089
+ const accessSecret = auth.accessSecret || "";
4090
+ const signParams = {
4091
+ user_id: userId,
4092
+ timestamp: String(Math.floor(Date.now() / 1e3)),
4093
+ app_id: String(auth.appId || ""),
4094
+ pkg_name: String(data.pkg_name || ""),
4095
+ feature: String(data.update_desc || ""),
4096
+ deploy_type: String(data.deploy_type || "1")
4097
+ // 默认审核后立即发布
4098
+ };
4099
+ const skipFields = [
4100
+ "ret",
4101
+ "msg",
4102
+ "user_id",
4103
+ "timestamp",
4104
+ "sign",
4105
+ "app_id",
4106
+ "pkg_name",
4107
+ "feature",
4108
+ "is64Bit",
4109
+ "md5",
4110
+ "serial_number"
4111
+ ];
4112
+ Object.keys(data).forEach((key) => {
4113
+ if (!skipFields.includes(key) && data[key] !== void 0 && data[key] !== null) {
4114
+ signParams[key] = String(data[key]);
4115
+ }
4116
+ });
4117
+ if (data.is64Bit) {
4118
+ signParams.apk64_file_serial_number = String(data.serial_number || "");
4119
+ if (data.md5) signParams.apk64_file_md5 = data.md5;
4120
+ delete signParams.apk32_file_serial_number;
4121
+ delete signParams.apk32_file_md5;
4122
+ } else {
4123
+ signParams.apk32_file_serial_number = String(data.serial_number || "");
4124
+ if (data.md5) signParams.apk32_file_md5 = data.md5;
4125
+ delete signParams.apk64_file_serial_number;
4126
+ delete signParams.apk64_file_md5;
4127
+ }
4128
+ const sign = this.generateSign(signParams, accessSecret);
4129
+ const formParams = {
4130
+ ...signParams,
4131
+ sign
4132
+ };
4133
+ logger.info(`formParams: ${JSON.stringify(formParams)}`);
4134
+ const url = `${_TencentUploader.API_BASE}/update_app`;
4135
+ const res = await import_axios9.default.post(url, new URLSearchParams(formParams).toString(), {
4136
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
4137
+ });
4138
+ if (res.data.ret !== 0) {
4139
+ throw new Error(`\u63D0\u4EA4\u6D41\u6C34\u53F7\u5931\u8D25: ${res.data.msg} (ret:${res.data.ret})`);
4140
+ }
4141
+ return res.data;
4142
+ }
4143
+ };
4144
+ // Annotate the CommonJS export names for ESM import in node:
4145
+ 0 && (module.exports = {
4146
+ AdHocUploader,
4147
+ AppleJWTGenerator,
4148
+ AppleStoreUploader,
4149
+ ConfigValidator,
4150
+ DEFAULT_RETRY_CONFIG,
4151
+ EnvValidator,
4152
+ ErrorCategory,
4153
+ HarmonyUploader,
4154
+ HuaweiUploader,
4155
+ OppoUploader,
4156
+ PgyerUploader,
4157
+ RetryStrategy,
4158
+ TencentUploader,
4159
+ TestFlightUploader,
4160
+ UploadManager,
4161
+ VivoUploader,
4162
+ XiaomiUploader,
4163
+ createUploadManager,
4164
+ createUploadRetryStrategy,
4165
+ parsePackageInfo
4166
+ });
4167
+ //# sourceMappingURL=index.cjs.map