@heybox/hb-sdk 0.8.0 → 0.8.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +19 -0
- package/dist/cli-chunks/{build-PYCNacya.cjs → build-FQoALfGC.cjs} +5 -5
- package/dist/cli-chunks/{context-m2W2XbL0.cjs → context-CA_Q1lyH.cjs} +2 -2
- package/dist/cli-chunks/{create-BdAg3WGA.cjs → create-BjIl4hy4.cjs} +1 -1
- package/dist/cli-chunks/{dev-CyZuw7Yn.cjs → dev-CiPQYsW_.cjs} +9 -9
- package/dist/cli-chunks/{doctor-DU8rCfUF.cjs → doctor-CS6c3n-W.cjs} +1 -1
- package/dist/cli-chunks/{index-MMW2ibQm.cjs → index-BEn7WaqA.cjs} +15 -15
- package/dist/cli-chunks/{index-DATObqzK.cjs → index-CsP_x6y6.cjs} +2 -2
- package/dist/cli-chunks/{index.esm-BiAaAUFC.cjs → index.esm-DeEc_-uV.cjs} +7 -7
- package/dist/cli-chunks/{login-B3TThMss.cjs → login-BENCVgaQ.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-BQj8YLI4.cjs → project-vite-BO8oOfcs.cjs} +1 -1
- package/dist/cli-chunks/{remote-DNvI7tHH.cjs → remote-IiVCXcSq.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-BEFp1w_s.cjs → runtime-gate-BMSY22AL.cjs} +1 -1
- package/dist/cli-chunks/{runtime-permission-env-CtL8rsjB.cjs → runtime-permission-env-BPRwn4Yc.cjs} +1 -1
- package/dist/cli-chunks/{session-DjBkjaF8.cjs → session-C0eIKZ6V.cjs} +1 -1
- package/dist/cli-chunks/{skill-cR_wnaw2.cjs → skill-DpInwbiA.cjs} +2 -2
- package/dist/cli-chunks/{version-yEn1E2Bg.cjs → version-BONZQWPR.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-DzEst9n7.js +99 -0
- package/dist/devtools/browser-dev-host/assets/{index-C5MZZDa5.js → index-B-NHlLsr.js} +2 -2
- package/dist/devtools/browser-dev-host/index.html +1 -1
- package/dist/index.cjs.js +83 -2
- package/dist/index.esm.js +83 -3
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/package.json +8 -10
- package/skill/SKILL.md +3 -0
- package/skill/references/api-protocol.md +7 -3
- package/skill/references/api-root.md +104 -1
- package/skill/references/recipes.md +1 -0
- package/skill/skill.json +5 -5
- package/types/core/client.d.ts +7 -1
- package/types/core/sdk.d.ts +3 -0
- package/types/core/singleton.d.ts +3 -0
- package/types/index.d.ts +3 -1
- package/types/modules/environment/index.d.ts +70 -0
- package/types/protocol.d.ts +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-TzYf9L6C.js +0 -99
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import{ah as Ta,aB as Pa,E as La,an as Ca,ao as Oa,a8 as Zn,aI as Q,ae as cs,b as Na}from"./workbench-state-BwV7bm4n.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",At="storage.getStorage",St="storage.setStorage",dr="network.request",ur="network.download",lr="files.pickFiles",hr="files.pickDirectory",fr="files.saveFile",vt="file.create",Rt="file.remove",mr="file.exists",gr="file.readText",pr="file.writeText",yr="file.readBytes",wr="file.writeBytes",Er="file.stat",br="directory.create",Dt="directory.remove",_r="directory.exists",Ir="directory.list",Ar="ui.showToast",Sr="ui.showLoading",vr="ui.hideLoading",Rr="device.vibrate",Dr="device.setClipboard",Tr="navigation.close",Pr="navigation.reload",Lr="navigation.openAppPage",_e="cloud.leaderboard.submit",ce="cloud.leaderboard.getList",Pe="cloud.leaderboard.getCurrentUserEntry",Fe="cloud.leaderboard.deleteCurrentUserEntry",fe="cloud.leaderboard.getInfo",Le=[{method:er,module:"auth",capability:er,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:tr,module:"user",capability:tr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:rr,module:"user",capability:rr,requirement:{kind:"none"},risk:"high"},{method:nr,module:"user",capability:nr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:ir,module:"share",capability:ir,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:or,module:"share",capability:or,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:sr,module:"share",capability:sr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ar,module:"viewport",capability:ar,requirement:{kind:"none"},risk:"low"},{method:cr,module:"viewport",capability:cr,requirement:{kind:"none"},risk:"low"},{method:At,module:"storage",capability:At,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:St,module:"storage",capability:St,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:dr,module:"network",capability:dr,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:ur,module:"network",capability:ur,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:lr,module:"files",capability:lr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hr,module:"files",capability:hr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fr,module:"files",capability:fr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vt,module:"file",capability:vt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Rt,module:"file",capability:Rt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mr,module:"file",capability:mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gr,module:"file",capability:gr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pr,module:"file",capability:pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"file",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:wr,module:"file",capability:wr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Er,module:"file",capability:Er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:br,module:"directory",capability:br,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dt,module:"directory",capability:Dt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"directory",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ir,module:"directory",capability:Ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ar,module:"ui",capability:Ar,requirement:{kind:"none"},risk:"low"},{method:Sr,module:"ui",capability:Sr,requirement:{kind:"none"},risk:"low"},{method:vr,module:"ui",capability:vr,requirement:{kind:"none"},risk:"low"},{method:Rr,module:"device",capability:Rr,requirement:{kind:"none"},risk:"low"},{method:Dr,module:"device",capability:Dr,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Tr,module:"navigation",capability:Tr,requirement:{kind:"none"},risk:"medium"},{method:Pr,module:"navigation",capability:Pr,requirement:{kind:"none"},risk:"medium"},{method:Lr,module:"navigation",capability:Lr,requirement:{kind:"none"},risk:"medium"},{method:_e,module:"cloud",capability:_e,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ce,module:"cloud",capability:ce,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Pe,module:"cloud",capability:Pe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Fe,module:"cloud",capability:Fe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:fe,module:"cloud",capability:fe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"}],Qe="heybox:miniprogram",ds=2,ka="hb_mini_bridge_nonce",Ma="sdk.handshake",Vt="runtime.location.probe",Ua="sdk.location.report",Ha="sdk.csp.violation",us="operation.progress";function xa(e){return!qe(e)||e.namespace!==Qe||e.version!==1&&e.version!==2||!Y(e.nonce)?!1:e.type==="handshake"?Y(e.id)&&e.method===Ma&&e.error===void 0&&Fa(e.payload):e.type==="request"?Y(e.id)&&Y(e.method)&&e.error===void 0:e.type==="response"?Y(e.id)&&(e.method===void 0||Y(e.method))&&(e.error===void 0||Va(e.error)):e.type==="event"?!Y(e.method)||e.error!==void 0?!1:e.method===us?e.version===2&&Y(e.id)&&Ba(e.payload):e.id===void 0||Y(e.id):e.type==="cancel"?e.version===2&&Y(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ei(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ls(e){return qe(e)?e.kind==="sandbox"?Ve(e,["kind"]):e.kind==="directory"&&Y(e.handleId)&&Ve(e,["kind","handleId"]):!1}function hs(e){return!qe(e)||e.kind!=="file"?!1:Y(e.handleId)?Ve(e,["kind","handleId"]):ls(e.root)&&ei(e.relativePath)&&Ve(e,["kind","root","relativePath"])}function fs(e){return!qe(e)||e.kind!=="directory"?!1:Y(e.handleId)?Ve(e,["kind","handleId"]):ls(e.root)&&ei(e.relativePath)&&Ve(e,["kind","root","relativePath"])}function Ba(e){return!qe(e)||!Ii(e.loaded)||typeof e.lengthComputable!="boolean"||!Ve(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ii(e.total)&&e.loaded<=e.total:e.total===void 0}function Fa(e){return qe(e)&&Y(e.href)&&typeof e.userAgent=="string"&&Y(e.sdkVersion)}function Va(e){return qe(e)&&Y(e.code)&&typeof e.message=="string"}function Ii(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Y(e){return typeof e=="string"&&e.length>0}function Ve(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Hr=["identity","profile"],ti=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network"];new Set(ti);const qa=new Set(ti);function $a(e){return qa.has(e)}function xr(e){if(!ct(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(!ct(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!$a(o)){if(!ct(n.config))return{valid:!1,permissions:{}};continue}if(o==="network"){const s=n.config;if(!ct(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!ct(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}return{valid:!0,permissions:r}}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Le.map(e=>e.method);function U(e,t,r){return{code:e,message:t,data:r}}function ms(e){return ja(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?U("RUNTIME_ERROR",e.message):U("UNKNOWN_ERROR","小程序运行时异常",e)}function ja(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function za(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ga=1e3;function Wa(e,t=za()){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<=Ga}const Ka="runtime.gate.probe",gs=new Set(Le.map(e=>e.method));class Ya{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ds;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:us,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=Wa(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&&xa(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===Ka){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,U("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!gs.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=ms(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})||!Qa(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 Qa(e){return typeof e=="string"&&gs.has(e)}const ps="METHOD_FORBIDDEN";function pe(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=ps,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 Ai={[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"],[At]:["storage.getRaw"],[St]:["storage.setRaw"],[dr]:["network.request"],[ur]:["network.stream","files.transfer","files.access"],[lr]:["files.external"],[hr]:["files.external"],[fr]:["files.save"],[vt]:["files.access"],[Rt]:["files.removeFile"],[mr]:["files.access"],[gr]:["files.access"],[pr]:["files.access"],[yr]:["files.access"],[wr]:["files.access"],[Er]:["files.access"],[br]:["files.access"],[Dt]:["files.removeDirectory"],[_r]:["files.access"],[Ir]:["files.access"],[Ar]:["presentation.showToast"],[Sr]:["presentation.showLoading"],[vr]:["presentation.hideLoading"],[Rr]:["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"],[Pe]:["account.getCurrentUserId","account.onChange","network.request"],[Fe]:["account.getCurrentUserId","account.onChange","network.request"],[fe]:["account.onChange","network.request"]};function Xa(e,t){if(t[e]!==!0)throw pe(e)}const Ja=32*1024*1024,Za=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function ec(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:Ja},i);return tc(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function tc(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:rc(t,ic(e,"content-type"))}}function rc(e,t){nc(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||!Za.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function nc(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 ic(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function L(e){return typeof e=="function"}function Si(e){return(...t)=>{throw pe(e)}}function K(e){return async(...t)=>{throw pe(e)}}const oc=(e,t)=>{},sc=()=>()=>{};function ac(e){const t={request:L(e.network?.request)?e.network.request.bind(e.network):K("network.request")},r={getCurrentUserId:L(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):K("account.getCurrentUserId"),ensureAuthenticated:L(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):K("account.ensureAuthenticated"),onChange:L(e.account?.onChange)?e.account.onChange.bind(e.account):sc},n={getRaw:L(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):K("storage.getRaw"),setRaw:L(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):K("storage.setRaw")},i={close:L(e.presentation?.close)?e.presentation.close.bind(e.presentation):K("presentation.close"),reload:L(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):K("presentation.reload"),openAppPage:L(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):K("presentation.openAppPage"),getViewportMetrics:L(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Si("presentation.getViewportMetrics"),getNavigationBarHeight:L(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Si("presentation.getNavigationBarHeight"),setNavigationBarStyle:L(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):K("presentation.setNavigationBarStyle"),showShareMenu:L(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):K("presentation.showShareMenu"),setScreenshotChromeHidden:L(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):oc,captureAndShare:L(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):K("presentation.captureAndShare"),showToast:L(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):K("presentation.showToast"),showLoading:L(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):K("presentation.showLoading"),hideLoading:L(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):K("presentation.hideLoading"),vibrate:L(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):K("presentation.vibrate"),setClipboard:L(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):K("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 cc(e){const t=dc(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 dc(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 vi(e,t){return t?.[e]!==!1}function uc(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")}function ys(e,t={}){const r={};for(const n of Object.keys(Ai)){const o=Ai[n].every(a=>e[a]),s=!uc(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=vi(n,t.callerCapabilities)&&vi(n,t.hostCapabilities)&&o&&s}return r}function ws(e={},t={}){const r=cc(e),n=ys(r,t);return{ports:ac(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ri(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):lc(e.signal,t);return{...e,signal:r}}function lc(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 hc(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 fc(e){return typeof e=="object"&&e!==null}function ne(e,t){const r=e.data;if(!fc(r)||typeof r.status!="string")throw new Error(t);return r}const Es={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},mc={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 Mt(e){return{mini_program_id:e.miniProgramId}}function gc(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function pc(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=gc(r.consent_challenge)),{...t,result:n}}const yc={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=>({...Mt(e.runtimeContext),challenge:e.challenge}),parse:e=>ne(e,"小程序授权取消接口响应异常")},wc={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=>Mt(e.runtimeContext),parse:e=>ne(e,"小程序授权撤销接口响应异常")},Ec={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=>Mt(e.runtimeContext),parse(e){const t=ne(e,"小程序隔离身份接口响应异常");return{...t,result:{appUserId:t.result.app_user_id}}}},bc={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=>({...Mt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>pc(e)},_c={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=>({...Mt(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}}}},Ic=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Ac=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Sc=/authorization|cookie|pkey|password|secret|token/i,bs=/authorization|cookie|pkey|token|password|secret/i;function ue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function vc(e){for(const t of Object.keys(e))if(!Ac.has(t))throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Ic)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 pt(e){if(Array.isArray(e))return e.map(pt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Sc.test(n)||(r[n]=pt(i));return r}function Ri(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))bs.test(r)||(t[r]=n);return t}function Rc(e){if(!e)return;const t=Object.keys(e).find(r=>bs.test(r));if(t)throw new q(`endpoint 禁止声明 credential-bearing header: ${t}`)}class rt 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 _s(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class nt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,_s(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Ut extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,_s(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Dc(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:pt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Ri(o),method:e.method,metadata:{endpointId:e.id},query:pt(n),timeout:e.timeout,url:r},data:pt(a.data),headers:Ri(a.headers)||{},status:a.status,statusText:a.statusText}}async function Br(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(vc(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;Rc(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 nt({endpointId:t.id,cause:d})}if(c.status<200||c.status>=300)throw new rt({endpointId:t.id,status:c.status});const u=Dc(t,r,i,o,s,a,n,c);if(t.parse)try{return await t.parse(u,r)}catch(d){throw new Ut({endpointId:t.id,cause:d})}return u.data}const Tc=new Set(Hr),Pc=1e3;function Lc(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 Li(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 Li(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 Uc(Br(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 Ut?l("INVALID_RESPONSE","授权接口响应不合法"):T instanceof nt?l("REQUEST_FAILED","授权请求失败"):T instanceof rt?l("REQUEST_FAILED",T.message):Is(T)?T:l("REQUEST_FAILED","授权请求失败")}}async function A(m,g){await y(yc,{runtimeContext:{miniProgramId:m},challenge:g}).catch(()=>{})}function v(m){const g=async()=>{const T=Ti(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 v(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),Cc("REQUEST_FAILED","授权确认界面执行失败",J))}if(await b(T,N),Z.status!=="granted")throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const se=kc(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=Ti(E),N=setTimeout(()=>T.abort(),Pc);try{const F=Mc(e.miniProgramPresentation),[V,Z]=await Promise.all([F?Promise.resolve(F):R(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 R(m,g){try{const E=e.identity.get()?.version?.trim(),T=await y(mc,{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(Es,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(bc,{runtimeContext:{miniProgramId:E},scopes:m});await b(T,N);const V=Ge(F,"小程序登录"),Z=Pi(V,"loginCode"),se=Pi(V,"consentChallenge");if(Z===se)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let J;if(Z)J=Di(V.loginCode);else{const z=Oc(V.consentChallenge),ye=await P(E,z,g,T,N);await b(T,N);const Gr=await y(_c,{runtimeContext:{miniProgramId:E},challenge:z.challenge,selectedScopes:ye});if(await b(T,N),J=Di(Ge(Gr,"小程序登录确认")),J.scopes.some(at=>!ye.includes(at)))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(Ec,{runtimeContext:{miniProgramId:g}});await b(m,E);const N=Nc(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(wc,{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 Cc(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 Di(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 Oc(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 Nc(e){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");return{appUserId:e.appUserId.trim()}}function kc(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 Mc(e){const t=Je(e?.name),r=Je(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ti(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 Uc(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"||!Tc.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 Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Is(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Li(e,t,r){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Is(e)?e:l("REQUEST_FAILED",r)}const Hc=new Set(Hr);function xc(e){return{[er]:async(t,r)=>e.authorization.login(Bc(t),r.trustedUserGesture)}}function Bc(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw Ci();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Hc.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Ci();return[...e.scopes]}function Ci(){return l("INVALID_PARAMS","auth.login 参数不合法")}const Fc={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,"排行榜记录删除接口响应异常")}},Vc={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,"当前排行榜记录接口响应异常")}},qc={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,"排行榜信息接口响应异常")}},$c={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,"排行榜列表接口响应异常")}},jc={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 Kt(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Oi(e){return e instanceof q?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function W(e){if(e.aborted)throw Kt()}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Kt());let n;try{n=e()}catch(i){return Promise.reject(Oi(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Kt())):new Promise((i,o)=>{let s=!1;const a=u=>{s||(s=!0,t.removeEventListener("abort",c),u())},c=()=>a(()=>o(Kt()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(u=>a(()=>i(u)),u=>a(()=>o(Oi(u))))})}const zc="default",Gc=/^[A-Za-z0-9_-]{1,64}$/,Wc=300*1e3,Kc=250,Yc=3,Qc={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 Xc{constructor(t){this.options=t,this.unsubscribeAccountChange=Zc(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(jc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(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=ut("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request($c,{miniProgramId:r,...t}),s=dt(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=ut("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Vc,{miniProgramId:n,...t}),c=dt(a,Pe);if(!me(c))throw j(`${Pe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Yr(c.entry,Pe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Fc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(i,Fe);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!me(o)||typeof o.deleted!="boolean")throw j(`${Fe} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",ut("info"),async()=>{const i=await this.request(qc,{miniProgramId:r,...t}),o=dt(i,fe);if(!me(o)||typeof o.key!="string"||!Gc.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=ut(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>=Kc&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Wc,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>=Yc)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)ki(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ki(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 Ui(n)?n:Mi()}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 ut(t,r??zc)}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 $(()=>Br(n,t,r,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw Ui(i)||kn(i,"REQUEST_UNSUPPORTED")?i:i instanceof q?ae("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof nt&&kn(i.cause,"INVALID_STATE")?i.cause:i instanceof rt&&(i.status===401||i.status===403)?ae("UNAUTHORIZED","当前用户未登录"):i instanceof nt||i instanceof rt?Mi():i instanceof Ut?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 Jc(e){return new Xc(e)}function Zc(e,t){try{return e.onChange(t)}catch(r){if(kn(r,ps))return()=>{};throw r}}function dt(e,t){if(!me(e)||typeof e.status!="string")throw j(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw ed(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 ed(e){if(e.status==="login"||e.status==="relogin")throw ae("UNAUTHORIZED",mt(e.msg)||"当前用户未登录");const t=Ni(e.result)??Ni(e),r=mt(t?.user_message)||mt(e.msg)||mt(t?.developer_message)||"排行榜请求失败";throw t?ae(td(t),r,{status:e.status,sbe:t}):ae("HEYBOX_API_ERROR",r,{status:e.status})}function Ni(e){return me(e)&&me(e.sbe)?e.sbe:void 0}function td(e){const t=mt(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 Qc[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 ki(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function ut(...e){return JSON.stringify(e)}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mt(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 Mi(){return ae("REQUEST_FAILED","排行榜请求失败")}function Ui(e){return e instanceof Error&&e.name==="AbortError"}const rd=/^[A-Za-z0-9_-]{1,64}$/,Hi=20,nd=100,xi=2048;function id(e){const t=Jc(e);return{handlers:{[_e]:async n=>t.submit(od(n)),[ce]:async n=>t.getList(sd(n)),[Pe]:async n=>t.getCurrentUserEntry(Qr(n,Pe)),[Fe]:async n=>t.deleteCurrentUserEntry(Qr(n,Fe)),[fe]:async n=>t.getInfo(Qr(n,fe))},dispose:()=>t.dispose()}}function od(e){const t=ni(e,_e,!1);if(ii(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{...oi(t.key,_e),score:t.score,...t.extra===void 0?{}:{extra:ad(t.extra)}}}function sd(e){if(e===void 0)return{limit:Hi};const t=ni(e,ce,!0);ii(t,["key","limit","cursor"],ce);const r=t.limit===void 0?Hi:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>nd)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{...oi(t.key,ce),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Qr(e,t){if(e===void 0)return{};const r=ni(e,t,!0);return ii(r,["key"],t),oi(r.key,t)}function ni(e,t,r){if(e===void 0&&r)return{};if(!As(e))throw ge("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function ii(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ge("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function oi(e,t){if(e===void 0)return{};if(typeof e!="string"||!rd.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function ad(e){if(!As(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>xi)throw ge("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${xi} 字节`);return e}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e,t){return{code:e,message:t}}const Bi=5e3,Fi=1e4;function Me(e){throw{code:"INVALID_PARAMS",message:e}}function Ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vs(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Me(`${r} 不支持字段: ${n.join(", ")}`)}function cd(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ss(e))return Me("device.vibrate 参数必须是对象");vs(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Me("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Bi?Me(`device.vibrate delay 必须是 0-${Bi} 的整数毫秒`):{intensity:r,delay:n}}function dd(e){return Ss(e)?(vs(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Me("device.setClipboard text 必须是非空字符串"):e.text.length>Fi?Me(`device.setClipboard text 不能超过 ${Fi} 字符`):{text:e.text}):Me("device.setClipboard 参数必须是对象")}function ud(e){return{[Rr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.vibrate(cd(t),e.operationContext),e.operationContext.signal)},[Dr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.setClipboard(dd(t),e.operationContext),e.operationContext.signal)}}}const ld=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"]),hd={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 si(e){const t=Rs(e),r=t&&ld.has(t)?l(t,hd[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function be(e){try{return e()}catch(t){throw si(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 Ds(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):Ps,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Mn,stat:s=>e.stat(s)})}function Ts(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=>Ds(e.file(a),n,{allowRemove:o}),directory:a=>Ts(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Mn,remove:s?(a,c)=>e.remove(a,c):Ps,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Mn(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Ps(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Vi=1024;class fd{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 qt(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>Vi)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)=>qt(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 $i(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=gd(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tt(r.relativePath),o=this.prepareFile(be(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=pd(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tt(r.relativePath),o=this.prepareDirectory(be(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return zi(t),qt(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 qt(n.handle,qi(t.ref,n.handle.name))}if(M(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return $i(n.handle,md(t.ref,n.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Ht(r),i=this.prepareFile(be(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:qi(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return be(()=>{zi(t);const i=n??t.mode;return ji(t.mode,i),{handle:Ds(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return be(()=>{Ed(t,i);const o=n??t.mode;return ji(t.mode,o),{handle:Ts(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Vi)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=yd();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(!wd(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.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 Tt(e){if(!ei(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Ht(e,t="文件名"){const r=Tt(e);if(r.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return r}function qi(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tt(`${e.relativePath}/${t}`)}}function md(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tt(`${e.relativePath}/${t}`)}}function qt(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function $i(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function ji(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function gd(e){return hs(e)||Ls(),e}function pd(e){return fs(e)||Ls(),e}function Ls(){throw l("INVALID_PARAMS","文件引用不合法")}function yd(){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 wd(e){return/^[0-9a-f]{32}$/.test(e)}function zi(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");Ht(e.name,"Host File name")}function Ed(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&&Ht(e.name,"Host Directory name")}const Gi=1e3,bd=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function _d(e){const t=r=>ri(e.operationContext,r.signal);return{files:{[lr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=Id(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=Ad(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=Sd(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:{[vt]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.create(Wi(i),t(n)))},[Rt]: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(Rt);await ee(()=>o.handle.remove(t(n)))},[mr]:async(r,n)=>{const i=ie(r);return Ki(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!M(o)||o.kind!=="file")throw Qi()})},[gr]:async(r,n)=>{const i=ie(r),o=Yi(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 Yi(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 Dd(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(Wi(i),t(n)))},[Dt]: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(Dt);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 Ki(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!M(o)||o.kind!=="directory")throw Qi()})},[Ir]:async(r,n)=>{const i=ie(r,["limit"]),o=vd(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 Id(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||oe("pickFiles 参数必须是对象"),Fr(e,["mode","accept","multiple"]);const t=Cs(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 Ad(e){return e===void 0?{mode:"read"}:(M(e)||oe("pickDirectory 参数必须是对象"),Fr(e,["mode"]),{mode:Cs(e.mode,"read")})}function Sd(e){return M(e)||oe("saveFile 参数必须是对象"),Fr(e,["suggestedName"]),{suggestedName:Ht(e.suggestedName,"suggestedName")}}function ie(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&oe("文件操作参数必须包含 target"),Fr(e,["target",...t]),e}function Wi(e){return{recursive:e.recursive===void 0?!1:Or(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Or(e.exclusive,"exclusive")}}function Cs(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 vd(e){if(e===void 0)return Gi;if((!Number.isSafeInteger(e)||e<=0)&&oe("limit 必须是正整数"),e>Gi)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Fr(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 Ki(e){try{return await e(),!0}catch(t){if(bd.has(Rs(t)??""))return!1;throw si(t)}}async function ee(e){try{return await e()}catch(t){throw si(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 Yi(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Qi(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Dd(e){if(!M(e)||e.kind!=="file"||!Td(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Pd(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 Td(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Pd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function oe(e){throw l("INVALID_PARAMS",e)}const Ld=["pc","console","mobile"],Cd=["game","wiki"];function Nr(e){throw{code:"INVALID_PARAMS",message:e}}function Od(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(e,t){return typeof e!="string"||!e.trim()?Nr(t):e.trim()}function Xi(e,t,r){return typeof e!="string"||!t.includes(e)?Nr(r):e}function Nd(e){const t={target:"game_detail",appId:Ue(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Xi(e.gameType,Ld,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Xi(e.page,Cd,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ue(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ue(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function kd(e){return{target:"user_detail",userId:Ue(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Md(e){const t={target:"post_detail",linkId:Ue(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ue(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ue(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Ud(e){return Od(e)?e.target==="game_detail"?Nd(e):e.target==="user_detail"?kd(e):e.target==="post_detail"?Md(e):Nr("navigation.openAppPage target 不支持"):Nr("navigation.openAppPage options 必须是对象")}function Hd(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 xd(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Bd(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 Fd(e){const t=Ud(e);return t.target==="game_detail"?Hd(t):t.target==="user_detail"?xd(t):Bd(t)}function Vd(e){throw{code:"INVALID_PARAMS",message:e}}function Ji(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Vd(`${t} 不支持参数`)}function qd(e){return{[Tr]:async t=>{W(e.operationContext.signal),Ji(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Pr]:async t=>{W(e.operationContext.signal),Ji(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Lr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.openAppPage(Fd(t),e.operationContext),e.operationContext.signal)}}}const $d=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),jd=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),zd=new Set(["range","if-range","a-im"]),Gd=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"]),Wd=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,$t={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Kd{constructor(t){this.signal=t}phase="initial";transition(t){if($t[t]<=$t[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if($t[this.phase]<$t.committed&&this.signal.aborted)throw ks()}normalizeHostError(t,r){return this.throwIfCancelled(),ai(t,r,this.signal)}}async function Yd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw pe("network.download");const o=ri(r.operationContext,t.signal),s=new Kd(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Zd(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=tu(c);ru(c,d);const h=nu(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=eu(e,a,d,i);let f=0;const _=Xd(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.hostHandle,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=Qd(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||Jd(n.network,c.body)}}function Qd(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 Xd(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Jd(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Zd(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Un(i.handle.mode),await uu(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Un(n.handle.mode),await lu(n.handle,r),{kind:"directory",...n}}function eu(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=ou(e,r),o=n.deriveFile(t,i);return Un(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function tu(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()||!$d.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 ru(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:du(t,jd)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function nu(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=iu(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 iu(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 ou(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=su(i);if(o&&Yt(o))return o}for(const i of r){const o=au(i);if(o&&Yt(o))return o}if(e.suggestedName!==void 0)return Os(e.suggestedName);const n=cu(e.url);return n&&Yt(n)?n:"download.bin"}function su(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 au(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 cu(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Os(e){try{Ht(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Yt(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Yt(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Wd.test(e))}function du(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function uu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Ns()}catch(r){throw ai(r,"file",t.signal)}}async function lu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Ns()}catch(r){throw ai(r,"file",t.signal)}}function Un(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const hu={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 ai(e,t,r){if(r.aborted)return ks();const n=fu(e);if(n&&Gd.has(n)){const o=l(n,hu[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 fu(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Ns(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function ks(){return l("DOWNLOAD_CANCELLED","下载已取消")}function mu(e){if(!e)return;const t=Object.keys(e).find(r=>zd.has(r.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const gu=4,pu=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],yu=["/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 wu(e,t){const r=Eu(e);return r===null||Zi(r,pu)?!0:t&&Zi(r,yu)}function Eu(e){let t=e;for(let r=0;r<gu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return eo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return eo(t)}function Zi(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function eo(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}const bu=new Set(["url","method","params","data","headers","timeout","withCredentials"]),_u=new Set(["url","to","params","headers","timeout","withCredentials","suggestedName","overwrite","maxBytes"]),Iu=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),to=3e4,ro=2*1024*1024,Au=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Su=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","set-cookie","transfer-encoding","user-agent"]),vu=/^(?: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 Du(e){const t=Tu(e.runtimePermissions),r=qu(e.allowedHttpOrigins);return{[ur]:async(n,i)=>{const o=Lu(n,{permission:t,allowedHttpOrigins:r});return Yd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[dr]:async(n,i)=>{const o=ri(e.operationContext,i?.signal);W(o.signal);const s=Pu(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw Gu(c)?c:Wu(c,"REQUEST_UNSUPPORTED")?k("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):k("REQUEST_FAILED","网络请求失败")}return zu(a)}}}function Tu(e){const t=xr(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Pu(e,t){const r=Vr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!bu.has(c));if(n.length>0)throw k("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);const i=Ms(r,t,"network.request"),o=Ou(r.method),s=r.data;s!==void 0&&Uu(s),xu(i.headers,s);const a=Bu(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 Lu(e,t){const r=Vr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!_u.has(c));if(n.length>0)throw k("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);const i=Ms(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw k("INVALID_PARAMS","network.download timeout 必须是有限正数");mu(i.headers);const o=hs(r.to),s=fs(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=Os(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 Ms(e,t,r){const n=Cu(e.url,t.allowedHttpOrigins,r),i=ju(n);if(i&&!t.permission.useOfficialDomain)throw k("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(wu(n.pathname,i))throw k("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,withCredentials:Mu(e.withCredentials,`${r} withCredentials 必须是布尔值`),params:e.params===void 0?void 0:{...Vr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Nu(e.headers,r),timeout:ku(e.timeout,r)}}function Cu(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 Ou(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(!Iu.has(t))throw k("INVALID_PARAMS","network.request method 不合法");return t}function Nu(e,t="network.request"){const r=Vr(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(Su.has(s)||s.startsWith("x-heybox-")||s.startsWith("x-xhh-"))throw k("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[i]=o}return n}function ku(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>to)throw k("INVALID_PARAMS",`${t} timeout 不能超过 ${to}ms`);return e}}function Mu(e,t){if(e!==void 0){if(typeof e!="boolean")throw k("INVALID_PARAMS",t);return e}}function Uu(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(Hu(e)>ro)throw k("INVALID_PARAMS",`network.request data 不能超过 ${ro} 字节`)}function Hu(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 xu(e,t){const r=Us(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 Bu(e,t,r){if(t===void 0)return;const n=Us(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)||Vu(t))?"form":Fu(t)?"json":void 0}function Us(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Fu(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Vu(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qu(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&&$u(n.hostname)&&t.add(n.origin)}catch{}return t}function $u(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 ju(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Au.some(r=>t===r||t.endsWith(`.${r}`))}function zu(e){return Object.keys(e.headers).some(no)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!no(t)))}:e}function no(e){const t=e.trim().toLowerCase();return vu.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Gu(e){return e instanceof Error&&e.name==="AbortError"}function Wu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Vr(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 jt=4294967296;function Ku(e){const t=new Yu;return t.write(e),t.finish()}class Yu{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<jt?(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=Qu(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<jt)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/jt),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/jt)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Qu(e){const t=new Uint8Array(Xu(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 Xu(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 Ju(e){Hn(e);const t=Ku(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 Zu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function el(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 tl(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=el(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function rl(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 Hs(e,t){if(e==null)return{};if(!Zu(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=tl(e.topicIds),n=rl(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 nl(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function il(e){try{if(nl(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function X(e){throw{code:"INVALID_PARAMS",message:e}}function xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e,t){return typeof e!="string"||!e.trim()?X(t):e}function ol(e,t){const r=xn(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?X(t):r}catch{return X(t)}}function sl(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function xs(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return X(`${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 X(`${t} 缺少有效的小程序分享地址`)}}function al(e,t){if(!xt(e))return X("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return X("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!sl(r))return X("share.showShareMenu channel 不合法");const n=Bs(e.extra,"share.showShareMenu");return{title:xn(e.title,"share.showShareMenu title 必须是非空字符串"),description:xn(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:xs(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:ol(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Bs(e,t){if(e!==void 0)try{return Ju(e)}catch{return X(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Fs(e,t){return e.invalidMessage&&await $(()=>il(t.environment),t.operationContext.signal)?X(e.invalidMessage):e.post}function io(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function cl(e){const t=e.getViewportMetrics();return{left:0,top:0,width:io(t.windowWidth,0),height:io(t.windowHeight,0)}}function Bn(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?X(t):r}function oo(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?X(t):r}function dl(e){return xt(e)?{left:Bn(e.left,"share.screenshot rect.left 必须是非负数字"),top:Bn(e.top,"share.screenshot rect.top 必须是非负数字"),width:oo(e.width,"share.screenshot rect.width 必须是正数"),height:oo(e.height,"share.screenshot rect.height 必须是正数")}:X("share.screenshot rect 必须是对象")}function ul(e,t){if(e!=null&&!xt(e))return X("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?X("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?cl(t):dl(r.rect),...r.delay===void 0?{}:{delay:Bn(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function ll(e,t){W(t.operationContext.signal);const r=al(e,t);let n=Hs(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Fs(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function hl(e,t){if(W(t.operationContext.signal),e!==void 0&&!xt(e))return X("share.copyLink 参数必须是对象");const r=Bs(e?.extra,"share.copyLink"),n=xs(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function fl(e,t){W(t.operationContext.signal);const r=ul(e,t.presentation),n=Hs(xt(e)?e.post:void 0,{method:"share.screenshot"}),i=await Fs(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=ml();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 gl(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(u)throw u;return c.value}function ml(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function gl(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 pl(e){return{[ir]:(t,r)=>hl(t,e),[or]:(t,r)=>ll(t,e),[sr]:(t,r)=>fl(t,e)}}const yl=128,wl=/^[A-Za-z0-9_-]+$/;function El(e){const t=bl(e),r={[At]:async n=>{W(e.operationContext.signal);const i=so(n,At,e.storageLimits?.maxKeyLength),o=await $(()=>e.storage.getRaw(rn(t(),i),e.operationContext),e.operationContext.signal);return{data:ao(o)}},[St]:async n=>{W(e.operationContext.signal);const i=Vs(n,"storage.setStorage 参数必须是对象"),o=so(i,St,e.storageLimits?.maxKeyLength),s=_l(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 Ce("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:ao(a),serializedValue:a,bytes:qs(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function bl(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${co(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${co(i)}`)}t=r!==void 0}if(!r)throw Ce("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function rn(e,t){return`hb_miniprogram_${e}_${t}`}function so(e,t,r=yl){const i=Vs(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Ce("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!wl.test(i))throw Ce("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function _l(e,t){let r;try{r=JSON.stringify(e)}catch{throw Ce("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Ce("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&qs(r)>t)throw Ce("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function ao(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Vs(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Ce("INVALID_PARAMS",t);return e}function co(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:Il(e)}function Il(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 qs(e){return new TextEncoder().encode(e).length}function Ce(e,t){return{code:e,message:t}}const uo=120;function De(e){throw{code:"INVALID_PARAMS",message:e}}function ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $s(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&De(`${r} 不支持字段: ${n.join(", ")}`)}function Al(e){if(!ci(e))return De("ui.showToast 参数必须是对象");if($s(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return De("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>uo)return De(`ui.showToast message 不能超过 ${uo} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return De("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Sl(e){return e===void 0?{dismissible:!1}:ci(e)?($s(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?De("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):De("ui.showLoading 参数必须是对象")}function vl(e){e!==void 0&&(!ci(e)||Object.keys(e).length)&&De("ui.hideLoading 不支持参数")}function Rl(e){return{[Ar]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showToast(Al(t),e.operationContext),e.operationContext.signal)},[Sr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showLoading(Sl(t),e.operationContext),e.operationContext.signal)},[vr]:async t=>{W(e.operationContext.signal),vl(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Dl={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ne(e,"当前用户首页资料接口响应异常")}},Tl=3e4;function Pl(e,t,r={}){const n=r.ttlMs??Tl;let i=0,o,s;async function a(){let u;try{u=await Br(e,Dl,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 Ut?l("INVALID_RESPONSE","user home_v2 响应不合法"):d instanceof nt?l("REQUEST_FAILED","user home_v2 请求失败"):d instanceof rt?l("REQUEST_FAILED",d.message):Cl(d)?d:l("REQUEST_FAILED","user home_v2 请求失败")}return Ll(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 Ll(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 Cl(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Ol={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 游戏库接口响应异常")}},js=20,Nl=100,zs=0,Gs="weeks",kl=100,Ml=new Set(["weeks","all","achieved"]);function Ul(e){const t=Pl(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 已终止"):ho(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 Br(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 Ut?l("INVALID_RESPONSE","用户接口响应不合法"):y instanceof nt?l("REQUEST_FAILED","用户请求失败"):y instanceof rt?l("REQUEST_FAILED",y.message):ho(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(Es,void 0).then(A=>{const v=lo(A,"账号基础信息");if(v.display_username!==void 0&&typeof v.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(v.display_avatar!==void 0&&typeof v.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:v.display_username??"",avatar:v.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{r.get(b)===y&&r.delete(b)});return r.set(b,y),y}async function _(b){const I=Hl(b);c();const y=n,A=await u();if(!A)return{isLogin:!1,isBound:!1,data:null};const v=await t.get(A);await d(A,y);const P=di(v.steam_id_info);if(Object.keys(P).length===0)return{isLogin:!0,isBound:!1,data:null};const H=await h(Ol,{userId:A,...I,personalInformationOpen:Ws(P.personal_infomation_open??P.personal_information_open)});await d(A,y);const R=lo(H,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:ql(R,I)}}return{getInfo:p,getSteamGameList:_,dispose(){i||(i=!0,n+=1,o(),s(),t.clear(),r.clear())}}}function Hl(e){if(e==null)return{limit:js,offset:zs,sort:Gs,includeHidden:!1};if(!M(e))throw Te("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Te(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:xl(e.limit),offset:Bl(e.offset),sort:Fl(e.sort),includeHidden:Vl(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw Te("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Te("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,kl))}return r}function xl(e){if(e===void 0)return js;if(!Number.isInteger(e)||Number(e)<1)throw Te("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Nl)}function Bl(e){if(e===void 0)return zs;if(!Number.isInteger(e)||Number(e)<0)throw Te("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Fl(e){if(e===void 0)return Gs;if(typeof e!="string"||!Ml.has(e))throw Te("user.getSteamGameList sort 不支持");return e}function Vl(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Te("user.getSteamGameList includeHidden 必须是 boolean");return e}function ql(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map($l).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=Ws(e.is_me);return s!==void 0&&(o.isMe=s),o}function $l(e){const t=di(e),r=kr(t.appid),n=kr(t.steam_appid)??r,i=ui(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};yt(o,"image",t.image),yt(o,"icon",t.appicon??t.icon),wt(o,"playtimeForever",t.playtime_forever),wt(o,"playtime2Weeks",t.playtime_2weeks);const s=zl(t.external_tags??t.tags);s.length&&(o.tags=s);const a=jl(t.price);return a&&(o.price=a),o}function jl(e){const t=di(e),r={};return yt(r,"current",t.current),yt(r,"initial",t.initial),wt(r,"discount",t.discount),wt(r,"lowestPrice",t.lowest_price),yt(r,"deadlineDate",t.deadline_date),wt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function lo(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 di(e){return M(e)?e:{}}function ui(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function zl(e){return Array.isArray(e)?e.map(ui).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 Ws(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function yt(e,t,r){const n=ui(r);n&&Object.assign(e,{[t]:n})}function wt(e,t,r){const n=kr(r);n!==void 0&&Object.assign(e,{[t]:n})}function Te(e){return l("INVALID_PARAMS",e)}function ho(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Gl(e){return{[tr]:async t=>(fo(t,"user.getInfo"),e.user.getInfo()),[rr]:async(t,r)=>{fo(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[nr]:async t=>e.user.getSteamGameList(t)}}function fo(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}function mo(e){throw{code:"INVALID_PARAMS",message:e}}function lt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Ks(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function zt(e,t,r){return Math.min(Ks(e,t),r)}async function Wl(e){try{return Ks(await e.getNavigationBarHeight(),0)}catch{return 0}}function Kl(e,t,r,n){const i=zt(e.safeArea?.left,0,t),o=Math.max(i,zt(e.safeArea?.right,t,t)),s=zt(e.safeArea?.top,n,r),a=Math.max(s,zt(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Yl(e){const t=e.getViewportMetrics(),r=lt(t.windowWidth,0),n=lt(t.windowHeight,0),i=await Wl(e);return{pixelRatio:lt(t.pixelRatio,1),screenWidth:lt(t.screenWidth,r),screenHeight:lt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Kl(t,r,n,i),screenTop:i}}function Ql(e){return{[ar]:async()=>(W(e.operationContext.signal),Yl(e.presentation)),[cr]:async t=>{if(W(e.operationContext.signal),typeof t!="object"||t===null||Array.isArray(t))return mo("viewport.setNavigationBarStyle 参数必须是对象");const r=t.foregroundStyle;if(r!=="light"&&r!=="dark")return mo("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>e.presentation.setNavigationBarStyle(r,e.operationContext),e.operationContext.signal)}}}const Xl=new Map(Le.map(e=>[e.method,e]));function nn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Jl(e){const t=xr(e);return r=>{if(r.requirement.kind==="none")return{allowed:!0};for(const n of r.requirement.permissions){const i=t.valid?t.permissions[n]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${n}`,data:{permission:n,method:r.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${n}`,data:{permission:n,method:r.method}}}return{allowed:!0}}}function Zl(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 eh(e){const t=Jl(e.runtimePermissions);let r=0;return{async dispatch(n,i,o){const s=e.now??th,a=e.onTrace?s():0,c=e.onTrace?`cap_${++r}`:"";try{if(e.terminalSignal.aborted)throw nn("RUNTIME_DESTROYED","小程序 Runtime 已终止");Xa(n,e.effectiveCapabilities);const u=Xl.get(n);if(!u)throw new Error(`Capability method ${n} 缺少 protocol metadata`);const d=t(u);if(!d.allowed)throw nn(d.code,d.message,d.data);const h=e.handlers[n];if(!h)throw new Error(`Capability method ${n} 缺少 handler`);const p=await Zl(async()=>{for(const f of e.policies??[]){const _=await f.evaluate({method:n,payload:i,capability:u});if(e.terminalSignal.aborted)throw yo();if(!_.allowed)throw nn(_.code,_.message,_.data)}if(e.terminalSignal.aborted)throw yo();return h(i,o)},void 0,o,e.terminalSignal);return go(e.onTrace,po(c,n,i,a,p),s),p}catch(u){throw go(e.onTrace,po(c,n,i,a,{status:"error",error:u}),s),u}}}}function th(){return typeof performance>"u"?Date.now():performance.now()}function go(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 po(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:rh(i.error)}:{},...nh(t,r,i)}}function rh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function nh(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"&&ih(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 ih(e){return typeof e=="object"&&e!==null}function yo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function oh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=new fd(e.files,e.miniProgramDetail),n=_d({registry:r,picker:e.picker,operationContext:t}),i=Lc({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation});let o,s,a=()=>{};try{o=Ul({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),a=i.onEvent((f,_)=>e.eventSink.postEvent(f,_)),s=id({account:e.account,identity:e.identity,network:e.network,operationContext:t});const c=El({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),u=[{name:"auth",handlers:xc({authorization:i})},{name:"user",handlers:Gl({user:o,authorization:i})},{name:"share",handlers:pl({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:Ql({operationContext:t,presentation:e.hostPresentation})},{name:"storage",handlers:c.handlers},{name:"network",handlers:Du({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:Rl({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:ud({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:qd({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:s.handlers}],d=sh(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 sh(e){const t=new Map(Le.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=Le.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Le.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const ah="heybox-mini-dev:";function wo(e){try{return ch(new URL(e))}catch{return!1}}function ch(e){return e.protocol===ah}function dh(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||uh(e)}function uh(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 lh=1,Ys="allow-scripts allow-same-origin",hh="",fh="no-referrer";function mh(e=Ys){return!e.split(/\s+/).includes("allow-same-origin")}function Eo(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const gh=new Set(["javascript:","data:","blob:","file:"]),bo="xiaoheihe.cn";function ph(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(gh.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!_h(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function yh(e,t){const r=new URL(e);return r.searchParams.set(ka,t),r.toString()}function wh(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Eh(r)??bh(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Eh(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function bh(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function _o(e){const t=new URL(e);return li(t)?"loopback":hi(t)?"lan":"production"}function _h(e,t,r){return Ih(e)||li(e)||hi(e)&&Sh(t,r)}function Ih(e){return e.protocol==="https:"&&Dh(e.hostname)}function li(e){return e.protocol==="http:"&&Ah(e.hostname)}function Ah(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function hi(e){return e.protocol==="http:"&&vh(e.hostname)}function Sh(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return li(r)||hi(r)}catch{return!1}}function vh(e){const t=Rh(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Rh(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 Dh(e){return e===bo||e.endsWith(`.${bo}`)}const Th=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"]),Ph=new Set(["url","inline","eval","unknown"]),Lh=/^\/(?:\:segment(?:\/\:segment)*)?$/,Ch=/^[a-f0-9]{64}$/,Oh=255,Nh=160,kh=256;function Mh(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Th.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>kh||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Ph.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Uh(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Nh||!Lh.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Ch.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 Uh(e){if(e!==void 0&&!(typeof e!="string"||e.length>Oh))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Hh=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 xh(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:Bh(i.pathname),sanitizedPathnameHash:Fh(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Bh(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Fh(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],v=le(y,7)^le(y,18)^y>>>3,P=le(A,17)^le(A,19)^A>>>10;o[I]=o[I-16]+v+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&_)+Hh[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 Vh=/^(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 qh(e){if(!e?.minimumSdkVersion)throw U("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=gt(e.minimumSdkVersion),r=e.sdkVersion?gt(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=gt("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,gt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function $h(e,t){if(typeof t!="string"||!gt(t))throw U("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw U("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function gt(e){const t=Vh.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 jh=1e4,sn=2e3,zh=2,Gh="open-with-native-credential-policy",Qs="安全提示",Xs="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Wh{nonce=Eo();runtimeId=Eo();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=ws(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??jh,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:(rf(),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=qh(t.sdkVersionPolicy),this.miniProgramDetail=sf(t),this.effectiveCapabilities=ys(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),Xh(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(Zh(r)),this.launchUrl=r,this.miniProgramSrc=yh(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,Ae(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=oh({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=eh({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}:{}};Ae(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Ya({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 Qh(t)?t:Js(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 ph(t,r,{allowPrivateNetwork:wo(r)||Io(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??tf)({message:Xs,title:Qs,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(_o(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!wo(r)&&!Io(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{Ao(),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(()=>Ao())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",hh),this.iframe.setAttribute("referrerpolicy",fh),this.iframe.setAttribute("sandbox",Ys)}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),Ae(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),Ae(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{$h(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>=zh)){this.failRuntime(U("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Vt,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:Vt})}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(Vt,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Vt})}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===Ha){this.handleCspViolation(t.payload);return}if(t.method!==Ua)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"||!wh(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=Mh(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){Ae(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=xh(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:lh,launchUrlType:_o(t),networkPolicy:Gh})}failRuntime(t){const r=Kh(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),Ae(this.options.onError,Yh(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,Ae(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ae(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 Kh(e){const t=ms(e);return Mr(e)&&"cause"in e&&Js(t,e.cause),t}function Js(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Yh(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Qh(e){return Mr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Mr(e){return!!e&&typeof e=="object"}function Ae(e,t){try{e?.(t)}catch{}}function Xh(e,t,r){try{e?.(t,r)}catch{}}function Io(e){try{const t=new URL(e);return t.protocol==="http:"&&dh(t.hostname)}catch{return!1}}function Jh(e){try{return new URL(e).origin}catch{return}}function Zh(e){return mh()?"*":Jh(e)}function ef(e){return`${Qs}
|
|
2
|
-
|
|
3
|
-
${Xs}
|
|
4
|
-
|
|
5
|
-
URL: ${e}`}function tf(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(ef(e.url))}function Ao(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function rf(){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:ds,knownMethodCount:Le.length,supportsFileCreate:Le.some(i=>i.method===vt),system:nf(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:of(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function nf(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 of(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function sf(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 af(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 Wh(e)}const cf=/^(?: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 df(e,t,r){return ec({mode:"request-only",request:(n,i={signal:t.signal})=>t.run(i.signal,async o=>{const s={...i,signal:o},a=hf(n),c=n.source==="public-sdk"&&n.withCredentials===!0?await uf(a,e,r(),s):await e.authenticatedRequest(a,s);return ff(c)})}).network}function uf(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,lf(e.target.url,r),n)}function lf(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 hf(e){const t=Zs(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function ff(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:Zs(e.headers)??{}}}function Zs(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!mf(t)))}function mf(e){const t=e.trim().toLowerCase();return cf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function gf(e,t,r,n){const i=bf(e.presentation,t);return{account:wf(e,t,r),network:df(e,t,n),...e.storage===void 0?{}:{storage:Ef(e,t)},...e.storage===void 0?{}:pf(e,t),...i===void 0?{}:{presentation:i}}}function pf(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 yf(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 wf(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 Ef(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 bf(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)=>hc(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 _f(){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 Gt(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 Gt(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(Gt(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 Gt(h.reason);return d}finally{for(const{listener:d,source:h}of c)h.removeEventListener("abort",d)}}}}function Gt(e){return new DOMException("Web Host operation aborted","AbortError")}async function If(e){const t=_f(),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=gf(e,t,i,()=>a),u=ws(c,{hostCapabilities:e.hostCapabilities}),d=yf(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:Af(e.authPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:s}}function an(e){try{e()}catch{}}function Af(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Ye={},cn,So;function Sf(){return So||(So=1,cn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),cn}var dn={},Se={},vo;function $e(){if(vo)return Se;vo=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 Se.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},Se.getSymbolTotalCodewords=function(n){return t[n]},Se.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Se.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Se.isKanjiModeEnabled=function(){return typeof e<"u"},Se.toSJIS=function(n){return e(n)},Se}var un={},Ro;function fi(){return Ro||(Ro=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,Do;function vf(){if(Do)return ln;Do=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,To;function Rf(){if(To)return hn;To=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={},Po;function Df(){return Po||(Po=1,(function(e){const t=$e().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={},Lo;function Tf(){if(Lo)return mn;Lo=1;const e=$e().getSymbolSize,t=7;return mn.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},mn}var gn={},Co;function Pf(){return Co||(Co=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 Wt={},Oo;function ea(){if(Oo)return Wt;Oo=1;const e=fi(),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 Wt.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}},Wt.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}},Wt}var pn={},ht={},No;function Lf(){if(No)return ht;No=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]})(),ht.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ht.exp=function(n){return e[n]},ht.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},ht}var ko;function Cf(){return ko||(ko=1,(function(e){const t=Lf();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,Mo;function Of(){if(Mo)return yn;Mo=1;const e=Cf();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={},Uo;function ta(){return Uo||(Uo=1,bn.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bn}var he={},Ho;function ra(){if(Ho)return he;Ho=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 xo;function je(){return xo||(xo=1,(function(e){const t=ta(),r=ra();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 Bo;function Nf(){return Bo||(Bo=1,(function(e){const t=$e(),r=ea(),n=fi(),i=je(),o=ta(),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 v=A-u(b,f);switch(b){case i.NUMERIC:return Math.floor(v/10*3);case i.ALPHANUMERIC:return Math.floor(v/11*2);case i.KANJI:return Math.floor(v/13);case i.BYTE:default:return Math.floor(v/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={},Fo;function kf(){if(Fo)return _n;Fo=1;const e=$e(),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,Vo;function Mf(){if(Vo)return An;Vo=1;const e=je();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,qo;function Uf(){if(qo)return Sn;qo=1;const e=je(),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 vn,$o;function Hf(){if($o)return vn;$o=1;const e=je();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)},vn=t,vn}var Rn,jo;function xf(){if(jo)return Rn;jo=1;const e=je(),t=$e();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)}},Rn=r,Rn}var Dn={exports:{}},zo;function Bf(){return zo||(zo=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 Go;function Ff(){return Go||(Go=1,(function(e){const t=je(),r=Mf(),n=Uf(),i=Hf(),o=xf(),s=ra(),a=$e(),c=Bf();function u(y){return unescape(encodeURIComponent(y)).length}function d(y,A,v){const P=[];let H;for(;(H=y.exec(v))!==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),v=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(v,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,v){const P=A.length-1>=0?A[A.length-1]:null;return P&&P.mode===v.mode?(A[A.length-1].data+=v.data,A):(A.push(v),A)},[])}function _(y){const A=[];for(let v=0;v<y.length;v++){const P=y[v];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 v={},P={start:{}};let H=["start"];for(let R=0;R<y.length;R++){const O=y[R],C=[];for(let S=0;S<O.length;S++){const w=O[S],D=""+R+S;C.push(D),v[D]={node:w,lastCount:0},P[D]={};for(let m=0;m<H.length;m++){const g=H[m];v[g]&&v[g].node.mode===w.mode?(P[g][D]=p(v[g].lastCount+w.length,w.mode)-p(v[g].lastCount,w.mode),v[g].lastCount+=w.length):(v[g]&&(v[g].lastCount=w.length),P[g][D]=p(w.length,w.mode)+4+t.getCharCountIndicator(w.mode,A))}}H=C}for(let R=0;R<H.length;R++)P[H[R]].end=0;return{map:P,table:v}}function I(y,A){let v;const P=t.getBestModeForData(y);if(v=t.from(A,P),v!==t.BYTE&&v.bit<P.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(v)+`.
|
|
8
|
-
Suggested mode is: `+t.toString(P));switch(v===t.KANJI&&!a.isKanjiModeEnabled()&&(v=t.BYTE),v){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(v,P){return typeof P=="string"?v.push(I(P,null)):P.data&&v.push(I(P.data,P.mode)),v},[])},e.fromString=function(A,v){const P=h(A,a.isKanjiModeEnabled()),H=_(P),R=b(H,v),O=c.find_path(R.map,"start","end"),C=[];for(let S=1;S<O.length-1;S++)C.push(R.table[O[S]].node);return e.fromArray(f(C))},e.rawSplit=function(A){return e.fromArray(h(A,a.isKanjiModeEnabled()))}})(In)),In}var Wo;function Vf(){if(Wo)return dn;Wo=1;const e=$e(),t=fi(),r=vf(),n=Rf(),i=Df(),o=Tf(),s=Pf(),a=ea(),c=Of(),u=Nf(),d=kf(),h=je(),p=Ff();function f(R,O){const C=R.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?R.set(D+g,m+E,!0,!0):R.set(D+g,m+E,!1,!0))}}function _(R){const O=R.size;for(let C=8;C<O-8;C++){const S=C%2===0;R.set(C,6,S,!0),R.set(6,C,S,!0)}}function b(R,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?R.set(w+m,D+g,!0,!0):R.set(w+m,D+g,!1,!0)}}function I(R,O){const C=R.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,R.set(w,D,m,!0),R.set(D,w,m,!0)}function y(R,O,C){const S=R.size,w=d.getEncodedBits(O,C);let D,m;for(D=0;D<15;D++)m=(w>>D&1)===1,D<6?R.set(D,8,m,!0):D<8?R.set(D+1,8,m,!0):R.set(S-15+D,8,m,!0),D<8?R.set(8,S-D-1,m,!0):D<9?R.set(8,15-D-1+1,m,!0):R.set(8,15-D-1,m,!0);R.set(S-8,8,1,!0)}function A(R,O){const C=R.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(!R.isReserved(w,g-E)){let T=!1;m<O.length&&(T=(O[m]>>>D&1)===1),R.set(w,g-E,T),D--,D===-1&&(m++,D=7)}if(w+=S,w<0||C<=w){w-=S,S=-S;break}}}function v(R,O,C){const S=new r;C.forEach(function(E){S.put(E.mode.bit,4),S.put(E.getLength(),h.getCharCountIndicator(E.mode,R)),E.write(S)});const w=e.getSymbolTotalCodewords(R),D=a.getTotalCodewordsCount(R,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,R,O)}function P(R,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 Gr=new Uint8Array(R.buffer);for(let ze=0;ze<m;ze++){const Wr=ze<E?N:F;J[ze]=Gr.slice(se,se+Wr),z[ze]=Z.encode(J[ze]),se+=Wr,ye=Math.max(ye,Wr)}const at=new Uint8Array(S);let _i=0,we,Ee;for(we=0;we<ye;we++)for(Ee=0;Ee<m;Ee++)we<J[Ee].length&&(at[_i++]=J[Ee][we]);for(we=0;we<V;we++)for(Ee=0;Ee<m;Ee++)at[_i++]=z[Ee][we];return at}function H(R,O,C,S){let w;if(Array.isArray(R))w=p.fromArray(R);else if(typeof R=="string"){let T=O;if(!T){const N=p.rawSplit(R);T=u.getBestVersionForData(N,C)}w=p.fromString(R,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=v(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={},Ko;function na(){return Ko||(Ko=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 Yo;function qf(){return Yo||(Yo=1,(function(e){const t=na();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={},Qo;function $f(){if(Qo)return Ln;Qo=1;const e=na();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 Xo;function jf(){if(Xo)return Ye;Xo=1;const e=Sf(),t=Vf(),r=qf(),n=$f();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 zf=jf();const Pt=500,Gf=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"]),Wf=/(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;function Jo(e){if(!e)return e;try{const t=new URL(e);if(t.username="",t.password="",Zo(t.searchParams),t.hash&&t.hash.length>1){const r=t.hash.slice(1);if(r.includes("=")){const n=new URLSearchParams(r);Zo(n)&&(t.hash=n.toString())}}return t.toString()}catch{return oa(e)}}function Kf(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Yf(t)?"[redacted]":r])):{}}function Fn(e){if(e!==void 0){if(typeof e=="string")return ia(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<=Pt?t:mi(r,Pt)}catch{return"[unserializable]"}}}function Et(e){return Array.isArray(e)?e.slice(0,20).map(t=>Et(t)):typeof e=="string"?Qf(e)?Jo(e):ia(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 st(t)?[t,"[redacted]"]:n==="headers"&&qn(r)?[t,Kf(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,Jo(r)]:[t,Et(r)]})):Fn(e)}function Yf(e){const t=e.trim().toLowerCase();return Gf.has(t)||st(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function st(e){return Wf.test(e.trim())}function ia(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<=Pt*2)try{const r=new URLSearchParams(t);if([...r.keys()].length>0){const n=Object.fromEntries([...r.entries()].map(([i,o])=>[i,st(i)?"[redacted]":o]));return Fn(n)}}catch{}return mi(oa(e),Pt)}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,st(t)?"[redacted]":Vn(r)])):typeof e=="string"?mi(e,Pt):e}function Zo(e){let t=!1;for(const r of[...e.keys()])st(r)&&(e.set(r,"[redacted]"),t=!0);return t}function oa(e){return e.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g,(t,r,n,i)=>st(n)?`${r}${n}=[redacted]`:t)}function Qf(e){return/^https?:\/\//i.test(e.trim())||/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function mi(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 Xf="/__hb_sdk__/dev-context";function Jf(e){if(!$n(e)||!es(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!$n(t)||!es(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Zf={networkRequest:{status:"disabled",useOfficialDomain:!1}};function em(e){const t=xr(e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:nm()}function tm(e,t){return sa(e,t,t.networkRequest.useOfficialDomain)}function rm(e,t){return sa(e,t,!1)}function nm(){return{networkRequest:{...Zf.networkRequest}}}function sa(e,t,r){const n=xr(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of ti){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:{key:s,status:a.status,config:{}})}const o=$n(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function $n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function es(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function im(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 om(e){return im({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 sm(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 am={identity:"小程序身份",profile:"昵称和头像"};function cm(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(am[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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function dm(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",releaseChannel:"development"},runtimePermissions:e.runtimePermissions,...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const ts="hb-sdk-action-dialog-style";function gi(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}fm();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>${rs(e.title)}</h2>
|
|
27
|
-
<pre class="hb-sdk-action-dialog__detail">${rs(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 um(e,t){await gi({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Lt(e.params)].join(`
|
|
33
|
-
`),signal:t.signal})}async function lm(e,t){await gi({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Lt(e.channel),"post: "+Lt(e.post)].join(`
|
|
34
|
-
`),signal:t.signal})}async function hm(e,t){await gi({title:"截图分享",detail:["rect: "+Lt(e.rect),"post: "+Lt(e.post)].join(`
|
|
35
|
-
`),signal:t.signal})}function Lt(e){return JSON.stringify(e,null,2)}function rs(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function fm(){if(document.getElementById(ts))return;const e=document.createElement("style");e.id=ts,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 mm(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 Oa({message:t,status:r})},showLoading:Ca,hideLoading:La,vibrate:Pa,openAppPage:um,showShareMenu:lm,captureAndShare:hm,setScreenshotChromeHidden:Ta}}const gm=/^[A-Za-z0-9_-]{22}$/,pm="https://api.xiaoheihe.cn/open_inapp/";function ym(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(!gm.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 wm(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`${pm}#${r}`}const Em="__hb_sdk_mini_dev__",bm="hb-sdk:mini-dev-console",_m="__hb_sdk_mini_dev_console_installed__",ns=_m;function Im(e,t=console){Sm(t,e,t)}const Am=["log","debug","info","warn","error"];function Sm(e,t,r){if(!r||r[ns]===!0)return!1;let n=!1;for(const i of Am){const o=e[i];if(typeof o!="function")continue;const s=function(...a){try{t(i,a)}catch{}return o.apply(this,a)};try{e[i]=s,n=!0}catch{return n}}return n&&(r[ns]=!0),n}const jn=1,is=64*1024,vm=64,Rm=/^[A-Za-z0-9_-]{22}$/;class te extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function Dm(e,t=!1){const r=Pm(e,t);switch(zn(r,"Server message"),Lm(r),r.type){case"grant":return bt(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.nextClientSequence,"nextClientSequence"),ke(r.nextServerSequence,"nextServerSequence"),os(r.snapshot),r;case"event":return bt(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Oe("event must be account.changed or status.changed"),os(r.snapshot),r;case"heartbeat":return bt(r,["version","type","connectionEpoch","sequence"],"heartbeat"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.sequence,"sequence"),r;default:return Oe("Unknown server message type")}}function Tm(e){const t=e.connectionEpoch;_t(t,"connectionEpoch"),ke(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(_t(n.connectionEpoch,"connectionEpoch"),ke(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 Pm(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>is)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>is)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return Cm(e),JSON.parse(e)}catch(r){throw r instanceof te?r:new te("INVALID_JSON","Channel frame must contain strict JSON")}}function os(e){zn(e,"snapshot"),bt(e,["account","permissions"],"snapshot"),zn(e.account,"snapshot.account"),bt(e.account,["revision"],"snapshot.account"),ke(e.account.revision,"snapshot.account.revision"),Jf(e.permissions)||Oe("snapshot.permissions is invalid")}function Lm(e){e.version!==jn&&Oe("version must be 1")}function zn(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Oe(`${t} must be a plain JSON object`)}function bt(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)))&&Oe(`${r} fields are invalid`)}function ke(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Oe(`${t} must be a non-negative safe integer`)}function _t(e,t){(typeof e!="string"||!Rm.test(e))&&Oe(`${t} must be a 22-character base64url value`)}function Oe(e){throw new te("INVALID_MESSAGE",e)}function Cm(e){new Om(e).scan()}class Om{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>=vm)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 ss=[1e3,2e3,4e3,8e3,15e3];function Nm(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)},v=()=>{if(h||f!==void 0||c)return;const w=ss[Math.min(p,ss.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()},R=()=>{s&&!s.hidden&&P()},O=()=>{b||(b=!0,o?.addEventListener("online",H),s?.addEventListener("visibilitychange",R))},C=()=>{b&&(b=!1,o?.removeEventListener("online",H),s?.removeEventListener("visibilitychange",R))},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"),v();return}try{D=Mm(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{w?.close(1011,"channel initialization failed")}catch{}v();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{}v()}},F=()=>{if(!(h||c!==w))try{w.send(JSON.stringify({version:jn,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=Dm(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=Tm({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:jn,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(),v())},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 km(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 Mm(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=km(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{Im((e,t)=>{Zn(`console.${e}`,{source:"host",message:t.map(r=>ua(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const Um="/__hb_sdk_bootstrap__",Hm="/__hb_sdk__/mobile-launch-redirect",xm="/__hb_sdk__/network",Bm="/session/status",Fm="/session/request",Vm="/session/events",qm=320,$m=1e3,jm=1e3,zm=15e3,aa=new URL(location.href).searchParams,ca=aa.get("mini_url"),qr=aa.get("ui_preview")==="1",x={device:ft("#device"),get mobileLanSelect(){return ft("#mobile-lan-select")},get mobileQrImage(){return ft("#mobile-qr-image")},get mobileQrStatus(){return ft("#mobile-qr-status")},storageSnapshot:ft("#storage-snapshot")};if(!ca&&!qr)throw x.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Gm=ca??"about:blank",de=await yi();let ve=de.lanAddresses,Qt=de.defaultLanAddressId,Xe=de.mobileLaunchRedirect,da=Ei(de),Ze=de.devContext,Ct=em(Ze),B=!1,$r=0;const pi=new AbortController;let He=0,tt,Ot,Xt=0,xe,Gn,Wn,Re=0,Nt=!1,Jt,et,On=!1,as=Promise.resolve(),It=-1,kt=!1,Be,Kn,Yn,Zt,Ne;const Ur=new Set,it=om({applyStatus:e=>ga(e,!0),fetchStatus:e=>ma(Sa(pi.signal,e)),getCanonicalRevision:()=>It,onError:gg,reconcile:()=>rg($r)}),Qn=sm({connectEvents:pa,invalidate:()=>it.invalidate(),isDisposed:()=>B,maxDelayMs:zm,minDelayMs:jm,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});await Xn(!1);_a();Aa(Ia(de));qr&&Qm();jr();await Bt("initial");qr||(pa(),eg());Wm();function Wm(){window.addEventListener("beforeunload",pg),window.addEventListener("hb-sdk:restart-runtime",ha),window.addEventListener("hb-sdk:refresh-storage",jr),window.addEventListener("hb-sdk:qr-open-change",la),window.addEventListener("message",Km)}function Km(e){const t=e.data;if(e.source===null||!Ie(t)||t.type!==bm||!Ie(t.detail))return;const r=t.detail;r.level!=="log"&&r.level!=="debug"&&r.level!=="info"&&r.level!=="warn"&&r.level!=="error"||!Array.isArray(r.args)||typeof r.timestamp!="number"||Zn(`console.${r.level}`,{source:"app",message:r.args.map(n=>ua(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function ua(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
93
|
-
`).slice(0,4).join(`
|
|
94
|
-
`):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function la(e){const t=e.detail?.open===!0;t!==Nt&&(Nt=t,Re+=1,zr(),et!==void 0&&window.clearInterval(et),et=void 0,t&&(x.mobileLanSelect.addEventListener("change",Ym),wa(),Ft(),de.devContext.source==="remote"&&(et=window.setInterval(()=>{hg()},$m))))}function Ym(){Nt&&Ft()}function ha(){fa("manual restart")}function fa(e){B||tt!==void 0||(re("runtime.restart",{boundary:He+1}),tt=window.setTimeout(()=>{tt=void 0,B||Bt(e)},0))}async function Bt(e){const t=++He;if(Ot=void 0,ya(e),Q.runtimeStatus="loading",Da(Ct),x.device.replaceChildren(),qr){x.device.innerHTML=`
|
|
95
|
-
<div class="browser-mock-preview">
|
|
96
|
-
<span class="browser-mock-preview__icon">UI</span>
|
|
97
|
-
<strong>Browser Mock</strong>
|
|
98
|
-
<small>mp_preview</small>
|
|
99
|
-
</div>`,Q.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=Em,x.device.appendChild(r);const n=new AbortController;Gn=n;try{const i=await If(Xm(n.signal,t));if(B||t!==He){i.dispose();return}Wn=i.dispose;const o=af({iframe:r,ports:i.ports,environment:i.environment,hostCapabilities:i.hostCapabilities,authPresentation:i.authPresentation,resolveLaunchConfiguration:async()=>(await i.resolveLaunch()).configuration,dispose:i.dispose,onReady:()=>{Q.runtimeStatus="ready",re("runtime.ready",{generation:t})},onStateChange:s=>{re("runtime.state",{generation:t,state:s})},onTrace:s=>Jm(t,s),onError:s=>{Q.runtimeStatus="error",re("runtime.error",Et(s))},onSecurityViolation:s=>re("runtime.security",Et(s)),onCapabilityTrace:s=>{re(s.method,s),s.method==="storage.setStorage"&&s.outcome==="success"&&jr()}});xe=o,await o.start()}catch(i){if(B||t!==He||n.signal.aborted)return;Q.runtimeStatus="error",re("runtime.start.failed",Et(i))}}function Qm(){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 Xm(e,t){return{signal:e,account:{async getCurrentUserId(){return(await Xn(!1,e)).user_id},async ensureAuthenticated({signal:r}){await Xn(!1,r)},onChange(r){return Ur.add(r),()=>Ur.delete(r)}},authenticatedRequest:Zm,storage:{area:"local",storage:localStorage},presentation:mm({close:async()=>{cs(),xe?.destroy(),Q.runtimeStatus="closed"},reload:()=>{!B&&t===He&&(Ot=t)},pushLog:re,getDeviceMetrics:()=>Na.value}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:r=>{document.title=r}},resolveLaunch:async()=>({configuration:dm({launchUrl:Gm,runtimePermissions:tm(Ze.runtimePermissions,Ct),...Ze.miniProgramId?{miniProgramId:Ze.miniProgramId}:{}}),hostHints:{launchKind:Ze.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:r=>cm(r)}}}function Jm(e,t){t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Ot!==e||e!==He||(Ot=void 0,fa("navigation.reload"))}async function Zm(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 wi(n?xm:Fm,{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&&it.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Xn(e,t){const r=$r,n=await ma(Sa(pi.signal,t));return va(r)?ga(n,e).status:Jn()}async function ma(e){return await(await fetch(Bm,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function ga(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<It)return{changed:!1,status:Jn()};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!==It||e.authenticated!==kt||r!==Be||n!==Kn||i!==Yn;return It=e.revision,kt=e.authenticated,Be=r,Kn=n,Yn=i,_a(),t&&o&&Ur.forEach(s=>s(Be)),{changed:o,status:Jn()}}function Jn(){return{authenticated:kt,revision:It,...kt&&Be?{user_id:Be}:{}}}function eg(){if(!(!de.csrfToken||B))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Ne=Nm({csrfToken:de.csrfToken,onDiagnostic:t=>re("channel.diagnostic",t),url:e.toString()}),Ne.subscribeUpdates((t,r)=>tg(t,r)),Ne.connect()}catch{Ne?.dispose(),Ne=void 0}}function tg(e,t){it.invalidate(e.account.revision),Eg(Ct,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Bt("status changed"):(Ct=Da(e.permissions),ng())}function pa(){if(Zt?.close(),Zt=void 0,!Be||B)return;const e=new EventSource(Vm,{withCredentials:!0});Zt=e,e.addEventListener("account-invalidated",()=>{it.invalidate()}),e.addEventListener("account-revision",()=>{it.invalidate()}),e.onopen=()=>{Qn.reset()},e.onerror=()=>{e.close(),Qn.schedule()}}async function rg(e){va(e)&&await Bt("account revision changed")}function ya(e){Xt+=1,cs(),xe?.destroy(),xe=void 0,Gn?.abort(new DOMException(e,"AbortError")),Gn=void 0,Wn?.(),Wn=void 0}async function ng(){B||(await Bt("permission changed"),!B&&await Ft())}async function yi(){const e=await fetch(Um,{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(!Ie(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Ra(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new ot;return{csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devContext:ig(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(wg):[],loginAvailable:t.loginAvailable===!0,miniProgram:fg(t.miniProgram),mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0}}function ig(e,t){return Ie(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 wi(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 wa(e=x.mobileLanSelect.options.length>0?x.mobileLanSelect.value:void 0){x.mobileLanSelect.replaceChildren();for(const t of ve){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,x.mobileLanSelect.appendChild(r)}e&&ve.some(({id:t})=>t===e)?x.mobileLanSelect.value=e:Qt&&ve.some(({id:t})=>t===Qt)?x.mobileLanSelect.value=Qt:ve[0]&&(x.mobileLanSelect.value=ve[0].id),x.mobileLanSelect.disabled=ve.length===0}async function Ft(){if(B)return;const e=++Re;zr();const t=yg();if(!t?.mobileAppQrPayload){x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="未发现可用的局域网地址";return}x.mobileQrStatus.textContent="正在生成二维码...";try{const r=await dg(t);if(e!==Re||B)return;const n=await og(r.address,r.expiresAt);if(e!==Re||B)return;const i=await zf.toDataURL(n.payload,{width:qm,margin:1});if(e!==Re||B)return;x.mobileQrImage.src=i,x.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,lg(n.expiresAt,e)}catch(r){if(e!==Re||B)return;if(r instanceof ot){ba();return}x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent=bi(r)}}async function og(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await sg(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:wm(ym({host:e.address,port:location.port,token:n.token}))}}catch{throw new ot}}async function sg(e,t){if(Xe?.addressId===e.id)return Xe;if(!Xe)return;const r=await wi(Hm,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Xe.token})});if(!r.ok)throw new ot;const n=await r.json(),i=Ie(n)?Ra({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new ot;return Xe=i,i}async function ag(e){const t=await yi(),r=cg(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return Ea(t),{...r,mobileAppQrPayload:n}}function cg(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function Ea(e){da=Ei(e),ve=e.lanAddresses,Qt=e.defaultLanAddressId,Xe=e.mobileLaunchRedirect,Aa(Ia(e)),wa()}class ot extends Error{}async function dg(e){const t=as.then(()=>ug(e));return as=t.then(()=>{},()=>{}),t}async function ug(e){const t=new URL(e.appUrl),r=new URL(Xf,location.origin),n=await wi(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:rm(Ze.runtimePermissions,Ct)})}),i=await n.json();if(!n.ok||!Ie(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await ag(e.id),expiresAt:i.expires_at}}function lg(e,t){Jt=window.setTimeout(()=>{!B&&Nt&&t===Re&&Ft()},Math.max(1e3,e-Date.now()-3e4))}async function hg(){if(!(On||B)){On=!0;try{const e=await yi();if(Ei(e)===da)return;Ea(e),Nt&&Ft()}catch(e){e instanceof ot&&ba()}finally{On=!1}}}function ba(){Re+=1,zr(),x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Ei(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 _a(){if(!kt){Q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Q.account={authenticated:!0,avatar:Yn??"",nickname:Kn||Be||"已登录"}}function Ia(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Aa(e){if(!!!e?.miniProgramId||!e){Q.miniProgram={bound:!1,iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Q.miniProgram={bound:!0,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function fg(e){if(e===null)return null;if(!Ie(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 jr(){const e=++Xt,t=xe,r=t?.diagnostics.storage;if(!r){Q.storage=[],Q.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(B||e!==Xt||t!==xe)return;Q.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Q.storageError=""}catch(n){if(B||e!==Xt||t!==xe)return;Q.storage=[],Q.storageError=bi(n)}}function mg(e,t){re("host.message",{message:e,status:t})}function gg(e){B||mg(bi(e),"error")}function re(e,t){Zn(e,t)}function pg(){B||(B=!0,window.removeEventListener("hb-sdk:restart-runtime",ha),window.removeEventListener("hb-sdk:refresh-storage",jr),window.removeEventListener("hb-sdk:qr-open-change",la),$r+=1,pi.abort(new DOMException("Browser Dev Host disposed","AbortError")),it.dispose(),He+=1,ya("Browser Dev Host disposed"),Zt?.close(),Ne?.dispose(),Ne=void 0,Qn.dispose(),Ot=void 0,tt!==void 0&&window.clearTimeout(tt),tt=void 0,zr(),et!==void 0&&window.clearInterval(et),Ur.clear())}function zr(){Jt!==void 0&&window.clearTimeout(Jt),Jt=void 0}function Sa(e,t){return t?AbortSignal.any([e,t]):e}function va(e){return!B&&e===$r}function yg(){return ve.find(({id:e})=>e===x.mobileLanSelect.value)}function wg(e){return Ie(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 Ra(e){if(!(!Ie(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 Da(e){return{networkRequest:{...e.networkRequest}}}function Eg(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function bi(e){return e instanceof Error&&e.message?e.message:"操作失败"}function Ie(e){return Object.prototype.toString.call(e)==="[object Object]"}function ft(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
|