@weapp-tailwindcss/hbuilderx-runner 0.0.4 → 0.1.1

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,24 +44,180 @@ 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
- const PROJECT_TYPE_UNSUPPORTED_RE = /项目类型为(.+?),暂不支持|project\s+type.+unsupported/i;
182
+ const PROJECT_TYPE_UNSUPPORTED_RE = /项目类型为([^,]+),暂不支持|是\s+([^,\s][^,]*)项目,暂不支持|project\s+type.+unsupported/i;
183
+ const PROJECT_TARGET_UNSUPPORTED_RE = /不支持运行到\s*(鸿蒙|Harmony)|(?:Harmony|OpenHarmony).+(?:target|platform).+unsupported/i;
50
184
  const CONFIG_LOAD_FAILED_RE = /failed to load config|error when starting dev server|Failed to resolve entry for package/i;
51
185
  const CLI_NOT_FOUND_RE = /未找到\s*HBuilderX\s*CLI|HBUILDERX_CLI_PATH|command not found|ENOENT/i;
186
+ const CLI_INSTANCE_MISMATCH_RE = /当前运行的cli与正在运行的HBuilderX不匹配|cli.+(?:does not match|mismatch).+HBuilderX|try.+HBuilderX.+(?:cli|MacOS)/i;
187
+ const CLI_HOST_AMBIGUOUS_RE = /multiple running hbuilderx|多个.+HBuilderX.+运行|listhost.+--\s*host|--host.+listhost/i;
52
188
  const ANDROID_TOOLCHAIN_MISSING_RE = /adb(?:\.exe)?(?:\s*[::].*)?(?:not found|ENOENT|不是内部或外部命令)|Android SDK|platform-tools/i;
53
189
  const IOS_TOOLCHAIN_MISSING_RE = /xcrun|xcode-select|xcodebuild|simctl|DEVELOPER_DIR|iOS 模拟器|Xcode/i;
54
- const HARMONY_TOOLCHAIN_MISSING_RE = /(?:^|\s)hdc[\s::]|Harmony|DevEco|OpenHarmony/i;
190
+ const HARMONY_TOOLCHAIN_MISSING_RES = [
191
+ /hdc(?:\.exe)?(?:\s+(?:list\s+targets|target\s+list))?\s*(?:[::]\s*)?(?:failed|not found|ENOENT|command not found)/i,
192
+ /未找到\s*(?:DevEco|鸿蒙)[^\r\n]*(?:SDK|工具链)/i,
193
+ /DevEco Studio[^\r\n]*(?:not found|未安装)/i,
194
+ /HDC_PATH/i
195
+ ];
196
+ const HARMONY_BUILD_FAILED_RE = /Failed to resolve OhmUrl|ArkTS Compiler Error|运行包制作失败|hvigor ERROR/i;
197
+ const IMPORTANT_LOG_RE = /\b(?:fatal|error)\b|失败|已停止运行/i;
198
+ const importantLogsByBuffer = /* @__PURE__ */ new WeakMap();
55
199
  function createLogBuffer(maxChunks = 160) {
56
200
  const logs = [];
201
+ const importantLogs = [];
202
+ const importantLogSet = /* @__PURE__ */ new Set();
203
+ importantLogsByBuffer.set(logs, importantLogs);
57
204
  return {
58
205
  logs,
59
206
  push(chunk) {
60
- logs.push(chunk.toString());
207
+ const text = chunk.toString();
208
+ logs.push(text);
61
209
  if (logs.length > maxChunks) logs.splice(0, logs.length - maxChunks);
210
+ for (const item of text.split(/\r?\n/)) {
211
+ if (!IMPORTANT_LOG_RE.test(item)) continue;
212
+ const line = item.trim();
213
+ if (!line || importantLogSet.has(line)) continue;
214
+ importantLogSet.add(line);
215
+ importantLogs.push(line);
216
+ if (importantLogs.length > 24) importantLogSet.delete(importantLogs.pop());
217
+ }
62
218
  },
63
219
  text() {
64
- return logs.join("");
220
+ return formatRecentLogs(logs);
65
221
  }
66
222
  };
67
223
  }
@@ -72,6 +228,16 @@ function collectProcessOutput(child, maxChunks = 160) {
72
228
  return buffer.logs;
73
229
  }
