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