@weapp-tailwindcss/hbuilderx-runner 0.0.3 → 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 CHANGED
@@ -23,11 +23,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  //#endregion
24
24
  let node_fs_promises = require("node:fs/promises");
25
25
  node_fs_promises = __toESM(node_fs_promises, 1);
26
- let node_child_process = require("node:child_process");
27
26
  let node_path = require("node:path");
28
27
  node_path = __toESM(node_path, 1);
29
28
  let node_process = require("node:process");
30
29
  node_process = __toESM(node_process, 1);
30
+ let node_child_process = require("node:child_process");
31
31
  //#region src/fs.ts
32
32
  async function fileExists(file) {
33
33
  try {
@@ -44,11 +44,146 @@ function wait(ms) {
44
44
  return new Promise((resolve) => setTimeout(resolve, ms));
45
45
  }
46
46
  //#endregion
47
+ //#region src/hbuilderx/discovery.ts
48
+ const macOSStableCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
49
+ const macOSAlphaCli = "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli";
50
+ function unique(items) {
51
+ return [...new Set(items)];
52
+ }
53
+ function normalizeFile(file, platform = node_process.default.platform) {
54
+ const normalized = node_path.default.normalize(file);
55
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
56
+ }
57
+ function resolveHBuilderXChannel(channel) {
58
+ const value = channel ?? "auto";
59
+ if (value === "auto" || value === "stable" || value === "alpha") return value;
60
+ throw new Error(`无效的 HBuilderX channel:${value}。可选值为 auto、stable、alpha。`);
61
+ }
62
+ function inferHBuilderXChannel(file) {
63
+ if (/HBuilderX(?:-|\s*)Alpha(?:\.app)?[\\/]/i.test(file) || /(?:^|[\\/])alpha(?:[\\/]|$)/i.test(file)) return "alpha";
64
+ if (/HBuilderX(?:\.app)?[\\/]/i.test(file) || /HBuilderX\.exe$/i.test(file)) return "stable";
65
+ return "unknown";
66
+ }
67
+ function getDefaultHBuilderXCliCandidates(env = node_process.default.env, channel = resolveHBuilderXChannel(env.HBUILDERX_CHANNEL), platform = node_process.default.platform) {
68
+ const defaults = platform === "darwin" ? channel === "stable" ? [macOSStableCli] : channel === "alpha" ? [macOSAlphaCli] : [macOSStableCli, macOSAlphaCli] : [];
69
+ return unique([env.HBUILDERX_CLI_PATH, ...defaults].filter((item) => Boolean(item)));
70
+ }
71
+ function extractHBuilderXMacOSExecutables(output) {
72
+ return unique(Array.from(output.matchAll(/(\/[^\r\n]*?HBuilderX(?:-Alpha|\s+Alpha)?\.app\/Contents\/MacOS\/HBuilderX)(?=\s|$)/gi), (match) => match[1]));
73
+ }
74
+ function extractHBuilderXWindowsExecutables(output) {
75
+ const executables = [];
76
+ for (const line of output.split(/\r?\n/)) {
77
+ const executable = line.split(",").at(-1)?.trim();
78
+ if (executable?.toLowerCase().endsWith("hbuilderx.exe")) executables.push(executable);
79
+ }
80
+ return unique(executables);
81
+ }
82
+ function extractHBuilderXExecutablesFromProcessOutput(output, platform = node_process.default.platform) {
83
+ return platform === "win32" ? extractHBuilderXWindowsExecutables(output) : extractHBuilderXMacOSExecutables(output);
84
+ }
85
+ function extractHBuilderXMacOSExecutable(line) {
86
+ return extractHBuilderXMacOSExecutables(line)[0];
87
+ }
88
+ function extractHBuilderXWindowsExecutable(line) {
89
+ return extractHBuilderXWindowsExecutables(line)[0];
90
+ }
91
+ function extractHBuilderXExecutableFromProcessOutput(output, platform = node_process.default.platform) {
92
+ return extractHBuilderXExecutablesFromProcessOutput(output, platform)[0];
93
+ }
94
+ async function findRunningHBuilderXCliCandidates(platform = node_process.default.platform) {
95
+ const result = platform === "win32" ? (0, node_child_process.spawnSync)("wmic", [
96
+ "process",
97
+ "where",
98
+ "name='HBuilderX.exe'",
99
+ "get",
100
+ "executablepath",
101
+ "/format:csv"
102
+ ], {
103
+ encoding: "utf8",
104
+ windowsHide: true
105
+ }) : (0, node_child_process.spawnSync)("ps", [
106
+ "-ax",
107
+ "-o",
108
+ "command="
109
+ ], { encoding: "utf8" });
110
+ if (result.error || result.status !== 0) return [];
111
+ const executables = extractHBuilderXExecutablesFromProcessOutput(`${result.stdout ?? ""}${result.stderr ?? ""}`, platform);
112
+ const candidates = [];
113
+ for (const executable of executables) {
114
+ if (!await fileExists(executable)) continue;
115
+ const cli = node_path.default.join(node_path.default.dirname(executable), platform === "win32" ? "cli.exe" : "cli");
116
+ if (await fileExists(cli)) candidates.push(cli);
117
+ }
118
+ return unique(candidates);
119
+ }
120
+ async function findRunningHBuilderXCli(platform = node_process.default.platform) {
121
+ return (await findRunningHBuilderXCliCandidates(platform))[0];
122
+ }
123
+ function sortByChannel(items) {
124
+ const weights = {
125
+ stable: 0,
126
+ alpha: 1,
127
+ unknown: 2
128
+ };
129
+ return [...items].sort((left, right) => weights[inferHBuilderXChannel(left)] - weights[inferHBuilderXChannel(right)]);
130
+ }
131
+ function selectHBuilderXCliCandidatesForChannel(items, channel) {
132
+ if (channel === "auto") return sortByChannel(items);
133
+ return items.filter((item) => inferHBuilderXChannel(item) === channel);
134
+ }
135
+ function resolveCandidateSource(candidate, env) {
136
+ if (candidate === env.HBUILDERX_CLI_PATH) return "env";
137
+ if (candidate === "/Applications/HBuilderX.app/Contents/MacOS/cli" || candidate === "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli") return "default-path";
138
+ return "candidate";
139
+ }
140
+ async function firstExisting(items) {
141
+ for (const item of items) if (await fileExists(item)) return item;
142
+ }
143
+ async function resolveHBuilderXCliInfoFromOptions(options = {}) {
144
+ const env = options.env ?? node_process.default.env;
145
+ const channel = resolveHBuilderXChannel(options.channel ?? env.HBUILDERX_CHANNEL);
146
+ const running = await findRunningHBuilderXCliCandidates();
147
+ if (options.candidates) {
148
+ const candidate = await firstExisting(options.candidates);
149
+ if (candidate) return {
150
+ path: candidate,
151
+ isRunning: running.some((item) => normalizeFile(item) === normalizeFile(candidate)),
152
+ source: resolveCandidateSource(candidate, env),
153
+ channel: inferHBuilderXChannel(candidate)
154
+ };
155
+ throw new Error("未找到显式指定的 HBuilderX CLI candidate。");
156
+ }
157
+ if (env.HBUILDERX_CLI_PATH && await fileExists(env.HBUILDERX_CLI_PATH)) return {
158
+ path: env.HBUILDERX_CLI_PATH,
159
+ isRunning: running.some((item) => normalizeFile(item) === normalizeFile(env.HBUILDERX_CLI_PATH)),
160
+ source: "env",
161
+ channel: inferHBuilderXChannel(env.HBUILDERX_CLI_PATH)
162
+ };
163
+ const runningCandidate = selectHBuilderXCliCandidatesForChannel(running, channel)[0];
164
+ if (runningCandidate) return {
165
+ path: runningCandidate,
166
+ isRunning: true,
167
+ source: "running-process",
168
+ channel: inferHBuilderXChannel(runningCandidate)
169
+ };
170
+ const defaultCandidate = await firstExisting(getDefaultHBuilderXCliCandidates({}, channel));
171
+ if (defaultCandidate) return {
172
+ path: defaultCandidate,
173
+ isRunning: false,
174
+ source: "default-path",
175
+ channel: inferHBuilderXChannel(defaultCandidate)
176
+ };
177
+ throw new Error([`未找到 HBuilderX ${channel === "auto" ? "" : `${channel} `}CLI。`, "请安装 HBuilderX,或设置 HBUILDERX_CLI_PATH=/path/to/cli。"].join(""));
178
+ }
179
+ //#endregion
47
180
  //#region src/logs.ts
48
181
  const PROJECT_NOT_UNI_APP_RE = /不是\s*uni-app\s*项目|not\s+a\s+uni-app\s+project/i;
49
182
  const PROJECT_TYPE_UNSUPPORTED_RE = /项目类型为(.+?),暂不支持|project\s+type.+unsupported/i;
50
183
  const CONFIG_LOAD_FAILED_RE = /failed to load config|error when starting dev server|Failed to resolve entry for package/i;
51
184
  const CLI_NOT_FOUND_RE = /未找到\s*HBuilderX\s*CLI|HBUILDERX_CLI_PATH|command not found|ENOENT/i;
185
+ const CLI_INSTANCE_MISMATCH_RE = /当前运行的cli与正在运行的HBuilderX不匹配|cli.+(?:does not match|mismatch).+HBuilderX|try.+HBuilderX.+(?:cli|MacOS)/i;
186
+ const CLI_HOST_AMBIGUOUS_RE = /multiple running hbuilderx|多个.+HBuilderX.+运行|listhost.+--\s*host|--host.+listhost/i;
52
187
  const ANDROID_TOOLCHAIN_MISSING_RE = /adb(?:\.exe)?(?:\s*[::].*)?(?:not found|ENOENT|不是内部或外部命令)|Android SDK|platform-tools/i;
53
188
  const IOS_TOOLCHAIN_MISSING_RE = /xcrun|xcode-select|xcodebuild|simctl|DEVELOPER_DIR|iOS 模拟器|Xcode/i;
54
189
  const HARMONY_TOOLCHAIN_MISSING_RE = /(?:^|\s)hdc[\s::]|Harmony|DevEco|OpenHarmony/i;
@@ -72,6 +207,16 @@ function collectProcessOutput(child, maxChunks = 160) {
72
207
  return buffer.logs;
73
208
  }
74
209
  function classifyHBuilderXOutput(output) {
210
+ if (CLI_INSTANCE_MISMATCH_RE.test(output)) return {
211
+ kind: "cli-instance-mismatch",
212
+ message: "当前 HBuilderX CLI 与目标运行实例不匹配。",
213
+ hint: "请使用与目标 stable/alpha 实例对应的 CLI,并通过 listhost 与 --host 绑定运行实例。"
214
+ };
215
+ if (CLI_HOST_AMBIGUOUS_RE.test(output)) return {
216
+ kind: "cli-host-ambiguous",
217
+ message: "检测到多个可用的 HBuilderX 运行实例。",
218
+ hint: "请设置 HBUILDERX_HOST,或在 runner options 中显式传入 host。"
219
+ };
75
220
  if (ANDROID_TOOLCHAIN_MISSING_RE.test(output)) return {
76
221
  kind: "android-toolchain-missing",
77
222
  message: "当前环境缺少 Android 运行所需工具链。",
@@ -270,70 +415,249 @@ function createProcessExitTracker(child) {
270
415
  };
271
416
  }
272
417
  //#endregion
273
- //#region src/hbuilderx.ts
274
- const macOSDefaultCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
275
- function getDefaultHBuilderXCliCandidates(env = node_process.default.env) {
276
- return [env.HBUILDERX_CLI_PATH, node_process.default.platform === "darwin" ? macOSDefaultCli : void 0].filter((item) => Boolean(item));
418
+ //#region src/hbuilderx/runner.ts
419
+ const ansiRE = new RegExp(`${String.fromCharCode(27)}\\[[\\d;]*m`, "g");
420
+ const defaultStartupTimeoutMs = 6e4;
421
+ const hostPollIntervalMs = 500;
422
+ const maxSessionLogChunks = 160;
423
+ function stripAnsi(value) {
424
+ return value.replace(ansiRE, "");
277
425
  }
278
- function extractHBuilderXMacOSExecutable(line) {
279
- return line.match(/(\/.*?HBuilderX[^/]*\.app\/Contents\/MacOS\/HBuilderX)(?:\s|$)/i)?.[1];
426
+ function parseHBuilderXHosts(output) {
427
+ return [...new Set(stripAnsi(output).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !/^-?\d+:cli:|命令.+(?:不存在|错误)|not detected running/i.test(line)))];
280
428
  }
281
- function extractHBuilderXWindowsExecutable(line) {
282
- const executable = line.split(",").at(-1)?.trim();
283
- return executable?.toLowerCase().endsWith("hbuilderx.exe") ? executable : void 0;
429
+ function parseHBuilderXVersion(output) {
430
+ return stripAnsi(output).match(/\b(\d+\.\d+(?:\.\d+)+(?:-[0-9a-z.-]+)?)\b/i)?.[1];
284
431
  }
285
- function extractHBuilderXExecutableFromProcessOutput(output, platform = node_process.default.platform) {
286
- for (const line of output.split(/\r?\n/)) {
287
- const executable = platform === "win32" ? extractHBuilderXWindowsExecutable(line) : extractHBuilderXMacOSExecutable(line);
288
- if (executable) return executable;
289
- }
432
+ function inferHBuilderXChannelFromVersion(version) {
433
+ return /(?:^|-)alpha(?:\.|$)/i.test(version) ? "alpha" : "stable";
290
434
  }
291
- async function findRunningHBuilderXCli(platform = node_process.default.platform) {
292
- const result = platform === "win32" ? (0, node_child_process.spawnSync)("wmic", [
293
- "process",
294
- "where",
295
- "name='HBuilderX.exe'",
296
- "get",
297
- "executablepath",
298
- "/format:csv"
299
- ], {
300
- encoding: "utf8",
301
- windowsHide: true
302
- }) : (0, node_child_process.spawnSync)("ps", [
303
- "-ax",
304
- "-o",
305
- "command="
306
- ], { encoding: "utf8" });
307
- if (result.error || result.status !== 0) return;
308
- const executable = extractHBuilderXExecutableFromProcessOutput(`${result.stdout ?? ""}${result.stderr ?? ""}`, platform);
309
- if (!executable || !await fileExists(executable)) return;
310
- const cli = node_path.default.join(node_path.default.dirname(executable), platform === "win32" ? "cli.exe" : "cli");
311
- return await fileExists(cli) ? cli : void 0;
435
+ function createHBuilderXNativeLaunchArgs(options) {
436
+ const args = [
437
+ "launch",
438
+ options.platform,
439
+ "--project",
440
+ node_path.default.resolve(options.cwd),
441
+ ...options.args ?? []
442
+ ];
443
+ if (options.compile != null && !args.includes("--compile")) args.push("--compile", String(options.compile));
444
+ if (options.runtimeLog != null && !args.includes("--runtime-log")) args.push("--runtime-log", String(options.runtimeLog));
445
+ return args;
312
446
  }
313
- function resolveCandidateSource(candidate, env) {
314
- if (candidate === env.HBUILDERX_CLI_PATH) return "env";
315
- if (candidate === macOSDefaultCli) return "default-path";
316
- return "candidate";
447
+ function createRunnerError(cliPath, cwd, args, kind, message, hint, logs) {
448
+ const output = formatRecentLogs(logs);
449
+ return new HBuilderXCommandError([
450
+ `${message}: ${cliPath} ${args.join(" ")}`,
451
+ `cwd=${cwd}`,
452
+ `issue=${kind}: ${message}`,
453
+ `hint=${hint}`,
454
+ output
455
+ ].filter(Boolean).join("\n"), {
456
+ command: cliPath,
457
+ args,
458
+ cwd,
459
+ exit: {
460
+ code: null,
461
+ signal: null
462
+ },
463
+ logs,
464
+ output,
465
+ issue: {
466
+ kind,
467
+ message,
468
+ hint
469
+ }
470
+ });
471
+ }
472
+ function bindHost(args, host) {
473
+ const hostIndex = args.indexOf("--host");
474
+ if (hostIndex < 0) return [
475
+ ...args,
476
+ "--host",
477
+ host
478
+ ];
479
+ if (args[hostIndex + 1] !== host) throw new Error(`runner 已绑定 HBuilderX host=${host},不能改为 ${args[hostIndex + 1] ?? "空值"}。`);
480
+ return args;
481
+ }
482
+ function appendLogs(target, source) {
483
+ target.push(...source);
484
+ if (target.length > maxSessionLogChunks) target.splice(0, target.length - maxSessionLogChunks);
317
485
  }
318
- async function resolveHBuilderXCliInfo(candidates, env = node_process.default.env) {
319
- if (!candidates) {
320
- const runningCli = await findRunningHBuilderXCli();
321
- if (runningCli) return {
322
- path: runningCli,
323
- isRunning: true,
324
- source: "running-process"
486
+ async function listCompatibleHosts(cliPath, cwd, env, expectedChannel, explicitHost, timeoutMs) {
487
+ const startedAt = Date.now();
488
+ const logs = [];
489
+ do {
490
+ const listed = await runCommand({
491
+ command: cliPath,
492
+ args: ["listhost"],
493
+ cwd,
494
+ env,
495
+ timeoutMs: Math.min(timeoutMs, 1e4),
496
+ allowFailure: true
497
+ });
498
+ appendLogs(logs, listed.logs);
499
+ const hosts = explicitHost ? [explicitHost] : parseHBuilderXHosts(listed.output);
500
+ const compatible = [];
501
+ for (const host of hosts) {
502
+ const versionResult = await runCommand({
503
+ command: cliPath,
504
+ args: [
505
+ "version",
506
+ "--host",
507
+ host
508
+ ],
509
+ cwd,
510
+ env,
511
+ timeoutMs: Math.min(timeoutMs, 1e4),
512
+ allowFailure: true
513
+ });
514
+ appendLogs(logs, versionResult.logs);
515
+ if (versionResult.issue.kind === "cli-instance-mismatch") return {
516
+ compatible: [],
517
+ logs
518
+ };
519
+ const version = versionResult.exit.code === 0 ? parseHBuilderXVersion(versionResult.output) : void 0;
520
+ if (!version) continue;
521
+ const channel = inferHBuilderXChannelFromVersion(version);
522
+ if (expectedChannel === "unknown" || channel === expectedChannel) compatible.push({
523
+ host,
524
+ version,
525
+ channel
526
+ });
527
+ }
528
+ if (compatible.length > 0) return {
529
+ compatible,
530
+ logs
325
531
  };
532
+ await wait(hostPollIntervalMs);
533
+ } while (Date.now() - startedAt < timeoutMs);
534
+ return {
535
+ compatible: [],
536
+ logs
537
+ };
538
+ }
539
+ async function createHBuilderXRunner(options = {}) {
540
+ const env = {
541
+ ...node_process.default.env,
542
+ ...options.env
543
+ };
544
+ const cwd = options.cwd ?? node_process.default.cwd();
545
+ const timeoutMs = options.timeoutMs ?? defaultStartupTimeoutMs;
546
+ const resolution = await resolveHBuilderXCliInfoFromOptions({
547
+ candidates: options.hbuilderxCliPath ? [options.hbuilderxCliPath] : options.candidates,
548
+ channel: options.channel,
549
+ env,
550
+ host: options.host
551
+ });
552
+ const cliEnv = {
553
+ ...env,
554
+ HBUILDERX_CLI_PATH: resolution.path
555
+ };
556
+ if (!resolution.isRunning) {
557
+ const opened = await runCommand({
558
+ command: resolution.path,
559
+ args: ["open"],
560
+ cwd,
561
+ env: cliEnv,
562
+ timeoutMs,
563
+ allowFailure: true
564
+ });
565
+ const openIssue = classifyHBuilderXOutput(opened.output);
566
+ if (opened.exit.code !== 0 || openIssue.kind === "cli-instance-mismatch" || openIssue.kind === "cli-host-ambiguous") throw createRunnerError(resolution.path, cwd, ["open"], openIssue.kind === "cli-host-ambiguous" ? "cli-host-ambiguous" : "cli-instance-mismatch", openIssue.message, openIssue.hint ?? "请检查目标 HBuilderX 运行实例。", opened.logs);
326
567
  }
327
- const items = candidates ?? getDefaultHBuilderXCliCandidates(env);
328
- for (const item of items) if (await fileExists(item)) return {
329
- path: item,
330
- isRunning: false,
331
- source: resolveCandidateSource(item, env)
568
+ const requestedChannel = resolveHBuilderXChannel(options.channel ?? env.HBUILDERX_CHANNEL);
569
+ const expectedChannel = resolution.channel !== "unknown" ? resolution.channel : requestedChannel === "auto" ? inferHBuilderXChannel(resolution.path) : requestedChannel;
570
+ const explicitHost = options.host ?? env.HBUILDERX_HOST;
571
+ const { compatible, logs } = await listCompatibleHosts(resolution.path, cwd, cliEnv, expectedChannel, explicitHost, timeoutMs);
572
+ if (compatible.length === 0) throw createRunnerError(resolution.path, cwd, ["listhost"], "cli-instance-mismatch", `未找到与 ${expectedChannel} CLI 匹配的 HBuilderX host`, "请启动对应版本,或检查 HBUILDERX_CLI_PATH、HBUILDERX_CHANNEL 和 HBUILDERX_HOST。", logs);
573
+ if (compatible.length > 1) throw createRunnerError(resolution.path, cwd, ["listhost"], "cli-host-ambiguous", `检测到多个匹配的 HBuilderX host:${compatible.map((item) => item.host).join(", ")}`, "请设置 HBUILDERX_HOST,或在 createHBuilderXRunner options 中显式传入 host。", logs);
574
+ const selected = compatible[0];
575
+ const boundResolution = {
576
+ ...resolution,
577
+ isRunning: true,
578
+ channel: selected.channel,
579
+ host: selected.host,
580
+ version: selected.version
581
+ };
582
+ const run = async (commandOptions) => await runCommand({
583
+ ...commandOptions,
584
+ command: resolution.path,
585
+ args: bindHost(commandOptions.args, selected.host),
586
+ cwd: commandOptions.cwd ?? cwd,
587
+ env: {
588
+ ...cliEnv,
589
+ ...commandOptions.env
590
+ }
591
+ });
592
+ const spawn = (commandOptions) => spawnCommand({
593
+ ...commandOptions,
594
+ command: resolution.path,
595
+ args: bindHost(commandOptions.args, selected.host),
596
+ cwd: commandOptions.cwd ?? cwd,
597
+ env: {
598
+ ...cliEnv,
599
+ ...commandOptions.env
600
+ }
601
+ });
602
+ const runner = {
603
+ resolution: boundResolution,
604
+ run,
605
+ spawn,
606
+ async closeProject(projectOptions) {
607
+ return await run({
608
+ ...projectOptions,
609
+ args: [
610
+ "project",
611
+ "close",
612
+ "--path",
613
+ node_path.default.resolve(projectOptions.cwd)
614
+ ],
615
+ allowFailure: projectOptions.allowFailure ?? true
616
+ });
617
+ },
618
+ async openProject(projectOptions) {
619
+ return await run({
620
+ ...projectOptions,
621
+ args: [
622
+ "project",
623
+ "open",
624
+ "--path",
625
+ node_path.default.resolve(projectOptions.cwd)
626
+ ]
627
+ });
628
+ },
629
+ async prepareProject(projectOptions) {
630
+ await runner.closeProject({
631
+ ...projectOptions,
632
+ allowFailure: true
633
+ });
634
+ return await runner.openProject(projectOptions);
635
+ },
636
+ async launchProject(launchOptions) {
637
+ return await run({
638
+ ...launchOptions,
639
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
640
+ });
641
+ },
642
+ startLaunch(launchOptions) {
643
+ return spawn({
644
+ ...launchOptions,
645
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
646
+ });
647
+ }
332
648
  };
333
- throw new Error("未找到 HBuilderX CLI。请先安装 HBuilderX,或设置 HBUILDERX_CLI_PATH=/path/to/cli。");
649
+ return runner;
650
+ }
651
+ //#endregion
652
+ //#region src/hbuilderx.ts
653
+ async function resolveHBuilderXCliInfo(candidatesOrOptions, env = node_process.default.env) {
654
+ return await resolveHBuilderXCliInfoFromOptions(Array.isArray(candidatesOrOptions) ? {
655
+ candidates: candidatesOrOptions,
656
+ env
657
+ } : candidatesOrOptions);
334
658
  }
335
- async function resolveHBuilderXCli(candidates) {
336
- return (await resolveHBuilderXCliInfo(candidates)).path;
659
+ async function resolveHBuilderXCli(candidatesOrOptions) {
660
+ return (await resolveHBuilderXCliInfo(candidatesOrOptions)).path;
337
661
  }
338
662
  function createHBuilderXEnv(options = {}) {
339
663
  return {
@@ -368,34 +692,13 @@ function spawnPnpmCommand(options) {
368
692
  });
369
693
  }
370
694
  async function closeProject(options) {
371
- return await runPnpmCommand({
372
- ...options,
373
- args: hbuilderxPnpmArgs([
374
- "project",
375
- "close",
376
- "--path",
377
- node_path.default.resolve(options.cwd)
378
- ]),
379
- allowFailure: options.allowFailure ?? true
380
- });
695
+ return await (await createHBuilderXRunner(options)).closeProject(options);
381
696
  }
382
697
  async function openProject(options) {
383
- return await runPnpmCommand({
384
- ...options,
385
- args: hbuilderxPnpmArgs([
386
- "project",
387
- "open",
388
- "--path",
389
- node_path.default.resolve(options.cwd)
390
- ])
391
- });
698
+ return await (await createHBuilderXRunner(options)).openProject(options);
392
699
  }
393
700
  async function prepareProject(options) {
394
- await closeProject({
395
- ...options,
396
- allowFailure: true
397
- });
398
- return await openProject(options);
701
+ return await (await createHBuilderXRunner(options)).prepareProject(options);
399
702
  }
400
703
  function createLaunchArgs(options) {
401
704
  const args = [
@@ -410,11 +713,11 @@ function createLaunchArgs(options) {
410
713
  return hbuilderxPnpmArgs(args);
411
714
  }
412
715
  async function launchProject(options) {
413
- return await runPnpmCommand({
414
- ...options,
415
- args: createLaunchArgs(options)
416
- });
716
+ return await (await createHBuilderXRunner(options)).launchProject(options);
417
717
  }
718
+ /**
719
+ * @deprecated 需要固定 stable/alpha 与 host 时,请使用 `createHBuilderXRunner().startLaunch()`。
720
+ */
418
721
  function startLaunch(options) {
419
722
  return spawnPnpmCommand({
420
723
  ...options,
@@ -492,6 +795,71 @@ function assertIosSimulatorToolchain(env = node_process.default.env) {
492
795
  "如果 firstLaunchStatus 不是 ready,请先打开 Xcode 完成首次组件安装,或执行 sudo xcodebuild -runFirstLaunch。"
493
796
  ].join("\n"));
494
797
  }
798
+ function parseIosSimulatorDevices(output) {
799
+ const jsonStart = output.indexOf("{");
800
+ const jsonEnd = output.lastIndexOf("}");
801
+ if (jsonStart < 0 || jsonEnd < jsonStart) return [];
802
+ let value;
803
+ try {
804
+ value = JSON.parse(output.slice(jsonStart, jsonEnd + 1));
805
+ } catch {
806
+ return [];
807
+ }
808
+ if (!value || typeof value !== "object" || !("devices" in value)) return [];
809
+ const devices = value.devices;
810
+ if (!devices || typeof devices !== "object") return [];
811
+ return Object.values(devices).flatMap((runtimeDevices) => {
812
+ if (!Array.isArray(runtimeDevices)) return [];
813
+ return runtimeDevices.flatMap((device) => {
814
+ if (!device || typeof device !== "object" || !("udid" in device) || typeof device.udid !== "string" || "isAvailable" in device && device.isAvailable === false) return [];
815
+ return [{
816
+ ..."lastBootedAt" in device && typeof device.lastBootedAt === "string" ? { lastBootedAt: device.lastBootedAt } : {},
817
+ name: "name" in device && typeof device.name === "string" ? device.name : device.udid,
818
+ state: "state" in device && typeof device.state === "string" ? device.state : "Unknown",
819
+ udid: device.udid
820
+ }];
821
+ });
822
+ });
823
+ }
824
+ function selectPreferredIosSimulatorDevice(devices) {
825
+ return [...devices].sort((left, right) => {
826
+ const stateDifference = Number(right.state === "Booted") - Number(left.state === "Booted");
827
+ if (stateDifference !== 0) return stateDifference;
828
+ const leftLastBootedAt = Date.parse(left.lastBootedAt ?? "");
829
+ const rightLastBootedAt = Date.parse(right.lastBootedAt ?? "");
830
+ const lastBootedDifference = (Number.isNaN(rightLastBootedAt) ? 0 : rightLastBootedAt) - (Number.isNaN(leftLastBootedAt) ? 0 : leftLastBootedAt);
831
+ if (lastBootedDifference !== 0) return lastBootedDifference;
832
+ return Number(/^iPhone\b/.test(right.name)) - Number(/^iPhone\b/.test(left.name));
833
+ })[0];
834
+ }
835
+ function resolveIosSimulatorDeviceId(env = node_process.default.env) {
836
+ const explicitDeviceId = env.E2E_HBUILDERX_IOS_DEVICE_ID;
837
+ if (explicitDeviceId) return explicitDeviceId;
838
+ const booted = runTool("xcrun", [
839
+ "simctl",
840
+ "list",
841
+ "devices",
842
+ "booted",
843
+ "--json"
844
+ ]);
845
+ const bootedDevice = selectPreferredIosSimulatorDevice(booted.ok ? parseIosSimulatorDevices(booted.output) : []);
846
+ if (bootedDevice) return bootedDevice.udid;
847
+ const available = runTool("xcrun", [
848
+ "simctl",
849
+ "list",
850
+ "devices",
851
+ "available",
852
+ "--json"
853
+ ]);
854
+ const availableDevice = selectPreferredIosSimulatorDevice(available.ok ? parseIosSimulatorDevices(available.output) : []);
855
+ if (availableDevice) return availableDevice.udid;
856
+ throw new Error([
857
+ "未找到可用于 HBuilderX app-ios E2E 的 iOS 模拟器。",
858
+ `booted: ${booted.output || "empty"}`,
859
+ `available: ${available.output || "empty"}`,
860
+ "请先在 Xcode 中安装并启动一个模拟器,或设置 E2E_HBUILDERX_IOS_DEVICE_ID。"
861
+ ].join("\n"));
862
+ }
495
863
  function resolveHdcCommand(env = node_process.default.env) {
496
864
  const candidates = [
497
865
  env.DEMO_VISUAL_HARMONY_HDC_PATH,
@@ -536,32 +904,51 @@ exports.classifyHBuilderXOutput = classifyHBuilderXOutput;
536
904
  exports.closeProject = closeProject;
537
905
  exports.collectProcessOutput = collectProcessOutput;
538
906
  exports.createHBuilderXEnv = createHBuilderXEnv;
907
+ exports.createHBuilderXNativeLaunchArgs = createHBuilderXNativeLaunchArgs;
908
+ exports.createHBuilderXRunner = createHBuilderXRunner;
539
909
  exports.createLaunchArgs = createLaunchArgs;
540
910
  exports.createLogBuffer = createLogBuffer;
541
911
  exports.createProcessExitTracker = createProcessExitTracker;
542
912
  exports.createTimeoutIssue = createTimeoutIssue;
543
913
  exports.extractHBuilderXExecutableFromProcessOutput = extractHBuilderXExecutableFromProcessOutput;
914
+ exports.extractHBuilderXExecutablesFromProcessOutput = extractHBuilderXExecutablesFromProcessOutput;
544
915
  exports.extractHBuilderXMacOSExecutable = extractHBuilderXMacOSExecutable;
916
+ exports.extractHBuilderXMacOSExecutables = extractHBuilderXMacOSExecutables;
545
917
  exports.extractHBuilderXWindowsExecutable = extractHBuilderXWindowsExecutable;
918
+ exports.extractHBuilderXWindowsExecutables = extractHBuilderXWindowsExecutables;
546
919
  exports.fileExists = fileExists;
547
920
  exports.findRunningHBuilderXCli = findRunningHBuilderXCli;
921
+ exports.findRunningHBuilderXCliCandidates = findRunningHBuilderXCliCandidates;
548
922
  exports.formatRecentLogs = formatRecentLogs;
549
923
  exports.getDefaultHBuilderXCliCandidates = getDefaultHBuilderXCliCandidates;
550
924
  exports.hbuilderxPnpmArgs = hbuilderxPnpmArgs;
925
+ exports.inferHBuilderXChannel = inferHBuilderXChannel;
926
+ exports.inferHBuilderXChannelFromVersion = inferHBuilderXChannelFromVersion;
551
927
  exports.killProcessTree = killProcessTree;
552
928
  exports.launchProject = launchProject;
929
+ exports.macOSAlphaCli = macOSAlphaCli;
930
+ exports.macOSStableCli = macOSStableCli;
553
931
  exports.openProject = openProject;
932
+ exports.parseHBuilderXHosts = parseHBuilderXHosts;
933
+ exports.parseHBuilderXVersion = parseHBuilderXVersion;
554
934
  exports.parseHdcTargets = parseHdcTargets;
935
+ exports.parseIosSimulatorDevices = parseIosSimulatorDevices;
555
936
  exports.prepareProject = prepareProject;
556
937
  exports.readUtf8 = readUtf8;
557
938
  exports.resolveAdbCommand = resolveAdbCommand;
939
+ exports.resolveHBuilderXChannel = resolveHBuilderXChannel;
558
940
  exports.resolveHBuilderXCli = resolveHBuilderXCli;
559
941
  exports.resolveHBuilderXCliInfo = resolveHBuilderXCliInfo;
942
+ exports.resolveHBuilderXCliInfoFromOptions = resolveHBuilderXCliInfoFromOptions;
560
943
  exports.resolveHdcCommand = resolveHdcCommand;
944
+ exports.resolveIosSimulatorDeviceId = resolveIosSimulatorDeviceId;
561
945
  exports.runCommand = runCommand;
562
946
  exports.runPnpmCommand = runPnpmCommand;
563
947
  exports.runTool = runTool;
948
+ exports.selectHBuilderXCliCandidatesForChannel = selectHBuilderXCliCandidatesForChannel;
949
+ exports.selectPreferredIosSimulatorDevice = selectPreferredIosSimulatorDevice;
564
950
  exports.spawnCommand = spawnCommand;
565
951
  exports.spawnPnpmCommand = spawnPnpmCommand;
566
952
  exports.startLaunch = startLaunch;
953
+ exports.stripAnsi = stripAnsi;
567
954
  exports.wait = wait;