74
230
  function classifyHBuilderXOutput(output) {
231
+ if (CLI_INSTANCE_MISMATCH_RE.test(output)) return {
232
+ kind: "cli-instance-mismatch",
233
+ message: "当前 HBuilderX CLI 与目标运行实例不匹配。",
234
+ hint: "请使用与目标 stable/alpha 实例对应的 CLI,并通过 listhost 与 --host 绑定运行实例。"
235
+ };
236
+ if (CLI_HOST_AMBIGUOUS_RE.test(output)) return {
237
+ kind: "cli-host-ambiguous",
238
+ message: "检测到多个可用的 HBuilderX 运行实例。",
239
+ hint: "请设置 HBUILDERX_HOST,或在 runner options 中显式传入 host。"
240
+ };
75
241
  if (ANDROID_TOOLCHAIN_MISSING_RE.test(output)) return {
76
242
  kind: "android-toolchain-missing",
77
243
  message: "当前环境缺少 Android 运行所需工具链。",
@@ -82,11 +248,16 @@ function classifyHBuilderXOutput(output) {
82
248
  message: "当前环境缺少 iOS 模拟器或 Xcode 工具链。",
83
249
  hint: "请安装完整 Xcode,确认 xcrun simctl/xcodebuild 可用,并完成 Xcode 首次启动组件安装。"
84
250
  };
85
- if (HARMONY_TOOLCHAIN_MISSING_RE.test(output)) return {
251
+ if (HARMONY_TOOLCHAIN_MISSING_RES.some((pattern) => pattern.test(output))) return {
86
252
  kind: "harmony-toolchain-missing",
87
253
  message: "当前环境缺少 Harmony 运行所需工具链。",
88
254
  hint: "请安装 DevEco Studio,或设置 HDC_PATH/E2E_HBUILDERX_HARMONY_HDC_PATH 指向 hdc。"
89
255
  };
256
+ if (HARMONY_BUILD_FAILED_RE.test(output)) return {
257
+ kind: "harmony-build-failed",
258
+ message: "HBuilderX 的 Harmony 工程构建失败。",
259
+ hint: "请查看保留的首个 ArkTS/hvigor 错误;这类错误发生在 HBuilderX 已生成 Harmony 工程之后。"
260
+ };
90
261
  if (CLI_NOT_FOUND_RE.test(output)) return {
91
262
  kind: "cli-not-found",
92
263
  message: "未找到 HBuilderX CLI。",
@@ -97,12 +268,21 @@ function classifyHBuilderXOutput(output) {
97
268
  message: "HBuilderX 将当前目录识别为非 uni-app 项目。",
98
269
  hint: "请确认传入的是 HBuilderX 可识别的项目根目录,并检查 manifest.json、pages.json 与导入状态。"
99
270
  };
100
- const unsupported = output.match(PROJECT_TYPE_UNSUPPORTED_RE);
101
- if (unsupported) return {
271
+ const unsupportedTarget = output.match(PROJECT_TARGET_UNSUPPORTED_RE);
272
+ if (unsupportedTarget) return {
102
273
  kind: "project-type-unsupported",
103
- message: `HBuilderX 不支持当前项目类型${unsupported[1] ? `:${unsupported[1].trim()}` : ""}。`,
104
- hint: "请确认项目已按目标平台导入,必要时先 close/open 项目后再 launch。"
274
+ message: `HBuilderX 不支持当前运行目标${unsupportedTarget[1] ? `:${unsupportedTarget[1]}` : ""}。`,
275
+ hint: "请升级到支持该项目目标的 HBuilderX channel,并确认项目路径与导入记录一致。"
105
276
  };
277
+ const unsupported = output.match(PROJECT_TYPE_UNSUPPORTED_RE);
278
+ if (unsupported) {
279
+ const projectType = unsupported[1] ?? unsupported[2];
280
+ return {
281
+ kind: "project-type-unsupported",
282
+ message: `HBuilderX 不支持当前项目类型${projectType ? `:${projectType.trim()}` : ""}。`,
283
+ hint: "请确认项目已按目标平台导入,必要时先 close/open 项目后再 launch。"
284
+ };
285
+ }
106
286
  if (CONFIG_LOAD_FAILED_RE.test(output)) return {
107
287
  kind: "config-load-failed",
108
288
  message: "HBuilderX/Vite 配置加载失败。",
@@ -122,7 +302,9 @@ function createTimeoutIssue() {
122
302
  }
123
303
  function formatRecentLogs(logs, maxLength = 6e3) {
124
304
  const output = logs.join("");
125
- return output.length > maxLength ? output.slice(-maxLength) : output;
305
+ const recent = output.length > maxLength ? output.slice(-maxLength) : output;
306
+ const important = (importantLogsByBuffer.get(logs) ?? []).filter((line) => !recent.includes(line));
307
+ return important.length > 0 ? `关键错误:\n${important.join("\n")}\n\n最近日志:\n${recent}` : recent;
126
308
  }
127
309
  //#endregion
128
310
  //#region src/process.ts
@@ -270,70 +452,249 @@ function createProcessExitTracker(child) {
270
452
  };
271
453
  }
272
454
  //#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));
455
+ //#region src/hbuilderx/runner.ts
456
+ const ansiRE = new RegExp(`${String.fromCharCode(27)}\\[[\\d;]*m`, "g");
457
+ const defaultStartupTimeoutMs = 6e4;
458
+ const hostPollIntervalMs = 500;
459
+ const maxSessionLogChunks = 160;
460
+ function stripAnsi(value) {
461
+ return value.replace(ansiRE, "");
277
462
  }
278
- function extractHBuilderXMacOSExecutable(line) {
279
- return line.match(/(\/.*?HBuilderX[^/]*\.app\/Contents\/MacOS\/HBuilderX)(?:\s|$)/i)?.[1];
463
+ function parseHBuilderXHosts(output) {
464
+ 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
465
  }
281
- function extractHBuilderXWindowsExecutable(line) {
282
- const executable = line.split(",").at(-1)?.trim();
283
- return executable?.toLowerCase().endsWith("hbuilderx.exe") ? executable : void 0;
466
+ function parseHBuilderXVersion(output) {
467
+ return stripAnsi(output).match(/\b(\d+\.\d+(?:\.\d+)+(?:-[0-9a-z.-]+)?)\b/i)?.[1];
284
468
  }
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
- }
469
+ function inferHBuilderXChannelFromVersion(version) {
470
+ return /(?:^|-)alpha(?:\.|$)/i.test(version) ? "alpha" : "stable";
290
471
  }
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;
472
+ function createHBuilderXNativeLaunchArgs(options) {
473
+ const args = [
474
+ "launch",
475
+ options.platform,
476
+ "--project",
477
+ node_path.default.resolve(options.cwd),
478
+ ...options.args ?? []
479
+ ];
480
+ if (options.compile != null && !args.includes("--compile")) args.push("--compile", String(options.compile));
481
+ if (options.runtimeLog != null && !args.includes("--runtime-log")) args.push("--runtime-log", String(options.runtimeLog));
482
+ return args;
312
483
  }
313
- function resolveCandidateSource(candidate, env) {
314
- if (candidate === env.HBUILDERX_CLI_PATH) return "env";
315
- if (candidate === macOSDefaultCli) return "default-path";
316
- return "candidate";
484
+ function createRunnerError(cliPath, cwd, args, kind, message, hint, logs) {
485
+ const output = formatRecentLogs(logs);
486
+ return new HBuilderXCommandError([
487
+ `${message}: ${cliPath} ${args.join(" ")}`,
488
+ `cwd=${cwd}`,
489
+ `issue=${kind}: ${message}`,
490
+ `hint=${hint}`,
491
+ output
492
+ ].filter(Boolean).join("\n"), {
493
+ command: cliPath,
494
+ args,
495
+ cwd,
496
+ exit: {
497
+ code: null,
498
+ signal: null
499
+ },
500
+ logs,
501
+ output,
502
+ issue: {
503
+ kind,
504
+ message,
505
+ hint
506
+ }
507
+ });
508
+ }
509
+ function bindHost(args, host) {
510
+ const hostIndex = args.indexOf("--host");
511
+ if (hostIndex < 0) return [
512
+ ...args,
513
+ "--host",
514
+ host
515
+ ];
516
+ if (args[hostIndex + 1] !== host) throw new Error(`runner 已绑定 HBuilderX host=${host},不能改为 ${args[hostIndex + 1] ?? "空值"}。`);
517
+ return args;
518
+ }
519
+ function appendLogs(target, source) {
520
+ target.push(...source);
521
+ if (target.length > maxSessionLogChunks) target.splice(0, target.length - maxSessionLogChunks);
317
522
  }
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"
523
+ async function listCompatibleHosts(cliPath, cwd, env, expectedChannel, explicitHost, timeoutMs) {
524
+ const startedAt = Date.now();
525
+ const logs = [];
526
+ do {
527
+ const listed = await runCommand({
528
+ command: cliPath,
529
+ args: ["listhost"],
530
+ cwd,
531
+ env,
532
+ timeoutMs: Math.min(timeoutMs, 1e4),
533
+ allowFailure: true
534
+ });
535
+ appendLogs(logs, listed.logs);
536
+ const hosts = explicitHost ? [explicitHost] : parseHBuilderXHosts(listed.output);
537
+ const compatible = [];
538
+ for (const host of hosts) {
539
+ const versionResult = await runCommand({
540
+ command: cliPath,
541
+ args: [
542
+ "version",
543
+ "--host",
544
+ host
545
+ ],
546
+ cwd,
547
+ env,
548
+ timeoutMs: Math.min(timeoutMs, 1e4),
549
+ allowFailure: true
550
+ });
551
+ appendLogs(logs, versionResult.logs);
552
+ if (versionResult.issue.kind === "cli-instance-mismatch") return {
553
+ compatible: [],
554
+ logs
555
+ };
556
+ const version = versionResult.exit.code === 0 ? parseHBuilderXVersion(versionResult.output) : void 0;
557
+ if (!version) continue;
558
+ const channel = inferHBuilderXChannelFromVersion(version);
559
+ if (expectedChannel === "unknown" || channel === expectedChannel) compatible.push({
560
+ host,
561
+ version,
562
+ channel
563
+ });
564
+ }
565
+ if (compatible.length > 0) return {
566
+ compatible,
567
+ logs
325
568
  };
569
+ await wait(hostPollIntervalMs);
570
+ } while (Date.now() - startedAt < timeoutMs);
571
+ return {
572
+ compatible: [],
573
+ logs
574
+ };
575
+ }
576
+ async function createHBuilderXRunner(options = {}) {
577
+ const env = {
578
+ ...node_process.default.env,
579
+ ...options.env
580
+ };
581
+ const cwd = options.cwd ?? node_process.default.cwd();
582
+ const timeoutMs = options.timeoutMs ?? defaultStartupTimeoutMs;
583
+ const resolution = await resolveHBuilderXCliInfoFromOptions({
584
+ candidates: options.hbuilderxCliPath ? [options.hbuilderxCliPath] : options.candidates,
585
+ channel: options.channel,
586
+ env,
587
+ host: options.host
588
+ });
589
+ const cliEnv = {
590
+ ...env,
591
+ HBUILDERX_CLI_PATH: resolution.path
592
+ };
593
+ if (!resolution.isRunning) {
594
+ const opened = await runCommand({
595
+ command: resolution.path,
596
+ args: ["open"],
597
+ cwd,
598
+ env: cliEnv,
599
+ timeoutMs,
600
+ allowFailure: true
601
+ });
602
+ const openIssue = classifyHBuilderXOutput(opened.output);
603
+ 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
604
  }
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)
605
+ const requestedChannel = resolveHBuilderXChannel(options.channel ?? env.HBUILDERX_CHANNEL);
606
+ const expectedChannel = resolution.channel !== "unknown" ? resolution.channel : requestedChannel === "auto" ? inferHBuilderXChannel(resolution.path) : requestedChannel;
607
+ const explicitHost = options.host ?? env.HBUILDERX_HOST;
608
+ const { compatible, logs } = await listCompatibleHosts(resolution.path, cwd, cliEnv, expectedChannel, explicitHost, timeoutMs);
609
+ 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);
610
+ 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);
611
+ const selected = compatible[0];
612
+ const boundResolution = {
613
+ ...resolution,
614
+ isRunning: true,
615
+ channel: selected.channel,
616
+ host: selected.host,
617
+ version: selected.version
332
618
  };
333
- throw new Error("未找到 HBuilderX CLI。请先安装 HBuilderX,或设置 HBUILDERX_CLI_PATH=/path/to/cli。");
619
+ const run = async (commandOptions) => await runCommand({
620
+ ...commandOptions,
621
+ command: resolution.path,
622
+ args: bindHost(commandOptions.args, selected.host),
623
+ cwd: commandOptions.cwd ?? cwd,
624
+ env: {
625
+ ...cliEnv,
626
+ ...commandOptions.env
627
+ }
628
+ });
629
+ const spawn = (commandOptions) => spawnCommand({
630
+ ...commandOptions,
631
+ command: resolution.path,
632
+ args: bindHost(commandOptions.args, selected.host),
633
+ cwd: commandOptions.cwd ?? cwd,
634
+ env: {
635
+ ...cliEnv,
636
+ ...commandOptions.env
637
+ }
638
+ });
639
+ const runner = {
640
+ resolution: boundResolution,
641
+ run,
642
+ spawn,
643
+ async closeProject(projectOptions) {
644
+ return await run({
645
+ ...projectOptions,
646
+ args: [
647
+ "project",
648
+ "close",
649
+ "--path",
650
+ node_path.default.resolve(projectOptions.cwd)
651
+ ],
652
+ allowFailure: projectOptions.allowFailure ?? true
653
+ });
654
+ },
655
+ async openProject(projectOptions) {
656
+ return await run({
657
+ ...projectOptions,
658
+ args: [
659
+ "project",
660
+ "open",
661
+ "--path",
662
+ node_path.default.resolve(projectOptions.cwd)
663
+ ]
664
+ });
665
+ },
666
+ async prepareProject(projectOptions) {
667
+ await runner.closeProject({
668
+ ...projectOptions,
669
+ allowFailure: true
670
+ });
671
+ return await runner.openProject(projectOptions);
672
+ },
673
+ async launchProject(launchOptions) {
674
+ return await run({
675
+ ...launchOptions,
676
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
677
+ });
678
+ },
679
+ startLaunch(launchOptions) {
680
+ return spawn({
681
+ ...launchOptions,
682
+ args: createHBuilderXNativeLaunchArgs(launchOptions)
683
+ });
684
+ }
685
+ };
686
+ return runner;
334
687
  }
335
- async function resolveHBuilderXCli(candidates) {
336
- return (await resolveHBuilderXCliInfo(candidates)).path;
688
+ //#endregion
689
+ //#region src/hbuilderx.ts
690
+ async function resolveHBuilderXCliInfo(candidatesOrOptions, env = node_process.default.env) {
691
+ return await resolveHBuilderXCliInfoFromOptions(Array.isArray(candidatesOrOptions) ? {
692
+ candidates: candidatesOrOptions,
693
+ env
694
+ } : candidatesOrOptions);
695
+ }
696
+ async function resolveHBuilderXCli(candidatesOrOptions) {
697
+ return (await resolveHBuilderXCliInfo(candidatesOrOptions)).path;
337
698
  }
338
699
  function createHBuilderXEnv(options = {}) {
339
700
  return {
@@ -368,34 +729,13 @@ function spawnPnpmCommand(options) {
368
729
  });
369
730
  }
370
731
  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
- });
732
+ return await (await createHBuilderXRunner(options)).closeProject(options);
381
733
  }
382
734
  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
- });
735
+ return await (await createHBuilderXRunner(options)).openProject(options);
392
736
  }
