@heybox/hb-sdk 0.9.6-alpha.1 → 0.9.6-alpha.11

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +86 -5
  2. package/README.md +37 -557
  3. package/dist/cli-chunks/{artifact-C5n7xjnz.cjs → artifact-BW6SD1G6.cjs} +3 -3
  4. package/dist/cli-chunks/{build-BgBt5SkX.cjs → build-B0Id0UTN.cjs} +8 -6
  5. package/dist/cli-chunks/{create-BL6uwtkQ.cjs → create-DVu93Ekp.cjs} +3 -1
  6. package/dist/cli-chunks/{dev-NgklQb6b.cjs → dev-CeSjpEZQ.cjs} +9613 -616
  7. package/dist/cli-chunks/{dev-context-Tf8MgSsu.cjs → dev-context-CVc_BsWR.cjs} +4 -6
  8. package/dist/cli-chunks/{doctor-CGlEf1yi.cjs → doctor-BF9mtkJr.cjs} +3 -1
  9. package/dist/cli-chunks/{games-Cc-DclmK.cjs → games-BKnDCklM.cjs} +3 -1
  10. package/dist/cli-chunks/{index-D9XLBbNV.cjs → index-Cgui_8Rk.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CmxsiTTn.cjs → index-Rp3UMZIO.cjs} +1754 -120
  12. package/dist/cli-chunks/index.esm-BK0eVYaM.cjs +154 -0
  13. package/dist/cli-chunks/{login-ZMBDHBuA.cjs → login-DpeDN-mt.cjs} +3 -3
  14. package/dist/cli-chunks/{project-vite-eM87vX9L.cjs → project-vite-Cg3jYqAJ.cjs} +3 -18
  15. package/dist/cli-chunks/{remote-DVhxpWDg.cjs → remote-BQ-9rhTb.cjs} +12 -21
  16. package/dist/cli-chunks/{runtime-permission-env-q1FWWwbV.cjs → runtime-permission-env-BgipCJ0Z.cjs} +62 -13
  17. package/dist/cli-chunks/{skill-mRXM87hY.cjs → skill-D7pd4yPq.cjs} +3 -2
  18. package/dist/cli-chunks/{version-BqHRI4Lz.cjs → version-DbjRZkb6.cjs} +1 -1
  19. package/dist/cli.cjs +3 -1
  20. package/dist/dev.cjs +1358 -0
  21. package/dist/dev.mjs +1356 -0
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DVlT56iQ.js +100 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BzRxl_MM.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +1 -0
  25. package/dist/devtools/browser-dev-host/assets/index-DY5ZynQp.js +586 -0
  26. package/dist/devtools/browser-dev-host/index.html +3 -3
  27. package/dist/index.cjs.js +232 -114
  28. package/dist/index.esm.js +232 -114
  29. package/dist/miniapp-publish.cjs.js +2 -2
  30. package/dist/miniapp-publish.esm.js +2 -2
  31. package/dist/protocol.cjs.js +5 -0
  32. package/dist/protocol.esm.js +5 -0
  33. package/dist/vite.cjs.js +1060 -203
  34. package/dist/vite.esm.js +1061 -204
  35. package/docs/device-logs.md +39 -22
  36. package/package.json +22 -9
  37. package/skill/skill.json +4 -4
  38. package/types/dev/index.d.cts +386 -0
  39. package/types/dev/index.d.mts +386 -0
  40. package/types/dev/vendor/playwright-core/LICENSE +202 -0
  41. package/types/dev/vendor/playwright-core/NOTICE +5 -0
  42. package/types/dev/vendor/playwright-core/UPSTREAM.json +5 -0
  43. package/types/dev/vendor/playwright-core/types/protocol.d.ts +24776 -0
  44. package/types/dev/vendor/playwright-core/types/structs.d.ts +52 -0
  45. package/types/dev/vendor/playwright-core/types/types.d.ts +27167 -0
  46. package/types/index.d.ts +66 -5
  47. package/types/protocol.d.ts +3 -2
  48. package/types/vite/index.d.ts +5 -4
  49. package/dist/cli-chunks/index.esm-DnyLP_Zc.cjs +0 -5216
  50. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DtWOjzCe.js +0 -103
  51. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-C2Vw0-AC.js +0 -6
  52. package/dist/devtools/browser-dev-host/assets/index-B-rjfibN.js +0 -567
  53. package/dist/devtools/browser-dev-host/assets/index-DSTlrpnQ.css +0 -1
  54. 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 检查资料完整性,不联网、不修改输入。 */
