@heybox/hb-sdk 0.8.0-alpha.3 → 0.8.0

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 (72) hide show
  1. package/CHANGELOG.md +136 -422
  2. package/README.md +28 -18
  3. package/dist/cli-chunks/{build-qWzAbpS7.cjs → build-PYCNacya.cjs} +8 -5
  4. package/dist/cli-chunks/{context-CtS2Thp0.cjs → context-m2W2XbL0.cjs} +42 -59
  5. package/dist/cli-chunks/{create-PV5ua977.cjs → create-BdAg3WGA.cjs} +2 -2
  6. package/dist/cli-chunks/{dev-CwKbAm_H.cjs → dev-CyZuw7Yn.cjs} +76 -64
  7. package/dist/cli-chunks/{doctor-tJUGOYrm.cjs → doctor-DU8rCfUF.cjs} +1 -1
  8. package/dist/cli-chunks/{index-DVuD75Hr.cjs → index-DATObqzK.cjs} +2 -2
  9. package/dist/cli-chunks/{index-De687C6-.cjs → index-MMW2ibQm.cjs} +32 -21
  10. package/dist/cli-chunks/{index.esm-B-4yrLNm.cjs → index.esm-BiAaAUFC.cjs} +8 -8
  11. package/dist/cli-chunks/{login-DolpqD8K.cjs → login-B3TThMss.cjs} +2 -2
  12. package/dist/cli-chunks/{project-vite-1rvkK-M8.cjs → project-vite-BQj8YLI4.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-rIAQE_G2.cjs → remote-DNvI7tHH.cjs} +57 -25
  14. package/dist/cli-chunks/{runtime-gate-DFjw66kF.cjs → runtime-gate-BEFp1w_s.cjs} +11 -3
  15. package/dist/cli-chunks/{runtime-permission-env-CjsCe5bp.cjs → runtime-permission-env-CtL8rsjB.cjs} +351 -0
  16. package/dist/cli-chunks/{session-CzaM2Cq3.cjs → session-DjBkjaF8.cjs} +1 -1
  17. package/dist/cli-chunks/{skill-CM40_9WH.cjs → skill-cR_wnaw2.cjs} +2 -2
  18. package/dist/cli-chunks/{version-Bz-AfXQU.cjs → version-yEn1E2Bg.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-TzYf9L6C.js +99 -0
  21. package/dist/devtools/browser-dev-host/assets/{index-CeP6SLB3.js → index-C5MZZDa5.js} +4 -4
  22. package/dist/devtools/browser-dev-host/assets/index-P-ra4m1y.css +1 -0
  23. package/dist/devtools/browser-dev-host/assets/workbench-state-BwV7bm4n.js +5 -0
  24. package/dist/devtools/browser-dev-host/index.html +3 -3
  25. package/dist/index.cjs.js +100 -2
  26. package/dist/index.esm.js +100 -2
  27. package/dist/protocol.cjs.js +189 -47
  28. package/dist/protocol.esm.js +189 -47
  29. package/dist/templates/{vue3-vite-ts → vanilla-vite-js}/.gitignore.ejs +0 -1
  30. package/dist/templates/vanilla-vite-js/README.md.ejs +14 -0
  31. package/dist/templates/vanilla-vite-js/index.html.ejs +20 -0
  32. package/dist/templates/vanilla-vite-js/package.json.ejs +22 -0
  33. package/dist/templates/vanilla-vite-js/src/assets/heybox-logo.svg +8 -0
  34. package/dist/templates/vanilla-vite-js/src/main.js +39 -0
  35. package/dist/templates/vanilla-vite-js/src/styles.css +155 -0
  36. package/dist/templates/{vue3-vite-ts/vite.config.ts → vanilla-vite-js/vite.config.js} +1 -2
  37. package/dist/vite.cjs.js +281 -13
  38. package/dist/vite.esm.js +281 -13
  39. package/package.json +13 -9
  40. package/skill/SKILL.md +8 -9
  41. package/skill/references/api-protocol.md +1 -3
  42. package/skill/references/api-root.md +65 -21
  43. package/skill/references/cli.md +17 -5
  44. package/skill/references/examples.md +3 -3
  45. package/skill/references/recipes.md +40 -41
  46. package/skill/references/safety-boundaries.md +9 -5
  47. package/skill/skill.json +5 -5
  48. package/types/core/mini-dev-console.d.ts +36 -0
  49. package/types/miniapp-manifest/index.d.ts +1 -0
  50. package/types/miniapp-manifest/node.d.ts +3 -0
  51. package/types/miniapp-manifest/permissions.d.ts +37 -0
  52. package/types/miniapp-manifest/schema.d.ts +5 -0
  53. package/types/modules/share/index.d.ts +1 -1
  54. package/types/modules/share/show-share-menu.d.ts +1 -1
  55. package/types/modules/share/types.d.ts +2 -4
  56. package/types/vite/index.d.ts +3 -1
  57. package/dist/devtools/browser-dev-host/assets/browser-dev-host-uq-Wac6k.js +0 -97
  58. package/dist/devtools/browser-dev-host/assets/index-KD2f3Jdz.css +0 -1
  59. package/dist/devtools/browser-dev-host/assets/workbench-state-D-1U0JRq.js +0 -5
  60. package/dist/templates/vue3-vite-ts/README.md.ejs +0 -47
  61. package/dist/templates/vue3-vite-ts/index.html.ejs +0 -12
  62. package/dist/templates/vue3-vite-ts/package.json.ejs +0 -33
  63. package/dist/templates/vue3-vite-ts/src/App.vue +0 -78
  64. package/dist/templates/vue3-vite-ts/src/__tests__/App.spec.ts +0 -148
  65. package/dist/templates/vue3-vite-ts/src/auth-handoff.ts +0 -46
  66. package/dist/templates/vue3-vite-ts/src/main.ts +0 -5
  67. package/dist/templates/vue3-vite-ts/src/styles.css +0 -60
  68. package/dist/templates/vue3-vite-ts/src/vite-env.d.ts +0 -1
  69. package/dist/templates/vue3-vite-ts/tsconfig.app.json +0 -17
  70. package/dist/templates/vue3-vite-ts/tsconfig.json +0 -11
  71. package/dist/templates/vue3-vite-ts/tsconfig.node.json +0 -11
  72. package/dist/templates/vue3-vite-ts/vitest.config.ts +0 -10
@@ -1,97 +0,0 @@
1
- import{ah as va,aB as Da,E as Ta,an as Pa,ao as La,aI as X,ae as ss,a8 as Ca,b as Oa}from"./workbench-state-D-1U0JRq.js";const er="auth.login",tr="user.getInfo",rr="user.revokeAuthorization",nr="user.getSteamGameList",ir="share.copyLink",or="share.showShareMenu",sr="share.screenshot",ar="viewport.getWindowInfo",cr="viewport.setNavigationBarStyle",_t="storage.getStorage",It="storage.setStorage",dr="network.request",ur="network.download",lr="files.pickFiles",hr="files.pickDirectory",fr="files.saveFile",At="file.create",St="file.remove",mr="file.exists",gr="file.readText",pr="file.writeText",yr="file.readBytes",wr="file.writeBytes",Er="file.stat",br="directory.create",Rt="directory.remove",_r="directory.exists",Ir="directory.list",Ar="ui.showToast",Sr="ui.showLoading",Rr="ui.hideLoading",vr="device.vibrate",Dr="device.setClipboard",Tr="navigation.close",Pr="navigation.reload",Lr="navigation.openAppPage",_e="cloud.leaderboard.submit",ce="cloud.leaderboard.getList",Te="cloud.leaderboard.getCurrentUserEntry",Be="cloud.leaderboard.deleteCurrentUserEntry",fe="cloud.leaderboard.getInfo",Pe=[{method:er,module:"auth",capability:er,permission:"auth.login",risk:"medium"},{method:tr,module:"user",capability:tr,permission:"user.getInfo",risk:"medium"},{method:rr,module:"user",capability:rr,permission:"user.revokeAuthorization",risk:"high"},{method:nr,module:"user",capability:nr,permission:"user.platformAccount.steam",risk:"high"},{method:ir,module:"share",capability:ir,permission:"share.copyLink",risk:"medium"},{method:or,module:"share",capability:or,permission:"share.basic",risk:"low"},{method:sr,module:"share",capability:sr,permission:"share.screenshot",risk:"medium"},{method:ar,module:"viewport",capability:ar,permission:"viewport.windowInfo",risk:"low"},{method:cr,module:"viewport",capability:cr,permission:"viewport.navigationBarStyle",risk:"low"},{method:_t,module:"storage",capability:_t,permission:"storage.read",risk:"low"},{method:It,module:"storage",capability:It,permission:"storage.write",risk:"medium"},{method:dr,module:"network",capability:dr,permission:"network.request",risk:"high"},{method:ur,module:"network",capability:ur,permission:"network.request",risk:"high"},{method:lr,module:"files",capability:lr,permission:"files.external",risk:"high"},{method:hr,module:"files",capability:hr,permission:"files.external",risk:"high"},{method:fr,module:"files",capability:fr,permission:"files.external",risk:"high"},{method:At,module:"file",capability:At,permission:"files.access",risk:"high"},{method:St,module:"file",capability:St,permission:"files.access",risk:"high"},{method:mr,module:"file",capability:mr,permission:"files.access",risk:"high"},{method:gr,module:"file",capability:gr,permission:"files.access",risk:"high"},{method:pr,module:"file",capability:pr,permission:"files.access",risk:"high"},{method:yr,module:"file",capability:yr,permission:"files.access",risk:"high"},{method:wr,module:"file",capability:wr,permission:"files.access",risk:"high"},{method:Er,module:"file",capability:Er,permission:"files.access",risk:"high"},{method:br,module:"directory",capability:br,permission:"files.access",risk:"high"},{method:Rt,module:"directory",capability:Rt,permission:"files.access",risk:"high"},{method:_r,module:"directory",capability:_r,permission:"files.access",risk:"high"},{method:Ir,module:"directory",capability:Ir,permission:"files.access",risk:"high"},{method:Ar,module:"ui",capability:Ar,permission:"ui.toast",risk:"low"},{method:Sr,module:"ui",capability:Sr,permission:"ui.loading",risk:"low"},{method:Rr,module:"ui",capability:Rr,permission:"ui.loading",risk:"low"},{method:vr,module:"device",capability:vr,permission:"device.vibrate",risk:"low"},{method:Dr,module:"device",capability:Dr,permission:"device.clipboard.write",risk:"medium"},{method:Tr,module:"navigation",capability:Tr,permission:"navigation.close",risk:"medium"},{method:Pr,module:"navigation",capability:Pr,permission:"navigation.reload",risk:"medium"},{method:Lr,module:"navigation",capability:Lr,permission:"navigation.openAppPage",risk:"medium"},{method:_e,module:"cloud",capability:_e,permission:"cloud.leaderboard.write",risk:"medium"},{method:ce,module:"cloud",capability:ce,permission:"cloud.leaderboard.read",risk:"low"},{method:Te,module:"cloud",capability:Te,permission:"cloud.leaderboard.currentUserEntry.read",risk:"medium"},{method:Be,module:"cloud",capability:Be,permission:"cloud.leaderboard.currentUserEntry.delete",risk:"medium"},{method:fe,module:"cloud",capability:fe,permission:"cloud.leaderboard.info.read",risk:"low"}],Qe="heybox:miniprogram",as=2,Na="hb_mini_bridge_nonce",ka="sdk.handshake",Ft="runtime.location.probe",Ma="sdk.location.report",Ua="sdk.csp.violation",cs="operation.progress";function Ha(e){return!Ve(e)||e.namespace!==Qe||e.version!==1&&e.version!==2||!Q(e.nonce)?!1:e.type==="handshake"?Q(e.id)&&e.method===ka&&e.error===void 0&&Ba(e.payload):e.type==="request"?Q(e.id)&&Q(e.method)&&e.error===void 0:e.type==="response"?Q(e.id)&&(e.method===void 0||Q(e.method))&&(e.error===void 0||Fa(e.error)):e.type==="event"?!Q(e.method)||e.error!==void 0?!1:e.method===cs?e.version===2&&Q(e.id)&&xa(e.payload):e.id===void 0||Q(e.id):e.type==="cancel"?e.version===2&&Q(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Jn(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ds(e){return Ve(e)?e.kind==="sandbox"?Fe(e,["kind"]):e.kind==="directory"&&Q(e.handleId)&&Fe(e,["kind","handleId"]):!1}function us(e){return!Ve(e)||e.kind!=="file"?!1:Q(e.handleId)?Fe(e,["kind","handleId"]):ds(e.root)&&Jn(e.relativePath)&&Fe(e,["kind","root","relativePath"])}function ls(e){return!Ve(e)||e.kind!=="directory"?!1:Q(e.handleId)?Fe(e,["kind","handleId"]):ds(e.root)&&Jn(e.relativePath)&&Fe(e,["kind","root","relativePath"])}function xa(e){return!Ve(e)||!Ei(e.loaded)||typeof e.lengthComputable!="boolean"||!Fe(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ei(e.total)&&e.loaded<=e.total:e.total===void 0}function Ba(e){return Ve(e)&&Q(e.href)&&typeof e.userAgent=="string"&&Q(e.sdkVersion)}function Fa(e){return Ve(e)&&Q(e.code)&&typeof e.message=="string"}function Ei(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Q(e){return typeof e=="string"&&e.length>0}function Fe(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Hr=["identity","profile"],Va=new Set(["network.request"]);function hs(e){return Va.has(e)}function Nt(e){if(!Wr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!Wr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim();if(t.has(i)||n.status!=="enabled"&&n.status!=="disabled"||!Wr(n.config))return{valid:!1,permissions:{}};if(t.add(i),!!hs(i)){if(i==="network.request"&&typeof n.config.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[i]={key:i,status:n.status,config:{useOfficialDomain:n.config.useOfficialDomain}}}}return{valid:!0,permissions:r}}function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Pe.map(e=>e.method);function U(e,t,r){return{code:e,message:t,data:r}}function fs(e){return qa(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?U("RUNTIME_ERROR",e.message):U("UNKNOWN_ERROR","小程序运行时异常",e)}function qa(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function $a(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ja=1e3;function za(e,t=$a()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=ja}const Ga="runtime.gate.probe",ms=new Set(Pe.map(e=>e.method));class Wa{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=as;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:Qe,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:Qe,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Qe,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Qe,version:2,nonce:this.nonce,type:"event",id:t,method:cs,payload:r})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r.payload,r.version,t.origin);return}if(r.type==="request"){let n=!1;try{n=za(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&Ha(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r,n){const i=!this.handshaken;if(i){if(this.onHandshake?.(t)===!1)return;this.bridgeVersion=r,r===1&&this.targetOrigin!=="*"&&n&&n!=="null"&&(this.targetOrigin=n),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.postEvent("ready",{timestamp:Date.now()}),i?this.onReady?.(t):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Ga){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,U("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!ms.has(t.method)){this.postResponse(t,void 0,U("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,U("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=fs(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:Qe,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Ka(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function Ka(e){return typeof e=="string"&&ms.has(e)}const gs="METHOD_FORBIDDEN";function pe(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=gs,t}class q extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const bi={[er]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[tr]:["account.getCurrentUserId","account.onChange","network.request"],[rr]:["account.getCurrentUserId","account.onChange","network.request"],[nr]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["presentation.setClipboard"],[or]:["presentation.showShareMenu"],[sr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ar]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[cr]:["presentation.setNavigationBarStyle"],[_t]:["storage.getRaw"],[It]:["storage.setRaw"],[dr]:["network.request"],[ur]:["network.stream","files.transfer","files.access"],[lr]:["files.external"],[hr]:["files.external"],[fr]:["files.save"],[At]:["files.access"],[St]:["files.removeFile"],[mr]:["files.access"],[gr]:["files.access"],[pr]:["files.access"],[yr]:["files.access"],[wr]:["files.access"],[Er]:["files.access"],[br]:["files.access"],[Rt]:["files.removeDirectory"],[_r]:["files.access"],[Ir]:["files.access"],[Ar]:["presentation.showToast"],[Sr]:["presentation.showLoading"],[Rr]:["presentation.hideLoading"],[vr]:["presentation.vibrate"],[Dr]:["presentation.setClipboard"],[Tr]:["presentation.close"],[Pr]:["presentation.reload"],[Lr]:["presentation.openAppPage"],[_e]:["account.getCurrentUserId","account.onChange","network.request"],[ce]:["account.onChange","network.request"],[Te]:["account.getCurrentUserId","account.onChange","network.request"],[Be]:["account.getCurrentUserId","account.onChange","network.request"],[fe]:["account.onChange","network.request"]};function Ya(e,t){if(t[e]!==!0)throw pe(e)}const Qa=32*1024*1024,Xa=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Ja(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:Qa},i);return Za(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Za(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:ec(t,rc(e,"content-type"))}}function ec(e,t){tc(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new q("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Xa.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function tc(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new q(`Host network response 不支持 charset=${t}`)}function rc(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function L(e){return typeof e=="function"}function _i(e){return(...t)=>{throw pe(e)}}function Y(e){return async(...t)=>{throw pe(e)}}const nc=(e,t)=>{},ic=()=>()=>{};function oc(e){const t={request:L(e.network?.request)?e.network.request.bind(e.network):Y("network.request")},r={getCurrentUserId:L(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Y("account.getCurrentUserId"),ensureAuthenticated:L(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Y("account.ensureAuthenticated"),onChange:L(e.account?.onChange)?e.account.onChange.bind(e.account):ic},n={getRaw:L(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Y("storage.getRaw"),setRaw:L(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Y("storage.setRaw")},i={close:L(e.presentation?.close)?e.presentation.close.bind(e.presentation):Y("presentation.close"),reload:L(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Y("presentation.reload"),openAppPage:L(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Y("presentation.openAppPage"),getViewportMetrics:L(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):_i("presentation.getViewportMetrics"),getNavigationBarHeight:L(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):_i("presentation.getNavigationBarHeight"),setNavigationBarStyle:L(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Y("presentation.setNavigationBarStyle"),showShareMenu:L(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Y("presentation.showShareMenu"),setScreenshotChromeHidden:L(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):nc,captureAndShare:L(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Y("presentation.captureAndShare"),showToast:L(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Y("presentation.showToast"),showLoading:L(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Y("presentation.showLoading"),hideLoading:L(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Y("presentation.hideLoading"),vibrate:L(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Y("presentation.vibrate"),setClipboard:L(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Y("presentation.setClipboard")},o=L(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0;return{network:t,account:r,storage:n,presentation:i,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.transfer===void 0?{}:{transfer:e.transfer},...o?{storageDiagnostics:o}:{}}}function sc(e){const t=ac(e.files?.sandbox),r=L(e.picker?.pickFiles)&&L(e.picker?.pickDirectory),n=L(e.picker?.saveFile),i=t||r||n,o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":L(e.account?.getCurrentUserId),"account.ensureAuthenticated":L(e.account?.ensureAuthenticated),"account.onChange":L(e.account?.onChange),"network.request":L(e.network?.request),"network.stream":L(e.transfer?.network.open)&&L(e.transfer?.network.release),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":L(o?.remove),"files.removeDirectory":L(e.files?.sandbox.remove),"files.transfer":L(e.transfer?.files.writeResource),"storage.getRaw":L(e.storage?.getRaw),"storage.setRaw":L(e.storage?.setRaw),"presentation.close":L(e.presentation?.close),"presentation.reload":L(e.presentation?.reload),"presentation.openAppPage":L(e.presentation?.openAppPage),"presentation.getViewportMetrics":L(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":L(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":L(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":L(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":L(e.presentation?.captureAndShare),"presentation.showToast":L(e.presentation?.showToast),"presentation.showLoading":L(e.presentation?.showLoading),"presentation.hideLoading":L(e.presentation?.hideLoading),"presentation.vibrate":L(e.presentation?.vibrate),"presentation.setClipboard":L(e.presentation?.setClipboard)}}function ac(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&L(t.file)&&L(t.directory)&&L(t.create)&&L(t.stat)&&L(t.list)}function Ii(e,t){return t?.[e]!==!1}function cc(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")}function ps(e,t={}){const r={};for(const n of Object.keys(bi)){const o=bi[n].every(a=>e[a]),s=!cc(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Ii(n,t.callerCapabilities)&&Ii(n,t.hostCapabilities)&&o&&s}return r}function ys(e={},t={}){const r=sc(e),n=ps(r,t);return{ports:oc(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Zn(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):dc(e.signal,t);return{...e,signal:r}}function dc(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{r.signal.aborted||(n(),r.abort(a.reason))},o=()=>i(e),s=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0})),r.signal}function uc(e){if(!e||typeof e!="object"||e.lifecycle!=="cleanup")return!1;const t=e.signal;return!!t&&typeof t=="object"&&typeof t.aborted=="boolean"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}function l(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lc(e){return typeof e=="object"&&e!==null}function ne(e,t){const r=e.data;if(!lc(r)||typeof r.status!="string")throw new Error(t);return r}const ws={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},hc={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.public.detail.get",method:"GET",path:"/user_miniprogram/public/detail",query(e){return{mini_program_id:e.mini_program_id,...e.miniprogram_version?{miniprogram_version:e.miniprogram_version}:{},...e.preview_token?{preview_token:e.preview_token}:{},...e.local_dev_launch_token?{local_dev_launch_token:e.local_dev_launch_token}:{},...e.entry?{entry:e.entry}:{},...e.h_src_parent?{h_src_parent:e.h_src_parent}:{},...e.extra!==void 0?{extra:e.extra}:{}}},parse(e,t){return ne(e,"工坊小程序详情加载失败")}};function kt(e){return{mini_program_id:e.miniProgramId}}function fc(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function mc(e){const t=ne(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=fc(r.consent_challenge)),{...t,result:n}}const gc={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.cancel.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/cancel",body:e=>({...kt(e.runtimeContext),challenge:e.challenge}),parse:e=>ne(e,"小程序授权取消接口响应异常")},pc={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.revoke.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/revoke",body:e=>kt(e.runtimeContext),parse:e=>ne(e,"小程序授权撤销接口响应异常")},yc={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.local_identity.post",method:"POST",path:"/user_miniprogram/runtime/local_identity",body:e=>kt(e.runtimeContext),parse(e){const t=ne(e,"小程序隔离身份接口响应异常");return{...t,result:{appUserId:t.result.app_user_id}}}},wc={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.begin.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/begin",body:e=>({...kt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>mc(e)},Ec={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.confirm.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/confirm",body:e=>({...kt(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ne(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},bc=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],_c=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Ic=/authorization|cookie|pkey|password|secret|token/i,Es=/authorization|cookie|pkey|token|password|secret/i;function ue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ac(e){for(const t of Object.keys(e))if(!_c.has(t))throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of bc)if(Object.prototype.hasOwnProperty.call(e,t)&&ue(e,t)!==void 0)throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(ue(e,"bodyEncoding")!==void 0&&ue(e,"bodyEncoding")!=="json"&&ue(e,"bodyEncoding")!=="form")throw new q("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(ue(e,"failurePresentation")!==void 0&&ue(e,"failurePresentation")!=="none")throw new q("endpoint failurePresentation 必须为 none");if(ue(e,"auth")!==void 0&&ue(e,"auth")!=="none"&&ue(e,"auth")!=="optional"&&ue(e,"auth")!=="required")throw new q("endpoint auth 必须为 none、optional 或 required")}function mt(e){if(Array.isArray(e))return e.map(mt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Ic.test(n)||(r[n]=mt(i));return r}function Ai(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Es.test(r)||(t[r]=n);return t}function Sc(e){if(!e)return;const t=Object.keys(e).find(r=>Es.test(r));if(t)throw new q(`endpoint 禁止声明 credential-bearing header: ${t}`)}class tt extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.setPrototypeOf(this,new.target.prototype)}}function bs(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class rt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,bs(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Mt extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,bs(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Rc(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:mt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Ai(o),method:e.method,metadata:{endpointId:e.id},query:mt(n),timeout:e.timeout,url:r},data:mt(a.data),headers:Ai(a.headers)||{},status:a.status,statusText:a.statusText}}async function xr(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Ac(t),typeof t.id!="string"||!t.id)throw new q("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new q("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new q("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;Sc(a);let c;try{c=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(d){throw d instanceof q?d:new rt({endpointId:t.id,cause:d})}if(c.status<200||c.status>=300)throw new tt({endpointId:t.id,status:c.status});const u=Rc(t,r,i,o,s,a,n,c);if(t.parse)try{return await t.parse(u,r)}catch(d){throw new Mt({endpointId:t.id,cause:d})}return u.data}const vc=new Set(Hr),Dc=1e3;function Tc(e){const t=new Set,r=new Map,n=new Map,i=new Set;let o=0,s=!1,a=Promise.resolve(),c;const u=e.account.onChange(m=>{d(),h("heybox_app_login_change",{isHeyboxAppLoggedIn:!!m})});function d(){o+=1,c?.abort(),r.clear(),n.clear(),i.clear()}function h(m,g){for(const E of t)try{E(m,g)}catch{}}function p(){const m=e.identity.get()?.miniProgramId?.trim();if(!m)throw l("INVALID_STATE","当前能力缺少 canonical 小程序身份");return m}function f(){if(s||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function _(){f();let m;try{m=await e.account.getCurrentUserId(e.operationContext)}catch(g){throw Di(g,e.operationContext.signal,"读取小黑盒账号失败")}return typeof m=="string"&&m.trim()?m.trim():void 0}async function b(m,g){const E=await _();if(o!==g||E!==m)throw l("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function I(m){f();try{await e.account.ensureAuthenticated({trustedUserGesture:m,reason:"runtime_auth",signal:e.operationContext.signal})}catch(E){throw Di(E,e.operationContext.signal,"小黑盒登录失败")}const g=await _();if(!g)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return g}async function y(m,g,E=e.operationContext.signal){try{if(E.aborted)throw Nn();return await kc(xr(e.network,m,g,{...e.operationContext,credentials:"heybox-session",signal:E}),E)}catch(T){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):T instanceof q?l("REQUEST_UNSUPPORTED",T.message):T instanceof Mt?l("INVALID_RESPONSE","授权接口响应不合法"):T instanceof rt?l("REQUEST_FAILED","授权请求失败"):T instanceof tt?l("REQUEST_FAILED",T.message):_s(T)?T:l("REQUEST_FAILED","授权请求失败")}}async function A(m,g){await y(gc,{runtimeContext:{miniProgramId:m},challenge:g}).catch(()=>{})}function R(m){const g=async()=>{const T=Ri(e.operationContext.signal);c=T;try{return await m(T.signal)}finally{c===T&&(c=void 0),T.abort()}},E=a.then(g,g);return a=E.then(()=>{},()=>{}),E}async function P(m,g,E,T,N){if(!E)throw await A(m,g.challenge),l("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await A(m,g.challenge),l("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return R(async F=>{await b(T,N);const V=await H(m,g.displayedScopes,F);await b(T,N);let Z;try{Z=await e.authPresentation.confirmAuthorization({miniProgramId:m,scopes:g.displayedScopes,...V,signal:F})}catch(J){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await b(T,N),await A(m,g.challenge),Pc("REQUEST_FAILED","授权确认界面执行失败",J))}if(await b(T,N),Z.status!=="granted")throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const se=Oc(Z.grantedScopes,g.displayedScopes);if(!se.includes("identity"))throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户拒绝授权");return se})}async function H(m,g,E){const T=Ri(E),N=setTimeout(()=>T.abort(),Dc);try{const F=Nc(e.miniProgramPresentation),[V,Z]=await Promise.all([F?Promise.resolve(F):v(m,T.signal),g.includes("profile")?O(T.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...Z?{userProfile:Z}:{}}}finally{clearTimeout(N),T.abort()}}async function v(m,g){try{const E=e.identity.get()?.version?.trim(),T=await y(hc,{mini_program_id:m,...E?{miniprogram_version:E}:{}},g),N=Ge(T,"小程序公开资料"),F=Je(N.name),V=Je(N.icon_url);return F||V?{...F?{name:F}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function O(m){try{const g=await y(ws,void 0,m),E=Ge(g,"账号基础信息"),T=Je(E.display_username),N=Je(E.display_avatar);return T||N?{...T?{nickname:T}:{},...N?{avatar:N}:{}}:void 0}catch{return}}async function C(m,g){const E=p(),T=await I(g),N=o,F=await y(wc,{runtimeContext:{miniProgramId:E},scopes:m});await b(T,N);const V=Ge(F,"小程序登录"),Z=vi(V,"loginCode"),se=vi(V,"consentChallenge");if(Z===se)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let J;if(Z)J=Si(V.loginCode);else{const z=Lc(V.consentChallenge),ye=await P(E,z,g,T,N);await b(T,N);const zr=await y(Ec,{runtimeContext:{miniProgramId:E},challenge:z.challenge,selectedScopes:ye});if(await b(T,N),J=Si(Ge(zr,"小程序登录确认")),J.scopes.some(st=>!ye.includes(st)))throw l("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}i.clear();for(const z of J.scopes)i.add(z);return h("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),h("user_info_authorization_change",Kr(i)),J}async function S(m,g){const E=o,T=await y(yc,{runtimeContext:{miniProgramId:g}});await b(m,E);const N=Cc(Ge(T,"用户本地身份"));for(const F of Hr)i.add(F);return h("user_info_authorization_change",Kr(i)),N}function w(m){f();const g=p(),E=`${m}\0${g}`,T=r.get(E);if(T)return Promise.resolve(T);const N=n.get(E);if(N)return N;const F=S(m,g).then(V=>(r.set(E,V),V)).finally(()=>{n.get(E)===F&&n.delete(E)});return n.set(E,F),F}async function D(m){if(!m)throw l("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const g=p(),E=o,T=await _();if(!T)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const N=await y(pc,{runtimeContext:{miniProgramId:g}});await b(T,E),Ge(N,"用户授权撤销"),d(),h("user_info_authorization_change",{identity:"denied",profile:"denied"})}return{login:C,getOrCreateLocalIdentity:w,getAuthorization:()=>Kr(i),revoke:D,onEvent(m){return t.add(m),()=>t.delete(m)},dispose(){s||(s=!0,d(),u(),t.clear())}}}function Pc(e,t,r){const n=l(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Ge(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Si(e){if(!M(e))throw l("INVALID_RESPONSE","login code 必须是对象");const t=Cr(e.scopes,"login code scopes");if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!t.includes("identity"))throw l("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:t}}function Lc(e){if(!M(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const t=Cr(e.requestedScopes,"challenge requestedScopes"),r=Cr(e.displayedScopes,"challenge displayedScopes");if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!t.length||!t.includes("identity")||!r.length||!r.includes("identity")||t.some(n=>!r.includes(n)))throw l("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:t,displayedScopes:r}}function Cc(e){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");return{appUserId:e.appUserId.trim()}}function Oc(e,t){const r=Cr(e,"授权选择 scopes");if(r.some(n=>!t.includes(n)))throw l("INVALID_RESPONSE","授权选择包含未展示的 scope");return r}function Je(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Nc(e){const t=Je(e?.name),r=Je(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ri(e){const t=new AbortController;return e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>t.abort(e.reason),{once:!0,signal:t.signal}),t}function kc(e,t){return t.aborted?Promise.reject(Nn()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Nn()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Nn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Cr(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!vc.has(r))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Kr(e){return Object.fromEntries(Hr.map(t=>[t,e.has(t)?"granted":"not_requested"]))}function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _s(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Di(e,t,r){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):_s(e)?e:l("REQUEST_FAILED",r)}const Mc=new Set(Hr);function Uc(e){return{[er]:async(t,r)=>{if(!xc(e.runtimePermissions))throw l("SERVER_API_REQUIRED","当前模式要求由小程序服务端完成 auth.login");return e.authorization.login(Hc(t),r.trustedUserGesture)}}}function Hc(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw Ti();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Mc.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Ti();return[...e.scopes]}function xc(e){const t=Nt(e);return t.valid&&t.permissions["network.request"]?.status==="enabled"}function Ti(){return l("INVALID_PARAMS","auth.login 参数不合法")}const Bc={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return ne(e,"排行榜记录删除接口响应异常")}},Fc={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/current",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return ne(e,"当前排行榜记录接口响应异常")}},Vc={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.info.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/info",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return ne(e,"排行榜信息接口响应异常")}},qc={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.list.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/list",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},limit:e.limit,...e.cursor?{cursor:e.cursor}:{}}},parse(e,t){return ne(e,"排行榜列表接口响应异常")}},$c={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.submit.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/submit",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},score:e.score,...e.extra===void 0?{}:{extra:JSON.stringify(e.extra)}}},parse(e,t){return ne(e,"排行榜提交接口响应异常")}};function Wt(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Pi(e){return e instanceof q?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function W(e){if(e.aborted)throw Wt()}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Wt());let n;try{n=e()}catch(i){return Promise.reject(Pi(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Wt())):new Promise((i,o)=>{let s=!1;const a=u=>{s||(s=!0,t.removeEventListener("abort",c),u())},c=()=>a(()=>o(Wt()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(u=>a(()=>i(u)),u=>a(()=>o(Pi(u))))})}const jc="default",zc=/^[A-Za-z0-9_-]{1,64}$/,Gc=300*1e3,Wc=250,Kc=3,Yc={1:"Canceled",2:"Unknown",3:"InvalidArgument",4:"DeadlineExceeded",5:"NotFound",6:"AlreadyExists",7:"PermissionDenied",8:"ResourceExhausted",9:"FailedPrecondition",10:"Aborted",11:"OutOfRange",12:"Unimplemented",13:"Internal",14:"Unavailable",15:"DataLoss",16:"Unauthenticated"};class Qc{constructor(t){this.options=t,this.unsubscribeAccountChange=Jc(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request($c,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=at(i,_e);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Yr(o,_e)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=ct("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(qc,{miniProgramId:r,...t}),s=at(o,ce);if(!me(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw j(`${ce} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw j(`${ce} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Yr(a,ce)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=ct("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Fc,{miniProgramId:n,...t}),c=at(a,Te);if(!me(c))throw j(`${Te} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Yr(c.entry,Te)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Bc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=at(i,Be);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!me(o)||typeof o.deleted!="boolean")throw j(`${Be} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",ct("info"),async()=>{const i=await this.request(Vc,{miniProgramId:r,...t}),o=at(i,fe);if(!me(o)||typeof o.key!="string"||!zc.test(o.key))throw j(`${fe} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw j(`${fe} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw j(`${fe} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw j(`${fe} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=ct(t,n),u=this.inflight.get(c);if(u)return u.promise;const d=this.accountGeneration,h=o?.generation,p=i().then(f=>(this.assertAccountGeneration(d),o&&s&&o.generation===h&&(r==="list"?s.size>=Wc&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Gc,value:f})),f)).finally(()=>{this.inflight.get(c)?.promise===p&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:p}),p}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Kc)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)Ci(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Ci(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw Ni(n)?n:Oi()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ae("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ae("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return ct(t,r??jc)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ae("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await $(()=>xr(n,t,r,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw Ni(i)||kn(i,"REQUEST_UNSUPPORTED")?i:i instanceof q?ae("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof rt&&kn(i.cause,"INVALID_STATE")?i.cause:i instanceof tt&&(i.status===401||i.status===403)?ae("UNAUTHORIZED","当前用户未登录"):i instanceof rt||i instanceof tt?Oi():i instanceof Mt?j(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):j(i instanceof Error?i.message:"排行榜响应不合法")}}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(W(this.options.operationContext.signal),this.disposed)throw ae("INVALID_STATE","Cloud capability 已释放")}}function Xc(e){return new Qc(e)}function Jc(e,t){try{return e.onChange(t)}catch(r){if(kn(r,gs))return()=>{};throw r}}function at(e,t){if(!me(e)||typeof e.status!="string")throw j(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Zc(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw j(`${t} 响应缺少 result`);return e.result}function Yr(e,t){if(!me(e))throw j(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw j(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw j(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw j(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw j(`${t} 返回的 score 必须是有限数字`);if(!me(e.extra))throw j(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw j(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function Zc(e){if(e.status==="login"||e.status==="relogin")throw ae("UNAUTHORIZED",ht(e.msg)||"当前用户未登录");const t=Li(e.result)??Li(e),r=ht(t?.user_message)||ht(e.msg)||ht(t?.developer_message)||"排行榜请求失败";throw t?ae(ed(t),r,{status:e.status,sbe:t}):ae("HEYBOX_API_ERROR",r,{status:e.status})}function Li(e){return me(e)&&me(e.sbe)?e.sbe:void 0}function ed(e){const t=ht(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return Yc[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function Ci(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function ct(...e){return JSON.stringify(e)}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function kn(e,t){return me(e)&&e.code===t}function ae(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function j(e){return ae("INVALID_RESPONSE",e)}function Oi(){return ae("REQUEST_FAILED","排行榜请求失败")}function Ni(e){return e instanceof Error&&e.name==="AbortError"}const td=/^[A-Za-z0-9_-]{1,64}$/,ki=20,rd=100,Mi=2048;function nd(e){const t=Xc(e);return{handlers:{[_e]:async n=>t.submit(id(n)),[ce]:async n=>t.getList(od(n)),[Te]:async n=>t.getCurrentUserEntry(Qr(n,Te)),[Be]:async n=>t.deleteCurrentUserEntry(Qr(n,Be)),[fe]:async n=>t.getInfo(Qr(n,fe))},dispose:()=>t.dispose()}}function id(e){const t=ei(e,_e,!1);if(ti(t,["key","score","extra"],_e),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw ge("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...ri(t.key,_e),score:t.score,...t.extra===void 0?{}:{extra:sd(t.extra)}}}function od(e){if(e===void 0)return{limit:ki};const t=ei(e,ce,!0);ti(t,["key","limit","cursor"],ce);const r=t.limit===void 0?ki:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>rd)throw ge("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...ri(t.key,ce),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Qr(e,t){if(e===void 0)return{};const r=ei(e,t,!0);return ti(r,["key"],t),ri(r.key,t)}function ei(e,t,r){if(e===void 0&&r)return{};if(!Is(e))throw ge("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function ti(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ge("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function ri(e,t){if(e===void 0)return{};if(typeof e!="string"||!td.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function sd(e){if(!Is(e))throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>Mi)throw ge("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Mi} 字节`);return e}function Is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e,t){return{code:e,message:t}}const Ui=5e3,Hi=1e4;function ke(e){throw{code:"INVALID_PARAMS",message:e}}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ss(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ke(`${r} 不支持字段: ${n.join(", ")}`)}function ad(e){if(e===void 0)return{intensity:"light",delay:0};if(!As(e))return ke("device.vibrate 参数必须是对象");Ss(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return ke("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Ui?ke(`device.vibrate delay 必须是 0-${Ui} 的整数毫秒`):{intensity:r,delay:n}}function cd(e){return As(e)?(Ss(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?ke("device.setClipboard text 必须是非空字符串"):e.text.length>Hi?ke(`device.setClipboard text 不能超过 ${Hi} 字符`):{text:e.text}):ke("device.setClipboard 参数必须是对象")}function dd(e){return{[vr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.vibrate(ad(t),e.operationContext),e.operationContext.signal)},[Dr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.setClipboard(cd(t),e.operationContext),e.operationContext.signal)}}}const ud=new Set(["METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),ld={METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function ni(e){const t=Rs(e),r=t&&ud.has(t)?l(t,ld[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function be(e){try{return e()}catch(t){throw ni(t)}}function Rs(e){try{if(!M(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function vs(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):Mn,remove:o?s=>e.remove(s):Ts,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Mn,stat:s=>e.stat(s)})}function Ds(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:a=>vs(e.file(a),n,{allowRemove:o}),directory:a=>Ds(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Mn,remove:s?(a,c)=>e.remove(a,c):Ts,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Mn(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Ts(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const xi=1024;class hd{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return Vt(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=be(()=>{if(!Array.isArray(t))throw l("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw l("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>xi)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let u=0;u<a;u+=1){if(!Object.prototype.hasOwnProperty.call(t,u))throw l("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[u],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Vt(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return Fi(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}resolveFileEntry(t){this.assertCanonicalDetail();const r=md(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=vt(r.relativePath),o=this.prepareFile(be(()=>n.handle.file(i)),n.origin,n.handle.mode).handle;return{ref:r,handle:o,origin:n.origin}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=gd(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=vt(r.relativePath),o=this.prepareDirectory(be(()=>n.handle.directory(i)),n.origin,n.handle.mode,!0).handle;return{ref:r,handle:o,origin:n.origin}}describeFile(t,r){return qi(t),Vt(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),be(()=>{if(!Array.isArray(r))throw l("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw l("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return be(()=>{if(M(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Vt(n.handle,Bi(t.ref,n.handle.name))}if(M(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Fi(n.handle,fd(t.ref,n.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Ut(r),i=this.prepareFile(be(()=>t.handle.file(n)),t.origin,t.handle.mode);return{ref:Bi(t.ref,n),handle:i.handle,origin:t.origin}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return be(()=>{qi(t);const i=n??t.mode;return Vi(t.mode,i),{handle:vs(t,i,{allowRemove:r==="sandbox"}),origin:r}})}prepareDirectory(t,r,n,i=!1){return be(()=>{wd(t,i);const o=n??t.mode;return Vi(t.mode,o),{handle:Ds(t,o,{allowRemove:r==="sandbox"}),origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>xi)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=pd();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw l("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!yd(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r)throw l("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw pe("files.sandbox");return this.prepareDirectory(be(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw pe("files")}}function vt(e){if(!Jn(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Ut(e,t="文件名"){const r=vt(e);if(r.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Bi(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:vt(`${e.relativePath}/${t}`)}}function fd(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:vt(`${e.relativePath}/${t}`)}}function Vt(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Fi(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Vi(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function md(e){return us(e)||Ps(),e}function gd(e){return ls(e)||Ps(),e}function Ps(){throw l("INVALID_PARAMS","文件引用不合法")}function pd(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw l("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function yd(e){return/^[0-9a-f]{32}$/.test(e)}function qi(e){if(!M(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw l("FILE_IO_FAILED","Host 返回了无效 File handle");Ut(e.name,"Host File name")}function wd(e,t=!1){if(!M(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw l("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw l("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Ut(e.name,"Host Directory name")}const $i=1e3,Ed=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function bd(e){const t=r=>Zn(e.operationContext,r.signal);return{files:{[lr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=_d(r),s=await ee(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[hr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=Id(r),s=await ee(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[fr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=Ad(r).suggestedName,s=t(n);if(!i.saveFile)throw pe("files.saveFile");const a=await ee(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[At]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.create(ji(i),t(n)))},[St]:async(r,n)=>{const i=ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),We(o.handle.mode),!o.handle.remove)throw pe(St);await ee(()=>o.handle.remove(t(n)))},[mr]:async(r,n)=>{const i=ie(r);return zi(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!M(o)||o.kind!=="file")throw Wi()})},[gr]:async(r,n)=>{const i=ie(r),o=Gi(await ee(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw l("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[pr]:async(r,n)=>{const i=ie(r,["content"]);typeof i.content!="string"&&oe("content 必须是字符串");const o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[yr]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).read(t(n)));return Gi(o)},[wr]:async(r,n)=>{const i=ie(r,["content"]),o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.write(Rd(i.content),t(n)))},[Er]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).stat(t(n)));return vd(o)}},directory:{[br]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);We(o.mode),await ee(()=>o.create(ji(i),t(n)))},[Rt]:async(r,n)=>{const i=ie(r,["recursive"]),o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),We(o.handle.mode),!o.handle.remove)throw pe(Rt);await ee(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Or(i.recursive,"recursive")},t(n)))},[_r]:async(r,n)=>{const i=ie(r);return zi(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!M(o)||o.kind!=="directory")throw Wi()})},[Ir]:async(r,n)=>{const i=ie(r,["limit"]),o=Sd(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ee(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function _d(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||oe("pickFiles 参数必须是对象"),Br(e,["mode","accept","multiple"]);const t=Ls(e.mode,"read"),r=e.multiple===void 0?!1:Or(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&oe("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Id(e){return e===void 0?{mode:"read"}:(M(e)||oe("pickDirectory 参数必须是对象"),Br(e,["mode"]),{mode:Ls(e.mode,"read")})}function Ad(e){return M(e)||oe("saveFile 参数必须是对象"),Br(e,["suggestedName"]),{suggestedName:Ut(e.suggestedName,"suggestedName")}}function ie(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&oe("文件操作参数必须包含 target"),Br(e,["target",...t]),e}function ji(e){return{recursive:e.recursive===void 0?!1:Or(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Or(e.exclusive,"exclusive")}}function Ls(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&oe("mode 必须是 read 或 readwrite"),e)}function Or(e,t){return typeof e!="boolean"&&oe(`${t} 必须是布尔值`),e}function Sd(e){if(e===void 0)return $i;if((!Number.isSafeInteger(e)||e<=0)&&oe("limit 必须是正整数"),e>$i)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Br(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&oe(`不支持字段: ${r.join(", ")}`)}function We(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Xr(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Jr(e){if(!e)throw pe("files.external");return e}async function zi(e){try{return await e(),!0}catch(t){if(Ed.has(Rs(t)??""))return!1;throw ni(t)}}async function ee(e){try{return await e()}catch(t){throw ni(t)}}function Rd(e){return e instanceof Uint8Array||oe("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&oe("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Gi(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Wi(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function vd(e){if(!M(e)||e.kind!=="file"||!Dd(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Td(e[t]))throw l("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function Dd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Td(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function oe(e){throw l("INVALID_PARAMS",e)}const Pd=["pc","console","mobile"],Ld=["game","wiki"];function Nr(e){throw{code:"INVALID_PARAMS",message:e}}function Cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Me(e,t){return typeof e!="string"||!e.trim()?Nr(t):e.trim()}function Ki(e,t,r){return typeof e!="string"||!t.includes(e)?Nr(r):e}function Od(e){const t={target:"game_detail",appId:Me(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Ki(e.gameType,Pd,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Ki(e.page,Ld,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Me(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Me(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Nd(e){return{target:"user_detail",userId:Me(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function kd(e){const t={target:"post_detail",linkId:Me(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Me(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Me(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Md(e){return Cd(e)?e.target==="game_detail"?Od(e):e.target==="user_detail"?Nd(e):e.target==="post_detail"?kd(e):Nr("navigation.openAppPage target 不支持"):Nr("navigation.openAppPage options 必须是对象")}function Ud(e){return{protocolType:"openRouterPath",path:"/game/detail",params:{app_id:e.appId,game_type:e.gameType,...e.page===void 0?{}:{page:e.page},...e.hSrc===void 0?{}:{h_src:e.hSrc},...e.skuId===void 0?{}:{sku_id:e.skuId}}}}function Hd(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function xd(e){return{protocolType:"openRouterPath",path:"/bbs/link",params:{link_id:e.linkId,...e.rootCommentId===void 0?{}:{root_comment_id:e.rootCommentId},...e.commentId===void 0?{}:{comment_id:e.commentId}}}}function Bd(e){const t=Md(e);return t.target==="game_detail"?Ud(t):t.target==="user_detail"?Hd(t):xd(t)}function Fd(e){throw{code:"INVALID_PARAMS",message:e}}function Yi(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Fd(`${t} 不支持参数`)}function Vd(e){return{[Tr]:async t=>{W(e.operationContext.signal),Yi(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Pr]:async t=>{W(e.operationContext.signal),Yi(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Lr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.openAppPage(Bd(t),e.operationContext),e.operationContext.signal)}}}const qd=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),$d=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),jd=new Set(["range","if-range","a-im"]),zd=new Set(["METHOD_FORBIDDEN","DOWNLOAD_HTTP_STATUS","DOWNLOAD_NETWORK_FAILED","DOWNLOAD_TIMEOUT","DOWNLOAD_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_IO_FAILED"]),Gd=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,qt={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Wd{constructor(t){this.signal=t}phase="initial";transition(t){if(qt[t]<=qt[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(qt[this.phase]<qt.committed&&this.signal.aborted)throw Ns()}normalizeHostError(t,r){return this.throwIfCancelled(),ii(t,r,this.signal)}}async function Kd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw pe("network.download");const o=Zn(r.operationContext,t.signal),s=new Wd(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Jd(e,i,o)}catch(d){throw s.normalizeHostError(d,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(d){throw s.normalizeHostError(d,"network")}let u=!1;try{s.throwIfCancelled(),s.transition("validate");const d=eu(c);tu(c,d);const h=ru(c.status,d);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw l("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const p=Zd(e,a,d,i);let f=0;const _=Qd(h.expectedBytes,e.maxBytes);en(t,Zr(0,h));const b={...o,onProgress(A){!Number.isSafeInteger(A)||A<f||_!==void 0&&A>_||(f=A,en(t,Zr(f,h)))}};s.transition("transfer"),u=!0;let I;try{I=await n.files.writeResource(p.handle,c.body,{mode:p.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},b)}catch(A){throw s.normalizeHostError(A,"transfer")}s.transition("committed"),f=Yd(I,h,f,e.maxBytes),en(t,Zr(f,h));const y=i.describeFile(p.handle,p.ref);return s.transition("completed"),y}finally{u||Xd(n.network,c.body)}}function Yd(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(n===void 0||o<=n))return o}catch{}return i}function Qd(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Xd(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Jd(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Un(i.handle.mode),await du(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Un(n.handle.mode),await uu(n.handle,r),{kind:"directory",...n}}function Zd(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,mode:"replace-existing"};const i=iu(e,r),o=n.deriveFile(t,i);return Un(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function eu(e){if(!e||typeof e!="object"||!Number.isInteger(e.status)||e.status<100||e.status>599||e.statusText!==void 0&&typeof e.statusText!="string"||!e.body||typeof e.body!="object")throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!M(e.headers))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!qd.has(r)||!Array.isArray(n)||n.length===0)throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function tu(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw l("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:cu(t,$d)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function ru(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(u=>u!=="0"))throw l("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw l("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=nu(t["content-encoding"]),a=e===204||e===205?0:n.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function nu(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Zr(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function en(e,t){try{e.postProgress(t)}catch{}}function iu(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=ou(i);if(o&&Kt(o))return o}for(const i of r){const o=su(i);if(o&&Kt(o))return o}if(e.suggestedName!==void 0)return Cs(e.suggestedName);const n=au(e.url);return n&&Kt(n)?n:"download.bin"}function ou(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function su(e){const t=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(e)?.[1];return t!==void 0?t.replace(/\\(["\\])/g,"$1"):/(?:^|;)\s*filename\s*=\s*([^;]+)/i.exec(e)?.[1]?.trim()}function au(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Cs(e){try{Ut(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Kt(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Kt(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Gd.test(e))}function cu(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function du(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Os()}catch(r){throw ii(r,"file",t.signal)}}async function uu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Os()}catch(r){throw ii(r,"file",t.signal)}}function Un(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const lu={METHOD_FORBIDDEN:"当前 Host 未开放下载能力",DOWNLOAD_HTTP_STATUS:"下载请求返回了失败状态",DOWNLOAD_NETWORK_FAILED:"下载网络请求失败",DOWNLOAD_TIMEOUT:"下载网络请求超时",DOWNLOAD_CANCELLED:"下载已取消",FILE_ACCESS_REVOKED:"下载目标授权已失效",FILE_ACCESS_DENIED:"下载目标不允许写入",FILE_NOT_FOUND:"下载目标文件不存在",DIRECTORY_NOT_FOUND:"下载目标目录不存在",FILE_ALREADY_EXISTS:"下载目标文件已存在",DIRECTORY_ALREADY_EXISTS:"下载目标目录已存在",FILE_TYPE_MISMATCH:"下载目标类型不匹配",FILE_TOO_LARGE:"下载响应超过大小限制",FILE_QUOTA_EXCEEDED:"下载目标配额已用尽",FILE_IO_FAILED:"下载文件写入失败"};function ii(e,t,r){if(r.aborted)return Ns();const n=hu(e);if(n&&zd.has(n)){const o=l(n,lu[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?l("DOWNLOAD_TIMEOUT","下载网络请求超时"):l("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?l("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):l("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function hu(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Os(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ns(){return l("DOWNLOAD_CANCELLED","下载已取消")}function fu(e){if(!e)return;const t=Object.keys(e).find(r=>jd.has(r.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const mu=4,gu=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],pu=["/account/restore_login","/account/check_login","/account/login","/account/get_login_code","/account/login_code","/account/get_qrcode_url","/account/qr_state","/account/google_2fa_verify","/account/open/login","/account/captcha","/account/get_verify_code","/account/send_verify_code","/account/verify_code"];function yu(e,t){const r=wu(e);return r===null||Qi(r,gu)?!0:t&&Qi(r,pu)}function wu(e){let t=e;for(let r=0;r<mu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Xi(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Xi(t)}function Qi(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Xi(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}const Eu=new Set(["url","method","params","data","headers","timeout","withCredentials"]),bu=new Set(["url","to","params","headers","timeout","withCredentials","suggestedName","overwrite","maxBytes"]),_u=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ji=3e4,Zi=2*1024*1024,Iu=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Au=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","set-cookie","transfer-encoding","user-agent"]),Su=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Ru="network.request 不支持 multipart/form-data,请使用专用上传能力";function vu(e){const t=Du(e.runtimePermissions),r=Vu(e.allowedHttpOrigins);return{[ur]:async(n,i)=>{if(!t.enabled)throw k("PERMISSION_DENIED","当前小程序暂不支持网络请求");const o=Pu(n,{permission:t,allowedHttpOrigins:r});return Kd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[dr]:async(n,i)=>{const o=Zn(e.operationContext,i?.signal);if(W(o.signal),!t.enabled)throw k("PERMISSION_DENIED","当前小程序暂不支持网络请求");const s=Tu(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw zu(c)?c:Gu(c,"REQUEST_UNSUPPORTED")?k("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):k("REQUEST_FAILED","网络请求失败")}return ju(a)}}}function Du(e){const t=Nt(e),r=t.permissions["network.request"];return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Tu(e,t){const r=Fr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Eu.has(c));if(n.length>0)throw k("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);const i=ks(r,t,"network.request"),o=Cu(r.method),s=r.data;s!==void 0&&Mu(s),Hu(i.headers,s);const a=xu(i.headers,s,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",...o===void 0?{}:{method:o},...i.params===void 0?{}:{params:i.params},...s===void 0?{}:{data:s},...i.headers===void 0?{}:{headers:i.headers},...i.withCredentials===void 0?{}:{withCredentials:i.withCredentials},...a===void 0?{}:{bodyEncoding:a},...i.timeout===void 0?{}:{timeout:i.timeout}}}function Pu(e,t){const r=Fr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!bu.has(c));if(n.length>0)throw k("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);const i=ks(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw k("INVALID_PARAMS","network.download timeout 必须是有限正数");fu(i.headers);const o=us(r.to),s=ls(r.to);if(!o&&!s)throw k("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw k("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw k("INVALID_PARAMS","suggestedName 必须是字符串");a=Cs(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw k("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw k("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout},...i.withCredentials===void 0?{}:{withCredentials:i.withCredentials}},url:i.url,to:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function ks(e,t,r){const n=Lu(e.url,t.allowedHttpOrigins,r),i=$u(n);if(i&&!t.permission.useOfficialDomain)throw k("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(yu(n.pathname,i))throw k("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,withCredentials:ku(e.withCredentials,`${r} withCredentials 必须是布尔值`),params:e.params===void 0?void 0:{...Fr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Ou(e.headers,r),timeout:Nu(e.timeout,r)}}function Lu(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw k("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw k("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw k("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw k("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw k("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Cu(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw k("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!_u.has(t))throw k("INVALID_PARAMS","network.request method 不合法");return t}function Ou(e,t="network.request"){const r=Fr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){if(!i.trim()||typeof o!="string")throw k("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);const s=i.trim().toLowerCase();if(Au.has(s)||s.startsWith("x-heybox-")||s.startsWith("x-xhh-"))throw k("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[i]=o}return n}function Nu(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw k("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ji)throw k("INVALID_PARAMS",`${t} timeout 不能超过 ${Ji}ms`);return e}}function ku(e,t){if(e!==void 0){if(typeof e!="boolean")throw k("INVALID_PARAMS",t);return e}}function Mu(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw k("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Uu(e)>Zi)throw k("INVALID_PARAMS",`network.request data 不能超过 ${Zi} 字节`)}function Uu(e){if(typeof e=="string")return tn(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return tn(e.toString());try{const t=JSON.stringify(e);return t?tn(t):0}catch{throw k("INVALID_PARAMS","network.request data 必须可序列化")}}function Hu(e,t){const r=Ms(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw k("INVALID_PARAMS",Ru)}function xu(e,t,r){if(t===void 0)return;const n=Ms(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||Fu(t))?"form":Bu(t)?"json":void 0}function Ms(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Bu(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Fu(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Vu(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&qu(n.hostname)&&t.add(n.origin)}catch{}return t}function qu(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function $u(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Iu.some(r=>t===r||t.endsWith(`.${r}`))}function ju(e){return Object.keys(e.headers).some(eo)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!eo(t)))}:e}function eo(e){const t=e.trim().toLowerCase();return Su.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function zu(e){return e instanceof Error&&e.name==="AbortError"}function Gu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Fr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw k("INVALID_PARAMS",t);return e}function tn(e){return new TextEncoder().encode(e).length}function k(e,t){return{code:e,message:t}}const $t=4294967296;function Wu(e){const t=new Ku;return t.write(e),t.finish()}class Ku{bytes=new Uint8Array(128);view=new DataView(this.bytes.buffer);offset=0;write(t){if(t===null)this.writeUint8(192);else if(typeof t=="boolean")this.writeUint8(t?195:194);else if(typeof t=="number")this.writeNumber(t);else if(typeof t=="string")this.writeString(t);else if(Array.isArray(t))this.writeArray(t);else if(typeof t=="object")this.writeMap(t);else throw new Error("unsupported share extra value")}finish(){return this.bytes.slice(0,this.offset)}writeNumber(t){if(!Number.isSafeInteger(t)){this.writeUint8(203),this.writeFloat64(t);return}if(t>=0){t<128?this.writeUint8(t):t<256?(this.writeUint8(204),this.writeUint8(t)):t<65536?(this.writeUint8(205),this.writeUint16(t)):t<$t?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=Yu(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<$t)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/$t),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/$t)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Yu(e){const t=new Uint8Array(Qu(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const o=e.charCodeAt(r);o>=56320&&o<=57343&&(r+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function Qu(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function Xu(e){Hn(e);const t=Wu(e);if(t.byteLength>128)throw new Error("share extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Hn(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)Hn(o,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.values(e);if(i.length>64)throw new Error("extra object has too many fields");for(const o of i)Hn(o,t+1,r);r.delete(e)}function Ju(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zu(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;if(typeof e=="string")return e.trim()||void 0}function el(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=Zu(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function tl(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(o)||(r.add(o),n.push(o))}return{invalidMessages:t,values:n}}function Us(e,t){if(e==null)return{};if(!Ju(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=el(e.topicIds),n=tl(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let o=r.values;t.maxTopicIds!==void 0&&o.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),o=o.slice(0,t.maxTopicIds));const s=o.length||n.values.length?{...o.length?{topicIds:o}:{},...n.values.length?{topics:n.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function rl(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function nl(e){try{if(rl(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function K(e){throw{code:"INVALID_PARAMS",message:e}}function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e,t){return typeof e!="string"||!e.trim()?K(t):e}function to(e,t){const r=xn(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?K(t):r}catch{return K(t)}}function il(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Hs(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return K(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return K(`${t} 缺少有效的小程序分享地址`)}}function ol(e,t){if(!Ht(e))return K("share.showShareMenu 参数必须是对象");const r=e.channel;if(r!==void 0&&!il(r))return K("share.showShareMenu channel 不合法");const n=xs(e.extra,"share.showShareMenu");let i;if(typeof e.url=="string"&&e.url.trim()){if(n!==void 0)return K("share.showShareMenu url 与 extra 不能同时使用");i=to(e.url,"share.showShareMenu url 必须是 HTTP(S) URL")}else{if(e.url!==void 0&&e.url!==null&&e.url!=="")return K("share.showShareMenu url 必须是 HTTP(S) URL");i=Hs(t,"share.showShareMenu",n)}return{title:xn(e.title,"share.showShareMenu title 必须是非空字符串"),description:xn(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:i,...e.imageUrl===void 0?{}:{imageUrl:to(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function xs(e,t){if(e!==void 0)try{return Xu(e)}catch{return K(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Bs(e,t){return e.invalidMessage&&await $(()=>nl(t.environment),t.operationContext.signal)?K(e.invalidMessage):e.post}function ro(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function sl(e){const t=e.getViewportMetrics();return{left:0,top:0,width:ro(t.windowWidth,0),height:ro(t.windowHeight,0)}}function Bn(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?K(t):r}function no(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?K(t):r}function al(e){return Ht(e)?{left:Bn(e.left,"share.screenshot rect.left 必须是非负数字"),top:Bn(e.top,"share.screenshot rect.top 必须是非负数字"),width:no(e.width,"share.screenshot rect.width 必须是正数"),height:no(e.height,"share.screenshot rect.height 必须是正数")}:K("share.screenshot rect 必须是对象")}function cl(e,t){if(e!=null&&!Ht(e))return K("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?K("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?sl(t):al(r.rect),...r.delay===void 0?{}:{delay:Bn(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function dl(e,t){W(t.operationContext.signal);const r=ol(e,t);let n=Us(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Bs(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function ul(e,t){if(W(t.operationContext.signal),e!==void 0&&!Ht(e))return K("share.copyLink 参数必须是对象");const r=xs(e?.extra,"share.copyLink"),n=Hs(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function ll(e,t){W(t.operationContext.signal);const r=cl(e,t.presentation),n=Us(Ht(e)?e.post:void 0,{method:"share.screenshot"}),i=await Bs(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=hl();let a=!1,c;try{a=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...r,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(d){c={status:"rejected",error:d}}const u=a?await fl(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(u)throw u;return c.value}function hl(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function fl(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function ml(e){return{[ir]:(t,r)=>ul(t,e),[or]:(t,r)=>dl(t,e),[sr]:(t,r)=>ll(t,e)}}const gl=128,pl=/^[A-Za-z0-9_-]+$/;function yl(e){const t=wl(e),r={[_t]:async n=>{W(e.operationContext.signal);const i=io(n,_t,e.storageLimits?.maxKeyLength),o=await $(()=>e.storage.getRaw(rn(t(),i),e.operationContext),e.operationContext.signal);return{data:oo(o)}},[It]:async n=>{W(e.operationContext.signal);const i=Fs(n,"storage.setStorage 参数必须是对象"),o=io(i,It,e.storageLimits?.maxKeyLength),s=El(i.data,e.storageLimits?.maxValueBytes);await $(()=>e.storage.setRaw(rn(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:r,diagnostics:{getSnapshot:async()=>{W(e.operationContext.signal);let n;try{n=t()}catch{throw Le("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=rn(n,"");return(await $(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(s=>s.key.startsWith(i)).map(s=>{const a=s.value;return{area:s.area,key:s.key.slice(i.length),value:oo(a),serializedValue:a,bytes:Vs(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function wl(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${so(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${so(i)}`)}t=r!==void 0}if(!r)throw Le("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function rn(e,t){return`hb_miniprogram_${e}_${t}`}function io(e,t,r=gl){const i=Fs(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Le("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!pl.test(i))throw Le("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function El(e,t){let r;try{r=JSON.stringify(e)}catch{throw Le("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Le("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Vs(r)>t)throw Le("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function oo(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Fs(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Le("INVALID_PARAMS",t);return e}function so(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:bl(e)}function bl(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Vs(e){return new TextEncoder().encode(e).length}function Le(e,t){return{code:e,message:t}}const ao=120;function ve(e){throw{code:"INVALID_PARAMS",message:e}}function oi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qs(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ve(`${r} 不支持字段: ${n.join(", ")}`)}function _l(e){if(!oi(e))return ve("ui.showToast 参数必须是对象");if(qs(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return ve("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>ao)return ve(`ui.showToast message 不能超过 ${ao} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return ve("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Il(e){return e===void 0?{dismissible:!1}:oi(e)?(qs(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?ve("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):ve("ui.showLoading 参数必须是对象")}function Al(e){e!==void 0&&(!oi(e)||Object.keys(e).length)&&ve("ui.hideLoading 不支持参数")}function Sl(e){return{[Ar]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showToast(_l(t),e.operationContext),e.operationContext.signal)},[Sr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showLoading(Il(t),e.operationContext),e.operationContext.signal)},[Rr]:async t=>{W(e.operationContext.signal),Al(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Rl={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ne(e,"当前用户首页资料接口响应异常")}},vl=3e4;function Dl(e,t,r={}){const n=r.ttlMs??vl;let i=0,o,s;async function a(){let u;try{u=await xr(e,Rl,void 0,{...t,credentials:"heybox-session"})}catch(d){throw t.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):d instanceof q?l("REQUEST_UNSUPPORTED",d.message):d instanceof Mt?l("INVALID_RESPONSE","user home_v2 响应不合法"):d instanceof rt?l("REQUEST_FAILED","user home_v2 请求失败"):d instanceof tt?l("REQUEST_FAILED",d.message):Pl(d)?d:l("REQUEST_FAILED","user home_v2 请求失败")}return Tl(u,"user home_v2")}function c(u){const d=Date.now();if(o?.userId===u&&o.expiresAt>d)return Promise.resolve(o.value);if(s?.userId===u&&s.generation===i)return s.promise;const h=i,p=a().then(f=>(i===h&&(o={userId:u,value:f,expiresAt:Date.now()+n}),f)).finally(()=>{s?.promise===p&&(s=void 0)});return s={userId:u,generation:h,promise:p},p}return{get:c,clear(){i+=1,o=void 0,s=void 0}}}function Tl(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Pl(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Ll={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.game.steam.get_game_list.get",method:"GET",path:"/game/steam/get_game_list",query(e){return{userid:e.userId,...e.steamId?{steam_id:e.steamId}:{},limit:e.limit,offset:e.offset,sort:e.sort,need_hidden:e.includeHidden,...e.personalInformationOpen===void 0?{}:{personal_infomation_open:e.personalInformationOpen},...e.q?{q:e.q}:{}}},parse(e,t){return ne(e,"Steam 游戏库接口响应异常")}},$s=20,Cl=100,js=0,zs="weeks",Ol=100,Nl=new Set(["weeks","all","achieved"]);function kl(e){const t=Dl(e.network,e.operationContext),r=new Map;let n=0,i=!1;const o=e.account.onChange(()=>{n+=1,t.clear(),r.clear()}),s=e.authorization.onEvent((b,I)=>{b==="user_info_authorization_change"&&"identity"in I&&I.identity==="denied"&&(n+=1,t.clear(),r.clear())});function a(){if(i||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(){const b=e.identity.get()?.miniProgramId?.trim();if(!b)throw l("INVALID_STATE","用户能力缺少 canonical 小程序身份");return b}async function u(){a();let b;try{b=await e.account.getCurrentUserId(e.operationContext)}catch(I){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):uo(I)?I:l("REQUEST_FAILED","读取小黑盒账号失败")}return typeof b=="string"&&b.trim()?b.trim():void 0}async function d(b,I){const y=await u();if(n!==I||y!==b)throw l("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function h(b,I){try{return await xr(e.network,b,I,{...e.operationContext,credentials:"heybox-session"})}catch(y){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):y instanceof q?l("REQUEST_UNSUPPORTED",y.message):y instanceof Mt?l("INVALID_RESPONSE","用户接口响应不合法"):y instanceof rt?l("REQUEST_FAILED","用户请求失败"):y instanceof tt?l("REQUEST_FAILED",y.message):uo(y)?y:l("REQUEST_FAILED","用户请求失败")}}async function p(){c();const b=n,I=await u();if(!I)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,A]=await Promise.all([e.authorization.getOrCreateLocalIdentity(I),f(I)]);return await d(I,b),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:A}}}function f(b){const I=r.get(b);if(I)return I;const y=h(ws,void 0).then(A=>{const R=co(A,"账号基础信息");if(R.display_username!==void 0&&typeof R.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(R.display_avatar!==void 0&&typeof R.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:R.display_username??"",avatar:R.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{r.get(b)===y&&r.delete(b)});return r.set(b,y),y}async function _(b){const I=Ml(b);c();const y=n,A=await u();if(!A)return{isLogin:!1,isBound:!1,data:null};const R=await t.get(A);await d(A,y);const P=si(R.steam_id_info);if(Object.keys(P).length===0)return{isLogin:!0,isBound:!1,data:null};const H=await h(Ll,{userId:A,...I,personalInformationOpen:Gs(P.personal_infomation_open??P.personal_information_open)});await d(A,y);const v=co(H,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:Fl(v,I)}}return{getInfo:p,getSteamGameList:_,dispose(){i||(i=!0,n+=1,o(),s(),t.clear(),r.clear())}}}function Ml(e){if(e==null)return{limit:$s,offset:js,sort:zs,includeHidden:!1};if(!M(e))throw De("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw De(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Ul(e.limit),offset:Hl(e.offset),sort:xl(e.sort),includeHidden:Bl(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw De("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw De("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ol))}return r}function Ul(e){if(e===void 0)return $s;if(!Number.isInteger(e)||Number(e)<1)throw De("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Cl)}function Hl(e){if(e===void 0)return js;if(!Number.isInteger(e)||Number(e)<0)throw De("user.getSteamGameList offset 必须是非负整数");return Number(e)}function xl(e){if(e===void 0)return zs;if(typeof e!="string"||!Nl.has(e))throw De("user.getSteamGameList sort 不支持");return e}function Bl(e){if(e===void 0)return!1;if(typeof e!="boolean")throw De("user.getSteamGameList includeHidden 必须是 boolean");return e}function Fl(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Vl).filter(a=>a!==void 0),n=kr(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=Gs(e.is_me);return s!==void 0&&(o.isMe=s),o}function Vl(e){const t=si(e),r=kr(t.appid),n=kr(t.steam_appid)??r,i=ai(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};gt(o,"image",t.image),gt(o,"icon",t.appicon??t.icon),pt(o,"playtimeForever",t.playtime_forever),pt(o,"playtime2Weeks",t.playtime_2weeks);const s=$l(t.external_tags??t.tags);s.length&&(o.tags=s);const a=ql(t.price);return a&&(o.price=a),o}function ql(e){const t=si(e),r={};return gt(r,"current",t.current),gt(r,"initial",t.initial),pt(r,"discount",t.discount),pt(r,"lowestPrice",t.lowest_price),gt(r,"deadlineDate",t.deadline_date),pt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function co(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function si(e){return M(e)?e:{}}function ai(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function $l(e){return Array.isArray(e)?e.map(ai).filter(Boolean):[]}function kr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Gs(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function gt(e,t,r){const n=ai(r);n&&Object.assign(e,{[t]:n})}function pt(e,t,r){const n=kr(r);n!==void 0&&Object.assign(e,{[t]:n})}function De(e){return l("INVALID_PARAMS",e)}function uo(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function jl(e){const t=Nt(e.runtimePermissions),r=()=>{if(!t.valid||t.permissions["network.request"]?.status==="enabled")throw l("SERVER_API_REQUIRED","当前模式要求由小程序服务端调用用户 API")},n=()=>{if(!t.valid)throw l("SERVER_API_REQUIRED","当前模式缺少有效的小程序权限快照")};return{[tr]:async i=>(r(),lo(i,"user.getInfo"),e.user.getInfo()),[rr]:async(i,o)=>{n(),lo(i,"user.revokeAuthorization"),await e.authorization.revoke(o.trustedUserGesture)},[nr]:async i=>(r(),e.user.getSteamGameList(i))}}function lo(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}function ho(e){throw{code:"INVALID_PARAMS",message:e}}function dt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Ws(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function jt(e,t,r){return Math.min(Ws(e,t),r)}async function zl(e){try{return Ws(await e.getNavigationBarHeight(),0)}catch{return 0}}function Gl(e,t,r,n){const i=jt(e.safeArea?.left,0,t),o=Math.max(i,jt(e.safeArea?.right,t,t)),s=jt(e.safeArea?.top,n,r),a=Math.max(s,jt(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Wl(e){const t=e.getViewportMetrics(),r=dt(t.windowWidth,0),n=dt(t.windowHeight,0),i=await zl(e);return{pixelRatio:dt(t.pixelRatio,1),screenWidth:dt(t.screenWidth,r),screenHeight:dt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Gl(t,r,n,i),screenTop:i}}function Kl(e){return{[ar]:async()=>(W(e.operationContext.signal),Wl(e.presentation)),[cr]:async t=>{if(W(e.operationContext.signal),typeof t!="object"||t===null||Array.isArray(t))return ho("viewport.setNavigationBarStyle 参数必须是对象");const r=t.foregroundStyle;if(r!=="light"&&r!=="dark")return ho("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>e.presentation.setNavigationBarStyle(r,e.operationContext),e.operationContext.signal)}}}const Yl=new Map(Pe.map(e=>[e.method,e]));function nn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Ql(e){const t=Nt(e);return r=>hs(r)?(t.valid?t.permissions[r]:void 0)?.status==="enabled"?{allowed:!0}:{allowed:!1,code:"PERMISSION_DENIED",message:r==="network.request"?"当前小程序暂不支持网络请求":"当前小程序暂不支持该能力"}:{allowed:!0}}function Xl(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=d=>{a||(a=!0,n.removeEventListener("abort",u),d())},u=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",u,{once:!0}),i.then(d=>c(()=>o({status:"handled",value:d})),d=>c(()=>s(d)))})}function Jl(e){const t=Ql(e.runtimePermissions);let r=0;return{async dispatch(n,i,o){const s=e.now??Zl,a=e.onTrace?s():0,c=e.onTrace?`cap_${++r}`:"";try{if(e.terminalSignal.aborted)throw nn("RUNTIME_DESTROYED","小程序 Runtime 已终止");Ya(n,e.effectiveCapabilities);const u=Yl.get(n);if(!u)throw new Error(`Capability method ${n} 缺少 protocol metadata`);const d=t(u.permission);if(!d.allowed)throw nn(d.code,d.message);const h=e.handlers[n];if(!h)throw new Error(`Capability method ${n} 缺少 handler`);const p=await Xl(async()=>{for(const f of e.policies??[]){const _=await f.evaluate({method:n,payload:i,capability:u});if(e.terminalSignal.aborted)throw go();if(!_.allowed)throw nn(_.code,_.message,_.data)}if(e.terminalSignal.aborted)throw go();return h(i,o)},void 0,o,e.terminalSignal);return fo(e.onTrace,mo(c,n,i,a,p),s),p}catch(u){throw fo(e.onTrace,mo(c,n,i,a,{status:"error",error:u}),s),u}}}}function Zl(){return typeof performance>"u"?Date.now():performance.now()}function fo(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function mo(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:eh(i.error)}:{},...th(t,r,i)}}function eh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function th(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&rh(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function rh(e){return typeof e=="object"&&e!==null}function go(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function nh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=new hd(e.files,e.miniProgramDetail),n=bd({registry:r,picker:e.picker,operationContext:t}),i=Tc({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation});let o,s,a=()=>{};try{o=kl({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),a=i.onEvent((f,_)=>e.eventSink.postEvent(f,_)),s=nd({account:e.account,identity:e.identity,network:e.network,operationContext:t});const c=yl({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),u=[{name:"auth",handlers:Uc({authorization:i,runtimePermissions:e.runtimePermissions})},{name:"user",handlers:jl({user:o,authorization:i,runtimePermissions:e.runtimePermissions})},{name:"share",handlers:ml({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:Kl({operationContext:t,presentation:e.hostPresentation})},{name:"storage",handlers:c.handlers},{name:"network",handlers:vu({network:e.network,transfer:e.transfer,fileRegistry:r,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:n.files},{name:"file",handlers:n.file},{name:"directory",handlers:n.directory},{name:"ui",handlers:Sl({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:dd({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:Vd({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:s.handlers}],d=ih(u);let h=!1;const p=()=>{h||(h=!0,e.terminalSignal.removeEventListener("abort",p),s?.dispose(),a(),o?.dispose(),i.dispose(),r.dispose())};return e.terminalSignal.aborted?p():e.terminalSignal.addEventListener("abort",p,{once:!0}),{modules:u,handlers:d,...c.diagnostics?{storageDiagnostics:c.diagnostics}:{},dispose:p}}catch(c){throw s?.dispose(),a(),o?.dispose(),i.dispose(),r.dispose(),c}}function ih(e){const t=new Map(Pe.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=Pe.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Pe.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const oh="heybox-mini-dev:";function po(e){try{return sh(new URL(e))}catch{return!1}}function sh(e){return e.protocol===oh}function ah(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||ch(e)}function ch(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const dh=1,Ks="allow-scripts allow-same-origin",uh="",lh="no-referrer";function hh(e=Ks){return!e.split(/\s+/).includes("allow-same-origin")}function yo(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const fh=new Set(["javascript:","data:","blob:","file:"]),wo="xiaoheihe.cn";function mh(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(fh.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Eh(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function gh(e,t){const r=new URL(e);return r.searchParams.set(Na,t),r.toString()}function ph(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=yh(r)??wh(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function yh(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function wh(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Eo(e){const t=new URL(e);return ci(t)?"loopback":di(t)?"lan":"production"}function Eh(e,t,r){return bh(e)||ci(e)||di(e)&&Ih(t,r)}function bh(e){return e.protocol==="https:"&&Rh(e.hostname)}function ci(e){return e.protocol==="http:"&&_h(e.hostname)}function _h(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function di(e){return e.protocol==="http:"&&Ah(e.hostname)}function Ih(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return ci(r)||di(r)}catch{return!1}}function Ah(e){const t=Sh(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Sh(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function Rh(e){return e===wo||e.endsWith(`.${wo}`)}const vh=new Set(["base-uri","child-src","connect-src","default-src","font-src","form-action","frame-src","img-src","manifest-src","media-src","object-src","prefetch-src","script-src","script-src-attr","script-src-elem","style-src","style-src-attr","style-src-elem","worker-src"]),Dh=new Set(["url","inline","eval","unknown"]),Th=/^\/(?:\:segment(?:\/\:segment)*)?$/,Ph=/^[a-f0-9]{64}$/,Lh=255,Ch=160,Oh=256;function Nh(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!vh.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Oh||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Dh.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=kh(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Ch||!Th.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Ph.test(o)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function kh(e){if(e!==void 0&&!(typeof e!="string"||e.length>Lh))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Mh=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Uh(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:Hh(i.pathname),sanitizedPathnameHash:xh(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Hh(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function xh(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let I=0;I<16;I+=1)o[I]=s.getUint32(a+I*4,!1);for(let I=16;I<64;I+=1){const y=o[I-15],A=o[I-2],R=le(y,7)^le(y,18)^y>>>3,P=le(A,17)^le(A,19)^A>>>10;o[I]=o[I-16]+R+o[I-7]+P>>>0}let[c,u,d,h,p,f,_,b]=i;for(let I=0;I<64;I+=1){const y=b+(le(p,6)^le(p,11)^le(p,25))+(p&f^~p&_)+Mh[I]+o[I]>>>0,A=(le(c,2)^le(c,13)^le(c,22))+(c&u^c&d^u&d);b=_,_=f,f=p,p=h+y>>>0,h=d,d=u,u=c,c=y+A>>>0}[c,u,d,h,p,f,_,b].forEach((I,y)=>{i[y]=i[y]+I>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function le(e,t){return e>>>t|e<<32-t}const Bh=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Fh(e){if(!e?.minimumSdkVersion)throw U("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=ft(e.minimumSdkVersion),r=e.sdkVersion?ft(e.sdkVersion):void 0;if(!t)throw U("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw U("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=ft("0.6.0");if(!r){if(on(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw U("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw U("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(on(r,t)<0)throw U("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:on(r,ft("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Vh(e,t){if(typeof t!="string"||!ft(t))throw U("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw U("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ft(e){const t=Bh.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function on(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const qh=1e4,sn=2e3,$h=2,jh="open-with-native-credential-policy",Ys="安全提示",Qs="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class zh{nonce=yo();runtimeId=yo();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;constructor(t){this.options=t,this.iframe=t.iframe;const r=ys(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??qh,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??U("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??U("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(ef(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.stateValue==="destroyed")return;const t=U("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?(this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.resendDocumentRevalidationProbe()):this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()}}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive()||(this.runtimePermissions=t.runtimePermissions,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope,this.allowedHttpOrigins=t.allowedHttpOrigins??this.options.allowedHttpOrigins,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=Fh(t.sdkVersionPolicy),this.miniProgramDetail=nf(t),this.effectiveCapabilities=ps(this.primitiveAvailability,{callerCapabilities:this.options.capabilities,hostCapabilities:this.options.hostCapabilities,miniProgramDetail:this.miniProgramDetail}),console.info("[hb-sdk-runtime] host capability",Object.freeze({filesAccessPrimitive:this.primitiveAvailability["files.access"],callerFileCreate:this.options.capabilities?.["file.create"]??"default",hostFileCreate:this.options.hostCapabilities?.["file.create"]??"default",canonicalMiniProgramDetail:!!this.miniProgramDetail?.miniProgramId.trim(),effectiveFileCreate:this.effectiveCapabilities["file.create"]===!0})),this.compatibilityWithoutSdk=!!(t.sdkVersionPolicy&&t.sdkVersionPolicy.releaseChannel!==void 0&&!this.sdkVersionDecision.sdkVersion&&!this.sdkVersionDecision.heartbeatEnabled),Yh(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive()))return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const r=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const n=await this.confirmDevMiniProgramLaunch(r);if(!this.isInactive()){if(!n){await this.closeAfterDevLaunchCancellation();return}this.bridgeServer?.setTargetOrigin(Xh(r)),this.launchUrl=r,this.miniProgramSrc=gh(r,this.nonce),this.traceSecurityPolicy(r),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ie(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=nh({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,transfer:this.ports.transfer,storage:this.ports.storage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins});const r=Jl({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:u,network:d})=>{const h={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...u?{errorCode:u}:{},...this.identity,...d?{network:d}:{}};Ie(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Wa({iframe:this.iframe,nonce:this.nonce,dispatcher:r,onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(U("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw Kh(t)?t:Xs(U("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return mh(t,r,{allowPrivateNetwork:po(r)||bo(r)||await this.isDevRuntime()})}catch(r){throw U("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Zh)({message:Qs,title:Ys,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Eo(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!po(r)&&!bo(r)}async closeAfterDevLaunchCancellation(){const t=U("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{_o(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>_o())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",uh),this.iframe.setAttribute("referrerpolicy",lh),this.iframe.setAttribute("sandbox",Ks)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),Ie(this.options.onReady,t)}completeCompatibilityLaunch(){if(this.stateValue!=="starting"||this.isInactive()||this.readyContext)return;this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:"bridge_ready"}),this.setState("ready"),this.resolveReady?.(t),Ie(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Vh(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(U("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时")))},this.handshakeTimeout))}clearHandshakeTimeout(){this.handshakeTimeoutTimer&&(clearTimeout(this.handshakeTimeoutTimer),this.handshakeTimeoutTimer=void 0)}sendLocationProbe(){if(this.isInactive()||!this.hostVisible||!this.sdkVersionDecision?.heartbeatEnabled||this.documentRevalidationPending)return;if(this.pendingProbeId&&(this.consecutiveHeartbeatMisses+=1,this.consecutiveHeartbeatMisses>=$h)){this.failRuntime(U("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Ft,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},sn),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Ft})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(r),t.deferProbe||this.sendDocumentRevalidationProbe(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(Ft,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Ft})}armDocumentRevalidationTimer(t){this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&(this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(U("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},sn))}clearDocumentRevalidationTimer(){this.documentRevalidationTimer&&(clearTimeout(this.documentRevalidationTimer),this.documentRevalidationTimer=void 0)}completeDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&(this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},sn))}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===Ua){this.handleCspViolation(t.payload);return}if(t.method!==Ma)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(U("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!ph(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(U("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=Nh(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){Ie(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Uh(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(U("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 发生未授权文档加载"))},50)}clearUnexpectedDocumentLoadFailure(){this.unexpectedDocumentLoadTimer&&(clearTimeout(this.unexpectedDocumentLoadTimer),this.unexpectedDocumentLoadTimer=void 0)}traceSecurityPolicy(t){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"security",sandboxPolicyVersion:dh,launchUrlType:Eo(t),networkPolicy:jh})}failRuntime(t){const r=Gh(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),Ie(this.options.onError,Wh(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,Ie(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ie(this.options.onTrace,{...t,runtimeId:this.runtimeId,...this.identity})}createLaunchContext(){return{launchUrl:this.launchUrl,src:this.miniProgramSrc,sdkVersion:this.sdkVersionDecision?.sdkVersion,heartbeatEnabled:!!this.sdkVersionDecision?.heartbeatEnabled,...this.identity}}createReadyContext(){return this.readyContext??this.createLaunchContext()}}function Gh(e){const t=fs(e);return Mr(e)&&"cause"in e&&Xs(t,e.cause),t}function Xs(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Wh(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Kh(e){return Mr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Mr(e){return!!e&&typeof e=="object"}function Ie(e,t){try{e?.(t)}catch{}}function Yh(e,t,r){try{e?.(t,r)}catch{}}function bo(e){try{const t=new URL(e);return t.protocol==="http:"&&ah(t.hostname)}catch{return!1}}function Qh(e){try{return new URL(e).origin}catch{return}}function Xh(e){return hh()?"*":Qh(e)}function Jh(e){return`${Ys}
2
-
3
- ${Qs}
4
-
5
- URL: ${e}`}function Zh(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Jh(e.url))}function _o(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function ef(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:as,knownMethodCount:Pe.length,supportsFileCreate:Pe.some(i=>i.method===At),system:tf(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ke(e?.hardwareConcurrency),maxTouchPoints:Ke(e?.maxTouchPoints),screen:{width:Ke(t?.width),height:Ke(t?.height)},viewport:{width:Ke(r?.innerWidth),height:Ke(r?.innerHeight),devicePixelRatio:rf(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function tf(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function Ke(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function rf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function nf(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function of(e){if(!Mr(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Mr(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new zh(e)}const sf=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i;function af(e,t,r){return Ja({mode:"request-only",request:(n,i={signal:t.signal})=>t.run(i.signal,async o=>{const s={...i,signal:o},a=uf(n),c=n.source==="public-sdk"&&n.withCredentials===!0?await cf(a,e,r(),s):await e.authenticatedRequest(a,s);return lf(c)})}).network}function cf(e,t,r,n){if(e.source!=="public-sdk"||e.target.kind!=="absolute-url")throw new q("Web public session 只支持按 origin 隔离的 absolute-url 请求");if(!t.partitionedOriginRequest)throw new q("Web Host 未提供按 origin 隔离的 cookie jar");if(!r)throw new q("origin-session 请求前必须先解析 canonical mini-program ID");return t.partitionedOriginRequest(e,df(e.target.url,r),n)}function df(e,t){let r;try{r=new URL(e)}catch{throw new q("origin-session 目标必须是有效的 absolute URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new q("origin-session 目标必须使用 HTTP(S)");return{canonicalMiniProgramId:t,targetOrigin:r.origin,redirectPolicy:"error"}}function uf(e){const t=Js(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function lf(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:Js(e.headers)??{}}}function Js(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!hf(t)))}function hf(e){const t=e.trim().toLowerCase();return sf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ff(e,t,r,n){const i=wf(e.presentation,t);return{account:pf(e,t,r),network:af(e,t,n),...e.storage===void 0?{}:{storage:yf(e,t)},...e.storage===void 0?{}:mf(e,t),...i===void 0?{}:{presentation:i}}}function mf(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function gf(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function pf(e,t,r){return{getCurrentUserId:n=>t.run(n.signal,i=>e.account.getCurrentUserId({signal:i})),ensureAuthenticated:n=>t.run(n.signal,i=>e.account.ensureAuthenticated({trustedUserGesture:n.trustedUserGesture,reason:n.reason,signal:i})),onChange:n=>{t.assertActive();const i=e.account.onChange(o=>{t.signal.aborted||n(o)});return r(i)}}}function yf(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function wf(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,o=>e.openAppPage(n,{signal:o}))),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(n,{signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>uc(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{signal:o}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,o=>e.vibrate(n,{signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{signal:o}))),Object.keys(r).length===0?void 0:r}function Ef(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw zt(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(d=>d.aborted);if(i)throw zt(i.reason);const o=new AbortController;let s;const a=new Promise((d,h)=>{s=h}),c=n.map(d=>{const h=()=>{o.signal.aborted||o.abort(d.reason),s(zt(d.reason))};return d.addEventListener("abort",h,{once:!0}),{listener:h,source:d}});let u;try{u=Promise.resolve(r(o.signal))}catch(d){u=Promise.reject(d)}try{const d=await Promise.race([u,a]),h=n.find(p=>p.aborted);if(h)throw zt(h.reason);return d}finally{for(const{listener:d,source:h}of c)h.removeEventListener("abort",d)}}}}function zt(e){return new DOMException("Web Host operation aborted","AbortError")}async function bf(e){const t=Ef(),r=new Set;let n=!1;const i=p=>{if(n||t.signal.aborted)return an(p),()=>{};let f=!0;const _=()=>{f&&(f=!1,r.delete(_),an(p))};return r.add(_),_},o=()=>s(e.signal.reason),s=p=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(p);for(const f of[...r])f();e.onDispose&&an(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);let a;const c=ff(e,t,i,()=>a),u=ys(c,{hostCapabilities:e.hostCapabilities}),d=gf(e,t);let h;return{platform:"web",ports:c,environment:d,resolveLaunch:()=>(h??=t.run(void 0,async p=>{const f=await e.resolveLaunch(p),_=f.configuration.canonicalIdentity?.miniProgramId;return a=(typeof _=="string"?_.trim():"")||void 0,f}),h),...e.authPresentation===void 0?{}:{authPresentation:_f(e.authPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:s}}function an(e){try{e()}catch{}}function _f(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Ye={},cn,Io;function If(){return Io||(Io=1,cn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),cn}var dn={},Ae={},Ao;function qe(){if(Ao)return Ae;Ao=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ae.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Ae.getSymbolTotalCodewords=function(n){return t[n]},Ae.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ae.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ae.isKanjiModeEnabled=function(){return typeof e<"u"},Ae.toSJIS=function(n){return e(n)},Ae}var un={},So;function ui(){return So||(So=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(un)),un}var ln,Ro;function Af(){if(Ro)return ln;Ro=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},ln=e,ln}var hn,vo;function Sf(){if(vo)return hn;vo=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},hn=e,hn}var fn={},Do;function Rf(){return Do||(Do=1,(function(e){const t=qe().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(fn)),fn}var mn={},To;function vf(){if(To)return mn;To=1;const e=qe().getSymbolSize,t=7;return mn.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},mn}var gn={},Po;function Df(){return Po||(Po=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,u=null,d=null;for(let h=0;h<o;h++){a=c=0,u=d=null;for(let p=0;p<o;p++){let f=i.get(h,p);f===u?a++:(a>=5&&(s+=t.N1+(a-5)),u=f,a=1),f=i.get(p,h),f===d?c++:(c>=5&&(s+=t.N1+(c-5)),d=f,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const u=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(u===4||u===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let u=0;u<o;u++){a=c=0;for(let d=0;d<o;d++)a=a<<1&2047|i.get(u,d),d>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(d,u),d>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let u=0;u<s;u++){o(u),e.applyMask(u,i);const d=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(u,i),d<c&&(c=d,a=u)}return a}})(gn)),gn}var Gt={},Lo;function Zs(){if(Lo)return Gt;Lo=1;const e=ui(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Gt.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},Gt.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},Gt}var pn={},ut={},Co;function Tf(){if(Co)return ut;Co=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),ut.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ut.exp=function(n){return e[n]},ut.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},ut}var Oo;function Pf(){return Oo||(Oo=1,(function(e){const t=Tf();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(pn)),pn}var yn,No;function Lf(){if(No)return yn;No=1;const e=Pf();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},yn=t,yn}var wn={},En={},bn={},ko;function ea(){return ko||(ko=1,bn.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bn}var he={},Mo;function ta(){if(Mo)return he;Mo=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
6
- ]))+`;he.KANJI=new RegExp(r,"g"),he.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),he.BYTE=new RegExp(n,"g"),he.NUMERIC=new RegExp(e,"g"),he.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return he.testKanji=function(c){return i.test(c)},he.testNumeric=function(c){return o.test(c)},he.testAlphanumeric=function(c){return s.test(c)},he}var Uo;function $e(){return Uo||(Uo=1,(function(e){const t=ea(),r=ta();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(En)),En}var Ho;function Cf(){return Ho||(Ho=1,(function(e){const t=qe(),r=Zs(),n=ui(),i=$e(),o=ea(),s=7973,a=t.getBCHDigit(s);function c(p,f,_){for(let b=1;b<=40;b++)if(f<=e.getCapacity(b,_,p))return b}function u(p,f){return i.getCharCountIndicator(p,f)+4}function d(p,f){let _=0;return p.forEach(function(b){const I=u(b.mode,f);_+=I+b.getBitsLength()}),_}function h(p,f){for(let _=1;_<=40;_++)if(d(p,_)<=e.getCapacity(_,f,i.MIXED))return _}e.from=function(f,_){return o.isValid(f)?parseInt(f,10):_},e.getCapacity=function(f,_,b){if(!o.isValid(f))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=i.BYTE);const I=t.getSymbolTotalCodewords(f),y=r.getTotalCodewordsCount(f,_),A=(I-y)*8;if(b===i.MIXED)return A;const R=A-u(b,f);switch(b){case i.NUMERIC:return Math.floor(R/10*3);case i.ALPHANUMERIC:return Math.floor(R/11*2);case i.KANJI:return Math.floor(R/13);case i.BYTE:default:return Math.floor(R/8)}},e.getBestVersionForData=function(f,_){let b;const I=n.from(_,n.M);if(Array.isArray(f)){if(f.length>1)return h(f,I);if(f.length===0)return 1;b=f[0]}else b=f;return c(b.mode,b.getLength(),I)},e.getEncodedBits=function(f){if(!o.isValid(f)||f<7)throw new Error("Invalid QR Code version");let _=f<<12;for(;t.getBCHDigit(_)-a>=0;)_^=s<<t.getBCHDigit(_)-a;return f<<12|_}})(wn)),wn}var _n={},xo;function Of(){if(xo)return _n;xo=1;const e=qe(),t=1335,r=21522,n=e.getBCHDigit(t);return _n.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},_n}var In={},An,Bo;function Nf(){if(Bo)return An;Bo=1;const e=$e();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},An=t,An}var Sn,Fo;function kf(){if(Fo)return Sn;Fo=1;const e=$e(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},Sn=r,Sn}var Rn,Vo;function Mf(){if(Vo)return Rn;Vo=1;const e=$e();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},Rn=t,Rn}var vn,qo;function Uf(){if(qo)return vn;qo=1;const e=$e(),t=qe();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
7
- Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},vn=r,vn}var Dn={exports:{}},$o;function Hf(){return $o||($o=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,u,d,h,p,f,_,b,I;!a.empty();){c=a.pop(),u=c.value,h=c.cost,p=r[u]||{};for(d in p)p.hasOwnProperty(d)&&(f=p[d],_=h+f,b=s[d],I=typeof s[d]>"u",(I||b>_)&&(s[d]=_,a.push(d,_),o[d]=u))}if(typeof i<"u"&&typeof s[i]>"u"){var y=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(y)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Dn)),Dn.exports}var jo;function xf(){return jo||(jo=1,(function(e){const t=$e(),r=Nf(),n=kf(),i=Mf(),o=Uf(),s=ta(),a=qe(),c=Hf();function u(y){return unescape(encodeURIComponent(y)).length}function d(y,A,R){const P=[];let H;for(;(H=y.exec(R))!==null;)P.push({data:H[0],index:H.index,mode:A,length:H[0].length});return P}function h(y){const A=d(s.NUMERIC,t.NUMERIC,y),R=d(s.ALPHANUMERIC,t.ALPHANUMERIC,y);let P,H;return a.isKanjiModeEnabled()?(P=d(s.BYTE,t.BYTE,y),H=d(s.KANJI,t.KANJI,y)):(P=d(s.BYTE_KANJI,t.BYTE,y),H=[]),A.concat(R,P,H).sort(function(O,C){return O.index-C.index}).map(function(O){return{data:O.data,mode:O.mode,length:O.length}})}function p(y,A){switch(A){case t.NUMERIC:return r.getBitsLength(y);case t.ALPHANUMERIC:return n.getBitsLength(y);case t.KANJI:return o.getBitsLength(y);case t.BYTE:return i.getBitsLength(y)}}function f(y){return y.reduce(function(A,R){const P=A.length-1>=0?A[A.length-1]:null;return P&&P.mode===R.mode?(A[A.length-1].data+=R.data,A):(A.push(R),A)},[])}function _(y){const A=[];for(let R=0;R<y.length;R++){const P=y[R];switch(P.mode){case t.NUMERIC:A.push([P,{data:P.data,mode:t.ALPHANUMERIC,length:P.length},{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.ALPHANUMERIC:A.push([P,{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.KANJI:A.push([P,{data:P.data,mode:t.BYTE,length:u(P.data)}]);break;case t.BYTE:A.push([{data:P.data,mode:t.BYTE,length:u(P.data)}])}}return A}function b(y,A){const R={},P={start:{}};let H=["start"];for(let v=0;v<y.length;v++){const O=y[v],C=[];for(let S=0;S<O.length;S++){const w=O[S],D=""+v+S;C.push(D),R[D]={node:w,lastCount:0},P[D]={};for(let m=0;m<H.length;m++){const g=H[m];R[g]&&R[g].node.mode===w.mode?(P[g][D]=p(R[g].lastCount+w.length,w.mode)-p(R[g].lastCount,w.mode),R[g].lastCount+=w.length):(R[g]&&(R[g].lastCount=w.length),P[g][D]=p(w.length,w.mode)+4+t.getCharCountIndicator(w.mode,A))}}H=C}for(let v=0;v<H.length;v++)P[H[v]].end=0;return{map:P,table:R}}function I(y,A){let R;const P=t.getBestModeForData(y);if(R=t.from(A,P),R!==t.BYTE&&R.bit<P.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(R)+`.
8
- Suggested mode is: `+t.toString(P));switch(R===t.KANJI&&!a.isKanjiModeEnabled()&&(R=t.BYTE),R){case t.NUMERIC:return new r(y);case t.ALPHANUMERIC:return new n(y);case t.KANJI:return new o(y);case t.BYTE:return new i(y)}}e.fromArray=function(A){return A.reduce(function(R,P){return typeof P=="string"?R.push(I(P,null)):P.data&&R.push(I(P.data,P.mode)),R},[])},e.fromString=function(A,R){const P=h(A,a.isKanjiModeEnabled()),H=_(P),v=b(H,R),O=c.find_path(v.map,"start","end"),C=[];for(let S=1;S<O.length-1;S++)C.push(v.table[O[S]].node);return e.fromArray(f(C))},e.rawSplit=function(A){return e.fromArray(h(A,a.isKanjiModeEnabled()))}})(In)),In}var zo;function Bf(){if(zo)return dn;zo=1;const e=qe(),t=ui(),r=Af(),n=Sf(),i=Rf(),o=vf(),s=Df(),a=Zs(),c=Lf(),u=Cf(),d=Of(),h=$e(),p=xf();function f(v,O){const C=v.size,S=o.getPositions(O);for(let w=0;w<S.length;w++){const D=S[w][0],m=S[w][1];for(let g=-1;g<=7;g++)if(!(D+g<=-1||C<=D+g))for(let E=-1;E<=7;E++)m+E<=-1||C<=m+E||(g>=0&&g<=6&&(E===0||E===6)||E>=0&&E<=6&&(g===0||g===6)||g>=2&&g<=4&&E>=2&&E<=4?v.set(D+g,m+E,!0,!0):v.set(D+g,m+E,!1,!0))}}function _(v){const O=v.size;for(let C=8;C<O-8;C++){const S=C%2===0;v.set(C,6,S,!0),v.set(6,C,S,!0)}}function b(v,O){const C=i.getPositions(O);for(let S=0;S<C.length;S++){const w=C[S][0],D=C[S][1];for(let m=-2;m<=2;m++)for(let g=-2;g<=2;g++)m===-2||m===2||g===-2||g===2||m===0&&g===0?v.set(w+m,D+g,!0,!0):v.set(w+m,D+g,!1,!0)}}function I(v,O){const C=v.size,S=u.getEncodedBits(O);let w,D,m;for(let g=0;g<18;g++)w=Math.floor(g/3),D=g%3+C-8-3,m=(S>>g&1)===1,v.set(w,D,m,!0),v.set(D,w,m,!0)}function y(v,O,C){const S=v.size,w=d.getEncodedBits(O,C);let D,m;for(D=0;D<15;D++)m=(w>>D&1)===1,D<6?v.set(D,8,m,!0):D<8?v.set(D+1,8,m,!0):v.set(S-15+D,8,m,!0),D<8?v.set(8,S-D-1,m,!0):D<9?v.set(8,15-D-1+1,m,!0):v.set(8,15-D-1,m,!0);v.set(S-8,8,1,!0)}function A(v,O){const C=v.size;let S=-1,w=C-1,D=7,m=0;for(let g=C-1;g>0;g-=2)for(g===6&&g--;;){for(let E=0;E<2;E++)if(!v.isReserved(w,g-E)){let T=!1;m<O.length&&(T=(O[m]>>>D&1)===1),v.set(w,g-E,T),D--,D===-1&&(m++,D=7)}if(w+=S,w<0||C<=w){w-=S,S=-S;break}}}function R(v,O,C){const S=new r;C.forEach(function(E){S.put(E.mode.bit,4),S.put(E.getLength(),h.getCharCountIndicator(E.mode,v)),E.write(S)});const w=e.getSymbolTotalCodewords(v),D=a.getTotalCodewordsCount(v,O),m=(w-D)*8;for(S.getLengthInBits()+4<=m&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const g=(m-S.getLengthInBits())/8;for(let E=0;E<g;E++)S.put(E%2?17:236,8);return P(S,v,O)}function P(v,O,C){const S=e.getSymbolTotalCodewords(O),w=a.getTotalCodewordsCount(O,C),D=S-w,m=a.getBlocksCount(O,C),g=S%m,E=m-g,T=Math.floor(S/m),N=Math.floor(D/m),F=N+1,V=T-N,Z=new c(V);let se=0;const J=new Array(m),z=new Array(m);let ye=0;const zr=new Uint8Array(v.buffer);for(let ze=0;ze<m;ze++){const Gr=ze<E?N:F;J[ze]=zr.slice(se,se+Gr),z[ze]=Z.encode(J[ze]),se+=Gr,ye=Math.max(ye,Gr)}const st=new Uint8Array(S);let wi=0,we,Ee;for(we=0;we<ye;we++)for(Ee=0;Ee<m;Ee++)we<J[Ee].length&&(st[wi++]=J[Ee][we]);for(we=0;we<V;we++)for(Ee=0;Ee<m;Ee++)st[wi++]=z[Ee][we];return st}function H(v,O,C,S){let w;if(Array.isArray(v))w=p.fromArray(v);else if(typeof v=="string"){let T=O;if(!T){const N=p.rawSplit(v);T=u.getBestVersionForData(N,C)}w=p.fromString(v,T||40)}else throw new Error("Invalid data");const D=u.getBestVersionForData(w,C);if(!D)throw new Error("The amount of data is too big to be stored in a QR Code");if(!O)O=D;else if(O<D)throw new Error(`
9
- The chosen QR Code version cannot contain this amount of data.
10
- Minimum version required to store current data is: `+D+`.
11
- `);const m=R(O,C,w),g=e.getSymbolSize(O),E=new n(g);return f(E,O),_(E),b(E,O),y(E,C,0),O>=7&&I(E,O),A(E,m),isNaN(S)&&(S=s.getBestMask(E,y.bind(null,E,C))),s.applyMask(S,E),y(E,C,S),{modules:E,version:O,errorCorrectionLevel:C,maskPattern:S,segments:w}}return dn.create=function(O,C){if(typeof O>"u"||O==="")throw new Error("No input text");let S=t.M,w,D;return typeof C<"u"&&(S=t.from(C.errorCorrectionLevel,t.M),w=u.from(C.version),D=s.from(C.maskPattern),C.toSJISFunc&&e.setToSJISFunction(C.toSJISFunc)),H(O,w,S,D)},dn}var Tn={},Pn={},Go;function ra(){return Go||(Go=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),u=Math.floor((s+o.margin*2)*c),d=o.margin*c,h=[o.color.light,o.color.dark];for(let p=0;p<u;p++)for(let f=0;f<u;f++){let _=(p*u+f)*4,b=o.color.light;if(p>=d&&f>=d&&p<u-d&&f<u-d){const I=Math.floor((p-d)/c),y=Math.floor((f-d)/c);b=h[a[I*s+y]?1:0]}n[_++]=b.r,n[_++]=b.g,n[_++]=b.b,n[_]=b.a}}})(Pn)),Pn}var Wo;function Ff(){return Wo||(Wo=1,(function(e){const t=ra();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,u=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(u=n()),c=t.getOptions(c);const d=t.getImageWidth(o.modules.size,c),h=u.getContext("2d"),p=h.createImageData(d,d);return t.qrToImageData(p.data,o,c),r(h,u,d),h.putImageData(p,0,0),u},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const u=e.render(o,s,c),d=c.type||"image/png",h=c.rendererOpts||{};return u.toDataURL(d,h.quality)}})(Tn)),Tn}var Ln={},Ko;function Vf(){if(Ko)return Ln;Ko=1;const e=ra();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,u=!1,d=0;for(let h=0;h<i.length;h++){const p=Math.floor(h%o),f=Math.floor(h/o);!p&&!u&&(u=!0),i[h]?(d++,h>0&&p>0&&i[h-1]||(a+=u?r("M",p+s,.5+f+s):r("m",c,0),c=0,u=!1),p+1<o&&i[h+1]||(a+=r("h",d),d=0)):c++}return a}return Ln.render=function(o,s,a){const c=e.getOptions(s),u=o.modules.size,d=o.modules.data,h=u+c.margin*2,p=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",f="<path "+t(c.color.dark,"stroke")+' d="'+n(d,u,c.margin)+'"/>',_='viewBox="0 0 '+h+" "+h+'"',I='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+_+' shape-rendering="crispEdges">'+p+f+`</svg>
12
- `;return typeof a=="function"&&a(null,I),I},Ln}var Yo;function qf(){if(Yo)return Ye;Yo=1;const e=If(),t=Bf(),r=Ff(),n=Vf();function i(o,s,a,c,u){const d=[].slice.call(arguments,1),h=d.length,p=typeof d[h-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(u=a,a=s,s=c=void 0):h===3&&(s.getContext&&typeof u>"u"?(u=c,c=void 0):(u=c,c=a,a=s,s=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=s,s=c=void 0):h===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(f,_){try{const b=t.create(a,c);f(o(b,s,c))}catch(b){_(b)}})}try{const f=t.create(a,c);u(null,o(f,s,c))}catch(f){u(f)}}return Ye.create=t.create,Ye.toCanvas=i.bind(null,r.render),Ye.toDataURL=i.bind(null,r.renderToDataURL),Ye.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Ye}var $f=qf();const Dt=500,jf=new Set(["authorization","cookie","proxy-authorization","set-cookie","token","x-pkey","api-key","apikey","x-api-key","x-auth-token","x-access-token","session","session-id","jwt","refresh-token","x-csrf-token"]),zf=/(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;function Qo(e){if(!e)return e;try{const t=new URL(e);if(t.username="",t.password="",Xo(t.searchParams),t.hash&&t.hash.length>1){const r=t.hash.slice(1);if(r.includes("=")){const n=new URLSearchParams(r);Xo(n)&&(t.hash=n.toString())}}return t.toString()}catch{return ia(e)}}function Gf(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Wf(t)?"[redacted]":r])):{}}function Fn(e){if(e!==void 0){if(typeof e=="string")return na(e);if(typeof e=="number"||typeof e=="boolean"||e===null)return e;try{const t=Vn(e),r=JSON.stringify(t);return r===void 0?"[unserializable]":r.length<=Dt?t:li(r,Dt)}catch{return"[unserializable]"}}}function yt(e){return Array.isArray(e)?e.slice(0,20).map(t=>yt(t)):typeof e=="string"?Kf(e)?Qo(e):na(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?e:qn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>{const n=t.trim().toLowerCase();return ot(t)?[t,"[redacted]"]:n==="headers"&&qn(r)?[t,Gf(Object.fromEntries(Object.entries(r).flatMap(([i,o])=>typeof o=="string"?[[i,o]]:[])))]:(n==="url"||n.endsWith("_url")||n.endsWith("url"))&&typeof r=="string"?[t,Qo(r)]:[t,yt(r)]})):Fn(e)}function Wf(e){const t=e.trim().toLowerCase();return jf.has(t)||ot(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ot(e){return zf.test(e.trim())}function na(e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return Fn(JSON.parse(t))}catch{}if(t.includes("=")&&!t.includes(`
13
- `)&&t.length<=Dt*2)try{const r=new URLSearchParams(t);if([...r.keys()].length>0){const n=Object.fromEntries([...r.entries()].map(([i,o])=>[i,ot(i)?"[redacted]":o]));return Fn(n)}}catch{}return li(ia(e),Dt)}function Vn(e){return Array.isArray(e)?e.slice(0,20).map(t=>Vn(t)):qn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ot(t)?"[redacted]":Vn(r)])):typeof e=="string"?li(e,Dt):e}function Xo(e){let t=!1;for(const r of[...e.keys()])ot(r)&&(e.set(r,"[redacted]"),t=!0);return t}function ia(e){return e.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g,(t,r,n,i)=>ot(n)?`${r}${n}=[redacted]`:t)}function Kf(e){return/^https?:\/\//i.test(e.trim())||/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function li(e,t){return e.length<=t?e:`${e.slice(0,t)}…(truncated, total=${e.length})`}function qn(e){return Object.prototype.toString.call(e)==="[object Object]"}const Yf="/__hb_sdk__/dev-context";function Qf(e){if(!Jo(e)||!Zo(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Jo(t)||!Zo(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Xf={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Jf(e){const t=Nt(e.runtimePermissions),r=t.permissions["network.request"];return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:em()}function oa(e){return{schema_version:1,entries:[{key:"network.request",status:e.networkRequest.status,config:{useOfficialDomain:e.networkRequest.useOfficialDomain}}]}}function Zf(e){return oa({networkRequest:{status:e.networkRequest.status,useOfficialDomain:!1}})}function em(){return{networkRequest:{...Xf.networkRequest}}}function Jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Zo(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function tm(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let u;try{u=await e.fetch(c.signal)}catch(h){a={ok:!1},!n&&!c.signal.aborted&&s(h);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let d;try{d=e.apply(u)}catch(h){a={ok:!1},n||s(h);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(d))try{await e.onChanged(d)}catch(h){a={ok:!1},n||s(h)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function rm(e){return tm({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function nm(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const im={identity:"小程序身份",profile:"昵称和头像"};function om(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
14
- <div class="hb-sdk-auth-dialog__panel">
15
- <h2>授权请求</h2>
16
- <p class="hb-sdk-auth-dialog__app">${Cn(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
17
- <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${Cn(im[a]||a)}</li>`).join("")}</ul>
18
- ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Cn(e.userProfile.nickname)}</p>`:""}
19
- <div class="hb-sdk-auth-dialog__actions">
20
- <button type="button" data-action="deny">拒绝</button>
21
- <button type="button" class="primary" data-action="allow">允许</button>
22
- </div>
23
- </div>
24
- `;const i=a=>{s(),t(a)},o=()=>{s(),r(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),n.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}function Cn(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function sm(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",releaseChannel:"development"},runtimePermissions:e.runtimePermissions,...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const es="hb-sdk-action-dialog-style";function hi(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}um();const n=document.createElement("div");n.className="hb-sdk-action-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
25
- <div class="hb-sdk-action-dialog__panel">
26
- <h2>${ts(e.title)}</h2>
27
- <pre class="hb-sdk-action-dialog__detail">${ts(e.detail)}</pre>
28
- <div class="hb-sdk-action-dialog__actions">
29
- <button type="button" class="primary" data-action="confirm">确定</button>
30
- </div>
31
- </div>
32
- `;const i=()=>{s(),t()},o=()=>{s(),r(e.signal?.reason)},s=()=>{e.signal?.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="confirm"]')?.addEventListener("click",i),e.signal?.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}async function am(e,t){await hi({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Tt(e.params)].join(`
33
- `),signal:t.signal})}async function cm(e,t){await hi({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Tt(e.channel),"post: "+Tt(e.post)].join(`
34
- `),signal:t.signal})}async function dm(e,t){await hi({title:"截图分享",detail:["rect: "+Tt(e.rect),"post: "+Tt(e.post)].join(`
35
- `),signal:t.signal})}function Tt(e){return JSON.stringify(e,null,2)}function ts(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function um(){if(document.getElementById(es))return;const e=document.createElement("style");e.id=es,e.textContent=`
36
- .hb-sdk-action-dialog {
37
- position: absolute;
38
- inset: 0;
39
- z-index: 40;
40
- display: grid;
41
- place-items: center;
42
- padding: 24px;
43
- background: rgba(15, 23, 42, 0.45);
44
- }
45
-
46
- .hb-sdk-action-dialog__panel {
47
- width: min(420px, 100%);
48
- border-radius: 12px;
49
- padding: 20px;
50
- background: #fff;
51
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
52
- }
53
-
54
- .hb-sdk-action-dialog__panel h2 {
55
- margin: 0 0 8px;
56
- font-size: 18px;
57
- }
58
-
59
- .hb-sdk-action-dialog__detail {
60
- margin: 0 0 16px;
61
- max-height: 40vh;
62
- overflow: auto;
63
- color: #1f2933;
64
- font-family: inherit;
65
- font-size: 12px;
66
- line-height: 1.6;
67
- white-space: pre-wrap;
68
- overflow-wrap: anywhere;
69
- word-break: break-word;
70
- }
71
-
72
- .hb-sdk-action-dialog__actions {
73
- display: flex;
74
- justify-content: flex-end;
75
- gap: 8px;
76
- }
77
-
78
- .hb-sdk-action-dialog__actions button {
79
- min-height: 36px;
80
- border: 1px solid #cad5e2;
81
- border-radius: 6px;
82
- padding: 0 12px;
83
- background: #fff;
84
- cursor: pointer;
85
- }
86
-
87
- .hb-sdk-action-dialog__actions .primary {
88
- border-color: #2563eb;
89
- color: #fff;
90
- background: #2563eb;
91
- }
92
- `,document.head.appendChild(e)}function lm(e){return{close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>{const t=e.getDeviceMetrics?.();return t?{windowWidth:t.screenWidth,windowHeight:t.screenHeight,screenWidth:t.screenWidth,screenHeight:t.screenHeight,pixelRatio:t.pixelRatio,safeArea:{top:t.safeAreaInsets.top,right:t.screenWidth-t.safeAreaInsets.right,bottom:t.screenHeight-t.safeAreaInsets.bottom,left:t.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}},getNavigationBarHeight:()=>e.getDeviceMetrics?.().statusBarHeight??0,setNavigationBarStyle:t=>{document.documentElement.dataset.navigationBarStyle=t},setClipboard:async({text:t})=>{await navigator.clipboard.writeText(t)},showToast:async({message:t,status:r})=>{e.pushLog("host.message",{message:t,status:r}),await La({message:t,status:r})},showLoading:Pa,hideLoading:Ta,vibrate:Da,openAppPage:am,showShareMenu:cm,captureAndShare:dm,setScreenshotChromeHidden:va}}const hm=/^[A-Za-z0-9_-]{22}$/,fm="https://api.xiaoheihe.cn/open_inapp/";function mm(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!hm.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function gm(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${fm}#${r}`}const $n=1,rs=64*1024,pm=64,ym=/^[A-Za-z0-9_-]{22}$/;class te extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function wm(e,t=!1){const r=bm(e,t);switch(jn(r,"Server message"),_m(r),r.type){case"grant":return wt(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Et(r.connectionEpoch,"connectionEpoch"),Ne(r.nextClientSequence,"nextClientSequence"),Ne(r.nextServerSequence,"nextServerSequence"),ns(r.snapshot),r;case"event":return wt(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Et(r.connectionEpoch,"connectionEpoch"),Ne(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ce("event must be account.changed or status.changed"),ns(r.snapshot),r;case"heartbeat":return wt(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Et(r.connectionEpoch,"connectionEpoch"),Ne(r.sequence,"sequence"),r;default:return Ce("Unknown server message type")}}function Em(e){const t=e.connectionEpoch;Et(t,"connectionEpoch"),Ne(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Et(n.connectionEpoch,"connectionEpoch"),Ne(n.sequence,"sequence"),n.connectionEpoch!==t)throw new te("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new te("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new te("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function bm(e,t){if(t)throw new te("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new te("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>rs)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>rs)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return Im(e),JSON.parse(e)}catch(r){throw r instanceof te?r:new te("INVALID_JSON","Channel frame must contain strict JSON")}}function ns(e){jn(e,"snapshot"),wt(e,["account","permissions"],"snapshot"),jn(e.account,"snapshot.account"),wt(e.account,["revision"],"snapshot.account"),Ne(e.account.revision,"snapshot.account.revision"),Qf(e.permissions)||Ce("snapshot.permissions is invalid")}function _m(e){e.version!==$n&&Ce("version must be 1")}function jn(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ce(`${t} must be a plain JSON object`)}function wt(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&Ce(`${r} fields are invalid`)}function Ne(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ce(`${t} must be a non-negative safe integer`)}function Et(e,t){(typeof e!="string"||!ym.test(e))&&Ce(`${t} must be a 22-character base64url value`)}function Ce(e){throw new te("INVALID_MESSAGE",e)}function Im(e){new Am(e).scan()}class Am{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=pm)throw new te("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new te("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const is=[1e3,2e3,4e3,8e3,15e3];function Sm(e){const t=new Set,r=e.webSocketFactory??(w=>new WebSocket(w)),n=e.randomValues??(w=>crypto.getRandomValues(w)),i=e.timers??{clearTimeout:w=>window.clearTimeout(w),setTimeout:(w,D)=>window.setTimeout(w,D)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,u,d,h=!1,p=0,f,_=!1,b=!1;const I=new Set,y=(w,D)=>{if(!(!e.onDiagnostic||I.has(w))){I.add(w);try{e.onDiagnostic({phase:w,...D?{code:D}:{}})}catch{}}},A=(w,D,m=!1)=>{if(d&&w.account.revision<d.account.revision)return;const g=d&&JSON.stringify(w)===JSON.stringify(d);if(d=w,!(g&&!m))for(const E of t)E(w,D)},R=()=>{if(h||f!==void 0||c)return;const w=is[Math.min(p,is.length-1)];p+=1,f=i.setTimeout(()=>{f=void 0,S()},w)},P=()=>{h||!_||c||(f!==void 0&&(i.clearTimeout(f),f=void 0),S())},H=()=>{a()&&P()},v=()=>{s&&!s.hidden&&P()},O=()=>{b||(b=!0,o?.addEventListener("online",H),s?.addEventListener("visibilitychange",v))},C=()=>{b&&(b=!1,o?.removeEventListener("online",H),s?.removeEventListener("visibilitychange",v))},S=()=>{if(h||c)return;_=!0,O(),f!==void 0&&(i.clearTimeout(f),f=void 0);let w,D;try{w=r(e.url)}catch{y("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),R();return}try{D=vm(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{w?.close(1011,"channel initialization failed")}catch{}R();return}c=w;let m,g,E;const T=()=>{w.removeEventListener("open",F),w.removeEventListener("message",V),w.removeEventListener("close",Z),w.removeEventListener("error",se),u===T&&(u=void 0)},N=()=>{if(c===w){c=void 0,T();try{w.close(1008,"invalid channel state")}catch{}R()}},F=()=>{if(!(h||c!==w))try{w.send(JSON.stringify({version:$n,type:"hello",csrfToken:e.csrfToken,clientNonce:D}))}catch{y("send","HELLO_SEND_FAILED"),N()}},V=J=>{if(h||c!==w)return;if(typeof J.data!="string"){y("parse","TEXT_FRAME_REQUIRED"),N();return}let z;try{z=wm(J.data)}catch(ye){y("parse",ye instanceof te?ye.code:"INVALID_MESSAGE"),N();return}if(z.type==="grant"){if(E){y("sequence","DUPLICATE_GRANT"),N();return}m=z.connectionEpoch,g=z.nextClientSequence,E=Em({connectionEpoch:m,nextSequence:z.nextServerSequence}),p=0,I.clear(),A(z.snapshot,{type:"grant"});return}if(!E||!m||g===void 0){y("sequence","MESSAGE_BEFORE_GRANT"),N();return}try{E.accept(z)}catch{y("sequence","INVALID_SEQUENCE"),N();return}if(z.type==="heartbeat"){try{w.send(JSON.stringify({version:$n,type:"heartbeat.ack",connectionEpoch:m,sequence:g}))}catch{y("send","HEARTBEAT_ACK_SEND_FAILED"),N()}g=g===Number.MAX_SAFE_INTEGER?void 0:g+1;return}A(z.snapshot,{type:"event",event:z.event},!0)},Z=()=>{c===w&&(y("close","SOCKET_CLOSED"),c=void 0,T(),R())},se=()=>{y("open","SOCKET_ERROR"),N()};w.addEventListener("open",F),w.addEventListener("message",V),w.addEventListener("close",Z),w.addEventListener("error",se),u=T};return{connect:S,subscribeUpdates(w){return t.add(w),()=>t.delete(w)},dispose(){if(h)return;h=!0,_=!1,C(),f!==void 0&&i.clearTimeout(f),f=void 0;const w=c;c=void 0,u?.(),w?.close(1e3,"client disposed"),t.clear()}}}function Rm(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function vm(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=Rm(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}const Dm="/__hb_sdk_bootstrap__",Tm="/__hb_sdk__/mobile-launch-redirect",Pm="/__hb_sdk__/network",Lm="/session/status",Cm="/session/request",Om="/session/events",Nm=320,km=1e3,Mm=1e3,Um=15e3,sa=new URL(location.href).searchParams,aa=sa.get("mini_url"),Vr=sa.get("ui_preview")==="1",x={device:lt("#device"),get mobileLanSelect(){return lt("#mobile-lan-select")},get mobileQrImage(){return lt("#mobile-qr-image")},get mobileQrStatus(){return lt("#mobile-qr-status")},storageSnapshot:lt("#storage-snapshot")};if(!aa&&!Vr)throw x.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Hm=aa??"about:blank",de=await mi();let Se=de.lanAddresses,Yt=de.defaultLanAddressId,Xe=de.mobileLaunchRedirect,ca=pi(de),Qt=de.devContext,Pt=Jf(Qt),B=!1,qr=0;const fi=new AbortController;let Ue=0,et,Lt,Xt=0,He,zn,Gn,Re=0,Ct=!1,Jt,Ze,On=!1,os=Promise.resolve(),bt=-1,Ot=!1,xe,Wn,Kn,Zt,Oe;const Ur=new Set,nt=rm({applyStatus:e=>fa(e,!0),fetchStatus:e=>ha(Ia(fi.signal,e)),getCanonicalRevision:()=>bt,onError:og,reconcile:()=>Gm(qr)}),Yn=nm({connectEvents:ma,invalidate:()=>nt.invalidate(),isDisposed:()=>B,maxDelayMs:Um,minDelayMs:Mm,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});await Qn(!1);Ea();_a(ba(de));Vr&&Fm();$r();await xt("initial");Vr||(ma(),jm());xm();function xm(){window.addEventListener("beforeunload",sg),window.addEventListener("hb-sdk:restart-runtime",ua),window.addEventListener("hb-sdk:refresh-storage",$r),window.addEventListener("hb-sdk:qr-open-change",da)}function da(e){const t=e.detail?.open===!0;t!==Ct&&(Ct=t,Re+=1,jr(),Ze!==void 0&&window.clearInterval(Ze),Ze=void 0,t&&(x.mobileLanSelect.addEventListener("change",Bm),pa(),Bt(),de.devContext.source==="remote"&&(Ze=window.setInterval(()=>{rg()},km))))}function Bm(){Ct&&Bt()}function ua(){la("manual restart")}function la(e){B||et!==void 0||(re("runtime.restart",{boundary:Ue+1}),et=window.setTimeout(()=>{et=void 0,B||xt(e)},0))}async function xt(e){const t=++Ue;if(Lt=void 0,ga(e),X.runtimeStatus="loading",Ra(Pt),x.device.replaceChildren(),Vr){x.device.innerHTML=`
93
- <div class="browser-mock-preview">
94
- <span class="browser-mock-preview__icon">UI</span>
95
- <strong>Browser Mock</strong>
96
- <small>mp_preview</small>
97
- </div>`,X.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",x.device.appendChild(r);const n=new AbortController;zn=n;try{const i=await bf(Vm(n.signal,t));if(B||t!==Ue){i.dispose();return}Gn=i.dispose;const o=of({iframe:r,ports:i.ports,environment:i.environment,hostCapabilities:i.hostCapabilities,authPresentation:i.authPresentation,resolveLaunchConfiguration:async()=>(await i.resolveLaunch()).configuration,dispose:i.dispose,onReady:()=>{X.runtimeStatus="ready",re("runtime.ready",{generation:t})},onStateChange:s=>{re("runtime.state",{generation:t,state:s})},onTrace:s=>qm(t,s),onError:s=>{X.runtimeStatus="error",re("runtime.error",yt(s))},onSecurityViolation:s=>re("runtime.security",yt(s)),onCapabilityTrace:s=>{re(s.method,s),s.method==="storage.setStorage"&&s.outcome==="success"&&$r()}});He=o,await o.start()}catch(i){if(B||t!==Ue||n.signal.aborted)return;X.runtimeStatus="error",re("runtime.start.failed",yt(i))}}function Fm(){re("runtime.ready",{generation:1}),re("user.getInfo",{durationMs:34,outcome:"success"}),re("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function Vm(e,t){return{signal:e,account:{async getCurrentUserId(){return(await Qn(!1,e)).user_id},async ensureAuthenticated({signal:r}){await Qn(!1,r)},onChange(r){return Ur.add(r),()=>Ur.delete(r)}},authenticatedRequest:$m,storage:{area:"local",storage:localStorage},presentation:lm({close:async()=>{ss(),He?.destroy(),X.runtimeStatus="closed"},reload:()=>{!B&&t===Ue&&(Lt=t)},pushLog:re,getDeviceMetrics:()=>Oa.value}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:r=>{document.title=r}},resolveLaunch:async()=>({configuration:sm({launchUrl:Hm,runtimePermissions:oa(Pt),...Qt.miniProgramId?{miniProgramId:Qt.miniProgramId}:{}}),hostHints:{launchKind:Qt.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:r=>om(r)}}}function qm(e,t){t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Lt!==e||e!==Ue||(Lt=void 0,la("navigation.reload"))}async function $m(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&(e.source==="public-sdk"?e.withCredentials!==!0:e.credentials==="omit")&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 未提供 public origin-session 请求闭包");const i=await gi(n?Pm:Cm,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&nt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Qn(e,t){const r=qr,n=await ha(Ia(fi.signal,t));return Aa(r)?fa(n,e).status:Xn()}async function ha(e){return await(await fetch(Lm,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function fa(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<bt)return{changed:!1,status:Xn()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?G(e.nickname):void 0,i=e.authenticated?G(e.avatar):void 0,o=e.revision!==bt||e.authenticated!==Ot||r!==xe||n!==Wn||i!==Kn;return bt=e.revision,Ot=e.authenticated,xe=r,Wn=n,Kn=i,Ea(),t&&o&&Ur.forEach(s=>s(xe)),{changed:o,status:Xn()}}function Xn(){return{authenticated:Ot,revision:bt,...Ot&&xe?{user_id:xe}:{}}}function jm(){if(!(!de.csrfToken||B))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Oe=Sm({csrfToken:de.csrfToken,onDiagnostic:t=>re("channel.diagnostic",t),url:e.toString()}),Oe.subscribeUpdates((t,r)=>zm(t,r)),Oe.connect()}catch{Oe?.dispose(),Oe=void 0}}function zm(e,t){nt.invalidate(e.account.revision),dg(Pt,e.permissions)?t.type==="event"&&t.event==="status.changed"&&xt("status changed"):(Pt=Ra(e.permissions),Wm())}function ma(){if(Zt?.close(),Zt=void 0,!xe||B)return;const e=new EventSource(Om,{withCredentials:!0});Zt=e,e.addEventListener("account-invalidated",()=>{nt.invalidate()}),e.addEventListener("account-revision",()=>{nt.invalidate()}),e.onopen=()=>{Yn.reset()},e.onerror=()=>{e.close(),Yn.schedule()}}async function Gm(e){Aa(e)&&await xt("account revision changed")}function ga(e){Xt+=1,ss(),He?.destroy(),He=void 0,zn?.abort(new DOMException(e,"AbortError")),zn=void 0,Gn?.(),Gn=void 0}async function Wm(){B||(await xt("permission changed"),!B&&await Bt())}async function mi(){const e=await fetch(Dm,{cache:"no-store",credentials:"same-origin",redirect:"error"});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!je(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Sa(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new it;return{csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devContext:Km(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(cg):[],loginAvailable:t.loginAvailable===!0,miniProgram:ng(t.miniProgram),mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0}}function Km(e,t){return je(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,warning:typeof e.warning=="string"?e.warning:void 0}:{source:"anonymous",runtimePermissions:t}}async function gi(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),de.csrfToken&&r.set("x-hb-sdk-csrf",de.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function pa(e=x.mobileLanSelect.options.length>0?x.mobileLanSelect.value:void 0){x.mobileLanSelect.replaceChildren();for(const t of Se){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,x.mobileLanSelect.appendChild(r)}e&&Se.some(({id:t})=>t===e)?x.mobileLanSelect.value=e:Yt&&Se.some(({id:t})=>t===Yt)?x.mobileLanSelect.value=Yt:Se[0]&&(x.mobileLanSelect.value=Se[0].id),x.mobileLanSelect.disabled=Se.length===0}async function Bt(){if(B)return;const e=++Re;jr();const t=ag();if(!t?.mobileAppQrPayload){x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="未发现可用的局域网地址";return}x.mobileQrStatus.textContent="正在生成二维码...";try{const r=await Zm(t);if(e!==Re||B)return;const n=await Ym(r.address,r.expiresAt);if(e!==Re||B)return;const i=await $f.toDataURL(n.payload,{width:Nm,margin:1});if(e!==Re||B)return;x.mobileQrImage.src=i,x.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,tg(n.expiresAt,e)}catch(r){if(e!==Re||B)return;if(r instanceof it){wa();return}x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent=yi(r)}}async function Ym(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await Qm(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:gm(mm({host:e.address,port:location.port,token:n.token}))}}catch{throw new it}}async function Qm(e,t){if(Xe?.addressId===e.id)return Xe;if(!Xe)return;const r=await gi(Tm,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Xe.token})});if(!r.ok)throw new it;const n=await r.json(),i=je(n)?Sa({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new it;return Xe=i,i}async function Xm(e){const t=await mi(),r=Jm(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return ya(t),{...r,mobileAppQrPayload:n}}function Jm(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function ya(e){ca=pi(e),Se=e.lanAddresses,Yt=e.defaultLanAddressId,Xe=e.mobileLaunchRedirect,_a(ba(e)),pa()}class it extends Error{}async function Zm(e){const t=os.then(()=>eg(e));return os=t.then(()=>{},()=>{}),t}async function eg(e){const t=new URL(e.appUrl),r=new URL(Yf,location.origin),n=await gi(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:Zf(Pt)})}),i=await n.json();if(!n.ok||!je(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await Xm(e.id),expiresAt:i.expires_at}}function tg(e,t){Jt=window.setTimeout(()=>{!B&&Ct&&t===Re&&Bt()},Math.max(1e3,e-Date.now()-3e4))}async function rg(){if(!(On||B)){On=!0;try{const e=await mi();if(pi(e)===ca)return;ya(e),Ct&&Bt()}catch(e){e instanceof it&&wa()}finally{On=!1}}}function wa(){Re+=1,jr(),x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="Mobile 短链接配置无效"}function pi(e){return JSON.stringify({defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason})}function Ea(){if(!Ot){X.account={authenticated:!1,avatar:"",nickname:"未登录"};return}X.account={authenticated:!0,avatar:Kn??"",nickname:Wn||xe||"已登录"}}function ba(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function _a(e){if(!!!e?.miniProgramId||!e){X.miniProgram={bound:!1,iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}X.miniProgram={bound:!0,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function ng(e){if(e===null)return null;if(!je(e))return;const t=G(e.miniProgramId)??G(e.mini_program_id);if(t)return{miniProgramId:t,...G(e.name)?{name:G(e.name)}:{},...G(e.iconUrl)??G(e.icon_url)?{iconUrl:G(e.iconUrl)??G(e.icon_url)}:{},...G(e.status)?{status:G(e.status)}:{},...G(e.version)?{version:G(e.version)}:{},...G(e.developerName)??G(e.developer_name)?{developerName:G(e.developerName)??G(e.developer_name)}:{}}}function G(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function $r(){const e=++Xt,t=He,r=t?.diagnostics.storage;if(!r){X.storage=[],X.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(B||e!==Xt||t!==He)return;X.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),X.storageError=""}catch(n){if(B||e!==Xt||t!==He)return;X.storage=[],X.storageError=yi(n)}}function ig(e,t){re("host.message",{message:e,status:t})}function og(e){B||ig(yi(e),"error")}function re(e,t){Ca(e,t)}function sg(){B||(B=!0,window.removeEventListener("hb-sdk:restart-runtime",ua),window.removeEventListener("hb-sdk:refresh-storage",$r),window.removeEventListener("hb-sdk:qr-open-change",da),qr+=1,fi.abort(new DOMException("Browser Dev Host disposed","AbortError")),nt.dispose(),Ue+=1,ga("Browser Dev Host disposed"),Zt?.close(),Oe?.dispose(),Oe=void 0,Yn.dispose(),Lt=void 0,et!==void 0&&window.clearTimeout(et),et=void 0,jr(),Ze!==void 0&&window.clearInterval(Ze),Ur.clear())}function jr(){Jt!==void 0&&window.clearTimeout(Jt),Jt=void 0}function Ia(e,t){return t?AbortSignal.any([e,t]):e}function Aa(e){return!B&&e===qr}function ag(){return Se.find(({id:e})=>e===x.mobileLanSelect.value)}function cg(e){return je(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function Sa(e){if(!(!je(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function Ra(e){return{networkRequest:{...e.networkRequest}}}function dg(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function yi(e){return e instanceof Error&&e.message?e.message:"操作失败"}function je(e){return Object.prototype.toString.call(e)==="[object Object]"}function lt(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}