@heybox/hb-sdk 0.9.6-alpha.5 → 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 +25 -5
- package/README.md +35 -563
- package/dist/cli-chunks/{artifact-DVC4uf_d.cjs → artifact-BZZtedxB.cjs} +3 -3
- package/dist/cli-chunks/{build-Cnbra2Uh.cjs → build-C4vRkpqF.cjs} +8 -6
- package/dist/cli-chunks/{create-BA6LJaSN.cjs → create-C4CXYcaO.cjs} +3 -1
- package/dist/cli-chunks/{dev-DhunXM74.cjs → dev-Cs1e2PBR.cjs} +8957 -366
- package/dist/cli-chunks/{dev-context-ChFPpG-d.cjs → dev-context-DkUPIPMO.cjs} +2 -2
- package/dist/cli-chunks/{doctor-of3bxqi4.cjs → doctor-CTE-ykJW.cjs} +3 -1
- package/dist/cli-chunks/{games-Cal1suXc.cjs → games-Bp5mp79Z.cjs} +3 -1
- package/dist/cli-chunks/{index-D-tz0KHY.cjs → index-Bnbj-tOs.cjs} +1618 -105
- package/dist/cli-chunks/{index-HKZRLLPE.cjs → index-Yef7fLOV.cjs} +1 -1
- package/dist/cli-chunks/index.esm-Cb7A6DlM.cjs +154 -0
- package/dist/cli-chunks/{login-Zl2mfKS3.cjs → login-DvKnuA5F.cjs} +3 -3
- package/dist/cli-chunks/{project-vite-DEBchdPu.cjs → project-vite-DdNQujlo.cjs} +3 -18
- package/dist/cli-chunks/{remote-CRhsafjv.cjs → remote-g9MP_ZKJ.cjs} +8 -20
- package/dist/cli-chunks/{runtime-permission-env-B2j6D1ts.cjs → runtime-permission-env-uu3dZhcm.cjs} +2 -2
- package/dist/cli-chunks/{skill-O1q_ccfW.cjs → skill-Dz8sjBhC.cjs} +3 -2
- package/dist/cli-chunks/{version-BOBr2N1h.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 +24 -11
- 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-BEoQF0yq.cjs +0 -5217
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-CTLTrYRi.js +0 -103
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-B8Nuahot.js +0 -6
- package/dist/devtools/browser-dev-host/assets/index-DkQhQiKD.js +0 -567
- package/dist/devtools/browser-dev-host/assets/index-QPl84u9f.css +0 -1
- package/docs/runtime-host-migration.md +0 -128
package/dist/vite.esm.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
3
|
import { createRequire, builtinModules } from 'node:module';
|
|
3
4
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
4
5
|
import { lstatSync, readFileSync, mkdirSync, writeFileSync, realpathSync, existsSync, constants as constants$1, readdirSync, readlinkSync, renameSync, rmSync, unwatchFile, createReadStream, watchFile, mkdtempSync, chmodSync } from 'node:fs';
|
|
@@ -10,7 +11,6 @@ import { readFile, mkdir, realpath, writeFile, stat, open } from 'node:fs/promis
|
|
|
10
11
|
import sharp from 'sharp';
|
|
11
12
|
import { tmpdir, platform, arch } from 'node:os';
|
|
12
13
|
import { inflateRawSync } from 'node:zlib';
|
|
13
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
14
14
|
|
|
15
15
|
/** 根据当前项目声明或实际版本 Manifest 检查资料完整性,不联网、不修改输入。 */
|
|
16
16
|
function getMiniappMetadataWarnings(metadata) {
|
|
@@ -450,7 +450,7 @@ const allowsEval = /* @__PURE__*/ cached(() => {
|
|
|
450
450
|
return false;
|
|
451
451
|
}
|
|
452
452
|
});
|
|
453
|
-
function isPlainObject(o) {
|
|
453
|
+
function isPlainObject$1(o) {
|
|
454
454
|
if (isObject(o) === false)
|
|
455
455
|
return false;
|
|
456
456
|
// modified constructor
|
|
@@ -470,7 +470,7 @@ function isPlainObject(o) {
|
|
|
470
470
|
return true;
|
|
471
471
|
}
|
|
472
472
|
function shallowClone(o) {
|
|
473
|
-
if (isPlainObject(o))
|
|
473
|
+
if (isPlainObject$1(o))
|
|
474
474
|
return { ...o };
|
|
475
475
|
if (Array.isArray(o))
|
|
476
476
|
return [...o];
|
|
@@ -570,7 +570,7 @@ function omit(schema, mask) {
|
|
|
570
570
|
return clone(schema, def);
|
|
571
571
|
}
|
|
572
572
|
function extend(schema, shape) {
|
|
573
|
-
if (!isPlainObject(shape)) {
|
|
573
|
+
if (!isPlainObject$1(shape)) {
|
|
574
574
|
throw new Error("Invalid input to extend: expected a plain object");
|
|
575
575
|
}
|
|
576
576
|
const checks = schema._zod.def.checks;
|
|
@@ -595,7 +595,7 @@ function extend(schema, shape) {
|
|
|
595
595
|
return clone(schema, def);
|
|
596
596
|
}
|
|
597
597
|
function safeExtend(schema, shape) {
|
|
598
|
-
if (!isPlainObject(shape)) {
|
|
598
|
+
if (!isPlainObject$1(shape)) {
|
|
599
599
|
throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
600
600
|
}
|
|
601
601
|
const def = mergeDefs(schema._zod.def, {
|
|
@@ -2501,7 +2501,7 @@ function mergeValues(a, b) {
|
|
|
2501
2501
|
if (a instanceof Date && b instanceof Date && +a === +b) {
|
|
2502
2502
|
return { valid: true, data: a };
|
|
2503
2503
|
}
|
|
2504
|
-
if (isPlainObject(a) && isPlainObject(b)) {
|
|
2504
|
+
if (isPlainObject$1(a) && isPlainObject$1(b)) {
|
|
2505
2505
|
const bKeys = Object.keys(b);
|
|
2506
2506
|
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
2507
2507
|
const newObj = { ...a, ...b };
|
|
@@ -2585,7 +2585,7 @@ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
|
|
|
2585
2585
|
$ZodType.init(inst, def);
|
|
2586
2586
|
inst._zod.parse = (payload, ctx) => {
|
|
2587
2587
|
const input = payload.value;
|
|
2588
|
-
if (!isPlainObject(input)) {
|
|
2588
|
+
if (!isPlainObject$1(input)) {
|
|
2589
2589
|
payload.issues.push({
|
|
2590
2590
|
expected: "record",
|
|
2591
2591
|
code: "invalid_type",
|
|
@@ -3107,10 +3107,10 @@ class $ZodRegistry {
|
|
|
3107
3107
|
}
|
|
3108
3108
|
}
|
|
3109
3109
|
// registries
|
|
3110
|
-
function registry
|
|
3110
|
+
function registry() {
|
|
3111
3111
|
return new $ZodRegistry();
|
|
3112
3112
|
}
|
|
3113
|
-
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry
|
|
3113
|
+
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
|
|
3114
3114
|
const globalRegistry = globalThis.__zod_globalRegistry;
|
|
3115
3115
|
|
|
3116
3116
|
// @__NO_SIDE_EFFECTS__
|
|
@@ -10326,29 +10326,7 @@ async function ensureBasicInfoDirectory(rootPath, relative) {
|
|
|
10326
10326
|
/** 构建时替换为当前发布包的实际版本。 */
|
|
10327
10327
|
const HB_SDK_VERSION = typeof undefined === 'string'
|
|
10328
10328
|
? undefined
|
|
10329
|
-
: '0.9.6-alpha.
|
|
10330
|
-
|
|
10331
|
-
/**
|
|
10332
|
-
* iframe 与调试台页面的开发期 console 捕获转发。
|
|
10333
|
-
*
|
|
10334
|
-
* 双条件门控(iframe 转发):
|
|
10335
|
-
* 1. 构建期:`hb-sdk dev`(vite serve)注入 `false`;`hb-sdk build` /
|
|
10336
|
-
* `vite build`(生产)永不注入或替换为 `false`,本模块被死代码消除。
|
|
10337
|
-
* 2. 运行期:仅在 `window.name` 为 `__hb_sdk_mini_dev__` 的调试 iframe 中激活,
|
|
10338
|
-
* 用户设备上的正式运行环境没有该标记。
|
|
10339
|
-
*
|
|
10340
|
-
* 无侵入 patch `console.log/debug/info/warn/error`:原样放行(DevTools 不受影响)+
|
|
10341
|
-
* 通过 `window.parent.postMessage` 转发给调试台(CSP 的 connect-src 不约束 postMessage,
|
|
10342
|
-
* 网络上报由调试台页面代理)。发送全程静默:失败不得回打 console,避免自触发死循环。
|
|
10343
|
-
*
|
|
10344
|
-
* 激活时机:由 SDK 默认单例初始化时调用(业务 `import '@heybox/hb-sdk'` 即生效);
|
|
10345
|
-
* iframe 标记由调试台 `iframe.name` 与 vite dev 注入的无依赖 bootstrap 共同设置。
|
|
10346
|
-
* 调试台页面自身(runtime 跑在这里,`[hb-sdk-runtime]` 日志不经过 iframe)另用
|
|
10347
|
-
* `installMiniDevConsoleSelfCapture` 接入「日志」页签(source: 'host')。
|
|
10348
|
-
*/
|
|
10349
|
-
const MINI_DEV_CONSOLE_EVENT_TYPE = 'hb-sdk:mini-dev-console';
|
|
10350
|
-
/** 调试台页面与 iframe bootstrap 共用的已安装标记(window/console 上的属性名)。 */
|
|
10351
|
-
const MINI_DEV_CONSOLE_INSTALL_FLAG = '__hb_sdk_mini_dev_console_installed__';
|
|
10329
|
+
: '0.9.6-alpha.6';
|
|
10352
10330
|
|
|
10353
10331
|
/**
|
|
10354
10332
|
* network.request 诊断日志的纯脱敏工具。
|
|
@@ -10358,6 +10336,25 @@ const MINI_DEV_CONSOLE_INSTALL_FLAG = '__hb_sdk_mini_dev_console_installed__';
|
|
|
10358
10336
|
* modules observability、devtools Browser Dev Host / proxy 共用,并满足 boundary
|
|
10359
10337
|
*(devtools 不得直接 import runtime capability modules)。
|
|
10360
10338
|
*/
|
|
10339
|
+
const DATA_PREVIEW_MAX_CHARS = 500;
|
|
10340
|
+
const SENSITIVE_HEADER_NAMES = new Set([
|
|
10341
|
+
'authorization',
|
|
10342
|
+
'cookie',
|
|
10343
|
+
'proxy-authorization',
|
|
10344
|
+
'set-cookie',
|
|
10345
|
+
'token',
|
|
10346
|
+
'x-pkey',
|
|
10347
|
+
'api-key',
|
|
10348
|
+
'apikey',
|
|
10349
|
+
'x-api-key',
|
|
10350
|
+
'x-auth-token',
|
|
10351
|
+
'x-access-token',
|
|
10352
|
+
'session',
|
|
10353
|
+
'session-id',
|
|
10354
|
+
'jwt',
|
|
10355
|
+
'refresh-token',
|
|
10356
|
+
'x-csrf-token',
|
|
10357
|
+
]);
|
|
10361
10358
|
/** 敏感字段名:header / query / body key 共用。 */
|
|
10362
10359
|
const SENSITIVE_KEY_PATTERN = /(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;
|
|
10363
10360
|
/**
|
|
@@ -10387,6 +10384,82 @@ function sanitizeNetworkRequestUrl(url) {
|
|
|
10387
10384
|
return redactSensitivePairsInRawText(url);
|
|
10388
10385
|
}
|
|
10389
10386
|
}
|
|
10387
|
+
/**
|
|
10388
|
+
* 脱敏请求/响应头;敏感名(含 heybox 前缀)替换为 `[redacted]`。
|
|
10389
|
+
*/
|
|
10390
|
+
function sanitizeNetworkHeaders(headers) {
|
|
10391
|
+
if (!headers) {
|
|
10392
|
+
return {};
|
|
10393
|
+
}
|
|
10394
|
+
return Object.fromEntries(Object.entries(headers).map(([key, value]) => [
|
|
10395
|
+
key,
|
|
10396
|
+
isSensitiveNetworkHeaderName(key) ? '[redacted]' : value,
|
|
10397
|
+
]));
|
|
10398
|
+
}
|
|
10399
|
+
/**
|
|
10400
|
+
* 预览请求/响应 data:递归脱敏敏感字段,截断长文本与大数组。
|
|
10401
|
+
*/
|
|
10402
|
+
function previewNetworkData(data) {
|
|
10403
|
+
if (data === undefined) {
|
|
10404
|
+
return undefined;
|
|
10405
|
+
}
|
|
10406
|
+
if (typeof data === 'string') {
|
|
10407
|
+
return previewNetworkStringData(data);
|
|
10408
|
+
}
|
|
10409
|
+
if (typeof data === 'number' || typeof data === 'boolean' || data === null) {
|
|
10410
|
+
return data;
|
|
10411
|
+
}
|
|
10412
|
+
try {
|
|
10413
|
+
const sanitized = sanitizeNetworkDataValue(data);
|
|
10414
|
+
const serialized = JSON.stringify(sanitized);
|
|
10415
|
+
if (serialized === undefined) {
|
|
10416
|
+
return '[unserializable]';
|
|
10417
|
+
}
|
|
10418
|
+
if (serialized.length <= DATA_PREVIEW_MAX_CHARS) {
|
|
10419
|
+
return sanitized;
|
|
10420
|
+
}
|
|
10421
|
+
return truncateText(serialized, DATA_PREVIEW_MAX_CHARS);
|
|
10422
|
+
}
|
|
10423
|
+
catch {
|
|
10424
|
+
return '[unserializable]';
|
|
10425
|
+
}
|
|
10426
|
+
}
|
|
10427
|
+
/**
|
|
10428
|
+
* 递归脱敏日志对象(payload / result):敏感 key、headers、url 字段统一处理。
|
|
10429
|
+
*/
|
|
10430
|
+
function redactNetworkLogValue(value) {
|
|
10431
|
+
if (Array.isArray(value)) {
|
|
10432
|
+
return value.slice(0, 20).map(item => redactNetworkLogValue(item));
|
|
10433
|
+
}
|
|
10434
|
+
if (typeof value === 'string') {
|
|
10435
|
+
if (looksLikeUrl(value)) {
|
|
10436
|
+
return sanitizeNetworkRequestUrl(value);
|
|
10437
|
+
}
|
|
10438
|
+
return previewNetworkStringData(value);
|
|
10439
|
+
}
|
|
10440
|
+
if (typeof value === 'number' || typeof value === 'boolean' || value === null || value === undefined) {
|
|
10441
|
+
return value;
|
|
10442
|
+
}
|
|
10443
|
+
if (!isPlainObject(value)) {
|
|
10444
|
+
return previewNetworkData(value);
|
|
10445
|
+
}
|
|
10446
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => {
|
|
10447
|
+
const normalized = key.trim().toLowerCase();
|
|
10448
|
+
if (isSensitiveNetworkKey(key)) {
|
|
10449
|
+
return [key, '[redacted]'];
|
|
10450
|
+
}
|
|
10451
|
+
if (normalized === 'headers' && isPlainObject(item)) {
|
|
10452
|
+
return [
|
|
10453
|
+
key,
|
|
10454
|
+
sanitizeNetworkHeaders(Object.fromEntries(Object.entries(item).flatMap(([headerKey, headerValue]) => typeof headerValue === 'string' ? [[headerKey, headerValue]] : []))),
|
|
10455
|
+
];
|
|
10456
|
+
}
|
|
10457
|
+
if ((normalized === 'url' || normalized.endsWith('_url') || normalized.endsWith('url')) && typeof item === 'string') {
|
|
10458
|
+
return [key, sanitizeNetworkRequestUrl(item)];
|
|
10459
|
+
}
|
|
10460
|
+
return [key, redactNetworkLogValue(item)];
|
|
10461
|
+
}));
|
|
10462
|
+
}
|
|
10390
10463
|
/**
|
|
10391
10464
|
* 诊断 message 中的 URL 片段做脱敏,避免 error.message 二次泄漏 query secrets。
|
|
10392
10465
|
*/
|
|
@@ -10396,9 +10469,58 @@ function sanitizeDiagnosticMessage(message) {
|
|
|
10396
10469
|
}
|
|
10397
10470
|
return message.replace(/https?:\/\/[^\s]+/gi, matched => sanitizeNetworkRequestUrl(matched.replace(/[),.;]+$/g, '')));
|
|
10398
10471
|
}
|
|
10472
|
+
function isSensitiveNetworkHeaderName(headerName) {
|
|
10473
|
+
const normalized = headerName.trim().toLowerCase();
|
|
10474
|
+
return (SENSITIVE_HEADER_NAMES.has(normalized) ||
|
|
10475
|
+
isSensitiveNetworkKey(normalized) ||
|
|
10476
|
+
normalized.startsWith('x-heybox-') ||
|
|
10477
|
+
normalized.startsWith('x-xhh-'));
|
|
10478
|
+
}
|
|
10399
10479
|
function isSensitiveNetworkKey(key) {
|
|
10400
10480
|
return SENSITIVE_KEY_PATTERN.test(key.trim());
|
|
10401
10481
|
}
|
|
10482
|
+
function previewNetworkStringData(data) {
|
|
10483
|
+
const trimmed = data.trim();
|
|
10484
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
10485
|
+
try {
|
|
10486
|
+
return previewNetworkData(JSON.parse(trimmed));
|
|
10487
|
+
}
|
|
10488
|
+
catch {
|
|
10489
|
+
// fall through
|
|
10490
|
+
}
|
|
10491
|
+
}
|
|
10492
|
+
if (trimmed.includes('=') && !trimmed.includes('\n') && trimmed.length <= DATA_PREVIEW_MAX_CHARS * 2) {
|
|
10493
|
+
try {
|
|
10494
|
+
const params = new URLSearchParams(trimmed);
|
|
10495
|
+
if ([...params.keys()].length > 0) {
|
|
10496
|
+
const redacted = Object.fromEntries([...params.entries()].map(([key, value]) => [
|
|
10497
|
+
key,
|
|
10498
|
+
isSensitiveNetworkKey(key) ? '[redacted]' : value,
|
|
10499
|
+
]));
|
|
10500
|
+
return previewNetworkData(redacted);
|
|
10501
|
+
}
|
|
10502
|
+
}
|
|
10503
|
+
catch {
|
|
10504
|
+
// fall through
|
|
10505
|
+
}
|
|
10506
|
+
}
|
|
10507
|
+
return truncateText(redactSensitivePairsInRawText(data), DATA_PREVIEW_MAX_CHARS);
|
|
10508
|
+
}
|
|
10509
|
+
function sanitizeNetworkDataValue(value) {
|
|
10510
|
+
if (Array.isArray(value)) {
|
|
10511
|
+
return value.slice(0, 20).map(item => sanitizeNetworkDataValue(item));
|
|
10512
|
+
}
|
|
10513
|
+
if (!isPlainObject(value)) {
|
|
10514
|
+
if (typeof value === 'string') {
|
|
10515
|
+
return truncateText(value, DATA_PREVIEW_MAX_CHARS);
|
|
10516
|
+
}
|
|
10517
|
+
return value;
|
|
10518
|
+
}
|
|
10519
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
10520
|
+
key,
|
|
10521
|
+
isSensitiveNetworkKey(key) ? '[redacted]' : sanitizeNetworkDataValue(item),
|
|
10522
|
+
]));
|
|
10523
|
+
}
|
|
10402
10524
|
function redactUrlSearchParams(params) {
|
|
10403
10525
|
let changed = false;
|
|
10404
10526
|
for (const key of [...params.keys()]) {
|
|
@@ -10410,76 +10532,723 @@ function redactUrlSearchParams(params) {
|
|
|
10410
10532
|
return changed;
|
|
10411
10533
|
}
|
|
10412
10534
|
function redactSensitivePairsInRawText(text) {
|
|
10413
|
-
return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key
|
|
10535
|
+
return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key) => {
|
|
10414
10536
|
if (!isSensitiveNetworkKey(key)) {
|
|
10415
10537
|
return full;
|
|
10416
10538
|
}
|
|
10417
10539
|
return `${prefix}${key}=[redacted]`;
|
|
10418
10540
|
});
|
|
10419
10541
|
}
|
|
10542
|
+
function looksLikeUrl(value) {
|
|
10543
|
+
return /^https?:\/\//i.test(value.trim()) || /^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim());
|
|
10544
|
+
}
|
|
10545
|
+
function truncateText(value, maxChars) {
|
|
10546
|
+
if (value.length <= maxChars) {
|
|
10547
|
+
return value;
|
|
10548
|
+
}
|
|
10549
|
+
return `${value.slice(0, maxChars)}…(truncated, total=${value.length})`;
|
|
10550
|
+
}
|
|
10551
|
+
function isPlainObject(value) {
|
|
10552
|
+
return Object.prototype.toString.call(value) === '[object Object]';
|
|
10553
|
+
}
|
|
10554
|
+
|
|
10555
|
+
function sanitizePresentationText(value, limit) {
|
|
10556
|
+
return sanitizeDiagnosticMessage(String(redactNetworkLogValue(value))).slice(0, limit);
|
|
10557
|
+
}
|
|
10558
|
+
/** 当前快照与历史事件共用白名单,不保存授权资料或任意参数。 */
|
|
10559
|
+
function sanitizeHostInteractionSnapshot(input) {
|
|
10560
|
+
if (!input || typeof input !== 'object')
|
|
10561
|
+
return undefined;
|
|
10562
|
+
const item = input;
|
|
10563
|
+
if (typeof item.interactionId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(item.interactionId) ||
|
|
10564
|
+
(typeof item.kind !== 'string' || !['toast', 'loading', 'dialog', 'effect'].includes(item.kind)) ||
|
|
10565
|
+
(typeof item.mode !== 'string' || !['simulated', 'browser'].includes(item.mode)) ||
|
|
10566
|
+
typeof item.method !== 'string' || !Number.isFinite(item.startedAt))
|
|
10567
|
+
return undefined;
|
|
10568
|
+
return {
|
|
10569
|
+
interactionId: item.interactionId,
|
|
10570
|
+
kind: item.kind,
|
|
10571
|
+
mode: item.mode,
|
|
10572
|
+
method: sanitizePresentationText(item.method, 100),
|
|
10573
|
+
startedAt: item.startedAt,
|
|
10574
|
+
...(typeof item.callId === 'string' ? { callId: sanitizePresentationText(item.callId, 100) } : {}),
|
|
10575
|
+
...(typeof item.message === 'string' ? { message: sanitizePresentationText(item.message, 512) } : {}),
|
|
10576
|
+
...(typeof item.title === 'string' ? { title: sanitizePresentationText(item.title, 120) } : {}),
|
|
10577
|
+
...(item.status === 'success' || item.status === 'error' ? { status: item.status } : {}),
|
|
10578
|
+
...(typeof item.dismissible === 'boolean' ? { dismissible: item.dismissible } : {}),
|
|
10579
|
+
...(Array.isArray(item.actions) ? { actions: item.actions.slice(0, 4).filter((value) => typeof value === 'string').map(value => sanitizePresentationText(value, 40)) } : {}),
|
|
10580
|
+
};
|
|
10581
|
+
}
|
|
10582
|
+
function sanitizeHostInteraction(input) {
|
|
10583
|
+
const snapshot = sanitizeHostInteractionSnapshot(input);
|
|
10584
|
+
if (!snapshot)
|
|
10585
|
+
return undefined;
|
|
10586
|
+
const state = input.state;
|
|
10587
|
+
if (typeof state !== 'string' || !['shown', 'completed', 'confirmed', 'cancelled', 'expired', 'replaced', 'hidden', 'closed'].includes(state))
|
|
10588
|
+
return undefined;
|
|
10589
|
+
return { ...snapshot, state: state };
|
|
10590
|
+
}
|
|
10591
|
+
|
|
10592
|
+
/** 本机开发工具合同,不属于 Mini-program bridge 协议。 */
|
|
10593
|
+
const DEV_DIAGNOSTICS_SCHEMA_VERSION = 3;
|
|
10594
|
+
const DEV_SANDBOX_READ_MAX_BYTES = 16 * 1024;
|
|
10595
|
+
const DEV_PRESENTATION_MAX_INTERACTIONS = 16;
|
|
10420
10596
|
|
|
10421
10597
|
const DEVICE_LOG_PATH = '/__hb_sdk__/device-logs';
|
|
10422
|
-
const
|
|
10423
|
-
const
|
|
10424
|
-
const
|
|
10425
|
-
function
|
|
10426
|
-
|
|
10427
|
-
|
|
10428
|
-
|
|
10429
|
-
|
|
10598
|
+
const sessionRegistryKey = Symbol.for('@heybox/hb-sdk/dev-diagnostics-sessions');
|
|
10599
|
+
const sessionRegistry = globalThis;
|
|
10600
|
+
const sessions = (sessionRegistry[sessionRegistryKey] ??= new Map());
|
|
10601
|
+
function getDevDiagnosticsSession(id) {
|
|
10602
|
+
return sessions.get(id);
|
|
10603
|
+
}
|
|
10604
|
+
function safeMessage(value, limit = 8192) {
|
|
10605
|
+
const plain = (text) => text
|
|
10606
|
+
.replace(/https?:\/\/[^\s]+/gi, (raw) => {
|
|
10607
|
+
try {
|
|
10608
|
+
const url = new URL(raw.replace(/[),.;]+$/g, ''));
|
|
10609
|
+
url.username = '';
|
|
10610
|
+
url.password = '';
|
|
10611
|
+
url.search = '';
|
|
10612
|
+
url.hash = '';
|
|
10613
|
+
return url.href;
|
|
10614
|
+
}
|
|
10615
|
+
catch {
|
|
10616
|
+
return '[URL]';
|
|
10617
|
+
}
|
|
10618
|
+
})
|
|
10619
|
+
.replace(/(x-hb-sdk-[a-z0-9-]+|authorization|cookie|password|secret|token|hkey|pkey|nonce|api[_-]?key)(["'\s:=]+)([^\s,}]+)/gi, '$1$2[redacted]');
|
|
10620
|
+
// Runtime 事实以 JSON 文本保存;逐字段处理,避免 URL 正则吞掉 JSON 分隔符。
|
|
10621
|
+
if (/^\s*[\[{]/.test(value)) {
|
|
10622
|
+
try {
|
|
10623
|
+
const parsed = JSON.parse(value);
|
|
10624
|
+
return JSON.stringify(parsed, (key, item) => isSensitiveNetworkKey(key) || /^(hkey|nonce)$/i.test(key) || key.toLowerCase().startsWith('x-hb-sdk-')
|
|
10625
|
+
? '[redacted]'
|
|
10626
|
+
: typeof item === 'string'
|
|
10627
|
+
? plain(item)
|
|
10628
|
+
: item).slice(0, limit);
|
|
10629
|
+
}
|
|
10630
|
+
catch {
|
|
10631
|
+
/* 截断或非法 JSON 继续按普通文本保守脱敏。 */
|
|
10632
|
+
}
|
|
10633
|
+
}
|
|
10634
|
+
return plain(value).slice(0, limit);
|
|
10635
|
+
}
|
|
10636
|
+
function safeError(error) {
|
|
10637
|
+
return {
|
|
10638
|
+
code: /^[A-Z0-9_]{1,100}$/.test(error.code) ? error.code : 'RUNTIME_FAILED',
|
|
10639
|
+
message: safeMessage(error.message),
|
|
10640
|
+
...(error.name ? { name: safeMessage(error.name, 100) } : {}),
|
|
10641
|
+
...(error.stack ? { stack: safeMessage(error.stack) } : {}),
|
|
10642
|
+
...(error.cause ? { cause: safeMessage(error.cause, 2048) } : {}),
|
|
10643
|
+
...(error.phase ? { phase: safeMessage(error.phase, 100) } : {}),
|
|
10430
10644
|
};
|
|
10431
10645
|
}
|
|
10646
|
+
/** 一次 dev 进程拥有的有界事实记录;上传会话与 Runtime 实例独立。 */
|
|
10432
10647
|
class DeviceLogStore {
|
|
10433
|
-
sandboxRequests = new Map();
|
|
10434
|
-
listSandbox(id, path) {
|
|
10435
|
-
const device = this.devices.get(id);
|
|
10436
|
-
if (!device || Date.now() - device.lastSeen > 15000)
|
|
10437
|
-
return Promise.resolve({ error: '设备已离线' });
|
|
10438
|
-
if (path !== '.' && (!path || path.length > 1024 || /[\\\\\u0000-\u001f]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..')))
|
|
10439
|
-
return Promise.resolve({ error: '无效目录路径' });
|
|
10440
|
-
if (this.sandboxRequests.size >= 64)
|
|
10441
|
-
return Promise.resolve({ error: '查询繁忙,请稍后重试' });
|
|
10442
|
-
const requestId = randomUUID();
|
|
10443
|
-
return new Promise(resolve => {
|
|
10444
|
-
const timer = setTimeout(() => { this.sandboxRequests.delete(requestId); resolve({ error: '设备查询超时' }); }, 10000);
|
|
10445
|
-
this.sandboxRequests.set(requestId, { id, path, requestId, resolve: value => { clearTimeout(timer); this.sandboxRequests.delete(requestId); resolve(value); } });
|
|
10446
|
-
});
|
|
10447
|
-
}
|
|
10448
10648
|
uploadToken = randomBytes(32).toString('hex');
|
|
10449
10649
|
epoch = randomUUID();
|
|
10650
|
+
sessionId = this.epoch;
|
|
10450
10651
|
expiresAt = Date.now() + 12 * 60 * 60 * 1000;
|
|
10451
10652
|
cursor = 0;
|
|
10452
10653
|
logs = [];
|
|
10453
|
-
|
|
10654
|
+
instances = new Map();
|
|
10655
|
+
terminalInstances = new Map();
|
|
10656
|
+
targets = new Map();
|
|
10657
|
+
primaryTargetId;
|
|
10658
|
+
browserOwners = new Map();
|
|
10659
|
+
controlledBrowserToken;
|
|
10660
|
+
browserPageCredentials = new Map();
|
|
10661
|
+
hostSequences = new Map();
|
|
10662
|
+
pending = new Map();
|
|
10663
|
+
uploadSessions = new Map();
|
|
10664
|
+
targetSnapshot(target, now = Date.now()) {
|
|
10665
|
+
return { ...target, stale: target.state !== 'closed' && now - target.updatedAt > 15000 };
|
|
10666
|
+
}
|
|
10667
|
+
instanceSnapshot(instance, now = Date.now()) {
|
|
10668
|
+
return {
|
|
10669
|
+
...instance,
|
|
10670
|
+
stale: instance.endedAt === undefined && now - (this.targets.get(instance.targetId)?.updatedAt ?? instance.updatedAt) > 15000,
|
|
10671
|
+
};
|
|
10672
|
+
}
|
|
10673
|
+
setSessionId(id) {
|
|
10674
|
+
this.sessionId = id;
|
|
10675
|
+
}
|
|
10676
|
+
registerTarget(input) {
|
|
10677
|
+
const existing = this.targets.get(input.targetId);
|
|
10678
|
+
if (existing && (existing.adapterId !== input.adapterId || existing.kind !== input.kind))
|
|
10679
|
+
throw new Error('TARGET_IDENTITY_MISMATCH');
|
|
10680
|
+
if (!existing && this.targets.size >= 128) {
|
|
10681
|
+
const closed = [...this.targets.values()].find((target) => target.state === 'closed' && (target.targetId !== this.primaryTargetId || input.primary));
|
|
10682
|
+
if (!closed)
|
|
10683
|
+
throw new Error('TARGET_LIMIT');
|
|
10684
|
+
this.targets.delete(closed.targetId);
|
|
10685
|
+
}
|
|
10686
|
+
if (existing && existing.ownerId !== input.ownerId) {
|
|
10687
|
+
for (const instance of this.instances.values())
|
|
10688
|
+
if (instance.targetId === input.targetId && instance.endedAt === undefined)
|
|
10689
|
+
this.updateInstance(instance.instanceId, { state: 'closed', reason: 'owner replaced' });
|
|
10690
|
+
}
|
|
10691
|
+
const metadata = this.targetMetadata(input.kind, { ...existing?.metadata, ...input.metadata });
|
|
10692
|
+
const target = {
|
|
10693
|
+
metadata,
|
|
10694
|
+
...(existing?.cdpTargetId ? { cdpTargetId: existing.cdpTargetId } : {}),
|
|
10695
|
+
targetId: input.targetId,
|
|
10696
|
+
adapterId: input.adapterId,
|
|
10697
|
+
ownerId: input.ownerId,
|
|
10698
|
+
kind: input.kind,
|
|
10699
|
+
capabilities: input.capabilities,
|
|
10700
|
+
state: existing?.ownerId === input.ownerId ? existing.state : 'detached',
|
|
10701
|
+
currentInstanceId: existing?.ownerId === input.ownerId ? existing.currentInstanceId : null,
|
|
10702
|
+
updatedAt: Date.now(),
|
|
10703
|
+
};
|
|
10704
|
+
this.targets.set(target.targetId, target);
|
|
10705
|
+
this.trimOwnerState();
|
|
10706
|
+
if (input.primary)
|
|
10707
|
+
this.primaryTargetId = target.targetId;
|
|
10708
|
+
return this.targetSnapshot(target);
|
|
10709
|
+
}
|
|
10710
|
+
targetMetadata(kind, input) {
|
|
10711
|
+
const fields = Object.fromEntries(['browser', 'os', 'deviceModel', 'osVersion'].flatMap((key) => {
|
|
10712
|
+
const value = input[key];
|
|
10713
|
+
return typeof value === 'string' && value.trim() ? [[key, safeMessage(value.trim(), 100)]] : [];
|
|
10714
|
+
}));
|
|
10715
|
+
const displayName = (kind === 'browser' ? [fields.browser, fields.os] : [fields.deviceModel, [fields.os, fields.osVersion].filter(Boolean).join(' ')])
|
|
10716
|
+
.filter(Boolean)
|
|
10717
|
+
.join(' · ') || (kind === 'browser' ? '浏览器预览' : '原生 Host');
|
|
10718
|
+
return { ...fields, displayName };
|
|
10719
|
+
}
|
|
10720
|
+
requireTarget(targetId, ownerId) {
|
|
10721
|
+
const target = this.targets.get(targetId);
|
|
10722
|
+
if (!target || target.ownerId !== ownerId || target.state === 'closed')
|
|
10723
|
+
throw new Error('TARGET_OWNER_CHANGED');
|
|
10724
|
+
return target;
|
|
10725
|
+
}
|
|
10726
|
+
registerInstance(instanceId, owner) {
|
|
10727
|
+
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(instanceId))
|
|
10728
|
+
throw new Error('INVALID_INSTANCE');
|
|
10729
|
+
const target = this.requireTarget(owner.targetId, owner.ownerId);
|
|
10730
|
+
const existing = this.instances.get(instanceId);
|
|
10731
|
+
if (existing) {
|
|
10732
|
+
if (existing.targetId !== target.targetId || existing.ownerId !== target.ownerId)
|
|
10733
|
+
throw new Error('INSTANCE_OWNER_MISMATCH');
|
|
10734
|
+
return this.instanceSnapshot(existing);
|
|
10735
|
+
}
|
|
10736
|
+
if ([...this.instances.values()].filter((instance) => instance.endedAt === undefined).length >= 256)
|
|
10737
|
+
throw new Error('INSTANCE_LIMIT');
|
|
10738
|
+
const now = Date.now();
|
|
10739
|
+
const instance = {
|
|
10740
|
+
instanceId,
|
|
10741
|
+
targetId: target.targetId,
|
|
10742
|
+
ownerId: target.ownerId,
|
|
10743
|
+
adapterId: target.adapterId,
|
|
10744
|
+
kind: target.kind,
|
|
10745
|
+
capabilities: owner.capabilities ?? target.capabilities,
|
|
10746
|
+
state: 'starting',
|
|
10747
|
+
startedAt: now,
|
|
10748
|
+
updatedAt: now,
|
|
10749
|
+
startCursor: this.cursor,
|
|
10750
|
+
lastCursor: this.cursor,
|
|
10751
|
+
};
|
|
10752
|
+
this.instances.set(instanceId, instance);
|
|
10753
|
+
return this.instanceSnapshot(instance);
|
|
10754
|
+
}
|
|
10755
|
+
activateInstance(targetId, ownerId, instanceId) {
|
|
10756
|
+
const target = this.requireTarget(targetId, ownerId);
|
|
10757
|
+
const instance = this.instances.get(instanceId);
|
|
10758
|
+
if (!instance || instance.targetId !== targetId || instance.ownerId !== ownerId || instance.endedAt !== undefined)
|
|
10759
|
+
throw new Error('INSTANCE_NOT_ACTIVATABLE');
|
|
10760
|
+
if (target.currentInstanceId && target.currentInstanceId !== instanceId)
|
|
10761
|
+
this.updateInstance(target.currentInstanceId, { state: 'closed', reason: 'replaced' });
|
|
10762
|
+
target.currentInstanceId = instanceId;
|
|
10763
|
+
target.state = 'attached';
|
|
10764
|
+
target.updatedAt = Date.now();
|
|
10765
|
+
return this.targetSnapshot(target);
|
|
10766
|
+
}
|
|
10767
|
+
detachInstance(targetId, ownerId, instanceId, reason = 'detached') {
|
|
10768
|
+
const target = this.requireTarget(targetId, ownerId);
|
|
10769
|
+
if (target.currentInstanceId !== instanceId)
|
|
10770
|
+
return this.targetSnapshot(target);
|
|
10771
|
+
const instance = this.instances.get(instanceId);
|
|
10772
|
+
if (instance && instance.endedAt === undefined)
|
|
10773
|
+
this.updateInstance(instanceId, { state: 'closed', reason });
|
|
10774
|
+
target.currentInstanceId = null;
|
|
10775
|
+
target.state = 'detached';
|
|
10776
|
+
target.updatedAt = Date.now();
|
|
10777
|
+
return this.targetSnapshot(target);
|
|
10778
|
+
}
|
|
10779
|
+
closeTarget(targetId, ownerId, reason = 'target closed') {
|
|
10780
|
+
const target = this.targets.get(targetId);
|
|
10781
|
+
if (!target || target.ownerId !== ownerId)
|
|
10782
|
+
throw new Error('TARGET_OWNER_CHANGED');
|
|
10783
|
+
if (target.state === 'closed')
|
|
10784
|
+
return;
|
|
10785
|
+
for (const instance of this.instances.values())
|
|
10786
|
+
if (instance.targetId === targetId && instance.endedAt === undefined)
|
|
10787
|
+
this.updateInstance(instance.instanceId, { state: 'closed', reason });
|
|
10788
|
+
target.currentInstanceId = null;
|
|
10789
|
+
target.state = 'closed';
|
|
10790
|
+
target.updatedAt = Date.now();
|
|
10791
|
+
this.trimOwnerState();
|
|
10792
|
+
}
|
|
10793
|
+
createOwnedBrowserTarget(metadata) {
|
|
10794
|
+
if (this.controlledBrowserToken) {
|
|
10795
|
+
const previous = this.browserOwners.get(this.controlledBrowserToken);
|
|
10796
|
+
if (previous) {
|
|
10797
|
+
const oldTarget = this.targets.get(previous.targetId);
|
|
10798
|
+
if (oldTarget && oldTarget.state !== 'closed')
|
|
10799
|
+
this.closeTarget(oldTarget.targetId, oldTarget.ownerId, 'owned page replaced');
|
|
10800
|
+
previous.closed = true;
|
|
10801
|
+
}
|
|
10802
|
+
}
|
|
10803
|
+
const ownerId = randomUUID(), token = randomBytes(32).toString('hex'), targetId = `preview:${randomUUID()}`;
|
|
10804
|
+
this.registerTarget({
|
|
10805
|
+
targetId,
|
|
10806
|
+
ownerId,
|
|
10807
|
+
adapterId: targetId,
|
|
10808
|
+
kind: 'browser',
|
|
10809
|
+
primary: true,
|
|
10810
|
+
metadata,
|
|
10811
|
+
capabilities: { storage: true, sandboxList: false, sandboxRead: false, presentation: true },
|
|
10812
|
+
});
|
|
10813
|
+
this.browserOwners.set(token, { controllerOwnerId: ownerId, targetId, closed: false });
|
|
10814
|
+
this.controlledBrowserToken = token;
|
|
10815
|
+
this.trimBrowserOwners();
|
|
10816
|
+
return { targetId, ownerId, token };
|
|
10817
|
+
}
|
|
10818
|
+
trimBrowserOwners() {
|
|
10819
|
+
while (this.browserOwners.size > 128) {
|
|
10820
|
+
const old = [...this.browserOwners.entries()].find(([token, owner]) => owner.closed && token !== this.controlledBrowserToken);
|
|
10821
|
+
if (!old)
|
|
10822
|
+
throw new Error('BROWSER_OWNER_LIMIT');
|
|
10823
|
+
this.browserOwners.delete(old[0]);
|
|
10824
|
+
}
|
|
10825
|
+
}
|
|
10826
|
+
bindPhysicalTarget(ownerId, browserTargetId) {
|
|
10827
|
+
const owner = this.controlledBrowserToken && this.browserOwners.get(this.controlledBrowserToken);
|
|
10828
|
+
if (!owner || owner.controllerOwnerId !== ownerId || owner.closed)
|
|
10829
|
+
return false;
|
|
10830
|
+
const target = this.targets.get(owner.targetId);
|
|
10831
|
+
target.cdpTargetId = browserTargetId;
|
|
10832
|
+
return true;
|
|
10833
|
+
}
|
|
10834
|
+
closeOwnedBrowserTarget(ownerId) {
|
|
10835
|
+
const owner = this.controlledBrowserToken && this.browserOwners.get(this.controlledBrowserToken);
|
|
10836
|
+
if (!owner || owner.controllerOwnerId !== ownerId || owner.closed)
|
|
10837
|
+
return;
|
|
10838
|
+
this.closeTarget(owner.targetId, this.targets.get(owner.targetId).ownerId);
|
|
10839
|
+
owner.closed = true;
|
|
10840
|
+
}
|
|
10841
|
+
/** 受控 token 必须先由 HTTP owner 通过当前 CDP 文档验证,不能凭最后到达决定页面代。 */
|
|
10842
|
+
attachBrowserPage(pageId, controllerToken, metadata) {
|
|
10843
|
+
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(pageId))
|
|
10844
|
+
throw new Error('INVALID_PAGE_ID');
|
|
10845
|
+
const controller = controllerToken ? this.browserOwners.get(controllerToken) : undefined;
|
|
10846
|
+
if (controllerToken && (!controller || controller.closed))
|
|
10847
|
+
throw new Error('BROWSER_OWNER_CHANGED');
|
|
10848
|
+
if (controller?.currentPageToken && this.targets.get(controller.targetId)?.ownerId === pageId) {
|
|
10849
|
+
return { target: this.targetSnapshot(this.targets.get(controller.targetId)), ownerToken: controller.currentPageToken };
|
|
10850
|
+
}
|
|
10851
|
+
const targetId = controller?.targetId ?? `page:${randomUUID()}`;
|
|
10852
|
+
const target = this.registerTarget({
|
|
10853
|
+
targetId,
|
|
10854
|
+
adapterId: targetId,
|
|
10855
|
+
ownerId: pageId,
|
|
10856
|
+
kind: 'browser',
|
|
10857
|
+
metadata,
|
|
10858
|
+
capabilities: { storage: true, sandboxList: false, sandboxRead: false, presentation: true },
|
|
10859
|
+
});
|
|
10860
|
+
const ownerToken = randomBytes(32).toString('hex');
|
|
10861
|
+
this.browserPageCredentials.set(ownerToken, { targetId, ownerId: pageId, controllerToken });
|
|
10862
|
+
if (controller)
|
|
10863
|
+
controller.currentPageToken = ownerToken;
|
|
10864
|
+
this.trimOwnerState();
|
|
10865
|
+
return { target, ownerToken };
|
|
10866
|
+
}
|
|
10867
|
+
trimOwnerState() {
|
|
10868
|
+
for (const [token, credential] of this.browserPageCredentials) {
|
|
10869
|
+
const target = this.targets.get(credential.targetId);
|
|
10870
|
+
if (target?.ownerId === credential.ownerId && target.state !== 'closed')
|
|
10871
|
+
continue;
|
|
10872
|
+
if ([...this.instances.values()].some((instance) => instance.targetId === credential.targetId && instance.ownerId === credential.ownerId))
|
|
10873
|
+
continue;
|
|
10874
|
+
this.browserPageCredentials.delete(token);
|
|
10875
|
+
}
|
|
10876
|
+
for (const [key, actor] of this.hostSequences) {
|
|
10877
|
+
const target = this.targets.get(actor.targetId);
|
|
10878
|
+
if (target?.ownerId === actor.ownerId && target.state !== 'closed')
|
|
10879
|
+
continue;
|
|
10880
|
+
if ([...this.instances.values()].some((instance) => instance.targetId === actor.targetId && instance.ownerId === actor.ownerId))
|
|
10881
|
+
continue;
|
|
10882
|
+
this.hostSequences.delete(key);
|
|
10883
|
+
}
|
|
10884
|
+
}
|
|
10885
|
+
isControlledBrowserOwner(token) {
|
|
10886
|
+
return this.browserOwners.get(token)?.targetId === this.primaryTargetId && this.primaryTargetId !== undefined;
|
|
10887
|
+
}
|
|
10888
|
+
authorizeBrowserPage(token, targetId, ownerId, historicalInstanceId) {
|
|
10889
|
+
const credential = this.browserPageCredentials.get(token);
|
|
10890
|
+
if (!credential || credential.targetId !== targetId || credential.ownerId !== ownerId)
|
|
10891
|
+
return false;
|
|
10892
|
+
const target = this.targets.get(targetId);
|
|
10893
|
+
const controller = credential.controllerToken ? this.browserOwners.get(credential.controllerToken) : undefined;
|
|
10894
|
+
if (target?.ownerId === ownerId &&
|
|
10895
|
+
target.state !== 'closed' &&
|
|
10896
|
+
(!credential.controllerToken || (controller?.currentPageToken === token && !controller.closed)))
|
|
10897
|
+
return true;
|
|
10898
|
+
const historical = historicalInstanceId && this.instances.get(historicalInstanceId);
|
|
10899
|
+
return Boolean(historical && historical.endedAt !== undefined && historical.targetId === targetId && historical.ownerId === ownerId);
|
|
10900
|
+
}
|
|
10901
|
+
updateInstance(id, update) {
|
|
10902
|
+
const instance = this.instances.get(id);
|
|
10903
|
+
if (!instance)
|
|
10904
|
+
throw new Error('INSTANCE_NOT_FOUND');
|
|
10905
|
+
const uploadSession = update.uploadSessionId ? this.uploadSessions.get(update.uploadSessionId) : undefined;
|
|
10906
|
+
if (uploadSession?.instanceId && uploadSession.instanceId !== id)
|
|
10907
|
+
throw new Error('UPLOAD_SESSION_OWNER_MISMATCH');
|
|
10908
|
+
// 终态不可复活,但允许迟到的身份关联补全此前已保存的失败证据。
|
|
10909
|
+
if (update.runtimeId && !instance.runtimeId)
|
|
10910
|
+
instance.runtimeId = update.runtimeId.slice(0, 100);
|
|
10911
|
+
if (uploadSession) {
|
|
10912
|
+
uploadSession.instanceId = id;
|
|
10913
|
+
instance.uploadSessionId = uploadSession.id;
|
|
10914
|
+
for (const log of this.logs)
|
|
10915
|
+
if (log.uploadSessionId === uploadSession.id && !log.instanceId) {
|
|
10916
|
+
log.instanceId = id;
|
|
10917
|
+
log.targetId = instance.targetId;
|
|
10918
|
+
log.ownerId = instance.ownerId;
|
|
10919
|
+
log.late = this.terminalInstances.has(id) && log.cursor > this.terminalInstances.get(id);
|
|
10920
|
+
instance.lastCursor = Math.max(instance.lastCursor, log.cursor);
|
|
10921
|
+
}
|
|
10922
|
+
}
|
|
10923
|
+
if (instance.endedAt !== undefined)
|
|
10924
|
+
return this.instanceSnapshot(instance);
|
|
10925
|
+
instance.updatedAt = Date.now();
|
|
10926
|
+
instance.state = update.state;
|
|
10927
|
+
if (typeof update.documentVerifying === 'boolean')
|
|
10928
|
+
instance.documentVerifying = update.documentVerifying;
|
|
10929
|
+
if (update.error && typeof update.error.code === 'string' && typeof update.error.message === 'string')
|
|
10930
|
+
instance.error = safeError(update.error);
|
|
10931
|
+
if (update.reason)
|
|
10932
|
+
instance.reason = safeMessage(update.reason, 200);
|
|
10933
|
+
if (update.state === 'failed' || update.state === 'closed') {
|
|
10934
|
+
instance.endedAt = Date.now();
|
|
10935
|
+
this.terminalInstances.set(id, this.cursor);
|
|
10936
|
+
for (const request of this.pending.values())
|
|
10937
|
+
if (request.task.instanceId === id)
|
|
10938
|
+
request.resolve(this.resourceError(request.task, 'closed', 'RUNTIME_INSTANCE_CLOSED'));
|
|
10939
|
+
this.trimTerminalInstances();
|
|
10940
|
+
}
|
|
10941
|
+
return this.instanceSnapshot(instance);
|
|
10942
|
+
}
|
|
10943
|
+
trimTerminalInstances() {
|
|
10944
|
+
while (this.terminalInstances.size > 64) {
|
|
10945
|
+
const oldest = this.terminalInstances.keys().next().value;
|
|
10946
|
+
this.terminalInstances.delete(oldest);
|
|
10947
|
+
this.instances.delete(oldest);
|
|
10948
|
+
for (const [uploadId, upload] of this.uploadSessions)
|
|
10949
|
+
if (upload.instanceId === oldest)
|
|
10950
|
+
this.uploadSessions.delete(uploadId);
|
|
10951
|
+
for (const target of this.targets.values())
|
|
10952
|
+
if (target.currentInstanceId === oldest)
|
|
10953
|
+
target.currentInstanceId = null;
|
|
10954
|
+
}
|
|
10955
|
+
this.trimOwnerState();
|
|
10956
|
+
}
|
|
10957
|
+
appendHostEvents(identity, events, producerId, sequence) {
|
|
10958
|
+
const instance = identity.instanceId === undefined ? undefined : this.instances.get(identity.instanceId);
|
|
10959
|
+
if (identity.instanceId !== undefined && !instance)
|
|
10960
|
+
throw new Error('INSTANCE_NOT_FOUND');
|
|
10961
|
+
if (instance && (instance.targetId !== identity.targetId || instance.ownerId !== identity.ownerId))
|
|
10962
|
+
throw new Error('INSTANCE_OWNER_MISMATCH');
|
|
10963
|
+
if (!instance || instance.endedAt === undefined)
|
|
10964
|
+
this.requireTarget(identity.targetId, identity.ownerId);
|
|
10965
|
+
if (!instance && events.some((event) => !event || event.source !== 'host'))
|
|
10966
|
+
throw new Error('RUNTIME_INSTANCE_REQUIRED');
|
|
10967
|
+
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(producerId) || !Number.isSafeInteger(sequence) || sequence < 1)
|
|
10968
|
+
throw new Error('INVALID_SEQUENCE');
|
|
10969
|
+
const key = JSON.stringify([identity.targetId, identity.ownerId]);
|
|
10970
|
+
const previous = this.hostSequences.get(key);
|
|
10971
|
+
if (previous && previous.producerId !== producerId)
|
|
10972
|
+
throw new Error('INVALID_PRODUCER');
|
|
10973
|
+
if (previous && previous.sequence >= sequence)
|
|
10974
|
+
return previous.sequence;
|
|
10975
|
+
for (const event of events)
|
|
10976
|
+
if (event && (event.source === 'host' || event.source === 'runtime'))
|
|
10977
|
+
this.append(event, identity);
|
|
10978
|
+
if (instance)
|
|
10979
|
+
instance.lastCursor = this.cursor;
|
|
10980
|
+
this.hostSequences.set(key, { targetId: identity.targetId, ownerId: identity.ownerId, producerId, sequence });
|
|
10981
|
+
return sequence;
|
|
10982
|
+
}
|
|
10983
|
+
append(event, identity) {
|
|
10984
|
+
if (!event ||
|
|
10985
|
+
!Number.isFinite(event.timestamp) ||
|
|
10986
|
+
typeof event.message !== 'string' ||
|
|
10987
|
+
!['log', 'debug', 'info', 'warn', 'error'].includes(event.level))
|
|
10988
|
+
return;
|
|
10989
|
+
const network = event.network;
|
|
10990
|
+
const interaction = event.source === 'host' ? sanitizeHostInteraction(event.interaction) : undefined;
|
|
10991
|
+
this.logs.push({
|
|
10992
|
+
cursor: ++this.cursor,
|
|
10993
|
+
...identity,
|
|
10994
|
+
...(identity.instanceId && this.instances.has(identity.instanceId)
|
|
10995
|
+
? { targetId: this.instances.get(identity.instanceId).targetId, ownerId: this.instances.get(identity.instanceId).ownerId }
|
|
10996
|
+
: {}),
|
|
10997
|
+
timestamp: event.timestamp,
|
|
10998
|
+
receivedAt: Date.now(),
|
|
10999
|
+
late: Boolean(identity.instanceId && this.instances.get(identity.instanceId)?.endedAt !== undefined),
|
|
11000
|
+
level: event.level,
|
|
11001
|
+
source: event.source,
|
|
11002
|
+
message: safeMessage(event.message),
|
|
11003
|
+
truncated: event.truncated === true || event.message.length > 8192,
|
|
11004
|
+
...(typeof event.phase === 'string' ? { phase: event.phase.slice(0, 100) } : {}),
|
|
11005
|
+
...(typeof event.method === 'string' ? { method: event.method.slice(0, 100) } : {}),
|
|
11006
|
+
...(typeof event.callId === 'string' ? { callId: event.callId.slice(0, 100) } : {}),
|
|
11007
|
+
...(typeof event.errorCode === 'string' && /^[A-Z0-9_]{1,100}$/.test(event.errorCode) ? { errorCode: event.errorCode } : {}),
|
|
11008
|
+
...(['started', 'success', 'error', 'cancelled', 'dropped'].includes(event.outcome ?? '') ? { outcome: event.outcome } : {}),
|
|
11009
|
+
...(Number.isFinite(event.startedAt) ? { startedAt: event.startedAt } : {}),
|
|
11010
|
+
...(Number.isFinite(event.durationMs) ? { durationMs: Math.max(0, event.durationMs) } : {}),
|
|
11011
|
+
...(interaction ? { interaction } : {}),
|
|
11012
|
+
...(network
|
|
11013
|
+
? {
|
|
11014
|
+
network: {
|
|
11015
|
+
...(typeof network.method === 'string' ? { method: network.method.slice(0, 20) } : {}),
|
|
11016
|
+
...(typeof network.origin === 'string' ? { origin: safeMessage(network.origin, 256) } : {}),
|
|
11017
|
+
...(typeof network.pathname === 'string' ? { pathname: safeMessage(network.pathname.split('?')[0], 1024) } : {}),
|
|
11018
|
+
...(Number.isInteger(network.responseStatus) ? { responseStatus: network.responseStatus } : {}),
|
|
11019
|
+
},
|
|
11020
|
+
}
|
|
11021
|
+
: {}),
|
|
11022
|
+
});
|
|
11023
|
+
if (this.logs.length > 5000)
|
|
11024
|
+
this.logs.splice(0, this.logs.length - 5000);
|
|
11025
|
+
}
|
|
11026
|
+
snapshot() {
|
|
11027
|
+
return {
|
|
11028
|
+
schemaVersion: DEV_DIAGNOSTICS_SCHEMA_VERSION,
|
|
11029
|
+
sessionId: this.sessionId,
|
|
11030
|
+
epoch: this.epoch,
|
|
11031
|
+
nextCursor: this.cursor,
|
|
11032
|
+
uploadSessions: [...this.uploadSessions.values()].map(({ id, browser, os, deviceModel, connectedAt, lastSeen }) => ({
|
|
11033
|
+
id,
|
|
11034
|
+
name: [browser, os, deviceModel].filter(Boolean).join(' · '),
|
|
11035
|
+
browser,
|
|
11036
|
+
os,
|
|
11037
|
+
...(deviceModel ? { deviceModel } : {}),
|
|
11038
|
+
connectedAt,
|
|
11039
|
+
lastSeen,
|
|
11040
|
+
online: Date.now() - lastSeen < 15000,
|
|
11041
|
+
})),
|
|
11042
|
+
};
|
|
11043
|
+
}
|
|
11044
|
+
inspect() {
|
|
11045
|
+
const now = Date.now();
|
|
11046
|
+
const targets = [...this.targets.values()].map((target) => this.targetSnapshot(target, now));
|
|
11047
|
+
// 对外保留登记顺序;同毫秒创建、旧实例更新和迟到事件都不会重排,调用方可取最后一次启动尝试。
|
|
11048
|
+
const instances = [...this.instances.values()].map((instance) => this.instanceSnapshot(instance, now));
|
|
11049
|
+
const primaryTarget = targets.find((target) => target.targetId === this.primaryTargetId) ?? null;
|
|
11050
|
+
const currentInstance = instances.find((instance) => instance.instanceId === primaryTarget?.currentInstanceId) ?? null;
|
|
11051
|
+
return {
|
|
11052
|
+
...this.snapshot(),
|
|
11053
|
+
targets,
|
|
11054
|
+
primaryTargetId: this.primaryTargetId ?? null,
|
|
11055
|
+
primaryTarget,
|
|
11056
|
+
timestamp: now,
|
|
11057
|
+
instances,
|
|
11058
|
+
currentInstance,
|
|
11059
|
+
recentFailure: [...this.terminalInstances.keys()]
|
|
11060
|
+
.map((id) => this.instanceSnapshot(this.instances.get(id), now))
|
|
11061
|
+
.filter((instance) => instance.state === 'failed')
|
|
11062
|
+
.at(-1) ?? null,
|
|
11063
|
+
stale: primaryTarget?.stale ?? false,
|
|
11064
|
+
};
|
|
11065
|
+
}
|
|
10454
11066
|
query(params) {
|
|
10455
11067
|
const after = Math.max(0, Number(params.get('after')) || 0);
|
|
10456
11068
|
const limit = Math.min(500, Math.max(1, Number(params.get('limit')) || 100));
|
|
10457
11069
|
const selected = this.logs.filter((log) => log.cursor > after &&
|
|
10458
|
-
(!params.get('
|
|
11070
|
+
(!params.get('uploadSessionId') || log.uploadSessionId === params.get('uploadSessionId')) &&
|
|
11071
|
+
(!params.get('instanceId') || log.instanceId === params.get('instanceId')) &&
|
|
11072
|
+
(!params.get('targetId') || log.targetId === params.get('targetId')) &&
|
|
10459
11073
|
(!params.get('level') || log.level === params.get('level')) &&
|
|
10460
|
-
(
|
|
11074
|
+
(params.get('problems') !== 'true' || log.level === 'warn' || log.level === 'error') &&
|
|
11075
|
+
(!params.get('phase') || log.phase === params.get('phase')) &&
|
|
11076
|
+
(!params.get('source') ||
|
|
11077
|
+
(params.get('source') === 'network'
|
|
11078
|
+
? (log.source === 'sdk' || log.source === 'host') && (Boolean(log.network) || log.method === 'network.request')
|
|
11079
|
+
: log.source === params.get('source'))) &&
|
|
10461
11080
|
(!params.get('callId') || log.callId === params.get('callId')) &&
|
|
10462
11081
|
(!params.get('id') || String(log.cursor) === params.get('id')) &&
|
|
10463
11082
|
(!params.get('since') || log.timestamp >= Number(params.get('since'))) &&
|
|
10464
|
-
(!params.get('query') ||
|
|
11083
|
+
(!params.get('query') ||
|
|
11084
|
+
[log.message, log.method, log.errorCode, log.network?.method, log.network?.origin, log.network?.pathname, log.network?.responseStatus, log.interaction?.interactionId, log.interaction?.kind, log.interaction?.state]
|
|
11085
|
+
.filter((value) => value !== undefined)
|
|
11086
|
+
.join(' ')
|
|
11087
|
+
.toLowerCase()
|
|
11088
|
+
.includes(params.get('query').toLowerCase())));
|
|
10465
11089
|
const items = selected.slice(0, limit);
|
|
10466
11090
|
return {
|
|
10467
|
-
|
|
10468
|
-
epoch: this.epoch,
|
|
11091
|
+
...this.snapshot(),
|
|
10469
11092
|
items,
|
|
10470
11093
|
nextCursor: selected.length > limit ? items.at(-1).cursor : this.cursor,
|
|
10471
11094
|
hasMore: selected.length > limit,
|
|
10472
11095
|
gap: after > 0 && after < (this.logs[0]?.cursor ?? 1) - 1,
|
|
10473
|
-
devices: [...this.devices.values()].map(({ id, name, platform, connectedAt, lastSeen }) => ({
|
|
10474
|
-
id,
|
|
10475
|
-
name,
|
|
10476
|
-
platform,
|
|
10477
|
-
connectedAt,
|
|
10478
|
-
lastSeen,
|
|
10479
|
-
online: Date.now() - lastSeen < 15000,
|
|
10480
|
-
})),
|
|
10481
11096
|
};
|
|
10482
11097
|
}
|
|
11098
|
+
resourceError(task, code, error = code) {
|
|
11099
|
+
const instance = this.instances.get(task.instanceId);
|
|
11100
|
+
const reason = instance?.reason ?? instance?.error?.code;
|
|
11101
|
+
return {
|
|
11102
|
+
instanceId: task.instanceId,
|
|
11103
|
+
requestId: task.requestId,
|
|
11104
|
+
resource: task.resource,
|
|
11105
|
+
timestamp: Date.now(),
|
|
11106
|
+
stale: instance ? this.instanceSnapshot(instance).stale : false,
|
|
11107
|
+
...(instance ? {
|
|
11108
|
+
lastKnownState: instance.state,
|
|
11109
|
+
lastSeenAt: this.targets.get(instance.targetId)?.updatedAt ?? instance.updatedAt,
|
|
11110
|
+
...(reason ? { reason } : {}),
|
|
11111
|
+
} : {}),
|
|
11112
|
+
code,
|
|
11113
|
+
error,
|
|
11114
|
+
};
|
|
11115
|
+
}
|
|
11116
|
+
ownsInstance(instanceId, targetId, ownerId) {
|
|
11117
|
+
const instance = this.instances.get(instanceId);
|
|
11118
|
+
return instance?.targetId === targetId && instance.ownerId === ownerId;
|
|
11119
|
+
}
|
|
11120
|
+
closeAdapter(adapterId, reason = 'adapter closed') {
|
|
11121
|
+
for (const target of this.targets.values())
|
|
11122
|
+
if (target.adapterId === adapterId && target.state !== 'closed')
|
|
11123
|
+
this.closeTarget(target.targetId, target.ownerId, reason);
|
|
11124
|
+
}
|
|
11125
|
+
queryResource(instanceId, resource, path, signal, options = {}) {
|
|
11126
|
+
const task = {
|
|
11127
|
+
requestId: randomUUID(),
|
|
11128
|
+
instanceId,
|
|
11129
|
+
resource,
|
|
11130
|
+
path,
|
|
11131
|
+
deadline: Date.now() + 10000,
|
|
11132
|
+
...(resource === 'sandbox'
|
|
11133
|
+
? {
|
|
11134
|
+
operation: options.operation ?? 'list',
|
|
11135
|
+
...(options.operation === 'read' ? { maxBytes: options.maxBytes ?? DEV_SANDBOX_READ_MAX_BYTES } : {}),
|
|
11136
|
+
}
|
|
11137
|
+
: {}),
|
|
11138
|
+
};
|
|
11139
|
+
if (path !== undefined && (typeof path !== 'string' || !path || path.length > 1024))
|
|
11140
|
+
return Promise.resolve(this.resourceError(task, 'invalid'));
|
|
11141
|
+
const instance = this.instances.get(instanceId);
|
|
11142
|
+
if (!instance)
|
|
11143
|
+
return Promise.resolve(this.resourceError(task, 'invalid', 'RUNTIME_INSTANCE_NOT_FOUND'));
|
|
11144
|
+
if (instance.endedAt !== undefined)
|
|
11145
|
+
return Promise.resolve(this.resourceError(task, 'closed', 'RUNTIME_INSTANCE_CLOSED'));
|
|
11146
|
+
if (this.instanceSnapshot(instance).stale)
|
|
11147
|
+
return Promise.resolve(this.resourceError(task, 'offline', 'HOST_UNRESPONSIVE'));
|
|
11148
|
+
if (task.operation === 'read' && (!Number.isSafeInteger(task.maxBytes) || task.maxBytes < 1 || task.maxBytes > DEV_SANDBOX_READ_MAX_BYTES))
|
|
11149
|
+
return Promise.resolve(this.resourceError(task, 'invalid'));
|
|
11150
|
+
if (resource === 'sandbox' && !(task.operation === 'read' ? instance.capabilities.sandboxRead : instance.capabilities.sandboxList))
|
|
11151
|
+
return Promise.resolve(this.resourceError(task, 'unsupported'));
|
|
11152
|
+
if (resource === 'presentation' && !instance.capabilities.presentation)
|
|
11153
|
+
return Promise.resolve(this.resourceError(task, 'unsupported'));
|
|
11154
|
+
if (resource === 'storage' && !instance.capabilities.storage)
|
|
11155
|
+
return Promise.resolve(this.resourceError(task, 'unsupported'));
|
|
11156
|
+
if (this.pending.size >= 64)
|
|
11157
|
+
return Promise.resolve(this.resourceError(task, 'busy'));
|
|
11158
|
+
return new Promise((resolve) => {
|
|
11159
|
+
const abort = () => finish(this.resourceError(task, 'closed', 'RESOURCE_QUERY_CANCELLED'));
|
|
11160
|
+
const timer = setTimeout(() => finish(this.resourceError(task, 'timeout', 'RESOURCE_QUERY_TIMEOUT')), 10000);
|
|
11161
|
+
const finish = (value) => {
|
|
11162
|
+
clearTimeout(timer);
|
|
11163
|
+
signal?.removeEventListener('abort', abort);
|
|
11164
|
+
this.pending.delete(task.requestId);
|
|
11165
|
+
resolve(value);
|
|
11166
|
+
};
|
|
11167
|
+
this.pending.set(task.requestId, { task, resolve: finish });
|
|
11168
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
11169
|
+
if (signal?.aborted)
|
|
11170
|
+
abort();
|
|
11171
|
+
});
|
|
11172
|
+
}
|
|
11173
|
+
pollResources(targetId, ownerId) {
|
|
11174
|
+
const target = this.requireTarget(targetId, ownerId);
|
|
11175
|
+
target.updatedAt = Date.now();
|
|
11176
|
+
const tasks = [];
|
|
11177
|
+
// 原生通道最多接收 64 KiB,按实际 JSON UTF-8 字节预留一半预算,不能按字符数猜大小。
|
|
11178
|
+
for (const pending of [...this.pending.values()]) {
|
|
11179
|
+
if (this.instances.get(pending.task.instanceId)?.targetId !== targetId || this.instances.get(pending.task.instanceId)?.ownerId !== ownerId)
|
|
11180
|
+
continue;
|
|
11181
|
+
if (Buffer.byteLength(JSON.stringify({ tasks: [...tasks, pending.task] })) > 32 * 1024)
|
|
11182
|
+
break;
|
|
11183
|
+
tasks.push(pending.task);
|
|
11184
|
+
// 轮转已发送项;慢查询和响应丢失不会饿死下一批,调用方按 requestId 去重。
|
|
11185
|
+
this.pending.delete(pending.task.requestId);
|
|
11186
|
+
this.pending.set(pending.task.requestId, pending);
|
|
11187
|
+
}
|
|
11188
|
+
return { tasks };
|
|
11189
|
+
}
|
|
11190
|
+
completeResource(requestId, instanceId, result) {
|
|
11191
|
+
const pending = this.pending.get(requestId);
|
|
11192
|
+
if (!pending || pending.task.instanceId !== instanceId)
|
|
11193
|
+
return false;
|
|
11194
|
+
if (pending.task.resource === 'sandbox' && pending.task.operation === 'read' && result.code === undefined) {
|
|
11195
|
+
const file = result.value;
|
|
11196
|
+
const maxBytes = pending.task.maxBytes;
|
|
11197
|
+
if (!file ||
|
|
11198
|
+
file.encoding !== 'base64' ||
|
|
11199
|
+
typeof file.data !== 'string' ||
|
|
11200
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data) ||
|
|
11201
|
+
typeof file.byteLength !== 'number' ||
|
|
11202
|
+
!Number.isSafeInteger(file.byteLength) ||
|
|
11203
|
+
file.byteLength < 0 ||
|
|
11204
|
+
file.byteLength > maxBytes ||
|
|
11205
|
+
Buffer.byteLength(file.data, 'base64') !== file.byteLength ||
|
|
11206
|
+
typeof file.truncated !== 'boolean') {
|
|
11207
|
+
pending.resolve(this.resourceError(pending.task, 'invalid'));
|
|
11208
|
+
return false;
|
|
11209
|
+
}
|
|
11210
|
+
}
|
|
11211
|
+
if (pending.task.resource === 'presentation') {
|
|
11212
|
+
if (result.code !== undefined) {
|
|
11213
|
+
// 错误只返回状态与受限原因,不允许 value 绕过呈现白名单。
|
|
11214
|
+
result = { code: result.code, error: result.error };
|
|
11215
|
+
}
|
|
11216
|
+
else {
|
|
11217
|
+
const snapshot = result.value;
|
|
11218
|
+
if (!snapshot || snapshot.instanceId !== instanceId || !Array.isArray(snapshot.interactions) || snapshot.interactions.length > DEV_PRESENTATION_MAX_INTERACTIONS) {
|
|
11219
|
+
pending.resolve(this.resourceError(pending.task, 'invalid'));
|
|
11220
|
+
return false;
|
|
11221
|
+
}
|
|
11222
|
+
const interactions = snapshot.interactions.map(sanitizeHostInteractionSnapshot);
|
|
11223
|
+
if (interactions.some(item => item === undefined)) {
|
|
11224
|
+
pending.resolve(this.resourceError(pending.task, 'invalid'));
|
|
11225
|
+
return false;
|
|
11226
|
+
}
|
|
11227
|
+
result = { ...result, value: { instanceId, interactions } };
|
|
11228
|
+
}
|
|
11229
|
+
}
|
|
11230
|
+
const serialized = JSON.stringify(result.value);
|
|
11231
|
+
if (serialized && Buffer.byteLength(serialized) > 65536) {
|
|
11232
|
+
pending.resolve(this.resourceError(pending.task, 'invalid'));
|
|
11233
|
+
return false;
|
|
11234
|
+
}
|
|
11235
|
+
const codes = ['unsupported', 'forbidden', 'offline', 'closed', 'timeout', 'busy', 'invalid'];
|
|
11236
|
+
if (result.code !== undefined && !codes.includes(result.code)) {
|
|
11237
|
+
pending.resolve(this.resourceError(pending.task, 'invalid'));
|
|
11238
|
+
return false;
|
|
11239
|
+
}
|
|
11240
|
+
pending.resolve({
|
|
11241
|
+
instanceId,
|
|
11242
|
+
requestId,
|
|
11243
|
+
resource: pending.task.resource,
|
|
11244
|
+
timestamp: Date.now(),
|
|
11245
|
+
stale: false,
|
|
11246
|
+
...(result.value === undefined ? {} : { value: result.value }),
|
|
11247
|
+
...(result.code === undefined ? {} : { code: result.code }),
|
|
11248
|
+
...(typeof result.error === 'string' ? { error: safeMessage(result.error, 2048) } : {}),
|
|
11249
|
+
});
|
|
11250
|
+
return true;
|
|
11251
|
+
}
|
|
10483
11252
|
async upload(req, res) {
|
|
10484
11253
|
const reply = (status, value) => {
|
|
10485
11254
|
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
@@ -10510,34 +11279,42 @@ class DeviceLogStore {
|
|
|
10510
11279
|
return;
|
|
10511
11280
|
}
|
|
10512
11281
|
const registrationId = typeof body.registrationId === 'string' && /^[a-f0-9]{32}$/.test(body.registrationId) ? body.registrationId : undefined;
|
|
10513
|
-
const existing = registrationId && [...this.
|
|
11282
|
+
const existing = registrationId && [...this.uploadSessions.values()].find((device) => device.registrationId === registrationId);
|
|
10514
11283
|
if (existing) {
|
|
10515
11284
|
reply(200, { id: existing.id, token: existing.token });
|
|
10516
11285
|
return;
|
|
10517
11286
|
}
|
|
10518
|
-
if (this.
|
|
10519
|
-
|
|
10520
|
-
|
|
11287
|
+
if (this.uploadSessions.size >= 64) {
|
|
11288
|
+
const offline = [...this.uploadSessions.values()].find((device) => Date.now() - device.lastSeen >= 15000);
|
|
11289
|
+
if (offline)
|
|
11290
|
+
this.uploadSessions.delete(offline.id);
|
|
11291
|
+
else {
|
|
11292
|
+
reply(429, {});
|
|
11293
|
+
return;
|
|
11294
|
+
}
|
|
10521
11295
|
}
|
|
10522
|
-
const id = randomUUID();
|
|
10523
|
-
const
|
|
11296
|
+
const id = randomUUID(), now = Date.now();
|
|
11297
|
+
const browser = ['Chrome', 'Edge', 'Firefox', 'Safari', 'WebView'].includes(body.browser) ? body.browser : 'Other';
|
|
11298
|
+
const os = ['iOS', 'Android', 'Windows', 'macOS', 'Linux'].includes(body.os) ? body.os : 'Other';
|
|
11299
|
+
const deviceModel = typeof body.deviceModel === 'string' ? safeMessage(body.deviceModel, 100) : undefined;
|
|
10524
11300
|
const device = {
|
|
10525
11301
|
id,
|
|
10526
|
-
|
|
11302
|
+
browser,
|
|
11303
|
+
os,
|
|
11304
|
+
deviceModel,
|
|
10527
11305
|
registrationId,
|
|
10528
|
-
connectedAt:
|
|
10529
|
-
|
|
10530
|
-
lastSeen: Date.now(),
|
|
11306
|
+
connectedAt: now,
|
|
11307
|
+
lastSeen: now,
|
|
10531
11308
|
sequence: 0,
|
|
10532
11309
|
token: randomBytes(32).toString('hex'),
|
|
10533
|
-
windowStart:
|
|
11310
|
+
windowStart: now,
|
|
10534
11311
|
count: 0,
|
|
10535
11312
|
};
|
|
10536
|
-
this.
|
|
11313
|
+
this.uploadSessions.set(id, device);
|
|
10537
11314
|
reply(200, { id, token: device.token });
|
|
10538
11315
|
return;
|
|
10539
11316
|
}
|
|
10540
|
-
const device = this.
|
|
11317
|
+
const device = this.uploadSessions.get(body.id);
|
|
10541
11318
|
if (!device || req.headers['x-hb-log-token'] !== device.token) {
|
|
10542
11319
|
reply(403, {});
|
|
10543
11320
|
return;
|
|
@@ -10556,46 +11333,24 @@ class DeviceLogStore {
|
|
|
10556
11333
|
}
|
|
10557
11334
|
device.count += body.logs.length;
|
|
10558
11335
|
device.lastSeen = Date.now();
|
|
10559
|
-
|
|
10560
|
-
const result = body.sandboxResult;
|
|
10561
|
-
const pending = this.sandboxRequests.get(result.requestId);
|
|
10562
|
-
if (pending?.id === device.id) {
|
|
10563
|
-
const entries = Array.isArray(result.entries) ? result.entries.slice(0, 200).filter((entry) => entry && ['file', 'directory'].includes(entry.kind) && typeof entry.name === 'string' && entry.name.length <= 255 && !/[\\\\/\u0000-\u001f]/.test(entry.name) && !['.', '..'].includes(entry.name)).map((entry) => ({ name: entry.name, kind: entry.kind })) : [];
|
|
10564
|
-
pending.resolve({ deviceSessionId: device.id, requestId: pending.requestId, path: pending.path, timestamp: Date.now(), entries, error: result.error ? '设备不支持或无权读取此目录' : undefined, truncated: result.truncated === true });
|
|
10565
|
-
}
|
|
10566
|
-
}
|
|
11336
|
+
const instance = device.instanceId ? this.instances.get(device.instanceId) : undefined;
|
|
10567
11337
|
for (const log of body.logs) {
|
|
10568
|
-
if (!log ||
|
|
10569
|
-
continue;
|
|
10570
|
-
if (!Number.isSafeInteger(log.sequence) ||
|
|
10571
|
-
log.sequence <= device.sequence ||
|
|
10572
|
-
!Number.isFinite(log.timestamp) ||
|
|
10573
|
-
!['log', 'debug', 'info', 'warn', 'error'].includes(log.level) ||
|
|
10574
|
-
typeof log.message !== 'string')
|
|
11338
|
+
if (!log || !Number.isSafeInteger(log.sequence) || log.sequence <= device.sequence)
|
|
10575
11339
|
continue;
|
|
11340
|
+
if (log.sequence > device.sequence + 1)
|
|
11341
|
+
this.append({
|
|
11342
|
+
source: 'app',
|
|
11343
|
+
level: 'warn',
|
|
11344
|
+
message: `上传序号缺口:${device.sequence + 1}–${log.sequence - 1}`,
|
|
11345
|
+
timestamp: Date.now(),
|
|
11346
|
+
truncated: true,
|
|
11347
|
+
}, { uploadSessionId: device.id, ...(instance ? { instanceId: instance.instanceId } : {}) });
|
|
10576
11348
|
device.sequence = log.sequence;
|
|
10577
|
-
this.
|
|
10578
|
-
cursor: ++this.cursor,
|
|
10579
|
-
deviceSessionId: device.id,
|
|
10580
|
-
sequence: log.sequence,
|
|
10581
|
-
timestamp: log.timestamp,
|
|
10582
|
-
receivedAt: Date.now(),
|
|
10583
|
-
level: log.level,
|
|
10584
|
-
source: log.source === 'sdk' ? 'sdk' : 'app',
|
|
10585
|
-
message: sanitizeDiagnosticMessage(log.message)
|
|
10586
|
-
.replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)(["'\s:=]+)([^\s,}]+)/gi, '$1$2[redacted]')
|
|
10587
|
-
.slice(0, 8192),
|
|
10588
|
-
truncated: log.truncated === true || log.message.length > 8192,
|
|
10589
|
-
...(typeof log.method === 'string' ? { method: log.method.slice(0, 100) } : {}),
|
|
10590
|
-
...(typeof log.callId === 'string' ? { callId: log.callId.slice(0, 100) } : {}),
|
|
10591
|
-
...(typeof log.errorCode === 'string' && /^[A-Z0-9_]{1,100}$/.test(log.errorCode) ? { errorCode: log.errorCode } : {}),
|
|
10592
|
-
...(log.outcome === 'success' || log.outcome === 'error' ? { outcome: log.outcome } : {}),
|
|
10593
|
-
...(Number.isFinite(log.durationMs) ? { durationMs: Math.max(0, log.durationMs) } : {}),
|
|
10594
|
-
});
|
|
11349
|
+
this.append({ ...log, source: log.source === 'sdk' ? 'sdk' : 'app', phase: log.source === 'sdk' ? 'client' : undefined }, { uploadSessionId: device.id, sequence: log.sequence, ...(instance ? { instanceId: instance.instanceId } : {}) });
|
|
10595
11350
|
}
|
|
10596
|
-
if (
|
|
10597
|
-
|
|
10598
|
-
reply(200, { sequence: device.sequence
|
|
11351
|
+
if (instance)
|
|
11352
|
+
instance.lastCursor = this.cursor;
|
|
11353
|
+
reply(200, { sequence: device.sequence });
|
|
10599
11354
|
}
|
|
10600
11355
|
catch {
|
|
10601
11356
|
reply(400, { code: 'INVALID_LOG_BATCH' });
|
|
@@ -10606,11 +11361,15 @@ class DeviceLogStore {
|
|
|
10606
11361
|
function deviceLogBootstrap(token) {
|
|
10607
11362
|
return `<script>(function(){if(window.__hb_sdk_device_logs_installed__)return;
|
|
10608
11363
|
window.__hb_sdk_device_logs_installed__=true;
|
|
10609
|
-
|
|
10610
|
-
var endpoint='${DEVICE_LOG_PATH}',credential='${token}',id='',queue=[],seq=0,busy=false,dropped=0,retryDelay=1000;
|
|
11364
|
+
var endpoint='${DEVICE_LOG_PATH}',registrationCredential='${token}',credential=registrationCredential,id='',queue=[],seq=0,busy=false,dropped=0,retryDelay=1000;
|
|
10611
11365
|
var registrationId=Array.from(crypto.getRandomValues(new Uint8Array(16)),function(n){return n.toString(16).padStart(2,'0')}).join('');
|
|
11366
|
+
function documentSignal(phase){if(window.parent===window)return;
|
|
11367
|
+
var navigation=performance.getEntriesByType('navigation')[0];
|
|
11368
|
+
window.parent.postMessage({type:'hb-sdk:dev-document',phase:phase,documentId:registrationId,href:location.href,nonce:new URL(location.href).searchParams.get('hb_mini_bridge_nonce'),navigationType:navigation?navigation.type:'navigate'},'*')}
|
|
11369
|
+
documentSignal('boot');
|
|
11370
|
+
window.addEventListener('pagehide',function(){documentSignal('leaving')});
|
|
11371
|
+
window.addEventListener('pageshow',function(){documentSignal('boot')});
|
|
10612
11372
|
var send=window.fetch.bind(window);
|
|
10613
|
-
var sandboxResult;
|
|
10614
11373
|
function format(v){try{return typeof v==='string'?v:v instanceof Error?v.stack||v.message:JSON.stringify(v,function(k,value){return /authorization|cookie|password|secret|token|pkey|api.?key/i.test(k)?'[redacted]':value})}catch(e){return '[无法序列化]'}}function add(level,args,source){if(queue.length>=500){queue.shift();
|
|
10615
11374
|
dropped++}var message=args.map(format).join(' ');
|
|
10616
11375
|
message=message.replace(/https?:\\/\\/[^\\s]+/g,function(raw){try{var url=new URL(raw);
|
|
@@ -10620,29 +11379,32 @@ url.search='';
|
|
|
10620
11379
|
url.hash='';
|
|
10621
11380
|
return url.href}catch(e){return '[URL]'}});
|
|
10622
11381
|
message=message.replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\\"'\\s:=]+)([^\\s,}]+)/gi,'$1$2[redacted]');
|
|
10623
|
-
queue.push({truncated:message.length>8192,sequence:++seq,timestamp:Date.now(),level:level,source:source||'app',message:message.slice(0,8192)})}window.
|
|
10624
|
-
|
|
11382
|
+
queue.push({truncated:message.length>8192,sequence:++seq,timestamp:Date.now(),level:level,source:source||'app',message:message.slice(0,8192)})}window.__hbSdkDevObserver=function(event){add(event.outcome==='error'?'error':'info',[event.method+' · '+event.outcome+' · '+event.durationMs+' ms'],'sdk');
|
|
11383
|
+
var entry=queue[queue.length-1];['phase','method','callId','outcome','durationMs','errorCode','timestamp','startedAt'].forEach(function(key){if(event[key]!==undefined)entry[key]=event[key]})};
|
|
10625
11384
|
['log','debug','info','warn','error'].forEach(function(level){var original=console[level];
|
|
10626
11385
|
console[level]=function(){add(level,Array.prototype.slice.call(arguments));
|
|
10627
11386
|
return original.apply(this,arguments)}});
|
|
10628
|
-
window.addEventListener('error',function(e){add('error',[e.message])});
|
|
11387
|
+
window.addEventListener('error',function(e){add('error',[e.error||e.message])});
|
|
10629
11388
|
window.addEventListener('unhandledrejection',function(e){add('error',[e.reason])});
|
|
10630
11389
|
async function flush(){if(busy)return;
|
|
10631
11390
|
busy=true;
|
|
10632
11391
|
var success=false;
|
|
10633
11392
|
try{if(!id){var ua=navigator.userAgent;
|
|
10634
|
-
var
|
|
10635
|
-
var
|
|
11393
|
+
var browser=/Edg\\//.test(ua)?'Edge':/Chrome|CriOS/.test(ua)?'Chrome':/Firefox|FxiOS/.test(ua)?'Firefox':/Safari/.test(ua)?'Safari':'Other';
|
|
11394
|
+
var os=/Android/.test(ua)?'Android':/iPhone|iPad/.test(ua)?'iOS':/Windows/.test(ua)?'Windows':/Mac/.test(ua)?'macOS':/Linux/.test(ua)?'Linux':'Other';
|
|
11395
|
+
var model=navigator.userAgentData&&navigator.userAgentData.model;
|
|
11396
|
+
var r=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({register:true,browser:browser,os:os,deviceModel:typeof model==='string'?model.slice(0,100):undefined,registrationId:registrationId}),signal:AbortSignal.timeout(5000)});
|
|
10636
11397
|
if(!r.ok)throw 0;
|
|
10637
11398
|
var d=await r.json();
|
|
10638
|
-
id=d.id;
|
|
11399
|
+
id=d.id;document.documentElement.dataset.hbSdkDeviceSessionId=id;
|
|
11400
|
+
if(window.parent!==window)window.parent.postMessage({type:'hb-sdk:dev-upload-session',deviceSessionId:id},'*');
|
|
10639
11401
|
credential=d.token}if(dropped){add('warn',['日志缓冲已丢弃 '+dropped+' 条']);
|
|
10640
11402
|
dropped=0}var batch=queue.slice(0,50);
|
|
10641
11403
|
while(batch.length>1&&new TextEncoder().encode(JSON.stringify(batch)).length>48000)batch.pop();
|
|
10642
|
-
var result=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({id:id,logs:batch
|
|
11404
|
+
var result=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({id:id,logs:batch}),signal:AbortSignal.timeout(5000)});
|
|
11405
|
+
if(result.status===403){id='';credential=registrationCredential;throw 0}
|
|
10643
11406
|
if(!result.ok)throw 0;
|
|
10644
|
-
var ack=await result.json();
|
|
10645
|
-
if(ack.sandboxRequest){try{var entries=await window.__hbSdkSandboxList(ack.sandboxRequest.path);sandboxResult={requestId:ack.sandboxRequest.requestId,entries:entries.slice(0,200),truncated:entries.length>200}}catch(e){sandboxResult={requestId:ack.sandboxRequest.requestId,error:true}}}
|
|
11407
|
+
var ack=await result.json();
|
|
10646
11408
|
queue=queue.filter(function(l){return l.sequence>ack.sequence});success=true}catch(e){}finally{retryDelay=success?1000:Math.min(retryDelay*2,30000);busy=false;setTimeout(flush,retryDelay)}}
|
|
10647
11409
|
flush()})();
|
|
10648
11410
|
</script>`;
|
|
@@ -20359,9 +21121,12 @@ function enforceMiniappHtmlPolicy(html, options = {}) {
|
|
|
20359
21121
|
...(options.hmrWebSocketUrls ?? []),
|
|
20360
21122
|
...(options.deviceLogUploadUrls ?? []),
|
|
20361
21123
|
].filter((source) => Boolean(source))));
|
|
20362
|
-
|
|
21124
|
+
let content = connectSources.length > 0
|
|
20363
21125
|
? PRODUCTION_CSP.replace("connect-src 'none'", `connect-src ${connectSources.join(' ')}`)
|
|
20364
21126
|
: PRODUCTION_CSP;
|
|
21127
|
+
// Vite 8 通过 Blob SharedWorker 等待 HMR 重连;只在显式开发 WS 入口存在时放行。
|
|
21128
|
+
if (options.hmrWebSocketUrls?.length)
|
|
21129
|
+
content = content.replace("worker-src 'none'", 'worker-src blob:');
|
|
20365
21130
|
head.childNodes.unshift({
|
|
20366
21131
|
nodeName: 'meta',
|
|
20367
21132
|
tagName: 'meta',
|
|
@@ -20553,29 +21318,8 @@ function assertMiniappBuildCompiler(esbuild) {
|
|
|
20553
21318
|
}
|
|
20554
21319
|
}
|
|
20555
21320
|
|
|
20556
|
-
/**
|
|
20557
|
-
* dev serve 时在入口 HTML 最早位置注入无依赖 console 捕获 bootstrap。
|
|
20558
|
-
*
|
|
20559
|
-
* 必须内联完整 patch 逻辑而非等 SDK 模块加载:vite client、业务代码的 console 调用
|
|
20560
|
-
* 都可能早于 SDK 单例初始化(如 [vite] connecting)。捕获条件:
|
|
20561
|
-
* 1. 构建期只有 vite serve 走到本分支(生产构建无此代码,双保险之 define 常量仍注入给 SDK 侧);
|
|
20562
|
-
* 2. 运行期仅调试 iframe(window.name 标记由调试台 iframe.name 与本 bootstrap 设置)激活。
|
|
20563
|
-
* 转发经 window.parent.postMessage(CSP connect-src 不约束 postMessage),失败静默,
|
|
20564
|
-
* 严禁回打 console 造成自触发循环。SDK 侧 installMiniDevConsoleForwarding 安装时
|
|
20565
|
-
* 检测同款 INSTALL_FLAG,不会重复 patch。
|
|
20566
|
-
*/
|
|
20567
|
-
function injectMiniDevConsoleBootstrap(html) {
|
|
20568
|
-
const bootstrap = `<script>(function(){var LEVELS=['log','debug','info','warn','error'];var FLAG='${MINI_DEV_CONSOLE_INSTALL_FLAG}';var TYPE='${MINI_DEV_CONSOLE_EVENT_TYPE}';if(window[FLAG])return;var patched=false;for(var i=0;i<LEVELS.length;i++)(function(level){var original=console[level];if(typeof original!=='function')return;console[level]=function(){try{parent.postMessage({type:TYPE,detail:{level:level,args:Array.prototype.slice.call(arguments),timestamp:Date.now()}},'*')}catch(e){}return original.apply(this,arguments)};patched=true})(LEVELS[i]);if(patched)window[FLAG]=true})();</script>`;
|
|
20569
|
-
const headIndex = html.indexOf('<head>');
|
|
20570
|
-
if (headIndex < 0) {
|
|
20571
|
-
return html;
|
|
20572
|
-
}
|
|
20573
|
-
const insertAt = headIndex + '<head>'.length;
|
|
20574
|
-
return `${html.slice(0, insertAt)}${bootstrap}${html.slice(insertAt)}`;
|
|
20575
|
-
}
|
|
20576
21321
|
const sdkVersionPlaceholder = ['__HB_SDK', 'VERSION__'].join('_');
|
|
20577
21322
|
const sdkVersionBuildConstant = ['__HB_SDK_BUILD', 'VERSION__'].join('_');
|
|
20578
|
-
const miniDevLoggingConstant = ['__HB_SDK_DEV', 'LOGGING__'].join('_');
|
|
20579
21323
|
const DEV_MANIFEST_PATH = '/__hb_sdk__/companion/manifest.json';
|
|
20580
21324
|
/**
|
|
20581
21325
|
* 本地 PC 调试开窗时的 manifest 入口。
|
|
@@ -20622,6 +21366,10 @@ if (!devSnapshotRegistry[devSnapshotStoreKey]) {
|
|
|
20622
21366
|
});
|
|
20623
21367
|
}
|
|
20624
21368
|
const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
|
|
21369
|
+
// 配置重载沿当前 server 的异步调用链传递 owner;同项目的另一台 dev 不共享记录。
|
|
21370
|
+
const diagnosticsOwnerKey = Symbol.for('@heybox/hb-sdk/vite-diagnostics-owner');
|
|
21371
|
+
const diagnosticsOwnerRegistry = globalThis;
|
|
21372
|
+
const diagnosticsOwner = (diagnosticsOwnerRegistry[diagnosticsOwnerKey] ??= new AsyncLocalStorage());
|
|
20625
21373
|
/**
|
|
20626
21374
|
* 创建工坊小程序使用的 Vite 插件。
|
|
20627
21375
|
*
|
|
@@ -20735,7 +21483,11 @@ const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
|
|
|
20735
21483
|
*/
|
|
20736
21484
|
function miniappManifest() {
|
|
20737
21485
|
const includeCompanions = process.env.HB_SDK_SKIP_COMPANIONS !== '1';
|
|
20738
|
-
const
|
|
21486
|
+
const diagnosticsSessionId = process.env.HB_SDK_DEV_DIAGNOSTICS_SESSION_ID;
|
|
21487
|
+
const managedDiagnostics = diagnosticsSessionId ? getDevDiagnosticsSession(diagnosticsSessionId) : undefined;
|
|
21488
|
+
if (diagnosticsSessionId && !managedDiagnostics)
|
|
21489
|
+
throw new Error('指定的开发诊断会话不存在,请通过 hb-sdk dev 重新启动服务');
|
|
21490
|
+
const deviceLogs = managedDiagnostics ?? diagnosticsOwner.getStore() ?? new DeviceLogStore();
|
|
20739
21491
|
const skipPlatformCsp = shouldSkipMiniappPlatformCspFromEnv();
|
|
20740
21492
|
let companionArtifactAccessToken = parseDevAccessToken(process.env[HB_SDK_COMPANION_ARTIFACT_ACCESS_TOKEN_ENV]);
|
|
20741
21493
|
let miniProgramManifestAccessToken = parseDevAccessToken(process.env[HB_SDK_MINI_PROGRAM_MANIFEST_ACCESS_TOKEN_ENV]);
|
|
@@ -20771,8 +21523,6 @@ function miniappManifest() {
|
|
|
20771
21523
|
...(buildTargets ? { build: { target: buildTargets } } : {}),
|
|
20772
21524
|
define: {
|
|
20773
21525
|
[sdkVersionBuildConstant]: JSON.stringify(resolveSdkVersion()),
|
|
20774
|
-
// 仅 vite serve(hb-sdk dev)注入;vite build / hb-sdk build 永不注入,捕获模块被死代码消除。
|
|
20775
|
-
...(isServe ? { [miniDevLoggingConstant]: 'true' } : {}),
|
|
20776
21526
|
},
|
|
20777
21527
|
};
|
|
20778
21528
|
},
|
|
@@ -20828,16 +21578,6 @@ function miniappManifest() {
|
|
|
20828
21578
|
server.config.logger.warn(`[${warning.code}] ${warning.message}`);
|
|
20829
21579
|
metadataWarningsShown = true;
|
|
20830
21580
|
}
|
|
20831
|
-
let unregisterLogs;
|
|
20832
|
-
const registerLogs = () => {
|
|
20833
|
-
const address = server.httpServer?.address();
|
|
20834
|
-
if (address && typeof address !== 'string')
|
|
20835
|
-
unregisterLogs = registerDeviceLogs(address.port, deviceLogs);
|
|
20836
|
-
};
|
|
20837
|
-
server.httpServer?.once('listening', registerLogs);
|
|
20838
|
-
server.httpServer?.once('close', () => unregisterLogs?.());
|
|
20839
|
-
if (server.httpServer?.listening)
|
|
20840
|
-
registerLogs();
|
|
20841
21581
|
let store = devSnapshotStores.get(root);
|
|
20842
21582
|
companionArtifactAccessToken ??= store?.token;
|
|
20843
21583
|
// 与 Companion 令牌同因:配置重载时 env 已不在,只能从同一服务的注册表恢复。
|
|
@@ -20857,7 +21597,7 @@ function miniappManifest() {
|
|
|
20857
21597
|
server.restart = async (forceOptimize) => {
|
|
20858
21598
|
store.restarting = true;
|
|
20859
21599
|
try {
|
|
20860
|
-
await restart(forceOptimize);
|
|
21600
|
+
await diagnosticsOwner.run(deviceLogs, () => restart(forceOptimize));
|
|
20861
21601
|
}
|
|
20862
21602
|
finally {
|
|
20863
21603
|
store.restarting = false;
|
|
@@ -21124,9 +21864,7 @@ function miniappManifest() {
|
|
|
21124
21864
|
: {}),
|
|
21125
21865
|
skipPlatformCsp,
|
|
21126
21866
|
});
|
|
21127
|
-
return command === 'serve'
|
|
21128
|
-
? injectMiniDevConsoleBootstrap(enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`))
|
|
21129
|
-
: enforced;
|
|
21867
|
+
return command === 'serve' ? enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`) : enforced;
|
|
21130
21868
|
},
|
|
21131
21869
|
async closeBundle() {
|
|
21132
21870
|
// Vite dev 的关闭/配置重载同样会触发此钩子,不执行发布打包。
|