@heybox/hb-sdk 0.9.6-alpha.0 → 0.9.6-alpha.10

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 (55) hide show
  1. package/CHANGELOG.md +91 -5
  2. package/README.md +35 -555
  3. package/dist/cli-chunks/{artifact-Cmg87Tf5.cjs → artifact-BaZzEQjq.cjs} +3 -3
  4. package/dist/cli-chunks/{build-C3etivt0.cjs → build-Ykhw1sz9.cjs} +8 -6
  5. package/dist/cli-chunks/{create-Blk6X1Yg.cjs → create-BEjKsD1y.cjs} +3 -1
  6. package/dist/cli-chunks/{dev-Bz2su6LB.cjs → dev-DpkBN4ir.cjs} +9613 -616
  7. package/dist/cli-chunks/{dev-context-CEkb1z-v.cjs → dev-context-B3Y_EcXC.cjs} +4 -6
  8. package/dist/cli-chunks/{doctor-DRod5jqN.cjs → doctor-DPELjB83.cjs} +3 -1
  9. package/dist/cli-chunks/{games-C__m_OWO.cjs → games-D2hnnWKY.cjs} +3 -1
  10. package/dist/cli-chunks/{index-Bkp6luz7.cjs → index-DCj9vtVv.cjs} +1 -1
  11. package/dist/cli-chunks/{index-Ce_VEy0u.cjs → index-DIgSsTuu.cjs} +1754 -120
  12. package/dist/cli-chunks/index.esm-t29GC7yg.cjs +154 -0
  13. package/dist/cli-chunks/{login-1OQQ9hax.cjs → login-C5XmcbRa.cjs} +3 -3
  14. package/dist/cli-chunks/{project-vite-DpG6qqyH.cjs → project-vite-B12EMgRq.cjs} +3 -18
  15. package/dist/cli-chunks/{remote-DDCv6nEF.cjs → remote-lFAA88Zl.cjs} +12 -21
  16. package/dist/cli-chunks/{runtime-permission-env-CSex_ggc.cjs → runtime-permission-env-CYbLBtWo.cjs} +61 -12
  17. package/dist/cli-chunks/{skill-BRQotwcs.cjs → skill-AilHsggi.cjs} +3 -2
  18. package/dist/cli-chunks/{version-Dl4XqQrU.cjs → version-KZTUyIiC.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-C0_lx52X.js +100 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-CPk4dD63.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-BzOC7Q8l.js +586 -0
  25. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +1 -0
  26. package/dist/devtools/browser-dev-host/index.html +3 -3
  27. package/dist/index.cjs.js +63 -112
  28. package/dist/index.esm.js +63 -112
  29. package/dist/miniapp-publish.cjs.js +1 -1
  30. package/dist/miniapp-publish.esm.js +1 -1
  31. package/dist/protocol.cjs.js +2 -0
  32. package/dist/protocol.esm.js +2 -0
  33. package/dist/vite.cjs.js +1059 -202
  34. package/dist/vite.esm.js +1060 -203
  35. package/docs/appreciation-code.md +67 -0
  36. package/docs/device-logs.md +39 -22
  37. package/package.json +24 -10
  38. package/skill/skill.json +4 -4
  39. package/types/dev/index.d.cts +386 -0
  40. package/types/dev/index.d.mts +386 -0
  41. package/types/dev/vendor/playwright-core/LICENSE +202 -0
  42. package/types/dev/vendor/playwright-core/NOTICE +5 -0
  43. package/types/dev/vendor/playwright-core/UPSTREAM.json +5 -0
  44. package/types/dev/vendor/playwright-core/types/protocol.d.ts +24776 -0
  45. package/types/dev/vendor/playwright-core/types/structs.d.ts +52 -0
  46. package/types/dev/vendor/playwright-core/types/types.d.ts +27167 -0
  47. package/types/index.d.ts +30 -4
  48. package/types/protocol.d.ts +3 -2
  49. package/types/vite/index.d.ts +5 -4
  50. package/dist/cli-chunks/index.esm-KLaZWTou.cjs +0 -5216
  51. package/dist/devtools/browser-dev-host/assets/browser-dev-host-HqISBdtQ.js +0 -103
  52. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-JFfHePS2.js +0 -6
  53. package/dist/devtools/browser-dev-host/assets/index-DSTlrpnQ.css +0 -1
  54. package/dist/devtools/browser-dev-host/assets/index-MBLQu8hw.js +0 -567
  55. package/docs/runtime-host-migration.md +0 -128
package/dist/vite.esm.js CHANGED
@@ -1,4 +1,5 @@
1
- import { createHash, randomUUID, randomBytes, timingSafeEqual } from 'node:crypto';
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
3
  import { createRequire, builtinModules } from 'node:module';
3
4
  import { pathToFileURL, fileURLToPath } from 'node:url';
4
5
  import { lstatSync, readFileSync, mkdirSync, writeFileSync, realpathSync, existsSync, constants as constants$1, readdirSync, readlinkSync, renameSync, rmSync, unwatchFile, createReadStream, watchFile, mkdtempSync, chmodSync } from 'node:fs';
@@ -10,7 +11,6 @@ import { readFile, mkdir, realpath, writeFile, stat, open } from 'node:fs/promis
10
11
  import sharp from 'sharp';
11
12
  import { tmpdir, platform, arch } from 'node:os';
12
13
  import { inflateRawSync } from 'node:zlib';
13
- import { AsyncLocalStorage } from 'node:async_hooks';
14
14
 
15
15
  /** 根据当前项目声明或实际版本 Manifest 检查资料完整性,不联网、不修改输入。 */
16
16
  function getMiniappMetadataWarnings(metadata) {
@@ -79,7 +79,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
79
79
  risk: 'high',
80
80
  config: {},
81
81
  methods: ['gameSaves.list', 'gameSaves.sync', 'gameSaves.getFile', 'gameSaves.readParsedData'],
82
- conditions: ['需要用户明确授权、有效 Steam 登录和支持文件读取的宿主;可按需读取受支持游戏的已有解析概览,不触发解析。'],
82
+ conditions: ['需声明权限并校验当前 Steam 账号,无需额外授权弹窗;可读取受支持游戏已有的完整结构化数据,不触发解析。同步需有效 Steam 登录,文件下载另需宿主支持文件读取。'],
83
83
  },
84
84
  {
85
85
  key: 'userInfo',
@@ -450,7 +450,7 @@ const allowsEval = /* @__PURE__*/ cached(() => {
450
450
  return false;
451
451
  }
452
452
  });
453
- function isPlainObject(o) {
453
+ function isPlainObject$1(o) {
454
454
  if (isObject(o) === false)
455
455
  return false;
456
456
  // modified constructor
@@ -470,7 +470,7 @@ function isPlainObject(o) {
470
470
  return true;
471
471
  }
472
472
  function shallowClone(o) {
473
- if (isPlainObject(o))
473
+ if (isPlainObject$1(o))
474
474
  return { ...o };
475
475
  if (Array.isArray(o))
476
476
  return [...o];
@@ -570,7 +570,7 @@ function omit(schema, mask) {
570
570
  return clone(schema, def);
571
571
  }
572
572
  function extend(schema, shape) {
573
- if (!isPlainObject(shape)) {
573
+ if (!isPlainObject$1(shape)) {
574
574
  throw new Error("Invalid input to extend: expected a plain object");
575
575
  }
576
576
  const checks = schema._zod.def.checks;
@@ -595,7 +595,7 @@ function extend(schema, shape) {
595
595
  return clone(schema, def);
596
596
  }
597
597
  function safeExtend(schema, shape) {
598
- if (!isPlainObject(shape)) {
598
+ if (!isPlainObject$1(shape)) {
599
599
  throw new Error("Invalid input to safeExtend: expected a plain object");
600
600
  }
601
601
  const def = mergeDefs(schema._zod.def, {
@@ -2501,7 +2501,7 @@ function mergeValues(a, b) {
2501
2501
  if (a instanceof Date && b instanceof Date && +a === +b) {
2502
2502
  return { valid: true, data: a };
2503
2503
  }
2504
- if (isPlainObject(a) && isPlainObject(b)) {
2504
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
2505
2505
  const bKeys = Object.keys(b);
2506
2506
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
2507
2507
  const newObj = { ...a, ...b };
@@ -2585,7 +2585,7 @@ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
2585
2585
  $ZodType.init(inst, def);
2586
2586
  inst._zod.parse = (payload, ctx) => {
2587
2587
  const input = payload.value;
2588
- if (!isPlainObject(input)) {
2588
+ if (!isPlainObject$1(input)) {
2589
2589
  payload.issues.push({
2590
2590
  expected: "record",
2591
2591
  code: "invalid_type",
@@ -3107,10 +3107,10 @@ class $ZodRegistry {
3107
3107
  }
3108
3108
  }
3109
3109
  // registries
3110
- function registry$1() {
3110
+ function registry() {
3111
3111
  return new $ZodRegistry();
3112
3112
  }
3113
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry$1());
3113
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
3114
3114
  const globalRegistry = globalThis.__zod_globalRegistry;
3115
3115
 
3116
3116
  // @__NO_SIDE_EFFECTS__
@@ -10326,29 +10326,7 @@ async function ensureBasicInfoDirectory(rootPath, relative) {
10326
10326
  /** 构建时替换为当前发布包的实际版本。 */
10327
10327
  const HB_SDK_VERSION = typeof undefined === 'string'
10328
10328
  ? undefined
10329
- : '0.9.6-alpha.0';
10330
-
10331
- /**
10332
- * iframe 与调试台页面的开发期 console 捕获转发。
10333
- *
10334
- * 双条件门控(iframe 转发):
10335
- * 1. 构建期:`hb-sdk dev`(vite serve)注入 `false`;`hb-sdk build` /
10336
- * `vite build`(生产)永不注入或替换为 `false`,本模块被死代码消除。
10337
- * 2. 运行期:仅在 `window.name` 为 `__hb_sdk_mini_dev__` 的调试 iframe 中激活,
10338
- * 用户设备上的正式运行环境没有该标记。
10339
- *
10340
- * 无侵入 patch `console.log/debug/info/warn/error`:原样放行(DevTools 不受影响)+
10341
- * 通过 `window.parent.postMessage` 转发给调试台(CSP 的 connect-src 不约束 postMessage,
10342
- * 网络上报由调试台页面代理)。发送全程静默:失败不得回打 console,避免自触发死循环。
10343
- *
10344
- * 激活时机:由 SDK 默认单例初始化时调用(业务 `import '@heybox/hb-sdk'` 即生效);
10345
- * iframe 标记由调试台 `iframe.name` 与 vite dev 注入的无依赖 bootstrap 共同设置。
10346
- * 调试台页面自身(runtime 跑在这里,`[hb-sdk-runtime]` 日志不经过 iframe)另用
10347
- * `installMiniDevConsoleSelfCapture` 接入「日志」页签(source: 'host')。
10348
- */
10349
- const MINI_DEV_CONSOLE_EVENT_TYPE = 'hb-sdk:mini-dev-console';
10350
- /** 调试台页面与 iframe bootstrap 共用的已安装标记(window/console 上的属性名)。 */
10351
- const MINI_DEV_CONSOLE_INSTALL_FLAG = '__hb_sdk_mini_dev_console_installed__';
10329
+ : '0.9.6-alpha.10';
10352
10330
 
10353
10331
  /**
10354
10332
  * network.request 诊断日志的纯脱敏工具。
@@ -10358,6 +10336,25 @@ const MINI_DEV_CONSOLE_INSTALL_FLAG = '__hb_sdk_mini_dev_console_installed__';
10358
10336
  * modules observability、devtools Browser Dev Host / proxy 共用,并满足 boundary
10359
10337
  *(devtools 不得直接 import runtime capability modules)。
10360
10338
  */
10339
+ const DATA_PREVIEW_MAX_CHARS = 500;
10340
+ const SENSITIVE_HEADER_NAMES = new Set([
10341
+ 'authorization',
10342
+ 'cookie',
10343
+ 'proxy-authorization',
10344
+ 'set-cookie',
10345
+ 'token',
10346
+ 'x-pkey',
10347
+ 'api-key',
10348
+ 'apikey',
10349
+ 'x-api-key',
10350
+ 'x-auth-token',
10351
+ 'x-access-token',
10352
+ 'session',
10353
+ 'session-id',
10354
+ 'jwt',
10355
+ 'refresh-token',
10356
+ 'x-csrf-token',
10357
+ ]);
10361
10358
  /** 敏感字段名:header / query / body key 共用。 */
10362
10359
  const SENSITIVE_KEY_PATTERN = /(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;
10363
10360
  /**
@@ -10387,6 +10384,82 @@ function sanitizeNetworkRequestUrl(url) {
10387
10384
  return redactSensitivePairsInRawText(url);
10388
10385
  }
10389
10386
  }
10387
+ /**
10388
+ * 脱敏请求/响应头;敏感名(含 heybox 前缀)替换为 `[redacted]`。
10389
+ */
10390
+ function sanitizeNetworkHeaders(headers) {
10391
+ if (!headers) {
10392
+ return {};
10393
+ }
10394
+ return Object.fromEntries(Object.entries(headers).map(([key, value]) => [
10395
+ key,
10396
+ isSensitiveNetworkHeaderName(key) ? '[redacted]' : value,
10397
+ ]));
10398
+ }
10399
+ /**
10400
+ * 预览请求/响应 data:递归脱敏敏感字段,截断长文本与大数组。
10401
+ */
10402
+ function previewNetworkData(data) {
10403
+ if (data === undefined) {
10404
+ return undefined;
10405
+ }
10406
+ if (typeof data === 'string') {
10407
+ return previewNetworkStringData(data);
10408
+ }
10409
+ if (typeof data === 'number' || typeof data === 'boolean' || data === null) {
10410
+ return data;
10411
+ }
10412
+ try {
10413
+ const sanitized = sanitizeNetworkDataValue(data);
10414
+ const serialized = JSON.stringify(sanitized);
10415
+ if (serialized === undefined) {
10416
+ return '[unserializable]';
10417
+ }
10418
+ if (serialized.length <= DATA_PREVIEW_MAX_CHARS) {
10419
+ return sanitized;
10420
+ }
10421
+ return truncateText(serialized, DATA_PREVIEW_MAX_CHARS);
10422
+ }
10423
+ catch {
10424
+ return '[unserializable]';
10425
+ }
10426
+ }
10427
+ /**
10428
+ * 递归脱敏日志对象(payload / result):敏感 key、headers、url 字段统一处理。
10429
+ */
10430
+ function redactNetworkLogValue(value) {
10431
+ if (Array.isArray(value)) {
10432
+ return value.slice(0, 20).map(item => redactNetworkLogValue(item));
10433
+ }
10434
+ if (typeof value === 'string') {
10435
+ if (looksLikeUrl(value)) {
10436
+ return sanitizeNetworkRequestUrl(value);
10437
+ }
10438
+ return previewNetworkStringData(value);
10439
+ }
10440
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null || value === undefined) {
10441
+ return value;
10442
+ }
10443
+ if (!isPlainObject(value)) {
10444
+ return previewNetworkData(value);
10445
+ }
10446
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
10447
+ const normalized = key.trim().toLowerCase();
10448
+ if (isSensitiveNetworkKey(key)) {
10449
+ return [key, '[redacted]'];
10450
+ }
10451
+ if (normalized === 'headers' && isPlainObject(item)) {
10452
+ return [
10453
+ key,
10454
+ sanitizeNetworkHeaders(Object.fromEntries(Object.entries(item).flatMap(([headerKey, headerValue]) => typeof headerValue === 'string' ? [[headerKey, headerValue]] : []))),
10455
+ ];
10456
+ }
10457
+ if ((normalized === 'url' || normalized.endsWith('_url') || normalized.endsWith('url')) && typeof item === 'string') {
10458
+ return [key, sanitizeNetworkRequestUrl(item)];
10459
+ }
10460
+ return [key, redactNetworkLogValue(item)];
10461
+ }));
10462
+ }
10390
10463
  /**
10391
10464
  * 诊断 message 中的 URL 片段做脱敏,避免 error.message 二次泄漏 query secrets。
10392
10465
  */
@@ -10396,9 +10469,58 @@ function sanitizeDiagnosticMessage(message) {
10396
10469
  }
10397
10470
  return message.replace(/https?:\/\/[^\s]+/gi, matched => sanitizeNetworkRequestUrl(matched.replace(/[),.;]+$/g, '')));
10398
10471
  }
10472
+ function isSensitiveNetworkHeaderName(headerName) {
10473
+ const normalized = headerName.trim().toLowerCase();
10474
+ return (SENSITIVE_HEADER_NAMES.has(normalized) ||
10475
+ isSensitiveNetworkKey(normalized) ||
10476
+ normalized.startsWith('x-heybox-') ||
10477
+ normalized.startsWith('x-xhh-'));
10478
+ }
10399
10479
  function isSensitiveNetworkKey(key) {
10400
10480
  return SENSITIVE_KEY_PATTERN.test(key.trim());
10401
10481
  }
10482
+ function previewNetworkStringData(data) {
10483
+ const trimmed = data.trim();
10484
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
10485
+ try {
10486
+ return previewNetworkData(JSON.parse(trimmed));
10487
+ }
10488
+ catch {
10489
+ // fall through
10490
+ }
10491
+ }
10492
+ if (trimmed.includes('=') && !trimmed.includes('\n') && trimmed.length <= DATA_PREVIEW_MAX_CHARS * 2) {
10493
+ try {
10494
+ const params = new URLSearchParams(trimmed);
10495
+ if ([...params.keys()].length > 0) {
10496
+ const redacted = Object.fromEntries([...params.entries()].map(([key, value]) => [
10497
+ key,
10498
+ isSensitiveNetworkKey(key) ? '[redacted]' : value,
10499
+ ]));
10500
+ return previewNetworkData(redacted);
10501
+ }
10502
+ }
10503
+ catch {
10504
+ // fall through
10505
+ }
10506
+ }
10507
+ return truncateText(redactSensitivePairsInRawText(data), DATA_PREVIEW_MAX_CHARS);
10508
+ }
10509
+ function sanitizeNetworkDataValue(value) {
10510
+ if (Array.isArray(value)) {
10511
+ return value.slice(0, 20).map(item => sanitizeNetworkDataValue(item));
10512
+ }
10513
+ if (!isPlainObject(value)) {
10514
+ if (typeof value === 'string') {
10515
+ return truncateText(value, DATA_PREVIEW_MAX_CHARS);
10516
+ }
10517
+ return value;
10518
+ }
10519
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
10520
+ key,
10521
+ isSensitiveNetworkKey(key) ? '[redacted]' : sanitizeNetworkDataValue(item),
10522
+ ]));
10523
+ }
10402
10524
  function redactUrlSearchParams(params) {
10403
10525
  let changed = false;
10404
10526
  for (const key of [...params.keys()]) {
@@ -10410,76 +10532,723 @@ function redactUrlSearchParams(params) {
10410
10532
  return changed;
10411
10533
  }
10412
10534
  function redactSensitivePairsInRawText(text) {
10413
- return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key, value) => {
10535
+ return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key) => {
10414
10536
  if (!isSensitiveNetworkKey(key)) {
10415
10537
  return full;
10416
10538
  }
10417
10539
  return `${prefix}${key}=[redacted]`;
10418
10540
  });
10419
10541
  }
10542
+ function looksLikeUrl(value) {
10543
+ return /^https?:\/\//i.test(value.trim()) || /^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim());
10544
+ }
10545
+ function truncateText(value, maxChars) {
10546
+ if (value.length <= maxChars) {
10547
+ return value;
10548
+ }
10549
+ return `${value.slice(0, maxChars)}…(truncated, total=${value.length})`;
10550
+ }
10551
+ function isPlainObject(value) {
10552
+ return Object.prototype.toString.call(value) === '[object Object]';
10553
+ }
10554
+
10555
+ function sanitizePresentationText(value, limit) {
10556
+ return sanitizeDiagnosticMessage(String(redactNetworkLogValue(value))).slice(0, limit);
10557
+ }
10558
+ /** 当前快照与历史事件共用白名单,不保存授权资料或任意参数。 */
10559
+ function sanitizeHostInteractionSnapshot(input) {
10560
+ if (!input || typeof input !== 'object')
10561
+ return undefined;
10562
+ const item = input;
10563
+ if (typeof item.interactionId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(item.interactionId) ||
10564
+ (typeof item.kind !== 'string' || !['toast', 'loading', 'dialog', 'effect'].includes(item.kind)) ||
10565
+ (typeof item.mode !== 'string' || !['simulated', 'browser'].includes(item.mode)) ||
10566
+ typeof item.method !== 'string' || !Number.isFinite(item.startedAt))
10567
+ return undefined;
10568
+ return {
10569
+ interactionId: item.interactionId,
10570
+ kind: item.kind,
10571
+ mode: item.mode,
10572
+ method: sanitizePresentationText(item.method, 100),
10573
+ startedAt: item.startedAt,
10574
+ ...(typeof item.callId === 'string' ? { callId: sanitizePresentationText(item.callId, 100) } : {}),
10575
+ ...(typeof item.message === 'string' ? { message: sanitizePresentationText(item.message, 512) } : {}),
10576
+ ...(typeof item.title === 'string' ? { title: sanitizePresentationText(item.title, 120) } : {}),
10577
+ ...(item.status === 'success' || item.status === 'error' ? { status: item.status } : {}),
10578
+ ...(typeof item.dismissible === 'boolean' ? { dismissible: item.dismissible } : {}),
10579
+ ...(Array.isArray(item.actions) ? { actions: item.actions.slice(0, 4).filter((value) => typeof value === 'string').map(value => sanitizePresentationText(value, 40)) } : {}),
10580
+ };
10581
+ }
10582
+ function sanitizeHostInteraction(input) {
10583
+ const snapshot = sanitizeHostInteractionSnapshot(input);
10584
+ if (!snapshot)
10585
+ return undefined;
10586
+ const state = input.state;
10587
+ if (typeof state !== 'string' || !['shown', 'completed', 'confirmed', 'cancelled', 'expired', 'replaced', 'hidden', 'closed'].includes(state))
10588
+ return undefined;
10589
+ return { ...snapshot, state: state };
10590
+ }
10591
+
10592
+ /** 本机开发工具合同,不属于 Mini-program bridge 协议。 */
10593
+ const DEV_DIAGNOSTICS_SCHEMA_VERSION = 3;
10594
+ const DEV_SANDBOX_READ_MAX_BYTES = 16 * 1024;
10595
+ const DEV_PRESENTATION_MAX_INTERACTIONS = 16;
10420
10596
 
10421
10597
  const DEVICE_LOG_PATH = '/__hb_sdk__/device-logs';
10422
- const registryKey = Symbol.for('@heybox/hb-sdk/device-logs');
10423
- const registry = globalThis;
10424
- const stores = (registry[registryKey] ??= new Map());
10425
- function registerDeviceLogs(port, store) {
10426
- stores.set(port, store);
10427
- return () => {
10428
- if (stores.get(port) === store)
10429
- stores.delete(port);
10598
+ const sessionRegistryKey = Symbol.for('@heybox/hb-sdk/dev-diagnostics-sessions');
10599
+ const sessionRegistry = globalThis;
10600
+ const sessions = (sessionRegistry[sessionRegistryKey] ??= new Map());
10601
+ function getDevDiagnosticsSession(id) {
10602
+ return sessions.get(id);
10603
+ }
10604
+ function safeMessage(value, limit = 8192) {
10605
+ const plain = (text) => text
10606
+ .replace(/https?:\/\/[^\s]+/gi, (raw) => {
10607
+ try {
10608
+ const url = new URL(raw.replace(/[),.;]+$/g, ''));
10609
+ url.username = '';
10610
+ url.password = '';
10611
+ url.search = '';
10612
+ url.hash = '';
10613
+ return url.href;
10614
+ }
10615
+ catch {
10616
+ return '[URL]';
10617
+ }
10618
+ })
10619
+ .replace(/(x-hb-sdk-[a-z0-9-]+|authorization|cookie|password|secret|token|hkey|pkey|nonce|api[_-]?key)(["'\s:=]+)([^\s,}]+)/gi, '$1$2[redacted]');
10620
+ // Runtime 事实以 JSON 文本保存;逐字段处理,避免 URL 正则吞掉 JSON 分隔符。
10621
+ if (/^\s*[\[{]/.test(value)) {
10622
+ try {
10623
+ const parsed = JSON.parse(value);
10624
+ return JSON.stringify(parsed, (key, item) => isSensitiveNetworkKey(key) || /^(hkey|nonce)$/i.test(key) || key.toLowerCase().startsWith('x-hb-sdk-')
10625
+ ? '[redacted]'
10626
+ : typeof item === 'string'
10627
+ ? plain(item)
10628
+ : item).slice(0, limit);
10629
+ }
10630
+ catch {
10631
+ /* 截断或非法 JSON 继续按普通文本保守脱敏。 */
10632
+ }
10633
+ }
10634
+ return plain(value).slice(0, limit);
10635
+ }
10636
+ function safeError(error) {
10637
+ return {
10638
+ code: /^[A-Z0-9_]{1,100}$/.test(error.code) ? error.code : 'RUNTIME_FAILED',
10639
+ message: safeMessage(error.message),
10640
+ ...(error.name ? { name: safeMessage(error.name, 100) } : {}),
10641
+ ...(error.stack ? { stack: safeMessage(error.stack) } : {}),
10642
+ ...(error.cause ? { cause: safeMessage(error.cause, 2048) } : {}),
10643
+ ...(error.phase ? { phase: safeMessage(error.phase, 100) } : {}),
10430
10644
  };
10431
10645
  }
10646
+ /** 一次 dev 进程拥有的有界事实记录;上传会话与 Runtime 实例独立。 */
10432
10647
  class DeviceLogStore {
10433
- sandboxRequests = new Map();
10434
- listSandbox(id, path) {
10435
- const device = this.devices.get(id);
10436
- if (!device || Date.now() - device.lastSeen > 15000)
10437
- return Promise.resolve({ error: '设备已离线' });
10438
- if (path !== '.' && (!path || path.length > 1024 || /[\\\\\u0000-\u001f]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..')))
10439
- return Promise.resolve({ error: '无效目录路径' });
10440
- if (this.sandboxRequests.size >= 64)
10441
- return Promise.resolve({ error: '查询繁忙,请稍后重试' });
10442
- const requestId = randomUUID();
10443
- return new Promise(resolve => {
10444
- const timer = setTimeout(() => { this.sandboxRequests.delete(requestId); resolve({ error: '设备查询超时' }); }, 10000);
10445
- this.sandboxRequests.set(requestId, { id, path, requestId, resolve: value => { clearTimeout(timer); this.sandboxRequests.delete(requestId); resolve(value); } });
10446
- });
10447
- }
10448
10648
  uploadToken = randomBytes(32).toString('hex');
10449
10649
  epoch = randomUUID();
10650
+ sessionId = this.epoch;
10450
10651
  expiresAt = Date.now() + 12 * 60 * 60 * 1000;
10451
10652
  cursor = 0;
10452
10653
  logs = [];
10453
- devices = new Map();
10654
+ instances = new Map();
10655
+ terminalInstances = new Map();
10656
+ targets = new Map();
10657
+ primaryTargetId;
10658
+ browserOwners = new Map();
10659
+ controlledBrowserToken;
10660
+ browserPageCredentials = new Map();
10661
+ hostSequences = new Map();
10662
+ pending = new Map();
10663
+ uploadSessions = new Map();
10664
+ targetSnapshot(target, now = Date.now()) {
10665
+ return { ...target, stale: target.state !== 'closed' && now - target.updatedAt > 15000 };
10666
+ }
10667
+ instanceSnapshot(instance, now = Date.now()) {
10668
+ return {
10669
+ ...instance,
10670
+ stale: instance.endedAt === undefined && now - (this.targets.get(instance.targetId)?.updatedAt ?? instance.updatedAt) > 15000,
10671
+ };
10672
+ }
10673
+ setSessionId(id) {
10674
+ this.sessionId = id;
10675
+ }
10676
+ registerTarget(input) {
10677
+ const existing = this.targets.get(input.targetId);
10678
+ if (existing && (existing.adapterId !== input.adapterId || existing.kind !== input.kind))
10679
+ throw new Error('TARGET_IDENTITY_MISMATCH');
10680
+ if (!existing && this.targets.size >= 128) {
10681
+ const closed = [...this.targets.values()].find((target) => target.state === 'closed' && (target.targetId !== this.primaryTargetId || input.primary));
10682
+ if (!closed)
10683
+ throw new Error('TARGET_LIMIT');
10684
+ this.targets.delete(closed.targetId);
10685
+ }
10686
+ if (existing && existing.ownerId !== input.ownerId) {
10687
+ for (const instance of this.instances.values())
10688
+ if (instance.targetId === input.targetId && instance.endedAt === undefined)
10689
+ this.updateInstance(instance.instanceId, { state: 'closed', reason: 'owner replaced' });
10690
+ }
10691
+ const metadata = this.targetMetadata(input.kind, { ...existing?.metadata, ...input.metadata });
10692
+ const target = {
10693
+ metadata,
10694
+ ...(existing?.cdpTargetId ? { cdpTargetId: existing.cdpTargetId } : {}),
10695
+ targetId: input.targetId,
10696
+ adapterId: input.adapterId,
10697
+ ownerId: input.ownerId,
10698
+ kind: input.kind,
10699
+ capabilities: input.capabilities,
10700
+ state: existing?.ownerId === input.ownerId ? existing.state : 'detached',
10701
+ currentInstanceId: existing?.ownerId === input.ownerId ? existing.currentInstanceId : null,
10702
+ updatedAt: Date.now(),
10703
+ };
10704
+ this.targets.set(target.targetId, target);
10705
+ this.trimOwnerState();
10706
+ if (input.primary)
10707
+ this.primaryTargetId = target.targetId;
10708
+ return this.targetSnapshot(target);
10709
+ }
10710
+ targetMetadata(kind, input) {
10711
+ const fields = Object.fromEntries(['browser', 'os', 'deviceModel', 'osVersion'].flatMap((key) => {
10712
+ const value = input[key];
10713
+ return typeof value === 'string' && value.trim() ? [[key, safeMessage(value.trim(), 100)]] : [];
10714
+ }));
10715
+ const displayName = (kind === 'browser' ? [fields.browser, fields.os] : [fields.deviceModel, [fields.os, fields.osVersion].filter(Boolean).join(' ')])
10716
+ .filter(Boolean)
10717
+ .join(' · ') || (kind === 'browser' ? '浏览器预览' : '原生 Host');
10718
+ return { ...fields, displayName };
10719
+ }
10720
+ requireTarget(targetId, ownerId) {
10721
+ const target = this.targets.get(targetId);
10722
+ if (!target || target.ownerId !== ownerId || target.state === 'closed')
10723
+ throw new Error('TARGET_OWNER_CHANGED');
10724
+ return target;
10725
+ }
10726
+ registerInstance(instanceId, owner) {
10727
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(instanceId))
10728
+ throw new Error('INVALID_INSTANCE');
10729
+ const target = this.requireTarget(owner.targetId, owner.ownerId);
10730
+ const existing = this.instances.get(instanceId);
10731
+ if (existing) {
10732
+ if (existing.targetId !== target.targetId || existing.ownerId !== target.ownerId)
10733
+ throw new Error('INSTANCE_OWNER_MISMATCH');
10734
+ return this.instanceSnapshot(existing);
10735
+ }
10736
+ if ([...this.instances.values()].filter((instance) => instance.endedAt === undefined).length >= 256)
10737
+ throw new Error('INSTANCE_LIMIT');
10738
+ const now = Date.now();
10739
+ const instance = {
10740
+ instanceId,
10741
+ targetId: target.targetId,
10742
+ ownerId: target.ownerId,
10743
+ adapterId: target.adapterId,
10744
+ kind: target.kind,
10745
+ capabilities: owner.capabilities ?? target.capabilities,
10746
+ state: 'starting',
10747
+ startedAt: now,
10748
+ updatedAt: now,
10749
+ startCursor: this.cursor,
10750
+ lastCursor: this.cursor,
10751
+ };
10752
+ this.instances.set(instanceId, instance);
10753
+ return this.instanceSnapshot(instance);
10754
+ }
10755
+ activateInstance(targetId, ownerId, instanceId) {
10756
+ const target = this.requireTarget(targetId, ownerId);
10757
+ const instance = this.instances.get(instanceId);
10758
+ if (!instance || instance.targetId !== targetId || instance.ownerId !== ownerId || instance.endedAt !== undefined)
10759
+ throw new Error('INSTANCE_NOT_ACTIVATABLE');
10760
+ if (target.currentInstanceId && target.currentInstanceId !== instanceId)
10761
+ this.updateInstance(target.currentInstanceId, { state: 'closed', reason: 'replaced' });
10762
+ target.currentInstanceId = instanceId;
10763
+ target.state = 'attached';
10764
+ target.updatedAt = Date.now();
10765
+ return this.targetSnapshot(target);
10766
+ }
10767
+ detachInstance(targetId, ownerId, instanceId, reason = 'detached') {
10768
+ const target = this.requireTarget(targetId, ownerId);
10769
+ if (target.currentInstanceId !== instanceId)
10770
+ return this.targetSnapshot(target);
10771
+ const instance = this.instances.get(instanceId);
10772
+ if (instance && instance.endedAt === undefined)
10773
+ this.updateInstance(instanceId, { state: 'closed', reason });
10774
+ target.currentInstanceId = null;
10775
+ target.state = 'detached';
10776
+ target.updatedAt = Date.now();
10777
+ return this.targetSnapshot(target);
10778
+ }
10779
+ closeTarget(targetId, ownerId, reason = 'target closed') {
10780
+ const target = this.targets.get(targetId);
10781
+ if (!target || target.ownerId !== ownerId)
10782
+ throw new Error('TARGET_OWNER_CHANGED');
10783
+ if (target.state === 'closed')
10784
+ return;
10785
+ for (const instance of this.instances.values())
10786
+ if (instance.targetId === targetId && instance.endedAt === undefined)
10787
+ this.updateInstance(instance.instanceId, { state: 'closed', reason });
10788
+ target.currentInstanceId = null;
10789
+ target.state = 'closed';
10790
+ target.updatedAt = Date.now();
10791
+ this.trimOwnerState();
10792
+ }
10793
+ createOwnedBrowserTarget(metadata) {
10794
+ if (this.controlledBrowserToken) {
10795
+ const previous = this.browserOwners.get(this.controlledBrowserToken);
10796
+ if (previous) {
10797
+ const oldTarget = this.targets.get(previous.targetId);
10798
+ if (oldTarget && oldTarget.state !== 'closed')
10799
+ this.closeTarget(oldTarget.targetId, oldTarget.ownerId, 'owned page replaced');
10800
+ previous.closed = true;
10801
+ }
10802
+ }
10803
+ const ownerId = randomUUID(), token = randomBytes(32).toString('hex'), targetId = `preview:${randomUUID()}`;
10804
+ this.registerTarget({
10805
+ targetId,
10806
+ ownerId,
10807
+ adapterId: targetId,
10808
+ kind: 'browser',
10809
+ primary: true,
10810
+ metadata,
10811
+ capabilities: { storage: true, sandboxList: false, sandboxRead: false, presentation: true },
10812
+ });
10813
+ this.browserOwners.set(token, { controllerOwnerId: ownerId, targetId, closed: false });
10814
+ this.controlledBrowserToken = token;
10815
+ this.trimBrowserOwners();
10816
+ return { targetId, ownerId, token };
10817
+ }
10818
+ trimBrowserOwners() {
10819
+ while (this.browserOwners.size > 128) {
10820
+ const old = [...this.browserOwners.entries()].find(([token, owner]) => owner.closed && token !== this.controlledBrowserToken);
10821
+ if (!old)
10822
+ throw new Error('BROWSER_OWNER_LIMIT');
10823
+ this.browserOwners.delete(old[0]);
10824
+ }
10825
+ }
10826
+ bindPhysicalTarget(ownerId, browserTargetId) {
10827
+ const owner = this.controlledBrowserToken && this.browserOwners.get(this.controlledBrowserToken);
10828
+ if (!owner || owner.controllerOwnerId !== ownerId || owner.closed)
10829
+ return false;
10830
+ const target = this.targets.get(owner.targetId);
10831
+ target.cdpTargetId = browserTargetId;
10832
+ return true;
10833
+ }
10834
+ closeOwnedBrowserTarget(ownerId) {
10835
+ const owner = this.controlledBrowserToken && this.browserOwners.get(this.controlledBrowserToken);
10836
+ if (!owner || owner.controllerOwnerId !== ownerId || owner.closed)
10837
+ return;
10838
+ this.closeTarget(owner.targetId, this.targets.get(owner.targetId).ownerId);
10839
+ owner.closed = true;
10840
+ }
10841
+ /** 受控 token 必须先由 HTTP owner 通过当前 CDP 文档验证,不能凭最后到达决定页面代。 */
10842
+ attachBrowserPage(pageId, controllerToken, metadata) {
10843
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(pageId))
10844
+ throw new Error('INVALID_PAGE_ID');
10845
+ const controller = controllerToken ? this.browserOwners.get(controllerToken) : undefined;
10846
+ if (controllerToken && (!controller || controller.closed))
10847
+ throw new Error('BROWSER_OWNER_CHANGED');
10848
+ if (controller?.currentPageToken && this.targets.get(controller.targetId)?.ownerId === pageId) {
10849
+ return { target: this.targetSnapshot(this.targets.get(controller.targetId)), ownerToken: controller.currentPageToken };
10850
+ }
10851
+ const targetId = controller?.targetId ?? `page:${randomUUID()}`;
10852
+ const target = this.registerTarget({
10853
+ targetId,
10854
+ adapterId: targetId,
10855
+ ownerId: pageId,
10856
+ kind: 'browser',
10857
+ metadata,
10858
+ capabilities: { storage: true, sandboxList: false, sandboxRead: false, presentation: true },
10859
+ });
10860
+ const ownerToken = randomBytes(32).toString('hex');
10861
+ this.browserPageCredentials.set(ownerToken, { targetId, ownerId: pageId, controllerToken });
10862
+ if (controller)
10863
+ controller.currentPageToken = ownerToken;
10864
+ this.trimOwnerState();
10865
+ return { target, ownerToken };
10866
+ }
10867
+ trimOwnerState() {
10868
+ for (const [token, credential] of this.browserPageCredentials) {
10869
+ const target = this.targets.get(credential.targetId);
10870
+ if (target?.ownerId === credential.ownerId && target.state !== 'closed')
10871
+ continue;
10872
+ if ([...this.instances.values()].some((instance) => instance.targetId === credential.targetId && instance.ownerId === credential.ownerId))
10873
+ continue;
10874
+ this.browserPageCredentials.delete(token);
10875
+ }
10876
+ for (const [key, actor] of this.hostSequences) {
10877
+ const target = this.targets.get(actor.targetId);
10878
+ if (target?.ownerId === actor.ownerId && target.state !== 'closed')
10879
+ continue;
10880
+ if ([...this.instances.values()].some((instance) => instance.targetId === actor.targetId && instance.ownerId === actor.ownerId))
10881
+ continue;
10882
+ this.hostSequences.delete(key);
10883
+ }
10884
+ }
10885
+ isControlledBrowserOwner(token) {
10886
+ return this.browserOwners.get(token)?.targetId === this.primaryTargetId && this.primaryTargetId !== undefined;
10887
+ }
10888
+ authorizeBrowserPage(token, targetId, ownerId, historicalInstanceId) {
10889
+ const credential = this.browserPageCredentials.get(token);
10890
+ if (!credential || credential.targetId !== targetId || credential.ownerId !== ownerId)
10891
+ return false;
10892
+ const target = this.targets.get(targetId);
10893
+ const controller = credential.controllerToken ? this.browserOwners.get(credential.controllerToken) : undefined;
10894
+ if (target?.ownerId === ownerId &&
10895
+ target.state !== 'closed' &&
10896
+ (!credential.controllerToken || (controller?.currentPageToken === token && !controller.closed)))
10897
+ return true;
10898
+ const historical = historicalInstanceId && this.instances.get(historicalInstanceId);
10899
+ return Boolean(historical && historical.endedAt !== undefined && historical.targetId === targetId && historical.ownerId === ownerId);
10900
+ }
10901
+ updateInstance(id, update) {
10902
+ const instance = this.instances.get(id);
10903
+ if (!instance)
10904
+ throw new Error('INSTANCE_NOT_FOUND');
10905
+ const uploadSession = update.uploadSessionId ? this.uploadSessions.get(update.uploadSessionId) : undefined;
10906
+ if (uploadSession?.instanceId && uploadSession.instanceId !== id)
10907
+ throw new Error('UPLOAD_SESSION_OWNER_MISMATCH');
10908
+ // 终态不可复活,但允许迟到的身份关联补全此前已保存的失败证据。
10909
+ if (update.runtimeId && !instance.runtimeId)
10910
+ instance.runtimeId = update.runtimeId.slice(0, 100);
10911
+ if (uploadSession) {
10912
+ uploadSession.instanceId = id;
10913
+ instance.uploadSessionId = uploadSession.id;
10914
+ for (const log of this.logs)
10915
+ if (log.uploadSessionId === uploadSession.id && !log.instanceId) {
10916
+ log.instanceId = id;
10917
+ log.targetId = instance.targetId;
10918
+ log.ownerId = instance.ownerId;
10919
+ log.late = this.terminalInstances.has(id) && log.cursor > this.terminalInstances.get(id);
10920
+ instance.lastCursor = Math.max(instance.lastCursor, log.cursor);
10921
+ }
10922
+ }
10923
+ if (instance.endedAt !== undefined)
10924
+ return this.instanceSnapshot(instance);
10925
+ instance.updatedAt = Date.now();
10926
+ instance.state = update.state;
10927
+ if (typeof update.documentVerifying === 'boolean')
10928
+ instance.documentVerifying = update.documentVerifying;
10929
+ if (update.error && typeof update.error.code === 'string' && typeof update.error.message === 'string')
10930
+ instance.error = safeError(update.error);
10931
+ if (update.reason)
10932
+ instance.reason = safeMessage(update.reason, 200);
10933
+ if (update.state === 'failed' || update.state === 'closed') {
10934
+ instance.endedAt = Date.now();
10935
+ this.terminalInstances.set(id, this.cursor);
10936
+ for (const request of this.pending.values())
10937
+ if (request.task.instanceId === id)
10938
+ request.resolve(this.resourceError(request.task, 'closed', 'RUNTIME_INSTANCE_CLOSED'));
10939
+ this.trimTerminalInstances();
10940
+ }
10941
+ return this.instanceSnapshot(instance);
10942
+ }
10943
+ trimTerminalInstances() {
10944
+ while (this.terminalInstances.size > 64) {
10945
+ const oldest = this.terminalInstances.keys().next().value;
10946
+ this.terminalInstances.delete(oldest);
10947
+ this.instances.delete(oldest);
10948
+ for (const [uploadId, upload] of this.uploadSessions)
10949
+ if (upload.instanceId === oldest)
10950
+ this.uploadSessions.delete(uploadId);
10951
+ for (const target of this.targets.values())
10952
+ if (target.currentInstanceId === oldest)
10953
+ target.currentInstanceId = null;
10954
+ }
10955
+ this.trimOwnerState();
10956
+ }
10957
+ appendHostEvents(identity, events, producerId, sequence) {
10958
+ const instance = identity.instanceId === undefined ? undefined : this.instances.get(identity.instanceId);
10959
+ if (identity.instanceId !== undefined && !instance)
10960
+ throw new Error('INSTANCE_NOT_FOUND');
10961
+ if (instance && (instance.targetId !== identity.targetId || instance.ownerId !== identity.ownerId))
10962
+ throw new Error('INSTANCE_OWNER_MISMATCH');
10963
+ if (!instance || instance.endedAt === undefined)
10964
+ this.requireTarget(identity.targetId, identity.ownerId);
10965
+ if (!instance && events.some((event) => !event || event.source !== 'host'))
10966
+ throw new Error('RUNTIME_INSTANCE_REQUIRED');
10967
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(producerId) || !Number.isSafeInteger(sequence) || sequence < 1)
10968
+ throw new Error('INVALID_SEQUENCE');
10969
+ const key = JSON.stringify([identity.targetId, identity.ownerId]);
10970
+ const previous = this.hostSequences.get(key);
10971
+ if (previous && previous.producerId !== producerId)
10972
+ throw new Error('INVALID_PRODUCER');
10973
+ if (previous && previous.sequence >= sequence)
10974
+ return previous.sequence;
10975
+ for (const event of events)
10976
+ if (event && (event.source === 'host' || event.source === 'runtime'))
10977
+ this.append(event, identity);
10978
+ if (instance)
10979
+ instance.lastCursor = this.cursor;
10980
+ this.hostSequences.set(key, { targetId: identity.targetId, ownerId: identity.ownerId, producerId, sequence });
10981
+ return sequence;
10982
+ }
10983
+ append(event, identity) {
10984
+ if (!event ||
10985
+ !Number.isFinite(event.timestamp) ||
10986
+ typeof event.message !== 'string' ||
10987
+ !['log', 'debug', 'info', 'warn', 'error'].includes(event.level))
10988
+ return;
10989
+ const network = event.network;
10990
+ const interaction = event.source === 'host' ? sanitizeHostInteraction(event.interaction) : undefined;
10991
+ this.logs.push({
10992
+ cursor: ++this.cursor,
10993
+ ...identity,
10994
+ ...(identity.instanceId && this.instances.has(identity.instanceId)
10995
+ ? { targetId: this.instances.get(identity.instanceId).targetId, ownerId: this.instances.get(identity.instanceId).ownerId }
10996
+ : {}),
10997
+ timestamp: event.timestamp,
10998
+ receivedAt: Date.now(),
10999
+ late: Boolean(identity.instanceId && this.instances.get(identity.instanceId)?.endedAt !== undefined),
11000
+ level: event.level,
11001
+ source: event.source,
11002
+ message: safeMessage(event.message),
11003
+ truncated: event.truncated === true || event.message.length > 8192,
11004
+ ...(typeof event.phase === 'string' ? { phase: event.phase.slice(0, 100) } : {}),
11005
+ ...(typeof event.method === 'string' ? { method: event.method.slice(0, 100) } : {}),
11006
+ ...(typeof event.callId === 'string' ? { callId: event.callId.slice(0, 100) } : {}),
11007
+ ...(typeof event.errorCode === 'string' && /^[A-Z0-9_]{1,100}$/.test(event.errorCode) ? { errorCode: event.errorCode } : {}),
11008
+ ...(['started', 'success', 'error', 'cancelled', 'dropped'].includes(event.outcome ?? '') ? { outcome: event.outcome } : {}),
11009
+ ...(Number.isFinite(event.startedAt) ? { startedAt: event.startedAt } : {}),
11010
+ ...(Number.isFinite(event.durationMs) ? { durationMs: Math.max(0, event.durationMs) } : {}),
11011
+ ...(interaction ? { interaction } : {}),
11012
+ ...(network
11013
+ ? {
11014
+ network: {
11015
+ ...(typeof network.method === 'string' ? { method: network.method.slice(0, 20) } : {}),
11016
+ ...(typeof network.origin === 'string' ? { origin: safeMessage(network.origin, 256) } : {}),
11017
+ ...(typeof network.pathname === 'string' ? { pathname: safeMessage(network.pathname.split('?')[0], 1024) } : {}),
11018
+ ...(Number.isInteger(network.responseStatus) ? { responseStatus: network.responseStatus } : {}),
11019
+ },
11020
+ }
11021
+ : {}),
11022
+ });
11023
+ if (this.logs.length > 5000)
11024
+ this.logs.splice(0, this.logs.length - 5000);
11025
+ }
11026
+ snapshot() {
11027
+ return {
11028
+ schemaVersion: DEV_DIAGNOSTICS_SCHEMA_VERSION,
11029
+ sessionId: this.sessionId,
11030
+ epoch: this.epoch,
11031
+ nextCursor: this.cursor,
11032
+ uploadSessions: [...this.uploadSessions.values()].map(({ id, browser, os, deviceModel, connectedAt, lastSeen }) => ({
11033
+ id,
11034
+ name: [browser, os, deviceModel].filter(Boolean).join(' · '),
11035
+ browser,
11036
+ os,
11037
+ ...(deviceModel ? { deviceModel } : {}),
11038
+ connectedAt,
11039
+ lastSeen,
11040
+ online: Date.now() - lastSeen < 15000,
11041
+ })),
11042
+ };
11043
+ }
11044
+ inspect() {
11045
+ const now = Date.now();
11046
+ const targets = [...this.targets.values()].map((target) => this.targetSnapshot(target, now));
11047
+ // 对外保留登记顺序;同毫秒创建、旧实例更新和迟到事件都不会重排,调用方可取最后一次启动尝试。
11048
+ const instances = [...this.instances.values()].map((instance) => this.instanceSnapshot(instance, now));
11049
+ const primaryTarget = targets.find((target) => target.targetId === this.primaryTargetId) ?? null;
11050
+ const currentInstance = instances.find((instance) => instance.instanceId === primaryTarget?.currentInstanceId) ?? null;
11051
+ return {
11052
+ ...this.snapshot(),
11053
+ targets,
11054
+ primaryTargetId: this.primaryTargetId ?? null,
11055
+ primaryTarget,
11056
+ timestamp: now,
11057
+ instances,
11058
+ currentInstance,
11059
+ recentFailure: [...this.terminalInstances.keys()]
11060
+ .map((id) => this.instanceSnapshot(this.instances.get(id), now))
11061
+ .filter((instance) => instance.state === 'failed')
11062
+ .at(-1) ?? null,
11063
+ stale: primaryTarget?.stale ?? false,
11064
+ };
11065
+ }
10454
11066
  query(params) {
10455
11067
  const after = Math.max(0, Number(params.get('after')) || 0);
10456
11068
  const limit = Math.min(500, Math.max(1, Number(params.get('limit')) || 100));
10457
11069
  const selected = this.logs.filter((log) => log.cursor > after &&
10458
- (!params.get('device') || log.deviceSessionId === params.get('device')) &&
11070
+ (!params.get('uploadSessionId') || log.uploadSessionId === params.get('uploadSessionId')) &&
11071
+ (!params.get('instanceId') || log.instanceId === params.get('instanceId')) &&
11072
+ (!params.get('targetId') || log.targetId === params.get('targetId')) &&
10459
11073
  (!params.get('level') || log.level === params.get('level')) &&
10460
- (!params.get('source') || log.source === params.get('source')) &&
11074
+ (params.get('problems') !== 'true' || log.level === 'warn' || log.level === 'error') &&
11075
+ (!params.get('phase') || log.phase === params.get('phase')) &&
11076
+ (!params.get('source') ||
11077
+ (params.get('source') === 'network'
11078
+ ? (log.source === 'sdk' || log.source === 'host') && (Boolean(log.network) || log.method === 'network.request')
11079
+ : log.source === params.get('source'))) &&
10461
11080
  (!params.get('callId') || log.callId === params.get('callId')) &&
10462
11081
  (!params.get('id') || String(log.cursor) === params.get('id')) &&
10463
11082
  (!params.get('since') || log.timestamp >= Number(params.get('since'))) &&
10464
- (!params.get('query') || log.message.toLowerCase().includes(params.get('query').toLowerCase())));
11083
+ (!params.get('query') ||
11084
+ [log.message, log.method, log.errorCode, log.network?.method, log.network?.origin, log.network?.pathname, log.network?.responseStatus, log.interaction?.interactionId, log.interaction?.kind, log.interaction?.state]
11085
+ .filter((value) => value !== undefined)
11086
+ .join(' ')
11087
+ .toLowerCase()
11088
+ .includes(params.get('query').toLowerCase())));
10465
11089
  const items = selected.slice(0, limit);
10466
11090
  return {
10467
- schemaVersion: 1,
10468
- epoch: this.epoch,
11091
+ ...this.snapshot(),
10469
11092
  items,
10470
11093
  nextCursor: selected.length > limit ? items.at(-1).cursor : this.cursor,
10471
11094
  hasMore: selected.length > limit,
10472
11095
  gap: after > 0 && after < (this.logs[0]?.cursor ?? 1) - 1,
10473
- devices: [...this.devices.values()].map(({ id, name, platform, connectedAt, lastSeen }) => ({
10474
- id,
10475
- name,
10476
- platform,
10477
- connectedAt,
10478
- lastSeen,
10479
- online: Date.now() - lastSeen < 15000,
10480
- })),
10481
11096
  };
10482
11097
  }
11098
+ resourceError(task, code, error = code) {
11099
+ const instance = this.instances.get(task.instanceId);
11100
+ const reason = instance?.reason ?? instance?.error?.code;
11101
+ return {
11102
+ instanceId: task.instanceId,
11103
+ requestId: task.requestId,
11104
+ resource: task.resource,
11105
+ timestamp: Date.now(),
11106
+ stale: instance ? this.instanceSnapshot(instance).stale : false,
11107
+ ...(instance ? {
11108
+ lastKnownState: instance.state,
11109
+ lastSeenAt: this.targets.get(instance.targetId)?.updatedAt ?? instance.updatedAt,
11110
+ ...(reason ? { reason } : {}),
11111
+ } : {}),
11112
+ code,
11113
+ error,
11114
+ };
11115
+ }
11116
+ ownsInstance(instanceId, targetId, ownerId) {
11117
+ const instance = this.instances.get(instanceId);
11118
+ return instance?.targetId === targetId && instance.ownerId === ownerId;
11119
+ }
11120
+ closeAdapter(adapterId, reason = 'adapter closed') {
11121
+ for (const target of this.targets.values())
11122
+ if (target.adapterId === adapterId && target.state !== 'closed')
11123
+ this.closeTarget(target.targetId, target.ownerId, reason);
11124
+ }
11125
+ queryResource(instanceId, resource, path, signal, options = {}) {
11126
+ const task = {
11127
+ requestId: randomUUID(),
11128
+ instanceId,
11129
+ resource,
11130
+ path,
11131
+ deadline: Date.now() + 10000,
11132
+ ...(resource === 'sandbox'
11133
+ ? {
11134
+ operation: options.operation ?? 'list',
11135
+ ...(options.operation === 'read' ? { maxBytes: options.maxBytes ?? DEV_SANDBOX_READ_MAX_BYTES } : {}),
11136
+ }
11137
+ : {}),
11138
+ };
11139
+ if (path !== undefined && (typeof path !== 'string' || !path || path.length > 1024))
11140
+ return Promise.resolve(this.resourceError(task, 'invalid'));
11141
+ const instance = this.instances.get(instanceId);
11142
+ if (!instance)
11143
+ return Promise.resolve(this.resourceError(task, 'invalid', 'RUNTIME_INSTANCE_NOT_FOUND'));
11144
+ if (instance.endedAt !== undefined)
11145
+ return Promise.resolve(this.resourceError(task, 'closed', 'RUNTIME_INSTANCE_CLOSED'));
11146
+ if (this.instanceSnapshot(instance).stale)
11147
+ return Promise.resolve(this.resourceError(task, 'offline', 'HOST_UNRESPONSIVE'));
11148
+ if (task.operation === 'read' && (!Number.isSafeInteger(task.maxBytes) || task.maxBytes < 1 || task.maxBytes > DEV_SANDBOX_READ_MAX_BYTES))
11149
+ return Promise.resolve(this.resourceError(task, 'invalid'));
11150
+ if (resource === 'sandbox' && !(task.operation === 'read' ? instance.capabilities.sandboxRead : instance.capabilities.sandboxList))
11151
+ return Promise.resolve(this.resourceError(task, 'unsupported'));
11152
+ if (resource === 'presentation' && !instance.capabilities.presentation)
11153
+ return Promise.resolve(this.resourceError(task, 'unsupported'));
11154
+ if (resource === 'storage' && !instance.capabilities.storage)
11155
+ return Promise.resolve(this.resourceError(task, 'unsupported'));
11156
+ if (this.pending.size >= 64)
11157
+ return Promise.resolve(this.resourceError(task, 'busy'));
11158
+ return new Promise((resolve) => {
11159
+ const abort = () => finish(this.resourceError(task, 'closed', 'RESOURCE_QUERY_CANCELLED'));
11160
+ const timer = setTimeout(() => finish(this.resourceError(task, 'timeout', 'RESOURCE_QUERY_TIMEOUT')), 10000);
11161
+ const finish = (value) => {
11162
+ clearTimeout(timer);
11163
+ signal?.removeEventListener('abort', abort);
11164
+ this.pending.delete(task.requestId);
11165
+ resolve(value);
11166
+ };
11167
+ this.pending.set(task.requestId, { task, resolve: finish });
11168
+ signal?.addEventListener('abort', abort, { once: true });
11169
+ if (signal?.aborted)
11170
+ abort();
11171
+ });
11172
+ }
11173
+ pollResources(targetId, ownerId) {
11174
+ const target = this.requireTarget(targetId, ownerId);
11175
+ target.updatedAt = Date.now();
11176
+ const tasks = [];
11177
+ // 原生通道最多接收 64 KiB,按实际 JSON UTF-8 字节预留一半预算,不能按字符数猜大小。
11178
+ for (const pending of [...this.pending.values()]) {
11179
+ if (this.instances.get(pending.task.instanceId)?.targetId !== targetId || this.instances.get(pending.task.instanceId)?.ownerId !== ownerId)
11180
+ continue;
11181
+ if (Buffer.byteLength(JSON.stringify({ tasks: [...tasks, pending.task] })) > 32 * 1024)
11182
+ break;
11183
+ tasks.push(pending.task);
11184
+ // 轮转已发送项;慢查询和响应丢失不会饿死下一批,调用方按 requestId 去重。
11185
+ this.pending.delete(pending.task.requestId);
11186
+ this.pending.set(pending.task.requestId, pending);
11187
+ }
11188
+ return { tasks };
11189
+ }
11190
+ completeResource(requestId, instanceId, result) {
11191
+ const pending = this.pending.get(requestId);
11192
+ if (!pending || pending.task.instanceId !== instanceId)
11193
+ return false;
11194
+ if (pending.task.resource === 'sandbox' && pending.task.operation === 'read' && result.code === undefined) {
11195
+ const file = result.value;
11196
+ const maxBytes = pending.task.maxBytes;
11197
+ if (!file ||
11198
+ file.encoding !== 'base64' ||
11199
+ typeof file.data !== 'string' ||
11200
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data) ||
11201
+ typeof file.byteLength !== 'number' ||
11202
+ !Number.isSafeInteger(file.byteLength) ||
11203
+ file.byteLength < 0 ||
11204
+ file.byteLength > maxBytes ||
11205
+ Buffer.byteLength(file.data, 'base64') !== file.byteLength ||
11206
+ typeof file.truncated !== 'boolean') {
11207
+ pending.resolve(this.resourceError(pending.task, 'invalid'));
11208
+ return false;
11209
+ }
11210
+ }
11211
+ if (pending.task.resource === 'presentation') {
11212
+ if (result.code !== undefined) {
11213
+ // 错误只返回状态与受限原因,不允许 value 绕过呈现白名单。
11214
+ result = { code: result.code, error: result.error };
11215
+ }
11216
+ else {
11217
+ const snapshot = result.value;
11218
+ if (!snapshot || snapshot.instanceId !== instanceId || !Array.isArray(snapshot.interactions) || snapshot.interactions.length > DEV_PRESENTATION_MAX_INTERACTIONS) {
11219
+ pending.resolve(this.resourceError(pending.task, 'invalid'));
11220
+ return false;
11221
+ }
11222
+ const interactions = snapshot.interactions.map(sanitizeHostInteractionSnapshot);
11223
+ if (interactions.some(item => item === undefined)) {
11224
+ pending.resolve(this.resourceError(pending.task, 'invalid'));
11225
+ return false;
11226
+ }
11227
+ result = { ...result, value: { instanceId, interactions } };
11228
+ }
11229
+ }
11230
+ const serialized = JSON.stringify(result.value);
11231
+ if (serialized && Buffer.byteLength(serialized) > 65536) {
11232
+ pending.resolve(this.resourceError(pending.task, 'invalid'));
11233
+ return false;
11234
+ }
11235
+ const codes = ['unsupported', 'forbidden', 'offline', 'closed', 'timeout', 'busy', 'invalid'];
11236
+ if (result.code !== undefined && !codes.includes(result.code)) {
11237
+ pending.resolve(this.resourceError(pending.task, 'invalid'));
11238
+ return false;
11239
+ }
11240
+ pending.resolve({
11241
+ instanceId,
11242
+ requestId,
11243
+ resource: pending.task.resource,
11244
+ timestamp: Date.now(),
11245
+ stale: false,
11246
+ ...(result.value === undefined ? {} : { value: result.value }),
11247
+ ...(result.code === undefined ? {} : { code: result.code }),
11248
+ ...(typeof result.error === 'string' ? { error: safeMessage(result.error, 2048) } : {}),
11249
+ });
11250
+ return true;
11251
+ }
10483
11252
  async upload(req, res) {
10484
11253
  const reply = (status, value) => {
10485
11254
  res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
@@ -10510,34 +11279,42 @@ class DeviceLogStore {
10510
11279
  return;
10511
11280
  }
10512
11281
  const registrationId = typeof body.registrationId === 'string' && /^[a-f0-9]{32}$/.test(body.registrationId) ? body.registrationId : undefined;
10513
- const existing = registrationId && [...this.devices.values()].find(device => device.registrationId === registrationId);
11282
+ const existing = registrationId && [...this.uploadSessions.values()].find((device) => device.registrationId === registrationId);
10514
11283
  if (existing) {
10515
11284
  reply(200, { id: existing.id, token: existing.token });
10516
11285
  return;
10517
11286
  }
10518
- if (this.devices.size >= 64) {
10519
- reply(429, {});
10520
- return;
11287
+ if (this.uploadSessions.size >= 64) {
11288
+ const offline = [...this.uploadSessions.values()].find((device) => Date.now() - device.lastSeen >= 15000);
11289
+ if (offline)
11290
+ this.uploadSessions.delete(offline.id);
11291
+ else {
11292
+ reply(429, {});
11293
+ return;
11294
+ }
10521
11295
  }
10522
- const id = randomUUID();
10523
- const platform = ['iOS', 'Android', 'Windows', 'macOS', 'Browser'].includes(body.platform) ? body.platform : 'Browser';
11296
+ const id = randomUUID(), now = Date.now();
11297
+ const browser = ['Chrome', 'Edge', 'Firefox', 'Safari', 'WebView'].includes(body.browser) ? body.browser : 'Other';
11298
+ const os = ['iOS', 'Android', 'Windows', 'macOS', 'Linux'].includes(body.os) ? body.os : 'Other';
11299
+ const deviceModel = typeof body.deviceModel === 'string' ? safeMessage(body.deviceModel, 100) : undefined;
10524
11300
  const device = {
10525
11301
  id,
10526
- platform,
11302
+ browser,
11303
+ os,
11304
+ deviceModel,
10527
11305
  registrationId,
10528
- connectedAt: Date.now(),
10529
- name: `${platform} · ${this.devices.size + 1}`,
10530
- lastSeen: Date.now(),
11306
+ connectedAt: now,
11307
+ lastSeen: now,
10531
11308
  sequence: 0,
10532
11309
  token: randomBytes(32).toString('hex'),
10533
- windowStart: Date.now(),
11310
+ windowStart: now,
10534
11311
  count: 0,
10535
11312
  };
10536
- this.devices.set(id, device);
11313
+ this.uploadSessions.set(id, device);
10537
11314
  reply(200, { id, token: device.token });
10538
11315
  return;
10539
11316
  }
10540
- const device = this.devices.get(body.id);
11317
+ const device = this.uploadSessions.get(body.id);
10541
11318
  if (!device || req.headers['x-hb-log-token'] !== device.token) {
10542
11319
  reply(403, {});
10543
11320
  return;
@@ -10556,46 +11333,24 @@ class DeviceLogStore {
10556
11333
  }
10557
11334
  device.count += body.logs.length;
10558
11335
  device.lastSeen = Date.now();
10559
- if (body.sandboxResult && typeof body.sandboxResult === 'object') {
10560
- const result = body.sandboxResult;
10561
- const pending = this.sandboxRequests.get(result.requestId);
10562
- if (pending?.id === device.id) {
10563
- const entries = Array.isArray(result.entries) ? result.entries.slice(0, 200).filter((entry) => entry && ['file', 'directory'].includes(entry.kind) && typeof entry.name === 'string' && entry.name.length <= 255 && !/[\\\\/\u0000-\u001f]/.test(entry.name) && !['.', '..'].includes(entry.name)).map((entry) => ({ name: entry.name, kind: entry.kind })) : [];
10564
- pending.resolve({ deviceSessionId: device.id, requestId: pending.requestId, path: pending.path, timestamp: Date.now(), entries, error: result.error ? '设备不支持或无权读取此目录' : undefined, truncated: result.truncated === true });
10565
- }
10566
- }
11336
+ const instance = device.instanceId ? this.instances.get(device.instanceId) : undefined;
10567
11337
  for (const log of body.logs) {
10568
- if (!log || typeof log !== 'object')
10569
- continue;
10570
- if (!Number.isSafeInteger(log.sequence) ||
10571
- log.sequence <= device.sequence ||
10572
- !Number.isFinite(log.timestamp) ||
10573
- !['log', 'debug', 'info', 'warn', 'error'].includes(log.level) ||
10574
- typeof log.message !== 'string')
11338
+ if (!log || !Number.isSafeInteger(log.sequence) || log.sequence <= device.sequence)
10575
11339
  continue;
11340
+ if (log.sequence > device.sequence + 1)
11341
+ this.append({
11342
+ source: 'app',
11343
+ level: 'warn',
11344
+ message: `上传序号缺口:${device.sequence + 1}–${log.sequence - 1}`,
11345
+ timestamp: Date.now(),
11346
+ truncated: true,
11347
+ }, { uploadSessionId: device.id, ...(instance ? { instanceId: instance.instanceId } : {}) });
10576
11348
  device.sequence = log.sequence;
10577
- this.logs.push({
10578
- cursor: ++this.cursor,
10579
- deviceSessionId: device.id,
10580
- sequence: log.sequence,
10581
- timestamp: log.timestamp,
10582
- receivedAt: Date.now(),
10583
- level: log.level,
10584
- source: log.source === 'sdk' ? 'sdk' : 'app',
10585
- message: sanitizeDiagnosticMessage(log.message)
10586
- .replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)(["'\s:=]+)([^\s,}]+)/gi, '$1$2[redacted]')
10587
- .slice(0, 8192),
10588
- truncated: log.truncated === true || log.message.length > 8192,
10589
- ...(typeof log.method === 'string' ? { method: log.method.slice(0, 100) } : {}),
10590
- ...(typeof log.callId === 'string' ? { callId: log.callId.slice(0, 100) } : {}),
10591
- ...(typeof log.errorCode === 'string' && /^[A-Z0-9_]{1,100}$/.test(log.errorCode) ? { errorCode: log.errorCode } : {}),
10592
- ...(log.outcome === 'success' || log.outcome === 'error' ? { outcome: log.outcome } : {}),
10593
- ...(Number.isFinite(log.durationMs) ? { durationMs: Math.max(0, log.durationMs) } : {}),
10594
- });
11349
+ this.append({ ...log, source: log.source === 'sdk' ? 'sdk' : 'app', phase: log.source === 'sdk' ? 'client' : undefined }, { uploadSessionId: device.id, sequence: log.sequence, ...(instance ? { instanceId: instance.instanceId } : {}) });
10595
11350
  }
10596
- if (this.logs.length > 5000)
10597
- this.logs.splice(0, this.logs.length - 5000);
10598
- 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 });
11351
+ if (instance)
11352
+ instance.lastCursor = this.cursor;
11353
+ reply(200, { sequence: device.sequence });
10599
11354
  }
10600
11355
  catch {
10601
11356
  reply(400, { code: 'INVALID_LOG_BATCH' });
@@ -10606,11 +11361,15 @@ class DeviceLogStore {
10606
11361
  function deviceLogBootstrap(token) {
10607
11362
  return `<script>(function(){if(window.__hb_sdk_device_logs_installed__)return;
10608
11363
  window.__hb_sdk_device_logs_installed__=true;
10609
- window.__hb_sdk_mini_dev_console_installed__=true;
10610
- var endpoint='${DEVICE_LOG_PATH}',credential='${token}',id='',queue=[],seq=0,busy=false,dropped=0,retryDelay=1000;
11364
+ var endpoint='${DEVICE_LOG_PATH}',registrationCredential='${token}',credential=registrationCredential,id='',queue=[],seq=0,busy=false,dropped=0,retryDelay=1000;
10611
11365
  var registrationId=Array.from(crypto.getRandomValues(new Uint8Array(16)),function(n){return n.toString(16).padStart(2,'0')}).join('');
11366
+ function documentSignal(phase){if(window.parent===window)return;
11367
+ var navigation=performance.getEntriesByType('navigation')[0];
11368
+ window.parent.postMessage({type:'hb-sdk:dev-document',phase:phase,documentId:registrationId,href:location.href,nonce:new URL(location.href).searchParams.get('hb_mini_bridge_nonce'),navigationType:navigation?navigation.type:'navigate'},'*')}
11369
+ documentSignal('boot');
11370
+ window.addEventListener('pagehide',function(){documentSignal('leaving')});
11371
+ window.addEventListener('pageshow',function(){documentSignal('boot')});
10612
11372
  var send=window.fetch.bind(window);
10613
- var sandboxResult;
10614
11373
  function format(v){try{return typeof v==='string'?v:v instanceof Error?v.stack||v.message:JSON.stringify(v,function(k,value){return /authorization|cookie|password|secret|token|pkey|api.?key/i.test(k)?'[redacted]':value})}catch(e){return '[无法序列化]'}}function add(level,args,source){if(queue.length>=500){queue.shift();
10615
11374
  dropped++}var message=args.map(format).join(' ');
10616
11375
  message=message.replace(/https?:\\/\\/[^\\s]+/g,function(raw){try{var url=new URL(raw);
@@ -10620,29 +11379,32 @@ url.search='';
10620
11379
  url.hash='';
10621
11380
  return url.href}catch(e){return '[URL]'}});
10622
11381
  message=message.replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\\"'\\s:=]+)([^\\s,}]+)/gi,'$1$2[redacted]');
10623
- queue.push({truncated:message.length>8192,sequence:++seq,timestamp:Date.now(),level:level,source:source||'app',message:message.slice(0,8192)})}window.__hbSdkDeviceLog=function(event){add(event.outcome==='error'?'error':'info',[event.method+' · '+event.outcome+' · '+event.durationMs+' ms'],'sdk');
10624
- Object.assign(queue[queue.length-1],event)};
11382
+ queue.push({truncated:message.length>8192,sequence:++seq,timestamp:Date.now(),level:level,source:source||'app',message:message.slice(0,8192)})}window.__hbSdkDevObserver=function(event){add(event.outcome==='error'?'error':'info',[event.method+' · '+event.outcome+' · '+event.durationMs+' ms'],'sdk');
11383
+ var entry=queue[queue.length-1];['phase','method','callId','outcome','durationMs','errorCode','timestamp','startedAt'].forEach(function(key){if(event[key]!==undefined)entry[key]=event[key]})};
10625
11384
  ['log','debug','info','warn','error'].forEach(function(level){var original=console[level];
10626
11385
  console[level]=function(){add(level,Array.prototype.slice.call(arguments));
10627
11386
  return original.apply(this,arguments)}});
10628
- window.addEventListener('error',function(e){add('error',[e.message])});
11387
+ window.addEventListener('error',function(e){add('error',[e.error||e.message])});
10629
11388
  window.addEventListener('unhandledrejection',function(e){add('error',[e.reason])});
10630
11389
  async function flush(){if(busy)return;
10631
11390
  busy=true;
10632
11391
  var success=false;
10633
11392
  try{if(!id){var ua=navigator.userAgent;
10634
- var 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';
10635
- 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)});
11393
+ var browser=/Edg\\//.test(ua)?'Edge':/Chrome|CriOS/.test(ua)?'Chrome':/Firefox|FxiOS/.test(ua)?'Firefox':/Safari/.test(ua)?'Safari':'Other';
11394
+ var os=/Android/.test(ua)?'Android':/iPhone|iPad/.test(ua)?'iOS':/Windows/.test(ua)?'Windows':/Mac/.test(ua)?'macOS':/Linux/.test(ua)?'Linux':'Other';
11395
+ var model=navigator.userAgentData&&navigator.userAgentData.model;
11396
+ var r=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({register:true,browser:browser,os:os,deviceModel:typeof model==='string'?model.slice(0,100):undefined,registrationId:registrationId}),signal:AbortSignal.timeout(5000)});
10636
11397
  if(!r.ok)throw 0;
10637
11398
  var d=await r.json();
10638
- id=d.id;
11399
+ id=d.id;document.documentElement.dataset.hbSdkDeviceSessionId=id;
11400
+ if(window.parent!==window)window.parent.postMessage({type:'hb-sdk:dev-upload-session',deviceSessionId:id},'*');
10639
11401
  credential=d.token}if(dropped){add('warn',['日志缓冲已丢弃 '+dropped+' 条']);
10640
11402
  dropped=0}var batch=queue.slice(0,50);
10641
11403
  while(batch.length>1&&new TextEncoder().encode(JSON.stringify(batch)).length>48000)batch.pop();
10642
- var result=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({id:id,logs:batch,sandboxResult:sandboxResult}),signal:AbortSignal.timeout(5000)});
11404
+ var result=await send(endpoint,{method:'POST',headers:{'content-type':'application/json','x-hb-log-token':credential},body:JSON.stringify({id:id,logs:batch}),signal:AbortSignal.timeout(5000)});
11405
+ if(result.status===403){id='';credential=registrationCredential;throw 0}
10643
11406
  if(!result.ok)throw 0;
10644
- var ack=await result.json();sandboxResult=undefined;
10645
- if(ack.sandboxRequest){try{var entries=await window.__hbSdkSandboxList(ack.sandboxRequest.path);sandboxResult={requestId:ack.sandboxRequest.requestId,entries:entries.slice(0,200),truncated:entries.length>200}}catch(e){sandboxResult={requestId:ack.sandboxRequest.requestId,error:true}}}
11407
+ var ack=await result.json();
10646
11408
  queue=queue.filter(function(l){return l.sequence>ack.sequence});success=true}catch(e){}finally{retryDelay=success?1000:Math.min(retryDelay*2,30000);busy=false;setTimeout(flush,retryDelay)}}
10647
11409
  flush()})();
10648
11410
  </script>`;
@@ -20307,6 +21069,42 @@ function walk$1(node, visit) {
20307
21069
  walk$1(node.content, visit);
20308
21070
  }
20309
21071
 
21072
+ /** 约束构建产物中的 HTTPS source,禁止通配、IP、端口及 CSP 注入。 */
21073
+ function normalizeMiniappBuildImageDomain(value) {
21074
+ if (typeof value !== 'string' || value !== value.trim() || value.length > 253)
21075
+ return undefined;
21076
+ const domain = value.toLowerCase();
21077
+ if (!domain.includes('.') || /^\d+(?:\.\d+)*$/.test(domain))
21078
+ return undefined;
21079
+ if (!domain.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))
21080
+ return undefined;
21081
+ if (domain.endsWith('.localhost') || domain.endsWith('.local') || domain.endsWith('.internal'))
21082
+ return undefined;
21083
+ return domain;
21084
+ }
21085
+ /** SDK 构建层独立消费平台资料;Runtime 继续独立校验可信启动策略。 */
21086
+ function parseMiniappBuildImagePolicy(value) {
21087
+ if (value === undefined || value === null)
21088
+ return undefined;
21089
+ if (typeof value !== 'object' || Array.isArray(value))
21090
+ throw new TypeError('图片构建策略格式无效');
21091
+ const record = value;
21092
+ const entries = record.entries === undefined ? [] : record.entries;
21093
+ if (!Number.isSafeInteger(record.revision) || record.revision < 1 ||
21094
+ (record.enforcement !== 'approved_domains' && record.enforcement !== 'restricted') ||
21095
+ !Array.isArray(entries) || entries.length > 20)
21096
+ throw new TypeError('图片构建策略格式无效');
21097
+ const domains = new Set();
21098
+ for (const entry of entries) {
21099
+ const domain = normalizeMiniappBuildImageDomain(entry && typeof entry === 'object' ? entry.domain : undefined);
21100
+ if (!domain)
21101
+ throw new TypeError('图片构建策略包含无效域名');
21102
+ domains.add(domain);
21103
+ }
21104
+ return Object.freeze({ revision: record.revision, enforcement: record.enforcement,
21105
+ entries: Object.freeze([...domains].sort().map((domain) => Object.freeze({ domain }))) });
21106
+ }
21107
+
20310
21108
  const FORBIDDEN_RESOURCE_HINTS = new Set(['dns-prefetch', 'preconnect', 'prerender']);
20311
21109
  const RELATIVE_URL_BASE = new URL('https://heybox-relative.invalid/');
20312
21110
  const OFFICIAL_RESOURCE_ROOT_DOMAINS = ['xiaoheihe.cn', 'max-c.com', 'debugmode.cn', 'maxjia.com'];
@@ -20314,11 +21112,13 @@ const OFFICIAL_RESOURCE_SOURCES = OFFICIAL_RESOURCE_ROOT_DOMAINS.flatMap((rootDo
20314
21112
  // 受控媒体预览通道:iOS `hbmini-media://preview/...`、鸿蒙 OHOS `hbmedia://<sessionId>/<previewId>`。
20315
21113
  // 两者是宿主注册的自定义 scheme,只允许出现在图片/媒体资源加载指令中,不放宽其它指令。
20316
21114
  const MEDIA_PREVIEW_SCHEME_SOURCES = ['hbmini-media:', 'hbmedia:'];
21115
+ // 平台图片的精确基础源,依据 SDK share 用例及 Host 菜单图片合同;不授予公开接口请求。
21116
+ const PLATFORM_IMAGE_DOMAINS = ['imgheybox.max-c.com'];
20317
21117
  const URL_ATTRIBUTES = {
20318
21118
  audio: ['src'],
20319
21119
  embed: ['src'],
20320
21120
  iframe: ['src'],
20321
- img: ['src'],
21121
+ img: ['src', 'srcset'],
20322
21122
  input: ['src'],
20323
21123
  object: ['data'],
20324
21124
  script: ['src'],
@@ -20331,7 +21131,7 @@ const PRODUCTION_CSP = [
20331
21131
  "connect-src 'none'",
20332
21132
  `script-src 'self' 'unsafe-inline' ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20333
21133
  `style-src 'self' 'unsafe-inline' ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20334
- `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
21134
+ `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${PLATFORM_IMAGE_DOMAINS.map((domain) => `https://${domain}`).join(' ')}`,
20335
21135
  `font-src 'self' data: ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20336
21136
  `media-src 'self' blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')} ${OFFICIAL_RESOURCE_SOURCES.join(' ')}`,
20337
21137
  "manifest-src 'self'",
@@ -20350,18 +21150,26 @@ function enforceMiniappHtmlPolicy(html, options = {}) {
20350
21150
  throw new Error('入口 index.html 必须包含 <head>');
20351
21151
  }
20352
21152
  removePlatformCspMarkers(document);
20353
- walk(document, (element) => validateElement(element));
21153
+ const imageDomains = new Set([...PLATFORM_IMAGE_DOMAINS, ...(options.approvedImageDomains ?? [])].map((domain) => {
21154
+ const normalized = normalizeMiniappBuildImageDomain(domain);
21155
+ if (!normalized)
21156
+ throw new Error('图片策略包含无效域名');
21157
+ return normalized;
21158
+ }));
21159
+ walk(document, (element) => validateElement(element, imageDomains));
20354
21160
  injectMiniappRuntimeGate(document);
20355
- if (options.skipPlatformCsp) {
20356
- return serialize(document);
20357
- }
21161
+ // 保留旧参数的类型兼容,但网络授权不能再移除 CSP。
20358
21162
  const connectSources = Array.from(new Set([
20359
- options.hmrWebSocketUrl,
21163
+ ...(options.hmrWebSocketUrls ?? []),
20360
21164
  ...(options.deviceLogUploadUrls ?? []),
20361
21165
  ].filter((source) => Boolean(source))));
20362
- const content = connectSources.length > 0
20363
- ? PRODUCTION_CSP.replace("connect-src 'none'", `connect-src ${connectSources.join(' ')}`)
20364
- : PRODUCTION_CSP;
21166
+ const imagePolicy = PRODUCTION_CSP.replace(/img-src[^;]*/, `img-src 'self' data: blob: ${MEDIA_PREVIEW_SCHEME_SOURCES.join(' ')}${[...imageDomains].sort().map((domain) => ` https://${domain}`).join('')}`);
21167
+ let content = connectSources.length > 0
21168
+ ? imagePolicy.replace("connect-src 'none'", `connect-src ${connectSources.join(' ')}`)
21169
+ : imagePolicy;
21170
+ // Vite 8 通过 Blob SharedWorker 等待 HMR 重连;只在显式开发 WS 入口存在时放行。
21171
+ if (options.hmrWebSocketUrls?.length)
21172
+ content = content.replace("worker-src 'none'", 'worker-src blob:');
20365
21173
  head.childNodes.unshift({
20366
21174
  nodeName: 'meta',
20367
21175
  tagName: 'meta',
@@ -20377,7 +21185,7 @@ function enforceMiniappHtmlPolicy(html, options = {}) {
20377
21185
  });
20378
21186
  return serialize(document);
20379
21187
  }
20380
- function validateElement(element) {
21188
+ function validateElement(element, imageDomains) {
20381
21189
  const tagName = element.tagName.toLowerCase();
20382
21190
  const attrs = new Map(element.attrs.map((attr) => [attr.name.toLowerCase(), attr.value]));
20383
21191
  if (tagName === 'meta' && attrs.get('http-equiv')?.toLowerCase() === 'refresh') {
@@ -20407,19 +21215,41 @@ function validateElement(element) {
20407
21215
  }
20408
21216
  for (const attribute of URL_ATTRIBUTES[tagName] ?? []) {
20409
21217
  const value = attrs.get(attribute);
21218
+ const imageResource = tagName === 'img' || (tagName === 'input' && attrs.get('type') === 'image') ||
21219
+ (tagName === 'video' && attribute === 'poster') ||
21220
+ (tagName === 'source' && element.parentNode && 'tagName' in element.parentNode && element.parentNode.tagName === 'picture');
21221
+ const validate = (candidate) => {
21222
+ if (imageResource && candidate && isApprovedImageUrl(candidate, imageDomains))
21223
+ return;
21224
+ validateResourceUrl(candidate, `<${tagName} ${attribute}>`, true, !imageResource && supportsOfficialResourceUrl(tagName, attribute));
21225
+ };
20410
21226
  if (attribute === 'srcset') {
21227
+ // 单个 data URL 的逗号属于 URL 内容,不能拆成第二个候选地址。
21228
+ if (value?.trim().toLowerCase().startsWith('data:') && !/\s(?:\d+(?:\.\d+)?[wx])\s*,/.test(value)) {
21229
+ validate(value.trim().split(/\s+/)[0]);
21230
+ continue;
21231
+ }
20411
21232
  for (const candidate of (value ?? '')
20412
21233
  .split(',')
20413
21234
  .map((item) => item.trim().split(/\s+/)[0])
20414
21235
  .filter(Boolean)) {
20415
- validateResourceUrl(candidate, `<${tagName} ${attribute}>`, true, supportsOfficialResourceUrl(tagName, attribute));
21236
+ validate(candidate);
20416
21237
  }
20417
21238
  }
20418
21239
  else {
20419
- validateResourceUrl(value, `<${tagName} ${attribute}>`, true, supportsOfficialResourceUrl(tagName, attribute));
21240
+ validate(value);
20420
21241
  }
20421
21242
  }
20422
21243
  }
21244
+ function isApprovedImageUrl(value, domains) {
21245
+ try {
21246
+ const url = new URL(value);
21247
+ return url.protocol === 'https:' && !url.port && !url.username && !url.password && domains.has(url.hostname.toLowerCase());
21248
+ }
21249
+ catch {
21250
+ return false;
21251
+ }
21252
+ }
20423
21253
  function removePlatformCspMarkers(node) {
20424
21254
  if (!('childNodes' in node))
20425
21255
  return;
@@ -20504,13 +21334,32 @@ function walk(node, visit) {
20504
21334
  walk(node.content, visit);
20505
21335
  }
20506
21336
 
20507
- const HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV = 'HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN';
20508
21337
  const HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV = 'HB_SDK_RUNTIME_PERMISSION_CONTEXT';
20509
21338
  const VERIFIED_RUNTIME_PERMISSION_CONTEXT = 'verified';
21339
+ const NETWORK_POLICY_ENV = 'HB_SDK_RUNTIME_NETWORK_POLICY';
20510
21340
  new AsyncLocalStorage();
20511
21341
  Promise.resolve();
20512
- function shouldSkipMiniappPlatformCspFromEnv(env = process.env) {
20513
- return env[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] === VERIFIED_RUNTIME_PERMISSION_CONTEXT && env[HB_SDK_RUNTIME_USE_OFFICIAL_DOMAIN_ENV] === '1';
21342
+ function shouldSkipMiniappPlatformCspFromEnv(_env = process.env) {
21343
+ return false;
21344
+ }
21345
+ function readMiniappApprovedImageDomainsFromEnv(env = process.env) {
21346
+ if (env[HB_SDK_RUNTIME_PERMISSION_CONTEXT_ENV] !== VERIFIED_RUNTIME_PERMISSION_CONTEXT || !env[NETWORK_POLICY_ENV])
21347
+ return [];
21348
+ return parseMiniappBuildImagePolicy(JSON.parse(env[NETWORK_POLICY_ENV]))?.entries.map((entry) => entry.domain) ?? [];
21349
+ }
21350
+
21351
+ // 配置文件由 Vite 重新加载,可能产生另一份模块实例;私有标记只用于同进程插件间交接。
21352
+ const POLICY_SOURCE = Symbol.for('@heybox/hb-sdk/dev-network-policy-source');
21353
+ /** 空清单也必须覆盖构建环境快照,防止撤权后恢复旧域名。 */
21354
+ function readMiniappDevApprovedImageDomains(plugins) {
21355
+ for (const plugin of plugins ?? []) {
21356
+ if (!plugin || typeof plugin !== 'object')
21357
+ continue;
21358
+ const source = plugin[POLICY_SOURCE];
21359
+ if (typeof source === 'function')
21360
+ return source();
21361
+ }
21362
+ return undefined;
20514
21363
  }
20515
21364
 
20516
21365
  /** 与平台 H5 保持相同的语法兼容下限;SDK 独立分发,不依赖内部 Platform 包。 */
@@ -20553,29 +21402,8 @@ function assertMiniappBuildCompiler(esbuild) {
20553
21402
  }
20554
21403
  }
20555
21404
 
20556
- /**
20557
- * dev serve 时在入口 HTML 最早位置注入无依赖 console 捕获 bootstrap。
20558
- *
20559
- * 必须内联完整 patch 逻辑而非等 SDK 模块加载:vite client、业务代码的 console 调用
20560
- * 都可能早于 SDK 单例初始化(如 [vite] connecting)。捕获条件:
20561
- * 1. 构建期只有 vite serve 走到本分支(生产构建无此代码,双保险之 define 常量仍注入给 SDK 侧);
20562
- * 2. 运行期仅调试 iframe(window.name 标记由调试台 iframe.name 与本 bootstrap 设置)激活。
20563
- * 转发经 window.parent.postMessage(CSP connect-src 不约束 postMessage),失败静默,
20564
- * 严禁回打 console 造成自触发循环。SDK 侧 installMiniDevConsoleForwarding 安装时
20565
- * 检测同款 INSTALL_FLAG,不会重复 patch。
20566
- */
20567
- function injectMiniDevConsoleBootstrap(html) {
20568
- const bootstrap = `<script>(function(){var LEVELS=['log','debug','info','warn','error'];var FLAG='${MINI_DEV_CONSOLE_INSTALL_FLAG}';var TYPE='${MINI_DEV_CONSOLE_EVENT_TYPE}';if(window[FLAG])return;var patched=false;for(var i=0;i<LEVELS.length;i++)(function(level){var original=console[level];if(typeof original!=='function')return;console[level]=function(){try{parent.postMessage({type:TYPE,detail:{level:level,args:Array.prototype.slice.call(arguments),timestamp:Date.now()}},'*')}catch(e){}return original.apply(this,arguments)};patched=true})(LEVELS[i]);if(patched)window[FLAG]=true})();</script>`;
20569
- const headIndex = html.indexOf('<head>');
20570
- if (headIndex < 0) {
20571
- return html;
20572
- }
20573
- const insertAt = headIndex + '<head>'.length;
20574
- return `${html.slice(0, insertAt)}${bootstrap}${html.slice(insertAt)}`;
20575
- }
20576
21405
  const sdkVersionPlaceholder = ['__HB_SDK', 'VERSION__'].join('_');
20577
21406
  const sdkVersionBuildConstant = ['__HB_SDK_BUILD', 'VERSION__'].join('_');
20578
- const miniDevLoggingConstant = ['__HB_SDK_DEV', 'LOGGING__'].join('_');
20579
21407
  const DEV_MANIFEST_PATH = '/__hb_sdk__/companion/manifest.json';
20580
21408
  /**
20581
21409
  * 本地 PC 调试开窗时的 manifest 入口。
@@ -20622,6 +21450,10 @@ if (!devSnapshotRegistry[devSnapshotStoreKey]) {
20622
21450
  });
20623
21451
  }
20624
21452
  const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
21453
+ // 配置重载沿当前 server 的异步调用链传递 owner;同项目的另一台 dev 不共享记录。
21454
+ const diagnosticsOwnerKey = Symbol.for('@heybox/hb-sdk/vite-diagnostics-owner');
21455
+ const diagnosticsOwnerRegistry = globalThis;
21456
+ const diagnosticsOwner = (diagnosticsOwnerRegistry[diagnosticsOwnerKey] ??= new AsyncLocalStorage());
20625
21457
  /**
20626
21458
  * 创建工坊小程序使用的 Vite 插件。
20627
21459
  *
@@ -20671,14 +21503,15 @@ const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
20671
21503
  * 转换 Vite 编译脚本的 JavaScript 语法,保留更旧的自定义目标,拒绝 `esbuild: false`;注入 SDK 构建版本,且仅
20672
21504
  * `vite serve` 注入开发日志编译常量。语法转换不处理原样复制或远端加载的脚本,不包含运行时 API polyfill,
20673
21505
  * 也不会更新已发布旧产物;
20674
- * - `configResolved`:确认插件唯一性,记录真实 `root`、`build.outDir`、`serve|build` 命令和精确 HMR
20675
- * WebSocket 地址,并再次确认生产环境的语法兼容目标;直接 `vite build` 使用该实际 `outDir`,
21506
+ * - `configResolved`:确认插件唯一性,记录真实 `root`、`build.outDir`、`serve|build` 命令和 HMR
21507
+ * 配置,并再次确认生产环境的语法兼容目标;直接 `vite build` 使用该实际 `outDir`,
20676
21508
  * `hb-sdk build` 则由 CLI 固定为 `dist/`;
20677
21509
  * - `configureServer`:为 `hb-sdk dev` 注册设备日志、本地小程序 Manifest 与 Companion Manifest/ZIP
20678
21510
  * 中间件;敏感路由只接受数值 loopback socket/Host、`GET|HEAD` 和 CLI 注入的独立短期令牌,快照在
20679
21511
  * 配置重载时按 digest 保留,并在服务真正关闭时清理;
20680
21512
  * - `transformIndexHtml`:校验 HTML URL/标签策略,注入 Runtime Gate;默认注入平台 CSP,serve 时
20681
- * `connect-src` 只开放解析出的 HMR WebSocket,并额外注入调试日志 bootstrap;
21513
+ * `connect-src` 按实际监听入口与显式 HMR 配置放行精确 WebSocket 地址,关闭 HMR 时不添加该许可,
21514
+ * 并额外注入调试日志 bootstrap;
20682
21515
  * - `buildEnd`:记住更早的 Rollup/Vite 错误,避免 `closeBundle` 的二次产物错误遮盖根因;
20683
21516
  * - `closeBundle`:serve 时直接完成;build 时复检最终 HTML,要求整个输出树只有根 `index.html`,再于
20684
21517
  * `build.outDir` 写入 `manifest.json`,并把 Companion 目录打包成
@@ -20734,14 +21567,19 @@ const devSnapshotStores = devSnapshotRegistry[devSnapshotStoreKey];
20734
21567
  */
20735
21568
  function miniappManifest() {
20736
21569
  const includeCompanions = process.env.HB_SDK_SKIP_COMPANIONS !== '1';
20737
- const deviceLogs = new DeviceLogStore();
20738
- const skipPlatformCsp = shouldSkipMiniappPlatformCspFromEnv();
21570
+ const diagnosticsSessionId = process.env.HB_SDK_DEV_DIAGNOSTICS_SESSION_ID;
21571
+ const managedDiagnostics = diagnosticsSessionId ? getDevDiagnosticsSession(diagnosticsSessionId) : undefined;
21572
+ if (diagnosticsSessionId && !managedDiagnostics)
21573
+ throw new Error('指定的开发诊断会话不存在,请通过 hb-sdk dev 重新启动服务');
21574
+ const deviceLogs = managedDiagnostics ?? diagnosticsOwner.getStore() ?? new DeviceLogStore();
21575
+ shouldSkipMiniappPlatformCspFromEnv();
21576
+ let approvedImageDomains = readMiniappApprovedImageDomainsFromEnv();
20739
21577
  let companionArtifactAccessToken = parseDevAccessToken(process.env[HB_SDK_COMPANION_ARTIFACT_ACCESS_TOKEN_ENV]);
20740
21578
  let miniProgramManifestAccessToken = parseDevAccessToken(process.env[HB_SDK_MINI_PROGRAM_MANIFEST_ACCESS_TOKEN_ENV]);
20741
21579
  let root = process.cwd();
20742
21580
  let outDir = 'dist';
20743
21581
  let command = 'build';
20744
- let hmrWebSocketUrl;
21582
+ let resolvedConfig;
20745
21583
  let configuredDeviceLogUploadUrls = [];
20746
21584
  let devServer;
20747
21585
  let metadataWarningsShown = false;
@@ -20770,8 +21608,6 @@ function miniappManifest() {
20770
21608
  ...(buildTargets ? { build: { target: buildTargets } } : {}),
20771
21609
  define: {
20772
21610
  [sdkVersionBuildConstant]: JSON.stringify(resolveSdkVersion()),
20773
- // 仅 vite serve(hb-sdk dev)注入;vite build / hb-sdk build 永不注入,捕获模块被死代码消除。
20774
- ...(isServe ? { [miniDevLoggingConstant]: 'true' } : {}),
20775
21611
  },
20776
21612
  };
20777
21613
  },
@@ -20785,6 +21621,9 @@ function miniappManifest() {
20785
21621
  root = resolved.root;
20786
21622
  outDir = resolved.build.outDir;
20787
21623
  command = resolved.command;
21624
+ if (command === 'serve') {
21625
+ approvedImageDomains = readMiniappDevApprovedImageDomains(resolved.plugins) ?? approvedImageDomains;
21626
+ }
20788
21627
  if (command === 'build') {
20789
21628
  assertMiniappBuildCompiler(resolved.esbuild);
20790
21629
  resolved.build.target = resolveMiniappBuildTargets(resolved.build.target);
@@ -20793,7 +21632,7 @@ function miniappManifest() {
20793
21632
  environment.build.target = resolveMiniappBuildTargets(environment.build.target);
20794
21633
  }
20795
21634
  }
20796
- hmrWebSocketUrl = resolveHmrWebSocketUrl(resolved);
21635
+ resolvedConfig = resolved;
20797
21636
  configuredDeviceLogUploadUrls = resolveConfiguredDeviceLogUploadUrls(resolved);
20798
21637
  },
20799
21638
  configureServer(server) {
@@ -20827,16 +21666,6 @@ function miniappManifest() {
20827
21666
  server.config.logger.warn(`[${warning.code}] ${warning.message}`);
20828
21667
  metadataWarningsShown = true;
20829
21668
  }
20830
- let unregisterLogs;
20831
- const registerLogs = () => {
20832
- const address = server.httpServer?.address();
20833
- if (address && typeof address !== 'string')
20834
- unregisterLogs = registerDeviceLogs(address.port, deviceLogs);
20835
- };
20836
- server.httpServer?.once('listening', registerLogs);
20837
- server.httpServer?.once('close', () => unregisterLogs?.());
20838
- if (server.httpServer?.listening)
20839
- registerLogs();
20840
21669
  let store = devSnapshotStores.get(root);
20841
21670
  companionArtifactAccessToken ??= store?.token;
20842
21671
  // 与 Companion 令牌同因:配置重载时 env 已不在,只能从同一服务的注册表恢复。
@@ -20856,7 +21685,7 @@ function miniappManifest() {
20856
21685
  server.restart = async (forceOptimize) => {
20857
21686
  store.restarting = true;
20858
21687
  try {
20859
- await restart(forceOptimize);
21688
+ await diagnosticsOwner.run(deviceLogs, () => restart(forceOptimize));
20860
21689
  }
20861
21690
  finally {
20862
21691
  store.restarting = false;
@@ -21117,14 +21946,13 @@ function miniappManifest() {
21117
21946
  ...(command === 'serve'
21118
21947
  ? {
21119
21948
  deviceLogUploadUrls: Array.from(new Set([...configuredDeviceLogUploadUrls, ...resolveViteDeviceLogUploadUrls(devServer?.resolvedUrls)])),
21120
- hmrWebSocketUrl,
21949
+ // resolvedUrls 在 listen 后才包含实际端口与所有可访问网卡,不能在 configResolved 固化。
21950
+ hmrWebSocketUrls: resolveHmrWebSocketUrls(resolvedConfig, devServer),
21121
21951
  }
21122
21952
  : {}),
21123
- skipPlatformCsp,
21953
+ approvedImageDomains,
21124
21954
  });
21125
- return command === 'serve'
21126
- ? injectMiniDevConsoleBootstrap(enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`))
21127
- : enforced;
21955
+ return command === 'serve' ? enforced.replace('<head>', `<head>${deviceLogBootstrap(deviceLogs.uploadToken)}`) : enforced;
21128
21956
  },
21129
21957
  async closeBundle() {
21130
21958
  // Vite dev 的关闭/配置重载同样会触发此钩子,不执行发布打包。
@@ -21162,7 +21990,7 @@ function miniappManifest() {
21162
21990
  if (!htmlFiles.includes(indexHtmlPath)) {
21163
21991
  throw new Error('构建产物必须包含入口 dist/index.html');
21164
21992
  }
21165
- writeFileSync(indexHtmlPath, enforceMiniappHtmlPolicy(readFileSync(indexHtmlPath, 'utf8'), { skipPlatformCsp }));
21993
+ writeFileSync(indexHtmlPath, enforceMiniappHtmlPolicy(readFileSync(indexHtmlPath, 'utf8'), { approvedImageDomains }));
21166
21994
  const basicInfo = await prepareMiniappBasicInfo(companionConfig.projectRoot, outputRoot, sdkVersion);
21167
21995
  const cardConfig = readMiniappWorkspaceCardsFromPackageJson(root);
21168
21996
  const workspaceCards = typeof cardConfig.declaration === 'string'
@@ -21373,16 +22201,45 @@ function resolveSdkVersion() {
21373
22201
  }
21374
22202
  return packageJson.version;
21375
22203
  }
21376
- function resolveHmrWebSocketUrl(resolved) {
22204
+ function resolveHmrWebSocketUrls(resolved, server) {
22205
+ if (!resolved)
22206
+ return [];
21377
22207
  const hmr = resolved.server.hmr;
21378
22208
  if (hmr === false)
21379
- return undefined;
22209
+ return [];
21380
22210
  const options = typeof hmr === 'object' ? hmr : {};
21381
- const protocol = options.protocol ?? (resolved.server.https ? 'wss' : 'ws');
21382
- const configuredHost = options.host ?? resolved.server.host;
21383
- const host = typeof configuredHost === 'string' && configuredHost !== '0.0.0.0' ? configuredHost : '127.0.0.1';
21384
- const port = options.clientPort ?? options.port ?? resolved.server.port;
21385
- return `${protocol}://${host}${port ? `:${port}` : ''}`;
22211
+ const urls = [...(server?.resolvedUrls?.local ?? []), ...(server?.resolvedUrls?.network ?? [])];
22212
+ if (urls.length === 0) {
22213
+ const configuredHost = resolved.server.host;
22214
+ const host = typeof configuredHost === 'string' && configuredHost !== '0.0.0.0' && configuredHost !== '::'
22215
+ ? configuredHost : '127.0.0.1';
22216
+ const address = server?.httpServer?.address();
22217
+ const port = address && typeof address !== 'string' ? address.port : resolved.server.port;
22218
+ const url = createDeviceLogUploadUrl(resolved.server.https ? 'https' : 'http', host, port);
22219
+ if (url)
22220
+ urls.push(url);
22221
+ }
22222
+ return Array.from(new Set(urls.flatMap((url) => {
22223
+ try {
22224
+ const source = new URL(url);
22225
+ if (source.protocol !== 'http:' && source.protocol !== 'https:')
22226
+ return [];
22227
+ const protocol = options.protocol || (source.protocol === 'https:' ? 'wss' : 'ws');
22228
+ const host = options.host || source.hostname;
22229
+ const normalizedHost = host.startsWith('[') || !host.includes(':') ? host : `[${host}]`;
22230
+ // 与 Vite client 一致:显式 clientPort/port 优先,否则从加载入口推导。
22231
+ const port = options.clientPort || options.port || source.port;
22232
+ const endpoint = new URL(`${protocol}://${normalizedHost}${port ? `:${port}` : ''}`);
22233
+ if (!['ws:', 'wss:'].includes(endpoint.protocol) || endpoint.hostname.includes('*')
22234
+ || ['0.0.0.0', '[::]'].includes(endpoint.hostname) || endpoint.username || endpoint.password
22235
+ || endpoint.pathname !== '/' || endpoint.search || endpoint.hash)
22236
+ return [];
22237
+ return [endpoint.origin];
22238
+ }
22239
+ catch {
22240
+ return [];
22241
+ }
22242
+ })));
21386
22243
  }
21387
22244
  function resolveConfiguredDeviceLogUploadUrls(resolved) {
21388
22245
  if (resolved.command !== 'serve')