@heybox/hb-sdk 0.8.3-alpha.2 → 0.8.3-alpha.3
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 +18 -0
- package/README.md +37 -1
- package/dist/cli-chunks/{build-lnIkF-rf.cjs → build-Dydd4Rzd.cjs} +5 -5
- package/dist/cli-chunks/{context-DAdousk7.cjs → context-DcuY0bGO.cjs} +2 -2
- package/dist/cli-chunks/{create-BrH3TKd9.cjs → create-DKVTlorM.cjs} +1 -1
- package/dist/cli-chunks/{dev-Dazm6mjQ.cjs → dev-DbrUeTqi.cjs} +9 -9
- package/dist/cli-chunks/{doctor-Dqju9vZQ.cjs → doctor-D184dg_h.cjs} +1 -1
- package/dist/cli-chunks/{index-ZxzVU017.cjs → index-BG8JJ9pA.cjs} +2 -2
- package/dist/cli-chunks/{index-Cscd6hCr.cjs → index-B_HjHK3d.cjs} +15 -15
- package/dist/cli-chunks/{index.esm-BPF3ML9J.cjs → index.esm-42g2R7qD.cjs} +7 -7
- package/dist/cli-chunks/{login-CR8vCqdL.cjs → login-D3MBcgNb.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-C0fvgvWp.cjs → project-vite-CUh6Dsv5.cjs} +1 -1
- package/dist/cli-chunks/{remote-CZBw05sT.cjs → remote-EBGDOJL3.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-CCyvzllG.cjs → runtime-gate-CE1ln9xc.cjs} +1 -1
- package/dist/cli-chunks/{runtime-permission-env-v9THnMre.cjs → runtime-permission-env-CVt4QPbX.cjs} +1 -1
- package/dist/cli-chunks/{session-UhAizNH0.cjs → session-CKuEz-ih.cjs} +1 -1
- package/dist/cli-chunks/{skill-BxL6KOYN.cjs → skill-oLEQS_U6.cjs} +2 -2
- package/dist/cli-chunks/{version-B-iUWMkU.cjs → version-BNNxfn8M.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-u03IcCCS.js +101 -0
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-B1QBmFTk.js → desktop-app-launch-EnOYLhEx.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-DWFHHorU.js → index-8YA6OLi7.js} +3 -3
- package/dist/devtools/browser-dev-host/index.html +2 -2
- package/dist/index.cjs.js +17 -1
- package/dist/index.esm.js +17 -1
- package/dist/protocol.cjs.js +9 -0
- package/dist/protocol.esm.js +9 -1
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/package.json +5 -5
- package/skill/skill.json +4 -4
- package/types/index.d.ts +2 -2
- package/types/modules/viewport/index.d.ts +33 -2
- package/types/protocol/capabilities.d.ts +1 -1
- package/types/protocol.d.ts +2 -2
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-BKVURp-m.js +0 -101
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import{H as Yi,aw as Tc,aW as Cc,K as Lc,aF as Mc,aG as kc,ak as zt,b1 as z,ab as Uc,al as js,an as xc,c as Qi,aC as Gs,a9 as Hc,as as $s,p as Fc,ay as Bc}from"./desktop-app-launch-EnOYLhEx.js";const En="auth.login",yn="user.getInfo",wn="user.revokeAuthorization",In="user.getSteamGameList",_n="share.copyLink",An="share.showShareMenu",bn="share.screenshot",We="viewport.setDisplay",Sn="viewport.getWindowInfo",On="viewport.setNavigationBarStyle",Tt="storage.getStorage",Ct="storage.setStorage",Rn="network.request",Nn="network.download",Dn="files.pickFiles",Pn="files.pickDirectory",vn="files.saveFile",Lt="file.create",Mt="file.remove",Tn="file.exists",kt="file.readText",Cn="file.writeText",Ut="file.readBytes",Ln="file.writeBytes",xt="file.stat",Mn="directory.create",Ht="directory.remove",kn="directory.exists",Un="directory.list",xn="ui.showToast",Hn="ui.showLoading",Fn="ui.hideLoading",Bn="device.vibrate",Vn="device.setClipboard",qn="navigation.close",zn="navigation.reload",jn="navigation.openAppPage",Oe="cloud.leaderboard.submit",fe="cloud.leaderboard.getList",Le="cloud.leaderboard.getCurrentUserEntry",Ke="cloud.leaderboard.deleteCurrentUserEntry",we="cloud.leaderboard.getInfo",Jn="companion.getInfo",Zn="companion.getPreparationStatus",er="companion.prepare",tr="companion.cancelPreparation",nr="companion.getActiveSession",rr="companion.launch",ir="companion.session.write",or="companion.session.closeStdin",sr="companion.session.terminate",ar="companion.session.ackOutput",cr="companion.openAttachment",dr="companion.showNotification",Me=[{method:En,module:"auth",capability:En,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:yn,module:"user",capability:yn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:wn,module:"user",capability:wn,requirement:{kind:"none"},risk:"high"},{method:In,module:"user",capability:In,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:_n,module:"share",capability:_n,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:An,module:"share",capability:An,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:bn,module:"share",capability:bn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Sn,module:"viewport",capability:Sn,requirement:{kind:"none"},risk:"low"},{method:On,module:"viewport",capability:On,requirement:{kind:"none"},risk:"low"},{method:We,module:"viewport",capability:We,requirement:{kind:"none"},risk:"low"},{method:Tt,module:"storage",capability:Tt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Ct,module:"storage",capability:Ct,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Rn,module:"network",capability:Rn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Nn,module:"network",capability:Nn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Dn,module:"files",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Pn,module:"files",capability:Pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vn,module:"files",capability:vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Lt,module:"file",capability:Lt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mt,module:"file",capability:Mt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tn,module:"file",capability:Tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kt,module:"file",capability:kt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Cn,module:"file",capability:Cn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ut,module:"file",capability:Ut,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ln,module:"file",capability:Ln,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xt,module:"file",capability:xt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"directory",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ht,module:"directory",capability:Ht,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kn,module:"directory",capability:kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Un,module:"directory",capability:Un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xn,module:"ui",capability:xn,requirement:{kind:"none"},risk:"low"},{method:Hn,module:"ui",capability:Hn,requirement:{kind:"none"},risk:"low"},{method:Fn,module:"ui",capability:Fn,requirement:{kind:"none"},risk:"low"},{method:Bn,module:"device",capability:Bn,requirement:{kind:"none"},risk:"low"},{method:Vn,module:"device",capability:Vn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:qn,module:"navigation",capability:qn,requirement:{kind:"none"},risk:"medium"},{method:zn,module:"navigation",capability:zn,requirement:{kind:"none"},risk:"medium"},{method:jn,module:"navigation",capability:jn,requirement:{kind:"none"},risk:"medium"},{method:Oe,module:"cloud",capability:Oe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:fe,module:"cloud",capability:fe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Le,module:"cloud",capability:Le,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ke,module:"cloud",capability:Ke,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:we,module:"cloud",capability:we,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[Jn,Zn,er,tr,nr,rr,ir,or,sr,ar,cr,dr].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],He="heybox:miniprogram",Ws=2,Vc="hb_mini_bridge_nonce",Ks="sdk.handshake",Xt="runtime.location.probe",qc="sdk.location.report",zc="sdk.csp.violation",Ys="operation.progress",jc="companion.session.output",Gc="companion.session.exit",$c="companion.session.ownershipLost";function Wc(e){return!xe(e)||e.namespace!==He||e.version!==1&&e.version!==2||!ee(e.nonce)?!1:e.type==="handshake"?ee(e.id)&&e.method===Ks&&e.error===void 0&&Xc(e.payload):e.type==="request"?ee(e.id)&&ee(e.method)&&e.error===void 0:e.type==="response"?ee(e.id)&&(e.method===void 0||ee(e.method))&&(e.error===void 0||Jc(e.error)):e.type==="event"?!ee(e.method)||e.error!==void 0?!1:e.method===Ys?e.version===2&&ee(e.id)&&Qc(e.payload):e.id===void 0||ee(e.id):e.type==="cancel"?e.version===2&&ee(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Ri(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Qs(e){return xe(e)?e.kind==="sandbox"?Re(e,["kind"]):e.kind==="directory"&&ee(e.handleId)&&Re(e,["kind","handleId"]):!1}function Ni(e){return!xe(e)||e.kind!=="file"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):Qs(e.root)&&Ri(e.relativePath)&&Re(e,["kind","root","relativePath"])}function Xs(e){return!xe(e)||e.kind!=="directory"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):Qs(e.root)&&(e.relativePath==="."||Ri(e.relativePath))&&Re(e,["kind","root","relativePath"])}function Js(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Kc(e){return!xe(e)||!ct(e.loaded)||typeof e.lengthComputable!="boolean"||!Re(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?ct(e.total)&&e.loaded<=e.total:e.total===void 0}function Yc(e){return xe(e)?e.phase==="downloading"?ct(e.loaded)&&(e.total===void 0||ct(e.total)&&e.loaded<=e.total)&&Re(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:ct(e.processed)&&ct(e.total)&&e.processed<=e.total&&Re(e,["phase","processed","total"]):!1}function Qc(e){return Kc(e)||Yc(e)}function Xc(e){return xe(e)&&ee(e.href)&&typeof e.userAgent=="string"&&ee(e.sdkVersion)}function Jc(e){return xe(e)&&ee(e.code)&&typeof e.message=="string"}function ct(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ee(e){return typeof e=="string"&&e.length>0}function Re(e,t){const n=new Set(t);return Object.keys(e).every(r=>n.has(r))}function xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const lt=["identity","profile","steam_account"],Zc=/^[a-z][a-z0-9-]{0,31}$/,Zs=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"],Di=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network","companion"];new Set(Di);const ed=new Set(Di);function td(e){return ed.has(e)}function Et(e){if(!Jt(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,n={};for(const r of e.entries){if(!Jt(r)||typeof r.key!="string"||!r.key.trim())return{valid:!1,permissions:{}};const i=r.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||r.status!=="enabled"&&r.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!td(o)){if(o==="network"){const s=r.config;if(!Jt(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(r.config!==null&&r.config!==void 0&&(!Jt(r.config)||Object.keys(r.config).length>0))return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{}}}}return{valid:!0,permissions:n}}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Me.map(e=>e.method);function F(e,t,n){return{code:e,message:t,data:n}}function Pi(e){return nd(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?F("RUNTIME_ERROR",e.message):F("UNKNOWN_ERROR","小程序运行时异常",e)}function nd(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function rd(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const id=1e3;function od(e,t=rd()){if(t.userActivation)return t.userActivation.isActive===!0;const n=t.lastUserInteractionAt,r=t.now??Date.now();return t.activeElement===e&&n!==void 0&&r>=n&&r-n<=id}const sd="runtime.gate.probe",ea=new Set(Me.map(e=>e.method));class ad{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Ws;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.environmentInfo=t.environmentInfo,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:He,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const n of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(n,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const n of this.operations.values())n.abort("bridge destroyed");this.operations.clear()}}postEvent(t,n){this.destroyed||this.postMessage({namespace:He,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:n})}postInternalRequest(t,n,r){this.destroyed||this.postMessage({namespace:He,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:n,method:t,payload:r})}postProgress(t,n){this.bridgeVersion===2&&this.postMessage({namespace:He,version:2,nonce:this.nonce,type:"event",id:t,method:Ys,payload:n})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const n=t.data;if(n.type==="handshake"){this.handleHandshake(n,t.origin);return}if(n.type==="request"){let r=!1;try{r=od(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{r=!1}this.handleRequest(n,r);return}if(n.type==="cancel"&&this.handshaken&&n.id){this.operations.get(n.id)?.abort();return}n.type==="event"&&this.handshaken&&this.onInternalEvent?.(n)}onUserInteraction(t){const n=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||n.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&Wc(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,n){const r=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(r)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&n&&n!=="null"&&(this.targetOrigin=n),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:He,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Ks,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(r):this.onDuplicateHandshake?.()}async handleRequest(t,n){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===sd){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,F("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!ea.has(t.method)){this.postResponse(t,void 0,F("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,F("INVALID_PARAMS","bridge request id 重复"));return}const r=new AbortController;this.operations.set(t.id,r);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===r&&this.postProgress(t.id,o)},signal:r.signal,trustedUserGesture:n});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==r)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==r)return;const o=Pi(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===r&&(this.operations.delete(t.id),r.signal.aborted||r.abort("operation terminal"))}}postResponse(t,n,r){if(!(!this.postMessage({namespace:He,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:n,error:r})||!cd(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:r?"error":"success",...r?{errorCode:r.code}:{}})}catch{}}postMessage(t){const n=this.iframe.contentWindow;return n?(n.postMessage(t,this.targetOrigin),!0):!1}}function cd(e){return typeof e=="string"&&ea.has(e)}const ta="METHOD_FORBIDDEN";function Ae(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=ta,t}class J extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",n){super(t),this.name="HostRequestUnsupportedError",n&&"cause"in n&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:n.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const Xi={[En]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[yn]:["account.getCurrentUserId","account.onChange","network.request"],[wn]:["account.getCurrentUserId","account.onChange","network.request"],[In]:["account.getCurrentUserId","account.onChange","network.request"],[_n]:["presentation.setClipboard"],[An]:["presentation.showShareMenu"],[bn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[We]:["presentation.applyOrientation"],[Sn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[On]:["presentation.setNavigationBarStyle"],[Tt]:["storage.getRaw"],[Ct]:["storage.setRaw"],[Rn]:["network.request"],[Nn]:["network.stream","files.transfer","files.access"],[Dn]:["files.external"],[Pn]:["files.external"],[vn]:["files.save"],[Lt]:["files.access"],[Mt]:["files.removeFile"],[Tn]:["files.access"],[kt]:["files.access"],[Cn]:["files.access"],[Ut]:["files.access"],[Ln]:["files.access"],[xt]:["files.access"],[Mn]:["files.access"],[Ht]:["files.removeDirectory"],[kn]:["files.access"],[Un]:["files.access"],[xn]:["presentation.showToast"],[Hn]:["presentation.showLoading"],[Fn]:["presentation.hideLoading"],[Bn]:["presentation.vibrate"],[Vn]:["presentation.setClipboard"],[qn]:["presentation.close"],[zn]:["presentation.reload"],[jn]:["presentation.openAppPage"],[Oe]:["account.getCurrentUserId","account.onChange","network.request"],[fe]:["account.onChange","network.request"],[Le]:["account.getCurrentUserId","account.onChange","network.request"],[Ke]:["account.getCurrentUserId","account.onChange","network.request"],[we]:["account.onChange","network.request"],[Jn]:["companion.getInfo"],[Zn]:["companion.getPreparationStatus"],[er]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[tr]:["companion.cancelPreparation"],[nr]:["companion.getActiveSession"],[rr]:["companion.getInfo","companion.launch"],[ir]:["companion.session.write"],[or]:["companion.session.closeStdin"],[sr]:["companion.session.terminate"],[ar]:["companion.session.ackOutput"],[cr]:["companion.openAttachment"],[dr]:["companion.showNotification"]};function dd(e,t){if(t[e]!==!0)throw Ae(e)}const ud=32*1024*1024,ld=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function fd(e){if(e.mode==="request-only")return{network:{request:(r,i)=>e.request(r,i)}};if(e.mode==="override-request")return{network:{request:(r,i)=>e.request(r,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:n}=e;return{stream:n,network:{async request(r,i){const o=await n.open(r,i);let s;try{const a=await t(o.body,{maxBytes:ud},i);return hd(o,a)}catch(a){throw s=a,a}finally{try{await n.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function hd(e,t){const n=Object.fromEntries(Object.entries(e.headers).map(([r,i])=>[r,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:n,data:md(t,pd(e,"content-type"))}}function md(e,t){gd(t);let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(r){throw new J("Host network response 不是合法 UTF-8 文本",{cause:r})}if(n.charCodeAt(0)===65279&&(n=n.slice(1)),!t||!ld.test(t)||n==="")return n;try{return JSON.parse(n)}catch{return n}}function gd(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new J(`Host network response 不支持 charset=${t}`)}function pd(e,t){return Object.entries(e.headers).find(([n])=>n.toLowerCase()===t)?.[1]?.[0]}function b(e){return typeof e=="function"}function Ji(e){return(...t)=>{throw Ae(e)}}function X(e){return async(...t)=>{throw Ae(e)}}const Ed=(e,t)=>{},yd=()=>()=>{};function wd(e){const t={request:b(e.network?.request)?e.network.request.bind(e.network):X("network.request")},n={getCurrentUserId:b(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):X("account.getCurrentUserId"),ensureAuthenticated:b(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):X("account.ensureAuthenticated"),onChange:b(e.account?.onChange)?e.account.onChange.bind(e.account):yd},r={getRaw:b(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):X("storage.getRaw"),setRaw:b(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):X("storage.setRaw")},i={...b(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...b(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:b(e.presentation?.close)?e.presentation.close.bind(e.presentation):X("presentation.close"),reload:b(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):X("presentation.reload"),openAppPage:b(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):X("presentation.openAppPage"),getViewportMetrics:b(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Ji("presentation.getViewportMetrics"),getNavigationBarHeight:b(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Ji("presentation.getNavigationBarHeight"),setNavigationBarStyle:b(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):X("presentation.setNavigationBarStyle"),showShareMenu:b(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):X("presentation.showShareMenu"),setScreenshotChromeHidden:b(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Ed,captureAndShare:b(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):X("presentation.captureAndShare"),showToast:b(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):X("presentation.showToast"),showLoading:b(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):X("presentation.showLoading"),hideLoading:b(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):X("presentation.hideLoading"),vibrate:b(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):X("presentation.vibrate"),setClipboard:b(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):X("presentation.setClipboard")},o=b(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,s=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(a=>[a,b(e.companion?.[a])?e.companion[a].bind(e.companion):X(`companion.${a}`)]));return b(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion)),{network:t,account:n,storage:r,presentation:i,companion:s,...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 Id(e){const t=_d(e.files?.sandbox),n=b(e.picker?.pickFiles)&&b(e.picker?.pickDirectory),r=b(e.picker?.saveFile),i=t||n||r||b(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":b(e.account?.getCurrentUserId),"account.ensureAuthenticated":b(e.account?.ensureAuthenticated),"account.onChange":b(e.account?.onChange),"network.request":b(e.network?.request),"network.stream":b(e.transfer?.network.open)&&b(e.transfer?.network.release),"files.sandbox":t,"files.external":n,"files.save":r,"files.access":i,"files.removeFile":b(o?.remove),"files.removeDirectory":b(e.files?.sandbox.remove),"files.transfer":b(e.transfer?.files.writeResource),"storage.getRaw":b(e.storage?.getRaw),"storage.setRaw":b(e.storage?.setRaw),"presentation.close":b(e.presentation?.close),"presentation.reload":b(e.presentation?.reload),"presentation.openAppPage":b(e.presentation?.openAppPage),"presentation.applyOrientation":b(e.presentation?.applyOrientation),"presentation.getViewportMetrics":b(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":b(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":b(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":b(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":b(e.presentation?.captureAndShare),"presentation.showToast":b(e.presentation?.showToast),"presentation.showLoading":b(e.presentation?.showLoading),"presentation.hideLoading":b(e.presentation?.hideLoading),"presentation.vibrate":b(e.presentation?.vibrate),"presentation.setClipboard":b(e.presentation?.setClipboard),"companion.getInfo":b(e.companion?.getInfo),"companion.getPreparationStatus":b(e.companion?.getPreparationStatus),"companion.prepare":b(e.companion?.prepare),"companion.cancelPreparation":b(e.companion?.cancelPreparation),"companion.getActiveSession":b(e.companion?.getActiveSession),"companion.launch":b(e.companion?.launch),"companion.session.write":b(e.companion?.write),"companion.session.closeStdin":b(e.companion?.closeStdin),"companion.session.terminate":b(e.companion?.terminate),"companion.session.ackOutput":b(e.companion?.ackOutput),"companion.openAttachment":b(e.companion?.openAttachment),"companion.showNotification":b(e.companion?.showNotification)}}function _d(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&b(t.file)&&b(t.directory)&&b(t.create)&&b(t.stat)&&b(t.list)}function Zi(e,t){return t?.[e]!==!1}function Ad(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function na(e,t={}){const n={};for(const r of Object.keys(Xi)){const o=Xi[r].every(a=>e[a]),s=!Ad(r)||!!t.miniProgramDetail?.miniProgramId.trim();n[r]=Zi(r,t.callerCapabilities)&&Zi(r,t.hostCapabilities)&&o&&s}return n}function ra(e={},t={}){const n=Id(e),r=na(n,t);return{ports:wd(e),primitiveAvailability:n,availablePrimitives:n,effectiveCapabilities:r}}function vi(e,t){if(!t||t===e.signal)return e;const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):bd(e.signal,t);return{...e,signal:n}}function bd(e,t){const n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{n.signal.aborted||(r(),n.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})),n.signal}function Sd(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"}const Od=4,Rd=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Nd=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),Dd=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Pd=["/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 vd(e,t){const n=Ld(e);return n===null||eo(n,Dd)?!0:t&&eo(n,Pd)}function Td(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Rd.some(n=>t===n||t.endsWith(`.${n}`))}function Cd(e){const t=e.trim().toLowerCase();return Nd.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Ld(e){let t=e;for(let n=0;n<Od;n+=1){let r;try{r=decodeURIComponent(t)}catch{return null}if(r===t)return to(t);t=r}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return to(t)}function eo(e,t){return t.some(n=>e===n||e.startsWith(`${n}/`))}function to(e){const t=[];for(const n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return`/${t.join("/")}`}function l(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Md(e){return typeof e=="object"&&e!==null}function ae(e,t){const n=e.data;if(!Md(n)||typeof n.status!="string")throw new Error(t);return n}const ia={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},kd={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 ae(e,"工坊小程序详情加载失败")}};function jt(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Ud(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function xd(e){const t=ae(e,"小程序登录授权接口响应异常"),n=t.result,r={};if(n.login_code&&typeof n.login_code=="object"){const i=n.login_code;r.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return n.consent_challenge&&typeof n.consent_challenge=="object"&&(r.consentChallenge=Ud(n.consent_challenge)),{...t,result:r}}const Hd={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=>({...jt(e.runtimeContext),challenge:e.challenge}),parse:e=>ae(e,"小程序授权取消接口响应异常")},Fd={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=>jt(e.runtimeContext),parse:e=>ae(e,"小程序授权撤销接口响应异常")},Bd={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=>jt(e.runtimeContext),parse(e){const t=ae(e,"小程序隔离身份接口响应异常"),n=typeof t.result.steam_id=="string"&&t.result.steam_id.trim()?t.result.steam_id.trim():void 0;return{...t,result:{appUserId:t.result.app_user_id,...n?{steamId:n}:{}}}}},Vd={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=>({...jt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>xd(e)},qd={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=>({...jt(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ae(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}};function zd(e){const t=Et(e);return t.valid&&t.permissions.network?.status==="enabled"}function oa(e,t){return t?e?"server":"local":"legacy"}function jd(e,t){return oa(zd(e),t)}function no(e,t){if(e==="server")throw l("SERVER_API_REQUIRED",`${t} 在联网模式下必须通过开发者服务端 OpenAPI 获取`)}function Gd(e,t){if(e==="local")throw l("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const $d=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Wd=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Kd=/authorization|cookie|pkey|password|secret|token/i,sa=/authorization|cookie|pkey|token|password|secret/i;function pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Yd(e){for(const t of Object.keys(e))if(!Wd.has(t))throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of $d)if(Object.prototype.hasOwnProperty.call(e,t)&&pe(e,t)!==void 0)throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(pe(e,"bodyEncoding")!==void 0&&pe(e,"bodyEncoding")!=="json"&&pe(e,"bodyEncoding")!=="form")throw new J("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(pe(e,"failurePresentation")!==void 0&&pe(e,"failurePresentation")!=="none")throw new J("endpoint failurePresentation 必须为 none");if(pe(e,"auth")!==void 0&&pe(e,"auth")!=="none"&&pe(e,"auth")!=="optional"&&pe(e,"auth")!=="required")throw new J("endpoint auth 必须为 none、optional 或 required")}function Ot(e){if(Array.isArray(e))return e.map(Ot);if(!e||typeof e!="object")return e;const t=e,n={};for(const[r,i]of Object.entries(t))Kd.test(r)||(n[r]=Ot(i));return n}function ro(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))sa.test(n)||(t[n]=r);return t}function Qd(e){if(!e)return;const t=Object.keys(e).find(n=>sa.test(n));if(t)throw new J(`endpoint 禁止声明 credential-bearing header: ${t}`)}class ft 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 aa(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class ht extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,aa(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Gt extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,aa(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Xd(e,t,n,r,i,o,s,a){return{config:{auth:e.auth,body:Ot(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:ro(o),method:e.method,metadata:{endpointId:e.id},query:Ot(r),timeout:e.timeout,url:n},data:Ot(a.data),headers:ro(a.headers)||{},status:a.status,statusText:a.statusText}}async function ur(e,t,n,r){if(!r||!r.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(r.credentials!=="heybox-session"&&r.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Yd(t),typeof t.id!="string"||!t.id)throw new J("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new J("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(n):t.path;if(typeof i!="string"||!i)throw new J("endpoint path 必须为非空字符串");const o=t.query?await t.query(n):void 0,s=t.body?await t.body(n):void 0,a=t.headers?await t.headers(n):void 0;Qd(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:r.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:r.signal,...r.miniProgramDetail===void 0?{}:{miniProgramDetail:r.miniProgramDetail}})}catch(u){throw u instanceof J?u:new ht({endpointId:t.id,cause:u})}if(c.status<200||c.status>=300)throw new ft({endpointId:t.id,status:c.status});const d=Xd(t,n,i,o,s,a,r,c);if(t.parse)try{return await t.parse(d,n)}catch(u){throw new Gt({endpointId:t.id,cause:u})}return d.data}const Jd=new Set(lt),Ti="steam_account",ca=new Set(lt.filter(e=>e!==Ti)),Zd=1e3;function eu(e){const t=new Set,n=new Map,r=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??oa(e.networkEnabled===!0,c);async function u(){if(!c)return{};if(!e.authorizationContext)throw l("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let p;try{p=await e.authorizationContext.get(e.operationContext)}catch{throw l("REQUEST_FAILED","读取 Runtime auth context 失败")}if(p.steamAccount!==c||p.userDataMode!==d)throw l("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const P=p.token.trim();if(!P)throw l("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:P}}const m=e.account.onChange(p=>{h(),f("heybox_app_login_change",{isHeyboxAppLoggedIn:!!p})});function h(){i+=1,a?.abort(),n.clear(),r.clear()}function f(p,P){for(const L of t)try{L(p,P)}catch{}}function I(){const p=e.identity.get()?.miniProgramId?.trim();if(!p)throw l("INVALID_STATE","当前能力缺少 canonical 小程序身份");return p}function E(){if(o||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function w(){E();let p;try{p=await e.account.getCurrentUserId(e.operationContext)}catch(P){throw ao(P,e.operationContext.signal,"读取小黑盒账号失败")}return typeof p=="string"&&p.trim()?p.trim():void 0}async function g(p,P){const L=await w();if(i!==P||L!==p)throw l("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function A(p){E();try{await e.account.ensureAuthenticated({trustedUserGesture:p,reason:"runtime_auth",signal:e.operationContext.signal})}catch(L){throw ao(L,e.operationContext.signal,"小黑盒登录失败")}const P=await w();if(!P)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return P}async function _(p,P,L=e.operationContext.signal){try{if(L.aborted)throw ii();return await su(ur(e.network,p,P,{...e.operationContext,credentials:"heybox-session",signal:L}),L)}catch(M){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):M instanceof J?l("REQUEST_UNSUPPORTED",M.message):M instanceof Gt?l("INVALID_RESPONSE","授权接口响应不合法"):M instanceof ht?l("REQUEST_FAILED","授权请求失败"):M instanceof ft?l("REQUEST_FAILED",M.message):da(M)?M:l("REQUEST_FAILED","授权请求失败")}}async function O(p,P){await _(Hd,{runtimeContext:{miniProgramId:p,...await u()},challenge:P}).catch(()=>{})}function x(p){const P=async()=>{const M=oo(e.operationContext.signal);a=M;try{return await p(M.signal)}finally{a===M&&(a=void 0),M.abort()}},L=s.then(P,P);return s=L.then(()=>{},()=>{}),L}async function S(p,P,L,M,U){if(!L)throw await O(p,P.challenge),l("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await O(p,P.challenge),l("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return x(async W=>{await g(M,U);const j=await C(p,P.displayedScopes,W);await g(M,U);let Q;try{Q=await e.authPresentation.confirmAuthorization({miniProgramId:p,scopes:P.displayedScopes,...j,signal:W})}catch(ne){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await g(M,U),await O(p,P.challenge),tu("REQUEST_FAILED","授权确认界面执行失败",ne))}if(await g(M,U),Q.status!=="granted")throw await O(p,P.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const K=iu(Q.grantedScopes,P.displayedScopes,c);if(!K.includes("identity"))throw await O(p,P.challenge),l("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function C(p,P,L){const M=oo(L),U=setTimeout(()=>M.abort(),Zd);try{const W=ou(e.miniProgramPresentation),[j,Q]=await Promise.all([W?Promise.resolve(W):T(p,M.signal),P.includes("profile")?R(M.signal):Promise.resolve(void 0)]);return{...j?{miniProgram:j}:{},...Q?{userProfile:Q}:{}}}finally{clearTimeout(U),M.abort()}}async function T(p,P){try{const L=e.identity.get()?.version?.trim(),M=await _(kd,{mini_program_id:p,...L?{miniprogram_version:L}:{}},P),U=tt(M,"小程序公开资料"),W=dt(U.name),j=dt(U.icon_url);return W||j?{...W?{name:W}:{},...j?{avatarUrl:j}:{}}:void 0}catch{return}}async function R(p){try{const P=await _(ia,void 0,p),L=tt(P,"账号基础信息"),M=dt(L.display_username),U=dt(L.display_avatar);return M||U?{...M?{nickname:M}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function y(p,P){if(Gd(d,"auth.login"),!c&&p.includes(Ti))throw l("INVALID_PARAMS","auth.login 参数不合法");const L=I(),M=await A(P),U=i,W=await _(Vd,{runtimeContext:{miniProgramId:L,...await u()},scopes:p});await g(M,U);const j=tt(W,"小程序登录"),Q=so(j,"loginCode"),K=so(j,"consentChallenge");if(Q===K)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ne;if(Q)ne=io(j.loginCode,c);else{const Je=nu(j.consentChallenge,c),Ze=await S(L,Je,P,M,U);await g(M,U);const Qt=await _(qd,{runtimeContext:{miniProgramId:L,...await u()},challenge:Je.challenge,selectedScopes:Ze});if(await g(M,U),ne=io(tt(Qt,"小程序登录确认"),c),ne.scopes.some(ue=>!Ze.includes(ue)))throw l("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}r.clear();for(const Je of ne.scopes)r.add(Je);return f("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),f("user_info_authorization_change",wr(r,c)),ne}async function N(p,P){const L=i,M=await _(Bd,{runtimeContext:{miniProgramId:P,...await u()}});await g(p,L);const U=ru(tt(M,"用户本地身份"),c);for(const W of c?lt:ca)r.add(W);return f("user_info_authorization_change",wr(r,c)),U}function v(p){E();const P=I(),L=`${p}\0${P}`,M=n.get(L);if(M)return M;const U=N(p,P).finally(()=>{n.get(L)===U&&n.delete(L)});return n.set(L,U),U}async function D(p){if(!p)throw l("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const P=I(),L=i,M=await w();if(!M)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await _(Fd,{runtimeContext:{miniProgramId:P,...await u()}});await g(M,L),tt(U,"用户授权撤销"),h(),f("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:y,getOrCreateLocalIdentity:v,getAuthorization:()=>wr(r,c),revoke:D,onEvent(p){return t.add(p),()=>t.delete(p)},dispose(){o||(o=!0,h(),m(),t.clear())}}}function tu(e,t,n){const r=l(e,t);return Object.defineProperty(r,"cause",{configurable:!0,enumerable:!1,value:n}),r}function tt(e,t){if(!k(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!k(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function io(e,t){if(!k(e))throw l("INVALID_RESPONSE","login code 必须是对象");const n=Gn(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!n.includes("identity"))throw l("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:n}}function nu(e,t){if(!k(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const n=Gn(e.requestedScopes,"challenge requestedScopes",t),r=Gn(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!n.length||!n.includes("identity")||!r.length||!r.includes("identity")||n.some(i=>!r.includes(i)))throw l("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:n,displayedScopes:r}}function ru(e,t){if(!k(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const n=e.appUserId.trim();if(!t)return{appUserId:n};if(e.steamId!==void 0&&typeof e.steamId!="string")throw l("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const r=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return r?{appUserId:n,steamId:r}:{appUserId:n}}function iu(e,t,n){const r=Gn(e,"授权选择 scopes",n);if(r.some(i=>!t.includes(i)))throw l("INVALID_RESPONSE","授权选择包含未展示的 scope");return r}function dt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ou(e){const t=dt(e?.name),n=dt(e?.avatarUrl);return t||n?{...t?{name:t}:{},...n?{avatarUrl:n}:{}}:void 0}function oo(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 su(e,t){return t.aborted?Promise.reject(ii()):new Promise((n,r)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>r(ii()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>n(a)),a=>o(()=>r(a)))})}function ii(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Gn(e,t,n){const r=n?Jd:ca;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!r.has(i))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function wr(e,t){const n=t?lt:lt.filter(r=>r!==Ti);return Object.fromEntries(n.map(r=>[r,e.has(r)?"granted":"not_requested"]))}function so(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function da(e){return k(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ao(e,t,n){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):da(e)?e:l("REQUEST_FAILED",n)}const au=new Set(lt);function cu(e){return{[En]:async(t,n)=>e.authorization.login(du(t),n.trustedUserGesture)}}function du(e){if(e===void 0)return["identity"];if(!k(e)||Object.keys(e).some(t=>t!=="scopes"))throw co();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!au.has(t))||new Set(e.scopes).size!==e.scopes.length)throw co();return[...e.scopes]}function co(){return l("INVALID_PARAMS","auth.login 参数不合法")}const uu={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 ae(e,"排行榜记录删除接口响应异常")}},lu={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 ae(e,"当前排行榜记录接口响应异常")}},fu={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 ae(e,"排行榜信息接口响应异常")}},hu={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 ae(e,"排行榜列表接口响应异常")}},mu={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 ae(e,"排行榜提交接口响应异常")}};function dn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function uo(e){return e instanceof J?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e){if(e.aborted)throw dn()}function q(e,t,n={}){if(t.aborted&&!n.invokeWhenAborted)return Promise.reject(dn());let r;try{r=e()}catch(i){return Promise.reject(uo(i))}return t.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(dn())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(dn()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(r).then(d=>a(()=>i(d)),d=>a(()=>o(uo(d))))})}const gu="default",pu=/^[A-Za-z0-9_-]{1,64}$/,Eu=300*1e3,yu=250,wu=3,Iu={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 _u{constructor(t){this.options=t,this.unsubscribeAccountChange=bu(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 n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(mu,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=yt(i,Oe);return this.invalidateMutableReads(this.createBucketKey(r,t.key)),Ir(o,Oe)}getList(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key),i=wt("list",t.limit,t.cursor??null);return this.read(r,"list",i,async()=>{const o=await this.request(hu,{miniProgramId:n,...t}),s=yt(o,fe);if(!Ie(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw G(`${fe} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw G(`${fe} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Ir(a,fe)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId(),i=await this.requireCurrentUser(n),o=this.createBucketKey(r,t.key),s=wt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(lu,{miniProgramId:r,...t}),c=yt(a,Le);if(!Ie(c))throw G(`${Le} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Ir(c.entry,Le)})}async deleteCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(uu,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=yt(i,Ke);if(this.invalidateMutableReads(this.createBucketKey(r,t.key)),!Ie(o)||typeof o.deleted!="boolean")throw G(`${Ke} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key);return this.read(r,"info",wt("info"),async()=>{const i=await this.request(fu,{miniProgramId:n,...t}),o=yt(i,we);if(!Ie(o)||typeof o.key!="string"||!pu.test(o.key))throw G(`${we} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw G(`${we} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw G(`${we} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw G(`${we} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,n,r,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[n],a=s?.get(r);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(r);const c=wt(t,r),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,m=o?.generation,h=i().then(f=>(this.assertAccountGeneration(u),o&&s&&o.generation===m&&(n==="list"?s.size>=yu&&s.delete(s.keys().next().value):s.clear(),s.set(r,{expiresAt:Date.now()+Eu,value:f})),f)).finally(()=>{this.inflight.get(c)?.promise===h&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:h}),h}getOrCreateBucket(t){const n=this.buckets.get(t);if(n)return n;if(this.pruneExpiredBuckets(),this.buckets.size>=wu)return;const r={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,r),r}invalidateMutableReads(t){this.invalidateInflight(t);const n=this.buckets.get(t);n&&(n.generation+=1,n.caches.list.clear(),n.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[n,r]of this.inflight)r.bucketKey===t&&this.inflight.delete(n)}pruneExpiredBuckets(){const t=Date.now();for(const[n,r]of this.buckets)fo(r,t),this.isBucketEmpty(n,r)&&this.buckets.delete(n)}removeEmptyBucket(t,n){fo(n,Date.now()),this.buckets.get(t)===n&&this.isBucketEmpty(t,n)&&this.buckets.delete(t)}isBucketEmpty(t,n){return![...this.inflight.values()].some(r=>r.bucketKey===t)&&Object.values(n.caches).every(r=>r.size===0)}async requireCurrentUser(t){this.assertUsable();let n;try{n=await q(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(r){throw mo(r)?r:ho()}if(this.assertAccountGeneration(t),typeof n!="string"||!n.trim())throw le("UNAUTHORIZED","当前用户未登录");return n.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw le("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,n){return wt(t,n??gu)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw le("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,n){this.assertUsable();const r={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await q(()=>ur(r,t,n,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw mo(i)||oi(i,"REQUEST_UNSUPPORTED")?i:i instanceof J?le("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof ht&&oi(i.cause,"INVALID_STATE")?i.cause:i instanceof ft&&(i.status===401||i.status===403)?le("UNAUTHORIZED","当前用户未登录"):i instanceof ht||i instanceof ft?ho():i instanceof Gt?G(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):G(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($(this.options.operationContext.signal),this.disposed)throw le("INVALID_STATE","Cloud capability 已释放")}}function Au(e){return new _u(e)}function bu(e,t){try{return e.onChange(t)}catch(n){if(oi(n,ta))return()=>{};throw n}}function yt(e,t){if(!Ie(e)||typeof e.status!="string")throw G(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Su(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw G(`${t} 响应缺少 result`);return e.result}function Ir(e,t){if(!Ie(e))throw G(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw G(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw G(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw G(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw G(`${t} 返回的 score 必须是有限数字`);if(!Ie(e.extra))throw G(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw G(`${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 Su(e){if(e.status==="login"||e.status==="relogin")throw le("UNAUTHORIZED",bt(e.msg)||"当前用户未登录");const t=lo(e.result)??lo(e),n=bt(t?.user_message)||bt(e.msg)||bt(t?.developer_message)||"排行榜请求失败";throw t?le(Ou(t),n,{status:e.status,sbe:t}):le("HEYBOX_API_ERROR",n,{status:e.status})}function lo(e){return Ie(e)&&Ie(e.sbe)?e.sbe:void 0}function Ou(e){const t=bt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const n=e.code;if(typeof n=="number"&&Number.isInteger(n))return Iu[n]||t||"HEYBOX_API_ERROR";if(typeof n=="string"){const r=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(n.trim());if(r?.[1])return r[1]}return t||"HEYBOX_API_ERROR"}function fo(e,t){for(const n of Object.values(e.caches))for(const[r,i]of n)i.expiresAt<=t&&n.delete(r)}function wt(...e){return JSON.stringify(e)}function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function oi(e,t){return Ie(e)&&e.code===t}function le(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function G(e){return le("INVALID_RESPONSE",e)}function ho(){return le("REQUEST_FAILED","排行榜请求失败")}function mo(e){return e instanceof Error&&e.name==="AbortError"}const Ru=/^[A-Za-z0-9_-]{1,64}$/,go=20,Nu=100,po=2048;function Du(e){const t=Au(e);return{handlers:{[Oe]:async r=>t.submit(Pu(r)),[fe]:async r=>t.getList(vu(r)),[Le]:async r=>t.getCurrentUserEntry(_r(r,Le)),[Ke]:async r=>t.deleteCurrentUserEntry(_r(r,Ke)),[we]:async r=>t.getInfo(_r(r,we))},dispose:()=>t.dispose()}}function Pu(e){const t=Ci(e,Oe,!1);if(Li(t,["key","score","extra"],Oe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw _e("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Mi(t.key,Oe),score:t.score,...t.extra===void 0?{}:{extra:Tu(t.extra)}}}function vu(e){if(e===void 0)return{limit:go};const t=Ci(e,fe,!0);Li(t,["key","limit","cursor"],fe);const n=t.limit===void 0?go:t.limit;if(typeof n!="number"||!Number.isInteger(n)||n<=0||n>Nu)throw _e("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw _e("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Mi(t.key,fe),limit:n,...t.cursor===void 0?{}:{cursor:t.cursor}}}function _r(e,t){if(e===void 0)return{};const n=Ci(e,t,!0);return Li(n,["key"],t),Mi(n.key,t)}function Ci(e,t,n){if(e===void 0&&n)return{};if(!ua(e))throw _e("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Li(e,t,n){const r=Object.keys(e).find(i=>!t.includes(i));if(r)throw _e("INVALID_PARAMS",`${n} 不支持参数 ${r}`)}function Mi(e,t){if(e===void 0)return{};if(typeof e!="string"||!Ru.test(e))throw _e("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Tu(e){if(!ua(e))throw _e("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw _e("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw _e("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>po)throw _e("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${po} 字节`);return e}function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e,t){return{code:e,message:t}}const Cu=new Set(["stdio","attachments","notifications"]),la=new Set(["windows-x64","macos-arm64"]),Lu=new Set(["unsigned","valid","invalid","unknown"]),Mu=/^[a-f0-9]{64}$/,ku=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Uu=new Set(Zs),xu=new Set([...Zs,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),fa=Object.freeze({COMPANION_UNSUPPORTED:"当前 Host 不支持 Companion",COMPANION_PREVIEW_UNSUPPORTED:"当前 Host 不支持预览 Companion",COMPANION_NOT_DECLARED:"当前版本未声明该 Companion",COMPANION_TARGET_UNSUPPORTED:"当前平台不支持该 Companion target",COMPANION_NOT_PREPARED:"Companion 尚未准备完成",COMPANION_PREPARATION_CANCELLED:"Companion 准备已取消",COMPANION_DOWNLOAD_FAILED:"Companion 下载失败",COMPANION_DESCRIPTOR_UNAVAILABLE:"Companion 授权或描述符暂不可用",COMPANION_ARCHIVE_INVALID:"Companion 归档不合法",COMPANION_INTEGRITY_FAILED:"Companion 完整性校验失败",COMPANION_ENTRYPOINT_INVALID:"Companion 入口不合法",COMPANION_USER_CANCELLED:"用户取消了 Companion 操作",COMPANION_ELEVATION_DENIED:"用户未授予 Companion 管理员权限",COMPANION_OS_BLOCKED:"操作系统安全策略阻止了 Companion",COMPANION_LAUNCH_FAILED:"Companion 启动失败",COMPANION_SESSION_VERSION_MISMATCH:"Companion Session 版本不匹配",COMPANION_SESSION_OWNERSHIP_LOST:"Companion Session 控制权已转移",COMPANION_SESSION_EXITED:"Companion Session 已退出",COMPANION_PIPE_CLOSED:"Companion 通信管道已关闭",COMPANION_OUTPUT_LIMIT:"Companion 输出超过限制",COMPANION_PROCESS_CRASHED:"Companion 进程异常退出",COMPANION_ATTACHMENT_NOT_FOUND:"Companion Attachment 不存在",COMPANION_NOTIFICATION_UNAVAILABLE:"Companion 通知不可用",COMPANION_TERMINATE_FAILED:"Companion 终止失败",PERMISSION_DENIED:"桌面辅助应用权限未启用或已撤销",USER_GESTURE_REQUIRED:"当前操作需要新的可信用户手势"});function Hu(e){const t=async(r,i,o,s)=>{const a=Fu(r);try{return await o(a,{...e.operationContext,signal:i.signal})}catch(c){throw ai(c,s)}},n=async(r,i,o)=>{if(!o.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw l("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>Bu(d,i)).catch(d=>{throw ai(d)});if((await e.companionPresentation.confirmCompanionOperation({action:r,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal})).status!=="granted")throw l("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Jn]:(r,i)=>t(r,i,async(o,s)=>si(await e.companion.getInfo(o,s),o)),[Zn]:(r,i)=>t(r,i,async(o,s)=>Eo(await e.companion.getPreparationStatus(o,s))),[er]:(r,i)=>t(r,i,async(o,s)=>{const a=Eo(await e.companion.getPreparationStatus(o,s));return a.state!=="ready"&&a.state!=="preparing"&&await n("prepare",o,i),si(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(ma(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[tr]:(r,i)=>t(r,i,(o,s)=>e.companion.cancelPreparation(o,s)),[nr]:(r,i)=>t(r,i,async(o,s)=>yo(await e.companion.getActiveSession(o,s),o)),[rr]:(r,i)=>t(r,i,async(o,s)=>{const a=yo(await e.companion.getActiveSession(o,s),o);return a||(await n("launch",o,i),ga(await e.companion.launch(o,s),o))}),[ir]:(r,i)=>nt(r,i,e,"write"),[or]:(r,i)=>nt(r,i,e,"closeStdin"),[sr]:(r,i)=>nt(r,i,e,"terminate"),[ar]:(r,i)=>nt(r,i,e,"ackOutput"),[cr]:async(r,i)=>{const o=await nt(r,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[dr]:(r,i)=>nt(r,i,e,"showNotification")}}function Fu(e){if(!k(e)||typeof e.alias!="string"||!Zc.test(e.alias))throw l("INVALID_PARAMS","Companion alias 不合法");return e.alias}async function nt(e,t,n,r){if(!k(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw l("INVALID_PARAMS","Companion Session controller 不合法");try{return await n.companion[r](Vu(e,r),{...n.operationContext,signal:t.signal})}catch(i){throw ai(i)}}function me(){throw l("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function ha(e){return!Array.isArray(e)||e.some(t=>!Cu.has(t))?me():Object.freeze([...new Set(e)])}function si(e,t){return!k(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!la.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Lu.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?me():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:ha(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Bu(e,t){const n=si(e,t);return!k(e)||e.sha256===void 0?n:typeof e.sha256!="string"||!Mu.test(e.sha256)?me():Object.freeze({...n,sha256:e.sha256})}function ma(e){return k(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):me():me()}function Eo(e){return k(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:ma(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&k(e.error)&&typeof e.error.code=="string"&&Uu.has(e.error.code)&&typeof e.error.message=="string"&&typeof e.error.retryable=="boolean"?Object.freeze({state:"failed",error:Object.freeze({code:e.error.code,message:fa[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):me():me()}function ga(e,t){return!k(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!la.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?me():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:ha(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function yo(e,t){return e===void 0?void 0:ga(e,t)}function Vu(e,t){const n=e,r={sessionId:n.sessionId,controllerGeneration:n.controllerGeneration};if(t==="write"){if(!Js(n.data))throw l("INVALID_PARAMS","Companion write data 不合法");return{...r,data:new Uint8Array(n.data)}}if(t==="ackOutput"){if(n.stream!=="stdout"&&n.stream!=="stderr"||!Number.isSafeInteger(n.sequence)||Number(n.sequence)<0)throw l("INVALID_PARAMS","Companion output ack 不合法");return{...r,stream:n.stream,sequence:n.sequence}}if(t==="openAttachment"){if(typeof n.id!="string"||!n.id)throw l("INVALID_PARAMS","Companion Attachment ID 不合法");return{...r,id:n.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(n.category)))throw l("INVALID_PARAMS","Companion notification category 不合法");return{...r,category:n.category}}return r}function qu(e){return!k(e)||!ku.has(String(e.reason))?me():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):me():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?me():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function zu(e){if(!k(e)||!k(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,n=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!Js(t.data)?void 0:{type:e.type,payload:{sessionId:n,controllerGeneration:t.controllerGeneration,stream:t.stream,sequence:t.sequence,data:new Uint8Array(t.data)}};if(e.type==="companion.session.exit")try{return{type:e.type,payload:{sessionId:n,exit:qu(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:n,controllerGeneration:t.controllerGeneration}}}function ai(e,t){return k(e)&&typeof e.code=="string"&&xu.has(e.code)?l(e.code,fa[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&k(e)&&e.name==="AbortError"?l(t,"Companion 准备已取消"):l("COMPANION_HOST_FAILED","Companion Host 操作失败")}const wo=5e3,Io=1e4;function qe(e){throw{code:"INVALID_PARAMS",message:e}}function pa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ea(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&qe(`${n} 不支持字段: ${r.join(", ")}`)}function ju(e){if(e===void 0)return{intensity:"light",delay:0};if(!pa(e))return qe("device.vibrate 参数必须是对象");Ea(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return qe("device.vibrate intensity 必须是 light、medium 或 heavy");const n=t,r=e.delay??0;return typeof r!="number"||!Number.isInteger(r)||r<0||r>wo?qe(`device.vibrate delay 必须是 0-${wo} 的整数毫秒`):{intensity:n,delay:r}}function Gu(e){return pa(e)?(Ea(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?qe("device.setClipboard text 必须是非空字符串"):e.text.length>Io?qe(`device.setClipboard text 不能超过 ${Io} 字符`):{text:e.text}):qe("device.setClipboard 参数必须是对象")}function $u(e){return{[Bn]:async t=>{$(e.operationContext.signal),await q(()=>e.presentation.vibrate(ju(t),e.operationContext),e.operationContext.signal)},[Vn]:async t=>{$(e.operationContext.signal),await q(()=>e.presentation.setClipboard(Gu(t),e.operationContext),e.operationContext.signal)}}}const Wu=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"]),Ku={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 ki(e){const t=ya(e),n=t&&Wu.has(t)?l(t,Ku[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(n,"cause",{value:e,enumerable:!1}),n}function Se(e){try{return e()}catch(t){throw ki(t)}}function ya(e){try{if(!k(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function wa(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:r,create:i?(s,a)=>e.create(s,a):ci,remove:o?s=>e.remove(s):_a,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):ci,stat:s=>e.stat(s)})}function Ia(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:r,file:a=>wa(e.file(a),r,{allowRemove:o}),directory:a=>Ia(e.directory(a),r,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):ci,remove:s?(a,c)=>e.remove(a,c):_a,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function ci(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function _a(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const _o=1024;class Yu{constructor(t,n){this.files=t,this.miniProgramDetail=n}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareFile(t,n,r),[o]=this.registerMany([i]);return Zt(i.handle,{kind:"file",handleId:o})}registerFiles(t,n="external",r,i){this.assertCanonicalDetail();const o=Se(()=>{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>_o)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw l("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],n,r))}return c}),s=this.registerMany(o);return o.map((a,c)=>Zt(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareDirectory(t,n,r),[o]=this.registerMany([i]);return bo(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ni(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const n=Xu(t);if("handleId"in n){const s=this.readDirect(n.handleId,"file");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=Ft(n.relativePath),o=this.prepareFile(Se(()=>r.hostHandle.file(i)),r.origin,r.handle.mode);return{ref:n,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const n=Ju(t);if("handleId"in n){const s=this.readDirect(n.handleId,"directory");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=n.relativePath==="."?".":Ft(n.relativePath),o=this.prepareDirectory(i==="."?r.hostHandle:Se(()=>r.hostHandle.directory(i)),r.origin,r.handle.mode,!0);return{ref:n,...o}}describeFile(t,n){return Oo(t),Zt(t,n)}describeListedEntries(t,n,r){return this.assertCanonicalDetail(),Se(()=>{if(!Array.isArray(n))throw l("FILE_IO_FAILED","Host 返回了无效目录列表");const i=n.length;if(i>r)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(n,s))throw l("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,n[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,n){return Se(()=>{if(k(n)&&n.kind==="file"){const r=this.prepareFile(n,t.origin,t.handle.mode);return Zt(r.handle,Ao(t.ref,r.handle.name))}if(k(n)&&n.kind==="directory"){const r=this.prepareDirectory(n,t.origin,t.handle.mode);return bo(r.handle,Qu(t.ref,r.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,n){this.assertCanonicalDetail();const r=$t(n),i=this.prepareFile(Se(()=>t.hostHandle.file(r)),t.origin,t.handle.mode);return{ref:Ao(t.ref,r),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,n,r){return Se(()=>{Oo(t);const i=r??t.mode;return So(t.mode,i),{handle:wa(t,i,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}prepareDirectory(t,n,r,i=!1){return Se(()=>{tl(t,i);const o=r??t.mode;return So(t.mode,o),{handle:Ia(t,o,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>_o)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const n=new Set,r=t.map(()=>{for(let i=0;i<8;i+=1){const o=Zu();if(!this.handles.has(o)&&!n.has(o))return n.add(o),o}throw l("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(r[o],i)),r}readDirect(t,n){if(!el(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const r=this.handles.get(t);if(!r)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(r.handle.kind!==n||r.hostHandle.kind!==n)throw l("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return r}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Ae("files.sandbox");return this.prepareDirectory(Se(()=>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 Ae("files")}}function Ft(e){if(!Ri(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function $t(e,t="文件名"){const n=Ft(e);if(n.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return n}function Ao(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Ft(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Qu(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Ft(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Zt(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function bo(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function So(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Xu(e){return Ni(e)||Aa(),e}function Ju(e){return Xs(e)||Aa(),e}function Aa(){throw l("INVALID_PARAMS","文件引用不合法")}function Zu(){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,n=>n.toString(16).padStart(2,"0")).join("")}function el(e){return/^[0-9a-f]{32}$/.test(e)}function Oo(e){if(!k(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");$t(e.name,"Host File name")}function tl(e,t=!1){if(!k(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&&$t(e.name,"Host Directory name")}const Ro=1e3,nl=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function rl(e){const t=n=>vi(e.operationContext,n.signal);return{files:{[Dn]:async(n,r)=>{Ar(r);const i=br(e.picker),o=il(n),s=await ie(()=>i.pickFiles(o,t(r)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Pn]:async(n,r)=>{Ar(r);const i=br(e.picker),o=ol(n),s=await ie(()=>i.pickDirectory(o,t(r)));return e.registry.registerDirectory(s,"external",o.mode)},[vn]:async(n,r)=>{Ar(r);const i=br(e.picker),o=sl(n).suggestedName,s=t(r);if(!i.saveFile)throw Ae("files.saveFile");const a=await ie(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Lt]:async(n,r)=>{const i=ce(n,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);rt(o.mode),await ie(()=>o.create(No(i),t(r)))},[Mt]:async(n,r)=>{const i=ce(n),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),rt(o.handle.mode),!o.handle.remove)throw Ae(Mt);await ie(()=>o.handle.remove(t(r)))},[Tn]:async(n,r)=>{const i=ce(n);return Do(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(r));if(!k(o)||o.kind!=="file")throw vo()})},[kt]:async(n,r)=>{const i=ce(n),o=Po(await ie(()=>e.registry.resolveFile(i.target).read(t(r))));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 文本")}},[Cn]:async(n,r)=>{const i=ce(n,["content"]);typeof i.content!="string"&&de("content 必须是字符串");const o=e.registry.resolveFile(i.target);rt(o.mode),await ie(()=>o.write(new TextEncoder().encode(i.content),t(r)))},[Ut]:async(n,r)=>{const i=ce(n),o=await ie(()=>e.registry.resolveFile(i.target).read(t(r)));return Po(o)},[Ln]:async(n,r)=>{const i=ce(n,["content"]),o=e.registry.resolveFile(i.target);rt(o.mode),await ie(()=>o.write(cl(i.content),t(r)))},[xt]:async(n,r)=>{const i=ce(n),o=await ie(()=>e.registry.resolveFile(i.target).stat(t(r)));return dl(o)}},directory:{[Mn]:async(n,r)=>{const i=ce(n,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);rt(o.mode),await ie(()=>o.create(No(i),t(r)))},[Ht]:async(n,r)=>{const i=ce(n,["recursive"]);if(k(i.target)&&i.target.relativePath===".")throw l("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),rt(o.handle.mode),!o.handle.remove)throw Ae(Ht);await ie(()=>o.handle.remove({recursive:i.recursive===void 0?!1:$n(i.recursive,"recursive")},t(r)))},[kn]:async(n,r)=>{const i=ce(n);return Do(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(r));if(!k(o)||o.kind!=="directory")throw vo()})},[Un]:async(n,r)=>{const i=ce(n,["limit"]),o=al(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ie(()=>s.handle.list({limit:o},t(r)));return e.registry.describeListedEntries(s,a,o)}}}}function il(e){if(e===void 0)return{mode:"read",multiple:!1};k(e)||de("pickFiles 参数必须是对象"),lr(e,["mode","accept","multiple"]);const t=ba(e.mode,"read"),n=e.multiple===void 0?!1:$n(e.multiple,"multiple");let r;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)))&&de("accept 必须是规范扩展名数组"),r=[...new Set(e.accept)]),{mode:t,multiple:n,...r===void 0?{}:{accept:r}}}function ol(e){return e===void 0?{mode:"read"}:(k(e)||de("pickDirectory 参数必须是对象"),lr(e,["mode"]),{mode:ba(e.mode,"read")})}function sl(e){return k(e)||de("saveFile 参数必须是对象"),lr(e,["suggestedName"]),{suggestedName:$t(e.suggestedName,"suggestedName")}}function ce(e,t=[]){return(!k(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&de("文件操作参数必须包含 target"),lr(e,["target",...t]),e}function No(e){return{recursive:e.recursive===void 0?!1:$n(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:$n(e.exclusive,"exclusive")}}function ba(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&de("mode 必须是 read 或 readwrite"),e)}function $n(e,t){return typeof e!="boolean"&&de(`${t} 必须是布尔值`),e}function al(e){if(e===void 0)return Ro;if((!Number.isSafeInteger(e)||e<=0)&&de("limit 必须是正整数"),e>Ro)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function lr(e,t){const n=Object.keys(e).filter(r=>!t.includes(r));n.length&&de(`不支持字段: ${n.join(", ")}`)}function rt(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Ar(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function br(e){if(!e)throw Ae("files.external");return e}async function Do(e){try{return await e(),!0}catch(t){if(nl.has(ya(t)??""))return!1;throw ki(t)}}async function ie(e){try{return await e()}catch(t){throw ki(t)}}function cl(e){return e instanceof Uint8Array||de("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&de("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Po(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function vo(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function dl(e){if(!k(e)||e.kind!=="file"||!ul(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!ll(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 ul(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ll(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function de(e){throw l("INVALID_PARAMS",e)}const fl=["pc","console","mobile"],hl=["game","wiki"];function Wn(e){throw{code:"INVALID_PARAMS",message:e}}function ml(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ze(e,t){return typeof e!="string"||!e.trim()?Wn(t):e.trim()}function To(e,t,n){return typeof e!="string"||!t.includes(e)?Wn(n):e}function gl(e){const t={target:"game_detail",appId:ze(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:To(e.gameType,fl,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=To(e.page,hl,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=ze(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=ze(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function pl(e){return{target:"user_detail",userId:ze(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function El(e){const t={target:"post_detail",linkId:ze(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=ze(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=ze(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function yl(e){return ml(e)?e.target==="game_detail"?gl(e):e.target==="user_detail"?pl(e):e.target==="post_detail"?El(e):Wn("navigation.openAppPage target 不支持"):Wn("navigation.openAppPage options 必须是对象")}function wl(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 Il(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function _l(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 Al(e){const t=yl(e);return t.target==="game_detail"?wl(t):t.target==="user_detail"?Il(t):_l(t)}function bl(e){throw{code:"INVALID_PARAMS",message:e}}function Co(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&bl(`${t} 不支持参数`)}function Sl(e){return{[qn]:async t=>{$(e.operationContext.signal),Co(t,"navigation.close"),await q(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[zn]:async t=>{$(e.operationContext.signal),Co(t,"navigation.reload"),await q(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[jn]:async t=>{$(e.operationContext.signal),await q(()=>e.presentation.openAppPage(Al(t),e.operationContext),e.operationContext.signal)}}}const Ol=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Rl=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Nl=new Set(["range","if-range","a-im"]),Dl=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"]),Pl=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,en={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class vl{constructor(t){this.signal=t}phase="initial";transition(t){if(en[t]<=en[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(en[this.phase]<en.committed&&this.signal.aborted)throw Ra()}normalizeHostError(t,n){return this.throwIfCancelled(),Ui(t,n,this.signal)}}async function Tl(e,t,n){const r=n.transfer,i=n.fileRegistry;if(!r||!i)throw Ae("network.download");const o=vi(n.operationContext,t.signal),s=new vl(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await kl(e,i,o)}catch(u){throw s.normalizeHostError(u,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await r.network.open(e.request,o)}catch(u){throw s.normalizeHostError(u,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const u=xl(c);Hl(c,u);const m=Fl(c.status,u);if(e.maxBytes!==void 0&&m.expectedBytes!==void 0&&m.expectedBytes>e.maxBytes)throw l("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const h=Ul(e,a,u,i);let f=0;const I=Ll(m.expectedBytes,e.maxBytes);Or(t,Sr(0,m));const E={...o,onProgress(A){!Number.isSafeInteger(A)||A<f||I!==void 0&&A>I||(f=A,Or(t,Sr(f,m)))}};s.transition("transfer"),d=!0;let w;try{w=await r.files.writeResource(h.hostHandle,c.body,{mode:h.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...m.expectedBytes===void 0?{}:{expectedBytes:m.expectedBytes}},E)}catch(A){throw s.normalizeHostError(A,"transfer")}s.transition("committed"),f=Cl(w,m,f,e.maxBytes),Or(t,Sr(f,m));const g=i.describeFile(h.handle,h.ref);return s.transition("completed"),g}finally{d||Ml(r.network,c.body)}}function Cl(e,t,n,r){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=r===void 0?n:Math.min(n,r);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(r===void 0||o<=r))return o}catch{}return i}function Ll(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Ml(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function kl(e,t,n){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return di(i.handle.mode),await $l(i.handle,n),{kind:"file",...i}}const r=t.resolveDirectoryEntry(e.to);return di(r.handle.mode),await Wl(r.handle,n),{kind:"directory",...r}}function Ul(e,t,n,r){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Vl(e,n),o=r.deriveFile(t,i);return di(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function xl(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(!k(e.headers))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[n,r]of Object.entries(e.headers)){if(n!==n.toLowerCase()||!Ol.has(n)||!Array.isArray(r)||r.length===0)throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(r.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[n]=[...r]}return t}function Hl(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:Gl(t,Rl)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Fl(e,t){const n=t["content-length"]??[],r=t["transfer-encoding"]??[];if(n.length>0&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&n.some(d=>d!=="0"))throw l("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=n.length===1&&/^(?:0|[1-9]\d*)$/.test(n[0])?Number(n[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Bl(t["content-encoding"]),a=e===204||e===205?0:r.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function Bl(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Sr(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Or(e,t){try{e.postProgress(t)}catch{}}function Vl(e,t){const n=t["content-disposition"]??[];for(const i of n){const o=ql(i);if(o&&un(o))return o}for(const i of n){const o=zl(i);if(o&&un(o))return o}if(e.suggestedName!==void 0)return Sa(e.suggestedName);const r=jl(e.url);return r&&un(r)?r:"download.bin"}function ql(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const n=t[1].trim().replace(/^"|"$/g,""),r=/^utf-8'[^']*'(.*)$/i.exec(n);if(r)try{return decodeURIComponent(r[1])}catch{return}}function zl(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 jl(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Sa(e){try{$t(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!un(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function un(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Pl.test(e))}function Gl(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>t.has(n)).map(([n,r])=>[n,r.join(", ")]))}async function $l(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="file")throw Oa()}catch(n){throw Ui(n,"file",t.signal)}}async function Wl(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="directory")throw Oa()}catch(n){throw Ui(n,"file",t.signal)}}function di(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const Kl={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 Ui(e,t,n){if(n.aborted)return Ra();const r=Yl(e);if(r&&Dl.has(r)){const o=l(r,Kl[r]??"下载失败");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 Yl(e){return k(e)&&typeof e.code=="string"?e.code:void 0}function Oa(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ra(){return l("DOWNLOAD_CANCELLED","下载已取消")}function Ql(e){if(!e)return;const t=Object.keys(e).find(n=>Nl.has(n.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const xi="withCredentials",Xl=new Set(["url","method","params","data","headers","timeout",xi]),Jl=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",xi]),Zl=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Lo=3e4,Mo=2*1024*1024,ef=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,tf=/[\u0000-\u0008\u000A-\u001F\u007F]/,nf=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,rf="network.request 不支持 multipart/form-data,请使用专用上传能力";function of(e){const t=sf(e.runtimePermissions),n=wf(e.allowedHttpOrigins);return{[Nn]:async(r,i)=>{const o=cf(r,{permission:t,allowedHttpOrigins:n});return Tl(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Rn]:async(r,i)=>{const o=vi(e.operationContext,i?.signal);$(o.signal);const s=af(r,{permission:t,allowedHttpOrigins:n});let a;try{a=await q(()=>e.network.request(s,o),o.signal)}catch(c){throw Af(c)?c:bf(c,"REQUEST_UNSUPPORTED")?H("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):H("REQUEST_FAILED","网络请求失败")}return _f(a)}}}function sf(e){const t=Et(e),n=t.permissions.network;return{enabled:t.valid&&n?.status==="enabled",useOfficialDomain:t.valid&&n?.status==="enabled"&&n.config.useOfficialDomain===!0}}function af(e,t){const n=fr(e,"network.request 参数必须是对象"),r=Object.keys(n).filter(c=>!Xl.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.request 不支持字段: ${r.join(", ")}`);Da(n,"network.request");const i=Na(n,t,"network.request"),o=uf(n.method),s=n.data;s!==void 0&&hf(s),gf(i.headers,s);const a=pf(i.headers,s,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:i.official?"official":"external",...o===void 0?{}:{method:o},...i.params===void 0?{}:{params:i.params},...s===void 0?{}:{data:s},...i.headers===void 0?{}:{headers:i.headers},...a===void 0?{}:{bodyEncoding:a},...i.timeout===void 0?{}:{timeout:i.timeout}}}function cf(e,t){const n=fr(e,"network.download 参数必须是对象"),r=Object.keys(n).filter(c=>!Jl.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.download 不支持字段: ${r.join(", ")}`);Da(n,"network.download");const i=Na(n,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw H("INVALID_PARAMS","network.download timeout 必须是有限正数");Ql(i.headers);const o=Ni(n.to),s=Xs(n.to);if(!o&&!s)throw H("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(n.suggestedName!==void 0||n.overwrite!==void 0))throw H("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(n.suggestedName!==void 0){if(typeof n.suggestedName!="string")throw H("INVALID_PARAMS","suggestedName 必须是字符串");a=Sa(n.suggestedName)}if(n.overwrite!==void 0&&typeof n.overwrite!="boolean")throw H("INVALID_PARAMS","overwrite 必须是布尔值");if(n.maxBytes!==void 0&&(!Number.isSafeInteger(n.maxBytes)||n.maxBytes<=0))throw H("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:n.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...n.overwrite===void 0?{}:{overwrite:n.overwrite},...n.maxBytes===void 0?{}:{maxBytes:n.maxBytes}}}function Na(e,t,n){const r=df(e.url,t.allowedHttpOrigins,n),i=Td(r);if(i&&!t.permission.useOfficialDomain)throw H("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(vd(r.pathname,i))throw H("PERMISSION_DENIED",`${n} 不允许访问 Runtime 或账号敏感接口`);return{url:r,official:i,params:e.params===void 0?void 0:{...fr(e.params,`${n} params 必须是对象`)},headers:e.headers===void 0?void 0:lf(e.headers,n),timeout:ff(e.timeout,n)}}function df(e,t,n="network.request"){if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);let r;try{r=new URL(e)}catch{throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);if(r.username||r.password)throw H("INVALID_PARAMS",`${n} url 不允许包含用户信息`);if(r.protocol==="http:"&&!t.has(r.origin))throw H("PERMISSION_DENIED",`${n} 生产环境只允许 HTTPS`);return r}function uf(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Zl.has(t))throw H("INVALID_PARAMS","network.request method 不合法");return t}function lf(e,t="network.request"){const n=fr(e,`${t} headers 必须是 Record<string, string>`),r={};for(const[i,o]of Object.entries(n)){const s=i.trim();if(!s||s!==i||!ef.test(s)||typeof o!="string"||tf.test(o))throw H("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Cd(s))throw H("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);r[s]=o}return r}function Da(e,t){const n=e[xi];if(n!==void 0&&typeof n!="boolean")throw H("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function ff(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw H("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Lo)throw H("INVALID_PARAMS",`${t} timeout 不能超过 ${Lo}ms`);return e}}function hf(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw H("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(mf(e)>Mo)throw H("INVALID_PARAMS",`network.request data 不能超过 ${Mo} 字节`)}function mf(e){if(typeof e=="string")return Rr(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Rr(e.toString());try{const t=JSON.stringify(e);return t?Rr(t):0}catch{throw H("INVALID_PARAMS","network.request data 必须可序列化")}}function gf(e,t){const n=Pa(e),r=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(n?.includes("multipart/form-data")||r)throw H("INVALID_PARAMS",rf)}function pf(e,t,n){if(t===void 0)return;const r=Pa(e);return r?.includes("application/x-www-form-urlencoded")?"form":r?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||n&&(Array.isArray(t)||yf(t))?"form":Ef(t)?"json":void 0}function Pa(e){return e?Object.entries(e).find(([n])=>n.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Ef(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function yf(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wf(e){const t=new Set;for(const n of e??[])try{const r=new URL(n);r.protocol==="http:"&&!r.username&&!r.password&&r.pathname==="/"&&!r.search&&!r.hash&&If(r.hostname)&&t.add(r.origin)}catch{}return t}function If(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const n=t.split(".").map(Number);return n.length!==4||n.some((r,i)=>!/^\d+$/.test(t.split(".")[i])||r<0||r>255)?!1:n[0]===127||n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}function _f(e){return Object.keys(e.headers).some(ko)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!ko(t)))}:e}function ko(e){const t=e.trim().toLowerCase();return nf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Af(e){return e instanceof Error&&e.name==="AbortError"}function bf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function fr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw H("INVALID_PARAMS",t);return e}function Rr(e){return new TextEncoder().encode(e).length}function H(e,t){return{code:e,message:t}}const tn=4294967296;function Sf(e){const t=new Of;return t.write(e),t.finish()}class Of{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<tn?(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 n=Rf(t),r=n.byteLength;if(r<32)this.writeUint8(160+r);else if(r<256)this.writeUint8(217),this.writeUint8(r);else if(r<65536)this.writeUint8(218),this.writeUint16(r);else if(r<tn)this.writeUint8(219),this.writeUint32(r);else throw new Error("share extra string is too long");this.writeBytes(n)}writeArray(t){const n=t.length;n<16?this.writeUint8(144+n):n<65536?(this.writeUint8(220),this.writeUint16(n)):(this.writeUint8(221),this.writeUint32(n));for(const r of t)this.write(r)}writeMap(t){const n=Object.keys(t),r=n.length;r<16?this.writeUint8(128+r):r<65536?(this.writeUint8(222),this.writeUint16(r)):(this.writeUint8(223),this.writeUint32(r));for(const i of n)this.writeString(i),this.write(t[i])}ensureCapacity(t){const n=this.offset+t;if(n<=this.bytes.byteLength)return;const r=new Uint8Array(Math.max(n,this.bytes.byteLength*2));r.set(this.bytes),this.bytes=r,this.view=new DataView(r.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/tn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/tn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Rf(e){const t=new Uint8Array(Nf(e));let n=0,r=0;for(;n<e.length;){let i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<e.length){const o=e.charCodeAt(n);o>=56320&&o<=57343&&(n+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[r++]=i:i<2048?(t[r++]=i>>6&31|192,t[r++]=i&63|128):i<65536?(t[r++]=i>>12&15|224,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128)}return t}function Nf(e){let t=0,n=0;for(;n<e.length;){let r=e.charCodeAt(n++);if(r<128)t+=1;else if(r<2048)t+=2;else{if(r>=55296&&r<=56319&&n<e.length){const i=e.charCodeAt(n);i>=56320&&i<=57343&&(n+=1,r=((r&1023)<<10)+(i&1023)+65536)}t+=r<65536?3:4}}return t}function Df(e){ui(e);const t=Sf(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 ui(e,t=0,n=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(n.has(e))throw new Error("extra value must not contain cycles");if(n.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)ui(o,t+1,n);n.delete(e);return}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==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)ui(o,t+1,n);n.delete(e)}function Pf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vf(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 Tf(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=vf(i);o?n.has(o)||(n.add(o),r.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:r}}function Cf(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):n.has(o)||(n.add(o),r.push(o))}return{invalidMessages:t,values:r}}function va(e,t){if(e==null)return{};if(!Pf(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const n=Tf(e.topicIds),r=Cf(e.topics),i=[...n.invalidMessages,...r.invalidMessages];let o=n.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||r.values.length?{...o.length?{topicIds:o}:{},...r.values.length?{topics:r.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function Lf(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Mf(e){try{if(Lf(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function te(e){throw{code:"INVALID_PARAMS",message:e}}function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function li(e,t){return typeof e!="string"||!e.trim()?te(t):e}function kf(e,t){const n=li(e,t);try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?te(t):n}catch{return te(t)}}function Uf(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Ta(e,t,n){const r=e.identity.get(),i=r?.miniProgramId.trim();if(!i)return te(`${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=r?.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),n!==void 0&&s.searchParams.set("extra",n),s.href}catch{return te(`${t} 缺少有效的小程序分享地址`)}}function xf(e,t){if(!Wt(e))return te("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return te("share.showShareMenu 不支持自定义 url");const n=e.channel;if(n!==void 0&&!Uf(n))return te("share.showShareMenu channel 不合法");const r=Ca(e.extra,"share.showShareMenu");return{title:li(e.title,"share.showShareMenu title 必须是非空字符串"),description:li(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Ta(t,"share.showShareMenu",r),...e.imageUrl===void 0?{}:{imageUrl:kf(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...n===void 0?{}:{channel:n}}}function Ca(e,t){if(e!==void 0)try{return Df(e)}catch{return te(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function La(e,t){return e.invalidMessage&&await q(()=>Mf(t.environment),t.operationContext.signal)?te(e.invalidMessage):e.post}function Uo(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function Hf(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Uo(t.windowWidth,0),height:Uo(t.windowHeight,0)}}function fi(e,t){const n=Number(e);return!Number.isFinite(n)||n<0?te(t):n}function xo(e,t){const n=Number(e);return!Number.isFinite(n)||n<=0?te(t):n}function Ff(e){return Wt(e)?{left:fi(e.left,"share.screenshot rect.left 必须是非负数字"),top:fi(e.top,"share.screenshot rect.top 必须是非负数字"),width:xo(e.width,"share.screenshot rect.width 必须是正数"),height:xo(e.height,"share.screenshot rect.height 必须是正数")}:te("share.screenshot rect 必须是对象")}function Bf(e,t){if(e!=null&&!Wt(e))return te("share.screenshot 参数必须是对象");const n=e??{};return n.saveToAlbum!==void 0&&typeof n.saveToAlbum!="boolean"?te("share.screenshot saveToAlbum 必须是布尔值"):{rect:n.rect===void 0?Hf(t):Ff(n.rect),...n.delay===void 0?{}:{delay:fi(n.delay,"share.screenshot delay 必须是非负数字")},...n.saveToAlbum===void 0?{}:{saveToAlbum:n.saveToAlbum}}}async function Vf(e,t){$(t.operationContext.signal);const n=xf(e,t);let r=va(e.post,{maxTopicIds:1,method:"share.showShareMenu"});n.channel&&r.post&&(r={invalidMessage:r.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await La(r,t);return q(()=>t.presentation.showShareMenu({...n,post:i},t.operationContext),t.operationContext.signal)}async function qf(e,t){if($(t.operationContext.signal),e!==void 0&&!Wt(e))return te("share.copyLink 参数必须是对象");const n=Ca(e?.extra,"share.copyLink"),r=Ta(t,"share.copyLink",n);return await q(()=>t.presentation.setClipboard({text:r},t.operationContext),t.operationContext.signal),r}async function zf(e,t){$(t.operationContext.signal);const n=Bf(e,t.presentation),r=va(Wt(e)?e.post:void 0,{method:"share.screenshot"}),i=await La(r,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=jf();let a=!1,c;try{a=!0,await q(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await q(()=>t.presentation.captureAndShare({...n,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(u){c={status:"rejected",error:u}}const d=a?await Gf(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(d)throw d;return c.value}function jf(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Gf(e,t,n){let r;try{r=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await q(()=>r,n,{invokeWhenAborted:!0})}catch(i){if(n.aborted)return i}}function $f(e){return{[_n]:(t,n)=>qf(t,e),[An]:(t,n)=>Vf(t,e),[bn]:(t,n)=>zf(t,e)}}const Wf=128,Kf=/^[A-Za-z0-9_-]+$/;function Yf(e){const t=Qf(e),n={[Tt]:async r=>{$(e.operationContext.signal);const i=Ho(r,Tt,e.storageLimits?.maxKeyLength),o=await q(()=>e.storage.getRaw(Nr(t(),i),e.operationContext),e.operationContext.signal);return{data:Fo(o)}},[Ct]:async r=>{$(e.operationContext.signal);const i=Ma(r,"storage.setStorage 参数必须是对象"),o=Ho(i,Ct,e.storageLimits?.maxKeyLength),s=Xf(i.data,e.storageLimits?.maxValueBytes);await q(()=>e.storage.setRaw(Nr(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:n,diagnostics:{getSnapshot:async()=>{$(e.operationContext.signal);let r;try{r=t()}catch{throw ke("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=Nr(r,"");return(await q(()=>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:Fo(a),serializedValue:a,bytes:ka(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:n}}function Qf(e){let t=!1,n;return()=>{if(!t){const r=e.identity.get()?.miniProgramId.trim();if(r)n=`id_${Bo(r)}`;else{const i=e.anonymousStorageScope?.trim();i&&(n=`anon_${Bo(i)}`)}t=n!==void 0}if(!n)throw ke("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return n}}function Nr(e,t){return`hb_miniprogram_${e}_${t}`}function Ho(e,t,n=Wf){const i=Ma(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw ke("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>n||!Kf.test(i))throw ke("INVALID_PARAMS",`storage key 仅支持 1-${n} 位字母、数字、下划线和连字符`);return i}function Xf(e,t){let n;try{n=JSON.stringify(e)}catch{throw ke("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof n!="string")throw ke("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&ka(n)>t)throw ke("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return n}function Fo(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Ma(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw ke("INVALID_PARAMS",t);return e}function Bo(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:Jf(e)}function Jf(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function ka(e){return new TextEncoder().encode(e).length}function ke(e,t){return{code:e,message:t}}const Vo=120;function Te(e){throw{code:"INVALID_PARAMS",message:e}}function Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ua(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&Te(`${n} 不支持字段: ${r.join(", ")}`)}function Zf(e){if(!Hi(e))return Te("ui.showToast 参数必须是对象");if(Ua(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Te("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Vo)return Te(`ui.showToast message 不能超过 ${Vo} 字符`);const n=e.status;if(n!==void 0&&n!=="success"&&n!=="error")return Te("ui.showToast status 必须是 success 或 error");const r=n;return{message:t,...r===void 0?{}:{status:r}}}function eh(e){return e===void 0?{dismissible:!1}:Hi(e)?(Ua(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Te("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Te("ui.showLoading 参数必须是对象")}function th(e){e!==void 0&&(!Hi(e)||Object.keys(e).length)&&Te("ui.hideLoading 不支持参数")}function nh(e){return{[xn]:async t=>{$(e.operationContext.signal),await q(()=>e.presentation.showToast(Zf(t),e.operationContext),e.operationContext.signal)},[Hn]:async t=>{$(e.operationContext.signal),await q(()=>e.presentation.showLoading(eh(t),e.operationContext),e.operationContext.signal)},[Fn]:async t=>{$(e.operationContext.signal),th(t),await q(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const rh={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ae(e,"当前用户首页资料接口响应异常")}},ih=3e4;function oh(e,t,n={}){const r=n.ttlMs??ih;let i=0,o,s;async function a(){let d;try{d=await ur(e,rh,void 0,{...t,credentials:"heybox-session"})}catch(u){throw t.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof J?l("REQUEST_UNSUPPORTED",u.message):u instanceof Gt?l("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof ht?l("REQUEST_FAILED","user home_v2 请求失败"):u instanceof ft?l("REQUEST_FAILED",u.message):ah(u)?u:l("REQUEST_FAILED","user home_v2 请求失败")}return sh(d,"user home_v2")}function c(d){const u=Date.now();if(o?.userId===d&&o.expiresAt>u)return Promise.resolve(o.value);if(s?.userId===d&&s.generation===i)return s.promise;const m=i,h=a().then(f=>(i===m&&(o={userId:d,value:f,expiresAt:Date.now()+r}),f)).finally(()=>{s?.promise===h&&(s=void 0)});return s={userId:d,generation:m,promise:h},h}return{get:c,clear(){i+=1,o=void 0,s=void 0}}}function sh(e,t){if(!k(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!k(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ah(e){return k(e)&&typeof e.code=="string"&&typeof e.message=="string"}const ch={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 ae(e,"Steam 游戏库接口响应异常")}},xa=20,dh=100,Ha=0,Fa="weeks",uh=100,lh=new Set(["weeks","all","achieved"]);function fh(e){const t=oh(e.network,e.operationContext),n=new Map;let r=0,i=!1;const o=e.account.onChange(()=>{r+=1,t.clear(),n.clear()}),s=e.authorization.onEvent((E,w)=>{E==="user_info_authorization_change"&&"identity"in w&&w.identity==="denied"&&(r+=1,t.clear(),n.clear())});function a(){if(i||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(){const E=e.identity.get()?.miniProgramId?.trim();if(!E)throw l("INVALID_STATE","用户能力缺少 canonical 小程序身份");return E}async function d(){a();let E;try{E=await e.account.getCurrentUserId(e.operationContext)}catch(w){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):zo(w)?w:l("REQUEST_FAILED","读取小黑盒账号失败")}return typeof E=="string"&&E.trim()?E.trim():void 0}async function u(E,w){const g=await d();if(r!==w||g!==E)throw l("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function m(E,w){try{return await ur(e.network,E,w,{...e.operationContext,credentials:"heybox-session"})}catch(g){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):g instanceof J?l("REQUEST_UNSUPPORTED",g.message):g instanceof Gt?l("INVALID_RESPONSE","用户接口响应不合法"):g instanceof ht?l("REQUEST_FAILED","用户请求失败"):g instanceof ft?l("REQUEST_FAILED",g.message):zo(g)?g:l("REQUEST_FAILED","用户请求失败")}}async function h(){c();const E=r,w=await d();if(!w)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[g,A]=await Promise.all([e.authorization.getOrCreateLocalIdentity(w),f(w)]);return await u(w,E),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:g.appUserId,profile:A,...g.steamId?{steam_id:g.steamId}:{}}}}function f(E){const w=n.get(E);if(w)return w;const g=m(ia,void 0).then(A=>{const _=qo(A,"账号基础信息");if(_.display_username!==void 0&&typeof _.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(_.display_avatar!==void 0&&typeof _.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:_.display_username??"",avatar:_.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{n.get(E)===g&&n.delete(E)});return n.set(E,g),g}async function I(E){const w=hh(E);c();const g=r,A=await d();if(!A)return{isLogin:!1,isBound:!1,data:null};const _=await t.get(A);await u(A,g);const O=Fi(_.steam_id_info);if(Object.keys(O).length===0)return{isLogin:!0,isBound:!1,data:null};const x=await m(ch,{userId:A,...w,personalInformationOpen:Ba(O.personal_infomation_open??O.personal_information_open)});await u(A,g);const S=qo(x,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:yh(S,w)}}return{getInfo:h,getSteamGameList:I,dispose(){i||(i=!0,r+=1,o(),s(),t.clear(),n.clear())}}}function hh(e){if(e==null)return{limit:xa,offset:Ha,sort:Fa,includeHidden:!1};if(!k(e))throw Ce("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(r=>!["steamId","limit","offset","sort","q","includeHidden"].includes(r));if(t)throw Ce(`user.getSteamGameList 不支持字段: ${t}`);const n={limit:mh(e.limit),offset:gh(e.offset),sort:ph(e.sort),includeHidden:Eh(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw Ce("user.getSteamGameList steamId 必须是非空字符串");n.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ce("user.getSteamGameList q 必须是字符串");const r=e.q.trim();r&&(n.q=r.slice(0,uh))}return n}function mh(e){if(e===void 0)return xa;if(!Number.isInteger(e)||Number(e)<1)throw Ce("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),dh)}function gh(e){if(e===void 0)return Ha;if(!Number.isInteger(e)||Number(e)<0)throw Ce("user.getSteamGameList offset 必须是非负整数");return Number(e)}function ph(e){if(e===void 0)return Fa;if(typeof e!="string"||!lh.has(e))throw Ce("user.getSteamGameList sort 不支持");return e}function Eh(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ce("user.getSteamGameList includeHidden 必须是 boolean");return e}function yh(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const n=e.game_list.map(wh).filter(a=>a!==void 0),r=Kn(e.total),i=t.offset+n.length,o={gameList:n,hasMore:n.length>=t.limit,nextOffset:i};r!==void 0&&(o.total=r,o.hasMore=i<r);const s=Ba(e.is_me);return s!==void 0&&(o.isMe=s),o}function wh(e){const t=Fi(e),n=Kn(t.appid),r=Kn(t.steam_appid)??n,i=Bi(t.name);if(n===void 0||r===void 0||!i)return;const o={appid:n,steamAppid:r,name:i};Rt(o,"image",t.image),Rt(o,"icon",t.appicon??t.icon),Nt(o,"playtimeForever",t.playtime_forever),Nt(o,"playtime2Weeks",t.playtime_2weeks);const s=_h(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Ih(t.price);return a&&(o.price=a),o}function Ih(e){const t=Fi(e),n={};return Rt(n,"current",t.current),Rt(n,"initial",t.initial),Nt(n,"discount",t.discount),Nt(n,"lowestPrice",t.lowest_price),Rt(n,"deadlineDate",t.deadline_date),Nt(n,"deadlineTimestamp",t.deadline_timestamp),Object.keys(n).length?n:void 0}function qo(e,t){if(!k(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!k(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Fi(e){return k(e)?e:{}}function Bi(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function _h(e){return Array.isArray(e)?e.map(Bi).filter(Boolean):[]}function Kn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Ba(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Rt(e,t,n){const r=Bi(n);r&&Object.assign(e,{[t]:r})}function Nt(e,t,n){const r=Kn(n);r!==void 0&&Object.assign(e,{[t]:r})}function Ce(e){return l("INVALID_PARAMS",e)}function zo(e){return k(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ah(e){const t=e.userDataMode??jd(e.runtimePermissions,e.steamAccount===!0);return{[yn]:async n=>(jo(n,"user.getInfo"),no(t,"user.getInfo"),e.user.getInfo()),[wn]:async(n,r)=>{jo(n,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[In]:async n=>(no(t,"user.getSteamGameList"),e.user.getSteamGameList(n))}}function jo(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}const bh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K";function Sh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","退出全屏"),t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 4px","border:0","border-radius:5px","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:rgba(57,61,64,.9)","color:#fff",'font:400 9px/12px "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)","transition:opacity .2s,transform .2s"].join(";");const n=document.createElement("img");n.src=bh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const r=document.createElement("span");r.textContent="退出全屏",r.style.whiteSpace="nowrap",t.append(n,r);let i=!0,o=!1,s=!1,a;function c(){clearTimeout(a),a=setTimeout(()=>{i=!1,t.style.opacity="0.18",t.style.transform="translate(38px, -50%)",t.setAttribute("aria-label","展开退出全屏按钮")},1e3)}function d(){i=!0,t.style.opacity="1",t.style.transform="translateY(-50%)",t.setAttribute("aria-label","退出全屏"),c()}async function u(){if(!(o||s)){if(!i){d();return}s=!0,clearTimeout(a);try{await e()}catch{}finally{s=!1,o||d()}}}return t.addEventListener("click",u),document.body.append(t),c(),{dispose(){o=!0,clearTimeout(a),t.removeEventListener("click",u),t.remove()}}}const Va=1e4;function Oh(e){const t=new AbortController;let n;const r=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",r,{once:!0}),e.aborted&&r();const i=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},Va);return{signal:t.signal,async run(o){try{return await q(o,t.signal)}catch(s){throw n??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",r)}}}function qa(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:n}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(n!==void 0&&typeof n!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&n===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:n}}function Dr(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function nn(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Rh(e){let t,n,r={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(h){if(!h.hideCapsule){s();return}o??=Sh(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(h,f){if(t===h){if(t=void 0,clearTimeout(h.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in f)h.controller.abort();else if(n={options:h.options,result:f.result},r=h.options,a(h.options),e.onApplied?.(h.options),f.result.supported&&!Dr(i,h.options)){i={...h.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:h.source})}catch{}}for(const I of h.subscribers)I.dispose(),"error"in f?I.reject(f.error):I.resolve(f.result);h.subscribers.clear()}}function d(){t&&c(t,{error:nn()})}function u(h,f){return new Promise((I,E)=>{const w=()=>{h.subscribers.delete(g),g.dispose(),E(nn()),h.subscribers.size===0&&c(h,{error:nn()})},g={resolve:I,reject:E,dispose:()=>f?.removeEventListener("abort",w)};h.subscribers.add(g),f?.addEventListener("abort",w,{once:!0}),f?.aborted&&w()})}const m={async apply(h,f,I="api"){if($(e.operationContext.signal),f?.aborted)throw nn();const E=qa(h),w=t?.options??r,g={mode:E.orientation??w.mode,hideCapsule:E.fullscreen??w.hideCapsule};g.mode==="landscape"&&(g.hideCapsule=!0);const A=e.presentation.applyOrientation;if(!A)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Dr(t.options,g))return u(t,f);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),n&&Dr(n.options,g))return n.result;n=void 0;const _={options:g,source:I,controller:new AbortController,subscribers:new Set};t=_;const O=u(_,f);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),f||(_.timer=setTimeout(()=>{c(_,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Va)),q(()=>A.call(e.presentation,g,{...e.operationContext,signal:_.controller.signal}),_.controller.signal).then(x=>c(_,{result:x??{supported:!0}}),x=>c(_,{error:x})),O},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return m}function Go(e){throw{code:"INVALID_PARAMS",message:e}}function It(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function za(e,t){const n=Number(e);return Number.isFinite(n)&&n>=0?n:t}function rn(e,t,n){return Math.min(za(e,t),n)}async function Nh(e){try{return za(await e.getNavigationBarHeight(),0)}catch{return 0}}function Dh(e,t,n,r){const i=rn(e.safeArea?.left,0,t),o=Math.max(i,rn(e.safeArea?.right,t,t)),s=rn(e.safeArea?.top,r,n),a=Math.max(s,rn(e.safeArea?.bottom,n,n));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function $o(e){const t=e.getViewportMetrics(),n=It(t.windowWidth,0),r=It(t.windowHeight,0),i=await Nh(e);return{pixelRatio:It(t.pixelRatio,1),screenWidth:It(t.screenWidth,n),screenHeight:It(t.screenHeight,r),windowWidth:n,windowHeight:r,statusBarHeight:i,safeArea:Dh(t,n,r,i),screenTop:i}}function Ph(e){const t=new AbortController,n={...e,operationContext:{...e.operationContext,signal:t.signal}};let r=!1,i=0,o,s;const a=()=>{if(r||n.operationContext.signal.aborted||!n.onViewportChange)return;const m=++i;$o(n.presentation).then(h=>{if(r||n.operationContext.signal.aborted||m!==i)return;const f=JSON.stringify(h);f!==o&&(o=f,n.onViewportChange?.(h))}).catch(()=>{})},c=Rh({...n,onApplied:a}),d=()=>{r||(r=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=n.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[We]:async(m,h)=>c.apply(m,h?.signal),[Sn]:async()=>($(n.operationContext.signal),$o(n.presentation)),[On]:async m=>{if($(n.operationContext.signal),typeof m!="object"||m===null||Array.isArray(m))return Go("viewport.setNavigationBarStyle 参数必须是对象");const h=m.foregroundStyle;if(h!=="light"&&h!=="dark")return Go("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await q(()=>n.presentation.setNavigationBarStyle(h,e.operationContext),n.operationContext.signal)}},applyOrientation:(m,h)=>c.apply({orientation:m.mode,fullscreen:m.hideCapsule},h),notifyChange:()=>{o=void 0,a()},dispose:d}}const vh=new Map(Me.map(e=>[e.method,e]));function on(e,t,n){return{code:e,message:t,...n===void 0?{}:{data:n}}}function Th(e){const t=Et(e);return n=>{if(n.requirement.kind==="none")return{allowed:!0};for(const r of n.requirement.permissions){const i=t.valid?t.permissions[r]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${r}`,data:{permission:r,method:n.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${r}`,data:{permission:r,method:n.method}}}return{allowed:!0}}}function Ch(e,t,n,r){let i;try{i=Promise.resolve(e(t,n))}catch(o){return r.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return r.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=u=>{a||(a=!0,r.removeEventListener("abort",d),u())},d=()=>c(()=>o({status:"dropped"}));r.addEventListener("abort",d,{once:!0}),i.then(u=>c(()=>o({status:"handled",value:u})),u=>c(()=>s(u)))})}function Lh(e){const t=Th(e.runtimePermissions),n=Et(e.runtimePermissions);let r=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??Mh,u=e.onTrace?d():0,m=e.onTrace?`cap_${++r}`:"",h=s===We?++i:void 0;let f;try{if(e.terminalSignal.aborted)throw on("RUNTIME_DESTROYED","小程序 Runtime 已终止");dd(s,e.effectiveCapabilities);const I=vh.get(s);if(!I)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const E=t(I),w=!E.allowed&&n.valid&&n.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!E.allowed&&!w)throw on(E.code,E.message,E.data);const g=e.handlers[s];if(!g)throw new Error(`Capability method ${s} 缺少 handler`);h!==void 0&&(f=Oh(c.signal));const A=f?{...c,signal:f.signal}:c,_=async()=>{for(const x of e.policies??[]){const S=await x.evaluate({method:s,payload:a,capability:I});if(e.terminalSignal.aborted||f?.signal.aborted)throw Yo();if(!S.allowed)throw on(S.code,S.message,S.data)}if(e.terminalSignal.aborted||f?.signal.aborted)throw Yo();if(h!==void 0){if(qa(a),h<o)throw on("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=h}return g(a,A)},O=await Ch(()=>f?f.run(_):_(),void 0,c,e.terminalSignal);return Wo(e.onTrace,Ko(m,s,a,u,O),d),O}catch(I){throw Wo(e.onTrace,Ko(m,s,a,u,{status:"error",error:I}),d),I}finally{f?.dispose()}}}}function Mh(){return typeof performance>"u"?Date.now():performance.now()}function Wo(e,t,n){if(!e)return;const r=n();try{e({...t,timestamp:r,durationMs:Math.max(0,Number.isFinite(r-t.startedAt)?r-t.startedAt:0)})}catch{}}function Ko(e,t,n,r,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:r,outcome:o,...i.status==="error"?{errorCode:kh(i.error)}:{},...Uh(t,n,i)}}function kh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Uh(e,t,n){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const r=new URL(t.url);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.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=n.status==="handled"&&ja(n.value)&&typeof n.value.status=="number"?n.value.status:void 0;return{network:{method:o,origin:r.origin,pathname:r.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function ja(e){return typeof e=="object"&&e!==null}function Yo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function xh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},n=new Yu(e.files,e.miniProgramDetail),r=rl({registry:n,picker:e.picker,operationContext:t}),i=eu({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext});let o,s,a,c=()=>{},d=()=>{};try{o=Ph({operationContext:t,presentation:e.hostPresentation,onDisplayChange:g=>e.eventSink.postEvent("display_change",g),onViewportChange:g=>e.eventSink.postEvent("viewport_change",g)}),s=fh({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),c=i.onEvent((g,A)=>e.eventSink.postEvent(g,A)),d=e.hostCompanion?.onSessionEvent?.(g=>{const A=zu(g);!e.terminalSignal.aborted&&A&&e.eventSink.postEvent(A.type,A.payload)})??(()=>{}),a=Du({account:e.account,identity:e.identity,network:e.network,operationContext:t});const u=Yf({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),m=[{name:"auth",handlers:cu({authorization:i})},{name:"user",handlers:Ah({user:s,authorization:i,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:$f({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:o.handlers},{name:"storage",handlers:u.handlers},{name:"network",handlers:of({network:e.network,transfer:e.transfer,fileRegistry:n,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:r.files},{name:"file",handlers:r.file},{name:"directory",handlers:r.directory},{name:"ui",handlers:nh({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:$u({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:Sl({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:a.handlers},{name:"companion",handlers:Hu({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:n})}],h=Hh(m);let f=!1;const I=()=>{f||(f=!0,e.terminalSignal.removeEventListener("abort",I),o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose())};e.terminalSignal.aborted?I():e.terminalSignal.addEventListener("abort",I,{once:!0});const E=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:m,handlers:h,allowsCompanionAttachmentAccess:(g,A)=>E.has(g)&&ja(A)&&n.isCompanionAttachmentRef(A.target),applyOrientation:o.applyOrientation,notifyViewportChange:o.notifyChange,...u.diagnostics?{storageDiagnostics:u.diagnostics}:{},dispose:I}}catch(u){throw o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose(),u}}function Hh(e){const t=new Map(Me.map(i=>[i.method,i.module])),n=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(n.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);n.set(a,s)}const r=Me.map(i=>i.method).filter(i=>!n.has(i));if(r.length>0)throw new Error(`Capability registry 缺少 method: ${r.join(", ")}`);if(n.size!==Me.length)throw new Error(`Capability registry method 数量不合法: ${n.size}`);return Object.freeze(Object.fromEntries(n))}const Fh="heybox-mini-dev:";function Qo(e){try{return Bh(new URL(e))}catch{return!1}}function Bh(e){return e.protocol===Fh}function Vh(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||qh(e)}function qh(e){const t=e.split(".");if(t.length!==4)return!1;const n=t.map(r=>/^\d+$/.test(r)?Number(r):Number.NaN);return n.some(r=>!Number.isInteger(r)||r<0||r>255)?!1:n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}const zh=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function jh(e,t){const n=[],r=Gh(e.environmentInfo,n),i=ln(r?.appVersion,"host.appVersion",n),o=Wh(r?.operatingSystem,n);return{info:Object.freeze({runtime:Object.freeze({mode:$h(e.sdkVersionPolicy?.releaseChannel,n)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:ln(t.miniProgramId),version:ln(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(n)}}function Gh(e,t){if(e!=null){if(Ga(e))return e;t.push("environmentInfo")}}function $h(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Wh(e,t){if(e==null)return{name:"unknown",version:null};if(!Ga(e))return t.push("operatingSystem"),{name:"unknown",version:null};const n=zh.has(e.name)?e.name:"unknown";return n==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:n,version:ln(e.version,"operatingSystem.version",t)}}function ln(e,t,n){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&n&&n.push(t),null)}function Ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Kh=1,$a="allow-scripts allow-same-origin",Yh="",Qh="no-referrer";function Xh(e=$a){return!e.split(/\s+/).includes("allow-same-origin")}function Xo(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Jh=new Set(["javascript:","data:","blob:","file:"]),Jo="xiaoheihe.cn";function Zh(e,t=window.location.href,n={}){const r=e.trim();if(!r)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(r)}catch{throw new Error("小程序链接必须是绝对 URL")}if(Jh.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!im(i,t,n))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function em(e,t){const n=new URL(e);return n.searchParams.set(Vc,t),n.toString()}function tm(e,t,n){try{const r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return!1;const o=nm(n)??rm(r.pathname);return i.pathname.startsWith(o)}catch{return!1}}function nm(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function rm(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const n=e.lastIndexOf("/");return n>=0?e.slice(0,n+1):"/"}function Zo(e){const t=new URL(e);return Vi(t)?"loopback":qi(t)?"lan":"production"}function im(e,t,n){return om(e)||Vi(e)||qi(e)&&am(t,n)}function om(e){return e.protocol==="https:"&&um(e.hostname)}function Vi(e){return e.protocol==="http:"&&sm(e.hostname)}function sm(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function qi(e){return e.protocol==="http:"&&cm(e.hostname)}function am(e,t){if(t.allowPrivateNetwork)return!0;try{const n=new URL(e);return Vi(n)||qi(n)}catch{return!1}}function cm(e){const t=dm(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function dm(e){const t=e.split(".");if(t.length!==4)return;const n=t.map(r=>{if(!/^\d+$/.test(r))return;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return n.every(r=>r!==void 0)?n:void 0}function um(e){return e===Jo||e.endsWith(`.${Jo}`)}const lm=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"]),fm=new Set(["url","inline","eval","unknown"]),hm=/^\/(?:\:segment(?:\/\:segment)*)?$/,mm=/^[a-f0-9]{64}$/,gm=255,pm=160,Em=256;function ym(e,t){const n=e;if(!n||typeof n.sdkVersion!="string"||n.sdkVersion!==t||typeof n.effectiveDirective!="string"||!lm.has(n.effectiveDirective)||typeof n.violatedDirective!="string"||n.violatedDirective.length>Em||n.violatedDirective.split(/\s/,1)[0]!==n.effectiveDirective||!["enforce","report"].includes(n.disposition??"")||typeof n.blockedResourceType!="string"||!fm.has(n.blockedResourceType)||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)||n.timestamp<0)return;const r=wm(n.blockedOrigin);if(n.blockedOrigin!==void 0&&!r)return;const i=n.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>pm||!hm.test(i)))return;const o=n.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!mm.test(o)||i===void 0)))return{effectiveDirective:n.effectiveDirective,violatedDirective:n.effectiveDirective,blockedResourceType:n.blockedResourceType,origin:r,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:n.sdkVersion,timestamp:n.timestamp}}function wm(e){if(e!==void 0&&!(typeof e!="string"||e.length>gm))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Im=/^(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 _m(e){if(!e?.minimumSdkVersion)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Be(e.minimumSdkVersion),n=e.sdkVersion?Be(e.sdkVersion):void 0;if(!t)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!n)throw F("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const r=Be("0.6.0");if(!n){if(fn(t,r)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw F("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&n.prerelease.length>0)throw F("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(fn(n,t)<0)throw F("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:fn(n,Be("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Am(e,t){if(typeof t!="string"||!Be(t))throw F("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw F("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function bm(e,t){const n=Be(e),r=Be(t);if(!(!n||!r))return fn(n,r)}function Be(e){const t=Im.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(n=>/^\d+$/.test(n)?Number(n):n)??[]}}function fn(e,t){for(const r of["major","minor","patch"])if(e[r]!==t[r])return e[r]<t[r]?-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 n=Math.max(e.prerelease.length,t.prerelease.length);for(let r=0;r<n;r+=1){const i=e.prerelease[r],o=t.prerelease[r];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 hr=["android","ios","ohos","windows","macos","linux"],Sm="0.9.0",Om=Object.freeze(["android","ios","ohos"]),Wa="该小程序暂不支持当前平台",Rm="PLATFORM_UNSUPPORTED";function Nm(e){return typeof e=="string"&&hr.includes(e)}function Dm(e){if(typeof e!="string")return;const t=e.trim().toLowerCase().replace(/[\s_-]/g,"");if(t==="android")return"android";if(t==="ios")return"ios";if(t==="ohos"||t==="harmony"||t==="harmonyos")return"ohos";if(t==="windows"||t==="win32"||t==="win64")return"windows";if(t==="mac"||t==="macos"||t==="darwin")return"macos";if(t==="linux")return"linux"}function Pm(e){const t=e.manifest;if(!Mm(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const r=ts(e.sdkVersion)??ts(t.sdkVersion);return Cm(r)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:Tm()}const n=Ka(t.platforms);return"reason"in n?{status:"invalid",reason:n.reason}:{status:"resolved",declaredPlatforms:n.platforms,effectivePlatforms:n.platforms,platformsDeclared:!0,policy:"explicit"}}function vm(e){const t=Dm(e.operatingSystemName);if(!t)return st("host_operating_system_unknown");const n=e.platformAccess;if(!n)return st("platform_access_missing",{platform:t});if(n.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:hr,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:n.reason};if(n.source==="manifest"){const s=Pm({manifest:n.manifest,...n.sdkVersion===void 0?{}:{sdkVersion:n.sdkVersion}});return s.status==="invalid"?st("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):es(t,s)}if(n.effectivePlatforms===void 0)return st("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const r=Ka(n.effectivePlatforms);if("reason"in r)return st("platform_declaration_invalid",{invalidReason:r.reason,platform:t});const i=typeof n.platformsDeclared=="boolean"?n.platformsDeclared:!0,o=Lm(n.platformPolicy)?n.platformPolicy:i?"explicit":"legacy_mobile_default";return es(t,{declaredPlatforms:i?r.platforms:[],effectivePlatforms:r.platforms,platformsDeclared:i,policy:o})}function es(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:st("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function st(e,t={}){return{status:"denied",reason:e,message:Wa,...t}}function Tm(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Om,platformsDeclared:!1,policy:"legacy_mobile_default"}}function Ka(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const n of e){if(!Nm(n))return{reason:"platform_unknown_value"};if(t.has(n))return{reason:"platform_duplicate_value"};t.add(n)}return{platforms:Object.freeze(hr.filter(n=>t.has(n)))}}function Cm(e){if(typeof e!="string"||!e.trim())return!1;const t=bm(e.trim(),Sm);return t!==void 0&&t>=0}function ts(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Lm(e){return e==="explicit"||e==="legacy_mobile_default"}function Mm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const km=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 Um(e,t,n){const r=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n,origin:i.origin,sanitizedPathname:xm(i.pathname),sanitizedPathnameHash:Hm(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n}}}function xm(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(n=>n?":segment":"").join("/")}function Hm(e){const t=new TextEncoder().encode(e),n=Math.ceil((t.length+9)/64)*64,r=new Uint8Array(n);r.set(t),r[t.length]=128,new DataView(r.buffer).setUint32(n-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(r.buffer);for(let a=0;a<n;a+=64){for(let w=0;w<16;w+=1)o[w]=s.getUint32(a+w*4,!1);for(let w=16;w<64;w+=1){const g=o[w-15],A=o[w-2],_=Ee(g,7)^Ee(g,18)^g>>>3,O=Ee(A,17)^Ee(A,19)^A>>>10;o[w]=o[w-16]+_+o[w-7]+O>>>0}let[c,d,u,m,h,f,I,E]=i;for(let w=0;w<64;w+=1){const g=E+(Ee(h,6)^Ee(h,11)^Ee(h,25))+(h&f^~h&I)+km[w]+o[w]>>>0,A=(Ee(c,2)^Ee(c,13)^Ee(c,22))+(c&d^c&u^d&u);E=I,I=f,f=h,h=m+g>>>0,m=u,u=d,d=c,c=g+A>>>0}[c,d,u,m,h,f,I,E].forEach((w,g)=>{i[g]=i[g]+w>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function Ee(e,t){return e>>>t|e<<32-t}const Fm=1e4,Pr=2e3,Bm=2,Vm="open-with-native-credential-policy",Ya="安全提示",Qa="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class qm{nonce=Xo();runtimeId=Xo();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;platformGateDecision;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;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const n=ra(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=n.ports,this.primitiveAvailability=n.primitiveAvailability,this.effectiveCapabilities=n.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const r=this.identity.miniProgramId?.trim();if(r)return{miniProgramId:r,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??Fm,this.iframeErrorListener=r=>{this.onIframeError(r)},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??F("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??F("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(Xm(),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=F("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"),this.capabilityGraph?.notifyViewportChange(),!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,n)=>{this.resolveReady=t,this.rejectReady=n})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;this.runtimePermissions=t.runtimePermissions,this.runtimeFeatures=t.runtimeFeatures,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=_m(t.sdkVersionPolicy);const n=jh(t,this.identity);if(this.environmentInfo=n.info,n.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${n.invalidFields.join(", ")}`}),this.platformGateDecision=vm({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw eg(this.platformGateDecision);if(this.miniProgramDetail=tg(t),this.effectiveCapabilities=na(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),$m(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 i=await this.confirmDevMiniProgramLaunch(r);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(Km(r)),this.launchUrl=r,this.miniProgramSrc=em(r,this.nonce),this.traceSecurityPolicy(r),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),this.primitiveAvailability["presentation.applyOrientation"]){try{await this.capabilityGraph?.applyOrientation({mode:"portrait",hideCapsule:!1})}catch(o){if(this.isInactive())return;const s=Pi(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:We,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ne(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(r,i)=>{this.stateValue==="ready"&&(r!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(r!=="display_change"||this.effectiveCapabilities[We])&&this.bridgeServer?.postEvent(r,i)}};this.capabilityGraph=xh({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,hostCompanion:this.ports.companion,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins});const n=Lh({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const m={type:"capability",runtimeId:this.runtimeId,callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};Ne(this.options.onCapabilityTrace,m)}}:{}});this.bridgeServer=new ad({iframe:this.iframe,nonce:this.nonce,dispatcher:n,environmentInfo:this.environmentInfo,onHandshake:r=>this.handleBridgeHandshake(r),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:r=>{this.handleInternalBridgeEvent(r)},onResponsePosted:({method:r,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:r,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 n=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(F("IFRAME_LOAD_ERROR",n,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 Gm(t)?t:Xa(F("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const n=t?.miniProgramId?.trim();n&&(this.identity.miniProgramId=n);const r=t?.miniProgramVersion?.trim();r&&(this.identity.miniProgramVersion=r)}async normalizeLaunchUrl(t){try{const n=this.options.environment.getCurrentHref();return Zh(t,n,{allowPrivateNetwork:Qo(n)||ns(n)||await this.isDevRuntime()})}catch(n){throw F("INVALID_LAUNCH_URL",n instanceof Error?n.message:"小程序链接不合法",n)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Qm)({message:Qa,title:Ya,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Zo(t)==="production")return!1;const n=this.options.environment.getCurrentHref();return!Qo(n)&&!ns(n)}async closeAfterDevLaunchCancellation(){const t=F("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const n=new AbortController;let r;try{r=Promise.resolve(this.ports.presentation.close({signal:n.signal}))}catch{rs(),r=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 r.catch(()=>rs())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Yh),this.iframe.setAttribute("referrerpolicy",Qh),this.iframe.setAttribute("sandbox",$a)}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 n of t)try{n?.()}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),this.capabilityGraph?.notifyViewportChange(),Ne(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),this.capabilityGraph?.notifyViewportChange(),Ne(this.options.onReady,t)}handleBridgeHandshake(t){const n=this.sdkVersionDecision?.sdkVersion;if(n)try{Am(n,t?.sdkVersion)}catch(r){return this.failRuntime(r),!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(F("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>=Bm)){this.failRuntime(F("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Xt,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Pr),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Xt})}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 n=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(n),t.deferProbe||this.sendDocumentRevalidationProbe(),n}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(Xt,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Xt})}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(F("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},Pr))}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()},Pr))}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===zc){this.handleCspViolation(t.payload);return}if(t.method!==qc)return;const n=this.sdkVersionDecision?.sdkVersion;if(!n)return;const r=t.payload;if(!r||r.sdkVersion!==n){this.failRuntime(F("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(r.probeId!==void 0&&r.probeId!==this.pendingProbeId)){if(typeof r.href!="string"||!tm(this.launchUrl,r.href,this.locationBasePath)){typeof r.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",r.href),this.failRuntime(F("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}r.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 n=ym(t,this.sdkVersionDecision?.sdkVersion);n&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:n.timestamp,sdkVersion:n.sdkVersion,origin:n.origin,sanitizedPathname:n.sanitizedPathname,sanitizedPathnameHash:n.sanitizedPathnameHash,effectiveDirective:n.effectiveDirective,violatedDirective:n.violatedDirective,blockedResourceType:n.blockedResourceType})}emitSecurityViolation(t){Ne(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,n){const r=Um(t,n,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(r)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(F("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:Kh,launchUrlType:Zo(t),networkPolicy:Vm})}failRuntime(t){const n=zm(t);return this.isInactive()||(this.terminalError=n,this.terminalController.abort(n),this.postBridgeError(n),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:n.code,message:n.message}),this.setState("failed"),this.teardownIframe(n),Ne(this.options.onError,jm(n)),this.rejectReady?.(n)),n}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,Ne(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ne(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 zm(e){const t=Pi(e);return Yn(e)&&"cause"in e&&Xa(t,e.cause),t}function Xa(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function jm(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Gm(e){return Yn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Yn(e){return!!e&&typeof e=="object"}function Ne(e,t){try{e?.(t)}catch{}}function $m(e,t,n){try{e?.(t,n)}catch{}}function ns(e){try{const t=new URL(e);return t.protocol==="http:"&&Vh(t.hostname)}catch{return!1}}function Wm(e){try{return new URL(e).origin}catch{return}}function Km(e){return Xh()?"*":Wm(e)}function Ym(e){return`${Ya}
|
|
2
|
+
|
|
3
|
+
${Qa}
|
|
4
|
+
|
|
5
|
+
URL: ${e}`}function Qm(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Ym(e.url))}function rs(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Xm(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,n=typeof window>"u"?void 0:window,r=Object.freeze({protocolVersion:Ws,knownMethodCount:Me.length,supportsFileCreate:Me.some(i=>i.method===Lt),system:Jm(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:it(e?.hardwareConcurrency),maxTouchPoints:it(e?.maxTouchPoints),screen:{width:it(t?.width),height:it(t?.height)},viewport:{width:it(n?.innerWidth),height:it(n?.innerHeight),devicePixelRatio:Zm(n?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",r)}function Jm(e="",t=""){const n=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(n)?"ios":n.includes("android")?"android":/win32|win64|windows/.test(n)?"windows":/darwin|macintosh|macintel|mac os/.test(n)?"macos":/linux|x11/.test(n)?"linux":"unknown"}function it(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function Zm(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function eg(e){return F(Rm,Wa,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function tg(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const n=e.canonicalIdentity?.miniProgramVersion?.trim(),r=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...n?{version:n}:{},...r?{name:r}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function ng(e){if(!Yn(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Yn(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 qm(e)}const rg=/^(?: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,ig=new Set(["origin","referer","user-agent"]);function og(e,t){return fd({mode:"request-only",request:(n,r={signal:t.signal})=>t.run(r.signal,async i=>{const o={...r,signal:i},s=sg(n),a=await e.authenticatedRequest(s,o);return dg(a)})}).network}function sg(e){const t=ag(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function ag(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!cg(t)))}function cg(e){const t=e.trim().toLowerCase();return ig.has(t)}function dg(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:ug(e.headers)??{}}}function ug(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!lg(t)))}function lg(e){const t=e.trim().toLowerCase();return rg.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function fg(e,t,n){const r=Eg(e.presentation,t);return{account:gg(e,t,n),network:og(e,t),...e.storage===void 0?{}:{storage:pg(e,t)},...e.storage===void 0?{}:hg(e,t),...r===void 0?{}:{presentation:r}}}function hg(e,t){const n=e.storage;return typeof n.storage.key!="function"||typeof n.storage.length!="number"?{}:{storageDiagnostics:{listRaw:r=>t.run(r.signal,()=>{const i=[];for(let o=0;o<n.storage.length;o+=1){const s=n.storage.key(o);if(s===null)continue;const a=n.storage.getItem(s);a!==null&&i.push({area:n.area,key:s,value:a})}return i})}}}function mg(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:n=>{t.assertActive(),e.environment.setDocumentTitle?.(n)}}}}function gg(e,t,n){return{getCurrentUserId:r=>t.run(r.signal,i=>e.account.getCurrentUserId({signal:i})),ensureAuthenticated:r=>t.run(r.signal,i=>e.account.ensureAuthenticated({trustedUserGesture:r.trustedUserGesture,reason:r.reason,signal:i})),onChange:r=>{t.assertActive();const i=e.account.onChange(o=>{t.signal.aborted||r(o)});return n(i)}}}function pg(e,t){const n=e.storage.storage;return{getRaw:(r,i)=>t.run(i.signal,()=>{const o=n.getItem(r);return o===null?void 0:o}),setRaw:(r,i,o)=>t.run(o.signal,()=>{n.setItem(r,i)})}}function Eg(e,t){if(!e)return;const n={};return e.close&&(n.close=r=>t.run(r.signal,i=>e.close({signal:i}))),e.reload&&(n.reload=r=>t.run(r.signal,i=>e.reload({signal:i}))),e.openAppPage&&(n.openAppPage=(r,i)=>t.run(i.signal,o=>e.openAppPage(r,{signal:o}))),e.applyOrientation&&(n.applyOrientation=(r,i)=>t.run(i.signal,o=>e.applyOrientation(r,{...i,signal:o}))),e.onViewportChange&&(n.onViewportChange=r=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||r()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),e.getViewportMetrics&&(n.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(n.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(n.setNavigationBarStyle=(r,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(r,{signal:o}))),e.showShareMenu&&(n.showShareMenu=(r,i)=>t.run(i.signal,o=>e.showShareMenu(r,{signal:o}))),e.setScreenshotChromeHidden&&(n.setScreenshotChromeHidden=(r,i)=>Sd(i)?e.setScreenshotChromeHidden(r,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(r,{signal:o}))),e.captureAndShare&&(n.captureAndShare=(r,i)=>t.run(i.signal,o=>e.captureAndShare(r,{signal:o}))),e.showToast&&(n.showToast=(r,i)=>t.run(i.signal,o=>e.showToast(r,{signal:o}))),e.showLoading&&(n.showLoading=(r,i)=>t.run(i.signal,o=>e.showLoading(r,{signal:o}))),e.hideLoading&&(n.hideLoading=r=>t.run(r.signal,i=>e.hideLoading({signal:i}))),e.vibrate&&(n.vibrate=(r,i)=>t.run(i.signal,o=>e.vibrate(r,{signal:o}))),e.setClipboard&&(n.setClipboard=(r,i)=>t.run(i.signal,o=>e.setClipboard(r,{signal:o}))),Object.keys(n).length===0?void 0:n}function yg(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const n=[e.signal,t].find(r=>r?.aborted);if(n)throw sn(n.reason)},run:async(t,n)=>{const r=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=r.find(u=>u.aborted);if(i)throw sn(i.reason);const o=new AbortController;let s;const a=new Promise((u,m)=>{s=m}),c=r.map(u=>{const m=()=>{o.signal.aborted||o.abort(u.reason),s(sn(u.reason))};return u.addEventListener("abort",m,{once:!0}),{listener:m,source:u}});let d;try{d=Promise.resolve(n(o.signal))}catch(u){d=Promise.reject(u)}try{const u=await Promise.race([d,a]),m=r.find(h=>h.aborted);if(m)throw sn(m.reason);return u}finally{for(const{listener:u,source:m}of c)m.removeEventListener("abort",u)}}}}function sn(e){return new DOMException("Web Host operation aborted","AbortError")}async function wg(e){const t=yg(),n=new Set;let r=!1;const i=m=>{if(r||t.signal.aborted)return vr(m),()=>{};let h=!0;const f=()=>{h&&(h=!1,n.delete(f),vr(m))};return n.add(f),f},o=()=>s(e.signal.reason),s=m=>{if(!r){r=!0,e.signal.removeEventListener("abort",o),t.abort(m);for(const h of[...n])h();e.onDispose&&vr(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=fg(e,t,i),c=ra(a,{hostCapabilities:e.hostCapabilities}),d=mg(e,t);let u;return{platform:"web",ports:a,environment:d,resolveLaunch:()=>(u??=t.run(void 0,async m=>e.resolveLaunch(m)),u),...e.authPresentation===void 0?{}:{authPresentation:Ig(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function vr(e){try{e()}catch{}}function Ig(e,t){return{confirmAuthorization:n=>t.run(n.signal,r=>e.confirmAuthorization({...n,signal:r}))}}var ot={},Tr,is;function _g(){return is||(is=1,Tr=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Tr}var Cr={},De={},os;function Ye(){if(os)return De;os=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 De.getSymbolSize=function(r){if(!r)throw new Error('"version" cannot be null or undefined');if(r<1||r>40)throw new Error('"version" should be in range from 1 to 40');return r*4+17},De.getSymbolTotalCodewords=function(r){return t[r]},De.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},De.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');e=r},De.isKanjiModeEnabled=function(){return typeof e<"u"},De.toSJIS=function(r){return e(r)},De}var Lr={},ss;function zi(){return ss||(ss=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.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: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,i){if(e.isValid(r))return r;try{return t(r)}catch{return i}}})(Lr)),Lr}var Mr,as;function Ag(){if(as)return Mr;as=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const n=Math.floor(t/8);return(this.buffer[n]>>>7-t%8&1)===1},put:function(t,n){for(let r=0;r<n;r++)this.putBit((t>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Mr=e,Mr}var kr,cs;function bg(){if(cs)return kr;cs=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,n,r,i){const o=t*this.size+n;this.data[o]=r,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,n){return this.data[t*this.size+n]},e.prototype.xor=function(t,n,r){this.data[t*this.size+n]^=r},e.prototype.isReserved=function(t,n){return this.reservedBit[t*this.size+n]},kr=e,kr}var Ur={},ds;function Sg(){return ds||(ds=1,(function(e){const t=Ye().getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const i=Math.floor(r/7)+2,o=t(r),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(r){const i=[],o=e.getRowColCoords(r),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}})(Ur)),Ur}var xr={},us;function Og(){if(us)return xr;us=1;const e=Ye().getSymbolSize,t=7;return xr.getPositions=function(r){const i=e(r);return[[0,0],[i-t,0],[0,i-t]]},xr}var Hr={},ls;function Rg(){return ls||(ls=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,d=null,u=null;for(let m=0;m<o;m++){a=c=0,d=u=null;for(let h=0;h<o;h++){let f=i.get(m,h);f===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=f,a=1),f=i.get(h,m),f===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=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 d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=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 n(r,i,o){switch(r){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:"+r)}}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,n(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})(Hr)),Hr}var an={},fs;function Ja(){if(fs)return an;fs=1;const e=zi(),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],n=[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 an.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}},an.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return n[(i-1)*4+0];case e.M:return n[(i-1)*4+1];case e.Q:return n[(i-1)*4+2];case e.H:return n[(i-1)*4+3];default:return}},an}var Fr={},_t={},hs;function Ng(){if(hs)return _t;hs=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let r=1;for(let i=0;i<255;i++)e[i]=r,t[r]=i,r<<=1,r&256&&(r^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),_t.log=function(r){if(r<1)throw new Error("log("+r+")");return t[r]},_t.exp=function(r){return e[r]},_t.mul=function(r,i){return r===0||i===0?0:e[t[r]+t[i]]},_t}var ms;function Dg(){return ms||(ms=1,(function(e){const t=Ng();e.mul=function(r,i){const o=new Uint8Array(r.length+i.length-1);for(let s=0;s<r.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(r[s],i[a]);return o},e.mod=function(r,i){let o=new Uint8Array(r);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(r){let i=new Uint8Array([1]);for(let o=0;o<r;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(Fr)),Fr}var Br,gs;function Pg(){if(gs)return Br;gs=1;const e=Dg();function t(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(r){this.degree=r,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(r.length+this.degree);i.set(r);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},Br=t,Br}var Vr={},qr={},zr={},ps;function Za(){return ps||(ps=1,zr.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),zr}var ye={},Es;function ec(){if(Es)return ye;Es=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
|
|
6
|
+
]))+`;ye.KANJI=new RegExp(n,"g"),ye.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ye.BYTE=new RegExp(r,"g"),ye.NUMERIC=new RegExp(e,"g"),ye.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+n+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ye.testKanji=function(c){return i.test(c)},ye.testNumeric=function(c){return o.test(c)},ye.testAlphanumeric=function(c){return s.test(c)},ye}var ys;function Qe(){return ys||(ys=1,(function(e){const t=Za(),n=ec();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 n.testNumeric(o)?e.NUMERIC:n.testAlphanumeric(o)?e.ALPHANUMERIC:n.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 r(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 r(o)}catch{return s}}})(qr)),qr}var ws;function vg(){return ws||(ws=1,(function(e){const t=Ye(),n=Ja(),r=zi(),i=Qe(),o=Za(),s=7973,a=t.getBCHDigit(s);function c(h,f,I){for(let E=1;E<=40;E++)if(f<=e.getCapacity(E,I,h))return E}function d(h,f){return i.getCharCountIndicator(h,f)+4}function u(h,f){let I=0;return h.forEach(function(E){const w=d(E.mode,f);I+=w+E.getBitsLength()}),I}function m(h,f){for(let I=1;I<=40;I++)if(u(h,I)<=e.getCapacity(I,f,i.MIXED))return I}e.from=function(f,I){return o.isValid(f)?parseInt(f,10):I},e.getCapacity=function(f,I,E){if(!o.isValid(f))throw new Error("Invalid QR Code version");typeof E>"u"&&(E=i.BYTE);const w=t.getSymbolTotalCodewords(f),g=n.getTotalCodewordsCount(f,I),A=(w-g)*8;if(E===i.MIXED)return A;const _=A-d(E,f);switch(E){case i.NUMERIC:return Math.floor(_/10*3);case i.ALPHANUMERIC:return Math.floor(_/11*2);case i.KANJI:return Math.floor(_/13);case i.BYTE:default:return Math.floor(_/8)}},e.getBestVersionForData=function(f,I){let E;const w=r.from(I,r.M);if(Array.isArray(f)){if(f.length>1)return m(f,w);if(f.length===0)return 1;E=f[0]}else E=f;return c(E.mode,E.getLength(),w)},e.getEncodedBits=function(f){if(!o.isValid(f)||f<7)throw new Error("Invalid QR Code version");let I=f<<12;for(;t.getBCHDigit(I)-a>=0;)I^=s<<t.getBCHDigit(I)-a;return f<<12|I}})(Vr)),Vr}var jr={},Is;function Tg(){if(Is)return jr;Is=1;const e=Ye(),t=1335,n=21522,r=e.getBCHDigit(t);return jr.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-r>=0;)c^=t<<e.getBCHDigit(c)-r;return(a<<10|c)^n},jr}var Gr={},$r,_s;function Cg(){if(_s)return $r;_s=1;const e=Qe();function t(n){this.mode=e.NUMERIC,this.data=n.toString()}return t.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%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(r){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),r.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),r.put(s,a*3+1))},$r=t,$r}var Wr,As;function Lg(){if(As)return Wr;As=1;const e=Qe(),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 n(r){this.mode=e.ALPHANUMERIC,this.data=r}return n.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.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)},Wr=n,Wr}var Kr,bs;function Mg(){if(bs)return Kr;bs=1;const e=Qe();function t(n){this.mode=e.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return t.getBitsLength=function(r){return r*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){for(let r=0,i=this.data.length;r<i;r++)n.put(this.data[r],8)},Kr=t,Kr}var Yr,Ss;function kg(){if(Ss)return Yr;Ss=1;const e=Qe(),t=Ye();function n(r){this.mode=e.KANJI,this.data=r}return n.getBitsLength=function(i){return i*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(r){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),r.put(o,13)}},Yr=n,Yr}var Qr={exports:{}},Os;function Ug(){return Os||(Os=1,(function(e){var t={single_source_shortest_paths:function(n,r,i){var o={},s={};s[r]=0;var a=t.PriorityQueue.make();a.push(r,0);for(var c,d,u,m,h,f,I,E,w;!a.empty();){c=a.pop(),d=c.value,m=c.cost,h=n[d]||{};for(u in h)h.hasOwnProperty(u)&&(f=h[u],I=m+f,E=s[u],w=typeof s[u]>"u",(w||E>I)&&(s[u]=I,a.push(u,I),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var g=["Could not find a path from ",r," to ",i,"."].join("");throw new Error(g)}return o},extract_shortest_path_from_predecessor_list:function(n,r){for(var i=[],o=r;o;)i.push(o),n[o],o=n[o];return i.reverse(),i},find_path:function(n,r,i){var o=t.single_source_shortest_paths(n,r,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,i={},o;n=n||{};for(o in r)r.hasOwnProperty(o)&&(i[o]=r[o]);return i.queue=[],i.sorter=n.sorter||r.default_sorter,i},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var i={value:n,cost:r};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})(Qr)),Qr.exports}var Rs;function xg(){return Rs||(Rs=1,(function(e){const t=Qe(),n=Cg(),r=Lg(),i=Mg(),o=kg(),s=ec(),a=Ye(),c=Ug();function d(g){return unescape(encodeURIComponent(g)).length}function u(g,A,_){const O=[];let x;for(;(x=g.exec(_))!==null;)O.push({data:x[0],index:x.index,mode:A,length:x[0].length});return O}function m(g){const A=u(s.NUMERIC,t.NUMERIC,g),_=u(s.ALPHANUMERIC,t.ALPHANUMERIC,g);let O,x;return a.isKanjiModeEnabled()?(O=u(s.BYTE,t.BYTE,g),x=u(s.KANJI,t.KANJI,g)):(O=u(s.BYTE_KANJI,t.BYTE,g),x=[]),A.concat(_,O,x).sort(function(C,T){return C.index-T.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.length}})}function h(g,A){switch(A){case t.NUMERIC:return n.getBitsLength(g);case t.ALPHANUMERIC:return r.getBitsLength(g);case t.KANJI:return o.getBitsLength(g);case t.BYTE:return i.getBitsLength(g)}}function f(g){return g.reduce(function(A,_){const O=A.length-1>=0?A[A.length-1]:null;return O&&O.mode===_.mode?(A[A.length-1].data+=_.data,A):(A.push(_),A)},[])}function I(g){const A=[];for(let _=0;_<g.length;_++){const O=g[_];switch(O.mode){case t.NUMERIC:A.push([O,{data:O.data,mode:t.ALPHANUMERIC,length:O.length},{data:O.data,mode:t.BYTE,length:O.length}]);break;case t.ALPHANUMERIC:A.push([O,{data:O.data,mode:t.BYTE,length:O.length}]);break;case t.KANJI:A.push([O,{data:O.data,mode:t.BYTE,length:d(O.data)}]);break;case t.BYTE:A.push([{data:O.data,mode:t.BYTE,length:d(O.data)}])}}return A}function E(g,A){const _={},O={start:{}};let x=["start"];for(let S=0;S<g.length;S++){const C=g[S],T=[];for(let R=0;R<C.length;R++){const y=C[R],N=""+S+R;T.push(N),_[N]={node:y,lastCount:0},O[N]={};for(let v=0;v<x.length;v++){const D=x[v];_[D]&&_[D].node.mode===y.mode?(O[D][N]=h(_[D].lastCount+y.length,y.mode)-h(_[D].lastCount,y.mode),_[D].lastCount+=y.length):(_[D]&&(_[D].lastCount=y.length),O[D][N]=h(y.length,y.mode)+4+t.getCharCountIndicator(y.mode,A))}}x=T}for(let S=0;S<x.length;S++)O[x[S]].end=0;return{map:O,table:_}}function w(g,A){let _;const O=t.getBestModeForData(g);if(_=t.from(A,O),_!==t.BYTE&&_.bit<O.bit)throw new Error('"'+g+'" cannot be encoded with mode '+t.toString(_)+`.
|
|
8
|
+
Suggested mode is: `+t.toString(O));switch(_===t.KANJI&&!a.isKanjiModeEnabled()&&(_=t.BYTE),_){case t.NUMERIC:return new n(g);case t.ALPHANUMERIC:return new r(g);case t.KANJI:return new o(g);case t.BYTE:return new i(g)}}e.fromArray=function(A){return A.reduce(function(_,O){return typeof O=="string"?_.push(w(O,null)):O.data&&_.push(w(O.data,O.mode)),_},[])},e.fromString=function(A,_){const O=m(A,a.isKanjiModeEnabled()),x=I(O),S=E(x,_),C=c.find_path(S.map,"start","end"),T=[];for(let R=1;R<C.length-1;R++)T.push(S.table[C[R]].node);return e.fromArray(f(T))},e.rawSplit=function(A){return e.fromArray(m(A,a.isKanjiModeEnabled()))}})(Gr)),Gr}var Ns;function Hg(){if(Ns)return Cr;Ns=1;const e=Ye(),t=zi(),n=Ag(),r=bg(),i=Sg(),o=Og(),s=Rg(),a=Ja(),c=Pg(),d=vg(),u=Tg(),m=Qe(),h=xg();function f(S,C){const T=S.size,R=o.getPositions(C);for(let y=0;y<R.length;y++){const N=R[y][0],v=R[y][1];for(let D=-1;D<=7;D++)if(!(N+D<=-1||T<=N+D))for(let p=-1;p<=7;p++)v+p<=-1||T<=v+p||(D>=0&&D<=6&&(p===0||p===6)||p>=0&&p<=6&&(D===0||D===6)||D>=2&&D<=4&&p>=2&&p<=4?S.set(N+D,v+p,!0,!0):S.set(N+D,v+p,!1,!0))}}function I(S){const C=S.size;for(let T=8;T<C-8;T++){const R=T%2===0;S.set(T,6,R,!0),S.set(6,T,R,!0)}}function E(S,C){const T=i.getPositions(C);for(let R=0;R<T.length;R++){const y=T[R][0],N=T[R][1];for(let v=-2;v<=2;v++)for(let D=-2;D<=2;D++)v===-2||v===2||D===-2||D===2||v===0&&D===0?S.set(y+v,N+D,!0,!0):S.set(y+v,N+D,!1,!0)}}function w(S,C){const T=S.size,R=d.getEncodedBits(C);let y,N,v;for(let D=0;D<18;D++)y=Math.floor(D/3),N=D%3+T-8-3,v=(R>>D&1)===1,S.set(y,N,v,!0),S.set(N,y,v,!0)}function g(S,C,T){const R=S.size,y=u.getEncodedBits(C,T);let N,v;for(N=0;N<15;N++)v=(y>>N&1)===1,N<6?S.set(N,8,v,!0):N<8?S.set(N+1,8,v,!0):S.set(R-15+N,8,v,!0),N<8?S.set(8,R-N-1,v,!0):N<9?S.set(8,15-N-1+1,v,!0):S.set(8,15-N-1,v,!0);S.set(R-8,8,1,!0)}function A(S,C){const T=S.size;let R=-1,y=T-1,N=7,v=0;for(let D=T-1;D>0;D-=2)for(D===6&&D--;;){for(let p=0;p<2;p++)if(!S.isReserved(y,D-p)){let P=!1;v<C.length&&(P=(C[v]>>>N&1)===1),S.set(y,D-p,P),N--,N===-1&&(v++,N=7)}if(y+=R,y<0||T<=y){y-=R,R=-R;break}}}function _(S,C,T){const R=new n;T.forEach(function(p){R.put(p.mode.bit,4),R.put(p.getLength(),m.getCharCountIndicator(p.mode,S)),p.write(R)});const y=e.getSymbolTotalCodewords(S),N=a.getTotalCodewordsCount(S,C),v=(y-N)*8;for(R.getLengthInBits()+4<=v&&R.put(0,4);R.getLengthInBits()%8!==0;)R.putBit(0);const D=(v-R.getLengthInBits())/8;for(let p=0;p<D;p++)R.put(p%2?17:236,8);return O(R,S,C)}function O(S,C,T){const R=e.getSymbolTotalCodewords(C),y=a.getTotalCodewordsCount(C,T),N=R-y,v=a.getBlocksCount(C,T),D=R%v,p=v-D,P=Math.floor(R/v),L=Math.floor(N/v),M=L+1,U=P-L,W=new c(U);let j=0;const Q=new Array(v),K=new Array(v);let ne=0;const Je=new Uint8Array(S.buffer);for(let et=0;et<v;et++){const yr=et<p?L:M;Q[et]=Je.slice(j,j+yr),K[et]=W.encode(Q[et]),j+=yr,ne=Math.max(ne,yr)}const Ze=new Uint8Array(R);let Qt=0,ue,be;for(ue=0;ue<ne;ue++)for(be=0;be<v;be++)ue<Q[be].length&&(Ze[Qt++]=Q[be][ue]);for(ue=0;ue<U;ue++)for(be=0;be<v;be++)Ze[Qt++]=K[be][ue];return Ze}function x(S,C,T,R){let y;if(Array.isArray(S))y=h.fromArray(S);else if(typeof S=="string"){let P=C;if(!P){const L=h.rawSplit(S);P=d.getBestVersionForData(L,T)}y=h.fromString(S,P||40)}else throw new Error("Invalid data");const N=d.getBestVersionForData(y,T);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=N;else if(C<N)throw new Error(`
|
|
9
|
+
The chosen QR Code version cannot contain this amount of data.
|
|
10
|
+
Minimum version required to store current data is: `+N+`.
|
|
11
|
+
`);const v=_(C,T,y),D=e.getSymbolSize(C),p=new r(D);return f(p,C),I(p),E(p,C),g(p,T,0),C>=7&&w(p,C),A(p,v),isNaN(R)&&(R=s.getBestMask(p,g.bind(null,p,T))),s.applyMask(R,p),g(p,T,R),{modules:p,version:C,errorCorrectionLevel:T,maskPattern:R,segments:y}}return Cr.create=function(C,T){if(typeof C>"u"||C==="")throw new Error("No input text");let R=t.M,y,N;return typeof T<"u"&&(R=t.from(T.errorCorrectionLevel,t.M),y=d.from(T.version),N=s.from(T.maskPattern),T.toSJISFunc&&e.setToSJISFunction(T.toSJISFunc)),x(C,y,R,N)},Cr}var Xr={},Jr={},Ds;function tc(){return Ds||(Ds=1,(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(o){return[o,o]}))),r.length===6&&r.push("F","F");const i=parseInt(r.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const i=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,o=r.width&&r.width>=21?r.width:void 0,s=r.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,i){return i.width&&i.width>=r+i.margin*2?i.width/(r+i.margin*2):i.scale},e.getImageWidth=function(r,i){const o=e.getScale(r,i);return Math.floor((r+i.margin*2)*o)},e.qrToImageData=function(r,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,m=[o.color.light,o.color.dark];for(let h=0;h<d;h++)for(let f=0;f<d;f++){let I=(h*d+f)*4,E=o.color.light;if(h>=u&&f>=u&&h<d-u&&f<d-u){const w=Math.floor((h-u)/c),g=Math.floor((f-u)/c);E=m[a[w*s+g]?1:0]}r[I++]=E.r,r[I++]=E.g,r[I++]=E.b,r[I]=E.a}}})(Jr)),Jr}var Ps;function Fg(){return Ps||(Ps=1,(function(e){const t=tc();function n(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 r(){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,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(o.modules.size,c),m=d.getContext("2d"),h=m.createImageData(u,u);return t.qrToImageData(h.data,o,c),n(m,d,u),m.putImageData(h,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),u=c.type||"image/png",m=c.rendererOpts||{};return d.toDataURL(u,m.quality)}})(Xr)),Xr}var Zr={},vs;function Bg(){if(vs)return Zr;vs=1;const e=tc();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 n(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function r(i,o,s){let a="",c=0,d=!1,u=0;for(let m=0;m<i.length;m++){const h=Math.floor(m%o),f=Math.floor(m/o);!h&&!d&&(d=!0),i[m]?(u++,m>0&&h>0&&i[m-1]||(a+=d?n("M",h+s,.5+f+s):n("m",c,0),c=0,d=!1),h+1<o&&i[m+1]||(a+=n("h",u),u=0)):c++}return a}return Zr.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,m=d+c.margin*2,h=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+m+"v"+m+'H0z"/>':"",f="<path "+t(c.color.dark,"stroke")+' d="'+r(u,d,c.margin)+'"/>',I='viewBox="0 0 '+m+" "+m+'"',w='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+I+' shape-rendering="crispEdges">'+h+f+`</svg>
|
|
12
|
+
`;return typeof a=="function"&&a(null,w),w},Zr}var Ts;function Vg(){if(Ts)return ot;Ts=1;const e=_g(),t=Hg(),n=Fg(),r=Bg();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),m=u.length,h=typeof u[m-1]=="function";if(!h&&!e())throw new Error("Callback required as last argument");if(h){if(m<2)throw new Error("Too few arguments provided");m===2?(d=a,a=s,s=c=void 0):m===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(a=s,s=c=void 0):m===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(f,I){try{const E=t.create(a,c);f(o(E,s,c))}catch(E){I(E)}})}try{const f=t.create(a,c);d(null,o(f,s,c))}catch(f){d(f)}}return ot.create=t.create,ot.toCanvas=i.bind(null,n.render),ot.toDataURL=i.bind(null,n.renderToDataURL),ot.toString=i.bind(null,function(o,s,a){return r.render(o,a)}),ot}var qg=Vg();const zg="/__hb_sdk__/dev-context";function jg(e){if(!hi(e)||!Cs(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!hi(t)||!Cs(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Gg={networkRequest:{status:"disabled",useOfficialDomain:!1}};function nc(e){const t=Et(e.runtimePermissions),n=t.permissions.network;return t.valid&&n?{networkRequest:{status:n.status,useOfficialDomain:n.config.useOfficialDomain===!0}}:Kg()}function $g(e,t){return rc(e,t,t.networkRequest.useOfficialDomain)}function Wg(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=nc(e);return rc(e.runtimePermissions,t,!1)}function Kg(){return{networkRequest:{...Gg.networkRequest}}}function rc(e,t,n){const r=Et(e);if(!r.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Di){const a=r.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:n}}:{key:s,status:a.status,config:{}})}const o=hi(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 hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Cs(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function Yg(e){let t,n=!1,r=!1,i;return{invalidate(a){return r?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(n=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){r||(r=!0,n=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;n&&!r;){n=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(m){a={ok:!1},!r&&!c.signal.aborted&&s(m);continue}finally{t===c&&(t=void 0)}if(r)return{ok:!1};let u;try{u=e.apply(d)}catch(m){a={ok:!1},r||s(m);continue}if(r)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(m){a={ok:!1},r||s(m)}}return r?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function Qg(e){return Yg({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 Xg(e){const t=e.minDelayMs??1e3,n=e.maxDelayMs??15e3;let r=t,i=!1,o;return{schedule:s,reset(){r=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){r=t,e.connectEvents();return}r=Math.min(r*2,n),s()}},r))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const Jg={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function Zg(e){return new Promise((t,n)=>{if(e.signal.aborted){n(e.signal.reason);return}const r=document.createElement("div");r.className="hb-sdk-auth-dialog",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.innerHTML=`
|
|
13
|
+
<div class="hb-sdk-auth-dialog__panel">
|
|
14
|
+
<h2>授权请求</h2>
|
|
15
|
+
<p class="hb-sdk-auth-dialog__app">${ei(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
16
|
+
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${ei(Jg[a]||a)}</li>`).join("")}</ul>
|
|
17
|
+
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${ei(e.userProfile.nickname)}</p>`:""}
|
|
18
|
+
<div class="hb-sdk-auth-dialog__actions">
|
|
19
|
+
<button type="button" data-action="deny">拒绝</button>
|
|
20
|
+
<button type="button" class="primary" data-action="allow">允许</button>
|
|
21
|
+
</div>
|
|
22
|
+
</div>
|
|
23
|
+
`;const i=a=>{s(),t(a)},o=()=>{s(),n(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),r.remove()};r.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),r.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(r)})}function ei(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function ep(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:Yi,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,platformAccess:{source:"manifest",manifest:{platforms:hr},sdkVersion:Yi},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Ls="hb-sdk-action-dialog-style";function ji(e){return new Promise((t,n)=>{if(e.signal?.aborted){n(e.signal.reason);return}ip();const r=document.createElement("div");r.className="hb-sdk-action-dialog",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.innerHTML=`
|
|
24
|
+
<div class="hb-sdk-action-dialog__panel">
|
|
25
|
+
<h2>${Ms(e.title)}</h2>
|
|
26
|
+
<pre class="hb-sdk-action-dialog__detail">${Ms(e.detail)}</pre>
|
|
27
|
+
<div class="hb-sdk-action-dialog__actions">
|
|
28
|
+
<button type="button" class="primary" data-action="confirm">确定</button>
|
|
29
|
+
</div>
|
|
30
|
+
</div>
|
|
31
|
+
`;const i=()=>{s(),t()},o=()=>{s(),n(e.signal?.reason)},s=()=>{e.signal?.removeEventListener("abort",o),r.remove()};r.querySelector('[data-action="confirm"]')?.addEventListener("click",i),e.signal?.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(r)})}async function tp(e,t){await ji({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Bt(e.params)].join(`
|
|
32
|
+
`),signal:t.signal})}async function np(e,t){await ji({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Bt(e.channel),"post: "+Bt(e.post)].join(`
|
|
33
|
+
`),signal:t.signal})}async function rp(e,t){await ji({title:"截图分享",detail:["rect: "+Bt(e.rect),"post: "+Bt(e.post)].join(`
|
|
34
|
+
`),signal:t.signal})}function Bt(e){return JSON.stringify(e,null,2)}function Ms(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function ip(){if(document.getElementById(Ls))return;const e=document.createElement("style");e.id=Ls,e.textContent=`
|
|
35
|
+
.hb-sdk-action-dialog {
|
|
36
|
+
position: absolute;
|
|
37
|
+
inset: 0;
|
|
38
|
+
z-index: 40;
|
|
39
|
+
display: grid;
|
|
40
|
+
place-items: center;
|
|
41
|
+
padding: 24px;
|
|
42
|
+
background: rgba(15, 23, 42, 0.45);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
.hb-sdk-action-dialog__panel {
|
|
46
|
+
width: min(420px, 100%);
|
|
47
|
+
border-radius: 12px;
|
|
48
|
+
padding: 20px;
|
|
49
|
+
background: #fff;
|
|
50
|
+
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
.hb-sdk-action-dialog__panel h2 {
|
|
54
|
+
margin: 0 0 8px;
|
|
55
|
+
font-size: 18px;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
.hb-sdk-action-dialog__detail {
|
|
59
|
+
margin: 0 0 16px;
|
|
60
|
+
max-height: 40vh;
|
|
61
|
+
overflow: auto;
|
|
62
|
+
color: #1f2933;
|
|
63
|
+
font-family: inherit;
|
|
64
|
+
font-size: 12px;
|
|
65
|
+
line-height: 1.6;
|
|
66
|
+
white-space: pre-wrap;
|
|
67
|
+
overflow-wrap: anywhere;
|
|
68
|
+
word-break: break-word;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
.hb-sdk-action-dialog__actions {
|
|
72
|
+
display: flex;
|
|
73
|
+
justify-content: flex-end;
|
|
74
|
+
gap: 8px;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
.hb-sdk-action-dialog__actions button {
|
|
78
|
+
min-height: 36px;
|
|
79
|
+
border: 1px solid #cad5e2;
|
|
80
|
+
border-radius: 6px;
|
|
81
|
+
padding: 0 12px;
|
|
82
|
+
background: #fff;
|
|
83
|
+
cursor: pointer;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
.hb-sdk-action-dialog__actions .primary {
|
|
87
|
+
border-color: #2563eb;
|
|
88
|
+
color: #fff;
|
|
89
|
+
background: #2563eb;
|
|
90
|
+
}
|
|
91
|
+
`,document.head.appendChild(e)}function op(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,e.onNavigationBarStyleChange?.(t)},setClipboard:async({text:t})=>{await navigator.clipboard.writeText(t)},showToast:async({message:t,status:n})=>{e.pushLog("host.message",{message:t,status:n}),await kc({message:t,status:n})},showLoading:Mc,hideLoading:Lc,vibrate:Cc,openAppPage:tp,showShareMenu:np,captureAndShare:rp,setScreenshotChromeHidden:Tc}}const ks=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],cn=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Us={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class sp{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((n,r)=>setTimeout(n,r)),this.clearSchedule=t.clearSchedule??(n=>clearTimeout(n)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async n=>this.getInfo(n),getPreparationStatus:async n=>this.getPreparationStatus(n),prepare:(n,r)=>this.prepare(n,r),cancelPreparation:async n=>this.cancelPreparation(n),getActiveSession:async n=>this.getActiveSession(n),launch:async n=>this.launch(n),write:async n=>this.write(n),closeStdin:async n=>this.closeStdin(n),terminate:async n=>this.terminate(n),ackOutput:async n=>this.ackOutput(n),openAttachment:async n=>this.openAttachment(n),showNotification:async n=>this.showNotification(n),onSessionEvent:n=>(this.sessionEventListeners.add(n),()=>this.sessionEventListeners.delete(n))},this.presentation={confirmCompanionOperation:async({action:n,companion:r})=>{const i=r.alias===`${n}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,r.alias,{action:n}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const n=t?[t]:[...ks];for(const r of n){const i=this.preparations.get(r);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(Z("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(r),this.sessions.delete(r)}this.diagnostic("reset",t)}getInfo(t){const n=this.readAlias(t);return{alias:n,displayName:`Browser Fake: ${n}`,target:n==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Us[n],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const n=this.readAlias(t);return this.preparations.get(n)?.status??{state:"not-prepared"}}prepare(t,n){const r=this.readAlias(t),i=this.preparations.get(r);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(r));if(i?.operation)return i.operation.listeners.add(n.onProgress),this.diagnostic("prepare.joined",r),n.onProgress(i.status.state==="preparing"?i.status.progress:cn[0]),i.operation.promise;let o,s;const a=new Promise((d,u)=>{o=d,s=u}),c={cancelled:!1,listeners:new Set([n.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:cn[0]},operation:c};this.preparations.set(r,d),this.diagnostic("prepare.started",r),cn.forEach((u,m)=>{const h=this.schedule(()=>{if(c.timers.delete(h),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(f=>f(u))}catch(f){c.cancelled=!0;for(const I of c.timers)this.clearSchedule(I);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",r,{message:f instanceof Error?f.message:String(f)}),c.reject(f);return}if(this.diagnostic("prepare.progress",r,{phase:u.phase}),m===cn.length-1){if(d.operation=void 0,r==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(Z("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",r,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(r)),this.diagnostic("prepare.ready",r)}}},m+1);c.timers.add(h)})}return a}cancelPreparation(t){const n=this.readAlias(t),r=this.preparations.get(n);if(r?.operation){r.operation.cancelled=!0;for(const i of r.operation.timers)this.clearSchedule(i);r.operation.reject(Z("COMPANION_PREPARATION_CANCELLED","准备已取消")),r.operation=void 0,r.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",n)}}getActiveSession(t){const n=this.readAlias(t),r=this.sessions.get(n);if(!r||r.exited)return;const i=r.snapshot.controllerGeneration;return r.snapshot={...r.snapshot,controllerGeneration:i+1},this.emit($c,{sessionId:r.snapshot.id,controllerGeneration:i}),r.waitingOutput&&(r.queuedOutput.unshift(r.waitingOutput),r.waitingOutput=void 0,this.flushOutput(r)),this.diagnostic("session.controller-transferred",n,{controllerGeneration:r.snapshot.controllerGeneration}),{...r.snapshot,capabilities:[...r.snapshot.capabilities]}}launch(t){const n=this.readAlias(t);if(this.getPreparationStatus(n).state!=="ready")throw Z("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(n==="os-blocked")throw Z("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const r=this.sessions.get(n);if(r&&!r.exited)throw Z("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:n,target:this.getInfo(n).target,capabilities:Us[n],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(n,o),this.diagnostic("session.launched",n,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
|
|
92
|
+
`),this.queueOutput(o,"stderr",1,`fake:diagnostic
|
|
93
|
+
`)},20),n==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),n==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),n==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const n=this.readController(t);if(!n.snapshot.capabilities.includes("stdio"))throw Z("COMPANION_PIPE_CLOSED","stdio 未启用");if(n.stdinClosed)throw Z("COMPANION_PIPE_CLOSED","stdin 已关闭");const r=Math.max(1,...n.queuedOutput.map(i=>i.sequence),n.waitingOutput?.sequence??0)+1;this.queueOutput(n,"stdout",r,new Uint8Array(t.data)),this.diagnostic("stdio.write",n.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const n=this.readController(t);n.stdinClosed=!0,this.diagnostic("stdio.closed",n.snapshot.alias)}terminate(t){const n=this.readController(t);this.exit(n,{reason:"terminated"})}ackOutput(t){const n=this.readController(t),r=n.waitingOutput;!r||r.stream!==t.stream||r.sequence!==t.sequence||(n.waitingOutput=void 0,this.diagnostic("stdio.ack",n.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(n))}openAttachment(t){const n=this.readController(t);if(!n.snapshot.capabilities.includes("attachments"))throw Z("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw Z("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",n.snapshot.alias,{id:t.id});const r=new TextEncoder().encode(`Browser Fake Companion report
|
|
94
|
+
`);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw Z("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(r),write:async()=>{throw Z("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:r.byteLength})}}showNotification(t){const n=this.readController(t);if(!n.snapshot.capabilities.includes("notifications"))throw Z("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",n.snapshot.alias,{category:t.category})}queueOutput(t,n,r,i){t.queuedOutput.push({stream:n,sequence:r,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const n=t.queuedOutput.shift();if(!n){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=n,this.emit(jc,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...n}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:n.data.byteLength,sequence:n.sequence,stream:n.stream})}requestExit(t,n){t.pendingExit=n,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,n)}exit(t,n){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(Gc,{sessionId:t.snapshot.id,exit:n}),this.diagnostic("session.exit",t.snapshot.alias,{...n}))}readController(t){const n=[...this.sessions.values()].find(r=>r.snapshot.id===t.sessionId);if(!n||n.exited)throw Z("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(n.snapshot.controllerGeneration!==t.controllerGeneration)throw Z("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return n}readAlias(t){if(!ks.includes(t))throw Z("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,n){this.eventSink?.(t,n),this.sessionEventListeners.forEach(r=>r({type:t,payload:n}))}diagnostic(t,n,r){this.onDiagnostic({action:t,...n?{alias:n}:{},...r?{detail:r}:{}})}}const ap=Object.freeze({[Jn]:!0,[Zn]:!0,[er]:!0,[tr]:!0,[nr]:!0,[rr]:!0,[ir]:!0,[or]:!0,[sr]:!0,[ar]:!0,[cr]:!0,[dr]:!0,[Ut]:!0,[kt]:!0,[xt]:!0});function cp(e){return new sp(e)}function Z(e,t){return Object.assign(new Error(t),{code:e})}const dp=/^[A-Za-z0-9_-]{22}$/,up="https://api.xiaoheihe.cn/open_inapp/";function lp(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(!dp.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const n=new URL(`http://${e.host}:${t}/l/${e.token}`);if(n.protocol!=="http:"||n.hostname!==e.host||n.port!==String(t)||n.username||n.password||n.search||n.hash)throw new TypeError("Mobile launch redirect host is invalid");return n.href}function fp(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 n=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${up}#${n}`}const hp="__hb_sdk_mini_dev__",mp="hb-sdk:mini-dev-console",gp="__hb_sdk_mini_dev_console_installed__",xs=gp;function pp(e,t=console){yp(t,e,t)}const Ep=["log","debug","info","warn","error"];function yp(e,t,n){if(!n||n[xs]===!0)return!1;let r=!1;for(const i of Ep){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,r=!0}catch{return r}}return r&&(n[xs]=!0),r}const mi=1,Hs=64*1024,wp=64,Ip=/^[A-Za-z0-9_-]{22}$/;class oe extends TypeError{code;constructor(t,n){super(n),this.name="BrowserDevHostChannelError",this.code=t}}function _p(e,t=!1){const n=bp(e,t);switch(gi(n,"Server message"),Sp(n),n.type){case"grant":return Dt(n,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Pt(n.connectionEpoch,"connectionEpoch"),Ve(n.nextClientSequence,"nextClientSequence"),Ve(n.nextServerSequence,"nextServerSequence"),Fs(n.snapshot),n;case"event":return Dt(n,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Pt(n.connectionEpoch,"connectionEpoch"),Ve(n.sequence,"sequence"),n.event!=="account.changed"&&n.event!=="status.changed"&&Ue("event must be account.changed or status.changed"),Fs(n.snapshot),n;case"heartbeat":return Dt(n,["version","type","connectionEpoch","sequence"],"heartbeat"),Pt(n.connectionEpoch,"connectionEpoch"),Ve(n.sequence,"sequence"),n;default:return Ue("Unknown server message type")}}function Ap(e){const t=e.connectionEpoch;Pt(t,"connectionEpoch"),Ve(e.nextSequence,"nextSequence");let n=e.nextSequence;return{get nextSequence(){return n},accept(r){if(Pt(r.connectionEpoch,"connectionEpoch"),Ve(r.sequence,"sequence"),r.connectionEpoch!==t)throw new oe("INVALID_SEQUENCE","Connection epoch does not match");if(n===void 0)throw new oe("INVALID_SEQUENCE","Sequence is exhausted");if(r.sequence!==n)throw new oe("INVALID_SEQUENCE",`Expected sequence ${n}`);n=n===Number.MAX_SAFE_INTEGER?void 0:n+1}}}function bp(e,t){if(t)throw new oe("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new oe("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Hs)throw new oe("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Hs)throw new oe("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return Op(e),JSON.parse(e)}catch(n){throw n instanceof oe?n:new oe("INVALID_JSON","Channel frame must contain strict JSON")}}function Fs(e){gi(e,"snapshot"),Dt(e,["account","permissions"],"snapshot"),gi(e.account,"snapshot.account"),Dt(e.account,["revision"],"snapshot.account"),Ve(e.account.revision,"snapshot.account.revision"),jg(e.permissions)||Ue("snapshot.permissions is invalid")}function Sp(e){e.version!==mi&&Ue("version must be 1")}function gi(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ue(`${t} must be a plain JSON object`)}function Dt(e,t,n,r=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!r.includes(o)))&&Ue(`${n} fields are invalid`)}function Ve(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ue(`${t} must be a non-negative safe integer`)}function Pt(e,t){(typeof e!="string"||!Ip.test(e))&&Ue(`${t} must be a 22-character base64url value`)}function Ue(e){throw new oe("INVALID_MESSAGE",e)}function Op(e){new Rp(e).scan()}class Rp{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 n=this.source[this.position];if(n==="{"||n==="["){if(t>=wp)throw new oe("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return n==="{"?this.scanObject(t):this.scanArray(t)}if(n==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const n=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const r=this.scanString(),i=JSON.parse(r);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(n.has(i))throw new oe("INVALID_JSON","Channel JSON contains a duplicate key");if(n.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 n=this.source[this.position];if(n==='"')return this.position+=1,this.source.slice(t,this.position);n==="\\"?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 Bs=[1e3,2e3,4e3,8e3,15e3];function Np(e){const t=new Set,n=e.webSocketFactory??(y=>new WebSocket(y)),r=e.randomValues??(y=>crypto.getRandomValues(y)),i=e.timers??{clearTimeout:y=>window.clearTimeout(y),setTimeout:(y,N)=>window.setTimeout(y,N)},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,d,u,m=!1,h=0,f,I=!1,E=!1;const w=new Set,g=(y,N)=>{if(!(!e.onDiagnostic||w.has(y))){w.add(y);try{e.onDiagnostic({phase:y,...N?{code:N}:{}})}catch{}}},A=(y,N,v=!1)=>{if(u&&y.account.revision<u.account.revision)return;const D=u&&JSON.stringify(y)===JSON.stringify(u);if(u=y,!(D&&!v))for(const p of t)p(y,N)},_=()=>{if(m||f!==void 0||c)return;const y=Bs[Math.min(h,Bs.length-1)];h+=1,f=i.setTimeout(()=>{f=void 0,R()},y)},O=()=>{m||!I||c||(f!==void 0&&(i.clearTimeout(f),f=void 0),R())},x=()=>{a()&&O()},S=()=>{s&&!s.hidden&&O()},C=()=>{E||(E=!0,o?.addEventListener("online",x),s?.addEventListener("visibilitychange",S))},T=()=>{E&&(E=!1,o?.removeEventListener("online",x),s?.removeEventListener("visibilitychange",S))},R=()=>{if(m||c)return;I=!0,C(),f!==void 0&&(i.clearTimeout(f),f=void 0);let y,N;try{y=n(e.url)}catch{g("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),_();return}try{N=Pp(r)}catch{g("entropy","NONCE_GENERATION_FAILED");try{y?.close(1011,"channel initialization failed")}catch{}_();return}c=y;let v,D,p;const P=()=>{y.removeEventListener("open",M),y.removeEventListener("message",U),y.removeEventListener("close",W),y.removeEventListener("error",j),d===P&&(d=void 0)},L=()=>{if(c===y){c=void 0,P();try{y.close(1008,"invalid channel state")}catch{}_()}},M=()=>{if(!(m||c!==y))try{y.send(JSON.stringify({version:mi,type:"hello",csrfToken:e.csrfToken,clientNonce:N}))}catch{g("send","HELLO_SEND_FAILED"),L()}},U=Q=>{if(m||c!==y)return;if(typeof Q.data!="string"){g("parse","TEXT_FRAME_REQUIRED"),L();return}let K;try{K=_p(Q.data)}catch(ne){g("parse",ne instanceof oe?ne.code:"INVALID_MESSAGE"),L();return}if(K.type==="grant"){if(p){g("sequence","DUPLICATE_GRANT"),L();return}v=K.connectionEpoch,D=K.nextClientSequence,p=Ap({connectionEpoch:v,nextSequence:K.nextServerSequence}),h=0,w.clear(),A(K.snapshot,{type:"grant"});return}if(!p||!v||D===void 0){g("sequence","MESSAGE_BEFORE_GRANT"),L();return}try{p.accept(K)}catch{g("sequence","INVALID_SEQUENCE"),L();return}if(K.type==="heartbeat"){try{y.send(JSON.stringify({version:mi,type:"heartbeat.ack",connectionEpoch:v,sequence:D}))}catch{g("send","HEARTBEAT_ACK_SEND_FAILED"),L()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}A(K.snapshot,{type:"event",event:K.event},!0)},W=()=>{c===y&&(g("close","SOCKET_CLOSED"),c=void 0,P(),_())},j=()=>{g("open","SOCKET_ERROR"),L()};y.addEventListener("open",M),y.addEventListener("message",U),y.addEventListener("close",W),y.addEventListener("error",j),d=P};return{connect:R,subscribeUpdates(y){return t.add(y),()=>t.delete(y)},dispose(){if(m)return;m=!0,I=!1,T(),f!==void 0&&i.clearTimeout(f),f=void 0;const y=c;c=void 0,d?.(),y?.close(1e3,"client disposed"),t.clear()}}}function Dp(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let n="";for(let r=0;r<e.length;r+=3){const i=e[r]??0,o=e[r+1],s=e[r+2];n+=t[i>>2],n+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(n+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(n+=t[s&63])}return n}function Pp(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 n=Dp(t);if(!/^[A-Za-z0-9_-]{22}$/.test(n))throw new TypeError("Channel nonce source returned invalid bytes");return n}try{pp((e,t)=>{zt(`console.${e}`,{source:"host",message:t.map(n=>lc(n)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const vp="/__hb_sdk_bootstrap__",Tp="/__hb_sdk__/mobile-launch-redirect",Cp="/__hb_sdk__/network",Lp="/session/status",Mp="/session/request",kp="/session/events",Up=320,xp=1e3,Hp=1e3,Fp=15e3,Vs="dark",ic=new URL(location.href).searchParams,oc=ic.get("mini_url"),Xe=ic.get("ui_preview")==="1",V={device:At("#device"),get mobileLanSelect(){return At("#mobile-lan-select")},get mobileQrImage(){return At("#mobile-qr-image")},get mobileQrStatus(){return At("#mobile-qr-status")},storageSnapshot:At("#storage-snapshot")};if(!oc&&!Xe)throw V.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const sc=oc??"about:blank",re=await Gi();z.devReadiness=re.devReadiness;z.miniProgramSupportsDesktop=re.miniProgramSupportsDesktop;let Pe=re.lanAddresses,hn=re.defaultLanAddressId,at=re.mobileLaunchRedirect,ac=re.nativeAppLaunchUnavailableReason,pi=re.miniProgramManifestAccessToken,cc=Wi(re),he=re.devContext,Qn=nc(he),B=!1,mr=0;const gr=new AbortController;let je=0,ut,Vt,mn=0,Ge,Ei,yi,ve=0,mt=!1,gn,wi,ti=!1,qs=Promise.resolve(),vt=-1,qt=!1,$e,Ii,_i,pn,Fe;const Xn=new Set,zs=cp({onDiagnostic:({action:e,alias:t,detail:n})=>ge(`companion.fake.${e}`,{...t?{alias:t}:{},...n})}),gt=Qg({applyStatus:e=>Ec(e,!0),fetchStatus:e=>pc(Nc(gr.signal,e)),getCanonicalRevision:()=>vt,onError:lE,reconcile:()=>Qp(mr)}),Ai=Xg({connectEvents:yc,invalidate:()=>gt.invalidate(),isDisposed:()=>B,maxDelayMs:Fp,minDelayMs:Hp,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let ni=0,St="",ri=!1,bi;await Si(!1);Sc();Rc(Oc(re));Xe&&zp();pr();Xe||await uc();await Kt("initial");Xe||(yc(),Kp());Bp();eE();function dc(){!Xe&&!B&&(bi=window.setTimeout(()=>{uc().finally(dc)},1e3))}dc();async function uc(){if(!(ri||B)){ri=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${ni}&limit=500`,{signal:AbortSignal.any([gr.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(B)return;if(St&&t.epoch!==St){ni=0,St=t.epoch;return}St=t.epoch,z.logDevices=t.devices,t.gap&&zt("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const n of t.items){const r=Uc(n.method||`console.${n.level}`,{...n,source:"app"},n.timestamp,n.level==="debug"?"log":n.level);r.source=n.source,r.summary=n.message,r.detail=n,r.deviceSessionId=n.deviceSessionId,r.deviceName=t.devices.find(i=>i.id===n.deviceSessionId)?.name,r.dedupeKey=void 0,js(r)}ni=t.nextCursor}catch{}finally{ri=!1}}}function Bp(){window.addEventListener("beforeunload",fE),window.addEventListener("hb-sdk:restart-runtime",hc),window.addEventListener("hb-sdk:refresh-storage",pr),window.addEventListener("hb-sdk:qr-open-change",fc),window.addEventListener("message",Vp)}function Vp(e){const t=e.data;if(e.source===null||!se(t)||t.type!==mp||!se(t.detail))return;const n=t.detail;n.level!=="log"&&n.level!=="debug"&&n.level!=="info"&&n.level!=="warn"&&n.level!=="error"||!Array.isArray(n.args)||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)||zt(`console.${n.level}`,{source:"app",message:n.args.map(r=>lc(r)).join(" ")},n.timestamp,n.level==="log"||n.level==="debug"?"log":n.level)}function lc(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
95
|
+
`).slice(0,4).join(`
|
|
96
|
+
`):"")||`${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 fc(e){const t=e.detail?.open===!0;t!==mt&&(mt=t,ve+=1,Er(),t&&(V.mobileLanSelect.addEventListener("change",qp),Ic(),Yt()))}function qp(){mt&&Yt()}function hc(){mc("manual restart")}function mc(e){B||ut!==void 0||(ge("runtime.restart",{boundary:je+1}),ut=window.setTimeout(()=>{ut=void 0,B||Kt(e)},0))}async function Kt(e){const t=++je;if(Vt=void 0,wc(e),gc(),z.runtimeStatus="loading",vc(Qn),V.device.replaceChildren(),Xe){V.device.innerHTML=`
|
|
97
|
+
<div class="browser-mock-preview">
|
|
98
|
+
<span class="browser-mock-preview__icon">UI</span>
|
|
99
|
+
<strong>Browser Mock</strong>
|
|
100
|
+
<small>mp_preview</small>
|
|
101
|
+
</div>`,z.runtimeStatus="idle";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name=hp,V.device.appendChild(n);const r=new AbortController;Ei=r;let i=!1;try{const o=await wg(jp(r.signal,t));if(B||t!==je){o.dispose();return}yi=o.dispose,o.ports.companion=zs.port;const s=ng({iframe:n,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,...ap},authPresentation:o.authPresentation,companionPresentation:zs.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{z.runtimeStatus="ready",ge("runtime.ready",{generation:t})},onTrace:a=>$p(t,a),onError:()=>{i=!0,z.runtimeStatus="error"},onCapabilityTrace:a=>{St||ge(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&pr()}});Ge=s,await s.start()}catch(o){if(B||t!==je||r.signal.aborted)return;z.runtimeStatus="error",i||ge("runtime.start.failed",xc(o))}}function zp(){ge("runtime.ready",{generation:1}),zt("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),ge("user.getInfo",{durationMs:34,outcome:"success"}),ge("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function jp(e,t){return{signal:e,account:{async getCurrentUserId(){return(await Si(!1,e)).user_id},async ensureAuthenticated({signal:n}){await Si(!1,n)},onChange(n){return Xn.add(n),()=>Xn.delete(n)}},authenticatedRequest:Wp,storage:{area:"local",storage:localStorage},presentation:op({close:async()=>{$s(),Ge?.destroy(),gc(),z.runtimeStatus="closed"},reload:()=>{!B&&t===je&&(Vt=t)},onNavigationBarStyleChange:Gs,pushLog:ge,getDeviceMetrics:()=>Qi.value}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:n=>{document.title=n}},resolveLaunch:async()=>({configuration:ep({launchUrl:sc,runtimePermissions:Gp($g(he.runtimePermissions,Qn)),...he.miniProgramId?{miniProgramId:he.miniProgramId}:{},operatingSystem:Qi.value.platform}),hostHints:{launchKind:he.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:n=>Zg(n)}}}function gc(){document.documentElement.dataset.navigationBarStyle=Vs,Gs(Vs)}function Gp(e){return{...e,entries:[...e.entries.filter(t=>t.key!=="companion"),{key:"companion",status:"enabled",config:{}}]}}function $p(e,t){const n=Hc(t,e);n&&js(n),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Vt!==e||e!==je)&&(Vt=void 0,mc("navigation.reload"))}async function Wp(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const r=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&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(!r&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await $i(r?Cp:Mp,{method:"POST",body:JSON.stringify(r??{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});!r&&i.status===401&>.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Si(e,t){const n=mr,r=await pc(Nc(gr.signal,t));return Dc(n)?Ec(r,e).status:Oi()}async function pc(e){return await(await fetch(Lp,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Ec(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<vt)return{changed:!1,status:Oi()};const n=e.authenticated?e.user_id:void 0,r=e.authenticated?Y(e.nickname):void 0,i=e.authenticated?Y(e.avatar):void 0,o=e.revision!==vt||e.authenticated!==qt||n!==$e||r!==Ii||i!==_i;return vt=e.revision,qt=e.authenticated,$e=n,Ii=r,_i=i,Sc(),t&&o&&Xn.forEach(s=>s($e)),{changed:o,status:Oi()}}function Oi(){return{authenticated:qt,revision:vt,...qt&&$e?{user_id:$e}:{}}}function Kp(){if(!(!re.csrfToken||B))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Fe=Np({csrfToken:re.csrfToken,onDiagnostic:t=>ge("channel.diagnostic",t),url:e.toString()}),Fe.subscribeUpdates((t,n)=>Yp(t,n)),Fe.connect()}catch{Fe?.dispose(),Fe=void 0}}function Yp(e,t){gt.invalidate(e.account.revision),gE(Qn,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Kt("status changed"):(Qn=vc(e.permissions),Xp())}function yc(){if(pn?.close(),pn=void 0,!$e||B)return;const e=new EventSource(kp);pn=e,e.addEventListener("account-invalidated",()=>{gt.invalidate()}),e.addEventListener("account-revision",()=>{gt.invalidate()}),e.onopen=()=>{Ai.reset()},e.onerror=()=>{e.close(),Ai.schedule()}}async function Qp(e){Dc(e)&&await Kt("account revision changed")}function wc(e){mn+=1,$s(),Ge?.destroy(),Ge=void 0,Ei?.abort(new DOMException(e,"AbortError")),Ei=void 0,yi?.(),yi=void 0}async function Xp(){B||(await Kt("permission changed"),!B&&await Yt())}async function Gi(){const e=await fetch(vp,{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(!se(t))throw new Error("Browser Dev Host bootstrap is invalid");const n=Pc(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!n)throw new pt;return{devReadiness:Jp(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devContext:Zp(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(mE):[],loginAvailable:t.loginAvailable===!0,miniProgram:dE(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,mobileLaunchRedirect:n,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0}}function Jp(e){if(!se(e))return;const t=s=>{if(!(!se(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},n=t(e.browser),r=t(e.mobile),i=t(e.companion);if(!n||!r||!i||!se(e.companion))return;const o=e.companion;return{browser:n,mobile:r,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>se(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}function Zp(e,t){return se(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 $i(e,t){const n=new Headers(t.headers);return n.set("content-type","application/json"),re.csrfToken&&n.set("x-hb-sdk-csrf",re.csrfToken),fetch(e,{...t,headers:n,cache:"no-store",credentials:"same-origin",redirect:"error"})}function eE(){Ac(),!Xe&&he.source==="remote"&&(wi=window.setInterval(()=>{cE()},xp))}function Ic(e=V.mobileLanSelect.options.length>0?V.mobileLanSelect.value:void 0){V.mobileLanSelect.replaceChildren();for(const t of Pe){const n=document.createElement("option");n.value=t.id,n.textContent=`${t.name} · ${t.address}`,V.mobileLanSelect.appendChild(n)}e&&Pe.some(({id:t})=>t===e)?V.mobileLanSelect.value=e:hn&&Pe.some(({id:t})=>t===hn)?V.mobileLanSelect.value=hn:Pe[0]&&(V.mobileLanSelect.value=Pe[0].id),V.mobileLanSelect.disabled=Pe.length===0}async function Yt(){if(B)return;const e=++ve;Er();const t=hE();if(!t?.mobileAppQrPayload){V.mobileQrImage.removeAttribute("src"),V.mobileQrStatus.textContent="未发现可用的局域网地址";return}V.mobileQrStatus.textContent="正在生成二维码...";try{const n=await oE(t);if(e!==ve||B)return;const r=await tE(n.address,n.expiresAt);if(e!==ve||B)return;const i=await qg.toDataURL(r.payload,{width:Up,margin:1});if(e!==ve||B)return;V.mobileQrImage.src=i,V.mobileQrStatus.textContent=`${n.address.name} · ${n.address.address}`,aE(r.expiresAt,e)}catch(n){if(e!==ve||B)return;if(n instanceof pt){bc();return}V.mobileQrImage.removeAttribute("src"),V.mobileQrStatus.textContent=Ki(n)}}async function tE(e,t){const n=e.mobileAppQrPayload;if(!n)throw new Error("Mobile 启动配置不可用");const r=await nE(e,n);if(!r)return{expiresAt:t,payload:n};try{return{expiresAt:Math.min(t,r.expiresAt),payload:fp(lp({host:e.address,port:location.port,token:r.token}))}}catch{throw new pt}}async function nE(e,t){if(at?.addressId===e.id)return at;if(!at)return;const n=await $i(Tp,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:at.token})});if(!n.ok)throw new pt;const r=await n.json(),i=se(r)?Pc({addressId:r.address_id,expiresAt:r.expires_at,token:r.token}):void 0;if(!i||i.addressId!==e.id)throw new pt;return at=i,i}async function rE(e){const t=await Gi(),n=iE(t,e),r=n?.mobileAppQrPayload;if(!n||!r)throw new Error("Mobile 启动配置不可用");return _c(t),{...n,mobileAppQrPayload:r}}function iE(e,t){return e.lanAddresses.find(({id:n})=>n===t)??e.lanAddresses.find(({id:n})=>n===e.defaultLanAddressId)??e.lanAddresses[0]}function _c(e){z.devReadiness=e.devReadiness,z.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,cc=Wi(e),he=e.devContext,Pe=e.lanAddresses,hn=e.defaultLanAddressId,at=e.mobileLaunchRedirect,ac=e.nativeAppLaunchUnavailableReason,pi=e.miniProgramManifestAccessToken,Rc(Oc(e)),mt&&Ic(),Ac()}function Ac(){let e;try{e=Fc(sc)}catch{}const t=he.miniProgramId?.trim().toLowerCase();let n=ac?.trim()??"";!n&&(he.source!=="remote"||!t)&&(n="请先绑定可管理的小程序"),!n&&!he.localDevLaunchToken?.trim()&&(n="正在等待有效的本地调试启动票"),!n&&!e&&(n="未发现可用的本机调试地址"),Bc({...e?{address:e}:{},...t?{miniProgramId:t}:{},...pi?{miniProgramManifestToken:pi}:{},ready:n==="",...n?{unavailableReason:n}:{}})}class pt extends Error{}async function oE(e){const t=qs.then(()=>sE(e));return qs=t.then(()=>{},()=>{}),t}async function sE(e){const t=new URL(e.appUrl),n=new URL(zg,location.origin),r=await $i(n.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:Wg(he)})}),i=await r.json();if(!r.ok||!se(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await rE(e.id),expiresAt:i.expires_at}}function aE(e,t){gn=window.setTimeout(()=>{!B&&mt&&t===ve&&Yt()},Math.max(1e3,e-Date.now()-3e4))}async function cE(){if(!(ti||B)){ti=!0;try{const e=await Gi();if(Wi(e)===cc)return;_c(e),mt&&Yt()}catch(e){e instanceof pt&&bc()}finally{ti=!1}}}function bc(){ve+=1,Er(),V.mobileQrImage.removeAttribute("src"),V.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Wi(e){return JSON.stringify({devReadiness:e.devReadiness,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop})}function Sc(){if(!qt){z.account={authenticated:!1,avatar:"",nickname:"未登录"};return}z.account={authenticated:!0,avatar:_i??"",nickname:Ii||$e||"已登录"}}function Oc(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Rc(e){if(!!!e?.miniProgramId||!e){z.miniProgram={bound:!1,iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}z.miniProgram={bound:!0,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function dE(e){if(e===null)return null;if(!se(e))return;const t=Y(e.miniProgramId)??Y(e.mini_program_id);if(t)return{miniProgramId:t,...Y(e.name)?{name:Y(e.name)}:{},...Y(e.iconUrl)??Y(e.icon_url)?{iconUrl:Y(e.iconUrl)??Y(e.icon_url)}:{},...Y(e.status)?{status:Y(e.status)}:{},...Y(e.version)?{version:Y(e.version)}:{},...Y(e.developerName)??Y(e.developer_name)?{developerName:Y(e.developerName)??Y(e.developer_name)}:{}}}function Y(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function pr(){const e=++mn,t=Ge,n=t?.diagnostics.storage;if(!n){z.storage=[],z.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const r=await n.getSnapshot();if(B||e!==mn||t!==Ge)return;z.storage=r.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),z.storageError=""}catch(r){if(B||e!==mn||t!==Ge)return;z.storage=[],z.storageError=Ki(r)}}function uE(e,t){ge("host.message",{message:e,status:t})}function lE(e){B||uE(Ki(e),"error")}function ge(e,t){zt(e,t)}function fE(){bi!==void 0&&window.clearTimeout(bi),!B&&(B=!0,window.removeEventListener("hb-sdk:restart-runtime",hc),window.removeEventListener("hb-sdk:refresh-storage",pr),window.removeEventListener("hb-sdk:qr-open-change",fc),mr+=1,gr.abort(new DOMException("Browser Dev Host disposed","AbortError")),gt.dispose(),je+=1,wc("Browser Dev Host disposed"),pn?.close(),Fe?.dispose(),Fe=void 0,Ai.dispose(),Vt=void 0,ut!==void 0&&window.clearTimeout(ut),ut=void 0,Er(),wi!==void 0&&window.clearInterval(wi),Xn.clear())}function Er(){gn!==void 0&&window.clearTimeout(gn),gn=void 0}function Nc(e,t){return t?AbortSignal.any([e,t]):e}function Dc(e){return!B&&e===mr}function hE(){return Pe.find(({id:e})=>e===V.mobileLanSelect.value)}function mE(e){return se(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 Pc(e){if(!(!se(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 vc(e){return{networkRequest:{...e.networkRequest}}}function gE(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ki(e){return e instanceof Error&&e.message?e.message:"操作失败"}function se(e){return Object.prototype.toString.call(e)==="[object Object]"}function At(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
|