@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.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
- import { spawn, spawnSync } from "node:child_process";
3
2
  import path from "node:path";
4
3
  import process from "node:process";
4
+ import { spawn, spawnSync } from "node:child_process";
5
5
  //#region src/fs.ts
6
6
  async function fileExists(file) {
7
7
  try {
@@ -18,11 +18,146 @@ function wait(ms) {
18
18
  return new Promise((resolve) => setTimeout(resolve, ms));
19
19
  }
20
20
  //#endregion
21
+ //#region src/hbuilderx/discovery.ts
22
+ const macOSStableCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
23
+ const macOSAlphaCli = "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli";
24
+ function unique(items) {
25
+ return [...new Set(items)];
26
+ }
27
+ function normalizeFile(file, platform = process.platform) {
28
+ const normalized = path.normalize(file);
29
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
30
+ }
31
+ function resolveHBuilderXChannel(channel) {
32
+ const value = channel ?? "auto";
33
+ if (value === "auto" || value === "stable" || value === "alpha") return value;
34
+ throw new Error(`无效的 HBuilderX channel:${value}。可选值为 auto、stable、alpha。`);
35
+ }
36
+ function inferHBuilderXChannel(file) {
37
+ if (/HBuilderX(?:-|\s*)Alpha(?:\.app)?[\\/]/i.test(file) || /(?:^|[\\/])alpha(?:[\\/]|$)/i.test(file)) return "alpha";
38
+ if (/HBuilderX(?:\.app)?[\\/]/i.test(file) || /HBuilderX\.exe$/i.test(file)) return "stable";
39
+ return "unknown";
40
+ }
41
+ function getDefaultHBuilderXCliCandidates(env = process.env, channel = resolveHBuilderXChannel(env.HBUILDERX_CHANNEL), platform = process.platform) {
42
+ const defaults = platform === "darwin" ? channel === "stable" ? [macOSStableCli] : channel === "alpha" ? [macOSAlphaCli] : [macOSStableCli, macOSAlphaCli] : [];
43
+ return unique([env.HBUILDERX_CLI_PATH, ...defaults].filter((item) => Boolean(item)));
44
+ }
45
+ function extractHBuilderXMacOSExecutables(output) {
46
+ return unique(Array.from(output.matchAll(/(\/[^\r\n]*?HBuilderX(?:-Alpha|\s+Alpha)?\.app\/Contents\/MacOS\/HBuilderX)(?=\s|$)/gi), (match) => match[1]));
47
+ }
48
+ function extractHBuilderXWindowsExecutables(output) {
49
+ const executables = [];
50
+ for (const line of output.split(/\r?\n/)) {
51
+ const executable = line.split(",").at(-1)?.trim();
52
+ if (executable?.toLowerCase().endsWith("hbuilderx.exe")) executables.push(executable);
53
+ }
54
+ return unique(executables);
55
+ }
56
+ function extractHBuilderXExecutablesFromProcessOutput(output, platform = process.platform) {
57
+ return platform === "win32" ? extractHBuilderXWindowsExecutables(output) : extractHBuilderXMacOSExecutables(output);
58
+ }
59
+ function extractHBuilderXMacOSExecutable(line) {
60
+ return extractHBuilderXMacOSExecutables(line)[0];
61
+ }
62
+ function extractHBuilderXWindowsExecutable(line) {
63
+ return extractHBuilderXWindowsExecutables(line)[0];
64
+ }
65
+ function extractHBuilderXExecutableFromProcessOutput(output, platform = process.platform) {
66
+ return extractHBuilderXExecutablesFromProcessOutput(output, platform)[0];
67
+ }
68
+ async function findRunningHBuilderXCliCandidates(platform = process.platform) {
69
+ const result = platform === "win32" ? spawnSync("wmic", [
70
+ "process",
71
+ "where",
72
+ "name='HBuilderX.exe'",
73
+ "get",
74
+ "executablepath",
75
+ "/format:csv"
76
+ ], {
77
+ encoding: "utf8",
78
+ windowsHide: true
79
+ }) : spawnSync("ps", [
80
+ "-ax",
81
+ "-o",
82
+ "command="
83
+ ], { encoding: "utf8" });
84
+ if (result.error || result.status !== 0) return [];
85
+ const executables = extractHBuilderXExecutablesFromProcessOutput(`${result.stdout ?? ""}${result.stderr ?? ""}`, platform);
86
+ const candidates = [];
87
+ for (const executable of executables) {
88
+ if (!await fileExists(executable)) continue;
89
+ const cli = path.join(path.dirname(executable), platform === "win32" ? "cli.exe" : "cli");
90
+ if (await fileExists(cli)) candidates.push(cli);
91
+ }
92
+ return unique(candidates);
93
+ }
94
+ async function findRunningHBuilderXCli(platform = process.platform) {
95
+ return (await findRunningHBuilderXCliCandidates(platform))[0];
96
+ }
97
+ function sortByChannel(items) {
98
+ const weights = {
99
+ stable: 0,
100
+ alpha: 1,
101
+ unknown: 2
102
+ };
103
+ return [...items].sort((left, right) => weights[inferHBuilderXChannel(left)] - weights[inferHBuilderXChannel(right)]);
104
+ }
105
+ function selectHBuilderXCliCandidatesForChannel(items, channel) {
106
+ if (channel === "auto") return sortByChannel(items);
107
+ return items.filter((item) => inferHBuilderXChannel(item) === channel);
108
+ }
109
+ function resolveCandidateSource(candidate, env) {
110
+ if (candidate === env.HBUILDERX_CLI_PATH) return "env";
111
+ if (candidate === "/Applications/HBuilderX.app/Contents/MacOS/cli" || candidate === "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli") return "default-path";
112
+ return "candidate";
113
+ }
114
+ async function firstExisting(items) {
115
+ for (const item of items) if (await fileExists(item)) return item;
116
+ }
117
+ async function resolveHBuilderXCliInfoFromOptions(options = {}) {
118
+ const env = options.env ?? process.env;
119
+ const channel = resolveHBuilderXChannel(options.channel ?? env.HBUILDERX_CHANNEL);
120
+ const running = await findRunningHBuilderXCliCandidates();
121
+ if (options.candidates) {
122
+ const candidate = await firstExisting(options.candidates);
123
+ if (candidate) return {
124
+ path: candidate,
125
+ isRunning: running.some((item) => normalizeFile(item) === normalizeFile(candidate)),
126
+ source: resolveCandidateSource(candidate, env),
127
+ channel: inferHBuilderXChannel(candidate)
128
+ };
129
+ throw new Error("未找到显式指定的 HBuilderX CLI candidate。");
130
+ }
131
+ if (env.HBUILDERX_CLI_PATH && await fileExists(env.HBUILDERX_CLI_PATH)) return {
132
+ path: env.HBUILDERX_CLI_PATH,
133
+ isRunning: running.some((item) => normalizeFile(item) === normalizeFile(env.HBUILDERX_CLI_PATH)),
134
+ source: "env",
135
+ channel: inferHBuilderXChannel(env.HBUILDERX_CLI_PATH)
136
+ };
137
+ const runningCandidate = selectHBuilderXCliCandidatesForChannel(running, channel)[0];
138
+ if (runningCandidate) return {
139
+ path: runningCandidate,
140
+ isRunning: true,
141
+ source: "running-process",
142
+ channel: inferHBuilderXChannel(runningCandidate)
143
+ };
144
+ const defaultCandidate = await firstExisting(getDefaultHBuilderXCliCandidates({}, channel));
145
+ if (defaultCandidate) return {
146
+ path: defaultCandidate,
147
+ isRunning: false,
148
+ source: "default-path",
149
+ channel: inferHBuilderXChannel(defaultCandidate)
150
+ };
151
+ throw new Error([`未找到 HBuilderX ${channel === "auto" ? "" : `${channel} `}CLI。`, "请安装 HBuilderX,或设置 HBUILDERX_CLI_PATH=/path/to/cli。"].join(""));
152
+ }
153
+ //#endregion
21
154
  //#region src/logs.ts
22
155
  const PROJECT_NOT_UNI_APP_RE = /不是\s*uni-app\s*项目|not\s+a\s+uni-app\s+project/i;
23
156
  const PROJECT_TYPE_UNSUPPORTED_RE = /项目类型为(.+?),暂不支持|project\s+type.+unsupported/i;
24
157
  const CONFIG_LOAD_FAILED_RE = /failed to load config|error when starting dev server|Failed to resolve entry for package/i;
25
158
  const CLI_NOT_FOUND_RE = /未找到\s*HBuilderX\s*CLI|HBUILDERX_CLI_PATH|command not found|ENOENT/i;
159
+ const CLI_INSTANCE_MISMATCH_RE = /当前运行的cli与正在运行的HBuilderX不匹配|cli.+(?:does not match|mismatch).+HBuilderX|try.+HBuilderX.+(?:cli|MacOS)/i;
160
+ const CLI_HOST_AMBIGUOUS_RE = /multiple running hbuilderx|多个.+HBuilderX.+运行|listhost.+--\s*host|--host.+listhost/i;
26
161
  const ANDROID_TOOLCHAIN_MISSING_RE = /adb(?:\.exe)?(?:\s*[::].*)?(?:not found|ENOENT|不是内部或外部命令)|Android SDK|platform-tools/i;
27
162
  const IOS_TOOLCHAIN_MISSING_RE = /xcrun|xcode-select|xcodebuild|simctl|DEVELOPER_DIR|iOS 模拟器|Xcode/i;
28
163
  const HARMONY_TOOLCHAIN_MISSING_RE = /(?:^|\s)hdc[\s::]|Harmony|DevEco|OpenHarmony/i;
@@ -46,6 +181,16 @@ function collectProcessOutput(child, maxChunks = 160) {
46
181
  return buffer.logs;
47
182
  }
48
183
  function classifyHBuilderXOutput(output) {
184
+ if (CLI_INSTANCE_MISMATCH_RE.test(output)) return {
185
+ kind: "cli-instance-mismatch",
186
+ message: "当前 HBuilderX CLI 与目标运行实例不匹配。",
187
+ hint: "请使用与目标 stable/alpha 实例对应的 CLI,并通过 listhost 与 --host 绑定运行实例。"
188
+ };
189
+ if (CLI_HOST_AMBIGUOUS_RE.test(output)) return {
190
+ kind: "cli-host-ambiguous",
191
+ message: "检测到多个可用的 HBuilderX 运行实例。",
192
+ hint: "请设置 HBUILDERX_HOST,或在 runner options 中显式传入 host。"
193
+ };
49
194
  if (ANDROID_TOOLCHAIN_MISSING_RE.test(output)) return {
50
195
  kind: "android-toolchain-missing",
51
196
  message: "当前环境缺少 Android 运行所需工具链。",
@@ -244,70 +389,249 @@ function createProcessExitTracker(child) {
244
389
  };
245
390
  }
246
391
  //#endregion
247
- //#region src/hbuilderx.ts
248
- const macOSDefaultCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
249
- function getDefaultHBuilderXCliCandidates(env = process.env) {
250
- return [env.HBUILDERX_CLI_PATH, process.platform === "darwin" ? macOSDefaultCli : void 0].filter((item) => Boolean(item));
392
+ //#region src/hbuilderx/runner.ts
393
+ const ansiRE = new RegExp(`${String.fromCharCode(27)}\\[[\\d;]*m`, "g");
394
+ const defaultStartupTimeoutMs = 6e4;
395
+ const hostPollIntervalMs = 500;
396
+ const maxSessionLogChunks = 160;
397
+ function stripAnsi(value) {
398
+ return value.replace(ansiRE, "");
251
399
  }
252
- function extractHBuilderXMacOSExecutable(line) {
253
- return line.match(/(\/.*?HBuilderX[^/]*\.app\/Contents\/MacOS\/HBuilderX)(?:\s|$)/i)?.[1];
400
+ function parseHBuilderXHosts(output) {
401
+ 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)))];
254
402
  }
255
- function extractHBuilderXWindowsExecutable(line) {
256
- const executable = line.split(",").at(-1)?.trim();
257
- return executable?.toLowerCase().endsWith("hbuilderx.exe") ? executable : void 0;
403
+ function parseHBuilderXVersion(output) {
404
+ return stripAnsi(output).match(/\b(\d+\.\d+(?:\.\d+)+(?:-[0-9a-z.-]+)?)\b/i)?.[1];
258
405
  }
259
- function extractHBuilderXExecutableFromProcessOutput(output, platform = process.platform) {
260
- for (const line of output.split(/\r?\n/)) {
261
- const executable = platform === "win32" ? extractHBuilderXWindowsExecutable(line) : extractHBuilderXMacOSExecutable(line);
262
- if (executable) return executable;
263
- }
406
+ function inferHBuilderXChannelFromVersion(version) {
407
+ return /(?:^|-)alpha(?:\.|$)/i.test(version) ? "alpha" : "stable";
264
408
  }
265
- async function findRunningHBuilderXCli(platform = process.platform) {
266
- const result = platform === "win32" ? spawnSync("wmic", [
267
- "process",
268
- "where",
269
- "name='HBuilderX.exe'",
270
- "get",
271
- "executablepath",
272
- "/format:csv"
273
- ], {
274
- encoding: "utf8",
275
- windowsHide: true
276
- }) : spawnSync("ps", [
277
- "-ax",
278
- "-o",
279
- "command="
280
- ], { encoding: "utf8" });
281
- if (result.error || result.status !== 0) return;
282
- const executable = extractHBuilderXExecutableFromProcessOutput(`${result.stdout ?? ""}${result.stderr ?? ""}`, platform);
283
- if (!executable || !await fileExists(executable)) return;
284
- const cli = path.join(path.dirname(executable), platform === "win32" ? "cli.exe" : "cli");
285
- return await fileExists(cli) ? cli : void 0;
409
+ function createHBuilderXNativeLaunchArgs(options) {
410
+ const args = [
411
+ "launch",
412
+ options.platform,
413
+ "--project",
414
+ path.resolve(options.cwd),
415
+ ...options.args ?? []
416
+ ];
417
+ if (options.compile != null && !args.includes("--compile")) args.push("--compile", String(options.compile));
418
+ if (options.runtimeLog != null && !args.includes("--runtime-log")) args.push("--runtime-log", String(options.runtimeLog));
419
+ return args;
286
420
  }
287
- function resolveCandidateSource(candidate, env) {
288
- if (candidate === env.HBUILDERX_CLI_PATH) return "env";
289
- if (candidate === macOSDefaultCli) return "default-path";
290
- return "candidate";
421
+ function createRunnerError(cliPath, cwd, args, kind, message, hint, logs) {
422
+ const output = formatRecentLogs(logs);
423
+ return new HBuilderXCommandError([
424
+ `${message}: ${cliPath} ${args.join(" ")}`,
425
+ `cwd=${cwd}`,
426
+ `issue=${kind}: ${message}`,
427
+ `hint=${hint}`,
428
+ output
429
+ ].filter(Boolean).join("\n"), {
430
+ command: cliPath,
431
+ args,
432
+ cwd,
433
+ exit: {
434
+ code: null,
435
+ signal: null
436
+ },
437
+ logs,
438
+ output,
439
+ issue: {
440
+ kind,
441
+ message,
442
+ hint
443
+ }
444
+ });
445
+ }
446
+ function bindHost(args, host) {
447
+ const hostIndex = args.indexOf("--host");
448
+ if (hostIndex < 0) return [
449
+ ...args,
450
+ "--host",
451
+ host
452
+ ];
453
+ if (args[hostIndex + 1] !== host) throw new Error(`runner 已绑定 HBuilderX host=${host},不能改为 ${args[hostIndex + 1] ?? "空值"}。`);
454
+ return args;
455
+ }
456
+ function appendLogs(target, source) {
457
+ target.push(...source);
458
+ if (target.length > maxSessionLogChunks) target.splice(0, target.length - maxSessionLogChunks);
291
459
  }
292
- async function resolveHBuilderXCliInfo(candidates, env = process.env) {
293
- if (!candidates) {
294
- const runningCli = await findRunningHBuilderXCli();
295
- if (runningCli) return {
296
- path: runningCli,
297
- isRunning: true,
298
- source: "running-process"
460
+ async function listCompatibleHosts(cliPath, cwd, env, expectedChannel, explicitHost, timeoutMs) {
461
+ const startedAt = Date.now();
462
+ const logs = [];
463
+ do {
464
+ const listed = await runCommand({
465
+ command: cliPath,
466
+ args: ["listhost"],
467
+ cwd,
468
+ env,
469
+ timeoutMs: Math.min(timeoutMs, 1e4),
470
+ allowFailure: true
471
+ });
472
+ appendLogs(logs, listed.logs);
473
+ const hosts = explicitHost ? [explicitHost] : parseHBuilderXHosts(listed.output);
474
+ const compatible = [];
475
+ for (const host of hosts) {
476
+ const versionResult = await runCommand({
477
+ command: cliPath,
478
+ args: [
479
+ "version",
480
+ "--host",
481
+ host
482
+ ],
483
+ cwd,
484
+ env,
485
+ timeoutMs: Math.min(timeoutMs, 1e4),
486
+ allowFailure: true
487
+ });
488
+ appendLogs(logs, versionResult.logs);
489
+ if (versionResult.issue.kind === "cli-instance-mismatch") return {
490
+ compatible: [],
491
+ logs
492
+ };
493
+ const version = versionResult.exit.code === 0 ? parseHBuilderXVersion(versionResult.output) : void 0;
494
+ if (!version) continue;
495
+ const channel = inferHBuilderXChannelFromVersion(version);
496
+ if (expectedChannel === "unknown" || channel === expectedChannel) compatible.push({
497
+ host,
498
+ version,
499
+ channel
500
+ });
501
+ }
502
+ if (compatible.length > 0) return {
503
+ compatible,
504
+ logs
299
505
  };
506
+ await wait(hostPollIntervalMs);
507
+ } while (Date.now() - startedAt < timeoutMs);
508
+ return {
509
+ compatible: [],
510
+ logs
511
+ };
512
+ }
513
+ async function createHBuilderXRunner(options = {}) {
514
+ const env = {
515
+ ...process.env,
516
+ ...options.env
517
+ };
518
+ const cwd = options.cwd ?? process.cwd();
519
+ const timeoutMs = options.timeoutMs ?? defaultStartupTimeoutMs;
520
+ const resolution = await resolveHBuilderXCliInfoFromOptions({
521
+ candidates: options.hbuilderxCliPath ? [options.hbuilderxCliPath] : options.candidates,
522
+ channel: options.channel,
523
+ env,
524
+ host: options.host
525
+ });
526
+ const cliEnv = {
527
+ ...env,
528
+ HBUILDERX_CLI_PATH: resolution.path
529
+ };
530
+ if (!resolution.isRunning) {
531
+ const opened = await runCommand({
532
+ command: resolution.path,
533
+ args: ["open"],
534
+ cwd,
535
+ env: cliEnv,
536
+ timeoutMs,
537
+ allowFailure: true
538
+ });
539
+ const openIssue = classifyHBuilderXOutput(opened.output);
540
+ 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);
300
541
  }
301
- const items = candidates ?? getDefaultHBuilderXCliCandidates(env);
302
- for (const item of items) if (await fileExists(item)) return {
303
- path: item,
304
- isRunning: false,
305
- source: resolveCandidateSource(item, env)
542
+ const requestedChannel = resolveHBuilderXChannel(options.channel ?? env.HBUILDERX_CHANNEL);
543
+ const expectedChannel = resolution.channel !== "unknown" ? resolution.channel : requestedChannel === "auto" ? inferHBuilderXChannel(resolution.path) : requestedChannel;
544
+ const explicitHost = options.host ?? env.HBUILDERX_HOST;
545
+ const { compatible, logs } = await listCompatibleHosts(resolution.path, cwd, cliEnv, expectedChannel, explicitHost, timeoutMs);
546
+ 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);
547
+ 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);
548
+ const selected = compatible[0];
549
+ const boundResolution = {
550
+ ...resolution,
551
+ isRunning: true,
552
+ channel: selected.channel,
553
+ host: selected.host,
554
+ version: selected.version
555
+ };
556
+ const run = async (commandOptions) => await runCommand({
557
+ ...commandOptions,
558
+ command: resolution.path,
559
+ args: bindHost(commandOptions.args, selected.host),
560
+ cwd: commandOptions.cwd ?? cwd,
561
+ env: {
562
+ ...cliEnv,
563
+ ...commandOptions.env
564
+ }
565
+ });
566
+ const spawn = (commandOptions) => spawnCommand({
567
+ ...commandOptions,
568
+ command: resolution.path,
569
+ args: bindHost(commandOptions.args, selected.host),
570
+ cwd: commandOptions.cwd ?? cwd,
571
+ env: {
572
+ ...cliEnv,
573
+ ...commandOptions.env
574
+ }
575
+ });
576
+ const runner = {
577
+ resolution: boundResolution,
578
+ run,
579
+ spawn,
580
+ async closeProject(projectOptions) {
581
+ return await run({
582
+ ...projectOptions,
583
+ args: [
584
+ "project",
585
+ "close",
586
+ "--path",
587
+ path.resolve(projectOptions.cwd)
588
+ ],
589
+ allowFailure: projectOptions.allowFailure ?? true
590
+ });
591
+ },
592
+ async openProject(projectOptions) {
593
+ return await run({
594
+ ...projectOptions,
595
+ args: [
596
+ "project",
597
+ "open",
598
+ "--path",
599
+ path.resolve(projectOptions.cwd)
600
+ ]
601
+ });
602
+ },
603
+ async prepareProject(projectOptions) {
604
+ await runner.closeProject({
605
+ ...projectOptions,
606
+ allowFailure: true
607
+ });
608
+ return await runner.openProject(projectOptions);
609
+ },
610
+ async launchProject(launchOptions) {
611
+ return await run({
612
+ ...launchOptions,
613
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
614
+ });
615
+ },
616
+ startLaunch(launchOptions) {
617
+ return spawn({
618
+ ...launchOptions,
619
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
620
+ });
621
+ }
306
622
  };
307
- throw new Error("未找到 HBuilderX CLI。请先安装 HBuilderX,或设置 HBUILDERX_CLI_PATH=/path/to/cli。");
623
+ return runner;
624
+ }
625
+ //#endregion
626
+ //#region src/hbuilderx.ts
627
+ async function resolveHBuilderXCliInfo(candidatesOrOptions, env = process.env) {
628
+ return await resolveHBuilderXCliInfoFromOptions(Array.isArray(candidatesOrOptions) ? {
629
+ candidates: candidatesOrOptions,
630
+ env
631
+ } : candidatesOrOptions);
308
632
  }
309
- async function resolveHBuilderXCli(candidates) {
310
- return (await resolveHBuilderXCliInfo(candidates)).path;
633
+ async function resolveHBuilderXCli(candidatesOrOptions) {
634
+ return (await resolveHBuilderXCliInfo(candidatesOrOptions)).path;
311
635
  }
312
636
  function createHBuilderXEnv(options = {}) {
313
637
  return {
@@ -342,34 +666,13 @@ function spawnPnpmCommand(options) {
342
666
  });
343
667
  }
344
668
  async function closeProject(options) {
345
- return await runPnpmCommand({
346
- ...options,
347
- args: hbuilderxPnpmArgs([
348
- "project",
349
- "close",
350
- "--path",
351
- path.resolve(options.cwd)
352
- ]),
353
- allowFailure: options.allowFailure ?? true
354
- });
669
+ return await (await createHBuilderXRunner(options)).closeProject(options);
355
670
  }
356
671
  async function openProject(options) {
357
- return await runPnpmCommand({
358
- ...options,
359
- args: hbuilderxPnpmArgs([
360
- "project",
361
- "open",
362
- "--path",
363
- path.resolve(options.cwd)
364
- ])
365
- });
672
+ return await (await createHBuilderXRunner(options)).openProject(options);
366
673
  }
367
674
  async function prepareProject(options) {
368
- await closeProject({
369
- ...options,
370
- allowFailure: true
371
- });
372
- return await openProject(options);
675
+ return await (await createHBuilderXRunner(options)).prepareProject(options);
373
676
  }
374
677
  function createLaunchArgs(options) {
375
678
  const args = [
@@ -384,11 +687,11 @@ function createLaunchArgs(options) {
384
687
  return hbuilderxPnpmArgs(args);
385
688
  }
386
689
  async function launchProject(options) {
387
- return await runPnpmCommand({
388
- ...options,
389
- args: createLaunchArgs(options)
390
- });
690
+ return await (await createHBuilderXRunner(options)).launchProject(options);
391
691
  }
692
+ /**
693
+ * @deprecated 需要固定 stable/alpha 与 host 时,请使用 `createHBuilderXRunner().startLaunch()`。
694
+ */
392
695
  function startLaunch(options) {
393
696
  return spawnPnpmCommand({
394
697
  ...options,
@@ -466,6 +769,71 @@ function assertIosSimulatorToolchain(env = process.env) {
466
769
  "如果 firstLaunchStatus 不是 ready,请先打开 Xcode 完成首次组件安装,或执行 sudo xcodebuild -runFirstLaunch。"
467
770
  ].join("\n"));
468
771
  }
772
+ function parseIosSimulatorDevices(output) {
773
+ const jsonStart = output.indexOf("{");
774
+ const jsonEnd = output.lastIndexOf("}");
775
+ if (jsonStart < 0 || jsonEnd < jsonStart) return [];
776
+ let value;
777
+ try {
778
+ value = JSON.parse(output.slice(jsonStart, jsonEnd + 1));
779
+ } catch {
780
+ return [];
781
+ }
782
+ if (!value || typeof value !== "object" || !("devices" in value)) return [];
783
+ const devices = value.devices;
784
+ if (!devices || typeof devices !== "object") return [];
785
+ return Object.values(devices).flatMap((runtimeDevices) => {
786
+ if (!Array.isArray(runtimeDevices)) return [];
787
+ return runtimeDevices.flatMap((device) => {
788
+ if (!device || typeof device !== "object" || !("udid" in device) || typeof device.udid !== "string" || "isAvailable" in device && device.isAvailable === false) return [];
789
+ return [{
790
+ ..."lastBootedAt" in device && typeof device.lastBootedAt === "string" ? { lastBootedAt: device.lastBootedAt } : {},
791
+ name: "name" in device && typeof device.name === "string" ? device.name : device.udid,
792
+ state: "state" in device && typeof device.state === "string" ? device.state : "Unknown",
793
+ udid: device.udid
794
+ }];
795
+ });
796
+ });
797
+ }
798
+ function selectPreferredIosSimulatorDevice(devices) {
799
+ return [...devices].sort((left, right) => {
800
+ const stateDifference = Number(right.state === "Booted") - Number(left.state === "Booted");
801
+ if (stateDifference !== 0) return stateDifference;
802
+ const leftLastBootedAt = Date.parse(left.lastBootedAt ?? "");
803
+ const rightLastBootedAt = Date.parse(right.lastBootedAt ?? "");
804
+ const lastBootedDifference = (Number.isNaN(rightLastBootedAt) ? 0 : rightLastBootedAt) - (Number.isNaN(leftLastBootedAt) ? 0 : leftLastBootedAt);
805
+ if (lastBootedDifference !== 0) return lastBootedDifference;
806
+ return Number(/^iPhone\b/.test(right.name)) - Number(/^iPhone\b/.test(left.name));
807
+ })[0];
808
+ }
809
+ function resolveIosSimulatorDeviceId(env = process.env) {
810
+ const explicitDeviceId = env.E2E_HBUILDERX_IOS_DEVICE_ID;
811
+ if (explicitDeviceId) return explicitDeviceId;
812
+ const booted = runTool("xcrun", [
813
+ "simctl",
814
+ "list",
815
+ "devices",
816
+ "booted",
817
+ "--json"
818
+ ]);
819
+ const bootedDevice = selectPreferredIosSimulatorDevice(booted.ok ? parseIosSimulatorDevices(booted.output) : []);
820
+ if (bootedDevice) return bootedDevice.udid;
821
+ const available = runTool("xcrun", [
822
+ "simctl",
823
+ "list",
824
+ "devices",
825
+ "available",
826
+ "--json"
827
+ ]);
828
+ const availableDevice = selectPreferredIosSimulatorDevice(available.ok ? parseIosSimulatorDevices(available.output) : []);
829
+ if (availableDevice) return availableDevice.udid;
830
+ throw new Error([
831
+ "未找到可用于 HBuilderX app-ios E2E 的 iOS 模拟器。",
832
+ `booted: ${booted.output || "empty"}`,
833
+ `available: ${available.output || "empty"}`,
834
+ "请先在 Xcode 中安装并启动一个模拟器,或设置 E2E_HBUILDERX_IOS_DEVICE_ID。"
835
+ ].join("\n"));
836
+ }
469
837
  function resolveHdcCommand(env = process.env) {
470
838
  const candidates = [
471
839
  env.DEMO_VISUAL_HARMONY_HDC_PATH,
@@ -502,4 +870,4 @@ function assertHarmonyToolchain(env = process.env, deviceId) {
502
870
  return hdc;
503
871
  }
504
872
  //#endregion
505
- export { HBuilderXCommandError, assertAndroidToolchain, assertHarmonyToolchain, assertIosSimulatorToolchain, classifyHBuilderXOutput, closeProject, collectProcessOutput, createHBuilderXEnv, createLaunchArgs, createLogBuffer, createProcessExitTracker, createTimeoutIssue, extractHBuilderXExecutableFromProcessOutput, extractHBuilderXMacOSExecutable, extractHBuilderXWindowsExecutable, fileExists, findRunningHBuilderXCli, formatRecentLogs, getDefaultHBuilderXCliCandidates, hbuilderxPnpmArgs, killProcessTree, launchProject, openProject, parseHdcTargets, prepareProject, readUtf8, resolveAdbCommand, resolveHBuilderXCli, resolveHBuilderXCliInfo, resolveHdcCommand, runCommand, runPnpmCommand, runTool, spawnCommand, spawnPnpmCommand, startLaunch, wait };
873
+ export { HBuilderXCommandError, assertAndroidToolchain, assertHarmonyToolchain, assertIosSimulatorToolchain, classifyHBuilderXOutput, closeProject, collectProcessOutput, createHBuilderXEnv, createHBuilderXNativeLaunchArgs, createHBuilderXRunner, createLaunchArgs, createLogBuffer, createProcessExitTracker, createTimeoutIssue, extractHBuilderXExecutableFromProcessOutput, extractHBuilderXExecutablesFromProcessOutput, extractHBuilderXMacOSExecutable, extractHBuilderXMacOSExecutables, extractHBuilderXWindowsExecutable, extractHBuilderXWindowsExecutables, fileExists, findRunningHBuilderXCli, findRunningHBuilderXCliCandidates, formatRecentLogs, getDefaultHBuilderXCliCandidates, hbuilderxPnpmArgs, inferHBuilderXChannel, inferHBuilderXChannelFromVersion, killProcessTree, launchProject, macOSAlphaCli, macOSStableCli, openProject, parseHBuilderXHosts, parseHBuilderXVersion, parseHdcTargets, parseIosSimulatorDevices, prepareProject, readUtf8, resolveAdbCommand, resolveHBuilderXChannel, resolveHBuilderXCli, resolveHBuilderXCliInfo, resolveHBuilderXCliInfoFromOptions, resolveHdcCommand, resolveIosSimulatorDeviceId, runCommand, runPnpmCommand, runTool, selectHBuilderXCliCandidatesForChannel, selectPreferredIosSimulatorDevice, spawnCommand, spawnPnpmCommand, startLaunch, stripAnsi, wait };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@weapp-tailwindcss/hbuilderx-runner",
3
3
  "type": "module",
4
- "version": "0.0.3",
4
+ "version": "0.1.0",
5
5
  "description": "Stable HBuilderX CLI runner utilities for weapp-tailwindcss local e2e workflows.",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",