@@ -82,7 +82,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
82
82
  risk: 'high',
83
83
  config: {},
84
84
  methods: ['gameSaves.list', 'gameSaves.sync', 'gameSaves.getFile', 'gameSaves.readParsedData'],
85
- conditions: ['需要用户明确授权、有效 Steam 登录和支持文件读取的宿主;可按需读取受支持游戏的已有解析概览,不触发解析。'],
85
+ conditions: ['需声明权限并校验当前 Steam 账号,无需额外授权弹窗;可读取受支持游戏已有的完整结构化数据,不触发解析。同步需有效 Steam 登录,文件下载另需宿主支持文件读取。'],
86
86
  },
87
87
  {
88
88
  key: 'userInfo',
@@ -111,7 +111,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
111
111
  access: 'declaration',
112
112
  risk: 'medium',
113
113
  config: {},
114
- methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot'],
114
+ methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot', 'share.screenshotLong'],
115
115
  conditions: ['继续执行分享参数校验和 Host 支持检查。'],
116
116
  },
117
117
  {
@@ -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$1() {
3113
+ function registry() {
3114
3114
  return new $ZodRegistry();
3115
3115
  }
3116
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry$1());
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.1';
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.11';
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, value) => {
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 registryKey = Symbol.for('@heybox/hb-sdk/device-logs');
10426
- const registry = globalThis;
10427
- const stores = (registry[registryKey] ??= new Map());
10428
- function registerDeviceLogs(port, store) {
10429
- stores.set(port, store);
10430
- return () => {
10431
- if (stores.get(port) === store)
10432
- stores.delete(port);
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
- devices = new Map();
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('device') || log.deviceSessionId === params.get('device')) &&
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
- (!params.get('source') || log.source === params.get('source')) &&
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') || log.message.toLowerCase().includes(params.get('query').toLowerCase())));
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
- schemaVersion: 1,
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.devices.values()].find(device => device.registrationId === registrationId);
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.devices.size >= 64) {
10522
- reply(429, {});
10523
- return;
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 platform = ['iOS', 'Android', 'Windows', 'macOS', 'Browser'].includes(body.platform) ? body.platform : 'Browser';
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
- platform,
11305
+ browser,
11306
+ os,
11307
+ deviceModel,
10530
11308
  registrationId,
10531
- connectedAt: Date.now(),
10532
- name: `${platform} · ${this.devices.size + 1}`,
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: Date.now(),
11313
+ windowStart: now,
10537
11314
  count: 0,
10538
11315
  };
10539
- this.devices.set(id, device);
11316
+ this.uploadSessions.set(id, device);
10540
11317
  reply(200, { id, token: device.token });
10541
11318
  return;
10542
11319
  }
