@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/index.esm.js CHANGED
@@ -252,7 +252,7 @@ function redactUrlSearchParams(params) {
252
252
  return changed;
253
253
  }
254
254
  function redactSensitivePairsInRawText(text) {
255
- return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key, value) => {
255
+ return text.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g, (full, prefix, key) => {
256
256
  if (!isSensitiveNetworkKey(key)) {
257
257
  return full;
258
258
  }
@@ -424,6 +424,10 @@ const USER_SHOW_APPRECIATION_METHOD = 'user.showAppreciation';
424
424
  const SHARE_COPY_LINK_METHOD = 'share.copyLink';
425
425
  const SHARE_SHOW_SHARE_MENU_METHOD = 'share.showShareMenu';
426
426
  const SHARE_SCREENSHOT_METHOD = 'share.screenshot';
427
+ /** DOM 长图内部传输方法;业务仍调用 screenshotElement。
428
+ * @internal
429
+ */
430
+ const SHARE_SCREENSHOT_LONG_METHOD = 'share.screenshotLong';
427
431
  const VIEWPORT_SET_DISPLAY_METHOD = 'viewport.setDisplay';
428
432
  const VIEWPORT_GET_WINDOW_INFO_METHOD = 'viewport.getWindowInfo';
429
433
  const VIEWPORT_SET_NAVIGATION_BAR_STYLE_METHOD = 'viewport.setNavigationBarStyle';
@@ -7505,7 +7509,7 @@ function createMessageId() {
7505
7509
  /** 构建时替换为当前发布包的实际版本。 */
7506
7510
  const HB_SDK_VERSION = typeof undefined === 'string'
7507
7511
  ? undefined
7508
- : '0.9.6-alpha.1';
7512
+ : '0.9.6-alpha.11';
7509
7513
 
7510
7514
  const RUNTIME_MODES = new Set(['production', 'preview', 'development', 'unknown']);
7511
7515
  const OPERATING_SYSTEM_NAMES = new Set(['android', 'ios', 'ohos', 'windows', 'macos', 'linux', 'unknown']);
@@ -7552,7 +7556,7 @@ function readRecord$1(value) {
7552
7556
 
7553
7557
  const DEFAULT_TIMEOUT = 10000;
7554
7558
  // 选择器等待、截图延迟、登录和关注确认由 Host 管理,使用长操作生命周期,不设固定总时长。
7555
- const HOST_MANAGED_TIMEOUT_METHODS = new Set([FILES_PICK_FILES_METHOD, FILES_PICK_DIRECTORY_METHOD, FILES_SAVE_FILE_METHOD, SHARE_SCREENSHOT_METHOD, USER_REQUEST_FOLLOW_AUTHOR_METHOD]);
7559
+ const HOST_MANAGED_TIMEOUT_METHODS = new Set([FILES_PICK_FILES_METHOD, FILES_PICK_DIRECTORY_METHOD, FILES_SAVE_FILE_METHOD, SHARE_SCREENSHOT_METHOD, SHARE_SCREENSHOT_LONG_METHOD, USER_REQUEST_FOLLOW_AUTHOR_METHOD]);
7556
7560
  const HANDSHAKE_RETRY_INTERVAL = 250;
7557
7561
  /** 底层 bridge client,负责握手、请求响应、事件分发与超时清理。 */
7558
7562
  class MiniProgramBridgeClient {
@@ -7635,18 +7639,52 @@ class MiniProgramBridgeClient {
7635
7639
  }
7636
7640
  /** 调用父容器开放能力。 */
7637
7641
  async request(method, ...args) {
7638
- const accountVersion = this.accountEventVersion;
7639
- const result = await this.performRequest(method, args[0], !HOST_MANAGED_TIMEOUT_METHODS.has(method));
7640
- if (method === 'auth.getAccountState' && accountVersion !== this.accountEventVersion) {
7641
- throw createSDKError('AUTHORIZATION_CONTEXT_CHANGED', '读取期间账号状态发生变化,请保留较新的事件状态');
7642
- }
7643
- return result;
7642
+ return this.performRequest(method, args[0], !HOST_MANAGED_TIMEOUT_METHODS.has(method), undefined, true);
7644
7643
  }
7645
7644
  /** 发起不使用固定总时长 timer 的长操作。 */
7646
7645
  async requestOperation(method, payload, options = {}) {
7647
7646
  return this.performRequest(method, payload, false, options);
7648
7647
  }
7649
- async performRequest(method, payload, useTimeout, options = {}) {
7648
+ async performRequest(method, payload, useTimeout, options = {}, validateAccountState = false) {
7649
+ const id = createMessageId();
7650
+ // 接收端仅由开发 HTML 安装;读取和回调均隔离,不改变业务结果。
7651
+ let observer;
7652
+ try {
7653
+ const candidate = this.selfWindow?.__hbSdkDevObserver;
7654
+ if (typeof candidate === 'function')
7655
+ observer = candidate;
7656
+ }
7657
+ catch { /* 自定义 Window 的访问器也不能阻断请求。 */ }
7658
+ if (!observer)
7659
+ return this.executeRequest(id, method, payload, useTimeout, options, validateAccountState);
7660
+ const startedAt = Date.now();
7661
+ const startedMonotonic = diagnosticNow();
7662
+ const report = (outcome, error) => {
7663
+ try {
7664
+ const errorCode = error instanceof HbMiniProgramSDKError ? error.code : undefined;
7665
+ observer({ phase: 'client', method, callId: id, outcome, timestamp: Date.now(), startedAt,
7666
+ durationMs: Math.max(0, diagnosticNow() - startedMonotonic), ...(errorCode ? { errorCode } : {}) });
7667
+ }
7668
+ catch { /* 调试观察不得影响 SDK 调用。 */ }
7669
+ };
7670
+ report('started');
7671
+ try {
7672
+ const value = await this.executeRequest(id, method, payload, useTimeout, options, validateAccountState);
7673
+ report('success');
7674
+ return value;
7675
+ }
7676
+ catch (error) {
7677
+ let cancelled = false;
7678
+ try {
7679
+ cancelled = error instanceof HbMiniProgramSDKError && (error.code === 'REQUEST_CANCELLED' || error.code === 'OPERATION_CANCELLED');
7680
+ }
7681
+ catch { /* 自定义拒绝值可包含抛错的 Proxy,仍须保留原拒绝值。 */ }
7682
+ report(cancelled || options.signal?.aborted ? 'cancelled' : 'error', error);
7683
+ throw error;
7684
+ }
7685
+ }
7686
+ async executeRequest(id, method, payload, useTimeout, options, validateAccountState) {
7687
+ const accountVersion = this.accountEventVersion;
7650
7688
  if (this.destroyed) {
7651
7689
  throw createSDKError('SDK_DESTROYED', '小程序 SDK 已销毁');
7652
7690
  }
@@ -7676,7 +7714,6 @@ class MiniProgramBridgeClient {
7676
7714
  if (options.signal?.aborted) {
7677
7715
  throw options.createAbortError?.() ?? createSDKError('REQUEST_CANCELLED', `${method} 已取消`);
7678
7716
  }
7679
- const id = createMessageId();
7680
7717
  const message = {
7681
7718
  namespace: MINI_PROGRAM_MESSAGE_NAMESPACE,
7682
7719
  version: MINI_PROGRAM_MESSAGE_VERSION,
@@ -7686,18 +7723,7 @@ class MiniProgramBridgeClient {
7686
7723
  method,
7687
7724
  payload,
7688
7725
  };
7689
- const startedAt = Date.now();
7690
- const report = (outcome, error) => {
7691
- if (typeof false === 'undefined' || !false)
7692
- return;
7693
- try {
7694
- const target = this.selfWindow;
7695
- const errorCode = error instanceof HbMiniProgramSDKError ? error.code : undefined;
7696
- target?.__hbSdkDeviceLog?.({ method, callId: id, outcome, durationMs: Date.now() - startedAt, errorCode });
7697
- }
7698
- catch { /* 调试输出不能改变 SDK 调用结果。 */ }
7699
- };
7700
- return new Promise((resolve, reject) => {
7726
+ const result = await new Promise((resolve, reject) => {
7701
7727
  const pending = {
7702
7728
  resolve: resolve,
7703
7729
  reject,
@@ -7745,7 +7771,11 @@ class MiniProgramBridgeClient {
7745
7771
  pending.abortHandler();
7746
7772
  }
7747
7773
  }
7748
- }).then(value => { report('success'); return value; }, error => { report('error', error); throw error; });
7774
+ });
7775
+ if (validateAccountState && method === 'auth.getAccountState' && accountVersion !== this.accountEventVersion) {
7776
+ throw createSDKError('AUTHORIZATION_CONTEXT_CHANGED', '读取期间账号状态发生变化,请保留较新的事件状态');
7777
+ }
7778
+ return result;
7749
7779
  }
7750
7780
  /** 销毁 SDK 实例,并拒绝尚未完成的请求。 */
7751
7781
  destroy() {
@@ -8072,6 +8102,10 @@ function waitForHandshakeOrAbort(handshake, signal, createAbortError, getTermina
8072
8102
  onAbort();
8073
8103
  });
8074
8104
  }
8105
+ /** 诊断耗时独立于墙钟校时。 */
8106
+ function diagnosticNow() {
8107
+ return typeof performance === 'undefined' ? Date.now() : performance.now();
8108
+ }
8075
8109
 
8076
8110
  /**
8077
8111
  * 获取短期授权码。
@@ -10558,6 +10592,14 @@ function decodeBase64Url(value) {
10558
10592
  return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
10559
10593
  }
10560
10594
 
10595
+ let queue = Promise.resolve();
10596
+ /** 同页截图串行执行,避免长图捕获面遮挡另一次截图。 */
10597
+ function serializeScreenshot(capture) {
10598
+ const result = queue.then(capture);
10599
+ queue = result.catch(() => undefined);
10600
+ return result;
10601
+ }
10602
+
10561
10603
  /**
10562
10604
  * 截图并唤起分享。
10563
10605
  *
@@ -10574,13 +10616,169 @@ function decodeBase64Url(value) {
10574
10616
  * @see {@link MiniProgramScreenshotOptions}
10575
10617
  */
10576
10618
  function screenshot(requester, options) {
10619
+ return serializeScreenshot(() => captureScreenshot(requester, options));
10620
+ }
10621
+ /** 已持有截图队列的内部入口。 */
10622
+ function captureScreenshot(requester, options) {
10623
+ warnScreenshotWatermark();
10624
+ return requester.request(SHARE_SCREENSHOT_METHOD, options);
10625
+ }
10626
+ function warnScreenshotWatermark() {
10577
10627
  try {
10578
10628
  console.warn('[hb-sdk] share.screenshot 行为变更提醒:正式版 SDK 0.9.1 及以上默认添加小程序品牌水印;低于 0.9.1(含预发布版本)的 SDK 保持无水印截图。升级前请在目标截图区域底部预留至少 57 个逻辑像素,避免遮挡重要内容;watermarkTheme 的 light 为黑色水印,dark 为白色水印且是默认值,不自动跟随系统主题。系统按键截图不在此能力范围内。');
10579
10629
  }
10580
10630
  catch {
10581
10631
  // 日志输出失败不能阻断截图调用。
10582
10632
  }
10583
- return requester.request(SHARE_SCREENSHOT_METHOD, options);
10633
+ }
10634
+
10635
+ /** 将当前页面的 DOM 边界转换为逻辑像素矩形,再复用原截图分享流程。 */
10636
+ async function screenshotElement(requester, options) {
10637
+ return serializeScreenshot(() => captureElement(requester, options));
10638
+ }
10639
+ async function captureElement(requester, options) {
10640
+ if (!options || typeof options !== 'object' || Array.isArray(options) || 'rect' in options) {
10641
+ throw createSDKError('INVALID_PARAMS', 'share.screenshotElement 必须传入包含 element 的配置,且不能指定 rect');
10642
+ }
10643
+ const { element, ...screenshotOptions } = options;
10644
+ if (typeof window === 'undefined' || typeof document === 'undefined' || typeof Element === 'undefined'
10645
+ || !(element instanceof Element) || element.ownerDocument !== document || !element.isConnected) {
10646
+ throw createSDKError('INVALID_PARAMS', 'share.screenshotElement element 必须是当前页面中已挂载的 DOM 元素');
10647
+ }
10648
+ // DOMRect 已是当前窗口逻辑像素;不叠加滚动偏移,也不乘设备像素比。
10649
+ const { left, top, width, height } = element.getBoundingClientRect();
10650
+ const windowWidth = document.documentElement.clientWidth || window.innerWidth;
10651
+ const windowHeight = document.documentElement.clientHeight || window.innerHeight;
10652
+ const visibility = window.getComputedStyle(element).visibility;
10653
+ if (![left, top, width, height, windowWidth, windowHeight].every(Number.isFinite)
10654
+ || width <= 0 || height <= 0 || windowWidth <= 0 || windowHeight <= 0
10655
+ || element.getClientRects().length === 0 || visibility === 'hidden' || visibility === 'collapse') {
10656
+ throw createSDKError('INVALID_PARAMS', 'share.screenshotElement element 必须具有可见的布局尺寸');
10657
+ }
10658
+ // 原生只支持纵向拼接;横向溢出不能静默退化为可见区域截图。
10659
+ if (width >= windowWidth + 1 || element.scrollWidth > element.clientWidth + 1) {
10660
+ throw createSDKError('INVALID_PARAMS', '暂不支持横向长图:元素宽度不能超过窗口,且不能包含横向溢出内容');
10661
+ }
10662
+ if (height >= windowHeight + 1 || element.scrollHeight > height + 1) {
10663
+ if (width > windowWidth + 1)
10664
+ throw createSDKError('INVALID_PARAMS', '长图宽度不能超过窗口');
10665
+ return screenshotLongElement(requester, options);
10666
+ }
10667
+ // clientWidth/clientHeight 为整数,DOMRect 保留亚像素;仅容忍不足 1 个逻辑像素的边界误差。
10668
+ const tolerance = 1;
10669
+ const right = left + width;
10670
+ const bottom = top + height;
10671
+ if (left <= -tolerance || top <= -tolerance || right >= windowWidth + tolerance || bottom >= windowHeight + tolerance) {
10672
+ throw createSDKError('INVALID_PARAMS', 'share.screenshotElement element 的完整边界必须位于当前可见窗口内');
10673
+ }
10674
+ const clippedLeft = Math.max(0, left);
10675
+ const clippedTop = Math.max(0, top);
10676
+ const clippedWidth = left < 0 || right > windowWidth ? Math.min(windowWidth, right) - clippedLeft : width;
10677
+ const clippedHeight = top < 0 || bottom > windowHeight ? Math.min(windowHeight, bottom) - clippedTop : height;
10678
+ if (clippedWidth <= 0 || clippedHeight <= 0) {
10679
+ throw createSDKError('INVALID_PARAMS', 'share.screenshotElement element 必须与当前可见窗口相交');
10680
+ }
10681
+ return captureScreenshot(requester, { ...screenshotOptions, rect: { left: clippedLeft, top: clippedTop, width: clippedWidth, height: clippedHeight } });
10682
+ }
10683
+ /** 在业务文档准备长图捕获面,再交给宿主原生截图。调用方持有同页截图队列。 */
10684
+ async function screenshotLongElement(requester, { element, ...options }) {
10685
+ if (!element.isConnected)
10686
+ throw createSDKError('INVALID_PARAMS', '截图元素已卸载');
10687
+ const bounds = element.getBoundingClientRect();
10688
+ const height = Math.max(bounds.height, element.scrollHeight + bounds.height - element.clientHeight);
10689
+ if (height > 10000 || bounds.width > 2048 || bounds.width * height > 4000000) {
10690
+ throw createSDKError('INVALID_PARAMS', '长图尺寸超过限制(高度 10000、面积 400 万逻辑像素)');
10691
+ }
10692
+ if (element.matches('iframe,video,object,embed') || element.querySelector('iframe,video,object,embed')) {
10693
+ throw createSDKError('INVALID_PARAMS', '长图暂不支持嵌入网页和视频');
10694
+ }
10695
+ // 在业务自己的文档内复制,DOM 不经过 bridge,也不导出 Canvas 像素。
10696
+ if (!(element instanceof HTMLElement))
10697
+ throw createSDKError('INVALID_PARAMS', '长图需要 HTML 容器元素');
10698
+ const sources = [element, ...element.querySelectorAll('*')];
10699
+ if (sources.some(source => source.shadowRoot || source.localName.includes('-'))) {
10700
+ throw createSDKError('INVALID_PARAMS', '长图暂不支持自定义元素和 Shadow DOM');
10701
+ }
10702
+ const clone = element.cloneNode(true);
10703
+ const copies = [clone, ...clone.querySelectorAll('*')];
10704
+ for (let i = 0; i < sources.length; i++) {
10705
+ const source = sources[i];
10706
+ const copy = copies[i];
10707
+ if (!copy.style)
10708
+ continue;
10709
+ const computed = window.getComputedStyle(source);
10710
+ if (computed.position === 'fixed' || computed.position === 'sticky')
10711
+ throw createSDKError('INVALID_PARAMS', '长图暂不支持固定或吸顶元素');
10712
+ for (let j = 0; j < computed.length; j++) {
10713
+ const name = computed.item(j);
10714
+ copy.style.setProperty(name, computed.getPropertyValue(name), 'important');
10715
+ }
10716
+ copy.style.setProperty('animation', 'none', 'important');
10717
+ copy.style.setProperty('transition', 'none', 'important');
10718
+ if (source instanceof HTMLCanvasElement) {
10719
+ copy.getContext('2d')?.drawImage(source, 0, 0);
10720
+ }
10721
+ if (source instanceof HTMLInputElement)
10722
+ copy.value = source.value;
10723
+ if (source instanceof HTMLTextAreaElement)
10724
+ copy.value = source.value;
10725
+ if (source instanceof HTMLSelectElement)
10726
+ copy.selectedIndex = source.selectedIndex;
10727
+ if (source instanceof HTMLImageElement) {
10728
+ copy.src = source.currentSrc || source.src;
10729
+ copy.removeAttribute('srcset');
10730
+ copy.loading = 'eager';
10731
+ }
10732
+ }
10733
+ if (window.getComputedStyle(element).backgroundColor === 'rgba(0, 0, 0, 0)')
10734
+ clone.style.setProperty('background-color', 'white', 'important');
10735
+ clone.querySelectorAll('script').forEach(script => script.remove());
10736
+ clone.setAttribute('aria-hidden', 'true');
10737
+ clone.inert = true;
10738
+ clone.dataset.hbScreenshotStage = '';
10739
+ for (const [key, value] of Object.entries({ position: 'absolute', left: '0', top: '0', margin: '0', transform: 'none', width: `${bounds.width}px`, height: `${height}px`, 'box-sizing': 'border-box', 'min-width': '0', 'max-width': 'none', 'min-height': '0', 'max-height': 'none', overflow: 'hidden', 'z-index': '2147483647', 'pointer-events': 'none' })) {
10740
+ clone.style.setProperty(key, value, 'important');
10741
+ }
10742
+ const x = window.scrollX;
10743
+ const y = window.scrollY;
10744
+ const documentStyles = [document.documentElement, document.body].map(node => ({ node, style: node.getAttribute('style') }));
10745
+ let timer;
10746
+ try {
10747
+ // 小程序经常锁定 body 的高度与滚动;临时释放裁剪,确保捕获面完整可绘制。
10748
+ for (const { node } of documentStyles) {
10749
+ node.style.setProperty('overflow', 'visible', 'important');
10750
+ node.style.setProperty('min-height', `${height}px`, 'important');
10751
+ node.style.setProperty('scroll-behavior', 'auto', 'important');
10752
+ }
10753
+ document.body.append(clone);
10754
+ window.scrollTo(0, 0);
10755
+ // body 定位上下文可能有偏移,将独立捕获面校正到文档原点。
10756
+ const stageBounds = clone.getBoundingClientRect();
10757
+ clone.style.setProperty('left', `${-stageBounds.left}px`, 'important');
10758
+ clone.style.setProperty('top', `${-stageBounds.top}px`, 'important');
10759
+ await Promise.race([
10760
+ Promise.all([...(clone instanceof HTMLImageElement ? [clone] : []), ...clone.querySelectorAll('img')].map(image => image.decode())),
10761
+ new Promise((_, reject) => { timer = setTimeout(() => reject(createSDKError('REQUEST_TIMEOUT', '长图图片加载超时')), 5000); }),
10762
+ ]);
10763
+ const rendered = clone.getBoundingClientRect();
10764
+ if (Math.abs(rendered.left) >= 1 || Math.abs(rendered.top) >= 1 || Math.abs(rendered.width - bounds.width) >= 1 || Math.abs(rendered.height - height) >= 1) {
10765
+ throw createSDKError('INVALID_PARAMS', '当前页面布局无法容纳长图捕获面');
10766
+ }
10767
+ warnScreenshotWatermark();
10768
+ return await requester.request(SHARE_SCREENSHOT_LONG_METHOD, { ...options, rect: { left: 0, top: 0, width: bounds.width, height } });
10769
+ }
10770
+ finally {
10771
+ clearTimeout(timer);
10772
+ clone.remove();
10773
+ // 在恢复业务的 smooth 滚动样式前立即还原,避免退出截图后继续滚动。
10774
+ window.scrollTo(x, y);
10775
+ for (const { node, style } of documentStyles) {
10776
+ if (style === null)
10777
+ node.removeAttribute('style');
10778
+ else
10779
+ node.setAttribute('style', style);
10780
+ }
10781
+ }
10584
10782
  }
10585
10783
 
10586
10784
  /**
@@ -10611,6 +10809,7 @@ function createShareModule(requester, launchHref) {
10611
10809
  getExtra: () => readMiniProgramShareExtra(launchHref),
10612
10810
  showShareMenu: (options) => showShareMenu(requester, options),
10613
10811
  screenshot: (options) => screenshot(requester, options),
10812
+ screenshotElement: (options) => screenshotElement(requester, options),
10614
10813
  };
10615
10814
  }
10616
10815
 
@@ -11385,13 +11584,18 @@ function getFollowStatus(requester) {
11385
11584
  *
11386
11585
  * @throws {@link HbMiniProgramSDKError} `userInfo` 未声明或不可用、握手失败、Host 不支持该能力、
11387
11586
  * 当前小程序身份缺失、账号/隔离身份读取失败、返回结构不合法、Runtime 终止,或请求期间
11388
- * 账号与授权上下文变化时抛出。
11587
+ * 账号与授权上下文变化时抛出。第三方联网小程序的身份读取返回 `SERVER_API_REQUIRED`。
11389
11588
  *
11390
11589
  * @remarks
11590
+ * **网络权限决定用户信息的读取入口:`local` 模式使用本方法;联网的 `server` 模式
11591
+ * 使用 `auth.login()` 与服务端换票,调用本方法读取身份会返回 `SERVER_API_REQUIRED`。**
11592
+ *
11391
11593
  * 当前账号未登录属于正常返回分支,不抛错。账号已登录时,该能力不展示授权 UI,也不要求
11392
11594
  * 可信用户手势;Runtime 会静默建立或读取当前小程序的隔离 `app_user_id`,并授予
11393
11595
  * `identity` 与 `profile`。它只要求 Manifest 中声明 `userInfo`,不要求公开 `network`
11394
- * 权限,也不返回可供服务端换票的授权码;开启网络权限后仍可调用。
11596
+ * 权限,也不返回可供服务端换票的授权码。第三方小程序在启用网络权限的 `server` 模式下
11597
+ * 会以 `SERVER_API_REQUIRED` 拒绝身份读取,应改用 `auth.login()` 并由开发者服务端换票;
11598
+ * `local` 与兼容 `legacy` 模式保留直接读取能力。
11395
11599
  *
11396
11600
  * @example
11397
11601
  * ```ts
@@ -11816,94 +12020,7 @@ function createMiniProgramSDK(options) {
11816
12020
  return new MiniProgramSDK(options);
11817
12021
  }
11818
12022
 
11819
- /**
11820
- * iframe 与调试台页面的开发期 console 捕获转发。
11821
- *
11822
- * 双条件门控(iframe 转发):
11823
- * 1. 构建期:`hb-sdk dev`(vite serve)注入 `false`;`hb-sdk build` /
11824
- * `vite build`(生产)永不注入或替换为 `false`,本模块被死代码消除。
11825
- * 2. 运行期:仅在 `window.name` 为 `__hb_sdk_mini_dev__` 的调试 iframe 中激活,
11826
- * 用户设备上的正式运行环境没有该标记。
11827
- *
11828
- * 无侵入 patch `console.log/debug/info/warn/error`:原样放行(DevTools 不受影响)+
11829
- * 通过 `window.parent.postMessage` 转发给调试台(CSP 的 connect-src 不约束 postMessage,
11830
- * 网络上报由调试台页面代理)。发送全程静默:失败不得回打 console,避免自触发死循环。
11831
- *
11832
- * 激活时机:由 SDK 默认单例初始化时调用(业务 `import '@heybox/hb-sdk'` 即生效);
11833
- * iframe 标记由调试台 `iframe.name` 与 vite dev 注入的无依赖 bootstrap 共同设置。
11834
- * 调试台页面自身(runtime 跑在这里,`[hb-sdk-runtime]` 日志不经过 iframe)另用
11835
- * `installMiniDevConsoleSelfCapture` 接入「日志」页签(source: 'host')。
11836
- */
11837
- const MINI_DEV_IFRAME_WINDOW_NAME = '__hb_sdk_mini_dev__';
11838
- const MINI_DEV_CONSOLE_EVENT_TYPE = 'hb-sdk:mini-dev-console';
11839
- /** 调试台页面与 iframe bootstrap 共用的已安装标记(window/console 上的属性名)。 */
11840
- const MINI_DEV_CONSOLE_INSTALL_FLAG = '__hb_sdk_mini_dev_console_installed__';
11841
- /** 调试台页面自捕获(source: 'host')与 iframe 转发共用的已安装标记。 */
11842
- const INSTALL_FLAG = MINI_DEV_CONSOLE_INSTALL_FLAG;
11843
- function isDevLoggingEnabled() {
11844
- if (typeof false !== 'undefined' && false !== true) {
11845
- return false;
11846
- }
11847
- return typeof window !== 'undefined' && window.name === MINI_DEV_IFRAME_WINDOW_NAME;
11848
- }
11849
- const levels = ['log', 'debug', 'info', 'warn', 'error'];
11850
- function patchConsoleLevels(consoleRef, deliver, owner) {
11851
- if (!owner || owner[INSTALL_FLAG] === true) {
11852
- return false;
11853
- }
11854
- let patched = false;
11855
- for (const level of levels) {
11856
- const original = consoleRef[level];
11857
- if (typeof original !== 'function') {
11858
- continue;
11859
- }
11860
- const forward = function (...args) {
11861
- try {
11862
- deliver(level, args);
11863
- }
11864
- catch {
11865
- /* 转发失败必须静默,禁止回打 console 造成自触发循环。 */
11866
- }
11867
- return original.apply(this, args);
11868
- };
11869
- try {
11870
- consoleRef[level] = forward;
11871
- patched = true;
11872
- }
11873
- catch {
11874
- return patched;
11875
- }
11876
- }
11877
- if (patched) {
11878
- owner[INSTALL_FLAG] = true;
11879
- }
11880
- return patched;
11881
- }
11882
- function installMiniDevConsoleForwarding(consoleRef = console) {
11883
- if (!isDevLoggingEnabled()) {
11884
- return;
11885
- }
11886
- patchConsoleLevels(consoleRef, (level, args) => {
11887
- const message = {
11888
- type: MINI_DEV_CONSOLE_EVENT_TYPE,
11889
- detail: { level, args, timestamp: Date.now() },
11890
- };
11891
- window.parent?.postMessage(message, '*');
11892
- }, typeof window === 'undefined' ? undefined : window);
11893
- }
11894
-
11895
12023
  let defaultSDK = createMiniProgramSDK();
11896
- if (typeof false !== 'undefined' && false && typeof window !== 'undefined') {
11897
- window.__hbSdkSandboxList = async (path) => (await getDefaultSDK().files.sandbox.directory(path).list({ limit: 200 })).map((entry) => ({ name: entry.name, kind: entry.kind }));
11898
- }
11899
- // 开发期调试台 console 捕获:双条件门控(vite serve 注入 define + 调试 iframe 标记),
11900
- // 生产构建被死代码消除,正式环境无副作用。失败静默,绝不影响 SDK 初始化。
11901
- try {
11902
- installMiniDevConsoleForwarding();
11903
- }
11904
- catch {
11905
- /* 捕获层异常不得阻断 SDK 单例创建。 */
11906
- }
11907
12024
  function getDefaultSDK() {
11908
12025
  if (!defaultSDK) {
11909
12026
  defaultSDK = createMiniProgramSDK();
@@ -12267,6 +12384,7 @@ const share = {
12267
12384
  getExtra: () => getDefaultSDK().share.getExtra(),
12268
12385
  showShareMenu: (options) => getDefaultSDK().share.showShareMenu(options),
12269
12386
  screenshot: (options) => getDefaultSDK().share.screenshot(options),
12387
+ screenshotElement: (options) => getDefaultSDK().share.screenshotElement(options),
12270
12388
  };
12271
12389
  /** 默认 SDK 实例的 Viewport 模块。 */
12272
12390
  const viewport = {
@@ -32,7 +32,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
32
32
  risk: 'high',
33
33
  config: {},
34
34
  methods: ['gameSaves.list', 'gameSaves.sync', 'gameSaves.getFile', 'gameSaves.readParsedData'],
35
- conditions: ['需要用户明确授权、有效 Steam 登录和支持文件读取的宿主;可按需读取受支持游戏的已有解析概览,不触发解析。'],
35
+ conditions: ['需声明权限并校验当前 Steam 账号,无需额外授权弹窗;可读取受支持游戏已有的完整结构化数据,不触发解析。同步需有效 Steam 登录,文件下载另需宿主支持文件读取。'],
36
36
  },
37
37
  {
38
38
  key: 'userInfo',
@@ -61,7 +61,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
61
61
  access: 'declaration',
62
62
  risk: 'medium',
63
63
  config: {},
64
- methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot'],
64
+ methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot', 'share.screenshotLong'],
65
65
  conditions: ['继续执行分享参数校验和 Host 支持检查。'],
66
66
  },
67
67
  {
@@ -30,7 +30,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
30
30
  risk: 'high',
31
31
  config: {},
32
32
  methods: ['gameSaves.list', 'gameSaves.sync', 'gameSaves.getFile', 'gameSaves.readParsedData'],
33
- conditions: ['需要用户明确授权、有效 Steam 登录和支持文件读取的宿主;可按需读取受支持游戏的已有解析概览,不触发解析。'],
33
+ conditions: ['需声明权限并校验当前 Steam 账号,无需额外授权弹窗;可读取受支持游戏已有的完整结构化数据,不触发解析。同步需有效 Steam 登录,文件下载另需宿主支持文件读取。'],
34
34
  },
35
35
  {
36
36
  key: 'userInfo',
@@ -59,7 +59,7 @@ const MINI_PROGRAM_PERMISSION_CATALOG = [
59
59
  access: 'declaration',
60
60
  risk: 'medium',
61
61
  config: {},
62
- methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot'],
62
+ methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot', 'share.screenshotLong'],
63
63
  conditions: ['继续执行分享参数校验和 Host 支持检查。'],
64
64
  },
65
65
  {
@@ -47,6 +47,10 @@ const USER_SHOW_APPRECIATION_METHOD = 'user.showAppreciation';
47
47
  const SHARE_COPY_LINK_METHOD = 'share.copyLink';
48
48
  const SHARE_SHOW_SHARE_MENU_METHOD = 'share.showShareMenu';
49
49
  const SHARE_SCREENSHOT_METHOD = 'share.screenshot';
50
+ /** DOM 长图内部传输方法;业务仍调用 screenshotElement。
51
+ * @internal
52
+ */
53
+ const SHARE_SCREENSHOT_LONG_METHOD = 'share.screenshotLong';
50
54
  const VIEWPORT_SET_DISPLAY_METHOD = 'viewport.setDisplay';
51
55
  const VIEWPORT_GET_WINDOW_INFO_METHOD = 'viewport.getWindowInfo';
52
56
  const VIEWPORT_SET_NAVIGATION_BAR_STYLE_METHOD = 'viewport.setNavigationBarStyle';
@@ -200,6 +204,7 @@ const MINI_PROGRAM_PROTOCOL_CAPABILITIES = [
200
204
  requirement: { kind: 'all', permissions: ['share'] },
201
205
  risk: 'medium',
202
206
  },
207
+ { method: SHARE_SCREENSHOT_LONG_METHOD, module: 'share', capability: SHARE_SCREENSHOT_LONG_METHOD, requirement: { kind: 'all', permissions: ['share'] }, risk: 'medium' },
203
208
  {
204
209
  method: VIEWPORT_GET_WINDOW_INFO_METHOD,
205
210
  module: 'viewport',
@@ -45,6 +45,10 @@ const USER_SHOW_APPRECIATION_METHOD = 'user.showAppreciation';
45
45
  const SHARE_COPY_LINK_METHOD = 'share.copyLink';
46
46
  const SHARE_SHOW_SHARE_MENU_METHOD = 'share.showShareMenu';
47
47
  const SHARE_SCREENSHOT_METHOD = 'share.screenshot';
48
+ /** DOM 长图内部传输方法;业务仍调用 screenshotElement。
49
+ * @internal
50
+ */
51
+ const SHARE_SCREENSHOT_LONG_METHOD = 'share.screenshotLong';
48
52
  const VIEWPORT_SET_DISPLAY_METHOD = 'viewport.setDisplay';
49
53
  const VIEWPORT_GET_WINDOW_INFO_METHOD = 'viewport.getWindowInfo';
50
54
  const VIEWPORT_SET_NAVIGATION_BAR_STYLE_METHOD = 'viewport.setNavigationBarStyle';
@@ -198,6 +202,7 @@ const MINI_PROGRAM_PROTOCOL_CAPABILITIES = [
198
202
  requirement: { kind: 'all', permissions: ['share'] },
199
203
  risk: 'medium',
200
204
  },
205
+ { method: SHARE_SCREENSHOT_LONG_METHOD, module: 'share', capability: SHARE_SCREENSHOT_LONG_METHOD, requirement: { kind: 'all', permissions: ['share'] }, risk: 'medium' },
201
206
  {
202
207
  method: VIEWPORT_GET_WINDOW_INFO_METHOD,
203
208
  module: 'viewport',