@heybox/hb-sdk 0.9.1-alpha.1 → 0.9.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/cli-chunks/{build-C5jFqooo.cjs → build-BrxETAg-.cjs} +5 -5
- package/dist/cli-chunks/{context-BkvtRlQM.cjs → context-DxBK07jO.cjs} +2 -2
- package/dist/cli-chunks/{create-uHfLV3qo.cjs → create-D_Cwz_i7.cjs} +1 -1
- package/dist/cli-chunks/{dev-BGgykbLg.cjs → dev-CVqfVj4a.cjs} +9 -9
- package/dist/cli-chunks/{doctor-Cfn2luVo.cjs → doctor-B__9PDSg.cjs} +1 -1
- package/dist/cli-chunks/{index-DZQ84rXZ.cjs → index-26VGAsFk.cjs} +2 -2
- package/dist/cli-chunks/{index-B0eNYO7I.cjs → index-Bdo2T9uy.cjs} +15 -15
- package/dist/cli-chunks/{index.esm-I50IudW7.cjs → index.esm-Bl6toxrf.cjs} +7 -7
- package/dist/cli-chunks/{login-BonS2uKg.cjs → login-BOk8eomf.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-BA_CFVq_.cjs → project-vite-BU-kVQwl.cjs} +1 -1
- package/dist/cli-chunks/{remote-NMK4n5ov.cjs → remote-BbB3_uFH.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-CKGRK3wC.cjs → runtime-gate-GQWWSNNP.cjs} +1 -1
- package/dist/cli-chunks/{runtime-permission-env-Bg7f-uj8.cjs → runtime-permission-env-AT-04rSn.cjs} +1 -1
- package/dist/cli-chunks/{session-XP1Y_N72.cjs → session-B_C7uQDa.cjs} +1 -1
- package/dist/cli-chunks/{skill-DV2oEH-I.cjs → skill-mwRSQNYa.cjs} +2 -2
- package/dist/cli-chunks/{version-rxh3jOOI.cjs → version-CDYLTzyb.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/{browser-dev-host-CBMI8jM6.js → browser-dev-host-Bkf-_cAD.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-kIe9c5pM.js +6 -0
- package/dist/devtools/browser-dev-host/assets/{index-sykXQUSO.js → index-C71D82Iw.js} +4 -4
- package/dist/devtools/browser-dev-host/assets/index-ClSYpidU.css +1 -0
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/package.json +9 -9
- package/skill/skill.json +4 -4
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DXfb_JMF.js +0 -6
- package/dist/devtools/browser-dev-host/assets/index-DRM3hPNc.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{H as Mo,aA as Cd,a$ as Ld,M as Md,aK as kd,aL as Ud,am as cr,b9 as j,ad as xd,an as Ua,at as Hd,b3 as Fd,ap as Bd,d as Vd,aH as xa,ab as qd,aw as Ha,r as zd,aC as Fa,o as Gd,aG as jd,a8 as $d,b1 as Wd,b0 as Kd,c as Yd}from"./desktop-app-launch-DXfb_JMF.js";const Vr="auth.login",qr="user.getInfo",zr="user.revokeAuthorization",Gr="user.getSteamGameList",jr="share.copyLink",$r="share.showShareMenu",Wr="share.screenshot",ot="viewport.setDisplay",Kr="viewport.getWindowInfo",Yr="viewport.setNavigationBarStyle",Kt="storage.getStorage",Yt="storage.setStorage",Qr="network.request",Jr="network.download",Xr="files.pickFiles",Zr="files.pickDirectory",en="files.saveFile",Qt="file.create",Jt="file.remove",tn="file.exists",Xt="file.readText",rn="file.writeText",Zt="file.readBytes",nn="file.writeBytes",er="file.stat",on="directory.create",tr="directory.remove",sn="directory.exists",an="directory.list",cn="ui.showToast",dn="ui.showLoading",ln="ui.hideLoading",un="device.vibrate",fn="device.setClipboard",hn="navigation.close",mn="navigation.reload",pn="navigation.openAppPage",Me="cloud.leaderboard.submit",be="cloud.leaderboard.getList",qe="cloud.leaderboard.getCurrentUserEntry",st="cloud.leaderboard.deleteCurrentUserEntry",De="cloud.leaderboard.getInfo",_n="companion.getInfo",Sn="companion.getPreparationStatus",vn="companion.prepare",On="companion.cancelPreparation",Rn="companion.getActiveSession",Dn="companion.launch",Nn="companion.session.write",Pn="companion.session.closeStdin",Tn="companion.session.terminate",Cn="companion.session.ackOutput",Ln="companion.openAttachment",Mn="companion.showNotification",ze=[{method:Vr,module:"auth",capability:Vr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:qr,module:"user",capability:qr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:zr,module:"user",capability:zr,requirement:{kind:"none"},risk:"high"},{method:Gr,module:"user",capability:Gr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:jr,module:"share",capability:jr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:$r,module:"share",capability:$r,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Wr,module:"share",capability:Wr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Kr,module:"viewport",capability:Kr,requirement:{kind:"none"},risk:"low"},{method:Yr,module:"viewport",capability:Yr,requirement:{kind:"none"},risk:"low"},{method:ot,module:"viewport",capability:ot,requirement:{kind:"none"},risk:"low"},{method:Kt,module:"storage",capability:Kt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Yt,module:"storage",capability:Yt,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Qr,module:"network",capability:Qr,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Jr,module:"network",capability:Jr,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Xr,module:"files",capability:Xr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Zr,module:"files",capability:Zr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:en,module:"files",capability:en,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qt,module:"file",capability:Qt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Jt,module:"file",capability:Jt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:tn,module:"file",capability:tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Xt,module:"file",capability:Xt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:rn,module:"file",capability:rn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Zt,module:"file",capability:Zt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:nn,module:"file",capability:nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:er,module:"file",capability:er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:on,module:"directory",capability:on,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:tr,module:"directory",capability:tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:sn,module:"directory",capability:sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:an,module:"directory",capability:an,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:cn,module:"ui",capability:cn,requirement:{kind:"none"},risk:"low"},{method:dn,module:"ui",capability:dn,requirement:{kind:"none"},risk:"low"},{method:ln,module:"ui",capability:ln,requirement:{kind:"none"},risk:"low"},{method:un,module:"device",capability:un,requirement:{kind:"none"},risk:"low"},{method:fn,module:"device",capability:fn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:hn,module:"navigation",capability:hn,requirement:{kind:"none"},risk:"medium"},{method:mn,module:"navigation",capability:mn,requirement:{kind:"none"},risk:"medium"},{method:pn,module:"navigation",capability:pn,requirement:{kind:"none"},risk:"medium"},{method:Me,module:"cloud",capability:Me,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:be,module:"cloud",capability:be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:qe,module:"cloud",capability:qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:st,module:"cloud",capability:st,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[_n,Sn,vn,On,Rn,Dn,Nn,Pn,Tn,Cn,Ln,Mn].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Je="heybox:miniprogram",Ba=2,Qd="hb_mini_bridge_nonce",Va="sdk.handshake",pr="runtime.location.probe",Jd="sdk.location.report",Xd="sdk.csp.violation",qa="operation.progress",Zd="companion.session.output",el="companion.session.exit",tl="companion.session.ownershipLost";function rl(e){return!Ye(e)||e.namespace!==Je||e.version!==1&&e.version!==2||!ae(e.nonce)?!1:e.type==="handshake"?ae(e.id)&&e.method===Va&&e.error===void 0&&sl(e.payload):e.type==="request"?ae(e.id)&&ae(e.method)&&e.error===void 0:e.type==="response"?ae(e.id)&&(e.method===void 0||ae(e.method))&&(e.error===void 0||al(e.error)):e.type==="event"?!ae(e.method)||e.error!==void 0?!1:e.method===qa?e.version===2&&ae(e.id)&&ol(e.payload):e.id===void 0||ae(e.id):e.type==="cancel"?e.version===2&&ae(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ao(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function za(e){return Ye(e)?e.kind==="sandbox"?ke(e,["kind"]):e.kind==="directory"&&ae(e.handleId)&&ke(e,["kind","handleId"]):!1}function co(e){return!Ye(e)||e.kind!=="file"?!1:ae(e.handleId)?ke(e,["kind","handleId"]):za(e.root)&&ao(e.relativePath)&&ke(e,["kind","root","relativePath"])}function Ga(e){return!Ye(e)||e.kind!=="directory"?!1:ae(e.handleId)?ke(e,["kind","handleId"]):za(e.root)&&(e.relativePath==="."||ao(e.relativePath))&&ke(e,["kind","root","relativePath"])}function ja(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function nl(e){return!Ye(e)||!bt(e.loaded)||typeof e.lengthComputable!="boolean"||!ke(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?bt(e.total)&&e.loaded<=e.total:e.total===void 0}function il(e){return Ye(e)?e.phase==="downloading"?bt(e.loaded)&&(e.total===void 0||bt(e.total)&&e.loaded<=e.total)&&ke(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:bt(e.processed)&&bt(e.total)&&e.processed<=e.total&&ke(e,["phase","processed","total"]):!1}function ol(e){return nl(e)||il(e)}function sl(e){return Ye(e)&&ae(e.href)&&typeof e.userAgent=="string"&&ae(e.sdkVersion)}function al(e){return Ye(e)&&ae(e.code)&&typeof e.message=="string"}function bt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ae(e){return typeof e=="string"&&e.length>0}function ke(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rr=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network","companion"];new Set(rr);const cl=new Set(rr);function dl(e){return cl.has(e)}function Qe(e){if(!gr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!gr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!dl(o)){if(o==="network"){const s=n.config;if(!gr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!gr(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Nr=["network","companion"];function $a(e){if(!yr(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>Nr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!yr(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!yr(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!yr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Nr.indexOf(n.key)-Nr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function ll(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Qe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network"]),n=[];for(const i of Nr)!r.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||n.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:n}}function lo(e){const t=Qe(e.runtimePermissions),r=$a(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of rr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=Wa(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...o===void 0?{}:{revision:o},entries:rr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yr(e,t){return Wa(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const _t=["identity","profile","steam_account"],ul=/^[a-z][a-z0-9-]{0,31}$/,Ka=["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"];ze.map(e=>e.method);function K(e,t,r){return{code:e,message:t,data:r}}function uo(e){return fl(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?K("RUNTIME_ERROR",e.message):K("UNKNOWN_ERROR","小程序运行时异常",e)}function fl(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function hl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ml=1e3;function pl(e,t=hl()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=ml}const gl="runtime.gate.probe",Ya=new Set(ze.map(e=>e.method));class yl{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Ba;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:Je,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Je,version:2,nonce:this.nonce,type:"event",id:t,method:qa,payload:r})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{n=pl(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&rl(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Va,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===gl){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,K("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ya.has(t.method)){this.postResponse(t,void 0,K("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,K("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=uo(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:Je,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!El(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function El(e){return typeof e=="string"&&Ya.has(e)}const Qa="METHOD_FORBIDDEN";function Te(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Qa,t}class oe extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const ko={[Vr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[qr]:["account.getCurrentUserId","account.onChange","network.request"],[zr]:["account.getCurrentUserId","account.onChange","network.request"],[Gr]:["account.getCurrentUserId","account.onChange","network.request"],[jr]:["presentation.setClipboard"],[$r]:["presentation.showShareMenu"],[Wr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ot]:["presentation.applyOrientation"],[Kr]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Yr]:["presentation.setNavigationBarStyle"],[Kt]:["storage.getRaw"],[Yt]:["storage.setRaw"],[Qr]:["network.request"],[Jr]:["network.stream","files.transfer","files.access"],[Xr]:["files.external"],[Zr]:["files.external"],[en]:["files.save"],[Qt]:["files.access"],[Jt]:["files.removeFile"],[tn]:["files.access"],[Xt]:["files.access"],[rn]:["files.access"],[Zt]:["files.access"],[nn]:["files.access"],[er]:["files.access"],[on]:["files.access"],[tr]:["files.removeDirectory"],[sn]:["files.access"],[an]:["files.access"],[cn]:["presentation.showToast"],[dn]:["presentation.showLoading"],[ln]:["presentation.hideLoading"],[un]:["presentation.vibrate"],[fn]:["presentation.setClipboard"],[hn]:["presentation.close"],[mn]:["presentation.reload"],[pn]:["presentation.openAppPage"],[Me]:["account.getCurrentUserId","account.onChange","network.request"],[be]:["account.onChange","network.request"],[qe]:["account.getCurrentUserId","account.onChange","network.request"],[st]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[_n]:["companion.getInfo"],[Sn]:["companion.getPreparationStatus"],[vn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[On]:["companion.cancelPreparation"],[Rn]:["companion.getActiveSession"],[Dn]:["companion.getInfo","companion.launch"],[Nn]:["companion.session.write"],[Pn]:["companion.session.closeStdin"],[Tn]:["companion.session.terminate"],[Cn]:["companion.session.ackOutput"],[Ln]:["companion.openAttachment"],[Mn]:["companion.showNotification"]};function wl(e,t){if(t[e]!==!0)throw Te(e)}const bl=32*1024*1024,Al=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Il(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:bl},i);return _l(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function _l(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:Sl(t,Ol(e,"content-type"))}}function Sl(e,t){vl(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new oe("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Al.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function vl(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new oe(`Host network response 不支持 charset=${t}`)}function Ol(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function k(e){return typeof e=="function"}function Uo(e){return(...t)=>{throw Te(e)}}function ne(e){return async(...t)=>{throw Te(e)}}const Rl=(e,t)=>{},Dl=()=>()=>{};function Nl(e){const t={request:k(e.network?.request)?e.network.request.bind(e.network):ne("network.request")},r={getCurrentUserId:k(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):ne("account.getCurrentUserId"),ensureAuthenticated:k(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):ne("account.ensureAuthenticated"),onChange:k(e.account?.onChange)?e.account.onChange.bind(e.account):Dl},n={getRaw:k(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):ne("storage.getRaw"),setRaw:k(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):ne("storage.setRaw")},i={...k(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...k(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:k(e.presentation?.close)?e.presentation.close.bind(e.presentation):ne("presentation.close"),reload:k(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):ne("presentation.reload"),openAppPage:k(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):ne("presentation.openAppPage"),openWindow:k(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):ne("presentation.openWindow"),getViewportMetrics:k(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Uo("presentation.getViewportMetrics"),getNavigationBarHeight:k(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Uo("presentation.getNavigationBarHeight"),setNavigationBarStyle:k(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):ne("presentation.setNavigationBarStyle"),showShareMenu:k(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):ne("presentation.showShareMenu"),setScreenshotChromeHidden:k(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Rl,captureAndShare:k(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):ne("presentation.captureAndShare"),showToast:k(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):ne("presentation.showToast"),showLoading:k(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):ne("presentation.showLoading"),hideLoading:k(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):ne("presentation.hideLoading"),vibrate:k(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):ne("presentation.vibrate"),setClipboard:k(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):ne("presentation.setClipboard")},o=k(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,k(e.companion?.[a])?e.companion[a].bind(e.companion):ne(`companion.${a}`)]));return k(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion)),{network:t,account:r,storage:n,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 Pl(e){const t=Tl(e.files?.sandbox),r=k(e.picker?.pickFiles)&&k(e.picker?.pickDirectory),n=k(e.picker?.saveFile),i=t||r||n||k(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":k(e.account?.getCurrentUserId),"account.ensureAuthenticated":k(e.account?.ensureAuthenticated),"account.onChange":k(e.account?.onChange),"network.request":k(e.network?.request),"network.stream":k(e.transfer?.network.open)&&k(e.transfer?.network.release),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":k(o?.remove),"files.removeDirectory":k(e.files?.sandbox.remove),"files.transfer":k(e.transfer?.files.writeResource),"storage.getRaw":k(e.storage?.getRaw),"storage.setRaw":k(e.storage?.setRaw),"presentation.close":k(e.presentation?.close),"presentation.reload":k(e.presentation?.reload),"presentation.openAppPage":k(e.presentation?.openAppPage),"presentation.applyOrientation":k(e.presentation?.applyOrientation),"presentation.openWindow":k(e.presentation?.openWindow),"presentation.getViewportMetrics":k(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":k(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":k(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":k(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":k(e.presentation?.captureAndShare),"presentation.showToast":k(e.presentation?.showToast),"presentation.showLoading":k(e.presentation?.showLoading),"presentation.hideLoading":k(e.presentation?.hideLoading),"presentation.vibrate":k(e.presentation?.vibrate),"presentation.setClipboard":k(e.presentation?.setClipboard),"companion.getInfo":k(e.companion?.getInfo),"companion.getPreparationStatus":k(e.companion?.getPreparationStatus),"companion.prepare":k(e.companion?.prepare),"companion.cancelPreparation":k(e.companion?.cancelPreparation),"companion.getActiveSession":k(e.companion?.getActiveSession),"companion.launch":k(e.companion?.launch),"companion.session.write":k(e.companion?.write),"companion.session.closeStdin":k(e.companion?.closeStdin),"companion.session.terminate":k(e.companion?.terminate),"companion.session.ackOutput":k(e.companion?.ackOutput),"companion.openAttachment":k(e.companion?.openAttachment),"companion.showNotification":k(e.companion?.showNotification)}}function Tl(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&k(t.file)&&k(t.directory)&&k(t.create)&&k(t.stat)&&k(t.list)}function xo(e,t){return t?.[e]!==!1}function Cl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function Ja(e,t={}){const r={};for(const n of Object.keys(ko)){const o=ko[n].every(a=>e[a]),s=!Cl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=xo(n,t.callerCapabilities)&&xo(n,t.hostCapabilities)&&o&&s}return r}function Xa(e={},t={}){const r=Pl(e),n=Ja(r,t);return{ports:Nl(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function kn(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Ll(e.signal,t);return{...e,signal:r}}function Ll(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{r.signal.aborted||(n(),r.abort(a.reason))},o=()=>i(e),s=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0})),r.signal}function Ml(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 kl=4,Ul=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],xl=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),Hl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Fl=["/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 Bl(e,t){const r=zl(e);return r===null||Ho(r,Hl)?!0:t&&Ho(r,Fl)}function Vl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Ul.some(r=>t===r||t.endsWith(`.${r}`))}function ql(e){const t=e.trim().toLowerCase();return xl.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function zl(e){let t=e;for(let r=0;r<kl;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Fo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Fo(t)}function Ho(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Fo(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function lt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Bo(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Za(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function l(b,v){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:b,type:v})).catch(()=>{})}catch{}}function g(b){const v=r.get(b);if(!v)throw new Error("Unknown runtime cache scope");return v}function m(b,v){return b.flatMap((A,P)=>{const _=JSON.stringify(b.slice(0,P+1));return[JSON.stringify([_]),JSON.stringify([_,v])]})}function u(b,v){return JSON.stringify(m(b,v).map(A=>n.get(A)??0))}async function p(b,v){const A=g(b),P=JSON.stringify([JSON.stringify(A),...v?[v]:[]]),_=(n.get(P)??0)+1;n.set(P,_),i.add(P);for(const L of a)L(A,v);if(!e.store){i.delete(P),l(v??"*","invalidation");return}try{await e.store.invalidate(A,v)}catch(L){throw l(v??"*","storage_error"),L}n.get(P)===_&&i.delete(P),l(v??"*","invalidation")}function R(b){if(c)throw new Error("Runtime cache manager disposed");const v=o.get(b.namespace);if(v){if(v.sourceCodec!==b.codec||v.definition.codec.version!==b.codec.version||JSON.stringify(v.definition.policy)!==JSON.stringify(b.policy))throw new Error("Conflicting runtime cache namespace");return v.cache}if(!b.namespace||!b.codec.version)throw new Error("Invalid runtime cache definition");const A=Object.freeze({...b.policy}),P=Object.freeze({version:b.codec.version,encode:b.codec.encode.bind(b.codec),decode:b.codec.decode.bind(b.codec),validate:b.codec.validate.bind(b.codec),clone:b.codec.clone.bind(b.codec)}),_=b.namespace;for(const D of[A.ttlMs,A.memoryMaxEntries,A.diskMaxEntries,A.diskMaxBytes,A.maxEntryBytes])if(!Number.isFinite(D)||D<0)throw new Error("Invalid runtime cache policy");const L=new Map,F=new Map,N=new Map;let I=!1;function d(D,M,O){if(c||I||D.aborted||u(M,_)!==O)throw lt()}function h(D){return A.ttlMs>0&&A.persistence==="memory-and-disk"&&!!e.store&&!m(D,_).some(M=>i.has(M))}function f(D,M,O){const U=t();return D.envelopeVersion===1&&JSON.stringify(D.address)===JSON.stringify(M)&&Bo(D.revisions,O)&&D.payload.byteLength<=A.maxEntryBytes&&Number.isFinite(D.cachedAt)&&Number.isFinite(D.expiresAt)&&D.cachedAt<=U&&D.cachedAt>=0&&D.expiresAt>D.cachedAt&&Math.min(D.expiresAt,D.cachedAt+A.ttlMs)>U}function y(D,M,O,U,x){if(!(A.ttlMs<=0||A.memoryMaxEntries<1)){for(const[H,q]of L)Math.min(q.entry.expiresAt,q.entry.cachedAt+A.ttlMs)<=t()&&L.delete(H);for(L.delete(D);L.size>=Math.floor(A.memoryMaxEntries);){const H=L.keys().next();if(H.done)break;L.delete(H.value)}L.set(D,{entry:M,value:O,epoch:U,persistent:x})}}async function w(D,M,O,U){const x={namespace:_,codecVersion:P.version,scopeIds:M,key:D.key},H=JSON.stringify(x);let q=[],z=h(M);if(z)try{q=await e.store.readRevisions(M,_)}catch{z=!1,l(_,"storage_error")}d(U.signal,M,O);async function G(){if(!z)return!0;try{return Bo(q,await e.store.readRevisions(M,_))}catch{return z=!1,l(_,"storage_error"),!1}}const ee=L.get(H);if(A.ttlMs>0&&ee&&ee.epoch===O&&f(ee.entry,x,q)&&ee.persistent===z&&await G())return d(U.signal,M,O),l(_,"memory_hit"),ee.value;if(L.delete(H),z){let $,fe;try{$=await e.store.read(x,A.maxEntryBytes),$&&f($,x,q)?fe=P.decode($.payload):$=void 0}catch{$=void 0,l(_,"storage_error")}if(d(U.signal,M,O),$&&await G())return d(U.signal,M,O),y(H,$,fe,O,!0),l(_,"disk_hit"),fe}l(_,"miss");const Z=P.validate(await D.load(U.signal));d(U.signal,M,O);const J=P.clone(Z);if(!await G()&&z)throw lt();if(d(U.signal,M,O),A.ttlMs>0){const $=t();let fe;try{fe=P.encode(J)}catch{return J}const Co={envelopeVersion:1,address:x,revisions:z?q:[],cachedAt:$,expiresAt:$+A.ttlMs,payload:fe};if(z&&fe.byteLength<=A.maxEntryBytes){let Wn=!0,Lo=!1;try{Wn=await e.store.publish(Co,A),Lo=Wn}catch{l(_,"storage_error")}if(d(U.signal,M,O),!Wn)throw lt();Lo&&l(_,"published")}d(U.signal,M,O),y(H,Co,J,O,z)}return J}async function S(D){if(c||I||D.signal?.aborted)return Promise.reject(lt());const M=g(D.scope),O=u(M,_);let U;if(h(M)){const z=new AbortController;N.set(z,M);const G=()=>z.abort();D.signal?.addEventListener("abort",G,{once:!0});let ee=()=>{};try{U=await Promise.race([e.store.readRevisions(M,_),new Promise((Z,J)=>{const $=()=>J(lt());z.signal.addEventListener("abort",$,{once:!0}),ee=()=>z.signal.removeEventListener("abort",$)})])}catch{z.signal.aborted||l(_,"storage_error")}finally{ee(),N.delete(z),D.signal?.removeEventListener("abort",G)}}d(D.signal??new AbortController().signal,M,O);const x=JSON.stringify([M,D.key,O,U]);let H=F.get(x);if(H?.controller.signal.aborted&&(H=void 0),!H){const z=new AbortController;H={ids:M,controller:z,waiters:0,promise:Promise.resolve(void 0)};const G=H;G.promise=w(D,M,O,z).finally(()=>{F.get(x)===G&&F.delete(x)}),F.set(x,G)}const q=H;return q.waiters+=1,new Promise((z,G)=>{let ee=!1;function Z($){ee||(ee=!0,D.signal?.removeEventListener("abort",J),q.controller.signal.removeEventListener("abort",J),q.waiters-=1,q.waiters===0&&q.controller.abort(),$())}function J(){Z(()=>G(lt()))}D.signal?.addEventListener("abort",J,{once:!0}),q.controller.signal.addEventListener("abort",J,{once:!0}),q.promise.then($=>Z(()=>{try{d(D.signal??new AbortController().signal,M,O),z(P.clone($))}catch(fe){G(fe)}}),$=>Z(()=>G($)))})}function T(D,M){if(M&&M!==_)return;const O=U=>D.every((x,H)=>U[H]===x);for(const[U,x]of L)O(x.entry.address.scopeIds)&&L.delete(U);for(const[U,x]of F)O(x.ids)&&(x.controller.abort(),F.delete(U));for(const[U,x]of N)O(x)&&U.abort()}function V(){if(!I){I=!0,L.clear();for(const D of N.keys())D.abort();N.clear();for(const D of F.values())D.controller.abort();F.clear(),s.delete(V),a.delete(T),o.get(_)?.cache===C&&o.delete(_)}}const C={read:S,invalidateScope:D=>p(D,_),dispose:V};return s.add(V),a.add(T),o.set(_,{definition:{namespace:_,codec:P,policy:A},sourceCodec:b.codec,cache:C}),C}return{createScope(b,v){if(c||!b)throw new Error("Invalid runtime cache scope");const A=Object.freeze({});return r.set(A,[...v?g(v):[],b]),A},register:R,invalidateScope:b=>p(b),dispose(){if(!c){c=!0;for(const b of[...s])b();o.clear(),n.clear(),i.clear()}}}}function Gl(e){const t=new TextEncoder,r=new TextDecoder("utf-8",{fatal:!0});return{version:e.version,validate:e.validate,encode:n=>t.encode(JSON.stringify(n)),decode:n=>e.validate(JSON.parse(r.decode(n))),clone:n=>e.validate(JSON.parse(JSON.stringify(n)))}}const jl=".hb-runtime-cache-v1",Kn=64*1024,ut=1e3,$l=2048,Pt=32*1024*1024,Wl=1024,Pr=new TextEncoder,Vo=new TextDecoder("utf-8",{fatal:!0});function Tt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Er(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Pr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function _e(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qo(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Kl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function zo(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Yl(e,t){const r=e.sandbox.directory(jl),n=r.directory("revisions"),i=r.directory("entries");for(const d of[r,n,i,i.directory("capability-check")])zo(d,["directory","file","create","stat","list","remove"]),zo(d.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(d){if(Kl(d))throw s=!0,d}function c(){if(t.signal.aborted)throw Tt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function l(d,h=t.signal){const f=o.then(()=>{if(h.aborted)throw Tt();return c(),d()},()=>{if(h.aborted)throw Tt();return c(),d()}).catch(S=>{throw a(S),S});if(o=f.catch(()=>{}),h.aborted)return Promise.reject(Tt());let y=()=>{};const w=new Promise((S,T)=>{const V=()=>T(Tt());h.addEventListener("abort",V,{once:!0}),y=()=>h.removeEventListener("abort",V)});return Promise.race([f,w]).finally(y)}async function g(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function m(d,h){const f=n.file(`${await Er([d,h??null])}.revision`);await p(f);let y=!1;try{await f.create({recursive:!1,exclusive:!0},t),y=!0}catch(T){a(T),c()}if(y){const T=qo();return await f.write(Pr.encode(T),t),c(),T}const w=await f.stat(t);if(w.size<1||w.size>128)throw new Error("缓存 revision 文件损坏");const S=Vo.decode(await f.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return c(),S}async function u(d){const h=await d.list({limit:ut},t);if(h.length>=ut)throw new Error("缓存目录超过治理上限");return h}async function p(d){try{await d.stat(t);return}catch(f){if(!wr(f))throw f}if((await u(n)).length>=ut-1)throw new Error("缓存 metadata 超过治理上限")}async function R(d,h){await g();const f=[];for(let y=0;y<d.length;y+=1){const w=d.slice(0,y+1);f.push(await m(w),await m(w,h))}return f}async function b(d){return r.directory(`entries/${await Er([d.namespace,d.codecVersion,d.scopeIds])}`)}async function v(d){return(await b(d)).file(`${await Er(d.key)}.cache`)}async function A(d,h){const f=await d.stat(t);if(f.size<5||f.size>h+Kn+4)throw new Error("缓存条目超过大小限制");const y=await d.read(t);if(c(),y.length!==f.size)throw new Error("缓存条目读取不完整");const w=new DataView(y.buffer,y.byteOffset,y.byteLength).getUint32(0);if(w<1||w>Kn||w+4>y.length)throw new Error("缓存信封损坏");const S=JSON.parse(Vo.decode(y.subarray(4,w+4))),T=y.slice(w+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(V=>typeof V=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(V=>typeof V=="string"&&V.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==T.length||T.length>h)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:T}}async function P(d){if(!d.remove)throw new Error("Host 不支持缓存文件删除");await d.remove(t)}async function _(d){try{if((await d.file.stat(t)).size!==d.size)return!1;const h=await A(d.file,Pt);return!_e(h.address,d.entry.address)||!_e(h.revisions,d.entry.revisions)||h.cachedAt!==d.entry.cachedAt||h.expiresAt!==d.entry.expiresAt||!_e(await L(h.payload),await L(d.entry.payload))?!1:(await P(d.file),!0)}catch(h){if(wr(h))return!0;throw h}}async function L(d){const h=await globalThis.crypto.subtle.digest("SHA-256",d);return Array.from(new Uint8Array(h),f=>f.toString(16).padStart(2,"0")).join("")}async function F(){const d=await u(n);let h=0;for(const S of d)if(S.kind==="file"&&(h+=(await S.stat(t)).size,h>Pt))throw new Error("缓存扫描超过字节上限");const f=[];let y=0,w=h;for(const S of await u(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const T of await u(S)){if(T.kind!=="file"||++y>$l)throw new Error("缓存文件超过治理上限");const V=(await T.stat(t)).size;if(w+=V,w>Pt)throw new Error("缓存扫描超过字节上限");try{const C=await A(T,Pt);f.push({file:T,entry:C,size:(await T.stat(t)).size,bucketName:S.name})}catch(C){a(C),c(),wr(C)||await P(T)}}}return{entries:f,metadataBytes:h}}async function N(){for(const d of await u(i))if(d.kind==="directory"&&d.remove&&(await u(d)).length===0)try{await d.remove({recursive:!1},t)}catch(h){a(h),c()}}function I(d){const{payload:h,...f}=d,y=Pr.encode(JSON.stringify({...f,payloadBytes:h.length}));if(y.length>Kn)throw new Error("缓存信封过大");const w=new Uint8Array(4+y.length+h.length);return new DataView(w.buffer).setUint32(0,y.length),w.set(y,4),w.set(h,y.length+4),w}return{readRevisions:(d,h)=>l(()=>R(d,h)),read:(d,h)=>l(async()=>{c();const f=await v(d);let y;try{y=await A(f,h)}catch(w){if(c(),wr(w))return;throw w}if(!(!_e(y.address,d)||y.expiresAt<=Date.now())&&_e(y.revisions,await R(d.scopeIds,d.namespace)))return y}),publish:(d,h)=>l(async()=>{c();const{address:f}=d;if(!_e(d.revisions,await R(f.scopeIds,f.namespace)))return!1;const y=I(d);if(d.payload.length>h.maxEntryBytes||y.length>h.diskMaxBytes||h.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await g();const w=await b(f),S=await v(f),T=await F(),V=[],C=new Map;for(const O of T.entries){if(O.bucketName===w.name&&O.file.name===S.name)continue;const U=JSON.stringify([O.entry.address.scopeIds,O.entry.address.namespace]);let x=C.get(U);if(x||(x=await R(O.entry.address.scopeIds,O.entry.address.namespace),C.set(U,x)),O.entry.expiresAt<=Date.now()||!_e(O.entry.revisions,x)){if(!await _(O))throw new Error("缓存治理期间条目已变化")}else V.push(O)}V.sort((O,U)=>O.entry.cachedAt-U.entry.cachedAt);function D(){const O=V.filter(U=>U.bucketName===w.name);return V.length+1>Wl||y.length+T.metadataBytes+V.reduce((U,x)=>U+x.size,0)>Pt||O.length+1>Math.min(h.diskMaxEntries,ut-1)||y.length+O.reduce((U,x)=>U+x.size,0)>h.diskMaxBytes}for(;D();){const O=V.filter(H=>H.bucketName===w.name),x=O.length+1>Math.min(h.diskMaxEntries,ut-1)||y.length+O.reduce((H,q)=>H+q.size,0)>h.diskMaxBytes?O[0]:V[0];if(!x||!await _(x))throw new Error("缓存容量不足或条目已变化");V.splice(V.indexOf(x),1)}await N();const M=await u(i);if(!M.some(O=>O.name===w.name)&&M.length>=ut-1)throw new Error("缓存目录超过治理上限");if(await w.create({recursive:!0,exclusive:!1},t),!_e(d.revisions,await R(f.scopeIds,f.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},t)}catch(O){a(O),await S.stat(t)}return await S.write(y,t),c(),_e(d.revisions,await R(f.scopeIds,f.namespace))}),invalidate:(d,h)=>l(async()=>{await g();const f=n.file(`${await Er([d,h??null])}.revision`);await p(f);try{await f.create({recursive:!1,exclusive:!0},t)}catch(y){a(y),await f.stat(t)}await f.write(Pr.encode(qo()),t),c();try{const{entries:y}=await F();for(const w of y){if(h!==void 0&&w.entry.address.namespace!==h||!d.every((T,V)=>w.entry.address.scopeIds[V]===T))continue;const S=await R(w.entry.address.scopeIds,w.entry.address.namespace);_e(w.entry.revisions,S)||await _(w)}await N()}catch(y){a(y),c()}})}}function wr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Ql="RATE_LIMITED_BY_RUNTIME",Jl="RATE_LIMITED",ec=20,tc=40,rc=150,nc=20,ic=1e4,oc=45e3,sc=1,Xl=300*1e3,Zl=64;function ft(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function eu(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function tu(e={}){const t=e.now??Date.now,r=eu(e.coalesceWindowMs,rc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,ft(e.budget?.ratePerSecond,ec)),burst:Math.max(1,Math.floor(ft(e.budget?.burst,tc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(ft(e.loopDetection?.maxCalls,nc))),windowMs:Math.max(1,Math.floor(ft(e.loopDetection?.windowMs,ic)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(ft(e.circuitBreaker?.failureThreshold,sc))),openMs:Math.max(1,Math.floor(ft(e.circuitBreaker?.openMs,oc)))},s=new Map,a=new Map,c=new Set,l=new Map,g=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},m={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function p(I){try{e.onReport?.(I)}catch{}}function R(I,d){if(!i)return{exceeded:!1,count:0};const h=a.get(I)??[],f=d-i.windowMs;let y=0;for(;y<h.length&&h[y]<=f;)y+=1;y>0&&h.splice(0,y);const w=h.length>=i.maxCalls;return w||(h.push(d),h.length>i.maxCalls+1&&h.splice(0,h.length-(i.maxCalls+1))),a.set(I,h),{exceeded:w,count:h.length}}function b(I){if(!n)return!0;const d=Math.max(0,I-g.updatedAt)/1e3;return g.tokens=Math.min(n.burst,g.tokens+d*n.ratePerSecond),g.updatedAt=I,g.tokens<1?!1:(g.tokens-=1,!0)}function v(I){if(!n)return 0;const d=Math.max(0,I-g.updatedAt)/1e3,h=Math.min(n.burst,g.tokens+d*n.ratePerSecond);return Math.max(0,Math.ceil((1-h)/n.ratePerSecond*1e3))}function A(I,d,h,f,y){if(!o)return;const w=l.get(d),S=(w?.open?0:w?.failures??0)+1;if(S<o.failureThreshold){l.set(d,{open:!1,openedAt:0,openMs:0,failures:S});return}const T=Math.min(Math.max(o.openMs,f),Xl);l.set(d,{open:!0,openedAt:y,openMs:T,failures:S}),m.circuitOpened+=1,p({type:"circuit_opened",capability:I,endpointId:d,status:h,openMs:T,timestamp:y})}function P(I){const d=l.get(I);d&&!d.open&&l.delete(I)}function _(I){for(const[d,h]of s)!h.pending&&h.expiresAt<=I&&s.delete(d);for(;s.size>=Zl;){const d=[...s].find(([,h])=>!h.pending);if(!d)break;s.delete(d[0])}}function L(I,d){if(I===void 0)return;const h=s.get(I);h?.promise===d&&(h.pending=!1)}function F(I,d){if(I===void 0)return;s.get(I)?.promise===d&&s.delete(I)}async function N(I){if(u)return I.load();const d=t();if(o){const w=l.get(I.endpointId);if(w?.open){const S=w.openedAt+w.openMs-d;if(S>0)throw m.circuitRejected+=1,p({type:"circuit_rejected",capability:I.capability,endpointId:I.endpointId,retryAfterMs:S,timestamp:d}),iu("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:I.endpointId,retryAfterMs:S});l.delete(I.endpointId)}}const h=R(I.endpointId,d);h.exceeded&&i?c.has(I.endpointId)||(c.add(I.endpointId),p({type:"loop_detected",capability:I.capability,endpointId:I.endpointId,count:h.count,windowMs:i.windowMs,timestamp:d})):c.delete(I.endpointId);const f=r>0?I.coalesceKey:void 0;if(f!==void 0){const w=s.get(f);if(w&&(w.pending||w.expiresAt>d))return m.coalesced+=1,p({type:"coalesced",capability:I.capability,endpointId:I.endpointId,timestamp:d}),w.promise;w&&s.delete(f)}if(h.exceeded&&i)throw m.loopRejected+=1,Go("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:I.capability,endpointId:I.endpointId,count:h.count,windowMs:i.windowMs});if(!b(d)){m.budgetRejected+=1;const w=v(d);throw p({type:"budget_exhausted",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w,timestamp:d}),Go("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w})}f!==void 0&&_(d);const y=I.load().then(w=>(L(f,y),P(I.endpointId),w),w=>{F(f,y);const S=ru(w);throw S!==void 0&&A(I.capability,I.endpointId,S,nu(w),d),w});return f!==void 0&&s.set(f,{promise:y,expiresAt:d+r,pending:!0}),y}return{execute:N,invalidateCoalescing(){s.clear()},snapshot(){return{...m,openCircuits:[...l.entries()].filter(([,I])=>I.open).map(([I])=>I)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),l.clear())}}}function ru(e){if(typeof e!="object"||e===null)return;const t=e.status;if(!(typeof t!="number"||!Number.isInteger(t)))return t===403||t===429?t:void 0}function nu(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Go(e,t){return{code:Ql,message:e,data:t}}function iu(e,t){return{code:Jl,message:e,data:t}}const ac=3e4,cc=6e4,ki=1440*60*1e3;function ou(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??ac)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??cc)):0,steamGameListTtlMs:t?su(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:ec,burst:tc},coalesceWindowMs:r?.coalesceWindowMs??rc,loopDetection:r?.loopDetection??{maxCalls:nc,windowMs:ic},circuitBreaker:r?.circuitBreaker??{failureThreshold:sc,openMs:oc}}}}function su(e){return e===void 0||!Number.isFinite(e)?ki:Math.max(0,Math.floor(e))}function E(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function au(e){return typeof e=="object"&&e!==null}function ge(e,t){const r=e.data;if(!au(r)||typeof r.status!="string")throw new Error(t);return r}const dc={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},cu={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 ge(e,"工坊小程序详情加载失败")}};function dr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function du(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function lu(e){const t=ge(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=du(r.consent_challenge)),{...t,result:n}}const uu={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=>({...dr(e.runtimeContext),challenge:e.challenge}),parse:e=>ge(e,"小程序授权取消接口响应异常")},fu={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=>dr(e.runtimeContext),parse:e=>ge(e,"小程序授权撤销接口响应异常")},hu={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=>dr(e.runtimeContext),parse(e){const t=ge(e,"小程序隔离身份接口响应异常"),r=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,...r?{steamId:r}:{}}}}},mu={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=>({...dr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>lu(e)},pu={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=>({...dr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ge(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},gu=64;function lc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??gu)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(m){for(const[u,p]of i)p.expiresAt<=m&&i.delete(u)}function l(m,u,p){if(a||t<=0||p!==s)return;const R=n();for(c(R),i.delete(m);i.size>=r;){const b=i.keys().next();if(b.done)break;i.delete(b.value)}i.set(m,{expiresAt:R+t,value:u})}function g(m,u){if(a)return u();if(t>0){const v=i.get(m);if(v&&v.expiresAt>n())return Promise.resolve(v.value);v&&i.delete(m)}const p=o.get(m);if(p)return p;const R=s,b=u().then(v=>(l(m,v,R),v)).finally(()=>{o.get(m)===b&&o.delete(m)});return o.set(m,b),b}return{read:g,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function yu(e,t){return t?e?"server":"local":"legacy"}function Eu(e,t){if(e==="local")throw E("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const wu=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],bu=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Au=/authorization|cookie|pkey|password|secret|token/i,uc=/authorization|cookie|pkey|token|password|secret/i;function Se(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Iu(e){for(const t of Object.keys(e))if(!bu.has(t))throw new oe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of wu)if(Object.prototype.hasOwnProperty.call(e,t)&&Se(e,t)!==void 0)throw new oe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Se(e,"bodyEncoding")!==void 0&&Se(e,"bodyEncoding")!=="json"&&Se(e,"bodyEncoding")!=="form")throw new oe("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Se(e,"failurePresentation")!==void 0&&Se(e,"failurePresentation")!=="none")throw new oe("endpoint failurePresentation 必须为 none");if(Se(e,"auth")!==void 0&&Se(e,"auth")!=="none"&&Se(e,"auth")!=="optional"&&Se(e,"auth")!=="required")throw new oe("endpoint auth 必须为 none、optional 或 required")}function Vt(e){if(Array.isArray(e))return e.map(Vt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Au.test(n)||(r[n]=Vt(i));return r}function jo(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))uc.test(r)||(t[r]=n);return t}function _u(e){if(!e)return;const t=Object.keys(e).find(r=>uc.test(r));if(t)throw new oe(`endpoint 禁止声明 credential-bearing header: ${t}`)}class St extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const $o=1440*60*1e3,Su=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function vu(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([s])=>s.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const s=Number(n)*1e3;return s>0?Math.min(s,$o):void 0}if(!Su.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,$o):void 0}function Ou(e,t,r,n){if(e.method!=="GET")return;let i;try{i=JSON.stringify([t??null,r??null])??"undefined"}catch{return}return`${e.id}\0${n}\0${i}`}function fc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class vt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,fc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class lr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,fc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Ru(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Vt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:jo(o),method:e.method,metadata:{endpointId:e.id},query:Vt(n),timeout:e.timeout,url:r},data:Vt(a.data),headers:jo(a.headers)||{},status:a.status,statusText:a.statusText}}async function Un(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Iu(t),typeof t.id!="string"||!t.id)throw new oe("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new oe("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new oe("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;_u(a);const c=async()=>{let m;try{m=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(p){throw p instanceof oe?p:new vt({endpointId:t.id,cause:p})}if(m.status<200||m.status>=300)throw new St({endpointId:t.id,status:m.status,retryAfterMs:vu(m.headers)});const u=Ru(t,r,i,o,s,a,n,m);if(t.parse)try{return await t.parse(u,r)}catch(p){throw new lr({endpointId:t.id,cause:p})}return u.data},l=n.gate;if(!l)return c();const g=Ou(t,o,s,n.credentials);return l.gate.execute({capability:l.capability,endpointId:t.id,...g===void 0?{}:{coalesceKey:g},load:c})}const Du=new Set(_t),fo="steam_account",hc=new Set(_t.filter(e=>e!==fo)),Nu=1e3;function Pu(e){const t=new Set,r=lc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??ac))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,l=e.userDataMode??yu(e.networkEnabled===!0,c),g=e.requestPolicyEnabled!==!1,m=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c)return{};if(!e.authorizationContext)throw E("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch{throw E("REQUEST_FAILED","读取 Runtime auth context 失败")}if(C.steamAccount!==c||C.userDataMode!==l)throw E("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const D=C.token.trim();if(!D)throw E("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:D}}const p=e.account.onChange(C=>{R(),b("heybox_app_login_change",{isHeyboxAppLoggedIn:!!C})});function R(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function b(C,D){C==="user_info_authorization_change"&&xu(D)&&r.invalidate();for(const M of t)try{M(C,D)}catch{}}function v(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw E("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function A(){if(o||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function P(){A();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(D){throw Qo(D,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function _(C,D){const M=await P();if(i!==D||M!==C)throw E("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function L(C){A();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(M){throw Qo(M,e.operationContext.signal,"小黑盒登录失败")}const D=await P();if(!D)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return D}async function F(C,D,M=e.operationContext.signal){try{if(M.aborted)throw Ui();return await Uu(Un(e.network,C,D,{...e.operationContext,credentials:"heybox-session",signal:M,...m?{gate:m}:{}}),M)}catch(O){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):O instanceof oe?E("REQUEST_UNSUPPORTED",O.message):O instanceof lr?E("INVALID_RESPONSE","授权接口响应不合法"):O instanceof vt?E("REQUEST_FAILED","授权请求失败"):O instanceof St?g&&(O.status===403||O.status===429)?E("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:O.status,...O.retryAfterMs===void 0?{}:{retryAfterMs:O.retryAfterMs}}):E("REQUEST_FAILED",O.message):mc(O)?O:E("REQUEST_FAILED","授权请求失败")}}async function N(C,D){await F(uu,{runtimeContext:{miniProgramId:C,...await u()},challenge:D}).catch(()=>{})}function I(C){const D=async()=>{const O=Ko(e.operationContext.signal);a=O;try{return await C(O.signal)}finally{a===O&&(a=void 0),O.abort()}},M=s.then(D,D);return s=M.then(()=>{},()=>{}),M}async function d(C,D,M,O,U){if(!M)throw await N(C,D.challenge),E("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await N(C,D.challenge),E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return I(async x=>{await _(O,U);const H=await h(C,D.displayedScopes,x);await _(O,U);let q;try{q=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:D.displayedScopes,...H,signal:x})}catch(G){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(O,U),await N(C,D.challenge),Tu("REQUEST_FAILED","授权确认界面执行失败",G))}if(await _(O,U),q.status!=="granted")throw await N(C,D.challenge),E("AUTHORIZATION_CANCELLED","用户取消授权");const z=Mu(q.grantedScopes,D.displayedScopes,c);if(!z.includes("identity"))throw await N(C,D.challenge),E("AUTHORIZATION_CANCELLED","用户拒绝授权");return z})}async function h(C,D,M){const O=Ko(M),U=setTimeout(()=>O.abort(),Nu);try{const x=ku(e.miniProgramPresentation),[H,q]=await Promise.all([x?Promise.resolve(x):f(C,O.signal),D.includes("profile")?y(O.signal):Promise.resolve(void 0)]);return{...H?{miniProgram:H}:{},...q?{userProfile:q}:{}}}finally{clearTimeout(U),O.abort()}}async function f(C,D){try{const M=e.identity.get()?.version?.trim(),O=await F(cu,{mini_program_id:C,...M?{miniprogram_version:M}:{}},D),U=ht(O,"小程序公开资料"),x=At(U.name),H=At(U.icon_url);return x||H?{...x?{name:x}:{},...H?{avatarUrl:H}:{}}:void 0}catch{return}}async function y(C){try{const D=await F(dc,void 0,C),M=ht(D,"账号基础信息"),O=At(M.display_username),U=At(M.display_avatar);return O||U?{...O?{nickname:O}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function w(C,D){if(Eu(l,"auth.login"),!c&&C.includes(fo))throw E("INVALID_PARAMS","auth.login 参数不合法");const M=v(),O=await L(D),U=i,x=await F(mu,{runtimeContext:{miniProgramId:M,...await u()},scopes:C});await _(O,U);const H=ht(x,"小程序登录"),q=Yo(H,"loginCode"),z=Yo(H,"consentChallenge");if(q===z)throw E("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let G;if(q)G=Wo(H.loginCode,c);else{const ee=Cu(H.consentChallenge,c),Z=await d(M,ee,D,O,U);await _(O,U);const J=await F(pu,{runtimeContext:{miniProgramId:M,...await u()},challenge:ee.challenge,selectedScopes:Z});if(await _(O,U),G=Wo(ht(J,"小程序登录确认"),c),G.scopes.some($=>!Z.includes($)))throw E("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ee of G.scopes)n.add(ee);return r.invalidate(),b("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),b("user_info_authorization_change",Yn(n,c)),G}async function S(C,D){const M=i,O=await F(hu,{runtimeContext:{miniProgramId:D,...await u()}});await _(C,M);const U=Lu(ht(O,"用户本地身份"),c);for(const x of c?_t:hc)n.add(x);return b("user_info_authorization_change",Yn(n,c)),U}function T(C){A();const D=v(),M=`${C}\0${D}\0${i}\0${c}`;return r.read(M,()=>S(C,D))}async function V(C){if(!C)throw E("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const D=v(),M=i,O=await P();if(!O)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await F(fu,{runtimeContext:{miniProgramId:D,...await u()}});await _(O,M),ht(U,"用户授权撤销"),R(),b("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:w,getOrCreateLocalIdentity:T,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Yn(n,c),revoke:V,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,R(),r.dispose(),p(),t.clear())}}}function Tu(e,t,r){const n=E(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function ht(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Wo(e,t){if(!B(e))throw E("INVALID_RESPONSE","login code 必须是对象");const r=gn(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw E("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Cu(e,t){if(!B(e))throw E("INVALID_RESPONSE","授权 challenge 必须是对象");const r=gn(e.requestedScopes,"challenge requestedScopes",t),n=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||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw E("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Lu(e,t){if(!B(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw E("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw E("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function Mu(e,t,r){const n=gn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw E("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function At(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ku(e){const t=At(e?.name),r=At(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ko(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 Uu(e,t){return t.aborted?Promise.reject(Ui()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Ui()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Ui(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function gn(e,t,r){const n=r?Du:hc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw E("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Yn(e,t){const r=t?_t:_t.filter(n=>n!==fo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Yo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function xu(e){return B(e)?Object.values(e).some(t=>t==="denied"):!1}function mc(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Qo(e,t,r){return t.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):mc(e)?e:E("REQUEST_FAILED",r)}const Hu=new Set(_t);function Fu(e){return{[Vr]:async(t,r)=>e.authorization.login(Bu(t),r.trustedUserGesture)}}function Bu(e){if(e===void 0)return["identity"];if(!B(e)||Object.keys(e).some(t=>t!=="scopes"))throw Jo();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Hu.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Jo();return[...e.scopes]}function Jo(){return E("INVALID_PARAMS","auth.login 参数不合法")}const Vu={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 ge(e,"排行榜记录删除接口响应异常")}},qu={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 ge(e,"当前排行榜记录接口响应异常")}},zu={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 ge(e,"排行榜信息接口响应异常")}},Gu={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 ge(e,"排行榜列表接口响应异常")}},ju={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 ge(e,"排行榜提交接口响应异常")}};function Tr(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Xo(e){return e instanceof oe?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function te(e){if(e.aborted)throw Tr()}function X(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Tr());let n;try{n=e()}catch(i){return Promise.reject(Xo(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Tr())):new Promise((i,o)=>{let s=!1;const a=l=>{s||(s=!0,t.removeEventListener("abort",c),l())},c=()=>a(()=>o(Tr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(l=>a(()=>i(l)),l=>a(()=>o(Xo(l))))})}const $u="default",Wu=/^[A-Za-z0-9_-]{1,64}$/,Ku=300*1e3,Yu=250,Qu=3,Ju={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 Xu{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=ef(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;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(ju,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Ct(i,Me);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Qn(o,Me)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Lt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(Gu,{miniProgramId:r,...t}),s=Ct(o,be);if(!Ne(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw re(`${be} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw re(`${be} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Qn(a,be)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=Lt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(qu,{miniProgramId:n,...t}),c=Ct(a,qe);if(!Ne(c))throw re(`${qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Qn(c.entry,qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Vu,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Ct(i,st);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ne(o)||typeof o.deleted!="boolean")throw re(`${st} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Lt("info"),async()=>{const i=await this.request(zu,{miniProgramId:r,...t}),o=Ct(i,De);if(!Ne(o)||typeof o.key!="string"||!Wu.test(o.key))throw re(`${De} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw re(`${De} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw re(`${De} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw re(`${De} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=Lt(t,n),l=this.inflight.get(c);if(l)return l.promise;const g=this.accountGeneration,m=o?.generation,u=i().then(p=>(this.assertAccountGeneration(g),o&&s&&o.generation===m&&(r==="list"?s.size>=Yu&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Ku,value:p})),p)).finally(()=>{this.inflight.get(c)?.promise===u&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:u}),u}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Qu)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)es(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){es(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await X(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw rs(n)?n:ts()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw Ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw Ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Lt(t,r??$u)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw Ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await X(()=>Un(n,t,r,{...this.options.operationContext,credentials:"heybox-session",...this.requestGateContext?{gate:this.requestGateContext}:{}}),this.options.operationContext.signal)}catch(i){if(rs(i)||Ht(i,"REQUEST_UNSUPPORTED")||Ht(i,"RATE_LIMITED")||Ht(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof oe)throw Ee("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求");if(i instanceof vt&&Ht(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof St){if(this.options.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw Ee("RATE_LIMITED","排行榜请求已被网关限流,请稍后重试",{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw Ee("UNAUTHORIZED","当前用户未登录")}throw i instanceof vt||i instanceof St?ts():i instanceof lr?re(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):re(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(te(this.options.operationContext.signal),this.disposed)throw Ee("INVALID_STATE","Cloud capability 已释放")}}function Zu(e){return new Xu(e)}function ef(e,t){try{return e.onChange(t)}catch(r){if(Ht(r,Qa))return()=>{};throw r}}function Ct(e,t){if(!Ne(e)||typeof e.status!="string")throw re(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw tf(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw re(`${t} 响应缺少 result`);return e.result}function Qn(e,t){if(!Ne(e))throw re(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw re(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw re(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw re(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw re(`${t} 返回的 score 必须是有限数字`);if(!Ne(e.extra))throw re(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw re(`${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 tf(e){if(e.status==="login"||e.status==="relogin")throw Ee("UNAUTHORIZED",xt(e.msg)||"当前用户未登录");const t=Zo(e.result)??Zo(e),r=xt(t?.user_message)||xt(e.msg)||xt(t?.developer_message)||"排行榜请求失败";throw t?Ee(rf(t),r,{status:e.status,sbe:t}):Ee("HEYBOX_API_ERROR",r,{status:e.status})}function Zo(e){return Ne(e)&&Ne(e.sbe)?e.sbe:void 0}function rf(e){const t=xt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return Ju[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function es(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Lt(...e){return JSON.stringify(e)}function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ht(e,t){return Ne(e)&&e.code===t}function Ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return Ee("INVALID_RESPONSE",e)}function ts(){return Ee("REQUEST_FAILED","排行榜请求失败")}function rs(e){return e instanceof Error&&e.name==="AbortError"}const nf=/^[A-Za-z0-9_-]{1,64}$/,ns=20,of=100,is=2048;function sf(e){const t=Zu(e);return{handlers:{[Me]:async n=>t.submit(af(n)),[be]:async n=>t.getList(cf(n)),[qe]:async n=>t.getCurrentUserEntry(Jn(n,qe)),[st]:async n=>t.deleteCurrentUserEntry(Jn(n,st)),[De]:async n=>t.getInfo(Jn(n,De))},dispose:()=>t.dispose()}}function af(e){const t=ho(e,Me,!1);if(mo(t,["key","score","extra"],Me),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Pe("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...po(t.key,Me),score:t.score,...t.extra===void 0?{}:{extra:df(t.extra)}}}function cf(e){if(e===void 0)return{limit:ns};const t=ho(e,be,!0);mo(t,["key","limit","cursor"],be);const r=t.limit===void 0?ns:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>of)throw Pe("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Pe("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...po(t.key,be),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Jn(e,t){if(e===void 0)return{};const r=ho(e,t,!0);return mo(r,["key"],t),po(r.key,t)}function ho(e,t,r){if(e===void 0&&r)return{};if(!pc(e))throw Pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function mo(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function po(e,t){if(e===void 0)return{};if(typeof e!="string"||!nf.test(e))throw Pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function df(e){if(!pc(e))throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>is)throw Pe("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${is} 字节`);return e}function pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){return{code:e,message:t}}const lf=new Set(["stdio","attachments","notifications"]),gc=new Set(["windows-x64","macos-arm64"]),uf=new Set(["unsigned","valid","invalid","unknown"]),ff=/^[a-f0-9]{64}$/,hf=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),mf=new Set(Ka),pf=new Set([...Ka,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),yc=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 gf(e){const t=async(n,i,o,s)=>{const a=yf(n);try{Re(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Re(i.signal),c}catch(c){throw Hi(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw E("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(l=>Ef(l,i)).catch(l=>{throw Hi(l)});Re(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Re(o.signal),c.status!=="granted")throw E("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[_n]:(n,i)=>t(n,i,async(o,s)=>xi(await e.companion.getInfo(o,s),o)),[Sn]:(n,i)=>t(n,i,async(o,s)=>os(await e.companion.getPreparationStatus(o,s))),[vn]:(n,i)=>t(n,i,async(o,s)=>{const a=os(await e.companion.getPreparationStatus(o,s));return Re(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Re(i.signal),xi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(wc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[On]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Rn]:(n,i)=>t(n,i,async(o,s)=>ss(await e.companion.getActiveSession(o,s),o)),[Dn]:(n,i)=>t(n,i,async(o,s)=>{const a=ss(await e.companion.getActiveSession(o,s),o);return Re(i.signal),a||(await r("launch",o,i),Re(i.signal),bc(await e.companion.launch(o,s),o))}),[Nn]:(n,i)=>mt(n,i,e,"write"),[Pn]:(n,i)=>mt(n,i,e,"closeStdin"),[Tn]:(n,i)=>mt(n,i,e,"terminate"),[Cn]:(n,i)=>mt(n,i,e,"ackOutput"),[Ln]:async(n,i)=>{const o=await mt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Mn]:(n,i)=>mt(n,i,e,"showNotification")}}function yf(e){if(!B(e)||typeof e.alias!="string"||!ul.test(e.alias))throw E("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Re(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function mt(e,t,r,n){if(!B(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw E("INVALID_PARAMS","Companion Session controller 不合法");try{Re(t.signal);const i=await r.companion[n](wf(e,n),{...r.operationContext,signal:t.signal});return Re(t.signal),i}catch(i){throw Hi(i)}}function Ae(){throw E("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Ec(e){return!Array.isArray(e)||e.some(t=>!lf.has(t))?Ae():Object.freeze([...new Set(e)])}function xi(e,t){return!B(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!gc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!uf.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Ae():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Ec(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Ef(e,t){const r=xi(e,t);return!B(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!ff.test(e.sha256)?Ae():Object.freeze({...r,sha256:e.sha256})}function wc(e){return B(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}):Ae():Ae()}function os(e){return B(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:wc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&B(e.error)&&typeof e.error.code=="string"&&mf.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:yc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Ae():Ae()}function bc(e,t){return!B(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!gc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Ae():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Ec(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ss(e,t){return e===void 0?void 0:bc(e,t)}function wf(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!ja(r.data))throw E("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw E("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw E("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw E("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function bf(e){return!B(e)||!hf.has(String(e.reason))?Ae():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Ae():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Ae():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Af(e){if(!B(e)||!B(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=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||!ja(t.data)?void 0:{type:e.type,payload:{sessionId:r,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:r,exit:bf(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function Hi(e,t){return B(e)&&typeof e.code=="string"&&pf.has(e.code)?E(e.code,yc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&B(e)&&e.name==="AbortError"?E(t,"Companion 准备已取消"):E("COMPANION_HOST_FAILED","Companion Host 操作失败")}const as=5e3,cs=1e4;function nt(e){throw{code:"INVALID_PARAMS",message:e}}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ic(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&nt(`${r} 不支持字段: ${n.join(", ")}`)}function If(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ac(e))return nt("device.vibrate 参数必须是对象");Ic(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return nt("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>as?nt(`device.vibrate delay 必须是 0-${as} 的整数毫秒`):{intensity:r,delay:n}}function _f(e){return Ac(e)?(Ic(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?nt("device.setClipboard text 必须是非空字符串"):e.text.length>cs?nt(`device.setClipboard text 不能超过 ${cs} 字符`):{text:e.text}):nt("device.setClipboard 参数必须是对象")}function Sf(e){return{[un]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.vibrate(If(t),e.operationContext),e.operationContext.signal)},[fn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.setClipboard(_f(t),e.operationContext),e.operationContext.signal)}}}const vf=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"]),Of={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 go(e){const t=_c(e),r=t&&vf.has(t)?E(t,Of[t]??"文件操作失败"):E("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Le(e){try{return e()}catch(t){throw go(t)}}function _c(e){try{if(!B(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function Sc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):Fi,remove:o?s=>e.remove(s):Oc,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Fi,stat:s=>e.stat(s)})}function vc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:a=>Sc(e.file(a),n,{allowRemove:o}),directory:a=>vc(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Fi,remove:s?(a,c)=>e.remove(a,c):Oc,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Fi(){return Promise.reject(E("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Oc(){return Promise.reject(E("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const ds=1024;class Rf{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return br(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Le(()=>{if(!Array.isArray(t))throw E("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw E("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>ds)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let l=0;l<a;l+=1){if(!Object.prototype.hasOwnProperty.call(t,l))throw E("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[l],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>br(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return us(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!co(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Nf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=nr(r.relativePath),o=this.prepareFile(Le(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Pf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":nr(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:Le(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return hs(t),br(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Le(()=>{if(!Array.isArray(r))throw E("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw E("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Le(()=>{if(B(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return br(n.handle,ls(t.ref,n.handle.name))}if(B(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return us(n.handle,Df(t.ref,n.handle.name))}throw E("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=ur(r),i=this.prepareFile(Le(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ls(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw E("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Le(()=>{hs(t);const i=n??t.mode;return fs(t.mode,i),{handle:Sc(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Le(()=>{Lf(t,i);const o=n??t.mode;return fs(t.mode,o),{handle:vc(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>ds)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Tf();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw E("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!Cf(t))throw E("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw E("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Te("files.sandbox");return this.prepareDirectory(Le(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Te("files")}}function nr(e){if(!ao(e))throw E("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function ur(e,t="文件名"){const r=nr(e);if(r.includes("/"))throw E("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ls(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:nr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Df(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:nr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function br(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function us(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function fs(e,t){if(t==="readwrite"&&e!=="readwrite")throw E("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Nf(e){return co(e)||Rc(),e}function Pf(e){return Ga(e)||Rc(),e}function Rc(){throw E("INVALID_PARAMS","文件引用不合法")}function Tf(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw E("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Cf(e){return/^[0-9a-f]{32}$/.test(e)}function hs(e){if(!B(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 E("FILE_IO_FAILED","Host 返回了无效 File handle");ur(e.name,"Host File name")}function Lf(e,t=!1){if(!B(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 E("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw E("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&ur(e.name,"Host Directory name")}const ms=1e3,Mf=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function kf(e){const t=r=>kn(e.operationContext,r.signal);return{files:{[Xr]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=Uf(r),s=await he(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Zr]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=xf(r),s=await he(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[en]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=Hf(r).suggestedName,s=t(n);if(!i.saveFile)throw Te("files.saveFile");const a=await he(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Qt]:async(r,n)=>{const i=ye(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.create(ps(i),t(n)))},[Jt]:async(r,n)=>{const i=ye(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw Te(Jt);await he(()=>o.handle.remove(t(n)))},[tn]:async(r,n)=>{const i=ye(r);return gs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!B(o)||o.kind!=="file")throw Es()})},[Xt]:async(r,n)=>{const i=ye(r),o=ys(await he(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw E("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[rn]:async(r,n)=>{const i=ye(r,["content"]);typeof i.content!="string"&&we("content 必须是字符串");const o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Zt]:async(r,n)=>{const i=ye(r),o=await he(()=>e.registry.resolveFile(i.target).read(t(n)));return ys(o)},[nn]:async(r,n)=>{const i=ye(r,["content"]),o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.write(Bf(i.content),t(n)))},[er]:async(r,n)=>{const i=ye(r),o=await he(()=>e.registry.resolveFile(i.target).stat(t(n)));return Vf(o)}},directory:{[on]:async(r,n)=>{const i=ye(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);pt(o.mode),await he(()=>o.create(ps(i),t(n)))},[tr]:async(r,n)=>{const i=ye(r,["recursive"]);if(B(i.target)&&i.target.relativePath===".")throw E("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw Te(tr);await he(()=>o.handle.remove({recursive:i.recursive===void 0?!1:yn(i.recursive,"recursive")},t(n)))},[sn]:async(r,n)=>{const i=ye(r);return gs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!B(o)||o.kind!=="directory")throw Es()})},[an]:async(r,n)=>{const i=ye(r,["limit"]),o=Ff(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await he(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Uf(e){if(e===void 0)return{mode:"read",multiple:!1};B(e)||we("pickFiles 参数必须是对象"),xn(e,["mode","accept","multiple"]);const t=Dc(e.mode,"read"),r=e.multiple===void 0?!1:yn(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&we("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function xf(e){return e===void 0?{mode:"read"}:(B(e)||we("pickDirectory 参数必须是对象"),xn(e,["mode"]),{mode:Dc(e.mode,"read")})}function Hf(e){return B(e)||we("saveFile 参数必须是对象"),xn(e,["suggestedName"]),{suggestedName:ur(e.suggestedName,"suggestedName")}}function ye(e,t=[]){return(!B(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&we("文件操作参数必须包含 target"),xn(e,["target",...t]),e}function ps(e){return{recursive:e.recursive===void 0?!1:yn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:yn(e.exclusive,"exclusive")}}function Dc(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&we("mode 必须是 read 或 readwrite"),e)}function yn(e,t){return typeof e!="boolean"&&we(`${t} 必须是布尔值`),e}function Ff(e){if(e===void 0)return ms;if((!Number.isSafeInteger(e)||e<=0)&&we("limit 必须是正整数"),e>ms)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function xn(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&we(`不支持字段: ${r.join(", ")}`)}function pt(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Xn(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Zn(e){if(!e)throw Te("files.external");return e}async function gs(e){try{return await e(),!0}catch(t){if(Mf.has(_c(t)??""))return!1;throw go(t)}}async function he(e){try{return await e()}catch(t){throw go(t)}}function Bf(e){return e instanceof Uint8Array||we("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&we("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function ys(e){if(!(e instanceof Uint8Array))throw E("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Es(){return E("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Vf(e){if(!B(e)||e.kind!=="file"||!qf(e.size))throw E("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!zf(e[t]))throw E("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 qf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function zf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function we(e){throw E("INVALID_PARAMS",e)}const Ar=4294967296;function Gf(e){const t=new jf;return t.write(e),t.finish()}class jf{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<Ar?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=$f(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<Ar)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/Ar),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Ar)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function $f(e){const t=new Uint8Array(Wf(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const o=e.charCodeAt(r);o>=56320&&o<=57343&&(r+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function Wf(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function Nc(e){Bi(e);const t=Gf(e);if(t.byteLength>128)throw new Error("launch extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Bi(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)Bi(o,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[o,s]of i){if(o==="__proto__")throw new Error("extra object key is not supported");Bi(s,t+1,r)}r.delete(e)}const Kf=["pc","console","mobile"],Yf=["game","wiki"];function En(e){throw{code:"INVALID_PARAMS",message:e}}function Qf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e,t){return typeof e!="string"||!e.trim()?En(t):e.trim()}function ws(e,t,r){return typeof e!="string"||!t.includes(e)?En(r):e}function Jf(e){const t={target:"game_detail",appId:Ge(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ws(e.gameType,Kf,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ws(e.page,Yf,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ge(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ge(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Xf(e){return{target:"user_detail",userId:Ge(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Zf(e){const t={target:"post_detail",linkId:Ge(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ge(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ge(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function eh(e){const t={target:"mini_program",miniProgramId:Ge(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function th(e){return Qf(e)?e.target==="game_detail"?Jf(e):e.target==="user_detail"?Xf(e):e.target==="post_detail"?Zf(e):e.target==="mini_program"?eh(e):En("navigation.openAppPage target 不支持"):En("navigation.openAppPage options 必须是对象")}function rh(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 nh(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ih(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 oh(e){const t=e;return t.target==="game_detail"?rh(t):t.target==="user_detail"?nh(t):ih(t)}const sh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",ah="data-hb-sdk-fullscreen-exit",ch=3e3,dh=2e3,bs="var(--white-70a,rgba(255,255,255,.7))",As="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function lh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(ah,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${bs}`,`box-shadow:${As}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=sh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,l;function g(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function m(){o||(t.style.width=g())}function u(){l?.cancel(),l=void 0}function p(v=dh){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=g(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},v)}function R(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=bs,t.style.boxShadow=As,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}async function b(){if(!(s||a)){if(!o){R();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||R()}}}return t.addEventListener("click",b),window.addEventListener("resize",m),document.body.append(t),!r&&t.animate&&(l=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),p(ch),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",b),window.removeEventListener("resize",m),t.remove()}}}const Pc=1e4;function Tc(e){const t=new AbortController;let r;const n=()=>{r??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",n,{once:!0}),e.aborted&&n();const i=setTimeout(()=>{r??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},Pc);return{signal:t.signal,async run(o){try{return await X(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function Cc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function ei(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Ir(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function uh(e){let t,r,n={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(u){if(!u.hideCapsule){s();return}o??=lh(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,p){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",l),"error"in p)u.controller.abort();else if(r={options:u.options,result:p.result},n=u.options,a(u.options),e.onApplied?.(u.options),p.result.supported&&!ei(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const R of u.subscribers)R.dispose(),"error"in p?R.reject(p.error):R.resolve(p.result);u.subscribers.clear()}}function l(){t&&c(t,{error:Ir()})}function g(u,p){return new Promise((R,b)=>{const v=()=>{u.subscribers.delete(A),A.dispose(),b(Ir()),u.subscribers.size===0&&c(u,{error:Ir()})},A={resolve:R,reject:b,dispose:()=>p?.removeEventListener("abort",v)};u.subscribers.add(A),p?.addEventListener("abort",v,{once:!0}),p?.aborted&&v()})}const m={async apply(u,p,R="api"){if(te(e.operationContext.signal),p?.aborted)throw Ir();const b=Cc(u),v=t?.options??n,A={mode:b.orientation??v.mode,hideCapsule:b.fullscreen??v.hideCapsule};A.mode==="landscape"&&(A.hideCapsule=!0);const P=e.presentation.applyOrientation;if(!P)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&ei(t.options,A))return g(t,p);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&ei(r.options,A))return r.result;r=void 0;const _={options:A,source:R,controller:new AbortController,subscribers:new Set};t=_;const L=g(_,p);return e.operationContext.signal.addEventListener("abort",l,{once:!0}),p||(_.timer=setTimeout(()=>{c(_,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Pc)),X(()=>P.call(e.presentation,A,{...e.operationContext,signal:_.controller.signal}),_.controller.signal).then(F=>c(_,{result:F??{supported:!0}}),F=>c(_,{error:F})),L},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return m}function Lc(e){throw{code:"INVALID_PARAMS",message:e}}function Is(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Lc(`${t} 不支持参数`)}function fh(e){return{[hn]:async t=>{te(e.operationContext.signal),Is(t,"navigation.close"),await X(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[mn]:async t=>{te(e.operationContext.signal),Is(t,"navigation.reload"),await X(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[pn]:async(t,r)=>{const n=kn(e.operationContext,r?.signal);te(n.signal);const i=th(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Nc(i.extra)}catch{Lc("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Tc(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}te(n.signal),await X(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await X(()=>e.presentation.openAppPage(oh(i),n),n.signal)}}}const hh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),mh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),ph=new Set(["range","if-range","a-im"]),gh=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"]),yh=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,_r={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Eh{constructor(t){this.signal=t}phase="initial";transition(t){if(_r[t]<=_r[this.phase])throw E("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(_r[this.phase]<_r.committed&&this.signal.aborted)throw Uc()}normalizeHostError(t,r){return this.throwIfCancelled(),yo(t,r,this.signal)}}async function wh(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Te("network.download");const o=kn(r.operationContext,t.signal),s=new Eh(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await _h(e,i,o)}catch(g){throw s.normalizeHostError(g,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(g){throw s.normalizeHostError(g,"network")}let l=!1;try{s.throwIfCancelled(),s.transition("validate");const g=vh(c);Oh(c,g);const m=Rh(c.status,g);if(e.maxBytes!==void 0&&m.expectedBytes!==void 0&&m.expectedBytes>e.maxBytes)throw E("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Sh(e,a,g,i);let p=0;const R=Ah(m.expectedBytes,e.maxBytes);ri(t,ti(0,m));const b={...o,onProgress(P){!Number.isSafeInteger(P)||P<p||R!==void 0&&P>R||(p=P,ri(t,ti(p,m)))}};s.transition("transfer"),l=!0;let v;try{v=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...m.expectedBytes===void 0?{}:{expectedBytes:m.expectedBytes}},b)}catch(P){throw s.normalizeHostError(P,"transfer")}s.transition("committed"),p=bh(v,m,p,e.maxBytes),ri(t,ti(p,m));const A=i.describeFile(u.handle,u.ref);return s.transition("completed"),A}finally{l||Ih(n.network,c.body)}}function bh(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(n===void 0||o<=n))return o}catch{}return i}function Ah(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Ih(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function _h(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Vi(i.handle.mode),await Mh(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Vi(n.handle.mode),await kh(n.handle,r),{kind:"directory",...n}}function Sh(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Nh(e,r),o=n.deriveFile(t,i);return Vi(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function vh(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 E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!B(e.headers))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!hh.has(r)||!Array.isArray(n)||n.length===0)throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Oh(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw E("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Lh(t,mh)});if((t["content-range"]?.length??0)>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Rh(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(l=>l!=="0"))throw E("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Dh(t["content-encoding"]),a=e===204||e===205?0:n.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function Dh(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function ti(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function ri(e,t){try{e.postProgress(t)}catch{}}function Nh(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Ph(i);if(o&&Cr(o))return o}for(const i of r){const o=Th(i);if(o&&Cr(o))return o}if(e.suggestedName!==void 0)return Mc(e.suggestedName);const n=Ch(e.url);return n&&Cr(n)?n:"download.bin"}function Ph(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function Th(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 Ch(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Mc(e){try{ur(e,"suggestedName")}catch{throw E("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Cr(e))throw E("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Cr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||yh.test(e))}function Lh(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Mh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw kc()}catch(r){throw yo(r,"file",t.signal)}}async function kh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw kc()}catch(r){throw yo(r,"file",t.signal)}}function Vi(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","下载目标只允许读取")}const Uh={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 yo(e,t,r){if(r.aborted)return Uc();const n=xh(e);if(n&&gh.has(n)){const o=E(n,Uh[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?E("DOWNLOAD_TIMEOUT","下载网络请求超时"):E("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?E("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):E("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function xh(e){return B(e)&&typeof e.code=="string"?e.code:void 0}function kc(){return E("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Uc(){return E("DOWNLOAD_CANCELLED","下载已取消")}function Hh(e){if(!e)return;const t=Object.keys(e).find(r=>ph.has(r.trim().toLowerCase()));if(t)throw E("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Eo="withCredentials",Fh=new Set(["url","method","params","data","headers","timeout",Eo]),Bh=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Eo]),Vh=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),_s=3e4,Ss=2*1024*1024,qh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zh=/[\u0000-\u0008\u000A-\u001F\u007F]/,Gh=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,jh="network.request 不支持 multipart/form-data,请使用专用上传能力";function $h(e){const t=Wh(e.runtimePermissions),r=sm(e.allowedHttpOrigins);return{[Jr]:async(n,i)=>{const o=Yh(n,{permission:t,allowedHttpOrigins:r});return wh(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Qr]:async(n,i)=>{const o=kn(e.operationContext,i?.signal);te(o.signal);const s=Kh(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await X(()=>e.network.request(s,o),o.signal)}catch(c){throw dm(c)?c:lm(c,"REQUEST_UNSUPPORTED")?W("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):W("REQUEST_FAILED","网络请求失败")}return cm(a)}}}function Wh(e){const t=Qe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Kh(e,t){const r=Hn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Fh.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Hc(r,"network.request");const i=xc(r,t,"network.request"),o=Jh(r.method),s=r.data;s!==void 0&&em(s),rm(i.headers,s);const a=nm(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 Yh(e,t){const r=Hn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Bh.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Hc(r,"network.download");const i=xc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw W("INVALID_PARAMS","network.download timeout 必须是有限正数");Hh(i.headers);const o=co(r.to),s=Ga(r.to);if(!o&&!s)throw W("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw W("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw W("INVALID_PARAMS","suggestedName 必须是字符串");a=Mc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw W("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw W("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:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function xc(e,t,r){const n=Qh(e.url,t.allowedHttpOrigins,r),i=Vl(n);if(i&&!t.permission.useOfficialDomain)throw W("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Bl(n.pathname,i))throw W("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Hn(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Xh(e.headers,r),timeout:Zh(e.timeout,r)}}function Qh(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw W("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw W("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Jh(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Vh.has(t))throw W("INVALID_PARAMS","network.request method 不合法");return t}function Xh(e,t="network.request"){const r=Hn(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!qh.test(s)||typeof o!="string"||zh.test(o))throw W("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(ql(s))throw W("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Hc(e,t){const r=e[Eo];if(r!==void 0&&typeof r!="boolean")throw W("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Zh(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw W("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>_s)throw W("INVALID_PARAMS",`${t} timeout 不能超过 ${_s}ms`);return e}}function em(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw W("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(tm(e)>Ss)throw W("INVALID_PARAMS",`network.request data 不能超过 ${Ss} 字节`)}function tm(e){if(typeof e=="string")return ni(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ni(e.toString());try{const t=JSON.stringify(e);return t?ni(t):0}catch{throw W("INVALID_PARAMS","network.request data 必须可序列化")}}function rm(e,t){const r=Fc(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw W("INVALID_PARAMS",jh)}function nm(e,t,r){if(t===void 0)return;const n=Fc(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||om(t))?"form":im(t)?"json":void 0}function Fc(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function im(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function om(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sm(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&am(n.hostname)&&t.add(n.origin)}catch{}return t}function am(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function cm(e){return Object.keys(e.headers).some(vs)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!vs(t)))}:e}function vs(e){const t=e.trim().toLowerCase();return Gh.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function dm(e){return e instanceof Error&&e.name==="AbortError"}function lm(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Hn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw W("INVALID_PARAMS",t);return e}function ni(e){return new TextEncoder().encode(e).length}function W(e,t){return{code:e,message:t}}function um(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fm(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 hm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=fm(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function mm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(o)||(r.add(o),n.push(o))}return{invalidMessages:t,values:n}}function Bc(e,t){if(e==null)return{};if(!um(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=hm(e.topicIds),n=mm(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let o=r.values;t.maxTopicIds!==void 0&&o.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),o=o.slice(0,t.maxTopicIds));const s=o.length||n.values.length?{...o.length?{topicIds:o}:{},...n.values.length?{topics:n.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function pm(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function gm(e){try{if(pm(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ce(e){throw{code:"INVALID_PARAMS",message:e}}function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qi(e,t){return typeof e!="string"||!e.trim()?ce(t):e}function ym(e,t){const r=qi(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ce(t):r}catch{return ce(t)}}function Em(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Vc(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ce(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return ce(`${t} 缺少有效的小程序分享地址`)}}function wm(e,t){if(!fr(e))return ce("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ce("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Em(r))return ce("share.showShareMenu channel 不合法");const n=qc(e.extra,"share.showShareMenu");return{title:qi(e.title,"share.showShareMenu title 必须是非空字符串"),description:qi(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Vc(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:ym(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function qc(e,t){if(e!==void 0)try{return Nc(e)}catch{return ce(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function zc(e,t){return e.invalidMessage&&await X(()=>gm(t.environment),t.operationContext.signal)?ce(e.invalidMessage):e.post}function Os(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function bm(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Os(t.windowWidth,0),height:Os(t.windowHeight,0)}}function zi(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ce(t):r}function Rs(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ce(t):r}function Am(e){return fr(e)?{left:zi(e.left,"share.screenshot rect.left 必须是非负数字"),top:zi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Rs(e.width,"share.screenshot rect.width 必须是正数"),height:Rs(e.height,"share.screenshot rect.height 必须是正数")}:ce("share.screenshot rect 必须是对象")}function Im(e,t){if(e!=null&&!fr(e))return ce("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ce("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?bm(t):Am(r.rect),...r.delay===void 0?{}:{delay:zi(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function _m(e,t){te(t.operationContext.signal);const r=wm(e,t);let n=Bc(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await zc(n,t);return X(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Sm(e,t){if(te(t.operationContext.signal),e!==void 0&&!fr(e))return ce("share.copyLink 参数必须是对象");const r=qc(e?.extra,"share.copyLink"),n=Vc(t,"share.copyLink",r);return await X(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function vm(e,t){te(t.operationContext.signal);const r=Im(e,t.presentation),n=Bc(fr(e)?e.post:void 0,{method:"share.screenshot"}),i=await zc(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Om();let a=!1,c;try{a=!0,await X(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await X(()=>t.presentation.captureAndShare({...r,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(g){c={status:"rejected",error:g}}const l=a?await Rm(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(l)throw l;return c.value}function Om(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Rm(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await X(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Dm(e){return{[jr]:(t,r)=>Sm(t,e),[$r]:(t,r)=>_m(t,e),[Wr]:(t,r)=>vm(t,e)}}const Nm=128,Pm=/^[A-Za-z0-9_-]+$/;function Tm(e){const t=Cm(e),r={[Kt]:async n=>{te(e.operationContext.signal);const i=Ds(n,Kt,e.storageLimits?.maxKeyLength),o=await X(()=>e.storage.getRaw(ii(t(),i),e.operationContext),e.operationContext.signal);return{data:Ns(o)}},[Yt]:async n=>{te(e.operationContext.signal);const i=Gc(n,"storage.setStorage 参数必须是对象"),o=Ds(i,Yt,e.storageLimits?.maxKeyLength),s=Lm(i.data,e.storageLimits?.maxValueBytes);await X(()=>e.storage.setRaw(ii(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:r,diagnostics:{getSnapshot:async()=>{te(e.operationContext.signal);let n;try{n=t()}catch{throw je("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=ii(n,"");return(await X(()=>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:Ns(a),serializedValue:a,bytes:jc(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function Cm(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${Ps(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${Ps(i)}`)}t=r!==void 0}if(!r)throw je("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function ii(e,t){return`hb_miniprogram_${e}_${t}`}function Ds(e,t,r=Nm){const i=Gc(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw je("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Pm.test(i))throw je("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Lm(e,t){let r;try{r=JSON.stringify(e)}catch{throw je("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw je("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&jc(r)>t)throw je("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ns(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Gc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw je("INVALID_PARAMS",t);return e}function Ps(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:Mm(e)}function Mm(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function jc(e){return new TextEncoder().encode(e).length}function je(e,t){return{code:e,message:t}}const Ts=120;function Be(e){throw{code:"INVALID_PARAMS",message:e}}function wo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $c(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Be(`${r} 不支持字段: ${n.join(", ")}`)}function km(e){if(!wo(e))return Be("ui.showToast 参数必须是对象");if($c(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Be("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Ts)return Be(`ui.showToast message 不能超过 ${Ts} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Be("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Um(e){return e===void 0?{dismissible:!1}:wo(e)?($c(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Be("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Be("ui.showLoading 参数必须是对象")}function xm(e){e!==void 0&&(!wo(e)||Object.keys(e).length)&&Be("ui.hideLoading 不支持参数")}function Hm(e){return{[cn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showToast(km(t),e.operationContext),e.operationContext.signal)},[dn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showLoading(Um(t),e.operationContext),e.operationContext.signal)},[ln]:async t=>{te(e.operationContext.signal),xm(t),await X(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Fm={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ge(e,"当前用户首页资料接口响应异常")}},Bm=3e4;function Vm(e,t,r={}){const n=r.ttlMs??Bm,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function l(){let m;try{m=await Un(e,Fm,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof oe?E("REQUEST_UNSUPPORTED",u.message):u instanceof lr?E("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof vt?E("REQUEST_FAILED","user home_v2 请求失败"):u instanceof St?i&&(u.status===403||u.status===429)?E("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):E("REQUEST_FAILED",u.message):zm(u)?u:E("REQUEST_FAILED","user home_v2 请求失败")}return qm(m,"user home_v2")}function g(m){const u=Date.now();if(a?.userId===m&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===m&&c.generation===s)return c.promise;const p=s,R=l().then(b=>(s===p&&(a={userId:m,value:b,expiresAt:Date.now()+n}),b)).finally(()=>{c?.promise===R&&(c=void 0)});return c={userId:m,generation:p,promise:R},R}return{get:g,clear(){s+=1,a=void 0,c=void 0}}}function qm(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function zm(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Gm={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 ge(e,"Steam 游戏库接口响应异常")}};function jm(e,t=ki){const r=Gl({version:"1",validate:Wm}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):ki,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function Cs(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function $m(e){const{query:t}=e;return JSON.stringify([e.miniProgramId,e.userId,e.effectiveSteamId??null,e.personalInformationOpen??null,t.limit,t.offset,t.sort,t.q??"",t.includeHidden])}function Wm(e){if(!B(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(oi(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Xe();for(const t of e.gameList){if(!B(t)||!Gi(t.appid)||!Gi(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Xe();for(const r of["image","icon"])Ls(t,r);for(const r of["playtimeForever","playtime2Weeks"])oi(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Xe();if(t.price!==void 0){if(!B(t.price))throw Xe();for(const r of["current","initial","deadlineDate"])Ls(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])oi(t.price,r)}}return e}function Gi(e){return typeof e=="number"&&Number.isFinite(e)}function oi(e,t){if(e[t]!==void 0&&!Gi(e[t]))throw Xe()}function Ls(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Xe()}function Xe(){return E("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Wc=20,Km=100,Ym=128,Kc=0,Yc="weeks",Qm=100,Jm=new Set(["weeks","all","achieved"]);function Xm(){return{nickname:"",avatar:""}}function Zm(e){const t=Vm(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Za(),i=jm(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(d,h){const f=JSON.stringify([d,h]);return(!o||o.key!==f)&&(o={key:f,scope:n.createScope(h,n.createScope(d))}),o.scope}function l(){const d=o;o=void 0,d&&n.invalidateScope(d.scope).catch(()=>{}),s.clear()}const g=lc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??cc))}),m=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,p=!1;const R=e.account.onChange(()=>{u+=1,t.clear(),g.invalidate(),l()}),b=e.authorization.onEvent((d,h)=>{d==="user_info_authorization_change"&&Object.values(h).some(f=>f==="denied")&&(u+=1,t.clear(),g.invalidate(),l(),a=a.then(async()=>{if(p)return;const f=await e.account.getCurrentUserId(e.operationContext);typeof f=="string"&&f.trim()&&await n.invalidateScope(c(A(),f.trim()))}).catch(()=>{}))});function v(){if(p||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function A(){const d=e.identity.get()?.miniProgramId?.trim();if(!d)throw E("INVALID_STATE","用户能力缺少 canonical 小程序身份");return d}async function P(){v(),await a,v();let d;try{d=await e.account.getCurrentUserId(e.operationContext)}catch(h){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ks(h)?h:E("REQUEST_FAILED","读取小黑盒账号失败")}return typeof d=="string"&&d.trim()?d.trim():void 0}async function _(d,h){const f=await P();if(u!==h||f!==d)throw E("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function L(d,h,f=e.operationContext.signal){try{return await Un(e.network,d,h,{...e.operationContext,signal:f,credentials:"heybox-session",...m?{gate:m}:{}})}catch(y){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):y instanceof oe?E("REQUEST_UNSUPPORTED",y.message):y instanceof lr?E("INVALID_RESPONSE","用户接口响应不合法"):y instanceof vt?E("REQUEST_FAILED","用户请求失败"):y instanceof St?r&&(y.status===403||y.status===429)?E("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:y.status,...y.retryAfterMs===void 0?{}:{retryAfterMs:y.retryAfterMs}}):E("REQUEST_FAILED",y.message):ks(y)?y:E("REQUEST_FAILED","用户请求失败")}}async function F(){A();const d=u,h=await P();if(!h)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[f,y]=await Promise.all([e.authorization.getOrCreateLocalIdentity(h),N(h).catch(()=>Xm())]);return await _(h,d),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:f.appUserId,profile:y,...f.steamId?{steam_id:f.steamId}:{}}}}function N(d){return g.read(d,()=>L(dc,void 0).then(h=>{const f=Ms(h,"账号基础信息");if(f.display_username!==void 0&&typeof f.display_username!="string")throw E("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(f.display_avatar!==void 0&&typeof f.display_avatar!="string")throw E("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:f.display_username??"",avatar:f.display_avatar??""}}))}async function I(d){const h=ep(d),f=A(),y=u,w=await P();if(!w)return l(),{isLogin:!1,isBound:!1,data:null};const S=await t.get(w);await _(w,y);const T=bo(S.steam_id_info);if(Object.keys(T).length===0)return await n.invalidateScope(c(f,w)).catch(()=>{}),await _(w,y),s.delete(JSON.stringify([f,w])),{isLogin:!0,isBound:!1,data:null};const V=JSON.stringify([f,w]),C=c(f,w),D=Cs({...h,steamId:void 0},T),M=Qc(T.personal_infomation_open??T.personal_information_open),O=JSON.stringify([D??null,M??null]),U=s.get(V);U&&U.identity!==O&&(await n.invalidateScope(C).catch(()=>{}),await _(w,y));const x={identity:O,scope:n.createScope(O,C)};s.set(V,x);const H=Cs(h,T),q=H?i.persistent:i.unresolved,z=n.createScope(H??"unresolved",x.scope),G=async()=>{if(await _(w,y),A()!==f||s.get(V)?.identity!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ee=await q.read({scope:z,key:$m({miniProgramId:f,userId:w,effectiveSteamId:H,personalInformationOpen:M,query:h}),signal:e.operationContext.signal,load:async Z=>{const J=await L(Gm,{userId:w,...h,personalInformationOpen:M},Z);return await G(),op(Ms(J,"Steam 游戏库"),h)}}).catch(async Z=>{throw await G(),Z});return await G(),{isLogin:!0,isBound:!0,data:ee}}return{getInfo:F,getSteamGameList:I,async invalidateSteamGameListCache(){const d=A(),h=u,f=await P();if(!f)return;const y=c(d,f);await Promise.all([i.persistent.invalidateScope(y),i.unresolved.invalidateScope(y)]),t.clear(),s.delete(JSON.stringify([d,f])),await _(f,h)},dispose(){p||(p=!0,u+=1,R(),b(),t.clear(),g.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function ep(e){if(e==null)return{limit:Wc,offset:Kc,sort:Yc,includeHidden:!1};if(!B(e))throw Ve("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ve(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:tp(e.limit),offset:rp(e.offset),sort:np(e.sort),includeHidden:ip(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Ym)throw Ve("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ve("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Qm))}return r}function tp(e){if(e===void 0)return Wc;if(!Number.isInteger(e)||Number(e)<1)throw Ve("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Km)}function rp(e){if(e===void 0)return Kc;if(!Number.isInteger(e)||Number(e)<0)throw Ve("user.getSteamGameList offset 必须是非负整数");return Number(e)}function np(e){if(e===void 0)return Yc;if(typeof e!="string"||!Jm.has(e))throw Ve("user.getSteamGameList sort 不支持");return e}function ip(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ve("user.getSteamGameList includeHidden 必须是 boolean");return e}function op(e,t){if(!Array.isArray(e.game_list))throw E("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(sp).filter(a=>a!==void 0),n=wn(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=Qc(e.is_me);return s!==void 0&&(o.isMe=s),o}function sp(e){const t=bo(e),r=wn(t.appid),n=wn(t.steam_appid)??r,i=Ao(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};qt(o,"image",t.image),qt(o,"icon",t.appicon??t.icon),zt(o,"playtimeForever",t.playtime_forever),zt(o,"playtime2Weeks",t.playtime_2weeks);const s=cp(t.external_tags??t.tags);s.length&&(o.tags=s);const a=ap(t.price);return a&&(o.price=a),o}function ap(e){const t=bo(e),r={};return qt(r,"current",t.current),qt(r,"initial",t.initial),zt(r,"discount",t.discount),zt(r,"lowestPrice",t.lowest_price),qt(r,"deadlineDate",t.deadline_date),zt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function Ms(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function bo(e){return B(e)?e:{}}function Ao(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function cp(e){return Array.isArray(e)?e.map(Ao).filter(Boolean):[]}function wn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Qc(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qt(e,t,r){const n=Ao(r);n&&Object.assign(e,{[t]:n})}function zt(e,t,r){const n=wn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ve(e){return E("INVALID_PARAMS",e)}function ks(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function dp(e){return{[qr]:async t=>(Us(t,"user.getInfo"),e.user.getInfo()),[zr]:async(t,r)=>{Us(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Gr]:async t=>e.user.getSteamGameList(t)}}function Us(e,t){if(e!==void 0)throw E("INVALID_PARAMS",`${t} 不接收入参`)}function xs(e){throw{code:"INVALID_PARAMS",message:e}}function Mt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Jc(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Sr(e,t,r){return Math.min(Jc(e,t),r)}async function lp(e){try{return Jc(await e.getNavigationBarHeight(),0)}catch{return 0}}function up(e,t,r,n){const i=Sr(e.safeArea?.left,0,t),o=Math.max(i,Sr(e.safeArea?.right,t,t)),s=Sr(e.safeArea?.top,n,r),a=Math.max(s,Sr(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Hs(e){const t=e.getViewportMetrics(),r=Mt(t.windowWidth,0),n=Mt(t.windowHeight,0),i=await lp(e);return{pixelRatio:Mt(t.pixelRatio,1),screenWidth:Mt(t.screenWidth,r),screenHeight:Mt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:up(t,r,n,i),screenTop:i}}function fp(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,o,s;const a=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const m=++i;Hs(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||m!==i)return;const p=JSON.stringify(u);p!==o&&(o=p,r.onViewportChange?.(u))}).catch(()=>{})},c=uh({...r,onApplied:a}),l=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",l),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?l():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",l,{once:!0})),{handlers:{[ot]:async(m,u)=>c.apply(m,u?.signal),[Kr]:async()=>(te(r.operationContext.signal),Hs(r.presentation)),[Yr]:async m=>{if(te(r.operationContext.signal),typeof m!="object"||m===null||Array.isArray(m))return xs("viewport.setNavigationBarStyle 参数必须是对象");const u=m.foregroundStyle;if(u!=="light"&&u!=="dark")return xs("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await X(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(m,u)=>c.apply({orientation:m.mode,fullscreen:m.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:l}}const hp=new Map(ze.map(e=>[e.method,e]));function vr(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function mp(e){const t=Qe(e);return r=>{if(r.requirement.kind==="none")return{allowed:!0};for(const n of r.requirement.permissions){const i=t.valid?t.permissions[n]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${n}`,data:{permission:n,method:r.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${n}`,data:{permission:n,method:r.method}}}return{allowed:!0}}}function pp(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=g=>{a||(a=!0,n.removeEventListener("abort",l),g())},l=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",l,{once:!0}),i.then(g=>c(()=>o({status:"handled",value:g})),g=>c(()=>s(g)))})}function gp(e){const t=mp(e.runtimePermissions),r=Qe(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const l=e.now??yp,g=e.onTrace?l():0,m=e.onTrace?`cap_${++n}`:"",u=s===ot?++i:void 0;let p;try{if(e.terminalSignal.aborted)throw vr("RUNTIME_DESTROYED","小程序 Runtime 已终止");wl(s,e.effectiveCapabilities);const R=hp.get(s);if(!R)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const b=t(R),v=!b.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!b.allowed&&!v)throw vr(b.code,b.message,b.data);const A=e.handlers[s];if(!A)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(p=Tc(c.signal));const P=p?{...c,signal:p.signal}:c,_=async()=>{for(const F of e.policies??[]){const N=await F.evaluate({method:s,payload:a,capability:R});if(e.terminalSignal.aborted||p?.signal.aborted)throw Vs();if(!N.allowed)throw vr(N.code,N.message,N.data)}if(e.terminalSignal.aborted||p?.signal.aborted)throw Vs();if(u!==void 0){if(Cc(a),u<o)throw vr("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return A(a,P)},L=await pp(()=>p?p.run(_):_(),void 0,c,e.terminalSignal);return Fs(e.onTrace,Bs(m,s,a,g,L),l),L}catch(R){throw Fs(e.onTrace,Bs(m,s,a,g,{status:"error",error:R}),l),R}finally{p?.dispose()}}}}function yp(){return typeof performance>"u"?Date.now():performance.now()}function Fs(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function Bs(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:Ep(i.error)}:{},...wp(t,r,i)}}function Ep(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function wp(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&Xc(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function Xc(e){return typeof e=="object"&&e!==null}function Vs(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function bp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=ou(e.requestPolicy);let n;if(e.files)try{n=Yl(e.files,t)}catch{}const i=Za({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Ap:void 0),s=r.enabled?tu({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Rf(e.files,e.miniProgramDetail),c=kf({registry:a,picker:e.picker,operationContext:t}),l=Pu({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,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let g,m,u,p=()=>{},R=()=>{};try{g=fp({operationContext:t,presentation:e.hostPresentation,onDisplayChange:N=>e.eventSink.postEvent("display_change",N),onViewportChange:N=>e.eventSink.postEvent("viewport_change",N)}),m=Zm({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:l,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),p=l.onEvent((N,I)=>e.eventSink.postEvent(N,I)),R=e.hostCompanion?.onSessionEvent?.(N=>{const I=Af(N);!e.terminalSignal.aborted&&I&&e.eventSink.postEvent(I.type,I.payload)})??(()=>{}),u=sf({account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const b=Tm({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),v=[{name:"auth",handlers:Fu({authorization:l})},{name:"user",handlers:dp({user:m,authorization:l,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Dm({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:g.handlers},{name:"storage",handlers:b.handlers},{name:"network",handlers:$h({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Hm({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Sf({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:fh({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:N=>g.applyOrientation({mode:"portrait",hideCapsule:!1},N)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:gf({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=Ip(v);let P=!1;const _=()=>{P||(P=!0,e.terminalSignal.removeEventListener("abort",_),g?.dispose(),u?.dispose(),p(),R(),m?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?_():e.terminalSignal.addEventListener("abort",_,{once:!0});const L=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:v,handlers:A,allowsCompanionAttachmentAccess:(N,I)=>L.has(N)&&Xc(I)&&a.isCompanionAttachmentRef(I.target),applyOrientation:g.applyOrientation,notifyViewportChange:g.notifyChange,...b.diagnostics?{storageDiagnostics:b.diagnostics}:{},dispose:_}}catch(b){throw g?.dispose(),u?.dispose(),p(),R(),m?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose(),b}}function Ap(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Ip(e){const t=new Map(ze.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=ze.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==ze.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const _p="heybox-mini-dev:";function qs(e){try{return Sp(new URL(e))}catch{return!1}}function Sp(e){return e.protocol===_p}function vp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Op(e)}function Op(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const Rp=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Dp(e,t){const r=[],n=Np(e.environmentInfo,r),i=Lr(n?.appVersion,"host.appVersion",r),o=Tp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Pp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Lr(t.miniProgramId),version:Lr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Np(e,t){if(e!=null){if(Zc(e))return e;t.push("environmentInfo")}}function Pp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Tp(e,t){if(e==null)return{name:"unknown",version:null};if(!Zc(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Rp.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:Lr(e.version,"operatingSystem.version",t)}}function Lr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Cp=1,ed="allow-scripts allow-same-origin",Lp="",Mp="no-referrer";function kp(e=ed){return!e.split(/\s+/).includes("allow-same-origin")}function zs(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Up=new Set(["javascript:","data:","blob:","file:"]),Gs="xiaoheihe.cn";function xp(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(Up.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!qp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Hp(e,t){const r=new URL(e);return r.searchParams.set(Qd,t),r.toString()}function Fp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Bp(r)??Vp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Bp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Vp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function js(e){const t=new URL(e);return Io(t)?"loopback":_o(t)?"lan":"production"}function qp(e,t,r){return zp(e)||Io(e)||_o(e)&&jp(t,r)}function zp(e){return e.protocol==="https:"&&Kp(e.hostname)}function Io(e){return e.protocol==="http:"&&Gp(e.hostname)}function Gp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function _o(e){return e.protocol==="http:"&&$p(e.hostname)}function jp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Io(r)||_o(r)}catch{return!1}}function $p(e){const t=Wp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Wp(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function Kp(e){return e===Gs||e.endsWith(`.${Gs}`)}const Yp=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"]),Qp=new Set(["url","inline","eval","unknown"]),Jp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Xp=/^[a-f0-9]{64}$/,Zp=255,eg=160,tg=256;function rg(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Yp.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>tg||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Qp.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=ng(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>eg||!Jp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Xp.test(o)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function ng(e){if(e!==void 0&&!(typeof e!="string"||e.length>Zp))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const ig=/^(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 og(e){if(!e?.minimumSdkVersion)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=et(e.minimumSdkVersion),r=e.sdkVersion?et(e.sdkVersion):void 0;if(!t)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw K("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=et("0.6.0");if(!r){if(Mr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw K("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw K("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Mr(r,t)<0)throw K("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Mr(r,et("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function sg(e,t){if(typeof t!="string"||!et(t))throw K("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw K("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ag(e,t){const r=et(e),n=et(t);if(!(!r||!n))return Mr(r,n)}function et(e){const t=ig.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function Mr(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Fn=["android","ios","ohos","windows","macos","linux"],cg="0.9.0",dg=Object.freeze(["android","ios","ohos","windows","macos"]),td="该小程序暂不支持当前平台",lg="PLATFORM_UNSUPPORTED";function ug(e){return typeof e=="string"&&Fn.includes(e)}function fg(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 hg(e){const t=e.manifest;if(!Eg(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ws(e.sdkVersion)??Ws(t.sdkVersion);return gg(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:pg()}const r=rd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function mg(e){const t=fg(e.operatingSystemName);if(!t)return Et("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Et("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Fn,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=hg({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Et("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):$s(t,s)}if(r.effectivePlatforms===void 0)return Et("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=rd(r.effectivePlatforms);if("reason"in n)return Et("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=yg(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return $s(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function $s(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Et("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Et(e,t={}){return{status:"denied",reason:e,message:td,...t}}function pg(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:dg,platformsDeclared:!1,policy:"legacy_mobile_default"}}function rd(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const r of e){if(!ug(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Fn.filter(r=>t.has(r)))}}function gg(e){if(typeof e!="string"||!e.trim())return!1;const t=ag(e.trim(),cg);return t!==void 0&&t>=0}function Ws(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yg(e){return e==="explicit"||e==="legacy_mobile_default"}function Eg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wg=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 bg(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:Ag(i.pathname),sanitizedPathnameHash:Ig(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Ag(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Ig(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let v=0;v<16;v+=1)o[v]=s.getUint32(a+v*4,!1);for(let v=16;v<64;v+=1){const A=o[v-15],P=o[v-2],_=ve(A,7)^ve(A,18)^A>>>3,L=ve(P,17)^ve(P,19)^P>>>10;o[v]=o[v-16]+_+o[v-7]+L>>>0}let[c,l,g,m,u,p,R,b]=i;for(let v=0;v<64;v+=1){const A=b+(ve(u,6)^ve(u,11)^ve(u,25))+(u&p^~u&R)+wg[v]+o[v]>>>0,P=(ve(c,2)^ve(c,13)^ve(c,22))+(c&l^c&g^l&g);b=R,R=p,p=u,u=m+A>>>0,m=g,g=l,l=c,c=A+P>>>0}[c,l,g,m,u,p,R,b].forEach((v,A)=>{i[A]=i[A]+v>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ve(e,t){return e>>>t|e<<32-t}const _g=1e4,si=2e3,Sg=2,vg="open-with-native-credential-policy",nd="安全提示",id="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Og{nonce=zs();runtimeId=zs();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 r=Xa(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??_g,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??K("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??K("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(kg(),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=K("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,r)=>{this.resolveReady=t,this.rejectReady=r})}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=og(t.sdkVersionPolicy);const r=Dp(t,this.identity);if(this.environmentInfo=r.info,r.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${r.invalidFields.join(", ")}`}),this.platformGateDecision=mg({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Hg(this.platformGateDecision);if(this.miniProgramDetail=Fg(t),this.effectiveCapabilities=Ja(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),Pg(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const n=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const i=await this.confirmDevMiniProgramLaunch(n);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(Cg(n)),this.launchUrl=n,this.miniProgramSrc=Hp(n,this.nonce),this.traceSecurityPolicy(n),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=uo(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ot,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ue(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[ot])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=bp({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,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});const r=gp({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:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:l,network:g})=>{const m={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...l?{errorCode:l}:{},...this.identity,...g?{network:g}:{}};Ue(this.options.onCapabilityTrace,m)}}:{}});this.bridgeServer=new yl({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(K("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw Ng(t)?t:od(K("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return xp(t,r,{allowPrivateNetwork:qs(r)||Ks(r)||await this.isDevRuntime()})}catch(r){throw K("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Mg)({message:id,title:nd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(js(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!qs(r)&&!Ks(r)}async closeAfterDevLaunchCancellation(){const t=K("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{Ys(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>Ys())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Lp),this.iframe.setAttribute("referrerpolicy",Mp),this.iframe.setAttribute("sandbox",ed)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Ue(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(),Ue(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{sg(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(K("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>=Sg)){this.failRuntime(K("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(pr,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},si),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:pr})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(r),t.deferProbe||this.sendDocumentRevalidationProbe(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(pr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:pr})}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(K("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},si))}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()},si))}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===Xd){this.handleCspViolation(t.payload);return}if(t.method!==Jd)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(K("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Fp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(K("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=rg(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){Ue(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=bg(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(K("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:Cp,launchUrlType:js(t),networkPolicy:vg})}failRuntime(t){const r=Rg(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),Ue(this.options.onError,Dg(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,Ue(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ue(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 Rg(e){const t=uo(e);return bn(e)&&"cause"in e&&od(t,e.cause),t}function od(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Dg(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Ng(e){return bn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function bn(e){return!!e&&typeof e=="object"}function Ue(e,t){try{e?.(t)}catch{}}function Pg(e,t,r){try{e?.(t,r)}catch{}}function Ks(e){try{const t=new URL(e);return t.protocol==="http:"&&vp(t.hostname)}catch{return!1}}function Tg(e){try{return new URL(e).origin}catch{return}}function Cg(e){return kp()?"*":Tg(e)}function Lg(e){return`${nd}
|
|
1
|
+
import{H as Mo,ax as Cd,aY as Ld,M as Md,aH as kd,aI as Ud,aj as cr,b6 as j,aa as xd,ak as Ua,aq as Hd,b0 as Fd,am as Bd,d as Vd,aE as xa,a8 as qd,at as Ha,r as zd,az as Fa,o as Gd,aD as jd,a5 as $d,a_ as Wd,aZ as Kd,c as Yd}from"./desktop-app-launch-kIe9c5pM.js";const Vr="auth.login",qr="user.getInfo",zr="user.revokeAuthorization",Gr="user.getSteamGameList",jr="share.copyLink",$r="share.showShareMenu",Wr="share.screenshot",ot="viewport.setDisplay",Kr="viewport.getWindowInfo",Yr="viewport.setNavigationBarStyle",Kt="storage.getStorage",Yt="storage.setStorage",Qr="network.request",Jr="network.download",Xr="files.pickFiles",Zr="files.pickDirectory",en="files.saveFile",Qt="file.create",Jt="file.remove",tn="file.exists",Xt="file.readText",rn="file.writeText",Zt="file.readBytes",nn="file.writeBytes",er="file.stat",on="directory.create",tr="directory.remove",sn="directory.exists",an="directory.list",cn="ui.showToast",dn="ui.showLoading",ln="ui.hideLoading",un="device.vibrate",fn="device.setClipboard",hn="navigation.close",mn="navigation.reload",pn="navigation.openAppPage",Me="cloud.leaderboard.submit",be="cloud.leaderboard.getList",qe="cloud.leaderboard.getCurrentUserEntry",st="cloud.leaderboard.deleteCurrentUserEntry",De="cloud.leaderboard.getInfo",_n="companion.getInfo",Sn="companion.getPreparationStatus",vn="companion.prepare",On="companion.cancelPreparation",Rn="companion.getActiveSession",Dn="companion.launch",Nn="companion.session.write",Pn="companion.session.closeStdin",Tn="companion.session.terminate",Cn="companion.session.ackOutput",Ln="companion.openAttachment",Mn="companion.showNotification",ze=[{method:Vr,module:"auth",capability:Vr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:qr,module:"user",capability:qr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:zr,module:"user",capability:zr,requirement:{kind:"none"},risk:"high"},{method:Gr,module:"user",capability:Gr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:jr,module:"share",capability:jr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:$r,module:"share",capability:$r,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Wr,module:"share",capability:Wr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Kr,module:"viewport",capability:Kr,requirement:{kind:"none"},risk:"low"},{method:Yr,module:"viewport",capability:Yr,requirement:{kind:"none"},risk:"low"},{method:ot,module:"viewport",capability:ot,requirement:{kind:"none"},risk:"low"},{method:Kt,module:"storage",capability:Kt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Yt,module:"storage",capability:Yt,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Qr,module:"network",capability:Qr,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Jr,module:"network",capability:Jr,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Xr,module:"files",capability:Xr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Zr,module:"files",capability:Zr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:en,module:"files",capability:en,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qt,module:"file",capability:Qt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Jt,module:"file",capability:Jt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:tn,module:"file",capability:tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Xt,module:"file",capability:Xt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:rn,module:"file",capability:rn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Zt,module:"file",capability:Zt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:nn,module:"file",capability:nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:er,module:"file",capability:er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:on,module:"directory",capability:on,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:tr,module:"directory",capability:tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:sn,module:"directory",capability:sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:an,module:"directory",capability:an,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:cn,module:"ui",capability:cn,requirement:{kind:"none"},risk:"low"},{method:dn,module:"ui",capability:dn,requirement:{kind:"none"},risk:"low"},{method:ln,module:"ui",capability:ln,requirement:{kind:"none"},risk:"low"},{method:un,module:"device",capability:un,requirement:{kind:"none"},risk:"low"},{method:fn,module:"device",capability:fn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:hn,module:"navigation",capability:hn,requirement:{kind:"none"},risk:"medium"},{method:mn,module:"navigation",capability:mn,requirement:{kind:"none"},risk:"medium"},{method:pn,module:"navigation",capability:pn,requirement:{kind:"none"},risk:"medium"},{method:Me,module:"cloud",capability:Me,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:be,module:"cloud",capability:be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:qe,module:"cloud",capability:qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:st,module:"cloud",capability:st,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[_n,Sn,vn,On,Rn,Dn,Nn,Pn,Tn,Cn,Ln,Mn].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Je="heybox:miniprogram",Ba=2,Qd="hb_mini_bridge_nonce",Va="sdk.handshake",pr="runtime.location.probe",Jd="sdk.location.report",Xd="sdk.csp.violation",qa="operation.progress",Zd="companion.session.output",el="companion.session.exit",tl="companion.session.ownershipLost";function rl(e){return!Ye(e)||e.namespace!==Je||e.version!==1&&e.version!==2||!ae(e.nonce)?!1:e.type==="handshake"?ae(e.id)&&e.method===Va&&e.error===void 0&&sl(e.payload):e.type==="request"?ae(e.id)&&ae(e.method)&&e.error===void 0:e.type==="response"?ae(e.id)&&(e.method===void 0||ae(e.method))&&(e.error===void 0||al(e.error)):e.type==="event"?!ae(e.method)||e.error!==void 0?!1:e.method===qa?e.version===2&&ae(e.id)&&ol(e.payload):e.id===void 0||ae(e.id):e.type==="cancel"?e.version===2&&ae(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ao(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function za(e){return Ye(e)?e.kind==="sandbox"?ke(e,["kind"]):e.kind==="directory"&&ae(e.handleId)&&ke(e,["kind","handleId"]):!1}function co(e){return!Ye(e)||e.kind!=="file"?!1:ae(e.handleId)?ke(e,["kind","handleId"]):za(e.root)&&ao(e.relativePath)&&ke(e,["kind","root","relativePath"])}function Ga(e){return!Ye(e)||e.kind!=="directory"?!1:ae(e.handleId)?ke(e,["kind","handleId"]):za(e.root)&&(e.relativePath==="."||ao(e.relativePath))&&ke(e,["kind","root","relativePath"])}function ja(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function nl(e){return!Ye(e)||!bt(e.loaded)||typeof e.lengthComputable!="boolean"||!ke(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?bt(e.total)&&e.loaded<=e.total:e.total===void 0}function il(e){return Ye(e)?e.phase==="downloading"?bt(e.loaded)&&(e.total===void 0||bt(e.total)&&e.loaded<=e.total)&&ke(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:bt(e.processed)&&bt(e.total)&&e.processed<=e.total&&ke(e,["phase","processed","total"]):!1}function ol(e){return nl(e)||il(e)}function sl(e){return Ye(e)&&ae(e.href)&&typeof e.userAgent=="string"&&ae(e.sdkVersion)}function al(e){return Ye(e)&&ae(e.code)&&typeof e.message=="string"}function bt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ae(e){return typeof e=="string"&&e.length>0}function ke(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rr=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network","companion"];new Set(rr);const cl=new Set(rr);function dl(e){return cl.has(e)}function Qe(e){if(!gr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!gr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!dl(o)){if(o==="network"){const s=n.config;if(!gr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!gr(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Nr=["network","companion"];function $a(e){if(!yr(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>Nr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!yr(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!yr(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!yr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Nr.indexOf(n.key)-Nr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function ll(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Qe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network"]),n=[];for(const i of Nr)!r.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||n.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:n}}function lo(e){const t=Qe(e.runtimePermissions),r=$a(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of rr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=Wa(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...o===void 0?{}:{revision:o},entries:rr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yr(e,t){return Wa(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const _t=["identity","profile","steam_account"],ul=/^[a-z][a-z0-9-]{0,31}$/,Ka=["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"];ze.map(e=>e.method);function K(e,t,r){return{code:e,message:t,data:r}}function uo(e){return fl(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?K("RUNTIME_ERROR",e.message):K("UNKNOWN_ERROR","小程序运行时异常",e)}function fl(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function hl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ml=1e3;function pl(e,t=hl()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=ml}const gl="runtime.gate.probe",Ya=new Set(ze.map(e=>e.method));class yl{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Ba;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:Je,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Je,version:2,nonce:this.nonce,type:"event",id:t,method:qa,payload:r})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{n=pl(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&rl(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Je,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Va,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===gl){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,K("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ya.has(t.method)){this.postResponse(t,void 0,K("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,K("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=uo(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:Je,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!El(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function El(e){return typeof e=="string"&&Ya.has(e)}const Qa="METHOD_FORBIDDEN";function Te(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Qa,t}class oe extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const ko={[Vr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[qr]:["account.getCurrentUserId","account.onChange","network.request"],[zr]:["account.getCurrentUserId","account.onChange","network.request"],[Gr]:["account.getCurrentUserId","account.onChange","network.request"],[jr]:["presentation.setClipboard"],[$r]:["presentation.showShareMenu"],[Wr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ot]:["presentation.applyOrientation"],[Kr]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Yr]:["presentation.setNavigationBarStyle"],[Kt]:["storage.getRaw"],[Yt]:["storage.setRaw"],[Qr]:["network.request"],[Jr]:["network.stream","files.transfer","files.access"],[Xr]:["files.external"],[Zr]:["files.external"],[en]:["files.save"],[Qt]:["files.access"],[Jt]:["files.removeFile"],[tn]:["files.access"],[Xt]:["files.access"],[rn]:["files.access"],[Zt]:["files.access"],[nn]:["files.access"],[er]:["files.access"],[on]:["files.access"],[tr]:["files.removeDirectory"],[sn]:["files.access"],[an]:["files.access"],[cn]:["presentation.showToast"],[dn]:["presentation.showLoading"],[ln]:["presentation.hideLoading"],[un]:["presentation.vibrate"],[fn]:["presentation.setClipboard"],[hn]:["presentation.close"],[mn]:["presentation.reload"],[pn]:["presentation.openAppPage"],[Me]:["account.getCurrentUserId","account.onChange","network.request"],[be]:["account.onChange","network.request"],[qe]:["account.getCurrentUserId","account.onChange","network.request"],[st]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[_n]:["companion.getInfo"],[Sn]:["companion.getPreparationStatus"],[vn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[On]:["companion.cancelPreparation"],[Rn]:["companion.getActiveSession"],[Dn]:["companion.getInfo","companion.launch"],[Nn]:["companion.session.write"],[Pn]:["companion.session.closeStdin"],[Tn]:["companion.session.terminate"],[Cn]:["companion.session.ackOutput"],[Ln]:["companion.openAttachment"],[Mn]:["companion.showNotification"]};function wl(e,t){if(t[e]!==!0)throw Te(e)}const bl=32*1024*1024,Al=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Il(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:bl},i);return _l(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function _l(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:Sl(t,Ol(e,"content-type"))}}function Sl(e,t){vl(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new oe("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Al.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function vl(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new oe(`Host network response 不支持 charset=${t}`)}function Ol(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function k(e){return typeof e=="function"}function Uo(e){return(...t)=>{throw Te(e)}}function ne(e){return async(...t)=>{throw Te(e)}}const Rl=(e,t)=>{},Dl=()=>()=>{};function Nl(e){const t={request:k(e.network?.request)?e.network.request.bind(e.network):ne("network.request")},r={getCurrentUserId:k(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):ne("account.getCurrentUserId"),ensureAuthenticated:k(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):ne("account.ensureAuthenticated"),onChange:k(e.account?.onChange)?e.account.onChange.bind(e.account):Dl},n={getRaw:k(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):ne("storage.getRaw"),setRaw:k(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):ne("storage.setRaw")},i={...k(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...k(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:k(e.presentation?.close)?e.presentation.close.bind(e.presentation):ne("presentation.close"),reload:k(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):ne("presentation.reload"),openAppPage:k(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):ne("presentation.openAppPage"),openWindow:k(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):ne("presentation.openWindow"),getViewportMetrics:k(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Uo("presentation.getViewportMetrics"),getNavigationBarHeight:k(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Uo("presentation.getNavigationBarHeight"),setNavigationBarStyle:k(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):ne("presentation.setNavigationBarStyle"),showShareMenu:k(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):ne("presentation.showShareMenu"),setScreenshotChromeHidden:k(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Rl,captureAndShare:k(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):ne("presentation.captureAndShare"),showToast:k(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):ne("presentation.showToast"),showLoading:k(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):ne("presentation.showLoading"),hideLoading:k(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):ne("presentation.hideLoading"),vibrate:k(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):ne("presentation.vibrate"),setClipboard:k(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):ne("presentation.setClipboard")},o=k(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,k(e.companion?.[a])?e.companion[a].bind(e.companion):ne(`companion.${a}`)]));return k(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion)),{network:t,account:r,storage:n,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 Pl(e){const t=Tl(e.files?.sandbox),r=k(e.picker?.pickFiles)&&k(e.picker?.pickDirectory),n=k(e.picker?.saveFile),i=t||r||n||k(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":k(e.account?.getCurrentUserId),"account.ensureAuthenticated":k(e.account?.ensureAuthenticated),"account.onChange":k(e.account?.onChange),"network.request":k(e.network?.request),"network.stream":k(e.transfer?.network.open)&&k(e.transfer?.network.release),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":k(o?.remove),"files.removeDirectory":k(e.files?.sandbox.remove),"files.transfer":k(e.transfer?.files.writeResource),"storage.getRaw":k(e.storage?.getRaw),"storage.setRaw":k(e.storage?.setRaw),"presentation.close":k(e.presentation?.close),"presentation.reload":k(e.presentation?.reload),"presentation.openAppPage":k(e.presentation?.openAppPage),"presentation.applyOrientation":k(e.presentation?.applyOrientation),"presentation.openWindow":k(e.presentation?.openWindow),"presentation.getViewportMetrics":k(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":k(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":k(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":k(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":k(e.presentation?.captureAndShare),"presentation.showToast":k(e.presentation?.showToast),"presentation.showLoading":k(e.presentation?.showLoading),"presentation.hideLoading":k(e.presentation?.hideLoading),"presentation.vibrate":k(e.presentation?.vibrate),"presentation.setClipboard":k(e.presentation?.setClipboard),"companion.getInfo":k(e.companion?.getInfo),"companion.getPreparationStatus":k(e.companion?.getPreparationStatus),"companion.prepare":k(e.companion?.prepare),"companion.cancelPreparation":k(e.companion?.cancelPreparation),"companion.getActiveSession":k(e.companion?.getActiveSession),"companion.launch":k(e.companion?.launch),"companion.session.write":k(e.companion?.write),"companion.session.closeStdin":k(e.companion?.closeStdin),"companion.session.terminate":k(e.companion?.terminate),"companion.session.ackOutput":k(e.companion?.ackOutput),"companion.openAttachment":k(e.companion?.openAttachment),"companion.showNotification":k(e.companion?.showNotification)}}function Tl(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&k(t.file)&&k(t.directory)&&k(t.create)&&k(t.stat)&&k(t.list)}function xo(e,t){return t?.[e]!==!1}function Cl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function Ja(e,t={}){const r={};for(const n of Object.keys(ko)){const o=ko[n].every(a=>e[a]),s=!Cl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=xo(n,t.callerCapabilities)&&xo(n,t.hostCapabilities)&&o&&s}return r}function Xa(e={},t={}){const r=Pl(e),n=Ja(r,t);return{ports:Nl(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function kn(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Ll(e.signal,t);return{...e,signal:r}}function Ll(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{r.signal.aborted||(n(),r.abort(a.reason))},o=()=>i(e),s=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0})),r.signal}function Ml(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 kl=4,Ul=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],xl=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),Hl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Fl=["/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 Bl(e,t){const r=zl(e);return r===null||Ho(r,Hl)?!0:t&&Ho(r,Fl)}function Vl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Ul.some(r=>t===r||t.endsWith(`.${r}`))}function ql(e){const t=e.trim().toLowerCase();return xl.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function zl(e){let t=e;for(let r=0;r<kl;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Fo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Fo(t)}function Ho(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Fo(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function lt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Bo(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Za(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function l(b,v){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:b,type:v})).catch(()=>{})}catch{}}function g(b){const v=r.get(b);if(!v)throw new Error("Unknown runtime cache scope");return v}function m(b,v){return b.flatMap((A,P)=>{const _=JSON.stringify(b.slice(0,P+1));return[JSON.stringify([_]),JSON.stringify([_,v])]})}function u(b,v){return JSON.stringify(m(b,v).map(A=>n.get(A)??0))}async function p(b,v){const A=g(b),P=JSON.stringify([JSON.stringify(A),...v?[v]:[]]),_=(n.get(P)??0)+1;n.set(P,_),i.add(P);for(const L of a)L(A,v);if(!e.store){i.delete(P),l(v??"*","invalidation");return}try{await e.store.invalidate(A,v)}catch(L){throw l(v??"*","storage_error"),L}n.get(P)===_&&i.delete(P),l(v??"*","invalidation")}function R(b){if(c)throw new Error("Runtime cache manager disposed");const v=o.get(b.namespace);if(v){if(v.sourceCodec!==b.codec||v.definition.codec.version!==b.codec.version||JSON.stringify(v.definition.policy)!==JSON.stringify(b.policy))throw new Error("Conflicting runtime cache namespace");return v.cache}if(!b.namespace||!b.codec.version)throw new Error("Invalid runtime cache definition");const A=Object.freeze({...b.policy}),P=Object.freeze({version:b.codec.version,encode:b.codec.encode.bind(b.codec),decode:b.codec.decode.bind(b.codec),validate:b.codec.validate.bind(b.codec),clone:b.codec.clone.bind(b.codec)}),_=b.namespace;for(const D of[A.ttlMs,A.memoryMaxEntries,A.diskMaxEntries,A.diskMaxBytes,A.maxEntryBytes])if(!Number.isFinite(D)||D<0)throw new Error("Invalid runtime cache policy");const L=new Map,F=new Map,N=new Map;let I=!1;function d(D,M,O){if(c||I||D.aborted||u(M,_)!==O)throw lt()}function h(D){return A.ttlMs>0&&A.persistence==="memory-and-disk"&&!!e.store&&!m(D,_).some(M=>i.has(M))}function f(D,M,O){const U=t();return D.envelopeVersion===1&&JSON.stringify(D.address)===JSON.stringify(M)&&Bo(D.revisions,O)&&D.payload.byteLength<=A.maxEntryBytes&&Number.isFinite(D.cachedAt)&&Number.isFinite(D.expiresAt)&&D.cachedAt<=U&&D.cachedAt>=0&&D.expiresAt>D.cachedAt&&Math.min(D.expiresAt,D.cachedAt+A.ttlMs)>U}function y(D,M,O,U,x){if(!(A.ttlMs<=0||A.memoryMaxEntries<1)){for(const[H,q]of L)Math.min(q.entry.expiresAt,q.entry.cachedAt+A.ttlMs)<=t()&&L.delete(H);for(L.delete(D);L.size>=Math.floor(A.memoryMaxEntries);){const H=L.keys().next();if(H.done)break;L.delete(H.value)}L.set(D,{entry:M,value:O,epoch:U,persistent:x})}}async function w(D,M,O,U){const x={namespace:_,codecVersion:P.version,scopeIds:M,key:D.key},H=JSON.stringify(x);let q=[],z=h(M);if(z)try{q=await e.store.readRevisions(M,_)}catch{z=!1,l(_,"storage_error")}d(U.signal,M,O);async function G(){if(!z)return!0;try{return Bo(q,await e.store.readRevisions(M,_))}catch{return z=!1,l(_,"storage_error"),!1}}const ee=L.get(H);if(A.ttlMs>0&&ee&&ee.epoch===O&&f(ee.entry,x,q)&&ee.persistent===z&&await G())return d(U.signal,M,O),l(_,"memory_hit"),ee.value;if(L.delete(H),z){let $,fe;try{$=await e.store.read(x,A.maxEntryBytes),$&&f($,x,q)?fe=P.decode($.payload):$=void 0}catch{$=void 0,l(_,"storage_error")}if(d(U.signal,M,O),$&&await G())return d(U.signal,M,O),y(H,$,fe,O,!0),l(_,"disk_hit"),fe}l(_,"miss");const Z=P.validate(await D.load(U.signal));d(U.signal,M,O);const J=P.clone(Z);if(!await G()&&z)throw lt();if(d(U.signal,M,O),A.ttlMs>0){const $=t();let fe;try{fe=P.encode(J)}catch{return J}const Co={envelopeVersion:1,address:x,revisions:z?q:[],cachedAt:$,expiresAt:$+A.ttlMs,payload:fe};if(z&&fe.byteLength<=A.maxEntryBytes){let Wn=!0,Lo=!1;try{Wn=await e.store.publish(Co,A),Lo=Wn}catch{l(_,"storage_error")}if(d(U.signal,M,O),!Wn)throw lt();Lo&&l(_,"published")}d(U.signal,M,O),y(H,Co,J,O,z)}return J}async function S(D){if(c||I||D.signal?.aborted)return Promise.reject(lt());const M=g(D.scope),O=u(M,_);let U;if(h(M)){const z=new AbortController;N.set(z,M);const G=()=>z.abort();D.signal?.addEventListener("abort",G,{once:!0});let ee=()=>{};try{U=await Promise.race([e.store.readRevisions(M,_),new Promise((Z,J)=>{const $=()=>J(lt());z.signal.addEventListener("abort",$,{once:!0}),ee=()=>z.signal.removeEventListener("abort",$)})])}catch{z.signal.aborted||l(_,"storage_error")}finally{ee(),N.delete(z),D.signal?.removeEventListener("abort",G)}}d(D.signal??new AbortController().signal,M,O);const x=JSON.stringify([M,D.key,O,U]);let H=F.get(x);if(H?.controller.signal.aborted&&(H=void 0),!H){const z=new AbortController;H={ids:M,controller:z,waiters:0,promise:Promise.resolve(void 0)};const G=H;G.promise=w(D,M,O,z).finally(()=>{F.get(x)===G&&F.delete(x)}),F.set(x,G)}const q=H;return q.waiters+=1,new Promise((z,G)=>{let ee=!1;function Z($){ee||(ee=!0,D.signal?.removeEventListener("abort",J),q.controller.signal.removeEventListener("abort",J),q.waiters-=1,q.waiters===0&&q.controller.abort(),$())}function J(){Z(()=>G(lt()))}D.signal?.addEventListener("abort",J,{once:!0}),q.controller.signal.addEventListener("abort",J,{once:!0}),q.promise.then($=>Z(()=>{try{d(D.signal??new AbortController().signal,M,O),z(P.clone($))}catch(fe){G(fe)}}),$=>Z(()=>G($)))})}function T(D,M){if(M&&M!==_)return;const O=U=>D.every((x,H)=>U[H]===x);for(const[U,x]of L)O(x.entry.address.scopeIds)&&L.delete(U);for(const[U,x]of F)O(x.ids)&&(x.controller.abort(),F.delete(U));for(const[U,x]of N)O(x)&&U.abort()}function V(){if(!I){I=!0,L.clear();for(const D of N.keys())D.abort();N.clear();for(const D of F.values())D.controller.abort();F.clear(),s.delete(V),a.delete(T),o.get(_)?.cache===C&&o.delete(_)}}const C={read:S,invalidateScope:D=>p(D,_),dispose:V};return s.add(V),a.add(T),o.set(_,{definition:{namespace:_,codec:P,policy:A},sourceCodec:b.codec,cache:C}),C}return{createScope(b,v){if(c||!b)throw new Error("Invalid runtime cache scope");const A=Object.freeze({});return r.set(A,[...v?g(v):[],b]),A},register:R,invalidateScope:b=>p(b),dispose(){if(!c){c=!0;for(const b of[...s])b();o.clear(),n.clear(),i.clear()}}}}function Gl(e){const t=new TextEncoder,r=new TextDecoder("utf-8",{fatal:!0});return{version:e.version,validate:e.validate,encode:n=>t.encode(JSON.stringify(n)),decode:n=>e.validate(JSON.parse(r.decode(n))),clone:n=>e.validate(JSON.parse(JSON.stringify(n)))}}const jl=".hb-runtime-cache-v1",Kn=64*1024,ut=1e3,$l=2048,Pt=32*1024*1024,Wl=1024,Pr=new TextEncoder,Vo=new TextDecoder("utf-8",{fatal:!0});function Tt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Er(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Pr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function _e(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qo(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Kl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function zo(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Yl(e,t){const r=e.sandbox.directory(jl),n=r.directory("revisions"),i=r.directory("entries");for(const d of[r,n,i,i.directory("capability-check")])zo(d,["directory","file","create","stat","list","remove"]),zo(d.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(d){if(Kl(d))throw s=!0,d}function c(){if(t.signal.aborted)throw Tt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function l(d,h=t.signal){const f=o.then(()=>{if(h.aborted)throw Tt();return c(),d()},()=>{if(h.aborted)throw Tt();return c(),d()}).catch(S=>{throw a(S),S});if(o=f.catch(()=>{}),h.aborted)return Promise.reject(Tt());let y=()=>{};const w=new Promise((S,T)=>{const V=()=>T(Tt());h.addEventListener("abort",V,{once:!0}),y=()=>h.removeEventListener("abort",V)});return Promise.race([f,w]).finally(y)}async function g(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function m(d,h){const f=n.file(`${await Er([d,h??null])}.revision`);await p(f);let y=!1;try{await f.create({recursive:!1,exclusive:!0},t),y=!0}catch(T){a(T),c()}if(y){const T=qo();return await f.write(Pr.encode(T),t),c(),T}const w=await f.stat(t);if(w.size<1||w.size>128)throw new Error("缓存 revision 文件损坏");const S=Vo.decode(await f.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return c(),S}async function u(d){const h=await d.list({limit:ut},t);if(h.length>=ut)throw new Error("缓存目录超过治理上限");return h}async function p(d){try{await d.stat(t);return}catch(f){if(!wr(f))throw f}if((await u(n)).length>=ut-1)throw new Error("缓存 metadata 超过治理上限")}async function R(d,h){await g();const f=[];for(let y=0;y<d.length;y+=1){const w=d.slice(0,y+1);f.push(await m(w),await m(w,h))}return f}async function b(d){return r.directory(`entries/${await Er([d.namespace,d.codecVersion,d.scopeIds])}`)}async function v(d){return(await b(d)).file(`${await Er(d.key)}.cache`)}async function A(d,h){const f=await d.stat(t);if(f.size<5||f.size>h+Kn+4)throw new Error("缓存条目超过大小限制");const y=await d.read(t);if(c(),y.length!==f.size)throw new Error("缓存条目读取不完整");const w=new DataView(y.buffer,y.byteOffset,y.byteLength).getUint32(0);if(w<1||w>Kn||w+4>y.length)throw new Error("缓存信封损坏");const S=JSON.parse(Vo.decode(y.subarray(4,w+4))),T=y.slice(w+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(V=>typeof V=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(V=>typeof V=="string"&&V.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==T.length||T.length>h)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:T}}async function P(d){if(!d.remove)throw new Error("Host 不支持缓存文件删除");await d.remove(t)}async function _(d){try{if((await d.file.stat(t)).size!==d.size)return!1;const h=await A(d.file,Pt);return!_e(h.address,d.entry.address)||!_e(h.revisions,d.entry.revisions)||h.cachedAt!==d.entry.cachedAt||h.expiresAt!==d.entry.expiresAt||!_e(await L(h.payload),await L(d.entry.payload))?!1:(await P(d.file),!0)}catch(h){if(wr(h))return!0;throw h}}async function L(d){const h=await globalThis.crypto.subtle.digest("SHA-256",d);return Array.from(new Uint8Array(h),f=>f.toString(16).padStart(2,"0")).join("")}async function F(){const d=await u(n);let h=0;for(const S of d)if(S.kind==="file"&&(h+=(await S.stat(t)).size,h>Pt))throw new Error("缓存扫描超过字节上限");const f=[];let y=0,w=h;for(const S of await u(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const T of await u(S)){if(T.kind!=="file"||++y>$l)throw new Error("缓存文件超过治理上限");const V=(await T.stat(t)).size;if(w+=V,w>Pt)throw new Error("缓存扫描超过字节上限");try{const C=await A(T,Pt);f.push({file:T,entry:C,size:(await T.stat(t)).size,bucketName:S.name})}catch(C){a(C),c(),wr(C)||await P(T)}}}return{entries:f,metadataBytes:h}}async function N(){for(const d of await u(i))if(d.kind==="directory"&&d.remove&&(await u(d)).length===0)try{await d.remove({recursive:!1},t)}catch(h){a(h),c()}}function I(d){const{payload:h,...f}=d,y=Pr.encode(JSON.stringify({...f,payloadBytes:h.length}));if(y.length>Kn)throw new Error("缓存信封过大");const w=new Uint8Array(4+y.length+h.length);return new DataView(w.buffer).setUint32(0,y.length),w.set(y,4),w.set(h,y.length+4),w}return{readRevisions:(d,h)=>l(()=>R(d,h)),read:(d,h)=>l(async()=>{c();const f=await v(d);let y;try{y=await A(f,h)}catch(w){if(c(),wr(w))return;throw w}if(!(!_e(y.address,d)||y.expiresAt<=Date.now())&&_e(y.revisions,await R(d.scopeIds,d.namespace)))return y}),publish:(d,h)=>l(async()=>{c();const{address:f}=d;if(!_e(d.revisions,await R(f.scopeIds,f.namespace)))return!1;const y=I(d);if(d.payload.length>h.maxEntryBytes||y.length>h.diskMaxBytes||h.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await g();const w=await b(f),S=await v(f),T=await F(),V=[],C=new Map;for(const O of T.entries){if(O.bucketName===w.name&&O.file.name===S.name)continue;const U=JSON.stringify([O.entry.address.scopeIds,O.entry.address.namespace]);let x=C.get(U);if(x||(x=await R(O.entry.address.scopeIds,O.entry.address.namespace),C.set(U,x)),O.entry.expiresAt<=Date.now()||!_e(O.entry.revisions,x)){if(!await _(O))throw new Error("缓存治理期间条目已变化")}else V.push(O)}V.sort((O,U)=>O.entry.cachedAt-U.entry.cachedAt);function D(){const O=V.filter(U=>U.bucketName===w.name);return V.length+1>Wl||y.length+T.metadataBytes+V.reduce((U,x)=>U+x.size,0)>Pt||O.length+1>Math.min(h.diskMaxEntries,ut-1)||y.length+O.reduce((U,x)=>U+x.size,0)>h.diskMaxBytes}for(;D();){const O=V.filter(H=>H.bucketName===w.name),x=O.length+1>Math.min(h.diskMaxEntries,ut-1)||y.length+O.reduce((H,q)=>H+q.size,0)>h.diskMaxBytes?O[0]:V[0];if(!x||!await _(x))throw new Error("缓存容量不足或条目已变化");V.splice(V.indexOf(x),1)}await N();const M=await u(i);if(!M.some(O=>O.name===w.name)&&M.length>=ut-1)throw new Error("缓存目录超过治理上限");if(await w.create({recursive:!0,exclusive:!1},t),!_e(d.revisions,await R(f.scopeIds,f.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},t)}catch(O){a(O),await S.stat(t)}return await S.write(y,t),c(),_e(d.revisions,await R(f.scopeIds,f.namespace))}),invalidate:(d,h)=>l(async()=>{await g();const f=n.file(`${await Er([d,h??null])}.revision`);await p(f);try{await f.create({recursive:!1,exclusive:!0},t)}catch(y){a(y),await f.stat(t)}await f.write(Pr.encode(qo()),t),c();try{const{entries:y}=await F();for(const w of y){if(h!==void 0&&w.entry.address.namespace!==h||!d.every((T,V)=>w.entry.address.scopeIds[V]===T))continue;const S=await R(w.entry.address.scopeIds,w.entry.address.namespace);_e(w.entry.revisions,S)||await _(w)}await N()}catch(y){a(y),c()}})}}function wr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Ql="RATE_LIMITED_BY_RUNTIME",Jl="RATE_LIMITED",ec=20,tc=40,rc=150,nc=20,ic=1e4,oc=45e3,sc=1,Xl=300*1e3,Zl=64;function ft(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function eu(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function tu(e={}){const t=e.now??Date.now,r=eu(e.coalesceWindowMs,rc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,ft(e.budget?.ratePerSecond,ec)),burst:Math.max(1,Math.floor(ft(e.budget?.burst,tc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(ft(e.loopDetection?.maxCalls,nc))),windowMs:Math.max(1,Math.floor(ft(e.loopDetection?.windowMs,ic)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(ft(e.circuitBreaker?.failureThreshold,sc))),openMs:Math.max(1,Math.floor(ft(e.circuitBreaker?.openMs,oc)))},s=new Map,a=new Map,c=new Set,l=new Map,g=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},m={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function p(I){try{e.onReport?.(I)}catch{}}function R(I,d){if(!i)return{exceeded:!1,count:0};const h=a.get(I)??[],f=d-i.windowMs;let y=0;for(;y<h.length&&h[y]<=f;)y+=1;y>0&&h.splice(0,y);const w=h.length>=i.maxCalls;return w||(h.push(d),h.length>i.maxCalls+1&&h.splice(0,h.length-(i.maxCalls+1))),a.set(I,h),{exceeded:w,count:h.length}}function b(I){if(!n)return!0;const d=Math.max(0,I-g.updatedAt)/1e3;return g.tokens=Math.min(n.burst,g.tokens+d*n.ratePerSecond),g.updatedAt=I,g.tokens<1?!1:(g.tokens-=1,!0)}function v(I){if(!n)return 0;const d=Math.max(0,I-g.updatedAt)/1e3,h=Math.min(n.burst,g.tokens+d*n.ratePerSecond);return Math.max(0,Math.ceil((1-h)/n.ratePerSecond*1e3))}function A(I,d,h,f,y){if(!o)return;const w=l.get(d),S=(w?.open?0:w?.failures??0)+1;if(S<o.failureThreshold){l.set(d,{open:!1,openedAt:0,openMs:0,failures:S});return}const T=Math.min(Math.max(o.openMs,f),Xl);l.set(d,{open:!0,openedAt:y,openMs:T,failures:S}),m.circuitOpened+=1,p({type:"circuit_opened",capability:I,endpointId:d,status:h,openMs:T,timestamp:y})}function P(I){const d=l.get(I);d&&!d.open&&l.delete(I)}function _(I){for(const[d,h]of s)!h.pending&&h.expiresAt<=I&&s.delete(d);for(;s.size>=Zl;){const d=[...s].find(([,h])=>!h.pending);if(!d)break;s.delete(d[0])}}function L(I,d){if(I===void 0)return;const h=s.get(I);h?.promise===d&&(h.pending=!1)}function F(I,d){if(I===void 0)return;s.get(I)?.promise===d&&s.delete(I)}async function N(I){if(u)return I.load();const d=t();if(o){const w=l.get(I.endpointId);if(w?.open){const S=w.openedAt+w.openMs-d;if(S>0)throw m.circuitRejected+=1,p({type:"circuit_rejected",capability:I.capability,endpointId:I.endpointId,retryAfterMs:S,timestamp:d}),iu("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:I.endpointId,retryAfterMs:S});l.delete(I.endpointId)}}const h=R(I.endpointId,d);h.exceeded&&i?c.has(I.endpointId)||(c.add(I.endpointId),p({type:"loop_detected",capability:I.capability,endpointId:I.endpointId,count:h.count,windowMs:i.windowMs,timestamp:d})):c.delete(I.endpointId);const f=r>0?I.coalesceKey:void 0;if(f!==void 0){const w=s.get(f);if(w&&(w.pending||w.expiresAt>d))return m.coalesced+=1,p({type:"coalesced",capability:I.capability,endpointId:I.endpointId,timestamp:d}),w.promise;w&&s.delete(f)}if(h.exceeded&&i)throw m.loopRejected+=1,Go("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:I.capability,endpointId:I.endpointId,count:h.count,windowMs:i.windowMs});if(!b(d)){m.budgetRejected+=1;const w=v(d);throw p({type:"budget_exhausted",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w,timestamp:d}),Go("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w})}f!==void 0&&_(d);const y=I.load().then(w=>(L(f,y),P(I.endpointId),w),w=>{F(f,y);const S=ru(w);throw S!==void 0&&A(I.capability,I.endpointId,S,nu(w),d),w});return f!==void 0&&s.set(f,{promise:y,expiresAt:d+r,pending:!0}),y}return{execute:N,invalidateCoalescing(){s.clear()},snapshot(){return{...m,openCircuits:[...l.entries()].filter(([,I])=>I.open).map(([I])=>I)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),l.clear())}}}function ru(e){if(typeof e!="object"||e===null)return;const t=e.status;if(!(typeof t!="number"||!Number.isInteger(t)))return t===403||t===429?t:void 0}function nu(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Go(e,t){return{code:Ql,message:e,data:t}}function iu(e,t){return{code:Jl,message:e,data:t}}const ac=3e4,cc=6e4,ki=1440*60*1e3;function ou(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??ac)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??cc)):0,steamGameListTtlMs:t?su(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:ec,burst:tc},coalesceWindowMs:r?.coalesceWindowMs??rc,loopDetection:r?.loopDetection??{maxCalls:nc,windowMs:ic},circuitBreaker:r?.circuitBreaker??{failureThreshold:sc,openMs:oc}}}}function su(e){return e===void 0||!Number.isFinite(e)?ki:Math.max(0,Math.floor(e))}function E(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function au(e){return typeof e=="object"&&e!==null}function ge(e,t){const r=e.data;if(!au(r)||typeof r.status!="string")throw new Error(t);return r}const dc={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},cu={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 ge(e,"工坊小程序详情加载失败")}};function dr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function du(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function lu(e){const t=ge(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=du(r.consent_challenge)),{...t,result:n}}const uu={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=>({...dr(e.runtimeContext),challenge:e.challenge}),parse:e=>ge(e,"小程序授权取消接口响应异常")},fu={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=>dr(e.runtimeContext),parse:e=>ge(e,"小程序授权撤销接口响应异常")},hu={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=>dr(e.runtimeContext),parse(e){const t=ge(e,"小程序隔离身份接口响应异常"),r=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,...r?{steamId:r}:{}}}}},mu={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=>({...dr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>lu(e)},pu={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=>({...dr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ge(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},gu=64;function lc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??gu)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(m){for(const[u,p]of i)p.expiresAt<=m&&i.delete(u)}function l(m,u,p){if(a||t<=0||p!==s)return;const R=n();for(c(R),i.delete(m);i.size>=r;){const b=i.keys().next();if(b.done)break;i.delete(b.value)}i.set(m,{expiresAt:R+t,value:u})}function g(m,u){if(a)return u();if(t>0){const v=i.get(m);if(v&&v.expiresAt>n())return Promise.resolve(v.value);v&&i.delete(m)}const p=o.get(m);if(p)return p;const R=s,b=u().then(v=>(l(m,v,R),v)).finally(()=>{o.get(m)===b&&o.delete(m)});return o.set(m,b),b}return{read:g,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function yu(e,t){return t?e?"server":"local":"legacy"}function Eu(e,t){if(e==="local")throw E("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const wu=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],bu=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Au=/authorization|cookie|pkey|password|secret|token/i,uc=/authorization|cookie|pkey|token|password|secret/i;function Se(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Iu(e){for(const t of Object.keys(e))if(!bu.has(t))throw new oe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of wu)if(Object.prototype.hasOwnProperty.call(e,t)&&Se(e,t)!==void 0)throw new oe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Se(e,"bodyEncoding")!==void 0&&Se(e,"bodyEncoding")!=="json"&&Se(e,"bodyEncoding")!=="form")throw new oe("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Se(e,"failurePresentation")!==void 0&&Se(e,"failurePresentation")!=="none")throw new oe("endpoint failurePresentation 必须为 none");if(Se(e,"auth")!==void 0&&Se(e,"auth")!=="none"&&Se(e,"auth")!=="optional"&&Se(e,"auth")!=="required")throw new oe("endpoint auth 必须为 none、optional 或 required")}function Vt(e){if(Array.isArray(e))return e.map(Vt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Au.test(n)||(r[n]=Vt(i));return r}function jo(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))uc.test(r)||(t[r]=n);return t}function _u(e){if(!e)return;const t=Object.keys(e).find(r=>uc.test(r));if(t)throw new oe(`endpoint 禁止声明 credential-bearing header: ${t}`)}class St extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const $o=1440*60*1e3,Su=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function vu(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([s])=>s.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const s=Number(n)*1e3;return s>0?Math.min(s,$o):void 0}if(!Su.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,$o):void 0}function Ou(e,t,r,n){if(e.method!=="GET")return;let i;try{i=JSON.stringify([t??null,r??null])??"undefined"}catch{return}return`${e.id}\0${n}\0${i}`}function fc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class vt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,fc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class lr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,fc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Ru(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Vt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:jo(o),method:e.method,metadata:{endpointId:e.id},query:Vt(n),timeout:e.timeout,url:r},data:Vt(a.data),headers:jo(a.headers)||{},status:a.status,statusText:a.statusText}}async function Un(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Iu(t),typeof t.id!="string"||!t.id)throw new oe("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new oe("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new oe("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;_u(a);const c=async()=>{let m;try{m=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(p){throw p instanceof oe?p:new vt({endpointId:t.id,cause:p})}if(m.status<200||m.status>=300)throw new St({endpointId:t.id,status:m.status,retryAfterMs:vu(m.headers)});const u=Ru(t,r,i,o,s,a,n,m);if(t.parse)try{return await t.parse(u,r)}catch(p){throw new lr({endpointId:t.id,cause:p})}return u.data},l=n.gate;if(!l)return c();const g=Ou(t,o,s,n.credentials);return l.gate.execute({capability:l.capability,endpointId:t.id,...g===void 0?{}:{coalesceKey:g},load:c})}const Du=new Set(_t),fo="steam_account",hc=new Set(_t.filter(e=>e!==fo)),Nu=1e3;function Pu(e){const t=new Set,r=lc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??ac))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,l=e.userDataMode??yu(e.networkEnabled===!0,c),g=e.requestPolicyEnabled!==!1,m=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c)return{};if(!e.authorizationContext)throw E("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch{throw E("REQUEST_FAILED","读取 Runtime auth context 失败")}if(C.steamAccount!==c||C.userDataMode!==l)throw E("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const D=C.token.trim();if(!D)throw E("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:D}}const p=e.account.onChange(C=>{R(),b("heybox_app_login_change",{isHeyboxAppLoggedIn:!!C})});function R(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function b(C,D){C==="user_info_authorization_change"&&xu(D)&&r.invalidate();for(const M of t)try{M(C,D)}catch{}}function v(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw E("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function A(){if(o||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function P(){A();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(D){throw Qo(D,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function _(C,D){const M=await P();if(i!==D||M!==C)throw E("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function L(C){A();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(M){throw Qo(M,e.operationContext.signal,"小黑盒登录失败")}const D=await P();if(!D)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return D}async function F(C,D,M=e.operationContext.signal){try{if(M.aborted)throw Ui();return await Uu(Un(e.network,C,D,{...e.operationContext,credentials:"heybox-session",signal:M,...m?{gate:m}:{}}),M)}catch(O){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):O instanceof oe?E("REQUEST_UNSUPPORTED",O.message):O instanceof lr?E("INVALID_RESPONSE","授权接口响应不合法"):O instanceof vt?E("REQUEST_FAILED","授权请求失败"):O instanceof St?g&&(O.status===403||O.status===429)?E("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:O.status,...O.retryAfterMs===void 0?{}:{retryAfterMs:O.retryAfterMs}}):E("REQUEST_FAILED",O.message):mc(O)?O:E("REQUEST_FAILED","授权请求失败")}}async function N(C,D){await F(uu,{runtimeContext:{miniProgramId:C,...await u()},challenge:D}).catch(()=>{})}function I(C){const D=async()=>{const O=Ko(e.operationContext.signal);a=O;try{return await C(O.signal)}finally{a===O&&(a=void 0),O.abort()}},M=s.then(D,D);return s=M.then(()=>{},()=>{}),M}async function d(C,D,M,O,U){if(!M)throw await N(C,D.challenge),E("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await N(C,D.challenge),E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return I(async x=>{await _(O,U);const H=await h(C,D.displayedScopes,x);await _(O,U);let q;try{q=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:D.displayedScopes,...H,signal:x})}catch(G){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(O,U),await N(C,D.challenge),Tu("REQUEST_FAILED","授权确认界面执行失败",G))}if(await _(O,U),q.status!=="granted")throw await N(C,D.challenge),E("AUTHORIZATION_CANCELLED","用户取消授权");const z=Mu(q.grantedScopes,D.displayedScopes,c);if(!z.includes("identity"))throw await N(C,D.challenge),E("AUTHORIZATION_CANCELLED","用户拒绝授权");return z})}async function h(C,D,M){const O=Ko(M),U=setTimeout(()=>O.abort(),Nu);try{const x=ku(e.miniProgramPresentation),[H,q]=await Promise.all([x?Promise.resolve(x):f(C,O.signal),D.includes("profile")?y(O.signal):Promise.resolve(void 0)]);return{...H?{miniProgram:H}:{},...q?{userProfile:q}:{}}}finally{clearTimeout(U),O.abort()}}async function f(C,D){try{const M=e.identity.get()?.version?.trim(),O=await F(cu,{mini_program_id:C,...M?{miniprogram_version:M}:{}},D),U=ht(O,"小程序公开资料"),x=At(U.name),H=At(U.icon_url);return x||H?{...x?{name:x}:{},...H?{avatarUrl:H}:{}}:void 0}catch{return}}async function y(C){try{const D=await F(dc,void 0,C),M=ht(D,"账号基础信息"),O=At(M.display_username),U=At(M.display_avatar);return O||U?{...O?{nickname:O}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function w(C,D){if(Eu(l,"auth.login"),!c&&C.includes(fo))throw E("INVALID_PARAMS","auth.login 参数不合法");const M=v(),O=await L(D),U=i,x=await F(mu,{runtimeContext:{miniProgramId:M,...await u()},scopes:C});await _(O,U);const H=ht(x,"小程序登录"),q=Yo(H,"loginCode"),z=Yo(H,"consentChallenge");if(q===z)throw E("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let G;if(q)G=Wo(H.loginCode,c);else{const ee=Cu(H.consentChallenge,c),Z=await d(M,ee,D,O,U);await _(O,U);const J=await F(pu,{runtimeContext:{miniProgramId:M,...await u()},challenge:ee.challenge,selectedScopes:Z});if(await _(O,U),G=Wo(ht(J,"小程序登录确认"),c),G.scopes.some($=>!Z.includes($)))throw E("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ee of G.scopes)n.add(ee);return r.invalidate(),b("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),b("user_info_authorization_change",Yn(n,c)),G}async function S(C,D){const M=i,O=await F(hu,{runtimeContext:{miniProgramId:D,...await u()}});await _(C,M);const U=Lu(ht(O,"用户本地身份"),c);for(const x of c?_t:hc)n.add(x);return b("user_info_authorization_change",Yn(n,c)),U}function T(C){A();const D=v(),M=`${C}\0${D}\0${i}\0${c}`;return r.read(M,()=>S(C,D))}async function V(C){if(!C)throw E("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const D=v(),M=i,O=await P();if(!O)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await F(fu,{runtimeContext:{miniProgramId:D,...await u()}});await _(O,M),ht(U,"用户授权撤销"),R(),b("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:w,getOrCreateLocalIdentity:T,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Yn(n,c),revoke:V,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,R(),r.dispose(),p(),t.clear())}}}function Tu(e,t,r){const n=E(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function ht(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Wo(e,t){if(!B(e))throw E("INVALID_RESPONSE","login code 必须是对象");const r=gn(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw E("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Cu(e,t){if(!B(e))throw E("INVALID_RESPONSE","授权 challenge 必须是对象");const r=gn(e.requestedScopes,"challenge requestedScopes",t),n=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||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw E("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Lu(e,t){if(!B(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw E("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw E("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function Mu(e,t,r){const n=gn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw E("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function At(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ku(e){const t=At(e?.name),r=At(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ko(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 Uu(e,t){return t.aborted?Promise.reject(Ui()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Ui()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Ui(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function gn(e,t,r){const n=r?Du:hc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw E("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Yn(e,t){const r=t?_t:_t.filter(n=>n!==fo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Yo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function xu(e){return B(e)?Object.values(e).some(t=>t==="denied"):!1}function mc(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Qo(e,t,r){return t.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):mc(e)?e:E("REQUEST_FAILED",r)}const Hu=new Set(_t);function Fu(e){return{[Vr]:async(t,r)=>e.authorization.login(Bu(t),r.trustedUserGesture)}}function Bu(e){if(e===void 0)return["identity"];if(!B(e)||Object.keys(e).some(t=>t!=="scopes"))throw Jo();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Hu.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Jo();return[...e.scopes]}function Jo(){return E("INVALID_PARAMS","auth.login 参数不合法")}const Vu={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 ge(e,"排行榜记录删除接口响应异常")}},qu={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 ge(e,"当前排行榜记录接口响应异常")}},zu={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 ge(e,"排行榜信息接口响应异常")}},Gu={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 ge(e,"排行榜列表接口响应异常")}},ju={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 ge(e,"排行榜提交接口响应异常")}};function Tr(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Xo(e){return e instanceof oe?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function te(e){if(e.aborted)throw Tr()}function X(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Tr());let n;try{n=e()}catch(i){return Promise.reject(Xo(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Tr())):new Promise((i,o)=>{let s=!1;const a=l=>{s||(s=!0,t.removeEventListener("abort",c),l())},c=()=>a(()=>o(Tr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(l=>a(()=>i(l)),l=>a(()=>o(Xo(l))))})}const $u="default",Wu=/^[A-Za-z0-9_-]{1,64}$/,Ku=300*1e3,Yu=250,Qu=3,Ju={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 Xu{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=ef(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;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(ju,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Ct(i,Me);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Qn(o,Me)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Lt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(Gu,{miniProgramId:r,...t}),s=Ct(o,be);if(!Ne(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw re(`${be} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw re(`${be} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Qn(a,be)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=Lt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(qu,{miniProgramId:n,...t}),c=Ct(a,qe);if(!Ne(c))throw re(`${qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Qn(c.entry,qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Vu,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Ct(i,st);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ne(o)||typeof o.deleted!="boolean")throw re(`${st} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Lt("info"),async()=>{const i=await this.request(zu,{miniProgramId:r,...t}),o=Ct(i,De);if(!Ne(o)||typeof o.key!="string"||!Wu.test(o.key))throw re(`${De} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw re(`${De} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw re(`${De} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw re(`${De} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=Lt(t,n),l=this.inflight.get(c);if(l)return l.promise;const g=this.accountGeneration,m=o?.generation,u=i().then(p=>(this.assertAccountGeneration(g),o&&s&&o.generation===m&&(r==="list"?s.size>=Yu&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Ku,value:p})),p)).finally(()=>{this.inflight.get(c)?.promise===u&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:u}),u}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Qu)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)es(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){es(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await X(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw rs(n)?n:ts()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw Ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw Ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Lt(t,r??$u)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw Ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await X(()=>Un(n,t,r,{...this.options.operationContext,credentials:"heybox-session",...this.requestGateContext?{gate:this.requestGateContext}:{}}),this.options.operationContext.signal)}catch(i){if(rs(i)||Ht(i,"REQUEST_UNSUPPORTED")||Ht(i,"RATE_LIMITED")||Ht(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof oe)throw Ee("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求");if(i instanceof vt&&Ht(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof St){if(this.options.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw Ee("RATE_LIMITED","排行榜请求已被网关限流,请稍后重试",{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw Ee("UNAUTHORIZED","当前用户未登录")}throw i instanceof vt||i instanceof St?ts():i instanceof lr?re(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):re(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(te(this.options.operationContext.signal),this.disposed)throw Ee("INVALID_STATE","Cloud capability 已释放")}}function Zu(e){return new Xu(e)}function ef(e,t){try{return e.onChange(t)}catch(r){if(Ht(r,Qa))return()=>{};throw r}}function Ct(e,t){if(!Ne(e)||typeof e.status!="string")throw re(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw tf(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw re(`${t} 响应缺少 result`);return e.result}function Qn(e,t){if(!Ne(e))throw re(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw re(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw re(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw re(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw re(`${t} 返回的 score 必须是有限数字`);if(!Ne(e.extra))throw re(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw re(`${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 tf(e){if(e.status==="login"||e.status==="relogin")throw Ee("UNAUTHORIZED",xt(e.msg)||"当前用户未登录");const t=Zo(e.result)??Zo(e),r=xt(t?.user_message)||xt(e.msg)||xt(t?.developer_message)||"排行榜请求失败";throw t?Ee(rf(t),r,{status:e.status,sbe:t}):Ee("HEYBOX_API_ERROR",r,{status:e.status})}function Zo(e){return Ne(e)&&Ne(e.sbe)?e.sbe:void 0}function rf(e){const t=xt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return Ju[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function es(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Lt(...e){return JSON.stringify(e)}function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ht(e,t){return Ne(e)&&e.code===t}function Ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return Ee("INVALID_RESPONSE",e)}function ts(){return Ee("REQUEST_FAILED","排行榜请求失败")}function rs(e){return e instanceof Error&&e.name==="AbortError"}const nf=/^[A-Za-z0-9_-]{1,64}$/,ns=20,of=100,is=2048;function sf(e){const t=Zu(e);return{handlers:{[Me]:async n=>t.submit(af(n)),[be]:async n=>t.getList(cf(n)),[qe]:async n=>t.getCurrentUserEntry(Jn(n,qe)),[st]:async n=>t.deleteCurrentUserEntry(Jn(n,st)),[De]:async n=>t.getInfo(Jn(n,De))},dispose:()=>t.dispose()}}function af(e){const t=ho(e,Me,!1);if(mo(t,["key","score","extra"],Me),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Pe("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...po(t.key,Me),score:t.score,...t.extra===void 0?{}:{extra:df(t.extra)}}}function cf(e){if(e===void 0)return{limit:ns};const t=ho(e,be,!0);mo(t,["key","limit","cursor"],be);const r=t.limit===void 0?ns:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>of)throw Pe("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Pe("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...po(t.key,be),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Jn(e,t){if(e===void 0)return{};const r=ho(e,t,!0);return mo(r,["key"],t),po(r.key,t)}function ho(e,t,r){if(e===void 0&&r)return{};if(!pc(e))throw Pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function mo(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function po(e,t){if(e===void 0)return{};if(typeof e!="string"||!nf.test(e))throw Pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function df(e){if(!pc(e))throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>is)throw Pe("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${is} 字节`);return e}function pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){return{code:e,message:t}}const lf=new Set(["stdio","attachments","notifications"]),gc=new Set(["windows-x64","macos-arm64"]),uf=new Set(["unsigned","valid","invalid","unknown"]),ff=/^[a-f0-9]{64}$/,hf=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),mf=new Set(Ka),pf=new Set([...Ka,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),yc=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 gf(e){const t=async(n,i,o,s)=>{const a=yf(n);try{Re(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Re(i.signal),c}catch(c){throw Hi(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw E("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(l=>Ef(l,i)).catch(l=>{throw Hi(l)});Re(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Re(o.signal),c.status!=="granted")throw E("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[_n]:(n,i)=>t(n,i,async(o,s)=>xi(await e.companion.getInfo(o,s),o)),[Sn]:(n,i)=>t(n,i,async(o,s)=>os(await e.companion.getPreparationStatus(o,s))),[vn]:(n,i)=>t(n,i,async(o,s)=>{const a=os(await e.companion.getPreparationStatus(o,s));return Re(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Re(i.signal),xi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(wc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[On]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Rn]:(n,i)=>t(n,i,async(o,s)=>ss(await e.companion.getActiveSession(o,s),o)),[Dn]:(n,i)=>t(n,i,async(o,s)=>{const a=ss(await e.companion.getActiveSession(o,s),o);return Re(i.signal),a||(await r("launch",o,i),Re(i.signal),bc(await e.companion.launch(o,s),o))}),[Nn]:(n,i)=>mt(n,i,e,"write"),[Pn]:(n,i)=>mt(n,i,e,"closeStdin"),[Tn]:(n,i)=>mt(n,i,e,"terminate"),[Cn]:(n,i)=>mt(n,i,e,"ackOutput"),[Ln]:async(n,i)=>{const o=await mt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Mn]:(n,i)=>mt(n,i,e,"showNotification")}}function yf(e){if(!B(e)||typeof e.alias!="string"||!ul.test(e.alias))throw E("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Re(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function mt(e,t,r,n){if(!B(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw E("INVALID_PARAMS","Companion Session controller 不合法");try{Re(t.signal);const i=await r.companion[n](wf(e,n),{...r.operationContext,signal:t.signal});return Re(t.signal),i}catch(i){throw Hi(i)}}function Ae(){throw E("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Ec(e){return!Array.isArray(e)||e.some(t=>!lf.has(t))?Ae():Object.freeze([...new Set(e)])}function xi(e,t){return!B(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!gc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!uf.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Ae():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Ec(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Ef(e,t){const r=xi(e,t);return!B(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!ff.test(e.sha256)?Ae():Object.freeze({...r,sha256:e.sha256})}function wc(e){return B(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}):Ae():Ae()}function os(e){return B(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:wc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&B(e.error)&&typeof e.error.code=="string"&&mf.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:yc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Ae():Ae()}function bc(e,t){return!B(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!gc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Ae():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Ec(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ss(e,t){return e===void 0?void 0:bc(e,t)}function wf(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!ja(r.data))throw E("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw E("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw E("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw E("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function bf(e){return!B(e)||!hf.has(String(e.reason))?Ae():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Ae():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Ae():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Af(e){if(!B(e)||!B(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=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||!ja(t.data)?void 0:{type:e.type,payload:{sessionId:r,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:r,exit:bf(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function Hi(e,t){return B(e)&&typeof e.code=="string"&&pf.has(e.code)?E(e.code,yc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&B(e)&&e.name==="AbortError"?E(t,"Companion 准备已取消"):E("COMPANION_HOST_FAILED","Companion Host 操作失败")}const as=5e3,cs=1e4;function nt(e){throw{code:"INVALID_PARAMS",message:e}}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ic(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&nt(`${r} 不支持字段: ${n.join(", ")}`)}function If(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ac(e))return nt("device.vibrate 参数必须是对象");Ic(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return nt("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>as?nt(`device.vibrate delay 必须是 0-${as} 的整数毫秒`):{intensity:r,delay:n}}function _f(e){return Ac(e)?(Ic(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?nt("device.setClipboard text 必须是非空字符串"):e.text.length>cs?nt(`device.setClipboard text 不能超过 ${cs} 字符`):{text:e.text}):nt("device.setClipboard 参数必须是对象")}function Sf(e){return{[un]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.vibrate(If(t),e.operationContext),e.operationContext.signal)},[fn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.setClipboard(_f(t),e.operationContext),e.operationContext.signal)}}}const vf=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"]),Of={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 go(e){const t=_c(e),r=t&&vf.has(t)?E(t,Of[t]??"文件操作失败"):E("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Le(e){try{return e()}catch(t){throw go(t)}}function _c(e){try{if(!B(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function Sc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):Fi,remove:o?s=>e.remove(s):Oc,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Fi,stat:s=>e.stat(s)})}function vc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:a=>Sc(e.file(a),n,{allowRemove:o}),directory:a=>vc(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Fi,remove:s?(a,c)=>e.remove(a,c):Oc,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Fi(){return Promise.reject(E("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Oc(){return Promise.reject(E("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const ds=1024;class Rf{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return br(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Le(()=>{if(!Array.isArray(t))throw E("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw E("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>ds)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let l=0;l<a;l+=1){if(!Object.prototype.hasOwnProperty.call(t,l))throw E("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[l],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>br(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return us(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!co(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Nf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=nr(r.relativePath),o=this.prepareFile(Le(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Pf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":nr(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:Le(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return hs(t),br(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Le(()=>{if(!Array.isArray(r))throw E("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw E("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Le(()=>{if(B(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return br(n.handle,ls(t.ref,n.handle.name))}if(B(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return us(n.handle,Df(t.ref,n.handle.name))}throw E("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=ur(r),i=this.prepareFile(Le(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ls(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw E("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Le(()=>{hs(t);const i=n??t.mode;return fs(t.mode,i),{handle:Sc(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Le(()=>{Lf(t,i);const o=n??t.mode;return fs(t.mode,o),{handle:vc(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>ds)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Tf();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw E("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!Cf(t))throw E("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw E("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Te("files.sandbox");return this.prepareDirectory(Le(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Te("files")}}function nr(e){if(!ao(e))throw E("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function ur(e,t="文件名"){const r=nr(e);if(r.includes("/"))throw E("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ls(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:nr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Df(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:nr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function br(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function us(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function fs(e,t){if(t==="readwrite"&&e!=="readwrite")throw E("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Nf(e){return co(e)||Rc(),e}function Pf(e){return Ga(e)||Rc(),e}function Rc(){throw E("INVALID_PARAMS","文件引用不合法")}function Tf(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw E("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Cf(e){return/^[0-9a-f]{32}$/.test(e)}function hs(e){if(!B(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 E("FILE_IO_FAILED","Host 返回了无效 File handle");ur(e.name,"Host File name")}function Lf(e,t=!1){if(!B(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 E("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw E("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&ur(e.name,"Host Directory name")}const ms=1e3,Mf=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function kf(e){const t=r=>kn(e.operationContext,r.signal);return{files:{[Xr]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=Uf(r),s=await he(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Zr]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=xf(r),s=await he(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[en]:async(r,n)=>{Xn(n);const i=Zn(e.picker),o=Hf(r).suggestedName,s=t(n);if(!i.saveFile)throw Te("files.saveFile");const a=await he(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Qt]:async(r,n)=>{const i=ye(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.create(ps(i),t(n)))},[Jt]:async(r,n)=>{const i=ye(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw Te(Jt);await he(()=>o.handle.remove(t(n)))},[tn]:async(r,n)=>{const i=ye(r);return gs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!B(o)||o.kind!=="file")throw Es()})},[Xt]:async(r,n)=>{const i=ye(r),o=ys(await he(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw E("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[rn]:async(r,n)=>{const i=ye(r,["content"]);typeof i.content!="string"&&we("content 必须是字符串");const o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Zt]:async(r,n)=>{const i=ye(r),o=await he(()=>e.registry.resolveFile(i.target).read(t(n)));return ys(o)},[nn]:async(r,n)=>{const i=ye(r,["content"]),o=e.registry.resolveFile(i.target);pt(o.mode),await he(()=>o.write(Bf(i.content),t(n)))},[er]:async(r,n)=>{const i=ye(r),o=await he(()=>e.registry.resolveFile(i.target).stat(t(n)));return Vf(o)}},directory:{[on]:async(r,n)=>{const i=ye(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);pt(o.mode),await he(()=>o.create(ps(i),t(n)))},[tr]:async(r,n)=>{const i=ye(r,["recursive"]);if(B(i.target)&&i.target.relativePath===".")throw E("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw Te(tr);await he(()=>o.handle.remove({recursive:i.recursive===void 0?!1:yn(i.recursive,"recursive")},t(n)))},[sn]:async(r,n)=>{const i=ye(r);return gs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!B(o)||o.kind!=="directory")throw Es()})},[an]:async(r,n)=>{const i=ye(r,["limit"]),o=Ff(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await he(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Uf(e){if(e===void 0)return{mode:"read",multiple:!1};B(e)||we("pickFiles 参数必须是对象"),xn(e,["mode","accept","multiple"]);const t=Dc(e.mode,"read"),r=e.multiple===void 0?!1:yn(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&we("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function xf(e){return e===void 0?{mode:"read"}:(B(e)||we("pickDirectory 参数必须是对象"),xn(e,["mode"]),{mode:Dc(e.mode,"read")})}function Hf(e){return B(e)||we("saveFile 参数必须是对象"),xn(e,["suggestedName"]),{suggestedName:ur(e.suggestedName,"suggestedName")}}function ye(e,t=[]){return(!B(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&we("文件操作参数必须包含 target"),xn(e,["target",...t]),e}function ps(e){return{recursive:e.recursive===void 0?!1:yn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:yn(e.exclusive,"exclusive")}}function Dc(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&we("mode 必须是 read 或 readwrite"),e)}function yn(e,t){return typeof e!="boolean"&&we(`${t} 必须是布尔值`),e}function Ff(e){if(e===void 0)return ms;if((!Number.isSafeInteger(e)||e<=0)&&we("limit 必须是正整数"),e>ms)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function xn(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&we(`不支持字段: ${r.join(", ")}`)}function pt(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Xn(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Zn(e){if(!e)throw Te("files.external");return e}async function gs(e){try{return await e(),!0}catch(t){if(Mf.has(_c(t)??""))return!1;throw go(t)}}async function he(e){try{return await e()}catch(t){throw go(t)}}function Bf(e){return e instanceof Uint8Array||we("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&we("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function ys(e){if(!(e instanceof Uint8Array))throw E("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Es(){return E("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Vf(e){if(!B(e)||e.kind!=="file"||!qf(e.size))throw E("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!zf(e[t]))throw E("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 qf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function zf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function we(e){throw E("INVALID_PARAMS",e)}const Ar=4294967296;function Gf(e){const t=new jf;return t.write(e),t.finish()}class jf{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<Ar?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=$f(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<Ar)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/Ar),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Ar)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function $f(e){const t=new Uint8Array(Wf(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const o=e.charCodeAt(r);o>=56320&&o<=57343&&(r+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function Wf(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function Nc(e){Bi(e);const t=Gf(e);if(t.byteLength>128)throw new Error("launch extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Bi(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)Bi(o,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[o,s]of i){if(o==="__proto__")throw new Error("extra object key is not supported");Bi(s,t+1,r)}r.delete(e)}const Kf=["pc","console","mobile"],Yf=["game","wiki"];function En(e){throw{code:"INVALID_PARAMS",message:e}}function Qf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e,t){return typeof e!="string"||!e.trim()?En(t):e.trim()}function ws(e,t,r){return typeof e!="string"||!t.includes(e)?En(r):e}function Jf(e){const t={target:"game_detail",appId:Ge(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ws(e.gameType,Kf,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ws(e.page,Yf,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ge(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ge(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Xf(e){return{target:"user_detail",userId:Ge(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Zf(e){const t={target:"post_detail",linkId:Ge(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ge(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ge(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function eh(e){const t={target:"mini_program",miniProgramId:Ge(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function th(e){return Qf(e)?e.target==="game_detail"?Jf(e):e.target==="user_detail"?Xf(e):e.target==="post_detail"?Zf(e):e.target==="mini_program"?eh(e):En("navigation.openAppPage target 不支持"):En("navigation.openAppPage options 必须是对象")}function rh(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 nh(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ih(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 oh(e){const t=e;return t.target==="game_detail"?rh(t):t.target==="user_detail"?nh(t):ih(t)}const sh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",ah="data-hb-sdk-fullscreen-exit",ch=3e3,dh=2e3,bs="var(--white-70a,rgba(255,255,255,.7))",As="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function lh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(ah,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${bs}`,`box-shadow:${As}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=sh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,l;function g(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function m(){o||(t.style.width=g())}function u(){l?.cancel(),l=void 0}function p(v=dh){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=g(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},v)}function R(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=bs,t.style.boxShadow=As,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}async function b(){if(!(s||a)){if(!o){R();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||R()}}}return t.addEventListener("click",b),window.addEventListener("resize",m),document.body.append(t),!r&&t.animate&&(l=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),p(ch),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",b),window.removeEventListener("resize",m),t.remove()}}}const Pc=1e4;function Tc(e){const t=new AbortController;let r;const n=()=>{r??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",n,{once:!0}),e.aborted&&n();const i=setTimeout(()=>{r??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},Pc);return{signal:t.signal,async run(o){try{return await X(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function Cc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function ei(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Ir(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function uh(e){let t,r,n={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(u){if(!u.hideCapsule){s();return}o??=lh(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,p){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",l),"error"in p)u.controller.abort();else if(r={options:u.options,result:p.result},n=u.options,a(u.options),e.onApplied?.(u.options),p.result.supported&&!ei(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const R of u.subscribers)R.dispose(),"error"in p?R.reject(p.error):R.resolve(p.result);u.subscribers.clear()}}function l(){t&&c(t,{error:Ir()})}function g(u,p){return new Promise((R,b)=>{const v=()=>{u.subscribers.delete(A),A.dispose(),b(Ir()),u.subscribers.size===0&&c(u,{error:Ir()})},A={resolve:R,reject:b,dispose:()=>p?.removeEventListener("abort",v)};u.subscribers.add(A),p?.addEventListener("abort",v,{once:!0}),p?.aborted&&v()})}const m={async apply(u,p,R="api"){if(te(e.operationContext.signal),p?.aborted)throw Ir();const b=Cc(u),v=t?.options??n,A={mode:b.orientation??v.mode,hideCapsule:b.fullscreen??v.hideCapsule};A.mode==="landscape"&&(A.hideCapsule=!0);const P=e.presentation.applyOrientation;if(!P)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&ei(t.options,A))return g(t,p);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&ei(r.options,A))return r.result;r=void 0;const _={options:A,source:R,controller:new AbortController,subscribers:new Set};t=_;const L=g(_,p);return e.operationContext.signal.addEventListener("abort",l,{once:!0}),p||(_.timer=setTimeout(()=>{c(_,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Pc)),X(()=>P.call(e.presentation,A,{...e.operationContext,signal:_.controller.signal}),_.controller.signal).then(F=>c(_,{result:F??{supported:!0}}),F=>c(_,{error:F})),L},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return m}function Lc(e){throw{code:"INVALID_PARAMS",message:e}}function Is(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Lc(`${t} 不支持参数`)}function fh(e){return{[hn]:async t=>{te(e.operationContext.signal),Is(t,"navigation.close"),await X(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[mn]:async t=>{te(e.operationContext.signal),Is(t,"navigation.reload"),await X(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[pn]:async(t,r)=>{const n=kn(e.operationContext,r?.signal);te(n.signal);const i=th(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Nc(i.extra)}catch{Lc("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Tc(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}te(n.signal),await X(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await X(()=>e.presentation.openAppPage(oh(i),n),n.signal)}}}const hh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),mh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),ph=new Set(["range","if-range","a-im"]),gh=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"]),yh=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,_r={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Eh{constructor(t){this.signal=t}phase="initial";transition(t){if(_r[t]<=_r[this.phase])throw E("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(_r[this.phase]<_r.committed&&this.signal.aborted)throw Uc()}normalizeHostError(t,r){return this.throwIfCancelled(),yo(t,r,this.signal)}}async function wh(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Te("network.download");const o=kn(r.operationContext,t.signal),s=new Eh(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await _h(e,i,o)}catch(g){throw s.normalizeHostError(g,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(g){throw s.normalizeHostError(g,"network")}let l=!1;try{s.throwIfCancelled(),s.transition("validate");const g=vh(c);Oh(c,g);const m=Rh(c.status,g);if(e.maxBytes!==void 0&&m.expectedBytes!==void 0&&m.expectedBytes>e.maxBytes)throw E("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Sh(e,a,g,i);let p=0;const R=Ah(m.expectedBytes,e.maxBytes);ri(t,ti(0,m));const b={...o,onProgress(P){!Number.isSafeInteger(P)||P<p||R!==void 0&&P>R||(p=P,ri(t,ti(p,m)))}};s.transition("transfer"),l=!0;let v;try{v=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...m.expectedBytes===void 0?{}:{expectedBytes:m.expectedBytes}},b)}catch(P){throw s.normalizeHostError(P,"transfer")}s.transition("committed"),p=bh(v,m,p,e.maxBytes),ri(t,ti(p,m));const A=i.describeFile(u.handle,u.ref);return s.transition("completed"),A}finally{l||Ih(n.network,c.body)}}function bh(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(n===void 0||o<=n))return o}catch{}return i}function Ah(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Ih(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function _h(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Vi(i.handle.mode),await Mh(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Vi(n.handle.mode),await kh(n.handle,r),{kind:"directory",...n}}function Sh(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Nh(e,r),o=n.deriveFile(t,i);return Vi(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function vh(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 E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!B(e.headers))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!hh.has(r)||!Array.isArray(n)||n.length===0)throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Oh(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw E("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Lh(t,mh)});if((t["content-range"]?.length??0)>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Rh(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(l=>l!=="0"))throw E("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Dh(t["content-encoding"]),a=e===204||e===205?0:n.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function Dh(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function ti(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function ri(e,t){try{e.postProgress(t)}catch{}}function Nh(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Ph(i);if(o&&Cr(o))return o}for(const i of r){const o=Th(i);if(o&&Cr(o))return o}if(e.suggestedName!==void 0)return Mc(e.suggestedName);const n=Ch(e.url);return n&&Cr(n)?n:"download.bin"}function Ph(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function Th(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 Ch(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Mc(e){try{ur(e,"suggestedName")}catch{throw E("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Cr(e))throw E("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Cr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||yh.test(e))}function Lh(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Mh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw kc()}catch(r){throw yo(r,"file",t.signal)}}async function kh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw kc()}catch(r){throw yo(r,"file",t.signal)}}function Vi(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","下载目标只允许读取")}const Uh={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 yo(e,t,r){if(r.aborted)return Uc();const n=xh(e);if(n&&gh.has(n)){const o=E(n,Uh[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?E("DOWNLOAD_TIMEOUT","下载网络请求超时"):E("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?E("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):E("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function xh(e){return B(e)&&typeof e.code=="string"?e.code:void 0}function kc(){return E("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Uc(){return E("DOWNLOAD_CANCELLED","下载已取消")}function Hh(e){if(!e)return;const t=Object.keys(e).find(r=>ph.has(r.trim().toLowerCase()));if(t)throw E("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Eo="withCredentials",Fh=new Set(["url","method","params","data","headers","timeout",Eo]),Bh=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Eo]),Vh=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),_s=3e4,Ss=2*1024*1024,qh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zh=/[\u0000-\u0008\u000A-\u001F\u007F]/,Gh=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,jh="network.request 不支持 multipart/form-data,请使用专用上传能力";function $h(e){const t=Wh(e.runtimePermissions),r=sm(e.allowedHttpOrigins);return{[Jr]:async(n,i)=>{const o=Yh(n,{permission:t,allowedHttpOrigins:r});return wh(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Qr]:async(n,i)=>{const o=kn(e.operationContext,i?.signal);te(o.signal);const s=Kh(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await X(()=>e.network.request(s,o),o.signal)}catch(c){throw dm(c)?c:lm(c,"REQUEST_UNSUPPORTED")?W("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):W("REQUEST_FAILED","网络请求失败")}return cm(a)}}}function Wh(e){const t=Qe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Kh(e,t){const r=Hn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Fh.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Hc(r,"network.request");const i=xc(r,t,"network.request"),o=Jh(r.method),s=r.data;s!==void 0&&em(s),rm(i.headers,s);const a=nm(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 Yh(e,t){const r=Hn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Bh.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Hc(r,"network.download");const i=xc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw W("INVALID_PARAMS","network.download timeout 必须是有限正数");Hh(i.headers);const o=co(r.to),s=Ga(r.to);if(!o&&!s)throw W("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw W("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw W("INVALID_PARAMS","suggestedName 必须是字符串");a=Mc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw W("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw W("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:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function xc(e,t,r){const n=Qh(e.url,t.allowedHttpOrigins,r),i=Vl(n);if(i&&!t.permission.useOfficialDomain)throw W("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Bl(n.pathname,i))throw W("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Hn(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Xh(e.headers,r),timeout:Zh(e.timeout,r)}}function Qh(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw W("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw W("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Jh(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Vh.has(t))throw W("INVALID_PARAMS","network.request method 不合法");return t}function Xh(e,t="network.request"){const r=Hn(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!qh.test(s)||typeof o!="string"||zh.test(o))throw W("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(ql(s))throw W("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Hc(e,t){const r=e[Eo];if(r!==void 0&&typeof r!="boolean")throw W("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Zh(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw W("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>_s)throw W("INVALID_PARAMS",`${t} timeout 不能超过 ${_s}ms`);return e}}function em(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw W("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(tm(e)>Ss)throw W("INVALID_PARAMS",`network.request data 不能超过 ${Ss} 字节`)}function tm(e){if(typeof e=="string")return ni(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ni(e.toString());try{const t=JSON.stringify(e);return t?ni(t):0}catch{throw W("INVALID_PARAMS","network.request data 必须可序列化")}}function rm(e,t){const r=Fc(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw W("INVALID_PARAMS",jh)}function nm(e,t,r){if(t===void 0)return;const n=Fc(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||om(t))?"form":im(t)?"json":void 0}function Fc(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function im(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function om(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sm(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&am(n.hostname)&&t.add(n.origin)}catch{}return t}function am(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function cm(e){return Object.keys(e.headers).some(vs)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!vs(t)))}:e}function vs(e){const t=e.trim().toLowerCase();return Gh.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function dm(e){return e instanceof Error&&e.name==="AbortError"}function lm(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Hn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw W("INVALID_PARAMS",t);return e}function ni(e){return new TextEncoder().encode(e).length}function W(e,t){return{code:e,message:t}}function um(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fm(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 hm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=fm(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function mm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(o)||(r.add(o),n.push(o))}return{invalidMessages:t,values:n}}function Bc(e,t){if(e==null)return{};if(!um(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=hm(e.topicIds),n=mm(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let o=r.values;t.maxTopicIds!==void 0&&o.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),o=o.slice(0,t.maxTopicIds));const s=o.length||n.values.length?{...o.length?{topicIds:o}:{},...n.values.length?{topics:n.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function pm(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function gm(e){try{if(pm(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ce(e){throw{code:"INVALID_PARAMS",message:e}}function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qi(e,t){return typeof e!="string"||!e.trim()?ce(t):e}function ym(e,t){const r=qi(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ce(t):r}catch{return ce(t)}}function Em(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Vc(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ce(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return ce(`${t} 缺少有效的小程序分享地址`)}}function wm(e,t){if(!fr(e))return ce("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ce("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Em(r))return ce("share.showShareMenu channel 不合法");const n=qc(e.extra,"share.showShareMenu");return{title:qi(e.title,"share.showShareMenu title 必须是非空字符串"),description:qi(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Vc(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:ym(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function qc(e,t){if(e!==void 0)try{return Nc(e)}catch{return ce(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function zc(e,t){return e.invalidMessage&&await X(()=>gm(t.environment),t.operationContext.signal)?ce(e.invalidMessage):e.post}function Os(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function bm(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Os(t.windowWidth,0),height:Os(t.windowHeight,0)}}function zi(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ce(t):r}function Rs(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ce(t):r}function Am(e){return fr(e)?{left:zi(e.left,"share.screenshot rect.left 必须是非负数字"),top:zi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Rs(e.width,"share.screenshot rect.width 必须是正数"),height:Rs(e.height,"share.screenshot rect.height 必须是正数")}:ce("share.screenshot rect 必须是对象")}function Im(e,t){if(e!=null&&!fr(e))return ce("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ce("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?bm(t):Am(r.rect),...r.delay===void 0?{}:{delay:zi(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function _m(e,t){te(t.operationContext.signal);const r=wm(e,t);let n=Bc(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await zc(n,t);return X(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Sm(e,t){if(te(t.operationContext.signal),e!==void 0&&!fr(e))return ce("share.copyLink 参数必须是对象");const r=qc(e?.extra,"share.copyLink"),n=Vc(t,"share.copyLink",r);return await X(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function vm(e,t){te(t.operationContext.signal);const r=Im(e,t.presentation),n=Bc(fr(e)?e.post:void 0,{method:"share.screenshot"}),i=await zc(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Om();let a=!1,c;try{a=!0,await X(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await X(()=>t.presentation.captureAndShare({...r,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(g){c={status:"rejected",error:g}}const l=a?await Rm(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(l)throw l;return c.value}function Om(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Rm(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await X(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Dm(e){return{[jr]:(t,r)=>Sm(t,e),[$r]:(t,r)=>_m(t,e),[Wr]:(t,r)=>vm(t,e)}}const Nm=128,Pm=/^[A-Za-z0-9_-]+$/;function Tm(e){const t=Cm(e),r={[Kt]:async n=>{te(e.operationContext.signal);const i=Ds(n,Kt,e.storageLimits?.maxKeyLength),o=await X(()=>e.storage.getRaw(ii(t(),i),e.operationContext),e.operationContext.signal);return{data:Ns(o)}},[Yt]:async n=>{te(e.operationContext.signal);const i=Gc(n,"storage.setStorage 参数必须是对象"),o=Ds(i,Yt,e.storageLimits?.maxKeyLength),s=Lm(i.data,e.storageLimits?.maxValueBytes);await X(()=>e.storage.setRaw(ii(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:r,diagnostics:{getSnapshot:async()=>{te(e.operationContext.signal);let n;try{n=t()}catch{throw je("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=ii(n,"");return(await X(()=>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:Ns(a),serializedValue:a,bytes:jc(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function Cm(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${Ps(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${Ps(i)}`)}t=r!==void 0}if(!r)throw je("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function ii(e,t){return`hb_miniprogram_${e}_${t}`}function Ds(e,t,r=Nm){const i=Gc(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw je("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Pm.test(i))throw je("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Lm(e,t){let r;try{r=JSON.stringify(e)}catch{throw je("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw je("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&jc(r)>t)throw je("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ns(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Gc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw je("INVALID_PARAMS",t);return e}function Ps(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:Mm(e)}function Mm(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function jc(e){return new TextEncoder().encode(e).length}function je(e,t){return{code:e,message:t}}const Ts=120;function Be(e){throw{code:"INVALID_PARAMS",message:e}}function wo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $c(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Be(`${r} 不支持字段: ${n.join(", ")}`)}function km(e){if(!wo(e))return Be("ui.showToast 参数必须是对象");if($c(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Be("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Ts)return Be(`ui.showToast message 不能超过 ${Ts} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Be("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Um(e){return e===void 0?{dismissible:!1}:wo(e)?($c(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Be("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Be("ui.showLoading 参数必须是对象")}function xm(e){e!==void 0&&(!wo(e)||Object.keys(e).length)&&Be("ui.hideLoading 不支持参数")}function Hm(e){return{[cn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showToast(km(t),e.operationContext),e.operationContext.signal)},[dn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showLoading(Um(t),e.operationContext),e.operationContext.signal)},[ln]:async t=>{te(e.operationContext.signal),xm(t),await X(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Fm={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ge(e,"当前用户首页资料接口响应异常")}},Bm=3e4;function Vm(e,t,r={}){const n=r.ttlMs??Bm,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function l(){let m;try{m=await Un(e,Fm,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof oe?E("REQUEST_UNSUPPORTED",u.message):u instanceof lr?E("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof vt?E("REQUEST_FAILED","user home_v2 请求失败"):u instanceof St?i&&(u.status===403||u.status===429)?E("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):E("REQUEST_FAILED",u.message):zm(u)?u:E("REQUEST_FAILED","user home_v2 请求失败")}return qm(m,"user home_v2")}function g(m){const u=Date.now();if(a?.userId===m&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===m&&c.generation===s)return c.promise;const p=s,R=l().then(b=>(s===p&&(a={userId:m,value:b,expiresAt:Date.now()+n}),b)).finally(()=>{c?.promise===R&&(c=void 0)});return c={userId:m,generation:p,promise:R},R}return{get:g,clear(){s+=1,a=void 0,c=void 0}}}function qm(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function zm(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Gm={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 ge(e,"Steam 游戏库接口响应异常")}};function jm(e,t=ki){const r=Gl({version:"1",validate:Wm}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):ki,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function Cs(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function $m(e){const{query:t}=e;return JSON.stringify([e.miniProgramId,e.userId,e.effectiveSteamId??null,e.personalInformationOpen??null,t.limit,t.offset,t.sort,t.q??"",t.includeHidden])}function Wm(e){if(!B(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(oi(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Xe();for(const t of e.gameList){if(!B(t)||!Gi(t.appid)||!Gi(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Xe();for(const r of["image","icon"])Ls(t,r);for(const r of["playtimeForever","playtime2Weeks"])oi(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Xe();if(t.price!==void 0){if(!B(t.price))throw Xe();for(const r of["current","initial","deadlineDate"])Ls(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])oi(t.price,r)}}return e}function Gi(e){return typeof e=="number"&&Number.isFinite(e)}function oi(e,t){if(e[t]!==void 0&&!Gi(e[t]))throw Xe()}function Ls(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Xe()}function Xe(){return E("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Wc=20,Km=100,Ym=128,Kc=0,Yc="weeks",Qm=100,Jm=new Set(["weeks","all","achieved"]);function Xm(){return{nickname:"",avatar:""}}function Zm(e){const t=Vm(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Za(),i=jm(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(d,h){const f=JSON.stringify([d,h]);return(!o||o.key!==f)&&(o={key:f,scope:n.createScope(h,n.createScope(d))}),o.scope}function l(){const d=o;o=void 0,d&&n.invalidateScope(d.scope).catch(()=>{}),s.clear()}const g=lc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??cc))}),m=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,p=!1;const R=e.account.onChange(()=>{u+=1,t.clear(),g.invalidate(),l()}),b=e.authorization.onEvent((d,h)=>{d==="user_info_authorization_change"&&Object.values(h).some(f=>f==="denied")&&(u+=1,t.clear(),g.invalidate(),l(),a=a.then(async()=>{if(p)return;const f=await e.account.getCurrentUserId(e.operationContext);typeof f=="string"&&f.trim()&&await n.invalidateScope(c(A(),f.trim()))}).catch(()=>{}))});function v(){if(p||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function A(){const d=e.identity.get()?.miniProgramId?.trim();if(!d)throw E("INVALID_STATE","用户能力缺少 canonical 小程序身份");return d}async function P(){v(),await a,v();let d;try{d=await e.account.getCurrentUserId(e.operationContext)}catch(h){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ks(h)?h:E("REQUEST_FAILED","读取小黑盒账号失败")}return typeof d=="string"&&d.trim()?d.trim():void 0}async function _(d,h){const f=await P();if(u!==h||f!==d)throw E("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function L(d,h,f=e.operationContext.signal){try{return await Un(e.network,d,h,{...e.operationContext,signal:f,credentials:"heybox-session",...m?{gate:m}:{}})}catch(y){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):y instanceof oe?E("REQUEST_UNSUPPORTED",y.message):y instanceof lr?E("INVALID_RESPONSE","用户接口响应不合法"):y instanceof vt?E("REQUEST_FAILED","用户请求失败"):y instanceof St?r&&(y.status===403||y.status===429)?E("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:y.status,...y.retryAfterMs===void 0?{}:{retryAfterMs:y.retryAfterMs}}):E("REQUEST_FAILED",y.message):ks(y)?y:E("REQUEST_FAILED","用户请求失败")}}async function F(){A();const d=u,h=await P();if(!h)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[f,y]=await Promise.all([e.authorization.getOrCreateLocalIdentity(h),N(h).catch(()=>Xm())]);return await _(h,d),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:f.appUserId,profile:y,...f.steamId?{steam_id:f.steamId}:{}}}}function N(d){return g.read(d,()=>L(dc,void 0).then(h=>{const f=Ms(h,"账号基础信息");if(f.display_username!==void 0&&typeof f.display_username!="string")throw E("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(f.display_avatar!==void 0&&typeof f.display_avatar!="string")throw E("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:f.display_username??"",avatar:f.display_avatar??""}}))}async function I(d){const h=ep(d),f=A(),y=u,w=await P();if(!w)return l(),{isLogin:!1,isBound:!1,data:null};const S=await t.get(w);await _(w,y);const T=bo(S.steam_id_info);if(Object.keys(T).length===0)return await n.invalidateScope(c(f,w)).catch(()=>{}),await _(w,y),s.delete(JSON.stringify([f,w])),{isLogin:!0,isBound:!1,data:null};const V=JSON.stringify([f,w]),C=c(f,w),D=Cs({...h,steamId:void 0},T),M=Qc(T.personal_infomation_open??T.personal_information_open),O=JSON.stringify([D??null,M??null]),U=s.get(V);U&&U.identity!==O&&(await n.invalidateScope(C).catch(()=>{}),await _(w,y));const x={identity:O,scope:n.createScope(O,C)};s.set(V,x);const H=Cs(h,T),q=H?i.persistent:i.unresolved,z=n.createScope(H??"unresolved",x.scope),G=async()=>{if(await _(w,y),A()!==f||s.get(V)?.identity!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ee=await q.read({scope:z,key:$m({miniProgramId:f,userId:w,effectiveSteamId:H,personalInformationOpen:M,query:h}),signal:e.operationContext.signal,load:async Z=>{const J=await L(Gm,{userId:w,...h,personalInformationOpen:M},Z);return await G(),op(Ms(J,"Steam 游戏库"),h)}}).catch(async Z=>{throw await G(),Z});return await G(),{isLogin:!0,isBound:!0,data:ee}}return{getInfo:F,getSteamGameList:I,async invalidateSteamGameListCache(){const d=A(),h=u,f=await P();if(!f)return;const y=c(d,f);await Promise.all([i.persistent.invalidateScope(y),i.unresolved.invalidateScope(y)]),t.clear(),s.delete(JSON.stringify([d,f])),await _(f,h)},dispose(){p||(p=!0,u+=1,R(),b(),t.clear(),g.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function ep(e){if(e==null)return{limit:Wc,offset:Kc,sort:Yc,includeHidden:!1};if(!B(e))throw Ve("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ve(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:tp(e.limit),offset:rp(e.offset),sort:np(e.sort),includeHidden:ip(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Ym)throw Ve("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ve("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Qm))}return r}function tp(e){if(e===void 0)return Wc;if(!Number.isInteger(e)||Number(e)<1)throw Ve("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Km)}function rp(e){if(e===void 0)return Kc;if(!Number.isInteger(e)||Number(e)<0)throw Ve("user.getSteamGameList offset 必须是非负整数");return Number(e)}function np(e){if(e===void 0)return Yc;if(typeof e!="string"||!Jm.has(e))throw Ve("user.getSteamGameList sort 不支持");return e}function ip(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ve("user.getSteamGameList includeHidden 必须是 boolean");return e}function op(e,t){if(!Array.isArray(e.game_list))throw E("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(sp).filter(a=>a!==void 0),n=wn(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=Qc(e.is_me);return s!==void 0&&(o.isMe=s),o}function sp(e){const t=bo(e),r=wn(t.appid),n=wn(t.steam_appid)??r,i=Ao(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};qt(o,"image",t.image),qt(o,"icon",t.appicon??t.icon),zt(o,"playtimeForever",t.playtime_forever),zt(o,"playtime2Weeks",t.playtime_2weeks);const s=cp(t.external_tags??t.tags);s.length&&(o.tags=s);const a=ap(t.price);return a&&(o.price=a),o}function ap(e){const t=bo(e),r={};return qt(r,"current",t.current),qt(r,"initial",t.initial),zt(r,"discount",t.discount),zt(r,"lowestPrice",t.lowest_price),qt(r,"deadlineDate",t.deadline_date),zt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function Ms(e,t){if(!B(e))throw E("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw E(n,r)}if(!B(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function bo(e){return B(e)?e:{}}function Ao(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function cp(e){return Array.isArray(e)?e.map(Ao).filter(Boolean):[]}function wn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Qc(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qt(e,t,r){const n=Ao(r);n&&Object.assign(e,{[t]:n})}function zt(e,t,r){const n=wn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ve(e){return E("INVALID_PARAMS",e)}function ks(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function dp(e){return{[qr]:async t=>(Us(t,"user.getInfo"),e.user.getInfo()),[zr]:async(t,r)=>{Us(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Gr]:async t=>e.user.getSteamGameList(t)}}function Us(e,t){if(e!==void 0)throw E("INVALID_PARAMS",`${t} 不接收入参`)}function xs(e){throw{code:"INVALID_PARAMS",message:e}}function Mt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Jc(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Sr(e,t,r){return Math.min(Jc(e,t),r)}async function lp(e){try{return Jc(await e.getNavigationBarHeight(),0)}catch{return 0}}function up(e,t,r,n){const i=Sr(e.safeArea?.left,0,t),o=Math.max(i,Sr(e.safeArea?.right,t,t)),s=Sr(e.safeArea?.top,n,r),a=Math.max(s,Sr(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Hs(e){const t=e.getViewportMetrics(),r=Mt(t.windowWidth,0),n=Mt(t.windowHeight,0),i=await lp(e);return{pixelRatio:Mt(t.pixelRatio,1),screenWidth:Mt(t.screenWidth,r),screenHeight:Mt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:up(t,r,n,i),screenTop:i}}function fp(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,o,s;const a=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const m=++i;Hs(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||m!==i)return;const p=JSON.stringify(u);p!==o&&(o=p,r.onViewportChange?.(u))}).catch(()=>{})},c=uh({...r,onApplied:a}),l=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",l),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?l():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",l,{once:!0})),{handlers:{[ot]:async(m,u)=>c.apply(m,u?.signal),[Kr]:async()=>(te(r.operationContext.signal),Hs(r.presentation)),[Yr]:async m=>{if(te(r.operationContext.signal),typeof m!="object"||m===null||Array.isArray(m))return xs("viewport.setNavigationBarStyle 参数必须是对象");const u=m.foregroundStyle;if(u!=="light"&&u!=="dark")return xs("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await X(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(m,u)=>c.apply({orientation:m.mode,fullscreen:m.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:l}}const hp=new Map(ze.map(e=>[e.method,e]));function vr(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function mp(e){const t=Qe(e);return r=>{if(r.requirement.kind==="none")return{allowed:!0};for(const n of r.requirement.permissions){const i=t.valid?t.permissions[n]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${n}`,data:{permission:n,method:r.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${n}`,data:{permission:n,method:r.method}}}return{allowed:!0}}}function pp(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=g=>{a||(a=!0,n.removeEventListener("abort",l),g())},l=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",l,{once:!0}),i.then(g=>c(()=>o({status:"handled",value:g})),g=>c(()=>s(g)))})}function gp(e){const t=mp(e.runtimePermissions),r=Qe(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const l=e.now??yp,g=e.onTrace?l():0,m=e.onTrace?`cap_${++n}`:"",u=s===ot?++i:void 0;let p;try{if(e.terminalSignal.aborted)throw vr("RUNTIME_DESTROYED","小程序 Runtime 已终止");wl(s,e.effectiveCapabilities);const R=hp.get(s);if(!R)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const b=t(R),v=!b.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!b.allowed&&!v)throw vr(b.code,b.message,b.data);const A=e.handlers[s];if(!A)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(p=Tc(c.signal));const P=p?{...c,signal:p.signal}:c,_=async()=>{for(const F of e.policies??[]){const N=await F.evaluate({method:s,payload:a,capability:R});if(e.terminalSignal.aborted||p?.signal.aborted)throw Vs();if(!N.allowed)throw vr(N.code,N.message,N.data)}if(e.terminalSignal.aborted||p?.signal.aborted)throw Vs();if(u!==void 0){if(Cc(a),u<o)throw vr("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return A(a,P)},L=await pp(()=>p?p.run(_):_(),void 0,c,e.terminalSignal);return Fs(e.onTrace,Bs(m,s,a,g,L),l),L}catch(R){throw Fs(e.onTrace,Bs(m,s,a,g,{status:"error",error:R}),l),R}finally{p?.dispose()}}}}function yp(){return typeof performance>"u"?Date.now():performance.now()}function Fs(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function Bs(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:Ep(i.error)}:{},...wp(t,r,i)}}function Ep(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function wp(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&Xc(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function Xc(e){return typeof e=="object"&&e!==null}function Vs(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function bp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=ou(e.requestPolicy);let n;if(e.files)try{n=Yl(e.files,t)}catch{}const i=Za({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Ap:void 0),s=r.enabled?tu({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Rf(e.files,e.miniProgramDetail),c=kf({registry:a,picker:e.picker,operationContext:t}),l=Pu({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,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let g,m,u,p=()=>{},R=()=>{};try{g=fp({operationContext:t,presentation:e.hostPresentation,onDisplayChange:N=>e.eventSink.postEvent("display_change",N),onViewportChange:N=>e.eventSink.postEvent("viewport_change",N)}),m=Zm({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:l,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),p=l.onEvent((N,I)=>e.eventSink.postEvent(N,I)),R=e.hostCompanion?.onSessionEvent?.(N=>{const I=Af(N);!e.terminalSignal.aborted&&I&&e.eventSink.postEvent(I.type,I.payload)})??(()=>{}),u=sf({account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const b=Tm({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),v=[{name:"auth",handlers:Fu({authorization:l})},{name:"user",handlers:dp({user:m,authorization:l,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Dm({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:g.handlers},{name:"storage",handlers:b.handlers},{name:"network",handlers:$h({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Hm({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Sf({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:fh({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:N=>g.applyOrientation({mode:"portrait",hideCapsule:!1},N)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:gf({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=Ip(v);let P=!1;const _=()=>{P||(P=!0,e.terminalSignal.removeEventListener("abort",_),g?.dispose(),u?.dispose(),p(),R(),m?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?_():e.terminalSignal.addEventListener("abort",_,{once:!0});const L=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:v,handlers:A,allowsCompanionAttachmentAccess:(N,I)=>L.has(N)&&Xc(I)&&a.isCompanionAttachmentRef(I.target),applyOrientation:g.applyOrientation,notifyViewportChange:g.notifyChange,...b.diagnostics?{storageDiagnostics:b.diagnostics}:{},dispose:_}}catch(b){throw g?.dispose(),u?.dispose(),p(),R(),m?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose(),b}}function Ap(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Ip(e){const t=new Map(ze.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=ze.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==ze.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const _p="heybox-mini-dev:";function qs(e){try{return Sp(new URL(e))}catch{return!1}}function Sp(e){return e.protocol===_p}function vp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Op(e)}function Op(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const Rp=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Dp(e,t){const r=[],n=Np(e.environmentInfo,r),i=Lr(n?.appVersion,"host.appVersion",r),o=Tp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Pp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Lr(t.miniProgramId),version:Lr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Np(e,t){if(e!=null){if(Zc(e))return e;t.push("environmentInfo")}}function Pp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Tp(e,t){if(e==null)return{name:"unknown",version:null};if(!Zc(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Rp.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:Lr(e.version,"operatingSystem.version",t)}}function Lr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Cp=1,ed="allow-scripts allow-same-origin",Lp="",Mp="no-referrer";function kp(e=ed){return!e.split(/\s+/).includes("allow-same-origin")}function zs(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Up=new Set(["javascript:","data:","blob:","file:"]),Gs="xiaoheihe.cn";function xp(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(Up.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!qp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Hp(e,t){const r=new URL(e);return r.searchParams.set(Qd,t),r.toString()}function Fp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Bp(r)??Vp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Bp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Vp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function js(e){const t=new URL(e);return Io(t)?"loopback":_o(t)?"lan":"production"}function qp(e,t,r){return zp(e)||Io(e)||_o(e)&&jp(t,r)}function zp(e){return e.protocol==="https:"&&Kp(e.hostname)}function Io(e){return e.protocol==="http:"&&Gp(e.hostname)}function Gp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function _o(e){return e.protocol==="http:"&&$p(e.hostname)}function jp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Io(r)||_o(r)}catch{return!1}}function $p(e){const t=Wp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Wp(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function Kp(e){return e===Gs||e.endsWith(`.${Gs}`)}const Yp=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"]),Qp=new Set(["url","inline","eval","unknown"]),Jp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Xp=/^[a-f0-9]{64}$/,Zp=255,eg=160,tg=256;function rg(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Yp.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>tg||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Qp.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=ng(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>eg||!Jp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Xp.test(o)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function ng(e){if(e!==void 0&&!(typeof e!="string"||e.length>Zp))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const ig=/^(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 og(e){if(!e?.minimumSdkVersion)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=et(e.minimumSdkVersion),r=e.sdkVersion?et(e.sdkVersion):void 0;if(!t)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw K("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=et("0.6.0");if(!r){if(Mr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw K("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw K("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Mr(r,t)<0)throw K("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Mr(r,et("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function sg(e,t){if(typeof t!="string"||!et(t))throw K("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw K("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ag(e,t){const r=et(e),n=et(t);if(!(!r||!n))return Mr(r,n)}function et(e){const t=ig.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function Mr(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Fn=["android","ios","ohos","windows","macos","linux"],cg="0.9.0",dg=Object.freeze(["android","ios","ohos","windows","macos"]),td="该小程序暂不支持当前平台",lg="PLATFORM_UNSUPPORTED";function ug(e){return typeof e=="string"&&Fn.includes(e)}function fg(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 hg(e){const t=e.manifest;if(!Eg(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ws(e.sdkVersion)??Ws(t.sdkVersion);return gg(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:pg()}const r=rd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function mg(e){const t=fg(e.operatingSystemName);if(!t)return Et("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Et("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Fn,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=hg({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Et("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):$s(t,s)}if(r.effectivePlatforms===void 0)return Et("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=rd(r.effectivePlatforms);if("reason"in n)return Et("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=yg(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return $s(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function $s(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Et("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Et(e,t={}){return{status:"denied",reason:e,message:td,...t}}function pg(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:dg,platformsDeclared:!1,policy:"legacy_mobile_default"}}function rd(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const r of e){if(!ug(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Fn.filter(r=>t.has(r)))}}function gg(e){if(typeof e!="string"||!e.trim())return!1;const t=ag(e.trim(),cg);return t!==void 0&&t>=0}function Ws(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yg(e){return e==="explicit"||e==="legacy_mobile_default"}function Eg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wg=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 bg(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:Ag(i.pathname),sanitizedPathnameHash:Ig(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Ag(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Ig(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let v=0;v<16;v+=1)o[v]=s.getUint32(a+v*4,!1);for(let v=16;v<64;v+=1){const A=o[v-15],P=o[v-2],_=ve(A,7)^ve(A,18)^A>>>3,L=ve(P,17)^ve(P,19)^P>>>10;o[v]=o[v-16]+_+o[v-7]+L>>>0}let[c,l,g,m,u,p,R,b]=i;for(let v=0;v<64;v+=1){const A=b+(ve(u,6)^ve(u,11)^ve(u,25))+(u&p^~u&R)+wg[v]+o[v]>>>0,P=(ve(c,2)^ve(c,13)^ve(c,22))+(c&l^c&g^l&g);b=R,R=p,p=u,u=m+A>>>0,m=g,g=l,l=c,c=A+P>>>0}[c,l,g,m,u,p,R,b].forEach((v,A)=>{i[A]=i[A]+v>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ve(e,t){return e>>>t|e<<32-t}const _g=1e4,si=2e3,Sg=2,vg="open-with-native-credential-policy",nd="安全提示",id="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Og{nonce=zs();runtimeId=zs();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 r=Xa(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??_g,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??K("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??K("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(kg(),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=K("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,r)=>{this.resolveReady=t,this.rejectReady=r})}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=og(t.sdkVersionPolicy);const r=Dp(t,this.identity);if(this.environmentInfo=r.info,r.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${r.invalidFields.join(", ")}`}),this.platformGateDecision=mg({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Hg(this.platformGateDecision);if(this.miniProgramDetail=Fg(t),this.effectiveCapabilities=Ja(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),Pg(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const n=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const i=await this.confirmDevMiniProgramLaunch(n);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(Cg(n)),this.launchUrl=n,this.miniProgramSrc=Hp(n,this.nonce),this.traceSecurityPolicy(n),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=uo(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ot,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ue(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[ot])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=bp({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,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});const r=gp({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:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:l,network:g})=>{const m={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...l?{errorCode:l}:{},...this.identity,...g?{network:g}:{}};Ue(this.options.onCapabilityTrace,m)}}:{}});this.bridgeServer=new yl({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(K("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw Ng(t)?t:od(K("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return xp(t,r,{allowPrivateNetwork:qs(r)||Ks(r)||await this.isDevRuntime()})}catch(r){throw K("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Mg)({message:id,title:nd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(js(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!qs(r)&&!Ks(r)}async closeAfterDevLaunchCancellation(){const t=K("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{Ys(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>Ys())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Lp),this.iframe.setAttribute("referrerpolicy",Mp),this.iframe.setAttribute("sandbox",ed)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Ue(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(),Ue(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{sg(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(K("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>=Sg)){this.failRuntime(K("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(pr,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},si),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:pr})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(r),t.deferProbe||this.sendDocumentRevalidationProbe(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(pr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:pr})}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(K("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},si))}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()},si))}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===Xd){this.handleCspViolation(t.payload);return}if(t.method!==Jd)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(K("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Fp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(K("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=rg(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){Ue(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=bg(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(K("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:Cp,launchUrlType:js(t),networkPolicy:vg})}failRuntime(t){const r=Rg(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),Ue(this.options.onError,Dg(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,Ue(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ue(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 Rg(e){const t=uo(e);return bn(e)&&"cause"in e&&od(t,e.cause),t}function od(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Dg(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Ng(e){return bn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function bn(e){return!!e&&typeof e=="object"}function Ue(e,t){try{e?.(t)}catch{}}function Pg(e,t,r){try{e?.(t,r)}catch{}}function Ks(e){try{const t=new URL(e);return t.protocol==="http:"&&vp(t.hostname)}catch{return!1}}function Tg(e){try{return new URL(e).origin}catch{return}}function Cg(e){return kp()?"*":Tg(e)}function Lg(e){return`${nd}
|
|
2
2
|
|
|
3
3
|
${id}
|
|
4
4
|
|