@heybox/hb-sdk 0.9.6-alpha.4 → 0.9.6-alpha.6
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/CHANGELOG.md +41 -5
- package/README.md +35 -561
- package/dist/cli-chunks/{artifact-D_M6R8VV.cjs → artifact-BZZtedxB.cjs} +3 -3
- package/dist/cli-chunks/{build-BKNp4DKT.cjs → build-C4vRkpqF.cjs} +8 -6
- package/dist/cli-chunks/{create-qW5pV_nK.cjs → create-C4CXYcaO.cjs} +3 -1
- package/dist/cli-chunks/{dev-BCwp9SuY.cjs → dev-Cs1e2PBR.cjs} +9312 -609
- package/dist/cli-chunks/{dev-context-Cjn8A7zv.cjs → dev-context-DkUPIPMO.cjs} +2 -2
- package/dist/cli-chunks/{doctor-DzZ_fxug.cjs → doctor-CTE-ykJW.cjs} +3 -1
- package/dist/cli-chunks/{games-oeSJAEM6.cjs → games-Bp5mp79Z.cjs} +3 -1
- package/dist/cli-chunks/{index-CET9kH6C.cjs → index-Bnbj-tOs.cjs} +1619 -105
- package/dist/cli-chunks/{index-jyCJyGf8.cjs → index-Yef7fLOV.cjs} +1 -1
- package/dist/cli-chunks/index.esm-Cb7A6DlM.cjs +154 -0
- package/dist/cli-chunks/{login-B9uQ4Duc.cjs → login-DvKnuA5F.cjs} +3 -3
- package/dist/cli-chunks/{project-vite-xtntRhkc.cjs → project-vite-DdNQujlo.cjs} +3 -18
- package/dist/cli-chunks/{remote-C-qyyMIQ.cjs → remote-g9MP_ZKJ.cjs} +8 -20
- package/dist/cli-chunks/{runtime-permission-env-D6wAj0cw.cjs → runtime-permission-env-uu3dZhcm.cjs} +2 -2
- package/dist/cli-chunks/{skill-av-4cZEX.cjs → skill-Dz8sjBhC.cjs} +3 -2
- package/dist/cli-chunks/{version-BMiC4gu_.cjs → version-CBmePZNV.cjs} +1 -1
- package/dist/cli.cjs +3 -1
- package/dist/dev.cjs +1358 -0
- package/dist/dev.mjs +1356 -0
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-DQC0jpRj.js +100 -0
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-Cgi2cM0p.js +6 -0
- package/dist/devtools/browser-dev-host/assets/index-Bgy5xJhe.js +586 -0
- package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +1 -0
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +53 -110
- package/dist/index.esm.js +53 -110
- package/dist/vite.cjs.js +908 -170
- package/dist/vite.esm.js +909 -171
- package/docs/device-logs.md +39 -22
- package/package.json +23 -10
- package/skill/skill.json +4 -4
- package/types/dev/index.d.cts +386 -0
- package/types/dev/index.d.mts +386 -0
- package/types/dev/vendor/playwright-core/LICENSE +202 -0
- package/types/dev/vendor/playwright-core/NOTICE +5 -0
- package/types/dev/vendor/playwright-core/UPSTREAM.json +5 -0
- package/types/dev/vendor/playwright-core/types/protocol.d.ts +24776 -0
- package/types/dev/vendor/playwright-core/types/structs.d.ts +52 -0
- package/types/dev/vendor/playwright-core/types/types.d.ts +27167 -0
- package/types/index.d.ts +4 -3
- package/types/protocol.d.ts +3 -2
- package/types/vite/index.d.ts +1 -1
- package/dist/cli-chunks/index.esm-buwSxNH8.cjs +0 -5216
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-tfBfReOu.js +0 -103
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-c9mxCZ3M.js +0 -6
- package/dist/devtools/browser-dev-host/assets/index-DNgaNjCW.js +0 -567
- package/dist/devtools/browser-dev-host/assets/index-DSTlrpnQ.css +0 -1
- package/docs/runtime-host-migration.md +0 -128
|
@@ -17,6 +17,8 @@ var require$$0$7 = require('constants');
|
|
|
17
17
|
var fs$3 = require('node:fs');
|
|
18
18
|
var fs$2 = require('node:fs/promises');
|
|
19
19
|
var node_zlib = require('node:zlib');
|
|
20
|
+
var childProcess = require('node:child_process');
|
|
21
|
+
var node_util = require('node:util');
|
|
20
22
|
var promises = require('node:readline/promises');
|
|
21
23
|
var promises$1 = require('node:timers/promises');
|
|
22
24
|
|
|
@@ -240,19 +242,19 @@ function requireArgument () {
|
|
|
240
242
|
|
|
241
243
|
var command = {};
|
|
242
244
|
|
|
243
|
-
const require$5 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-
|
|
245
|
+
const require$5 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-Bnbj-tOs.cjs', document.baseURI).href)));
|
|
244
246
|
function __require$4() { return require$5("node:events"); }
|
|
245
247
|
|
|
246
|
-
const require$4 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-
|
|
248
|
+
const require$4 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-Bnbj-tOs.cjs', document.baseURI).href)));
|
|
247
249
|
function __require$3() { return require$4("node:child_process"); }
|
|
248
250
|
|
|
249
|
-
const require$3 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-
|
|
251
|
+
const require$3 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-Bnbj-tOs.cjs', document.baseURI).href)));
|
|
250
252
|
function __require$2() { return require$3("node:path"); }
|
|
251
253
|
|
|
252
|
-
const require$2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-
|
|
254
|
+
const require$2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-Bnbj-tOs.cjs', document.baseURI).href)));
|
|
253
255
|
function __require$1() { return require$2("node:fs"); }
|
|
254
256
|
|
|
255
|
-
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-
|
|
257
|
+
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-Bnbj-tOs.cjs', document.baseURI).href)));
|
|
256
258
|
function __require() { return require$1("node:process"); }
|
|
257
259
|
|
|
258
260
|
var help = {};
|
|
@@ -16388,7 +16390,7 @@ function createCookie(name, value) {
|
|
|
16388
16390
|
return `${name}=${value}`;
|
|
16389
16391
|
}
|
|
16390
16392
|
function isHeyboxAuthSession(value) {
|
|
16391
|
-
if (!isRecord$
|
|
16393
|
+
if (!isRecord$2(value)) {
|
|
16392
16394
|
return false;
|
|
16393
16395
|
}
|
|
16394
16396
|
return (typeof value.heyboxId === 'string' &&
|
|
@@ -16414,7 +16416,7 @@ function normalizeHeyboxAuthSession(session) {
|
|
|
16414
16416
|
return normalized;
|
|
16415
16417
|
}
|
|
16416
16418
|
function normalizeSelectedDeveloperEntitySnapshot(value) {
|
|
16417
|
-
if (!isRecord$
|
|
16419
|
+
if (!isRecord$2(value)) {
|
|
16418
16420
|
return undefined;
|
|
16419
16421
|
}
|
|
16420
16422
|
if (typeof value.entityId !== 'number' || !Number.isFinite(value.entityId)) {
|
|
@@ -16436,7 +16438,7 @@ function normalizeSelectedDeveloperEntitySnapshot(value) {
|
|
|
16436
16438
|
selectedAt: value.selectedAt,
|
|
16437
16439
|
};
|
|
16438
16440
|
}
|
|
16439
|
-
function isRecord$
|
|
16441
|
+
function isRecord$2(value) {
|
|
16440
16442
|
return Object.prototype.toString.call(value) === '[object Object]';
|
|
16441
16443
|
}
|
|
16442
16444
|
|
|
@@ -17251,7 +17253,7 @@ async function inspectFeedbackLog(file, size) {
|
|
|
17251
17253
|
return { mimeType: 'text/plain', width: 0, height: 0 };
|
|
17252
17254
|
}
|
|
17253
17255
|
async function createFeedbackCosClient(getToken) {
|
|
17254
|
-
const { default: COS } = await Promise.resolve().then(function () { return require('./index-
|
|
17256
|
+
const { default: COS } = await Promise.resolve().then(function () { return require('./index-Yef7fLOV.cjs'); }).then(function (n) { return n.index; });
|
|
17255
17257
|
const cos = new COS({
|
|
17256
17258
|
getAuthorization(_options, callback) {
|
|
17257
17259
|
void getToken().then((token) => callback({
|
|
@@ -20355,104 +20357,1585 @@ function installFeedbackCommand(program, runtime = {}) {
|
|
|
20355
20357
|
installFeedbackTicketCommands(command, runtime);
|
|
20356
20358
|
}
|
|
20357
20359
|
|
|
20358
|
-
|
|
20360
|
+
/** CLI 与 Node 连接入口共用项目定位;不加载 Vite、终端交互或日志组件。 */
|
|
20361
|
+
function findProjectRoot(startDir) {
|
|
20362
|
+
let current = path.resolve(startDir);
|
|
20363
|
+
while (true) {
|
|
20364
|
+
if (fs$3.existsSync(path.join(current, 'package.json')))
|
|
20365
|
+
return current;
|
|
20366
|
+
const parent = path.dirname(current);
|
|
20367
|
+
if (parent === current)
|
|
20368
|
+
throw new Error('当前目录或父目录未找到 package.json');
|
|
20369
|
+
current = parent;
|
|
20370
|
+
}
|
|
20371
|
+
}
|
|
20372
|
+
|
|
20373
|
+
/** 仅本地开发工具使用,不属于 Mini-program SDK 或 Host wire contract。 */
|
|
20374
|
+
const PREVIEW_PATH = '/__hb_sdk__/preview';
|
|
20375
|
+
const PREVIEW_SELECTORS = {
|
|
20376
|
+
device: '[data-preview-target="device"]',
|
|
20377
|
+
screen: '[data-preview-target="screen"]',
|
|
20378
|
+
app: '#device iframe',
|
|
20379
|
+
workbench: '[data-testid="workbench-root"]',
|
|
20380
|
+
};
|
|
20381
|
+
|
|
20382
|
+
/** 只接受普通对象字面量;null、数组与其它值一律拒绝。 */
|
|
20383
|
+
function isRecord$1(value) {
|
|
20384
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20385
|
+
}
|
|
20386
|
+
|
|
20387
|
+
class DevHostError extends Error {
|
|
20388
|
+
code;
|
|
20389
|
+
constructor(code, message) {
|
|
20390
|
+
super(message);
|
|
20391
|
+
this.code = code;
|
|
20392
|
+
this.name = 'DevHostError';
|
|
20393
|
+
}
|
|
20394
|
+
}
|
|
20395
|
+
const RECORD_NAME = /^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/;
|
|
20396
|
+
const MAX_RECORDS = 128;
|
|
20397
|
+
const MAX_JSON_BYTES = 64 * 1024;
|
|
20398
|
+
function devHostRegistryDirectory(cacheRoot = process.env.HB_SDK_DEV_HOST_CACHE_DIR ?? envPaths('hb-sdk', { suffix: '' }).cache) {
|
|
20399
|
+
return path.join(cacheRoot, 'dev-hosts', 'v1');
|
|
20400
|
+
}
|
|
20401
|
+
/** 服务就绪后才登记实际地址;临时文件晋升后才会被其它 CLI 发现。 */
|
|
20402
|
+
async function registerDevHost(input, options = {}) {
|
|
20403
|
+
const record = {
|
|
20404
|
+
...readIdentity({ ...input, schemaVersion: 1 }),
|
|
20405
|
+
projectRoot: await fs$2.realpath(input.projectRoot),
|
|
20406
|
+
pid: process.pid,
|
|
20407
|
+
startedAt: new Date().toISOString(),
|
|
20408
|
+
};
|
|
20409
|
+
const directory = (await prepareRegistryDirectory(options, true));
|
|
20410
|
+
if (process.platform !== 'win32')
|
|
20411
|
+
await fs$2.chmod(directory, 0o700);
|
|
20412
|
+
// 每次登记独占文件;迟到的退出清理不会删掉后来启动的同一端口或会话。
|
|
20413
|
+
const filename = `${node_crypto.createHash('sha256').update(record.sessionId).digest('hex')}-${node_crypto.randomUUID()}.json`;
|
|
20414
|
+
const target = path.join(directory, filename);
|
|
20415
|
+
const staging = target + '.tmp';
|
|
20416
|
+
try {
|
|
20417
|
+
await fs$2.writeFile(staging, JSON.stringify(record) + '\n', { flag: 'wx', mode: 0o600 });
|
|
20418
|
+
await fs$2.rename(staging, target);
|
|
20419
|
+
}
|
|
20420
|
+
finally {
|
|
20421
|
+
await fs$2.rm(staging, { force: true });
|
|
20422
|
+
}
|
|
20423
|
+
return async () => { await fs$2.rm(target, { force: true }); };
|
|
20424
|
+
}
|
|
20425
|
+
/** 列出当前用户的登记;超时记录仍可见,已经退出或被其它服务占用的地址会收敛清理。 */
|
|
20426
|
+
async function listDevHosts(options = {}) {
|
|
20427
|
+
return (await inspectRegisteredHosts(options)).map(({ listing }) => listing);
|
|
20428
|
+
}
|
|
20429
|
+
/** 显式端口仍核对实时身份;不要求存在本机登记,也不伪造 PID 和启动时间。 */
|
|
20430
|
+
async function connectDevHost(input, options = {}) {
|
|
20431
|
+
const projectRoot = await fs$2.realpath(input.projectRoot);
|
|
20432
|
+
const connection = await probePort(input.port, options);
|
|
20433
|
+
if (connection.record.projectRoot !== projectRoot) {
|
|
20434
|
+
throw new DevHostError('PROJECT_MISMATCH', '指定端口的调试台不属于当前项目,请检查 --port 或运行 hb-sdk dev list');
|
|
20435
|
+
}
|
|
20436
|
+
return connection;
|
|
20437
|
+
}
|
|
20438
|
+
/** 隐式目标只允许当前项目唯一的有效登记,绝不选择最近会话或回退固定端口。 */
|
|
20439
|
+
async function resolveDevHostConnection(input, options = {}) {
|
|
20440
|
+
if (input.port !== undefined)
|
|
20441
|
+
return connectDevHost({ projectRoot: input.projectRoot, port: input.port }, options);
|
|
20442
|
+
const projectRoot = await fs$2.realpath(input.projectRoot);
|
|
20443
|
+
const candidates = await inspectRegisteredHosts(options, projectRoot);
|
|
20444
|
+
if (!candidates.length)
|
|
20445
|
+
throw new DevHostError('DEV_HOST_NOT_FOUND', '当前项目没有运行中的调试台,请先运行 hb-sdk dev;可用 hb-sdk dev list 查看本机服务');
|
|
20446
|
+
if (candidates.length > 1) {
|
|
20447
|
+
const ports = candidates.map(({ listing }) => listing.port).sort((a, b) => a - b).join('、');
|
|
20448
|
+
throw new DevHostError('DEV_HOST_AMBIGUOUS', `当前项目存在多个调试台(${ports}),请指定 --port <端口>`);
|
|
20449
|
+
}
|
|
20450
|
+
const [candidate] = candidates;
|
|
20451
|
+
if (!candidate.connection)
|
|
20452
|
+
throw new DevHostError('DEV_HOST_UNREACHABLE', `当前项目的调试台 ${candidate.listing.port} 暂不可达,请检查 dev 终端或显式指定 --port`);
|
|
20453
|
+
return candidate.connection;
|
|
20454
|
+
}
|
|
20455
|
+
async function inspectRegisteredHosts(options, projectRoot) {
|
|
20456
|
+
const directory = await prepareRegistryDirectory(options, false);
|
|
20457
|
+
if (!directory)
|
|
20458
|
+
return [];
|
|
20459
|
+
const names = await fs$2.readdir(directory).catch((error) => {
|
|
20460
|
+
if (error.code === 'ENOENT')
|
|
20461
|
+
return [];
|
|
20462
|
+
throw error;
|
|
20463
|
+
});
|
|
20464
|
+
const files = names.filter((name) => RECORD_NAME.test(name));
|
|
20465
|
+
// 单次只处理有限记录;仍先清理能确认失效的条目,避免崩溃遗留积累后永远无法收敛。
|
|
20466
|
+
const batch = files.slice(0, MAX_RECORDS);
|
|
20467
|
+
const output = [];
|
|
20468
|
+
let index = 0;
|
|
20469
|
+
await Promise.all(Array.from({ length: Math.min(8, batch.length) }, async () => {
|
|
20470
|
+
while (index < batch.length) {
|
|
20471
|
+
const filename = path.join(directory, batch[index++]);
|
|
20472
|
+
let record;
|
|
20473
|
+
try {
|
|
20474
|
+
const info = await fs$2.lstat(filename);
|
|
20475
|
+
if (!info.isFile() || info.size > MAX_JSON_BYTES || (process.getuid && info.uid !== process.getuid()))
|
|
20476
|
+
continue;
|
|
20477
|
+
record = readRecord(JSON.parse(await fs$2.readFile(filename, 'utf8')));
|
|
20478
|
+
}
|
|
20479
|
+
catch {
|
|
20480
|
+
// 未完成、损坏或来自不支持版本的文件不参与选路,也不自动删除未知文件。
|
|
20481
|
+
continue;
|
|
20482
|
+
}
|
|
20483
|
+
if (!(options.isProcessAlive ?? isProcessAlive)(record.pid)) {
|
|
20484
|
+
await fs$2.rm(filename, { force: true });
|
|
20485
|
+
continue;
|
|
20486
|
+
}
|
|
20487
|
+
// 查询当前项目时不向其它项目发起握手;全局列表才检查所有在线身份。
|
|
20488
|
+
if (projectRoot !== undefined && record.projectRoot !== projectRoot)
|
|
20489
|
+
continue;
|
|
20490
|
+
try {
|
|
20491
|
+
const connection = await probePort(record.port, options);
|
|
20492
|
+
if (connection.record.sessionId !== record.sessionId || connection.record.projectRoot !== record.projectRoot || connection.record.appUrl !== record.appUrl || connection.record.previewUrl !== record.previewUrl) {
|
|
20493
|
+
await fs$2.rm(filename, { force: true });
|
|
20494
|
+
continue;
|
|
20495
|
+
}
|
|
20496
|
+
connection.record = { ...connection.record, pid: record.pid, startedAt: record.startedAt };
|
|
20497
|
+
output.push({ listing: { ...record, state: 'ready' }, connection });
|
|
20498
|
+
}
|
|
20499
|
+
catch (error) {
|
|
20500
|
+
options.signal?.throwIfAborted();
|
|
20501
|
+
if (isConnectionRefused(error)) {
|
|
20502
|
+
await fs$2.rm(filename, { force: true });
|
|
20503
|
+
continue;
|
|
20504
|
+
}
|
|
20505
|
+
output.push({ listing: { ...record, state: 'unreachable' } });
|
|
20506
|
+
}
|
|
20507
|
+
}
|
|
20508
|
+
}));
|
|
20509
|
+
if (files.length > MAX_RECORDS)
|
|
20510
|
+
throw new DevHostError('DEV_HOST_REGISTRY_FULL', '本机调试台登记过多,已清理本批失效记录;请重试或检查用户缓存');
|
|
20511
|
+
return output.sort((a, b) => a.listing.projectRoot.localeCompare(b.listing.projectRoot) || a.listing.port - b.listing.port);
|
|
20512
|
+
}
|
|
20513
|
+
async function probePort(port, options) {
|
|
20514
|
+
validatePort(port);
|
|
20515
|
+
const origin = new URL(`http://127.0.0.1:${port}`).origin;
|
|
20516
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
20517
|
+
const signal = AbortSignal.any([AbortSignal.timeout(options.requestTimeoutMs ?? 1200), ...(options.signal ? [options.signal] : [])]);
|
|
20518
|
+
signal.throwIfAborted();
|
|
20519
|
+
const bootstrap = await requestJson(fetchImpl, origin + '/__hb_sdk_bootstrap__', { signal });
|
|
20520
|
+
if (typeof bootstrap.csrfToken !== 'string' || !bootstrap.csrfToken || bootstrap.csrfToken.length > 512)
|
|
20521
|
+
throw new DevHostError('DEV_HOST_INVALID', '目标没有返回有效的调试台握手信息,请重新启动 hb-sdk dev');
|
|
20522
|
+
const status = await requestJson(fetchImpl, origin + PREVIEW_PATH, { signal, headers: { origin, 'x-hb-sdk-csrf': bootstrap.csrfToken } });
|
|
20523
|
+
const record = readIdentity({ ...status, port });
|
|
20524
|
+
if (new URL(record.previewUrl).origin !== origin)
|
|
20525
|
+
throw new DevHostError('DEV_HOST_INVALID', '目标调试台返回了不匹配的地址');
|
|
20526
|
+
record.projectRoot = await fs$2.realpath(record.projectRoot);
|
|
20527
|
+
return { record, origin, csrfToken: bootstrap.csrfToken, status };
|
|
20528
|
+
}
|
|
20529
|
+
/** 登记命名空间只接受真实目录,避免 mkdir/chmod 跟随缓存中的软链接。 */
|
|
20530
|
+
async function prepareRegistryDirectory(options, create) {
|
|
20531
|
+
const directory = devHostRegistryDirectory(options.cacheRoot);
|
|
20532
|
+
const root = path.dirname(path.dirname(directory));
|
|
20533
|
+
for (const [index, current] of [root, path.join(root, 'dev-hosts'), directory].entries()) {
|
|
20534
|
+
let info = await fs$2.lstat(current).catch((error) => {
|
|
20535
|
+
if (error.code === 'ENOENT')
|
|
20536
|
+
return undefined;
|
|
20537
|
+
throw error;
|
|
20538
|
+
});
|
|
20539
|
+
if (!info) {
|
|
20540
|
+
if (!create)
|
|
20541
|
+
return;
|
|
20542
|
+
await fs$2.mkdir(current, { recursive: index === 0, mode: 0o700 }).catch((error) => {
|
|
20543
|
+
if (error.code !== 'EEXIST')
|
|
20544
|
+
throw error;
|
|
20545
|
+
});
|
|
20546
|
+
info = await fs$2.lstat(current);
|
|
20547
|
+
}
|
|
20548
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
20549
|
+
throw new DevHostError('DEV_HOST_REGISTRY_INVALID', '调试台登记目录不能是文件或软链接,请检查用户缓存配置');
|
|
20550
|
+
}
|
|
20551
|
+
return directory;
|
|
20552
|
+
}
|
|
20553
|
+
async function requestJson(fetchImpl, url, options) {
|
|
20554
|
+
const response = await fetchImpl(url, { ...options, redirect: 'error' });
|
|
20555
|
+
if (!response.ok)
|
|
20556
|
+
throw new DevHostError('DEV_HOST_UNAVAILABLE', `调试台握手失败:HTTP ${response.status}`);
|
|
20557
|
+
const chunks = [];
|
|
20558
|
+
let length = 0;
|
|
20559
|
+
const reader = response.body?.getReader();
|
|
20560
|
+
if (!reader)
|
|
20561
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台没有返回 JSON');
|
|
20562
|
+
try {
|
|
20563
|
+
while (true) {
|
|
20564
|
+
const { done, value } = await reader.read();
|
|
20565
|
+
if (done)
|
|
20566
|
+
break;
|
|
20567
|
+
length += value.length;
|
|
20568
|
+
if (length > MAX_JSON_BYTES)
|
|
20569
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台握手结果过大');
|
|
20570
|
+
chunks.push(value);
|
|
20571
|
+
}
|
|
20572
|
+
}
|
|
20573
|
+
finally {
|
|
20574
|
+
await reader.cancel().catch(() => undefined);
|
|
20575
|
+
}
|
|
20576
|
+
let parsed;
|
|
20577
|
+
try {
|
|
20578
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
20579
|
+
}
|
|
20580
|
+
catch {
|
|
20581
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台返回了无效 JSON');
|
|
20582
|
+
}
|
|
20583
|
+
if (!isRecord$1(parsed))
|
|
20584
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台返回了无效 JSON');
|
|
20585
|
+
return parsed;
|
|
20586
|
+
}
|
|
20587
|
+
function readIdentity(value) {
|
|
20588
|
+
if (!isRecord$1(value) || value.schemaVersion !== 1 || typeof value.projectRoot !== 'string' || !path.isAbsolute(value.projectRoot) || typeof value.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(value.sessionId)) {
|
|
20589
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台身份信息无效');
|
|
20590
|
+
}
|
|
20591
|
+
validatePort(value.port);
|
|
20592
|
+
const appUrl = readSafeLocalUrl(value.appUrl, true);
|
|
20593
|
+
const previewUrl = readSafeLocalUrl(value.previewUrl);
|
|
20594
|
+
if (effectivePort(new URL(previewUrl)) !== value.port)
|
|
20595
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台端口与地址不一致');
|
|
20596
|
+
return { schemaVersion: 1, projectRoot: value.projectRoot, sessionId: value.sessionId, appUrl, previewUrl, port: value.port };
|
|
20597
|
+
}
|
|
20598
|
+
function readRecord(value) {
|
|
20599
|
+
const identity = readIdentity(value);
|
|
20600
|
+
if (!isRecord$1(value) || !Number.isInteger(value.pid) || Number(value.pid) <= 0 || Number(value.pid) > 0x7fffffff || typeof value.startedAt !== 'string' || !Number.isFinite(Date.parse(value.startedAt)))
|
|
20601
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台进程记录无效');
|
|
20602
|
+
return { ...identity, pid: Number(value.pid), startedAt: value.startedAt };
|
|
20603
|
+
}
|
|
20604
|
+
function readSafeLocalUrl(value, allowHttps = false) {
|
|
20605
|
+
if (typeof value !== 'string' || value.length > 8192)
|
|
20606
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台地址无效');
|
|
20607
|
+
let url;
|
|
20608
|
+
try {
|
|
20609
|
+
url = new URL(value);
|
|
20610
|
+
}
|
|
20611
|
+
catch {
|
|
20612
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试台地址无效');
|
|
20613
|
+
}
|
|
20614
|
+
if ((url.protocol !== 'http:' && !(allowHttps && url.protocol === 'https:')) || url.hostname !== '127.0.0.1' || url.username || url.password)
|
|
20615
|
+
throw new DevHostError('DEV_HOST_INVALID', '调试地址必须是受支持的本机 numeric loopback');
|
|
20616
|
+
validatePort(effectivePort(url));
|
|
20617
|
+
// 列表只需要可打开的入口;服务会为 / 补齐 mini_url,查询串与 fragment 不落盘。
|
|
20618
|
+
url.search = '';
|
|
20619
|
+
url.hash = '';
|
|
20620
|
+
return url.toString();
|
|
20621
|
+
}
|
|
20622
|
+
function effectivePort(url) {
|
|
20623
|
+
return url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80;
|
|
20624
|
+
}
|
|
20625
|
+
function validatePort(value) {
|
|
20626
|
+
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65535)
|
|
20627
|
+
throw new DevHostError('INVALID_PORT', '调试台端口无效');
|
|
20628
|
+
}
|
|
20629
|
+
function isProcessAlive(pid) {
|
|
20630
|
+
try {
|
|
20631
|
+
process.kill(pid, 0);
|
|
20632
|
+
return true;
|
|
20633
|
+
}
|
|
20634
|
+
catch (error) {
|
|
20635
|
+
return error.code === 'EPERM';
|
|
20636
|
+
}
|
|
20637
|
+
}
|
|
20638
|
+
function isConnectionRefused(error) {
|
|
20639
|
+
if (!error || typeof error !== 'object')
|
|
20640
|
+
return false;
|
|
20641
|
+
const cause = error;
|
|
20642
|
+
return cause.code === 'ECONNREFUSED' || isConnectionRefused(cause.cause) || (Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every(isConnectionRefused));
|
|
20643
|
+
}
|
|
20644
|
+
|
|
20645
|
+
/** 启动参数只影响 dev 启动;工具命令使用自身的目标端口或当前项目发现。 */
|
|
20646
|
+
function readDevToolPort(command, value) {
|
|
20647
|
+
for (let parent = command.parent; parent; parent = parent.parent) {
|
|
20648
|
+
if (parent.name() !== 'dev')
|
|
20649
|
+
continue;
|
|
20650
|
+
for (const key of ['port', 'browserDevHostPort', 'browser', 'browserMode', 'open']) {
|
|
20651
|
+
if (parent.getOptionValueSource(key) === 'cli') {
|
|
20652
|
+
throw new Error('dev 启动参数不能用于工具子命令;指定目标请在子命令后使用 --port');
|
|
20653
|
+
}
|
|
20654
|
+
}
|
|
20655
|
+
}
|
|
20656
|
+
if (value === undefined)
|
|
20657
|
+
return;
|
|
20658
|
+
const port = Number(value);
|
|
20659
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
20660
|
+
throw new Error('调试台端口无效');
|
|
20661
|
+
return port;
|
|
20662
|
+
}
|
|
20663
|
+
async function connectCurrentDevHost(port) {
|
|
20664
|
+
const projectRoot = await fs$2.realpath(findProjectRoot(process.cwd()));
|
|
20665
|
+
return resolveDevHostConnection({ projectRoot, port });
|
|
20666
|
+
}
|
|
20667
|
+
/** 所有后续读取也携带当前会话凭据,端口被另一进程复用时立即失败。 */
|
|
20668
|
+
async function requestDevHost(connection, pathname, options = {}, timeoutMs = 5000) {
|
|
20669
|
+
const headers = new Headers(options.headers);
|
|
20670
|
+
headers.set('origin', connection.origin);
|
|
20671
|
+
headers.set('x-hb-sdk-csrf', connection.csrfToken);
|
|
20672
|
+
if (options.body !== undefined)
|
|
20673
|
+
headers.set('content-type', 'application/json');
|
|
20674
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
20675
|
+
const signal = AbortSignal.any([timeout, ...(options.signal ? [options.signal] : [])]);
|
|
20676
|
+
try {
|
|
20677
|
+
signal.throwIfAborted();
|
|
20678
|
+
const response = await fetch(connection.origin + pathname, {
|
|
20679
|
+
...options,
|
|
20680
|
+
headers,
|
|
20681
|
+
redirect: 'error',
|
|
20682
|
+
signal,
|
|
20683
|
+
});
|
|
20684
|
+
let value;
|
|
20685
|
+
try {
|
|
20686
|
+
value = await response.json();
|
|
20687
|
+
}
|
|
20688
|
+
catch (error) {
|
|
20689
|
+
signal.throwIfAborted();
|
|
20690
|
+
if (!(error instanceof SyntaxError))
|
|
20691
|
+
throw error;
|
|
20692
|
+
}
|
|
20693
|
+
signal.throwIfAborted();
|
|
20694
|
+
const result = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
20695
|
+
if (!response.ok) {
|
|
20696
|
+
const code = typeof result?.code === 'string' ? result.code : `HTTP_${response.status}`;
|
|
20697
|
+
const message = typeof result?.message === 'string' ? result.message : '调试台请求失败,请检查会话后重试';
|
|
20698
|
+
throw new DevHostError(code, `${code}: ${message}`);
|
|
20699
|
+
}
|
|
20700
|
+
if (!result)
|
|
20701
|
+
throw new DevHostError('DEV_PROTOCOL_INVALID', '调试台返回了无效的 JSON 对象');
|
|
20702
|
+
return result;
|
|
20703
|
+
}
|
|
20704
|
+
catch (error) {
|
|
20705
|
+
// 外部取消保留调用者原因;本层期限和传输异常使用稳定的工具错误码。
|
|
20706
|
+
options.signal?.throwIfAborted();
|
|
20707
|
+
if (timeout.aborted)
|
|
20708
|
+
throw new DevHostError('DEV_TIMEOUT', '调试台请求超时,请用 hb-sdk dev inspect 检查会话');
|
|
20709
|
+
if (error instanceof DevHostError)
|
|
20710
|
+
throw error;
|
|
20711
|
+
throw new DevHostError('DEV_HOST_UNREACHABLE', '调试台连接已中断,请检查 dev 终端后重新连接');
|
|
20712
|
+
}
|
|
20713
|
+
}
|
|
20714
|
+
function writeDevResult(value) {
|
|
20715
|
+
process.stdout.write(JSON.stringify(value) + '\n');
|
|
20716
|
+
}
|
|
20717
|
+
|
|
20718
|
+
/** 取消当前等待,不取消共享任务;迟到资源仍由各自 owner 接管和释放。 */
|
|
20719
|
+
function awaitWithSignal(work, signal) {
|
|
20720
|
+
if (!signal)
|
|
20721
|
+
return work;
|
|
20722
|
+
return new Promise((resolve, reject) => {
|
|
20723
|
+
const abort = () => {
|
|
20724
|
+
signal.removeEventListener('abort', abort);
|
|
20725
|
+
reject(signal.reason);
|
|
20726
|
+
};
|
|
20727
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
20728
|
+
work.then((value) => {
|
|
20729
|
+
signal.removeEventListener('abort', abort);
|
|
20730
|
+
resolve(value);
|
|
20731
|
+
}, (error) => {
|
|
20732
|
+
signal.removeEventListener('abort', abort);
|
|
20733
|
+
reject(error);
|
|
20734
|
+
});
|
|
20735
|
+
if (signal.aborted)
|
|
20736
|
+
abort();
|
|
20737
|
+
});
|
|
20738
|
+
}
|
|
20739
|
+
|
|
20740
|
+
/** 固定兼容版本;生产安装不声明 core 依赖,也不下载浏览器。 */
|
|
20741
|
+
const PREVIEW_PLAYWRIGHT_VERSION = '1.64.1';
|
|
20742
|
+
const execFileAsync = node_util.promisify(childProcess.execFile);
|
|
20743
|
+
const pending = new Map();
|
|
20744
|
+
function previewDependencyDirectory(cacheRoot = process.env.HB_SDK_PREVIEW_CACHE_DIR ?? envPaths('hb-sdk', { suffix: '' }).cache) {
|
|
20745
|
+
return path.join(cacheRoot, 'preview', 'playwright-core', PREVIEW_PLAYWRIGHT_VERSION);
|
|
20746
|
+
}
|
|
20747
|
+
/** 只读取兼容缓存的安装元数据;status 不执行控制库,也不触发安装。 */
|
|
20748
|
+
function getPreviewPlaywrightStatus(cacheRoot) {
|
|
20749
|
+
const unavailable = { version: PREVIEW_PLAYWRIGHT_VERSION, installed: false, modulePath: null };
|
|
20750
|
+
const directory = previewDependencyDirectory(cacheRoot);
|
|
20751
|
+
try {
|
|
20752
|
+
const ready = JSON.parse(fs$3.readFileSync(path.join(directory, 'ready.json'), 'utf8'));
|
|
20753
|
+
const packageDirectory = path.join(directory, 'node_modules/playwright-core');
|
|
20754
|
+
const manifest = JSON.parse(fs$3.readFileSync(path.join(packageDirectory, 'package.json'), 'utf8'));
|
|
20755
|
+
if (ready.version !== PREVIEW_PLAYWRIGHT_VERSION || manifest.version !== PREVIEW_PLAYWRIGHT_VERSION)
|
|
20756
|
+
return unavailable;
|
|
20757
|
+
const modulePath = path.resolve(packageDirectory, typeof manifest.main === 'string' ? manifest.main : 'index.js');
|
|
20758
|
+
const relative = path.relative(packageDirectory, modulePath);
|
|
20759
|
+
if (relative.startsWith('..') || path.isAbsolute(relative) || !fs$3.statSync(modulePath).isFile())
|
|
20760
|
+
return unavailable;
|
|
20761
|
+
return { version: PREVIEW_PLAYWRIGHT_VERSION, installed: true, modulePath };
|
|
20762
|
+
}
|
|
20763
|
+
catch {
|
|
20764
|
+
return unavailable;
|
|
20765
|
+
}
|
|
20766
|
+
}
|
|
20767
|
+
/** 安装锁跨进程生效;同版本跨项目复用,失败不留下可加载的半成品。 */
|
|
20768
|
+
function loadPreviewPlaywright(options = {}) {
|
|
20769
|
+
const directory = previewDependencyDirectory(options.cacheRoot);
|
|
20770
|
+
let promise = pending.get(directory);
|
|
20771
|
+
if (!promise) {
|
|
20772
|
+
promise = loadOrInstall(directory, options).finally(() => pending.delete(directory));
|
|
20773
|
+
pending.set(directory, promise);
|
|
20774
|
+
}
|
|
20775
|
+
return promise;
|
|
20776
|
+
}
|
|
20777
|
+
async function readInstalled(directory) {
|
|
20778
|
+
try {
|
|
20779
|
+
const ready = JSON.parse(await fs$2.readFile(path.join(directory, 'ready.json'), 'utf8'));
|
|
20780
|
+
const manifest = JSON.parse(await fs$2.readFile(path.join(directory, 'node_modules/playwright-core/package.json'), 'utf8'));
|
|
20781
|
+
if (ready.version !== PREVIEW_PLAYWRIGHT_VERSION || manifest.version !== PREVIEW_PLAYWRIGHT_VERSION)
|
|
20782
|
+
return;
|
|
20783
|
+
const requireFromCache = node_module.createRequire(path.join(directory, 'package.json'));
|
|
20784
|
+
const module = requireFromCache('playwright-core');
|
|
20785
|
+
if (typeof module.chromium?.connectOverCDP === 'function')
|
|
20786
|
+
return module;
|
|
20787
|
+
}
|
|
20788
|
+
catch {
|
|
20789
|
+
/* 缺失或不完整时在锁内重建。 */
|
|
20790
|
+
}
|
|
20791
|
+
}
|
|
20792
|
+
async function loadOrInstall(directory, options) {
|
|
20793
|
+
const cached = await readInstalled(directory);
|
|
20794
|
+
if (cached)
|
|
20795
|
+
return cached;
|
|
20796
|
+
await fs$2.mkdir(path.dirname(directory), { recursive: true });
|
|
20797
|
+
const lock = directory + '.lock';
|
|
20798
|
+
const owner = `${process.pid}:${node_crypto.randomUUID()}`;
|
|
20799
|
+
const deadline = Date.now() + 180_000;
|
|
20800
|
+
while (true) {
|
|
20801
|
+
try {
|
|
20802
|
+
await fs$2.mkdir(lock);
|
|
20803
|
+
await fs$2.writeFile(path.join(lock, 'owner'), owner);
|
|
20804
|
+
break;
|
|
20805
|
+
}
|
|
20806
|
+
catch (error) {
|
|
20807
|
+
if (error.code !== 'EEXIST')
|
|
20808
|
+
throw error;
|
|
20809
|
+
const installed = await readInstalled(directory);
|
|
20810
|
+
if (installed)
|
|
20811
|
+
return installed;
|
|
20812
|
+
// 安装进程异常退出后可安全重试;EPERM 表示进程仍存在。
|
|
20813
|
+
try {
|
|
20814
|
+
const previous = await fs$2.readFile(path.join(lock, 'owner'), 'utf8');
|
|
20815
|
+
const pid = Number(previous.split(':')[0]);
|
|
20816
|
+
if (Number.isInteger(pid) && pid > 0) {
|
|
20817
|
+
try {
|
|
20818
|
+
process.kill(pid, 0);
|
|
20819
|
+
}
|
|
20820
|
+
catch (cause) {
|
|
20821
|
+
if (cause.code === 'ESRCH') {
|
|
20822
|
+
if ((await fs$2.readFile(path.join(lock, 'owner'), 'utf8')) === previous)
|
|
20823
|
+
await fs$2.rm(lock, { recursive: true, force: true });
|
|
20824
|
+
}
|
|
20825
|
+
}
|
|
20826
|
+
}
|
|
20827
|
+
}
|
|
20828
|
+
catch {
|
|
20829
|
+
// 极少数进程在 mkdir 后、写 owner 前退出;只回收已超过安装时限的空锁。
|
|
20830
|
+
const age = await fs$2.stat(lock)
|
|
20831
|
+
.then((info) => Date.now() - info.mtimeMs)
|
|
20832
|
+
.catch(() => 0);
|
|
20833
|
+
if (age > 180_000)
|
|
20834
|
+
await fs$2.rm(lock, { recursive: true, force: true });
|
|
20835
|
+
}
|
|
20836
|
+
if (Date.now() >= deadline)
|
|
20837
|
+
throw new Error('等待预览依赖安装超时,请稍后重试');
|
|
20838
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
20839
|
+
}
|
|
20840
|
+
}
|
|
20841
|
+
const staging = `${directory}.tmp-${node_crypto.randomUUID()}`;
|
|
20842
|
+
try {
|
|
20843
|
+
const installed = await readInstalled(directory);
|
|
20844
|
+
if (installed)
|
|
20845
|
+
return installed;
|
|
20846
|
+
options.progress?.(`首次使用预览能力,正在安装 playwright-core@${PREVIEW_PLAYWRIGHT_VERSION}(不下载浏览器)`);
|
|
20847
|
+
await fs$2.mkdir(staging);
|
|
20848
|
+
await fs$2.writeFile(path.join(staging, 'package.json'), JSON.stringify({ private: true }));
|
|
20849
|
+
await (options.install ?? installPlaywright)(staging);
|
|
20850
|
+
const manifest = JSON.parse(await fs$2.readFile(path.join(staging, 'node_modules/playwright-core/package.json'), 'utf8'));
|
|
20851
|
+
if (manifest.version !== PREVIEW_PLAYWRIGHT_VERSION)
|
|
20852
|
+
throw new Error('预览依赖版本校验失败');
|
|
20853
|
+
await fs$2.writeFile(path.join(staging, 'ready.json'), JSON.stringify({ version: PREVIEW_PLAYWRIGHT_VERSION }));
|
|
20854
|
+
// 暂存目录不能提前 require:core 内部的延迟 require 必须以晋升后的路径为基准。
|
|
20855
|
+
await fs$2.access(path.join(staging, 'node_modules/playwright-core', manifest.main ?? 'index.js'));
|
|
20856
|
+
await fs$2.rm(directory, { recursive: true, force: true });
|
|
20857
|
+
await fs$2.rename(staging, directory);
|
|
20858
|
+
const result = await readInstalled(directory);
|
|
20859
|
+
if (!result)
|
|
20860
|
+
throw new Error('无法加载已安装的预览依赖');
|
|
20861
|
+
return result;
|
|
20862
|
+
}
|
|
20863
|
+
finally {
|
|
20864
|
+
await fs$2.rm(staging, { recursive: true, force: true });
|
|
20865
|
+
if ((await fs$2.readFile(path.join(lock, 'owner'), 'utf8').catch(() => '')) === owner)
|
|
20866
|
+
await fs$2.rm(lock, { recursive: true, force: true });
|
|
20867
|
+
}
|
|
20868
|
+
}
|
|
20869
|
+
async function installPlaywright(directory) {
|
|
20870
|
+
const args = [
|
|
20871
|
+
'install',
|
|
20872
|
+
'--prefix',
|
|
20873
|
+
directory,
|
|
20874
|
+
'--save-exact',
|
|
20875
|
+
'--ignore-scripts',
|
|
20876
|
+
'--no-audit',
|
|
20877
|
+
'--no-fund',
|
|
20878
|
+
`playwright-core@${PREVIEW_PLAYWRIGHT_VERSION}`,
|
|
20879
|
+
];
|
|
20880
|
+
// Windows 的 npm.cmd 不能直接 execFile;通过 Node 执行 npm CLI,始终不经过 shell。
|
|
20881
|
+
const npmCli = process.env.npm_execpath?.endsWith('npm-cli.js')
|
|
20882
|
+
? process.env.npm_execpath
|
|
20883
|
+
: process.platform === 'win32'
|
|
20884
|
+
? path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js')
|
|
20885
|
+
: undefined;
|
|
20886
|
+
try {
|
|
20887
|
+
await execFileAsync(npmCli ? process.execPath : 'npm', npmCli ? [npmCli, ...args] : args, {
|
|
20888
|
+
cwd: directory,
|
|
20889
|
+
timeout: 120_000,
|
|
20890
|
+
maxBuffer: 1024 * 1024,
|
|
20891
|
+
windowsHide: true,
|
|
20892
|
+
});
|
|
20893
|
+
}
|
|
20894
|
+
catch {
|
|
20895
|
+
// npm 输出可能包含私有 registry 凭据,不将原始 stdout/stderr 写入错误或 JSON。
|
|
20896
|
+
throw new Error('安装预览依赖失败,请检查 npm、registry 和网络后重试;已有人工预览不受影响');
|
|
20897
|
+
}
|
|
20898
|
+
}
|
|
20899
|
+
|
|
20359
20900
|
/**
|
|
20360
|
-
*
|
|
20361
|
-
*
|
|
20362
|
-
* 2. 否则跟随父 `dev` 命令的 `--browser-dev-host-port`;
|
|
20363
|
-
* 3. 都没有时回退调试台默认端口 5174。
|
|
20364
|
-
* 这里不能读 `dev --port`:那是小程序开发服务器端口,日志路由只挂在调试台服务上。
|
|
20901
|
+
* 有界等待:超过 timeoutMs 后由 onTimeout 决定结果(返回或抛错)。
|
|
20902
|
+
* 计时器总会清理,迟到结果由调用方按需接管。
|
|
20365
20903
|
*/
|
|
20366
|
-
function
|
|
20367
|
-
|
|
20368
|
-
|
|
20369
|
-
|
|
20370
|
-
|
|
20371
|
-
|
|
20372
|
-
|
|
20373
|
-
|
|
20374
|
-
|
|
20904
|
+
async function waitBounded(work, timeoutMs, onTimeout) {
|
|
20905
|
+
let timer;
|
|
20906
|
+
try {
|
|
20907
|
+
return await Promise.race([
|
|
20908
|
+
work,
|
|
20909
|
+
new Promise((resolve, reject) => {
|
|
20910
|
+
timer = setTimeout(() => {
|
|
20911
|
+
try {
|
|
20912
|
+
resolve(onTimeout());
|
|
20913
|
+
}
|
|
20914
|
+
catch (error) {
|
|
20915
|
+
reject(error);
|
|
20916
|
+
}
|
|
20917
|
+
}, timeoutMs);
|
|
20918
|
+
}),
|
|
20919
|
+
]);
|
|
20920
|
+
}
|
|
20921
|
+
finally {
|
|
20922
|
+
clearTimeout(timer);
|
|
20375
20923
|
}
|
|
20376
|
-
return DEFAULT_BROWSER_DEV_HOST_PORT;
|
|
20377
20924
|
}
|
|
20378
|
-
|
|
20379
|
-
|
|
20380
|
-
|
|
20381
|
-
|
|
20382
|
-
|
|
20925
|
+
|
|
20926
|
+
class PreviewTargetError extends Error {
|
|
20927
|
+
code;
|
|
20928
|
+
name = 'PreviewError';
|
|
20929
|
+
constructor(code, message) {
|
|
20930
|
+
super(message);
|
|
20931
|
+
this.code = code;
|
|
20932
|
+
}
|
|
20933
|
+
}
|
|
20934
|
+
/** 只按浏览器登记的 targetId 认领 Page;不按 URL、顺序或同地址副本猜测。 */
|
|
20935
|
+
async function findPreviewPage(connection, targetId, signal, timeoutMs = 10_000) {
|
|
20936
|
+
signal?.throwIfAborted();
|
|
20937
|
+
if (!targetId)
|
|
20938
|
+
throw unavailable();
|
|
20939
|
+
const timeout = new AbortController();
|
|
20940
|
+
const deadline = setTimeout(() => timeout.abort(unavailable()), timeoutMs);
|
|
20941
|
+
const operationSignal = AbortSignal.any([timeout.signal, ...(signal ? [signal] : [])]);
|
|
20942
|
+
try {
|
|
20943
|
+
while (true) {
|
|
20944
|
+
operationSignal.throwIfAborted();
|
|
20945
|
+
if (!connection.isConnected())
|
|
20946
|
+
throw disconnected();
|
|
20947
|
+
for (const page of connection.contexts().flatMap((context) => context.pages())) {
|
|
20948
|
+
operationSignal.throwIfAborted();
|
|
20949
|
+
let session;
|
|
20950
|
+
let matched = false;
|
|
20951
|
+
try {
|
|
20952
|
+
const attaching = page
|
|
20953
|
+
.context()
|
|
20954
|
+
.newCDPSession(page)
|
|
20955
|
+
.then((value) => {
|
|
20956
|
+
if (operationSignal.aborted)
|
|
20957
|
+
void value.detach().catch(() => undefined);
|
|
20958
|
+
return value;
|
|
20959
|
+
});
|
|
20960
|
+
session = await awaitWithSignal(attaching, operationSignal);
|
|
20961
|
+
const result = await awaitWithSignal(session.send('Target.getTargetInfo'), operationSignal);
|
|
20962
|
+
matched = isRecord$1(result) && isRecord$1(result.targetInfo) && result.targetInfo.targetId === targetId;
|
|
20963
|
+
}
|
|
20964
|
+
catch {
|
|
20965
|
+
operationSignal.throwIfAborted();
|
|
20966
|
+
if (!connection.isConnected())
|
|
20967
|
+
throw disconnected();
|
|
20968
|
+
// 已关闭或无法附加的候选不会变成替代目标,继续核对其它 Page 的精确 ID。
|
|
20969
|
+
}
|
|
20970
|
+
finally {
|
|
20971
|
+
if (session)
|
|
20972
|
+
await boundedDetach(session);
|
|
20973
|
+
}
|
|
20974
|
+
operationSignal.throwIfAborted();
|
|
20975
|
+
if (matched)
|
|
20976
|
+
return page;
|
|
20977
|
+
}
|
|
20978
|
+
await awaitWithSignal(new Promise((resolve) => setTimeout(resolve, 100)), operationSignal);
|
|
20979
|
+
}
|
|
20980
|
+
}
|
|
20981
|
+
finally {
|
|
20982
|
+
clearTimeout(deadline);
|
|
20983
|
+
}
|
|
20984
|
+
}
|
|
20985
|
+
function unavailable() {
|
|
20986
|
+
return new PreviewTargetError('PAGE_UNAVAILABLE', '本次调试标签页不可用,请运行 hb-sdk dev preview open 后重试');
|
|
20987
|
+
}
|
|
20988
|
+
function disconnected() {
|
|
20989
|
+
return new PreviewTargetError('BROWSER_CLOSED', '预览浏览器连接已断开,请重新打开窗口');
|
|
20990
|
+
}
|
|
20991
|
+
async function boundedDetach(session) {
|
|
20992
|
+
await waitBounded(session.detach().catch(() => undefined), 250, () => undefined);
|
|
20993
|
+
}
|
|
20994
|
+
/** 只核验精确命中的自有 target 内容,不通过 URL 寻找或认领页面。 */
|
|
20995
|
+
function isPreviewDocumentUrl(actual, expected) {
|
|
20996
|
+
try {
|
|
20997
|
+
const current = new URL(String(actual));
|
|
20998
|
+
const preview = new URL(expected);
|
|
20999
|
+
return (current.origin === preview.origin &&
|
|
21000
|
+
current.pathname === preview.pathname &&
|
|
21001
|
+
current.searchParams.get('mini_url') === preview.searchParams.get('mini_url'));
|
|
21002
|
+
}
|
|
21003
|
+
catch {
|
|
21004
|
+
return false;
|
|
21005
|
+
}
|
|
21006
|
+
}
|
|
21007
|
+
|
|
21008
|
+
/** 当前客户端无法确认焦点模拟的创建或释放;调用方应断开自己的控制连接兜底。 */
|
|
21009
|
+
class PreviewFocusError extends Error {
|
|
21010
|
+
code;
|
|
21011
|
+
name = 'PreviewError';
|
|
21012
|
+
constructor(code, message) {
|
|
21013
|
+
super(message);
|
|
21014
|
+
this.code = code;
|
|
21015
|
+
}
|
|
21016
|
+
}
|
|
21017
|
+
/**
|
|
21018
|
+
* 只为调用方已核验的 SDK Page 持有一份交互焦点模拟。
|
|
21019
|
+
* 原生 Chrome 按 CDP session 聚合状态;释放只 detach 自己的 session,不显式关掉其他客户端的模拟。
|
|
21020
|
+
*/
|
|
21021
|
+
async function acquirePreviewFocus(page, signal) {
|
|
21022
|
+
signal?.throwIfAborted();
|
|
21023
|
+
let session;
|
|
21024
|
+
let releasing;
|
|
21025
|
+
const release = () => {
|
|
21026
|
+
if (!session)
|
|
21027
|
+
return Promise.resolve();
|
|
21028
|
+
return (releasing ??= detachFocus(session));
|
|
21029
|
+
};
|
|
21030
|
+
try {
|
|
21031
|
+
const attaching = page
|
|
21032
|
+
.context()
|
|
21033
|
+
.newCDPSession(page)
|
|
21034
|
+
.then(async (value) => {
|
|
21035
|
+
session = value;
|
|
21036
|
+
if (signal?.aborted) {
|
|
21037
|
+
await release().catch(() => undefined);
|
|
21038
|
+
signal.throwIfAborted();
|
|
21039
|
+
}
|
|
21040
|
+
return value;
|
|
21041
|
+
});
|
|
21042
|
+
const client = await awaitWithSignal(attaching, signal);
|
|
21043
|
+
signal?.throwIfAborted();
|
|
21044
|
+
await awaitWithSignal(client.send('Emulation.setFocusEmulationEnabled', { enabled: true }), signal);
|
|
21045
|
+
signal?.throwIfAborted();
|
|
21046
|
+
return release;
|
|
21047
|
+
}
|
|
21048
|
+
catch {
|
|
21049
|
+
let cleanupFailed = false;
|
|
21050
|
+
try {
|
|
21051
|
+
await release();
|
|
21052
|
+
}
|
|
21053
|
+
catch {
|
|
21054
|
+
cleanupFailed = true;
|
|
21055
|
+
}
|
|
21056
|
+
signal?.throwIfAborted();
|
|
21057
|
+
if (cleanupFailed)
|
|
21058
|
+
throw releaseFailed();
|
|
21059
|
+
throw new PreviewFocusError('PREVIEW_FOCUS_UNAVAILABLE', '无法为当前 SDK 预览启用交互焦点模拟,请重新打开预览后重试');
|
|
21060
|
+
}
|
|
21061
|
+
}
|
|
21062
|
+
async function detachFocus(session) {
|
|
21063
|
+
try {
|
|
21064
|
+
// detach 的同步异常同样按释放失败处理,不向调用方泄露原始协议细节。
|
|
21065
|
+
await waitBounded(Promise.resolve().then(() => session.detach()), 500, () => {
|
|
21066
|
+
throw releaseFailed();
|
|
21067
|
+
});
|
|
21068
|
+
}
|
|
21069
|
+
catch {
|
|
21070
|
+
throw releaseFailed();
|
|
21071
|
+
}
|
|
21072
|
+
}
|
|
21073
|
+
function releaseFailed() {
|
|
21074
|
+
return new PreviewFocusError('PREVIEW_FOCUS_RELEASE_FAILED', '未能确认交互焦点模拟已释放,请断开当前控制客户端后重新连接');
|
|
21075
|
+
}
|
|
21076
|
+
|
|
21077
|
+
/**
|
|
21078
|
+
* 在 Node.js 中连接当前项目已打开的共享预览,返回原生 Playwright 对象。
|
|
21079
|
+
*
|
|
21080
|
+
* @param connection - 已核验并固定的开发会话。
|
|
21081
|
+
* @param options - 取消信号、焦点模拟和连接预算。
|
|
21082
|
+
* @returns 精确绑定当前预览目标的 Page、动态 FrameLocator、会话快照和断连函数。
|
|
21083
|
+
* @remarks
|
|
21084
|
+
* 调用前需要运行 `hb-sdk dev` 并打开预览。本函数不会启动服务、打开页面或重播操作。
|
|
21085
|
+
* 首次使用时按需安装固定版本控制库到用户缓存,不下载浏览器;共享安装有自己的有限期限,
|
|
21086
|
+
* 不占用 `timeoutMs`,但取消后不会继续建立连接。返回前会再次核验原服务与 target 身份。
|
|
21087
|
+
* `page` 不会在服务重启或标签页关闭后自动迁移;需要重新调用本函数。
|
|
21088
|
+
* 原生 Playwright 操作的等待和取消由调用方自行指定,结束后应在 finally 中断连。
|
|
21089
|
+
* 默认仅对精确 SDK Page 启用交互焦点模拟,让后台窗口的动画帧、点击与截图可以正常等待。
|
|
21090
|
+
* 模拟会影响 document.visibilityState,并可能触发 visibilitychange;不会抢占系统焦点或修改其他页面、媒体设置。
|
|
21091
|
+
* 多个客户端分别持有自己的模拟,disconnect 只释放本连接;需要观察真实生命周期时传 emulateFocus: false。
|
|
21092
|
+
* @throws 目标缺失、会话变化、版本不兼容或超时时抛出带 `code` 和操作指引的 Error;取消时抛出 signal.reason。
|
|
21093
|
+
* @example
|
|
21094
|
+
* ```ts
|
|
21095
|
+
* import { connectDevSession } from '@heybox/hb-sdk/dev';
|
|
21096
|
+
*
|
|
21097
|
+
* const dev = await connectDevSession();
|
|
21098
|
+
* const preview = await dev.preview.connect();
|
|
21099
|
+
* try {
|
|
21100
|
+
* await preview.app.locator('body').screenshot({ path: 'app.png' });
|
|
21101
|
+
* } finally {
|
|
21102
|
+
* await preview.disconnect();
|
|
21103
|
+
* }
|
|
21104
|
+
* ```
|
|
21105
|
+
* @since 0.9.6
|
|
21106
|
+
*/
|
|
21107
|
+
async function connectPreviewBrowser(connection, options = {}) {
|
|
21108
|
+
validateOptions(options);
|
|
21109
|
+
options.signal?.throwIfAborted();
|
|
21110
|
+
const budget = connectionBudget(options.timeoutMs ?? 30_000, options.signal);
|
|
21111
|
+
const { signal } = budget;
|
|
21112
|
+
const wait = async (work) => {
|
|
21113
|
+
const value = await awaitWithSignal(work, signal);
|
|
21114
|
+
budget.check();
|
|
21115
|
+
return value;
|
|
21116
|
+
};
|
|
21117
|
+
let browser;
|
|
21118
|
+
let releaseFocus;
|
|
21119
|
+
let closing;
|
|
21120
|
+
const disconnect = () => {
|
|
21121
|
+
if (!browser)
|
|
21122
|
+
return Promise.resolve();
|
|
21123
|
+
// connectOverCDP 的 Browser.close 仅释放本客户端;不关闭 page、context 或所属浏览器 lease。
|
|
21124
|
+
return (closing ??= Promise.resolve().then(async () => {
|
|
21125
|
+
// 即使 detach 未获确认,随后关闭自己的 client 仍会释放该 client 的 CDP sessions。
|
|
21126
|
+
try {
|
|
21127
|
+
await releaseFocus?.();
|
|
21128
|
+
}
|
|
21129
|
+
catch {
|
|
21130
|
+
/* 只断开本客户端兜底,不覆盖其他客户端的焦点状态。 */
|
|
21131
|
+
}
|
|
21132
|
+
finally {
|
|
21133
|
+
await browser.close();
|
|
21134
|
+
}
|
|
21135
|
+
}));
|
|
21136
|
+
};
|
|
21137
|
+
try {
|
|
21138
|
+
const projectRoot = connection.record.projectRoot;
|
|
21139
|
+
const status = await wait(requestDevHost(connection, PREVIEW_PATH, { signal }, Math.min(5000, budget.remaining())));
|
|
21140
|
+
const expected = await wait(readSnapshot(status, connection));
|
|
21141
|
+
const validateCurrent = async () => {
|
|
21142
|
+
let value;
|
|
21143
|
+
try {
|
|
21144
|
+
value = await wait(requestDevHost(connection, PREVIEW_PATH, { signal }, Math.min(5000, budget.remaining())));
|
|
21145
|
+
}
|
|
21146
|
+
catch {
|
|
21147
|
+
signal.throwIfAborted();
|
|
21148
|
+
throw failure('PREVIEW_SESSION_CHANGED', '当前调试台已不可用或会话已变化,请检查 dev 终端并重新调用 dev.preview.connect()');
|
|
21149
|
+
}
|
|
21150
|
+
const current = await wait(readSnapshot(value, connection));
|
|
21151
|
+
if (current.targetId !== expected.targetId || current.endpoint !== expected.endpoint || current.previewUrl !== expected.previewUrl) {
|
|
21152
|
+
throw failure('PREVIEW_TARGET_CHANGED', '预览目标已变化,请重新调用 dev.preview.connect();如页面已关闭,请先运行 hb-sdk dev preview open');
|
|
21153
|
+
}
|
|
21154
|
+
};
|
|
21155
|
+
await validateCurrent();
|
|
21156
|
+
budget.pause();
|
|
21157
|
+
let driver;
|
|
21158
|
+
try {
|
|
21159
|
+
driver = await wait(loadPreviewPlaywright());
|
|
21160
|
+
}
|
|
21161
|
+
catch {
|
|
21162
|
+
signal.throwIfAborted();
|
|
21163
|
+
throw failure('DEPENDENCY_UNAVAILABLE', '无法加载固定版本预览控制库,请运行 hb-sdk dev preview setup 后重新连接');
|
|
21164
|
+
}
|
|
21165
|
+
budget.resume();
|
|
21166
|
+
await validateCurrent();
|
|
21167
|
+
const connecting = driver.chromium
|
|
21168
|
+
.connectOverCDP(expected.endpoint, { noDefaults: true, timeout: budget.remaining() })
|
|
21169
|
+
.then(async (connection) => {
|
|
21170
|
+
// 唯一动态适配边界:loader 已校验固定版本,真实对象是该官方版本的 Browser。
|
|
21171
|
+
browser = connection;
|
|
21172
|
+
if (signal.aborted) {
|
|
21173
|
+
await disconnect().catch(() => undefined);
|
|
21174
|
+
signal.throwIfAborted();
|
|
21175
|
+
}
|
|
21176
|
+
return browser;
|
|
21177
|
+
});
|
|
21178
|
+
const client = await wait(connecting);
|
|
21179
|
+
const page = await wait(findPreviewPage(client, expected.targetId, signal, budget.remaining()));
|
|
21180
|
+
await validateCurrent();
|
|
21181
|
+
signal.throwIfAborted();
|
|
21182
|
+
assertPreviewContent(page, expected.previewUrl);
|
|
21183
|
+
if (options.emulateFocus !== false) {
|
|
21184
|
+
await wait(acquirePreviewFocus(page, signal).then(async (release) => {
|
|
21185
|
+
releaseFocus = release;
|
|
21186
|
+
if (signal.aborted) {
|
|
21187
|
+
await release().catch(() => undefined);
|
|
21188
|
+
signal.throwIfAborted();
|
|
21189
|
+
}
|
|
21190
|
+
}));
|
|
21191
|
+
await validateCurrent();
|
|
21192
|
+
budget.check();
|
|
21193
|
+
assertPreviewContent(page, expected.previewUrl);
|
|
21194
|
+
}
|
|
21195
|
+
return {
|
|
21196
|
+
page,
|
|
21197
|
+
app: page.frameLocator(PREVIEW_SELECTORS.app),
|
|
21198
|
+
session: { id: connection.record.sessionId, projectRoot, port: connection.record.port, cdpTargetId: expected.targetId },
|
|
21199
|
+
disconnect,
|
|
21200
|
+
};
|
|
21201
|
+
}
|
|
21202
|
+
catch (error) {
|
|
21203
|
+
await disconnect().catch(() => undefined);
|
|
21204
|
+
signal.throwIfAborted();
|
|
21205
|
+
if (error instanceof PreviewConnectionError || error instanceof PreviewFocusError || error instanceof DevHostError)
|
|
21206
|
+
throw error;
|
|
21207
|
+
if (isRecord$1(error) && (error.code === 'PAGE_UNAVAILABLE' || error.code === 'BROWSER_CLOSED')) {
|
|
21208
|
+
throw failure(String(error.code), '当前预览标签页不可用,请运行 hb-sdk dev preview open 后重新调用 dev.preview.connect()');
|
|
21209
|
+
}
|
|
21210
|
+
throw failure('PREVIEW_CONNECT_FAILED', '连接预览失败,请用 hb-sdk dev inspect 检查当前窗口,再重新调用 dev.preview.connect()');
|
|
21211
|
+
}
|
|
21212
|
+
finally {
|
|
21213
|
+
budget.dispose();
|
|
21214
|
+
}
|
|
21215
|
+
}
|
|
21216
|
+
class PreviewConnectionError extends Error {
|
|
21217
|
+
code;
|
|
21218
|
+
name = 'PreviewConnectionError';
|
|
21219
|
+
constructor(code, message) {
|
|
21220
|
+
super(message);
|
|
21221
|
+
this.code = code;
|
|
21222
|
+
}
|
|
21223
|
+
}
|
|
21224
|
+
function failure(code, message) {
|
|
21225
|
+
return new PreviewConnectionError(code, message);
|
|
21226
|
+
}
|
|
21227
|
+
function incompatible() {
|
|
21228
|
+
return failure('PREVIEW_INCOMPATIBLE', '调试台控制协议或固定驱动版本不兼容,请升级 SDK 并重新运行 hb-sdk dev');
|
|
21229
|
+
}
|
|
21230
|
+
async function readSnapshot(value, connection) {
|
|
21231
|
+
if (value.schemaVersion !== 1 || !isRecord$1(value.playwright) || value.playwright.version !== PREVIEW_PLAYWRIGHT_VERSION)
|
|
21232
|
+
throw incompatible();
|
|
21233
|
+
const { projectRoot } = connection.record;
|
|
21234
|
+
const actualRoot = typeof value.projectRoot === 'string' ? await fs$2.realpath(value.projectRoot).catch(() => undefined) : undefined;
|
|
21235
|
+
if (value.sessionId !== connection.record.sessionId || actualRoot !== projectRoot) {
|
|
21236
|
+
throw failure('PREVIEW_SESSION_CHANGED', '当前调试台已不属于原项目或会话,请重新调用 dev.preview.connect()');
|
|
21237
|
+
}
|
|
21238
|
+
if (!isRecord$1(value.browser))
|
|
21239
|
+
throw incompatible();
|
|
21240
|
+
if (value.browser.state !== 'ready') {
|
|
21241
|
+
const uncertain = isRecord$1(value.browser.openError) && value.browser.openError.code === 'TARGET_CREATION_UNCONFIRMED';
|
|
21242
|
+
throw failure('PREVIEW_NOT_OPEN', uncertain
|
|
21243
|
+
? '尚无法确认预览页,请先检查浏览器,再运行 hb-sdk dev preview open,随后重新连接'
|
|
21244
|
+
: '当前项目尚未打开可连接的预览页,请先运行 hb-sdk dev preview open');
|
|
21245
|
+
}
|
|
21246
|
+
const endpoint = value.browser.cdpEndpoint;
|
|
21247
|
+
const targetId = value.browser.cdpTargetId;
|
|
21248
|
+
if (typeof endpoint !== 'string' ||
|
|
21249
|
+
typeof targetId !== 'string' ||
|
|
21250
|
+
!targetId.trim() ||
|
|
21251
|
+
targetId.length > 512 ||
|
|
21252
|
+
typeof value.previewUrl !== 'string')
|
|
21253
|
+
throw incompatible();
|
|
21254
|
+
let url;
|
|
21255
|
+
let previewUrl;
|
|
21256
|
+
try {
|
|
21257
|
+
url = new URL(endpoint);
|
|
21258
|
+
previewUrl = new URL(value.previewUrl);
|
|
21259
|
+
}
|
|
21260
|
+
catch {
|
|
21261
|
+
throw incompatible();
|
|
21262
|
+
}
|
|
21263
|
+
if (!['http:', 'ws:'].includes(url.protocol) || url.hostname !== '127.0.0.1' || url.username || url.password || url.hash)
|
|
21264
|
+
throw incompatible();
|
|
21265
|
+
if (previewUrl.origin !== new URL(connection.origin).origin || previewUrl.username || previewUrl.password)
|
|
21266
|
+
throw incompatible();
|
|
21267
|
+
return { endpoint, targetId, previewUrl: previewUrl.toString() };
|
|
21268
|
+
}
|
|
21269
|
+
function assertPreviewContent(page, expectedUrl) {
|
|
21270
|
+
if (isPreviewDocumentUrl(page.url(), expectedUrl))
|
|
21271
|
+
return;
|
|
21272
|
+
throw failure('PREVIEW_PAGE_CHANGED', '本次预览标签页已离开调试台,请运行 hb-sdk dev preview open 后重新调用 dev.preview.connect()');
|
|
21273
|
+
}
|
|
21274
|
+
function validateOptions(options) {
|
|
21275
|
+
if (!options || typeof options !== 'object' || Array.isArray(options))
|
|
21276
|
+
throw failure('INVALID_OPTIONS', '连接选项必须是对象');
|
|
21277
|
+
if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 2_147_483_647))
|
|
21278
|
+
throw failure('INVALID_TIMEOUT', 'timeoutMs 必须是有效的正整数毫秒数');
|
|
21279
|
+
if (options.signal !== undefined &&
|
|
21280
|
+
(!options.signal ||
|
|
21281
|
+
typeof options.signal.addEventListener !== 'function' ||
|
|
21282
|
+
typeof options.signal.throwIfAborted !== 'function' ||
|
|
21283
|
+
typeof options.signal.aborted !== 'boolean'))
|
|
21284
|
+
throw failure('INVALID_SIGNAL', 'signal 必须是 Node.js AbortSignal');
|
|
21285
|
+
if (options.emulateFocus !== undefined && typeof options.emulateFocus !== 'boolean')
|
|
21286
|
+
throw failure('INVALID_FOCUS', 'emulateFocus 必须是 boolean');
|
|
21287
|
+
}
|
|
21288
|
+
function connectionBudget(timeoutMs, external) {
|
|
21289
|
+
const expired = new AbortController();
|
|
21290
|
+
let signal;
|
|
21291
|
+
try {
|
|
21292
|
+
signal = AbortSignal.any([expired.signal, ...(external ? [external] : [])]);
|
|
21293
|
+
}
|
|
21294
|
+
catch {
|
|
21295
|
+
throw failure('INVALID_SIGNAL', 'signal 必须是 Node.js AbortSignal');
|
|
21296
|
+
}
|
|
21297
|
+
let remaining = timeoutMs;
|
|
21298
|
+
let deadlineAt = Date.now() + remaining;
|
|
21299
|
+
let timer;
|
|
21300
|
+
const start = () => {
|
|
21301
|
+
deadlineAt = Date.now() + remaining;
|
|
21302
|
+
timer = setTimeout(() => expired.abort(failure('PREVIEW_TIMEOUT', '连接预览超时,请检查 dev 终端;首次使用可先运行 hb-sdk dev preview setup')), remaining);
|
|
21303
|
+
};
|
|
21304
|
+
const check = () => {
|
|
21305
|
+
if (timer !== undefined && Date.now() >= deadlineAt)
|
|
21306
|
+
expired.abort(failure('PREVIEW_TIMEOUT', '连接预览超时,请检查 dev 终端后重新连接'));
|
|
21307
|
+
signal.throwIfAborted();
|
|
21308
|
+
};
|
|
21309
|
+
start();
|
|
21310
|
+
return {
|
|
21311
|
+
signal,
|
|
21312
|
+
check,
|
|
21313
|
+
remaining() {
|
|
21314
|
+
check();
|
|
21315
|
+
return Math.max(1, deadlineAt - Date.now());
|
|
21316
|
+
},
|
|
21317
|
+
pause() {
|
|
21318
|
+
check();
|
|
21319
|
+
remaining = Math.max(1, deadlineAt - Date.now());
|
|
21320
|
+
clearTimeout(timer);
|
|
21321
|
+
timer = undefined;
|
|
21322
|
+
},
|
|
21323
|
+
resume() {
|
|
21324
|
+
check();
|
|
21325
|
+
start();
|
|
21326
|
+
},
|
|
21327
|
+
dispose() {
|
|
21328
|
+
clearTimeout(timer);
|
|
21329
|
+
},
|
|
21330
|
+
};
|
|
21331
|
+
}
|
|
21332
|
+
|
|
21333
|
+
/** 本机开发工具合同,不属于 Mini-program bridge 协议。 */
|
|
21334
|
+
const DEV_DIAGNOSTICS_PATH = '/__hb_sdk__/diagnostics';
|
|
21335
|
+
const DEV_RESOURCE_PATH = '/__hb_sdk__/resources';
|
|
21336
|
+
const DEV_DIAGNOSTICS_SCHEMA_VERSION = 3;
|
|
21337
|
+
const DEV_SANDBOX_READ_MAX_BYTES = 16 * 1024;
|
|
21338
|
+
const DEV_PRESENTATION_MAX_INTERACTIONS = 16;
|
|
21339
|
+
|
|
21340
|
+
/** CLI 与 Node 共用固定连接,禁止每次操作重新发现并静默迁移到新服务。 */
|
|
21341
|
+
function createDevSession(connection, sessionSignal) {
|
|
21342
|
+
const request = async (pathname, options = {}, init = {}) => {
|
|
21343
|
+
const operation = requestBudget(options);
|
|
21344
|
+
try {
|
|
21345
|
+
return await requestDevHost(connection, pathname, { ...init, signal: operation.signal }, operation.remaining());
|
|
21346
|
+
}
|
|
21347
|
+
finally {
|
|
21348
|
+
operation.dispose();
|
|
21349
|
+
}
|
|
21350
|
+
};
|
|
21351
|
+
const check = (value) => {
|
|
21352
|
+
if (value.schemaVersion !== DEV_DIAGNOSTICS_SCHEMA_VERSION)
|
|
21353
|
+
throw new DevHostError('DEV_PROTOCOL_INCOMPATIBLE', '开发会话诊断协议不兼容,请升级 SDK 并重启 hb-sdk dev');
|
|
21354
|
+
if (value.sessionId !== connection.record.sessionId)
|
|
21355
|
+
throw new DevHostError('DEV_SESSION_CHANGED', '开发会话已变化,请重新调用 connectDevSession');
|
|
21356
|
+
};
|
|
21357
|
+
const inspect = async (options = {}) => {
|
|
21358
|
+
const operation = requestBudget(options);
|
|
21359
|
+
try {
|
|
21360
|
+
// 先固定预算再启动并发请求;不能在首个 Promise 启动后同步抛错,留下无人接管的拒绝。
|
|
21361
|
+
const timeoutMs = operation.remaining();
|
|
21362
|
+
const [preview, diagnostics] = await Promise.all([
|
|
21363
|
+
requestDevHost(connection, PREVIEW_PATH, { signal: operation.signal }, timeoutMs),
|
|
21364
|
+
requestDevHost(connection, DEV_DIAGNOSTICS_PATH + '?mode=inspect', { signal: operation.signal }, timeoutMs),
|
|
21365
|
+
]);
|
|
21366
|
+
operation.remaining();
|
|
21367
|
+
check(diagnostics);
|
|
21368
|
+
if (preview.sessionId !== connection.record.sessionId || preview.projectRoot !== connection.record.projectRoot)
|
|
21369
|
+
throw new DevHostError('DEV_SESSION_CHANGED', '开发会话已变化,请重新连接');
|
|
21370
|
+
if (!Array.isArray(diagnostics.targets) ||
|
|
21371
|
+
!Array.isArray(diagnostics.instances) ||
|
|
21372
|
+
!Number.isSafeInteger(diagnostics.nextCursor) ||
|
|
21373
|
+
typeof diagnostics.epoch !== 'string')
|
|
21374
|
+
throw new DevHostError('DEV_PROTOCOL_INVALID', '开发会话返回了无效状态');
|
|
21375
|
+
return { ...preview, ...diagnostics };
|
|
21376
|
+
}
|
|
21377
|
+
finally {
|
|
21378
|
+
operation.dispose();
|
|
21379
|
+
}
|
|
21380
|
+
};
|
|
21381
|
+
const resolveSelection = async (selection, options) => {
|
|
21382
|
+
if (selection.instanceId !== undefined)
|
|
21383
|
+
return { instanceId: selection.instanceId };
|
|
21384
|
+
const snapshot = await inspect(options);
|
|
21385
|
+
const target = selection.targetId === undefined ? snapshot.primaryTarget : snapshot.targets.find((item) => item.targetId === selection.targetId);
|
|
21386
|
+
if (!target)
|
|
21387
|
+
throw new DevHostError('DEV_TARGET_NOT_FOUND', '目标不存在,请用 dev inspect 查看 targets');
|
|
21388
|
+
if (!target.currentInstanceId)
|
|
21389
|
+
throw new DevHostError('RUNTIME_NOT_STARTED', '该目标尚无当前实例,请查看 dev inspect');
|
|
21390
|
+
return { targetId: target.targetId, instanceId: target.currentInstanceId };
|
|
21391
|
+
};
|
|
21392
|
+
const logs = async (filters = {}) => {
|
|
21393
|
+
validateSelection(filters);
|
|
21394
|
+
const params = logParameters(filters);
|
|
21395
|
+
const value = await request(DEV_DIAGNOSTICS_PATH + '?' + params, filters);
|
|
21396
|
+
check(value);
|
|
21397
|
+
if (!Array.isArray(value.items) ||
|
|
21398
|
+
!Number.isSafeInteger(value.nextCursor) ||
|
|
21399
|
+
typeof value.epoch !== 'string' ||
|
|
21400
|
+
typeof value.hasMore !== 'boolean' ||
|
|
21401
|
+
typeof value.gap !== 'boolean')
|
|
21402
|
+
throw new DevHostError('DEV_PROTOCOL_INVALID', '开发会话返回了无效日志页');
|
|
21403
|
+
return value;
|
|
21404
|
+
};
|
|
21405
|
+
const projection = async (filters, kind) => {
|
|
21406
|
+
validateSelection(filters);
|
|
21407
|
+
logParameters(filters);
|
|
21408
|
+
const operation = requestBudget(filters);
|
|
21409
|
+
try {
|
|
21410
|
+
let targetId = filters.targetId;
|
|
21411
|
+
if (targetId === undefined && filters.instanceId === undefined) {
|
|
21412
|
+
targetId = (await inspect({ signal: operation.signal, timeoutMs: operation.remaining() })).primaryTargetId ?? undefined;
|
|
21413
|
+
if (!targetId)
|
|
21414
|
+
throw new DevHostError('DEV_TARGET_NOT_FOUND', '尚无主预览目标,请指定 targetId 或 instanceId');
|
|
21415
|
+
}
|
|
21416
|
+
return await logs({
|
|
21417
|
+
...filters,
|
|
21418
|
+
targetId,
|
|
21419
|
+
...(kind === 'network' ? { source: 'network' } : { problems: true }),
|
|
21420
|
+
signal: operation.signal,
|
|
21421
|
+
timeoutMs: operation.remaining(),
|
|
21422
|
+
});
|
|
21423
|
+
}
|
|
21424
|
+
finally {
|
|
21425
|
+
operation.dispose();
|
|
21426
|
+
}
|
|
21427
|
+
};
|
|
21428
|
+
const resource = async (name, options = {}) => {
|
|
21429
|
+
validateSelection(options);
|
|
21430
|
+
if (options.path !== undefined && (typeof options.path !== 'string' || !options.path || options.path.length > 1024))
|
|
21431
|
+
throw new DevHostError('INVALID_RESOURCE_PATH', 'path 必须是有界非空逻辑路径');
|
|
21432
|
+
if (options.maxBytes !== undefined &&
|
|
21433
|
+
(!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1 || options.maxBytes > DEV_SANDBOX_READ_MAX_BYTES))
|
|
21434
|
+
throw new DevHostError('INVALID_READ_LIMIT', 'maxBytes 必须是 1 至 16384 的整数');
|
|
21435
|
+
const operation = requestBudget({ ...options, timeoutMs: options.timeoutMs ?? 12_000 });
|
|
21436
|
+
try {
|
|
21437
|
+
const selected = await resolveSelection(options, { signal: operation.signal, timeoutMs: operation.remaining() });
|
|
21438
|
+
const instanceId = selected.instanceId;
|
|
21439
|
+
const value = await request(DEV_RESOURCE_PATH, { signal: operation.signal, timeoutMs: operation.remaining() }, {
|
|
21440
|
+
method: 'POST',
|
|
21441
|
+
body: JSON.stringify({
|
|
21442
|
+
instanceId,
|
|
21443
|
+
resource: name,
|
|
21444
|
+
...(options.path !== undefined ? { path: options.path } : {}),
|
|
21445
|
+
...(options.operation ? { operation: options.operation } : {}),
|
|
21446
|
+
...(options.maxBytes !== undefined ? { maxBytes: options.maxBytes } : {}),
|
|
21447
|
+
}),
|
|
21448
|
+
});
|
|
21449
|
+
check(value);
|
|
21450
|
+
if (value.instanceId !== instanceId || value.resource !== name)
|
|
21451
|
+
throw new DevHostError('DEV_PROTOCOL_INVALID', '资源结果不属于请求实例');
|
|
21452
|
+
if (selected.targetId !== undefined) {
|
|
21453
|
+
const snapshot = await inspect({ signal: operation.signal, timeoutMs: operation.remaining() });
|
|
21454
|
+
if (snapshot.targets.find((target) => target.targetId === selected.targetId)?.currentInstanceId !== instanceId)
|
|
21455
|
+
throw new DevHostError('RUNTIME_INSTANCE_CHANGED', `目标 ${selected.targetId} 的当前实例已变化,请重新检查后显式重试`);
|
|
21456
|
+
}
|
|
21457
|
+
return value;
|
|
21458
|
+
}
|
|
21459
|
+
finally {
|
|
21460
|
+
operation.dispose();
|
|
21461
|
+
}
|
|
21462
|
+
};
|
|
21463
|
+
const action = async (command, options = {}, data = {}) => request(PREVIEW_PATH, { ...options, timeoutMs: options.timeoutMs ?? 200_000 }, {
|
|
21464
|
+
method: 'POST',
|
|
21465
|
+
body: JSON.stringify({ ...data, command, sessionId: connection.record.sessionId, projectRoot: connection.record.projectRoot }),
|
|
21466
|
+
});
|
|
21467
|
+
return {
|
|
21468
|
+
id: connection.record.sessionId,
|
|
21469
|
+
projectRoot: connection.record.projectRoot,
|
|
21470
|
+
port: connection.record.port,
|
|
21471
|
+
inspect,
|
|
21472
|
+
logs,
|
|
21473
|
+
async waitForRuntime(options = {}) {
|
|
21474
|
+
validateSelection(options);
|
|
21475
|
+
const operation = requestBudget({ ...options, timeoutMs: options.timeoutMs ?? 30_000 });
|
|
21476
|
+
const followsTarget = options.instanceId === undefined;
|
|
21477
|
+
let targetId = options.targetId;
|
|
21478
|
+
let instanceId = options.instanceId;
|
|
21479
|
+
let last;
|
|
21480
|
+
try {
|
|
21481
|
+
while (true) {
|
|
21482
|
+
const snapshot = await inspect({ signal: operation.signal, timeoutMs: operation.remaining() });
|
|
21483
|
+
targetId ??= followsTarget ? (snapshot.primaryTargetId ?? undefined) : undefined;
|
|
21484
|
+
const target = targetId === undefined ? undefined : snapshot.targets.find((item) => item.targetId === targetId);
|
|
21485
|
+
if (targetId !== undefined && !target)
|
|
21486
|
+
throw new DevHostError('DEV_TARGET_NOT_FOUND', '所选目标已不可查询,请查看 dev inspect');
|
|
21487
|
+
if (followsTarget)
|
|
21488
|
+
instanceId ??= target?.currentInstanceId ?? undefined;
|
|
21489
|
+
const instance = instanceId ? snapshot.instances.find((item) => item.instanceId === instanceId) : null;
|
|
21490
|
+
last = { snapshot, target: target ?? (instance ? snapshot.targets.find(item => item.targetId === instance.targetId) : undefined), instance };
|
|
21491
|
+
if (!instanceId && target) {
|
|
21492
|
+
const lastAttempt = snapshot.instances.findLast((item) => item.targetId === target.targetId && item.ownerId === target.ownerId);
|
|
21493
|
+
if (lastAttempt?.state === 'failed' || lastAttempt?.state === 'closed')
|
|
21494
|
+
throw runtimeFailure(lastAttempt, snapshot);
|
|
21495
|
+
if (target.state === 'closed')
|
|
21496
|
+
throw new DevHostError('DEV_TARGET_CLOSED', `目标 ${target.targetId} 已关闭,请重新选择目标`);
|
|
21497
|
+
}
|
|
21498
|
+
if (instanceId && !instance)
|
|
21499
|
+
throw new DevHostError('RUNTIME_INSTANCE_NOT_FOUND', `实例 ${instanceId} 已不可查询,请检查 dev inspect`);
|
|
21500
|
+
if (instance?.state === 'failed')
|
|
21501
|
+
throw runtimeFailure(instance, snapshot);
|
|
21502
|
+
if (instanceId &&
|
|
21503
|
+
((followsTarget && target?.currentInstanceId !== instanceId) || (instance?.state === 'closed' && instance.reason === 'replaced')))
|
|
21504
|
+
throw new DevHostError('RUNTIME_INSTANCE_CHANGED', `实例 ${instanceId} 已被替换,请检查 dev inspect 后显式重试`);
|
|
21505
|
+
if (instance?.state === 'closed')
|
|
21506
|
+
throw runtimeFailure(instance, snapshot);
|
|
21507
|
+
if (instance?.state === 'ready' && !instance.documentVerifying && !instance.stale && (!followsTarget || (target?.state === 'attached' && !target.stale)))
|
|
21508
|
+
return instance;
|
|
21509
|
+
await delay(Math.min(100, operation.remaining()), operation.signal);
|
|
21510
|
+
}
|
|
21511
|
+
}
|
|
21512
|
+
catch (error) {
|
|
21513
|
+
if (!options.signal?.aborted && true && error instanceof DevHostError && error.code === 'DEV_TIMEOUT' && last) {
|
|
21514
|
+
if (last.target?.stale || last.instance?.stale)
|
|
21515
|
+
throw runtimeWaitFailure('HOST_UNRESPONSIVE', '等待期间 Host 心跳仍未恢复,请检查目标连接和 dev inspect', last);
|
|
21516
|
+
throw runtimeWaitFailure(last.instance?.documentVerifying ? 'RUNTIME_DOCUMENT_VERIFYING' : 'RUNTIME_NOT_READY', last.instance?.documentVerifying ? '等待期间当前文档未完成验证,请查看 Runtime 日志' : '等待期间 Runtime 未就绪,请查看实例状态和启动日志', last);
|
|
21517
|
+
}
|
|
21518
|
+
throw error;
|
|
21519
|
+
}
|
|
21520
|
+
finally {
|
|
21521
|
+
operation.dispose();
|
|
21522
|
+
}
|
|
21523
|
+
},
|
|
21524
|
+
preview: {
|
|
21525
|
+
connect(options = {}) {
|
|
21526
|
+
return connectPreviewBrowser(connection, {
|
|
21527
|
+
...options,
|
|
21528
|
+
signal: combinedSignal(options.signal, sessionSignal),
|
|
21529
|
+
});
|
|
21530
|
+
},
|
|
21531
|
+
open: (options) => action('open', options),
|
|
21532
|
+
select(options) {
|
|
21533
|
+
if (options.preset === undefined && options.orientation === undefined)
|
|
21534
|
+
throw new DevHostError('INVALID_SELECTION', '请提供 preset 或 orientation');
|
|
21535
|
+
if (options.preset === 'desktop' && options.orientation)
|
|
21536
|
+
throw new DevHostError('INVALID_SELECTION', '桌面方向由窗口决定');
|
|
21537
|
+
return action('select', options, { preset: options.preset, orientation: options.orientation });
|
|
21538
|
+
},
|
|
21539
|
+
reload: (options) => action('reload', options),
|
|
21540
|
+
capture(options = {}) {
|
|
21541
|
+
if (options.scope === 'workbench' && options.scale === 'device')
|
|
21542
|
+
throw new DevHostError('INVALID_CAPTURE', 'workbench 取景只支持 css');
|
|
21543
|
+
return action('capture', options, { scope: options.scope ?? 'device', scale: options.scale ?? 'css' });
|
|
21544
|
+
},
|
|
21545
|
+
},
|
|
21546
|
+
resources: {
|
|
21547
|
+
presentation: (options) => resource('presentation', options),
|
|
21548
|
+
storage: (options) => resource('storage', options),
|
|
21549
|
+
sandbox: (options) => resource('sandbox', { ...options, operation: 'list' }),
|
|
21550
|
+
sandboxRead: (options) => resource('sandbox', { ...options, operation: 'read', maxBytes: options.maxBytes ?? DEV_SANDBOX_READ_MAX_BYTES }),
|
|
21551
|
+
network: (filters = {}) => projection(filters, 'network'),
|
|
21552
|
+
problems: (filters = {}) => projection(filters, 'problems'),
|
|
21553
|
+
},
|
|
21554
|
+
};
|
|
21555
|
+
}
|
|
21556
|
+
function validateSelection(selection) {
|
|
21557
|
+
if (selection.targetId !== undefined && selection.instanceId !== undefined)
|
|
21558
|
+
throw new DevHostError('INVALID_TARGET_SELECTION', 'targetId 与 instanceId 不能同时提供');
|
|
21559
|
+
if (selection.targetId !== undefined && (typeof selection.targetId !== 'string' || !selection.targetId || selection.targetId.length > 200))
|
|
21560
|
+
throw new DevHostError('INVALID_TARGET', 'targetId 必须是有效目标 ID');
|
|
21561
|
+
if (selection.instanceId !== undefined && (typeof selection.instanceId !== 'string' || !/^[A-Za-z0-9_-]{1,100}$/.test(selection.instanceId)))
|
|
21562
|
+
throw new DevHostError('INVALID_INSTANCE', 'instanceId 必须是有效启动实例 ID');
|
|
21563
|
+
}
|
|
21564
|
+
function runtimeWaitFailure(code, message, last) {
|
|
21565
|
+
return Object.assign(new DevHostError(code, message), {
|
|
21566
|
+
targetId: last.target?.targetId ?? last.instance?.targetId ?? null,
|
|
21567
|
+
instanceId: last.instance?.instanceId ?? null,
|
|
21568
|
+
lastKnownState: last.instance?.state ?? null,
|
|
21569
|
+
lastSeenAt: last.target?.updatedAt ?? last.instance?.updatedAt ?? null,
|
|
21570
|
+
documentVerifying: last.instance?.documentVerifying === true,
|
|
21571
|
+
logs: { epoch: last.snapshot.epoch, through: last.snapshot.nextCursor },
|
|
21572
|
+
});
|
|
21573
|
+
}
|
|
21574
|
+
function runtimeFailure(instance, snapshot) {
|
|
21575
|
+
return Object.assign(new DevHostError(instance.error?.code ?? 'RUNTIME_CLOSED', instance.error?.message ?? instance.reason ?? 'Runtime 实例已结束'), {
|
|
21576
|
+
instanceId: instance.instanceId,
|
|
21577
|
+
diagnostic: instance.error,
|
|
21578
|
+
logs: { epoch: snapshot.epoch, after: Math.max(0, instance.startCursor - 1), through: instance.lastCursor },
|
|
21579
|
+
});
|
|
21580
|
+
}
|
|
21581
|
+
function logParameters(filters) {
|
|
21582
|
+
const params = new URLSearchParams();
|
|
21583
|
+
for (const key of ['after', 'limit', 'id', 'since']) {
|
|
21584
|
+
const value = filters[key];
|
|
21585
|
+
if (value === undefined)
|
|
21586
|
+
continue;
|
|
21587
|
+
const min = key === 'limit' || key === 'id' ? 1 : 0;
|
|
21588
|
+
if (!Number.isSafeInteger(value) || value < min || (key === 'limit' && value > 500))
|
|
21589
|
+
throw new DevHostError('INVALID_LOG_FILTER', `${key} 无效`);
|
|
21590
|
+
params.set(key, String(value));
|
|
21591
|
+
}
|
|
21592
|
+
if (filters.source !== undefined && !['app', 'sdk', 'runtime', 'host', 'network'].includes(filters.source))
|
|
21593
|
+
throw new DevHostError('INVALID_LOG_FILTER', 'source 无效');
|
|
21594
|
+
if (filters.level !== undefined && !['log', 'debug', 'info', 'warn', 'error'].includes(filters.level))
|
|
21595
|
+
throw new DevHostError('INVALID_LOG_FILTER', 'level 无效');
|
|
21596
|
+
if (filters.problems !== undefined) {
|
|
21597
|
+
if (typeof filters.problems !== 'boolean')
|
|
21598
|
+
throw new DevHostError('INVALID_LOG_FILTER', 'problems 无效');
|
|
21599
|
+
params.set('problems', String(filters.problems));
|
|
21600
|
+
}
|
|
21601
|
+
for (const key of ['targetId', 'instanceId', 'uploadSessionId', 'callId', 'phase', 'source', 'level', 'query']) {
|
|
21602
|
+
const value = filters[key];
|
|
21603
|
+
if (value !== undefined) {
|
|
21604
|
+
if (typeof value !== 'string' || value.length > 1024)
|
|
21605
|
+
throw new DevHostError('INVALID_LOG_FILTER', `${key} 无效`);
|
|
21606
|
+
params.set(key, value);
|
|
21607
|
+
}
|
|
21608
|
+
}
|
|
21609
|
+
return params;
|
|
21610
|
+
}
|
|
21611
|
+
function combinedSignal(signal, external) {
|
|
21612
|
+
return (signal ?? external);
|
|
21613
|
+
}
|
|
21614
|
+
function requestBudget(options, external) {
|
|
21615
|
+
const timeoutMs = options.timeoutMs ?? 5000;
|
|
21616
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647)
|
|
21617
|
+
throw new DevHostError('INVALID_TIMEOUT', 'timeoutMs 必须是有效的正整数毫秒数');
|
|
21618
|
+
const deadline = Date.now() + timeoutMs;
|
|
21619
|
+
const timeout = new AbortController();
|
|
21620
|
+
const signal = AbortSignal.any([timeout.signal, ...([]), ...(options.signal ? [options.signal] : [])]);
|
|
21621
|
+
signal.throwIfAborted();
|
|
21622
|
+
const timer = setTimeout(() => timeout.abort(new DevHostError('DEV_TIMEOUT', '开发工具请求超时,请用 dev inspect 查看实例与日志')), timeoutMs);
|
|
21623
|
+
return {
|
|
21624
|
+
signal,
|
|
21625
|
+
remaining() {
|
|
21626
|
+
if (Date.now() >= deadline)
|
|
21627
|
+
timeout.abort(new DevHostError('DEV_TIMEOUT', '开发工具请求超时,请用 dev inspect 查看实例与日志'));
|
|
21628
|
+
signal.throwIfAborted();
|
|
21629
|
+
return Math.max(1, deadline - Date.now());
|
|
21630
|
+
},
|
|
21631
|
+
dispose() {
|
|
21632
|
+
clearTimeout(timer);
|
|
21633
|
+
},
|
|
21634
|
+
};
|
|
21635
|
+
}
|
|
21636
|
+
function delay(ms, signal) {
|
|
21637
|
+
return new Promise((resolve, reject) => {
|
|
21638
|
+
const abort = () => {
|
|
21639
|
+
clearTimeout(timer);
|
|
21640
|
+
signal.removeEventListener('abort', abort);
|
|
21641
|
+
reject(signal.reason);
|
|
21642
|
+
};
|
|
21643
|
+
const timer = setTimeout(() => {
|
|
21644
|
+
signal.removeEventListener('abort', abort);
|
|
21645
|
+
resolve();
|
|
21646
|
+
}, ms);
|
|
21647
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
21648
|
+
if (signal.aborted)
|
|
21649
|
+
abort();
|
|
21650
|
+
});
|
|
21651
|
+
}
|
|
21652
|
+
|
|
21653
|
+
/** 本地工具共享 Node 会话语义,stdout 固定 JSON/NDJSON。 */
|
|
21654
|
+
function installDevToolCommands(dev) {
|
|
20383
21655
|
dev.enablePositionalOptions();
|
|
20384
21656
|
dev.parent?.enablePositionalOptions();
|
|
20385
|
-
dev
|
|
20386
|
-
.
|
|
20387
|
-
.
|
|
21657
|
+
dev
|
|
21658
|
+
.command('list')
|
|
21659
|
+
.description('列出当前用户启动的本机开发服务')
|
|
21660
|
+
.action(async (_options, command) => {
|
|
21661
|
+
readDevToolPort(command);
|
|
21662
|
+
writeDevResult({ schemaVersion: 1, sessions: await listDevHosts() });
|
|
21663
|
+
});
|
|
21664
|
+
dev
|
|
21665
|
+
.command('inspect')
|
|
21666
|
+
.description('读取开发会话、预览连接、当前实例及最近失败;不连接浏览器')
|
|
21667
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目')
|
|
20388
21668
|
.action(async (options, command) => {
|
|
20389
|
-
const
|
|
20390
|
-
|
|
20391
|
-
throw new Error('端口无效');
|
|
20392
|
-
const origin = `http://127.0.0.1:${port}`;
|
|
20393
|
-
const bootstrap = await (await fetch(origin + '/__hb_sdk_bootstrap__', { signal: AbortSignal.timeout(5000), redirect: 'error' })).json();
|
|
20394
|
-
const response = await fetch(origin + '/__hb_sdk__/sandbox', { method: 'POST', redirect: 'error', headers: { origin, 'content-type': 'application/json', 'x-hb-sdk-csrf': bootstrap.csrfToken }, body: JSON.stringify({ device: options.device, path: options.path }), signal: AbortSignal.timeout(12000) });
|
|
20395
|
-
if (!response.ok)
|
|
20396
|
-
throw new Error(`目录查询失败:HTTP ${response.status}`);
|
|
20397
|
-
process.stdout.write(JSON.stringify(await response.json()) + '\n');
|
|
21669
|
+
const connection = await connectCurrentDevHost(readDevToolPort(command, options.port));
|
|
21670
|
+
writeDevResult(await createDevSession(connection).inspect());
|
|
20398
21671
|
});
|
|
20399
|
-
|
|
20400
|
-
|
|
20401
|
-
|
|
20402
|
-
|
|
20403
|
-
|
|
20404
|
-
|
|
20405
|
-
|
|
20406
|
-
|
|
20407
|
-
|
|
20408
|
-
|
|
20409
|
-
|
|
20410
|
-
|
|
20411
|
-
|
|
20412
|
-
|
|
20413
|
-
|
|
20414
|
-
|
|
20415
|
-
|
|
20416
|
-
|
|
20417
|
-
|
|
20418
|
-
|
|
20419
|
-
|
|
20420
|
-
|
|
20421
|
-
|
|
20422
|
-
|
|
20423
|
-
|
|
20424
|
-
|
|
20425
|
-
|
|
20426
|
-
|
|
20427
|
-
|
|
20428
|
-
|
|
20429
|
-
|
|
20430
|
-
|
|
20431
|
-
|
|
20432
|
-
|
|
20433
|
-
|
|
20434
|
-
|
|
20435
|
-
|
|
20436
|
-
|
|
20437
|
-
|
|
20438
|
-
|
|
20439
|
-
|
|
20440
|
-
|
|
20441
|
-
|
|
21672
|
+
dev
|
|
21673
|
+
.command('uploads')
|
|
21674
|
+
.description('列出当前项目的日志上传会话与连接状态')
|
|
21675
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目')
|
|
21676
|
+
.action(async (options, command) => {
|
|
21677
|
+
const connection = await connectCurrentDevHost(readDevToolPort(command, options.port));
|
|
21678
|
+
const page = await createDevSession(connection).logs({ limit: 1 });
|
|
21679
|
+
writeDevResult({ schemaVersion: page.schemaVersion, sessionId: page.sessionId, epoch: page.epoch, uploadSessions: page.uploadSessions });
|
|
21680
|
+
});
|
|
21681
|
+
const sandbox = dev.command('sandbox').description('按实例只读访问实际 Host 沙箱');
|
|
21682
|
+
sandbox
|
|
21683
|
+
.command('list')
|
|
21684
|
+
.option('--target <id>', '读取目标当前实例;与 --instance 互斥')
|
|
21685
|
+
.option('--instance <id>', '启动实例 ID;默认主预览实例')
|
|
21686
|
+
.option('--path <path>', '逻辑目录', '.')
|
|
21687
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目')
|
|
21688
|
+
.action(async (options, command) => {
|
|
21689
|
+
const selection = readTargetSelection(options);
|
|
21690
|
+
const connection = await connectCurrentDevHost(readDevToolPort(command, options.port));
|
|
21691
|
+
writeDevResult(await createDevSession(connection).resources.sandbox({ ...selection, path: options.path }));
|
|
21692
|
+
});
|
|
21693
|
+
sandbox
|
|
21694
|
+
.command('read')
|
|
21695
|
+
.requiredOption('--path <path>', '逻辑文件路径')
|
|
21696
|
+
.option('--target <id>', '读取目标当前实例;与 --instance 互斥')
|
|
21697
|
+
.option('--instance <id>', '启动实例 ID;原生实例可从 dev inspect 获取')
|
|
21698
|
+
.option('--max-bytes <count>', '最多读取的字节数,1 至 16384;输出 base64', '16384')
|
|
21699
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目')
|
|
21700
|
+
.action(async (options, command) => {
|
|
21701
|
+
const selection = readTargetSelection(options);
|
|
21702
|
+
const maxBytes = finiteNumber(options.maxBytes, '读取上限', 1, 16384, true);
|
|
21703
|
+
const connection = await connectCurrentDevHost(readDevToolPort(command, options.port));
|
|
21704
|
+
writeDevResult(await createDevSession(connection).resources.sandboxRead({
|
|
21705
|
+
...selection,
|
|
21706
|
+
path: options.path,
|
|
21707
|
+
maxBytes,
|
|
21708
|
+
}));
|
|
21709
|
+
});
|
|
21710
|
+
dev
|
|
21711
|
+
.command('logs')
|
|
21712
|
+
.description('增量读取当前项目统一诊断事实')
|
|
21713
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目')
|
|
21714
|
+
.option('--upload <id>', '日志上传会话 ID')
|
|
21715
|
+
.option('--target <id>', '逻辑调试目标;日志查询其全部历史,与 --instance 互斥')
|
|
21716
|
+
.option('--instance <id>', '小程序启动实例 ID')
|
|
21717
|
+
.option('--level <level>', '日志级别')
|
|
21718
|
+
.option('--source <source>', '日志来源 app | sdk | runtime | host | network')
|
|
21719
|
+
.option('--query <text>', '搜索脱敏摘要')
|
|
21720
|
+
.option('--callId <id>', '关联 bridge/SDK 调用 ID')
|
|
21721
|
+
.option('--phase <phase>', '调用阶段,例如 client 或 host')
|
|
21722
|
+
.option('--id <id>', '读取服务端日志 ID')
|
|
21723
|
+
.option('--since <timestamp>', '源墙钟时间下界,毫秒')
|
|
21724
|
+
.option('--after <cursor>', '从服务端接收游标后继续读取', '0')
|
|
21725
|
+
.option('--limit <count>', '每页条数,1 至 500', '100')
|
|
21726
|
+
.option('--follow', '持续输出 NDJSON')
|
|
21727
|
+
.option('--duration <seconds>', '跟随时长,默认 60 秒', '60')
|
|
21728
|
+
.action(async (options, command) => {
|
|
21729
|
+
const port = readDevToolPort(command, options.port);
|
|
21730
|
+
if (!options.follow && command.getOptionValueSource('duration') === 'cli')
|
|
21731
|
+
throw new Error('--duration 需要与 --follow 一起使用');
|
|
21732
|
+
const duration = finiteNumber(options.duration, '跟随时长', Number.MIN_VALUE);
|
|
21733
|
+
const filters = {
|
|
21734
|
+
after: finiteNumber(options.after, '日志游标', 0, Number.MAX_SAFE_INTEGER, true),
|
|
21735
|
+
limit: finiteNumber(options.limit, '分页条数', 1, 500, true),
|
|
21736
|
+
...(options.since !== undefined ? { since: finiteNumber(options.since, '源墙钟时间', 0, Number.MAX_SAFE_INTEGER, true) } : {}),
|
|
21737
|
+
...(options.id !== undefined ? { id: finiteNumber(options.id, '日志 ID', 1, Number.MAX_SAFE_INTEGER, true) } : {}),
|
|
21738
|
+
...readTargetSelection(options),
|
|
21739
|
+
uploadSessionId: options.upload,
|
|
21740
|
+
callId: options.callId,
|
|
21741
|
+
phase: options.phase,
|
|
21742
|
+
query: options.query,
|
|
21743
|
+
level: options.level,
|
|
21744
|
+
source: options.source,
|
|
21745
|
+
};
|
|
21746
|
+
if (options.level && !['log', 'debug', 'info', 'warn', 'error'].includes(options.level))
|
|
21747
|
+
throw new Error('日志级别无效');
|
|
21748
|
+
if (options.source && !['app', 'sdk', 'runtime', 'host', 'network'].includes(options.source))
|
|
21749
|
+
throw new Error('日志来源无效');
|
|
21750
|
+
const connection = await connectCurrentDevHost(port);
|
|
21751
|
+
const session = createDevSession(connection);
|
|
21752
|
+
let epoch = '';
|
|
21753
|
+
const deadline = Date.now() + duration * 1000;
|
|
21754
|
+
do {
|
|
21755
|
+
const page = await session.logs(filters);
|
|
21756
|
+
// 服务身份固定;同一服务主动更新 epoch 时只显式重置游标,不迁移到另一个 dev。
|
|
21757
|
+
if (epoch && epoch !== page.epoch) {
|
|
21758
|
+
filters.after = 0;
|
|
20442
21759
|
epoch = page.epoch;
|
|
20443
|
-
|
|
20444
|
-
|
|
20445
|
-
|
|
20446
|
-
|
|
20447
|
-
|
|
20448
|
-
|
|
20449
|
-
|
|
21760
|
+
continue;
|
|
21761
|
+
}
|
|
21762
|
+
epoch = page.epoch;
|
|
21763
|
+
writeDevResult(page);
|
|
21764
|
+
filters.after = page.nextCursor;
|
|
21765
|
+
if (!options.follow)
|
|
21766
|
+
break;
|
|
21767
|
+
if (!page.hasMore)
|
|
21768
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(1000, Math.max(0, deadline - Date.now()))));
|
|
21769
|
+
} while (Date.now() < deadline);
|
|
21770
|
+
});
|
|
21771
|
+
}
|
|
21772
|
+
function finiteNumber(value, label, min, max = Number.MAX_SAFE_INTEGER, integer = false) {
|
|
21773
|
+
const number = Number(value);
|
|
21774
|
+
if (!value.trim() || !Number.isFinite(number) || number < min || number > max || (integer && !Number.isInteger(number)))
|
|
21775
|
+
throw new Error(`${label}无效`);
|
|
21776
|
+
return number;
|
|
21777
|
+
}
|
|
21778
|
+
function readTargetSelection(options) {
|
|
21779
|
+
if (options.target !== undefined && options.instance !== undefined)
|
|
21780
|
+
throw new Error('--target 与 --instance 不能同时提供');
|
|
21781
|
+
return { targetId: options.target, instanceId: options.instance };
|
|
21782
|
+
}
|
|
21783
|
+
|
|
21784
|
+
/**
|
|
21785
|
+
* 桌面预览的伪设备 id。
|
|
21786
|
+
*
|
|
21787
|
+
* 它不是固定预设:真实尺寸由 `package.json#heybox.window` 声明与用户记忆决定,
|
|
21788
|
+
* 所以不放进 `DEVICE_PRESETS`,避免被 `resolveDevicePreset` 当成手机机型。
|
|
21789
|
+
*/
|
|
21790
|
+
const DESKTOP_DEVICE_ID = 'desktop';
|
|
21791
|
+
const IPHONE_VIEWPORT = { width: 440, height: 956 };
|
|
21792
|
+
const IPHONE_SCREEN_RECT = { top: 1.32, right: 3.4, bottom: 1.32, left: 3.4 };
|
|
21793
|
+
const PIXEL_VIEWPORT = { width: 410, height: 914 };
|
|
21794
|
+
const PIXEL_SCREEN_RECT = { top: 2.05, right: 4.8, bottom: 1.8, left: 4.1 };
|
|
21795
|
+
function calibrateFrame(viewport, screenRect, asset) {
|
|
21796
|
+
const frameWidth = viewport.width / (1 - (screenRect.left + screenRect.right) / 100);
|
|
21797
|
+
const frameHeight = viewport.height / (1 - (screenRect.top + screenRect.bottom) / 100);
|
|
21798
|
+
const assetRadius = asset.width * asset.radiusWidthRatio;
|
|
21799
|
+
return {
|
|
21800
|
+
frameWidth,
|
|
21801
|
+
frameHeight,
|
|
21802
|
+
frameAssetWidth: asset.width,
|
|
21803
|
+
frameAssetHeight: asset.height,
|
|
21804
|
+
screenRadius: {
|
|
21805
|
+
x: assetRadius * (frameWidth / asset.width),
|
|
21806
|
+
y: assetRadius * (frameHeight / asset.height),
|
|
21807
|
+
},
|
|
21808
|
+
};
|
|
21809
|
+
}
|
|
21810
|
+
const DEVICE_PRESETS = [
|
|
21811
|
+
{
|
|
21812
|
+
id: 'iphone-16-pro-max',
|
|
21813
|
+
label: 'iPhone 16 Pro Max',
|
|
21814
|
+
screenWidth: IPHONE_VIEWPORT.width,
|
|
21815
|
+
screenHeight: IPHONE_VIEWPORT.height,
|
|
21816
|
+
...calibrateFrame(IPHONE_VIEWPORT, IPHONE_SCREEN_RECT, {
|
|
21817
|
+
width: 415,
|
|
21818
|
+
height: 843,
|
|
21819
|
+
radiusWidthRatio: 0.122126436781609,
|
|
21820
|
+
}),
|
|
21821
|
+
maxPresentationScale: 1,
|
|
21822
|
+
pixelRatio: 3,
|
|
21823
|
+
statusBarHeight: 55,
|
|
21824
|
+
safeAreaInsets: { top: 55, right: 0, bottom: 34, left: 0 },
|
|
21825
|
+
landscape: { statusBarHeight: 0, safeAreaInsets: { top: 0, right: 62, bottom: 21, left: 62 } },
|
|
21826
|
+
screenRect: IPHONE_SCREEN_RECT,
|
|
21827
|
+
toolbarLeft: 53.67,
|
|
21828
|
+
platform: 'ios',
|
|
21829
|
+
},
|
|
21830
|
+
{
|
|
21831
|
+
id: 'pixel-9-pro',
|
|
21832
|
+
label: 'Pixel 9 Pro',
|
|
21833
|
+
screenWidth: PIXEL_VIEWPORT.width,
|
|
21834
|
+
screenHeight: PIXEL_VIEWPORT.height,
|
|
21835
|
+
...calibrateFrame(PIXEL_VIEWPORT, PIXEL_SCREEN_RECT, {
|
|
21836
|
+
width: 353,
|
|
21837
|
+
height: 745,
|
|
21838
|
+
radiusWidthRatio: 0.126666666666667,
|
|
21839
|
+
}),
|
|
21840
|
+
maxPresentationScale: 1,
|
|
21841
|
+
pixelRatio: 2.625,
|
|
21842
|
+
statusBarHeight: 50,
|
|
21843
|
+
safeAreaInsets: { top: 50, right: 0, bottom: 24, left: 0 },
|
|
21844
|
+
landscape: { statusBarHeight: 0, safeAreaInsets: { top: 0, right: 0, bottom: 24, left: 50 } },
|
|
21845
|
+
screenRect: PIXEL_SCREEN_RECT,
|
|
21846
|
+
toolbarLeft: 44.69,
|
|
21847
|
+
platform: 'android',
|
|
21848
|
+
},
|
|
21849
|
+
];
|
|
21850
|
+
/** Agent 可选择的预览模式;桌面尺寸取自当前窗口,不伪装成固定机型尺寸。 */
|
|
21851
|
+
function listPreviewSelections() {
|
|
21852
|
+
return [
|
|
21853
|
+
...DEVICE_PRESETS.map(({ id, label, screenWidth, screenHeight, platform }) => ({
|
|
21854
|
+
id,
|
|
21855
|
+
label,
|
|
21856
|
+
screenWidth,
|
|
21857
|
+
screenHeight,
|
|
21858
|
+
platform,
|
|
21859
|
+
dynamic: false,
|
|
21860
|
+
})),
|
|
21861
|
+
{ id: DESKTOP_DEVICE_ID, label: '桌面', screenWidth: null, screenHeight: null, platform: 'desktop', dynamic: true },
|
|
21862
|
+
];
|
|
21863
|
+
}
|
|
21864
|
+
|
|
21865
|
+
function installDevPreviewCommands(dev) {
|
|
21866
|
+
dev.enablePositionalOptions();
|
|
21867
|
+
dev.parent?.enablePositionalOptions();
|
|
21868
|
+
const preview = dev.command('preview').description('共享浏览器预览、设备选择与截图;固定 JSON 输出');
|
|
21869
|
+
preview
|
|
21870
|
+
.command('presets')
|
|
21871
|
+
.description('列出手机与桌面预设,无需启动服务或下载依赖')
|
|
21872
|
+
.action((_options, command) => {
|
|
21873
|
+
readDevToolPort(command);
|
|
21874
|
+
writeDevResult({ presets: listPreviewSelections() });
|
|
21875
|
+
});
|
|
21876
|
+
preview
|
|
21877
|
+
.command('setup')
|
|
21878
|
+
.description('预安装固定版本 playwright-core 到用户缓存,不下载浏览器')
|
|
21879
|
+
.action(async (_options, command) => {
|
|
21880
|
+
readDevToolPort(command);
|
|
21881
|
+
await loadPreviewPlaywright({ progress: (message) => process.stderr.write(`[hb-sdk] ${message}\n`) });
|
|
21882
|
+
writeDevResult({ version: PREVIEW_PLAYWRIGHT_VERSION, directory: previewDependencyDirectory(), ready: true });
|
|
21883
|
+
});
|
|
21884
|
+
for (const command of ['open', 'select', 'reload', 'capture']) {
|
|
21885
|
+
const item = preview
|
|
21886
|
+
.command(command)
|
|
21887
|
+
.description({
|
|
21888
|
+
open: '打开或复用本机共享窗口,不下载依赖',
|
|
21889
|
+
select: '选择机型或方向,等待预览布局完成',
|
|
21890
|
+
reload: '按调试台重启行为重新加载小程序 Runtime',
|
|
21891
|
+
capture: '截取当前画面,默认包含外框和宿主弹层',
|
|
21892
|
+
}[command])
|
|
21893
|
+
.option('--port <port>', '显式指定调试台;默认发现当前项目');
|
|
21894
|
+
if (command === 'select') {
|
|
21895
|
+
item
|
|
21896
|
+
.addOption(new Option('--preset <id>', '预设 ID').choices(listPreviewSelections().map((preset) => preset.id)))
|
|
21897
|
+
.addOption(new Option('--orientation <orientation>', '手机预览方向').choices(['portrait', 'landscape']));
|
|
21898
|
+
}
|
|
21899
|
+
if (command === 'capture') {
|
|
21900
|
+
item
|
|
21901
|
+
.addOption(new Option('--scope <scope>', '截图取景范围').choices(['device', 'screen', 'app', 'workbench']).default('device'))
|
|
21902
|
+
.addOption(new Option('--scale <scale>', 'css 截当前画面;device 按原始布局和浏览器 DPR 重绘,会触发可见性通知')
|
|
21903
|
+
.choices(['css', 'device'])
|
|
21904
|
+
.default('css'))
|
|
21905
|
+
.option('--output <path>', 'PNG 输出路径;默认在当前目录生成文件');
|
|
21906
|
+
}
|
|
21907
|
+
item.action(async (options, cli) => {
|
|
21908
|
+
const port = readDevToolPort(cli, options.port);
|
|
21909
|
+
if (command === 'select' && options.preset === undefined && options.orientation === undefined)
|
|
21910
|
+
throw new Error('请提供 --preset 或 --orientation');
|
|
21911
|
+
if (command === 'select' && options.preset === 'desktop' && options.orientation)
|
|
21912
|
+
throw new Error('桌面方向由窗口尺寸决定,不能指定 --orientation');
|
|
21913
|
+
if (options.scope === 'workbench' && options.scale === 'device')
|
|
21914
|
+
throw new Error('workbench 是当前调试台视图,请使用 --scale css');
|
|
21915
|
+
const connection = await connectCurrentDevHost(port);
|
|
21916
|
+
const session = createDevSession(connection);
|
|
21917
|
+
const result = command === 'select'
|
|
21918
|
+
? await session.preview.select({ preset: options.preset, orientation: options.orientation })
|
|
21919
|
+
: command === 'capture'
|
|
21920
|
+
? await session.preview.capture({ scope: options.scope, scale: options.scale })
|
|
21921
|
+
: await session.preview[command]();
|
|
21922
|
+
if (command === 'capture') {
|
|
21923
|
+
const image = result.image;
|
|
21924
|
+
if (!image || typeof image.base64 !== 'string')
|
|
21925
|
+
throw new Error('调试台没有返回截图');
|
|
21926
|
+
const target = path.resolve(options.output ?? `hb-preview-${Date.now()}.png`);
|
|
21927
|
+
await fs$2.mkdir(path.dirname(target), { recursive: true });
|
|
21928
|
+
await fs$2.writeFile(target, Buffer.from(image.base64, 'base64'), { flag: 'wx' });
|
|
21929
|
+
const { base64: _base64, ...metadata } = image;
|
|
21930
|
+
result.image = { ...metadata, path: target };
|
|
21931
|
+
}
|
|
21932
|
+
writeDevResult(result);
|
|
20450
21933
|
});
|
|
20451
21934
|
}
|
|
20452
21935
|
}
|
|
20453
21936
|
|
|
20454
21937
|
const CLI_VERSION_PLACEHOLDER = ['__HB', 'SDK', 'CLI', 'VERSION__'].join('_');
|
|
20455
|
-
const BUILT_CLI_VERSION = '0.9.6-alpha.
|
|
21938
|
+
const BUILT_CLI_VERSION = '0.9.6-alpha.6';
|
|
20456
21939
|
const PACKAGE_JSON_CANDIDATES$1 = [
|
|
20457
21940
|
path.resolve(__dirname, '..', '..', 'package.json'),
|
|
20458
21941
|
path.resolve(__dirname, '..', 'package.json'),
|
|
@@ -21404,7 +22887,7 @@ function createCliProgram(overrides = {}) {
|
|
|
21404
22887
|
.exitOverride();
|
|
21405
22888
|
installVersionUpdateReminder(program, handlers.printUpdateReminder, resolveLogger);
|
|
21406
22889
|
program.hook('preAction', async (_program, command) => {
|
|
21407
|
-
if (readCommandOptionsWithAncestors(command).json)
|
|
22890
|
+
if (readCommandOptionsWithAncestors(command).json || isDevToolCommand(command))
|
|
21408
22891
|
return;
|
|
21409
22892
|
try {
|
|
21410
22893
|
await handlers.printReleaseHighlight({ logger: resolveLogger(command) });
|
|
@@ -21422,6 +22905,8 @@ function createCliProgram(overrides = {}) {
|
|
|
21422
22905
|
addVerboseOption(program
|
|
21423
22906
|
.command('dev')
|
|
21424
22907
|
.description('启动当前小程序项目的 Vite 开发服务器和浏览器调试页服务')
|
|
22908
|
+
.addOption(new Option('--browser <browser>', '预览使用的本机浏览器').choices(['chrome', 'edge']))
|
|
22909
|
+
.addOption(new Option('--browser-mode <mode>', '默认 auto:优先请求日常浏览器授权后回退;isolated 直接使用临时独立环境').choices(['auto', 'isolated']))
|
|
21425
22910
|
.option('--port <port>', '小程序开发服务器端口', parsePositivePort)
|
|
21426
22911
|
.option('--browser-dev-host-port <port>', '浏览器调试页服务端口', parsePositivePort)
|
|
21427
22912
|
.option('--no-open', '不自动打开浏览器调试页')
|
|
@@ -21430,7 +22915,8 @@ function createCliProgram(overrides = {}) {
|
|
|
21430
22915
|
const logger = resolveLogger(command);
|
|
21431
22916
|
await handlers.runDevCommand(options, { logger });
|
|
21432
22917
|
}, handlers.printUpdateReminder, resolveLogger));
|
|
21433
|
-
|
|
22918
|
+
installDevToolCommands(program.commands.find(command => command.name() === 'dev'));
|
|
22919
|
+
installDevPreviewCommands(program.commands.find(command => command.name() === 'dev'));
|
|
21434
22920
|
addVerboseOption(program.command('build').description('构建当前小程序项目')
|
|
21435
22921
|
.option('--env <name>', '加载项目根下 .env.<name> 预设并作为 Vite mode')
|
|
21436
22922
|
// 根程序开启位置化解析后,子命令必须自己声明同名选项才能拿到它;这里声明但不展示,
|
|
@@ -21718,39 +23204,39 @@ function createCommandLoggerResolver(options) {
|
|
|
21718
23204
|
};
|
|
21719
23205
|
}
|
|
21720
23206
|
const defaultClearLoginStatus = async (...args) => {
|
|
21721
|
-
const { clearLoginStatus } = await Promise.resolve().then(function () { return require('./login-
|
|
23207
|
+
const { clearLoginStatus } = await Promise.resolve().then(function () { return require('./login-DvKnuA5F.cjs'); });
|
|
21722
23208
|
return clearLoginStatus(...args);
|
|
21723
23209
|
};
|
|
21724
23210
|
const defaultLoginToHeybox = async (...args) => {
|
|
21725
|
-
const { loginToHeybox } = await Promise.resolve().then(function () { return require('./login-
|
|
23211
|
+
const { loginToHeybox } = await Promise.resolve().then(function () { return require('./login-DvKnuA5F.cjs'); });
|
|
21726
23212
|
return loginToHeybox(...args);
|
|
21727
23213
|
};
|
|
21728
23214
|
const defaultPrintLoginStatus = async (...args) => {
|
|
21729
|
-
const { printLoginStatus } = await Promise.resolve().then(function () { return require('./login-
|
|
23215
|
+
const { printLoginStatus } = await Promise.resolve().then(function () { return require('./login-DvKnuA5F.cjs'); });
|
|
21730
23216
|
return printLoginStatus(...args);
|
|
21731
23217
|
};
|
|
21732
23218
|
const defaultRunBuildCommand = async (...args) => {
|
|
21733
|
-
const { runBuildCommand } = await Promise.resolve().then(function () { return require('./build-
|
|
23219
|
+
const { runBuildCommand } = await Promise.resolve().then(function () { return require('./build-C4vRkpqF.cjs'); });
|
|
21734
23220
|
return runBuildCommand(...args);
|
|
21735
23221
|
};
|
|
21736
23222
|
const defaultRunCreateCommand = async (...args) => {
|
|
21737
|
-
const { runCreateCommand } = await Promise.resolve().then(function () { return require('./create-
|
|
23223
|
+
const { runCreateCommand } = await Promise.resolve().then(function () { return require('./create-C4CXYcaO.cjs'); });
|
|
21738
23224
|
return runCreateCommand(...args);
|
|
21739
23225
|
};
|
|
21740
23226
|
const defaultRunDevCommand = async (...args) => {
|
|
21741
|
-
const { runDevCommand } = await Promise.resolve().then(function () { return require('./dev-
|
|
23227
|
+
const { runDevCommand } = await Promise.resolve().then(function () { return require('./dev-Cs1e2PBR.cjs'); }).then(function (n) { return n.dev; });
|
|
21742
23228
|
return runDevCommand(...args);
|
|
21743
23229
|
};
|
|
21744
23230
|
const defaultRunDoctorCommand = async (...args) => {
|
|
21745
|
-
const { runDoctorCommand } = await Promise.resolve().then(function () { return require('./doctor-
|
|
23231
|
+
const { runDoctorCommand } = await Promise.resolve().then(function () { return require('./doctor-CTE-ykJW.cjs'); });
|
|
21746
23232
|
return runDoctorCommand(...args);
|
|
21747
23233
|
};
|
|
21748
23234
|
const defaultRunSkillInstallCommand = async (...args) => {
|
|
21749
|
-
const { runSkillInstallCommand } = await Promise.resolve().then(function () { return require('./skill-
|
|
23235
|
+
const { runSkillInstallCommand } = await Promise.resolve().then(function () { return require('./skill-Dz8sjBhC.cjs'); });
|
|
21750
23236
|
return runSkillInstallCommand(...args);
|
|
21751
23237
|
};
|
|
21752
23238
|
const defaultRunRemoteCommand = async (...args) => {
|
|
21753
|
-
const { runRemoteCommand } = await Promise.resolve().then(function () { return require('./remote-
|
|
23239
|
+
const { runRemoteCommand } = await Promise.resolve().then(function () { return require('./remote-g9MP_ZKJ.cjs'); });
|
|
21754
23240
|
return runRemoteCommand(...args);
|
|
21755
23241
|
};
|
|
21756
23242
|
function resolveStandaloneLogger(options, verbose) {
|
|
@@ -21771,6 +23257,14 @@ function readCommandOptionsWithAncestors(command) {
|
|
|
21771
23257
|
}
|
|
21772
23258
|
return Object.assign({}, ...chain.reverse().map((item) => item.opts()));
|
|
21773
23259
|
}
|
|
23260
|
+
/** dev 工具固定机器输出,即使由交互终端调用也不能弹出启动公告。 */
|
|
23261
|
+
function isDevToolCommand(command) {
|
|
23262
|
+
for (let parent = command.parent; parent; parent = parent.parent) {
|
|
23263
|
+
if (parent.name() === 'dev')
|
|
23264
|
+
return true;
|
|
23265
|
+
}
|
|
23266
|
+
return false;
|
|
23267
|
+
}
|
|
21774
23268
|
function installVersionUpdateReminder(program, printUpdateReminder, resolveLogger) {
|
|
21775
23269
|
const parseAsync = program.parseAsync.bind(program);
|
|
21776
23270
|
program.parseAsync = (async (...args) => {
|
|
@@ -21842,16 +23336,26 @@ function parseNonNegativeInteger(value) {
|
|
|
21842
23336
|
return parsed;
|
|
21843
23337
|
}
|
|
21844
23338
|
const defaultRunGameSearchCommand = async (...args) => {
|
|
21845
|
-
const { runGameSearchCommand } = await Promise.resolve().then(function () { return require('./games-
|
|
23339
|
+
const { runGameSearchCommand } = await Promise.resolve().then(function () { return require('./games-Bp5mp79Z.cjs'); });
|
|
21846
23340
|
return runGameSearchCommand(...args);
|
|
21847
23341
|
};
|
|
21848
23342
|
|
|
21849
23343
|
exports.CliError = CliError;
|
|
21850
23344
|
exports.DEPLOY_LOCKED_MESSAGE = DEPLOY_LOCKED_MESSAGE;
|
|
23345
|
+
exports.DESKTOP_DEVICE_ID = DESKTOP_DEVICE_ID;
|
|
23346
|
+
exports.DEVICE_PRESETS = DEVICE_PRESETS;
|
|
23347
|
+
exports.DEV_DIAGNOSTICS_PATH = DEV_DIAGNOSTICS_PATH;
|
|
23348
|
+
exports.DEV_DIAGNOSTICS_SCHEMA_VERSION = DEV_DIAGNOSTICS_SCHEMA_VERSION;
|
|
23349
|
+
exports.DEV_PRESENTATION_MAX_INTERACTIONS = DEV_PRESENTATION_MAX_INTERACTIONS;
|
|
23350
|
+
exports.DEV_RESOURCE_PATH = DEV_RESOURCE_PATH;
|
|
23351
|
+
exports.DEV_SANDBOX_READ_MAX_BYTES = DEV_SANDBOX_READ_MAX_BYTES;
|
|
21851
23352
|
exports.HB_SDK_PACKAGE_NAME = HB_SDK_PACKAGE_NAME;
|
|
21852
23353
|
exports.HB_SDK_SKILL_NAME = HB_SDK_SKILL_NAME;
|
|
23354
|
+
exports.PREVIEW_SELECTORS = PREVIEW_SELECTORS;
|
|
21853
23355
|
exports.acquireDeployLock = acquireDeployLock;
|
|
23356
|
+
exports.acquirePreviewFocus = acquirePreviewFocus;
|
|
21854
23357
|
exports.applyMiniProgramServiceTagIfNeeded = applyMiniProgramServiceTagIfNeeded;
|
|
23358
|
+
exports.awaitWithSignal = awaitWithSignal;
|
|
21855
23359
|
exports.clearHeyboxAuthSession = clearHeyboxAuthSession;
|
|
21856
23360
|
exports.commonjsGlobal = commonjsGlobal;
|
|
21857
23361
|
exports.createCliLogger = createCliLogger;
|
|
@@ -21862,11 +23366,18 @@ exports.createHeyboxAuthSession = createHeyboxAuthSession;
|
|
|
21862
23366
|
exports.createHeyboxOpenPlatformRequestContext = createHeyboxOpenPlatformRequestContext;
|
|
21863
23367
|
exports.createSkillContentHash = createSkillContentHash;
|
|
21864
23368
|
exports.envPaths = envPaths;
|
|
23369
|
+
exports.findPreviewPage = findPreviewPage;
|
|
23370
|
+
exports.findProjectRoot = findProjectRoot;
|
|
21865
23371
|
exports.formatCliRateLimitHint = formatCliRateLimitHint;
|
|
21866
23372
|
exports.getAuthCacheFilePath = getAuthCacheFilePath;
|
|
21867
23373
|
exports.getCDNUploadInfo = getCDNUploadInfo;
|
|
21868
23374
|
exports.getCDNUploadToken = getCDNUploadToken;
|
|
21869
23375
|
exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
|
|
23376
|
+
exports.getPreviewPlaywrightStatus = getPreviewPlaywrightStatus;
|
|
23377
|
+
exports.isPreviewDocumentUrl = isPreviewDocumentUrl;
|
|
23378
|
+
exports.isRecord = isRecord$1;
|
|
23379
|
+
exports.listPreviewSelections = listPreviewSelections;
|
|
23380
|
+
exports.loadPreviewPlaywright = loadPreviewPlaywright;
|
|
21870
23381
|
exports.postCDNUploadCallback = postCDNUploadCallback;
|
|
21871
23382
|
exports.printRateLimitUpgradeHint = printRateLimitUpgradeHint;
|
|
21872
23383
|
exports.readCliRateLimitState = readCliRateLimitState;
|
|
@@ -21875,6 +23386,7 @@ exports.readHeyboxApiEnvelope = readHeyboxApiEnvelope;
|
|
|
21875
23386
|
exports.readHeyboxAuthSession = readHeyboxAuthSession;
|
|
21876
23387
|
exports.readRedactedErrorMessage = readRedactedErrorMessage;
|
|
21877
23388
|
exports.readRedactedHeyboxAuthStatus = readRedactedHeyboxAuthStatus;
|
|
23389
|
+
exports.registerDevHost = registerDevHost;
|
|
21878
23390
|
exports.requireEnvPaths = requireEnvPaths;
|
|
21879
23391
|
exports.requireHeyboxAuthSession = requireHeyboxAuthSession;
|
|
21880
23392
|
exports.requireInherits = requireInherits;
|
|
@@ -21884,8 +23396,10 @@ exports.requireSemver = requireSemver;
|
|
|
21884
23396
|
exports.resolveHeyboxApiBaseUrl = resolveHeyboxApiBaseUrl;
|
|
21885
23397
|
exports.resolveHeyboxLoginBaseUrl = resolveHeyboxLoginBaseUrl;
|
|
21886
23398
|
exports.resolveHeyboxOpenPlatformBaseUrl = resolveHeyboxOpenPlatformBaseUrl;
|
|
23399
|
+
exports.resolveHeyboxRylaiServiceTag = resolveHeyboxRylaiServiceTag;
|
|
21887
23400
|
exports.runCli = runCli;
|
|
21888
23401
|
exports.semverExports = semverExports;
|
|
21889
23402
|
exports.setSelectedDeveloperEntitySnapshot = setSelectedDeveloperEntitySnapshot;
|
|
23403
|
+
exports.waitBounded = waitBounded;
|
|
21890
23404
|
exports.withDeployLock = withDeployLock;
|
|
21891
23405
|
exports.writeHeyboxAuthSession = writeHeyboxAuthSession;
|