10543
- const device = this.devices.get(body.id);
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
- if (body.sandboxResult && typeof body.sandboxResult === 'object') {
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 || typeof log !== 'object')
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.logs.push({
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 (this.logs.length > 5000)
10600
- this.logs.splice(0, this.logs.length - 5000);
10601
- reply(200, { sequence: device.sequence, sandboxRequest: [...this.sandboxRequests.values()].find(request => request.id === device.id) ? (() => { const request = [...this.sandboxRequests.values()].find(request => request.id === device.id); return { requestId: request.requestId, path: request.path }; })() : undefined });
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
- window.__hb_sdk_mini_dev_console_installed__=true;
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.__hbSdkDeviceLog=function(event){add(event.outcome==='error'?'error':'info',[event.method+' · '+event.outcome+' · '+event.durationMs+' ms'],'sdk');
10627
- Object.assign(queue[queue.length-1],event)};
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 platform=window.name==='__hb_sdk_mini_dev__'?'Browser':/Android/i.test(ua)?'Android':/iPhone|iPad/i.test(ua)?'iOS':/Windows/i.test(ua)?'Windows':/Mac/i.test(ua)?'macOS':'Browser';
10638
- var r=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({register:true,platform:platform,registrationId:registrationId}),signal:AbortSignal.timeout(5000)});
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,sandboxResult:sandboxResult}),signal:AbortSignal.timeout(5000)});
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();sandboxResult=undefined;
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>`;
@@ -20310,6 +21072,42 @@ function walk$1(node, visit) {
20310
21072
  walk$1(node.content, visit);
20311
21073
  }
20312
21074
 
21075
+ /** 约束构建产物中的 HTTPS source,禁止通配、IP、端口及 CSP 注入。 */
21076
+ function normalizeMiniappBuildImageDomain(value) {
21077
+ if (typeof value !== 'string' || value !== value.trim() || value.length > 253)
21078
+ return undefined;
21079
+ const domain = value.toLowerCase();
21080
+ if (!domain.includes('.') || /^\d+(?:\.\d+)*$/.test(domain))
21081
+ return undefined;
21082
+ if (!domain.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))
21083
+ return undefined;
21084
+ if (domain.endsWith('.localhost') || domain.endsWith('.local') || domain.endsWith('.internal'))
21085
+ return undefined;
21086
+ return domain;
21087
+ }
21088
+ /** SDK 构建层独立消费平台资料;Runtime 继续独立校验可信启动策略。 */
21089
+ function parseMiniappBuildImagePolicy(value) {
21090
+ if (value === undefined || value === null)
21091
+ return undefined;
21092
+ if (typeof value !== 'object' || Array.isArray(value))
21093
+ throw new TypeError('图片构建策略格式无效');
21094
+ const record = value;
21095
+ const entries = record.entries === undefined ? [] : record.entries;
21096
+ if (!Number.isSafeInteger(record.revision) || record.revision < 1 ||
21097
+ (record.enforcement !== 'approved_domains' && record.enforcement !== 'restricted') ||
21098
+ !Array.isArray(entries) || entries.length > 20)
21099
+ throw new TypeError('图片构建策略格式无效');
21100
+ const domains = new Set();
21101
+ for (const entry of entries) {
21102
+ const domain = normalizeMiniappBuildImageDomain(entry && typeof entry === 'object' ? entry.domain : undefined);
21103
+ if (!domain)
21104
+ throw new TypeError('图片构建策略包含无效域名');
21105
+ domains.add(domain);
21106
+ }
21107
+ return Object.freeze({ revision: record.revision, enforcement: record.enforcement,
21108
+ entries: Object.freeze([...domains].sort().map((domain) => Object.freeze({ domain }))) });
21109
+ }
21110
+
20313
21111
  const FORBIDDEN_RESOURCE_HINTS = new Set(['dns-prefetch', 'preconnect', 'prerender']);
20314
21112
  const RELATIVE_URL_BASE = new URL('https://heybox-relative.invalid/');
20315
21113
  const OFFICIAL_RESOURCE_ROOT_DOMAINS = ['xiaoheihe.cn', 'max-c.com', 'debugmode.cn', 'maxjia.com'];
@@ -20317,11 +21115,13 @@ const OFFICIAL_RESOURCE_SOURCES = OFFICIAL_RESOURCE_ROOT_DOMAINS.flatMap((rootDo
20317
21115
  // 受控媒体预览通道:iOS `hbmini-media://preview/...`、鸿蒙 OHOS `hbmedia://<sessionId>/<previewId>`。
20318
21116
  // 两者是宿主注册的自定义 scheme,只允许出现在图片/媒体资源加载指令中,不放宽其它指令。
20319
21117
  const MEDIA_PREVIEW_SCHEME_SOURCES = ['hbmini-media:', 'hbmedia:'];