393
737
  async function prepareProject(options) {
394
- await closeProject({
395
- ...options,
396
- allowFailure: true
397
- });
398
- return await openProject(options);
738
+ return await (await createHBuilderXRunner(options)).prepareProject(options);
399
739
  }
400
740
  function createLaunchArgs(options) {
401
741
  const args = [
@@ -410,11 +750,11 @@ function createLaunchArgs(options) {
410
750
  return hbuilderxPnpmArgs(args);
411
751
  }
412
752
  async function launchProject(options) {
413
- return await runPnpmCommand({
414
- ...options,
415
- args: createLaunchArgs(options)
416
- });
753
+ return await (await createHBuilderXRunner(options)).launchProject(options);
417
754
  }
755
+ /**
756
+ * @deprecated 需要固定 stable/alpha 与 host 时,请使用 `createHBuilderXRunner().startLaunch()`。
757
+ */
418
758
  function startLaunch(options) {
419
759
  return spawnPnpmCommand({
420
760
  ...options,
@@ -601,35 +941,51 @@ exports.classifyHBuilderXOutput = classifyHBuilderXOutput;
601
941
  exports.closeProject = closeProject;
602
942
  exports.collectProcessOutput = collectProcessOutput;
603
943
  exports.createHBuilderXEnv = createHBuilderXEnv;
944
+ exports.createHBuilderXNativeLaunchArgs = createHBuilderXNativeLaunchArgs;
945
+ exports.createHBuilderXRunner = createHBuilderXRunner;
604
946
  exports.createLaunchArgs = createLaunchArgs;
605
947
  exports.createLogBuffer = createLogBuffer;
606
948
  exports.createProcessExitTracker = createProcessExitTracker;
607
949
  exports.createTimeoutIssue = createTimeoutIssue;
608
950
  exports.extractHBuilderXExecutableFromProcessOutput = extractHBuilderXExecutableFromProcessOutput;
951
+ exports.extractHBuilderXExecutablesFromProcessOutput = extractHBuilderXExecutablesFromProcessOutput;
609
952
  exports.extractHBuilderXMacOSExecutable = extractHBuilderXMacOSExecutable;
953
+ exports.extractHBuilderXMacOSExecutables = extractHBuilderXMacOSExecutables;
610
954
  exports.extractHBuilderXWindowsExecutable = extractHBuilderXWindowsExecutable;
955
+ exports.extractHBuilderXWindowsExecutables = extractHBuilderXWindowsExecutables;
611
956
  exports.fileExists = fileExists;
612
957
  exports.findRunningHBuilderXCli = findRunningHBuilderXCli;
958
+ exports.findRunningHBuilderXCliCandidates = findRunningHBuilderXCliCandidates;
613
959
  exports.formatRecentLogs = formatRecentLogs;
614
960
  exports.getDefaultHBuilderXCliCandidates = getDefaultHBuilderXCliCandidates;
615
961
  exports.hbuilderxPnpmArgs = hbuilderxPnpmArgs;
962
+ exports.inferHBuilderXChannel = inferHBuilderXChannel;
963
+ exports.inferHBuilderXChannelFromVersion = inferHBuilderXChannelFromVersion;
616
964
  exports.killProcessTree = killProcessTree;
617
965
  exports.launchProject = launchProject;
966
+ exports.macOSAlphaCli = macOSAlphaCli;
967
+ exports.macOSStableCli = macOSStableCli;
618
968
  exports.openProject = openProject;
969
+ exports.parseHBuilderXHosts = parseHBuilderXHosts;
970
+ exports.parseHBuilderXVersion = parseHBuilderXVersion;
619
971
  exports.parseHdcTargets = parseHdcTargets;
620
972
  exports.parseIosSimulatorDevices = parseIosSimulatorDevices;
621
973
  exports.prepareProject = prepareProject;
622
974
  exports.readUtf8 = readUtf8;
623
975
  exports.resolveAdbCommand = resolveAdbCommand;
976
+ exports.resolveHBuilderXChannel = resolveHBuilderXChannel;
624
977
  exports.resolveHBuilderXCli = resolveHBuilderXCli;
625
978
  exports.resolveHBuilderXCliInfo = resolveHBuilderXCliInfo;
979
+ exports.resolveHBuilderXCliInfoFromOptions = resolveHBuilderXCliInfoFromOptions;
626
980
  exports.resolveHdcCommand = resolveHdcCommand;
627
981
  exports.resolveIosSimulatorDeviceId = resolveIosSimulatorDeviceId;
628
982
  exports.runCommand = runCommand;
629
983
  exports.runPnpmCommand = runPnpmCommand;
630
984
  exports.runTool = runTool;
985
+ exports.selectHBuilderXCliCandidatesForChannel = selectHBuilderXCliCandidatesForChannel;
631
986
  exports.selectPreferredIosSimulatorDevice = selectPreferredIosSimulatorDevice;
632
987
  exports.spawnCommand = spawnCommand;
633
988
  exports.spawnPnpmCommand = spawnPnpmCommand;
634
989
  exports.startLaunch = startLaunch;
990
+ exports.stripAnsi = stripAnsi;
635
991
  exports.wait = wait;