21118
+ // 平台图片的精确基础源,依据 SDK share 用例及 Host 菜单图片合同;不授予公开接口请求。
21119
+ const PLATFORM_IMAGE_DOMAINS = ['imgheybox.max-c.com'];
20320
21120
  const URL_ATTRIBUTES = {
20321
21121
  audio: ['src'],
20322
21122
  embed: ['src'],
20323
21123
  iframe: ['src'],
20324
- img: ['src'],
21124
+ img: ['src', 'srcset'],
20325
21125
  input: ['src'],
20326
21126
  object: ['data'],
20327
21127
  script: ['src'],
@@ -20334,7 +21134,7 @@ const PRODUCTION_CSP = [
20334
21134
  "connect-src 'none'",
20335
21135
  `script-src 'self' 'unsafe-inline' ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20336
21136
  `style-src 'self' 'unsafe-inline' ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20337
- `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
21137
+ `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${PLATFORM_IMAGE_DOMAINS.map((domain) => `https://${domain}`).join(' ')}`,
20338
21138
  `font-src 'self' data: ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20339
21139
  `media-src 'self' blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20340
21140
  "manifest-src 'self'",
@@ -20353,18 +21153,26 @@ function enforceMiniappHtmlPolicy(html, options = {}) {
20353
21153
  throw new Error('入口 index.html 必须包含 <head>');
20354
21154
  }
20355
21155
  removePlatformCspMarkers(document);
20356
- walk(document, (element) => validateElement(element));
21156
+ const imageDomains = new Set([...PLATFORM_IMAGE_DOMAINS, ...(options.approvedImageDomains ?? [])].map((domain) => {
21157
+ const normalized = normalizeMiniappBuildImageDomain(domain);
21158
+ if (!normalized)
21159
+ throw new Error('图片策略包含无效域名');
21160
+ return normalized;
21161
+ }));
21162
+ walk(document, (element) => validateElement(element, imageDomains));
20357
21163
  injectMiniappRuntimeGate(document);
20358
- if (options.skipPlatformCsp) {
20359
- return serialize(document);
20360
- }
21164
+ // 保留旧参数的类型兼容,但网络授权不能再移除 CSP。
20361
21165
  const connectSources = Array.from(new Set([
20362
- options.hmrWebSocketUrl,
21166
+ ...(options.hmrWebSocketUrls ?? []),
20363
21167
  ...(options.deviceLogUploadUrls ?? []),
20364
21168
  ].filter((source) => Boolean(source))));
20365
- const content = connectSources.length > 0
20366
- ? PRODUCTION_CSP.replace("connect-src 'none'", `connect-src ${connectSources.join(' ')}`)
20367
- : PRODUCTION_CSP;
21169
+ const imagePolicy = PRODUCTION_CSP.replace(/img-src[^;]*/, `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')}${[...imageDomains].sort().map((domain) => ` https://${domain}`).join('')}`);
21170
+ let content = connectSources.length > 0
21171
+ ? imagePolicy.replace("connect-src 'none'", `connect-src ${connectSources.join(' ')}`)
21172
+ : imagePolicy;
21173
+ // Vite 8 通过 Blob SharedWorker 等待 HMR 重连;只在显式开发 WS 入口存在时放行。
21174
+ if (options.hmrWebSocketUrls?.length)
21175
+ content = content.replace("worker-src 'none'", 'worker-src blob:');
20368
21176
  head.childNodes.unshift({
20369
21177
  nodeName: 'meta',
20370
21178
  tagName: 'meta',
@@ -20380,7 +21188,7 @@ function enforceMiniappHtmlPolicy(html, options = {}) {
20380
21188
  });
20381
21189
  return serialize(document);
20382
21190
  }
20383
- function validateElement(element) {
21191
+ function validateElement(element, imageDomains) {
20384
21192
  const tagName = element.tagName.toLowerCase();
20385
21193
  const attrs = new Map(element.attrs.map((attr) => [attr.name.toLowerCase(), attr.value]));
20386
21194
  if (tagName === 'meta' && attrs.get('http-equiv')?.toLowerCase() === 'refresh') {
@@ -20410,19 +21218,41 @@ function validateElement(element) {
20410
21218
  }
20411
21219
  for (const attribute of URL_ATTRIBUTES[tagName] ?? []) {
20412
21220
  const value = attrs.get(attribute);
21221
+ const imageResource = tagName === 'img' || (tagName === 'input' && attrs.get('type') === 'image') ||
21222
+ (tagName === 'video' && attribute === 'poster') ||
21223
+ (tagName === 'source' && element.parentNode && 'tagName' in element.parentNode && element.parentNode.tagName === 'picture');
21224
+ const validate = (candidate) => {
21225
+ if (imageResource && candidate && isApprovedImageUrl(candidate, imageDomains))
21226
+ return;
21227
+ validateResourceUrl(candidate, `<${tagName} ${attribute}>`, true, !imageResource && supportsOfficialResourceUrl(tagName, attribute));
21228
+ };
20413
21229
  if (attribute === 'srcset') {
21230
+ // 单个 data URL 的逗号属于 URL 内容,不能拆成第二个候选地址。
21231
+ if (value?.trim().toLowerCase().startsWith('data:') && !/\s(?:\d+(?:\.\d+)?[wx])\s*,/.test(value)) {
21232
+ validate(value.trim().split(/\s+/)[0]);
21233
+ continue;
21234
+ }
20414
21235
  for (const candidate of (value ?? '')
20415
21236
  .split(',')
20416
21237
  .map((item) => item.trim().split(/\s+/)[0])
20417
21238
  .filter(Boolean)) {
20418
- validateResourceUrl(candidate, `<${tagName} ${attribute}>`, true, supportsOfficialResourceUrl(tagName, attribute));
21239
+ validate(candidate);
20419
21240
  }
20420
21241
  }
20421
21242
  else {
20422
- validateResourceUrl(value, `<${tagName} ${attribute}>`, true, supportsOfficialResourceUrl(tagName, attribute));
21243
+ validate(value);
20423
21244
  }
20424
21245
  }
20425
21246
  }
21247
+ function isApprovedImageUrl(value, domains) {
21248
+ try {
21249
+ const url = new URL(value);
21250
+ return url.protocol === 'https:' && !url.port && !url.username && !url.password && domains.has(url.hostname.toLowerCase());
21251
+ }
21252
+ catch {
21253
+ return false;
21254
+ }
21255
+ }
20426
21256
  function removePlatformCspMarkers(node) {
20427
21257
  if (!('childNodes' in node))
20428
21258
  return;
@@ -20507,13 +21337,32 @@ function walk(node, visit) {
20507
21337
  walk(node.content, visit);
20508
21338
  }
20509
21339
 
20510
- const HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV = 'HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN';
20511
21340
  const HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV = 'HB_SDK_RUNTIME_PERMISSION_CONTEXT';
20512
21341
  const VERIFIED_RUNTIME_PERMISSION_CONTEXT = 'verified';
21342
+ const NETWORK_POLICY_ENV = 'HB_SDK_RUNTIME_NETWORK_POLICY';
20513
21343
  new node_async_hooks.AsyncLocalStorage();
20514
21344
  Promise.resolve();
20515
- function shouldSkipMiniappPlatformCspFromEnv(env = process.env) {
20516
- return env[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] === VERIFIED_RUNTIME_PERMISSION_CONTEXT && env[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV] === '1';
21345
+ function shouldSkipMiniappPlatformCspFromEnv(_env = process.env) {
21346
+ return false;
21347
+ }
21348
+ function readMiniappApprovedImageDomainsFromEnv(env = process.env) {
21349
+ if (env[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] !== VERIFIED_RUNTIME_PERMISSION_CONTEXT || !env[NETWORK_POLICY_ENV])
21350
+ return [];
21351
+ return parseMiniappBuildImagePolicy(JSON.parse(env[NETWORK_POLICY_ENV]))?.entries.map((entry) => entry.domain) ?? [];
21352
+ }
21353
+
21354
+ // 配置文件由 Vite 重新加载,可能产生另一份模块实例;私有标记只用于同进程插件间交接。
21355
+ const POLICY_SOURCE = Symbol.for('@heybox/hb-sdk/dev-network-policy-source');
21356
+ /** 空清单也必须覆盖构建环境快照,防止撤权后恢复旧域名。 */
21357
+ function readMiniappDevApprovedImageDomains(plugins) {
21358
+ for (const plugin of plugins ?? []) {
21359
+ if (!plugin || typeof plugin !== 'object')
21360
+ continue;
21361
+ const source = plugin[POLICY_SOURCE];
21362
+ if (typeof source === 'function')
21363
+ return source();
21364
+ }
21365
+ return undefined;
20517
21366
  }
20518
21367
 
20519
21368
  /** 与平台 H5 保持相同的语法兼容下限;SDK 独立分发,不依赖内部 Platform 包。 */
@@ -20556,29 +21405,8 @@ function assertMiniappBuildCompiler(esbuild) {
20556
21405
  }
20557
21406
  }
20558
21407
 
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
21408
  const sdkVersionPlaceholder = ['__HB_SDK', 'VERSION__'].join('_');
20580
21409
  const sdkVersionBuildConstant = ['__HB_SDK_BUILD', 'VERSION__'].join('_');
20581
- const miniDevLoggingConstant = ['__HB_SDK_DEV', 'LOGGING__'].join('_');
20582
21410
  const DEV_MANIFEST_PATH = '/__hb_sdk__/companion/manifest.json';
20583
21411
  /**
20584
21412
  * 本地 PC 调试开窗时的 manifest 入口。
@@ -20625,6 +21453,10 @@ if (!devSnapshotRegistry[devSnapshotStoreKey]) {
20625
21453
  });
20626
21454
  }
20627
21455
  const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
21456
+ // 配置重载沿当前 server 的异步调用链传递 owner;同项目的另一台 dev 不共享记录。
21457
+ const diagnosticsOwnerKey = Symbol.for('@heybox/hb-sdk/vite-diagnostics-owner');
21458
+ const diagnosticsOwnerRegistry = globalThis;
21459
+ const diagnosticsOwner = (diagnosticsOwnerRegistry[diagnosticsOwnerKey] ??= new node_async_hooks.AsyncLocalStorage());
20628
21460
  /**
20629
21461
  * 创建工坊小程序使用的 Vite 插件。
20630
21462
  *
@@ -20674,14 +21506,15 @@ const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
20674
21506
  * 转换 Vite 编译脚本的 JavaScript 语法,保留更旧的自定义目标,拒绝 `esbuild: false`;注入 SDK 构建版本,且仅
20675
21507
  * `vite serve` 注入开发日志编译常量。语法转换不处理原样复制或远端加载的脚本,不包含运行时 API polyfill,
20676
21508
  * 也不会更新已发布旧产物;
20677
- * - `configResolved`:确认插件唯一性,记录真实 `root`、`build.outDir`、`serve|build` 命令和精确 HMR
20678
- * WebSocket 地址,并再次确认生产环境的语法兼容目标;直接 `vite build` 使用该实际 `outDir`,
21509
+ * - `configResolved`:确认插件唯一性,记录真实 `root`、`build.outDir`、`serve|build` 命令和 HMR
21510
+ * 配置,并再次确认生产环境的语法兼容目标;直接 `vite build` 使用该实际 `outDir`,
20679
21511
  * `hb-sdk build` 则由 CLI 固定为 `dist/`;
20680
21512
  * - `configureServer`:为 `hb-sdk dev` 注册设备日志、本地小程序 Manifest 与 Companion Manifest/ZIP
20681
21513
  * 中间件;敏感路由只接受数值 loopback socket/Host、`GET|HEAD` 和 CLI 注入的独立短期令牌,快照在
20682
21514
  * 配置重载时按 digest 保留,并在服务真正关闭时清理;
20683
21515
  * - `transformIndexHtml`:校验 HTML URL/标签策略,注入 Runtime Gate;默认注入平台 CSP,serve 时
20684
- * `connect-src` 只开放解析出的 HMR WebSocket,并额外注入调试日志 bootstrap;
21516
+ * `connect-src` 按实际监听入口与显式 HMR 配置放行精确 WebSocket 地址,关闭 HMR 时不添加该许可,
21517
+ * 并额外注入调试日志 bootstrap;
20685
21518
  * - `buildEnd`:记住更早的 Rollup/Vite 错误,避免 `closeBundle` 的二次产物错误遮盖根因;
20686
21519
  * - `closeBundle`:serve 时直接完成;build 时复检最终 HTML,要求整个输出树只有根 `index.html`,再于
20687
21520
  * `build.outDir` 写入 `manifest.json`,并把 Companion 目录打包成
@@ -20737,14 +21570,19 @@ const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
20737
21570
  */
20738
21571
  function miniappManifest() {
20739
21572
  const includeCompanions = process.env.HB_SDK_SKIP_COMPANIONS !== '1';
20740
- const deviceLogs = new DeviceLogStore();
20741
- const skipPlatformCsp = shouldSkipMiniappPlatformCspFromEnv();
21573
+ const diagnosticsSessionId = process.env.HB_SDK_DEV_DIAGNOSTICS_SESSION_ID;
21574
+ const managedDiagnostics = diagnosticsSessionId ? getDevDiagnosticsSession(diagnosticsSessionId) : undefined;
21575
+ if (diagnosticsSessionId && !managedDiagnostics)
21576
+ throw new Error('指定的开发诊断会话不存在,请通过 hb-sdk dev 重新启动服务');
21577
+ const deviceLogs = managedDiagnostics ?? diagnosticsOwner.getStore() ?? new DeviceLogStore();
21578
+ shouldSkipMiniappPlatformCspFromEnv();
21579
+ let approvedImageDomains = readMiniappApprovedImageDomainsFromEnv();
20742
21580
  let companionArtifactAccessToken = parseDevAccessToken(process.env[HB_SDK_COMPANION_ARTIFACT_ACCESS_TOKEN_ENV]);
20743
21581
  let miniProgramManifestAccessToken = parseDevAccessToken(process.env[HB_SDK_MINI_PROGRAM_MANIFEST_ACCESS_TOKEN_ENV]);
20744
21582
  let root = process.cwd();
20745
21583
  let outDir = 'dist';
20746
21584
  let command = 'build';
20747
- let hmrWebSocketUrl;
21585
+ let resolvedConfig;
20748
21586
  let configuredDeviceLogUploadUrls = [];
20749
21587
  let devServer;
20750
21588
  let metadataWarningsShown = false;
@@ -20773,8 +21611,6 @@ function miniappManifest() {
20773
21611
  ...(buildTargets ? { build: { target: buildTargets } } : {}),
20774
21612
  define: {
20775
21613
  [sdkVersionBuildConstant]: JSON.stringify(resolveSdkVersion()),
20776
- // 仅 vite serve(hb-sdk dev)注入;vite build / hb-sdk build 永不注入,捕获模块被死代码消除。
20777
- ...(isServe ? { [miniDevLoggingConstant]: 'true' } : {}),
20778
21614
  },
20779
21615
  };
20780
21616
  },
@@ -20788,6 +21624,9 @@ function miniappManifest() {
20788
21624
  root = resolved.root;
20789
21625
  outDir = resolved.build.outDir;
20790
21626
  command = resolved.command;
21627
+ if (command === 'serve') {
21628
+ approvedImageDomains = readMiniappDevApprovedImageDomains(resolved.plugins) ?? approvedImageDomains;
21629
+ }
20791
21630
  if (command === 'build') {
20792
21631
  assertMiniappBuildCompiler(resolved.esbuild);
20793
21632
  resolved.build.target = resolveMiniappBuildTargets(resolved.build.target);
@@ -20796,7 +21635,7 @@ function miniappManifest() {
20796
21635
  environment.build.target = resolveMiniappBuildTargets(environment.build.target);
20797
21636
  }
20798
21637
  }
20799
- hmrWebSocketUrl = resolveHmrWebSocketUrl(resolved);
21638
+ resolvedConfig = resolved;
20800
21639
  configuredDeviceLogUploadUrls = resolveConfiguredDeviceLogUploadUrls(resolved);
20801
21640
  },
20802
21641
  configureServer(server) {
@@ -20830,16 +21669,6 @@ function miniappManifest() {
20830
21669
  server.config.logger.warn(`[${warning.code}] ${warning.message}`);
20831
21670
  metadataWarningsShown = true;
20832
21671
  }
20833
- let unregisterLogs;
20834
- const registerLogs = () => {
20835
- const address = server.httpServer?.address();
20836
- if (address && typeof address !== 'string')
20837
- unregisterLogs = registerDeviceLogs(address.port, deviceLogs);
20838
- };
20839
- server.httpServer?.once('listening', registerLogs);
20840
- server.httpServer?.once('close', () => unregisterLogs?.());
20841
- if (server.httpServer?.listening)
20842
- registerLogs();
20843
21672
  let store = devSnapshotStores.get(root);
20844
21673
  companionArtifactAccessToken ??= store?.token;
20845
21674
  // 与 Companion 令牌同因:配置重载时 env 已不在,只能从同一服务的注册表恢复。
@@ -20859,7 +21688,7 @@ function miniappManifest() {
20859
21688
  server.restart = async (forceOptimize) => {
20860
21689
  store.restarting = true;
20861
21690
  try {
20862
- await restart(forceOptimize);
21691
+ await diagnosticsOwner.run(deviceLogs, () => restart(forceOptimize));
20863
21692
  }
20864
21693
  finally {
20865
21694
  store.restarting = false;
@@ -21120,14 +21949,13 @@ function miniappManifest() {
21120
21949
  ...(command === 'serve'
21121
21950
  ? {
21122
21951
  deviceLogUploadUrls: Array.from(new Set([...configuredDeviceLogUploadUrls, ...resolveViteDeviceLogUploadUrls(devServer?.resolvedUrls)])),
21123
- hmrWebSocketUrl,
21952
+ // resolvedUrls 在 listen 后才包含实际端口与所有可访问网卡,不能在 configResolved 固化。
21953
+ hmrWebSocketUrls: resolveHmrWebSocketUrls(resolvedConfig, devServer),
21124
21954
  }
21125
21955
  : {}),
21126
- skipPlatformCsp,
21956
+ approvedImageDomains,
21127
21957
  });
21128
- return command === 'serve'
21129
- ? injectMiniDevConsoleBootstrap(enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`))
21130
- : enforced;
21958
+ return command === 'serve' ? enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`) : enforced;
21131
21959
  },
21132
21960
  async closeBundle() {
21133
21961
  // Vite dev 的关闭/配置重载同样会触发此钩子,不执行发布打包。
@@ -21165,7 +21993,7 @@ function miniappManifest() {
21165
21993
  if (!htmlFiles.includes(indexHtmlPath)) {
21166
21994
  throw new Error('构建产物必须包含入口 dist/index.html');
21167
21995
  }
21168
- node_fs.writeFileSync(indexHtmlPath, enforceMiniappHtmlPolicy(node_fs.readFileSync(indexHtmlPath, 'utf8'), { skipPlatformCsp }));
21996
+ node_fs.writeFileSync(indexHtmlPath, enforceMiniappHtmlPolicy(node_fs.readFileSync(indexHtmlPath, 'utf8'), { approvedImageDomains }));
21169
21997
  const basicInfo = await prepareMiniappBasicInfo(companionConfig.projectRoot, outputRoot, sdkVersion);
21170
21998
  const cardConfig = readMiniappWorkspaceCardsFromPackageJson(root);
21171
21999
  const workspaceCards = typeof cardConfig.declaration === 'string'
@@ -21376,16 +22204,45 @@ function resolveSdkVersion() {
21376
22204
  }
21377
22205
  return packageJson.version;
21378
22206
  }
21379
- function resolveHmrWebSocketUrl(resolved) {
22207
+ function resolveHmrWebSocketUrls(resolved, server) {
22208
+ if (!resolved)
22209
+ return [];
21380
22210
  const hmr = resolved.server.hmr;
21381
22211
  if (hmr === false)
21382
- return undefined;
22212
+ return [];
21383
22213
  const options = typeof hmr === 'object' ? hmr : {};
21384
- const protocol = options.protocol ?? (resolved.server.https ? 'wss' : 'ws');
21385
- const configuredHost = options.host ?? resolved.server.host;
21386
- const host = typeof configuredHost === 'string' && configuredHost !== '0.0.0.0' ? configuredHost : '127.0.0.1';
21387
- const port = options.clientPort ?? options.port ?? resolved.server.port;
21388
- return `${protocol}://${host}${port ? `:${port}` : ''}`;
22214
+ const urls = [...(server?.resolvedUrls?.local ?? []), ...(server?.resolvedUrls?.network ?? [])];
22215
+ if (urls.length === 0) {
22216
+ const configuredHost = resolved.server.host;
22217
+ const host = typeof configuredHost === 'string' && configuredHost !== '0.0.0.0' && configuredHost !== '::'
22218
+ ? configuredHost : '127.0.0.1';
22219
+ const address = server?.httpServer?.address();
22220
+ const port = address && typeof address !== 'string' ? address.port : resolved.server.port;
22221
+ const url = createDeviceLogUploadUrl(resolved.server.https ? 'https' : 'http', host, port);
22222
+ if (url)
22223
+ urls.push(url);
22224
+ }
22225
+ return Array.from(new Set(urls.flatMap((url) => {
22226
+ try {
22227
+ const source = new URL(url);
22228
+ if (source.protocol !== 'http:' && source.protocol !== 'https:')
22229
+ return [];
22230
+ const protocol = options.protocol || (source.protocol === 'https:' ? 'wss' : 'ws');
22231
+ const host = options.host || source.hostname;
22232
+ const normalizedHost = host.startsWith('[') || !host.includes(':') ? host : `[${host}]`;
22233
+ // 与 Vite client 一致:显式 clientPort/port 优先,否则从加载入口推导。
22234
+ const port = options.clientPort || options.port || source.port;
22235
+ const endpoint = new URL(`${protocol}://${normalizedHost}${port ? `:${port}` : ''}`);
22236
+ if (!['ws:', 'wss:'].includes(endpoint.protocol) || endpoint.hostname.includes('*')
22237
+ || ['0.0.0.0', '[::]'].includes(endpoint.hostname) || endpoint.username || endpoint.password
22238
+ || endpoint.pathname !== '/' || endpoint.search || endpoint.hash)
22239
+ return [];
22240
+ return [endpoint.origin];
22241
+ }
22242
+ catch {
22243
+ return [];
22244
+ }
22245
+ })));
21389
22246
  }
21390
22247
  function resolveConfiguredDeviceLogUploadUrls(resolved) {
21391
22248
  if (resolved.command !== 'serve')