@heybox/hb-sdk 0.9.2-alpha.2 → 0.9.2-alpha.4
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 +12 -0
- package/README.md +1 -1
- package/dist/cli-chunks/{build-CyswVc4b.cjs → build-etbZdJO5.cjs} +5 -5
- package/dist/cli-chunks/{context-Dr_SFRYa.cjs → context-BX3UdvCA.cjs} +2 -2
- package/dist/cli-chunks/{create-DY4e3-ai.cjs → create-D-QYk3Id.cjs} +1 -1
- package/dist/cli-chunks/{dev-DKuNXTMr.cjs → dev-B2FbHnLs.cjs} +8 -8
- package/dist/cli-chunks/{doctor-FC9aE_Ku.cjs → doctor-DFHzviTV.cjs} +1 -1
- package/dist/cli-chunks/{index-B8qBsp6f.cjs → index-CFV0c-vf.cjs} +16 -16
- package/dist/cli-chunks/{index-B9xW1kud.cjs → index-DYi1Jf48.cjs} +1 -1
- package/dist/cli-chunks/{index.esm-D7sYo7d4.cjs → index.esm-Dg3sRrvn.cjs} +6 -6
- package/dist/cli-chunks/{login-D8w3N8jn.cjs → login-CQ0ihlKn.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-BDpkwL6C.cjs → project-vite-wFdIcJhz.cjs} +1 -1
- package/dist/cli-chunks/{remote-kpeucBW7.cjs → remote-B4geHbvv.cjs} +6 -6
- package/dist/cli-chunks/{runtime-gate-C3P-8VeT.cjs → runtime-gate-DOhGnhsc.cjs} +2 -2
- package/dist/cli-chunks/{runtime-permission-env-BBLrXaE_.cjs → runtime-permission-env-Btaxs6QZ.cjs} +2 -2
- package/dist/cli-chunks/{skill-B4LVsoOx.cjs → skill-BNFw3HaN.cjs} +2 -2
- package/dist/cli-chunks/{version-DgbarBxd.cjs → version-CKVR_8Qo.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-DeJ6f40r.js +102 -0
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-zP3CDynX.js → desktop-app-launch-C326YXxP.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-BnkA-gEX.js → index-Dvu71DSJ.js} +3 -3
- package/dist/devtools/browser-dev-host/index.html +2 -2
- 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/docs/runtime-host-migration.md +2 -2
- package/package.json +6 -6
- package/skill/skill.json +4 -4
- package/dist/devtools/browser-dev-host/assets/browser-dev-host--bEdWcBx.js +0 -102
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import{H as ns,ax as fu,aY as hu,M as mu,aH as gu,aI as pu,aj as br,b6 as Q,aa as yu,ak as fc,aq as Eu,b0 as wu,am as Iu,d as Mu,aE as hc,a8 as Au,at as mc,r as Nu,az as gc,o as Du,aD as Su,a5 as Tu,a_ as bu,aZ as Ou,c as _u}from"./desktop-app-launch-zP3CDynX.js";const sn="workspaceCards.requestRefresh",an="auth.login",cn="user.getInfo",dn="user.revokeAuthorization",un="user.getSteamGameList",ln="share.copyLink",fn="share.showShareMenu",hn="share.screenshot",ct="viewport.setDisplay",mn="viewport.getWindowInfo",gn="viewport.setNavigationBarStyle",lr="storage.getStorage",fr="storage.setStorage",pn="network.request",yn="network.download",En="network.upload",wn="files.pickFiles",In="files.pickDirectory",Mn="files.saveFile",hr="file.create",mr="file.remove",An="file.exists",gr="file.readText",Nn="file.writeText",pr="file.readBytes",Dn="file.writeBytes",yr="file.stat",Sn="directory.create",Er="directory.remove",Tn="directory.exists",bn="directory.list",On="ui.showToast",_n="ui.showLoading",vn="ui.hideLoading",Ln="device.vibrate",Cn="device.setClipboard",Rn="device.executeProtocol",Pn="navigation.close",kn="navigation.reload",xn="navigation.openAppPage",je="cloud.leaderboard.submit",De="cloud.leaderboard.getList",Qe="cloud.leaderboard.getCurrentUserEntry",dt="cloud.leaderboard.deleteCurrentUserEntry",Re="cloud.leaderboard.getInfo",vt="cloud.storage.getStorage",Lt="cloud.storage.setStorage",Ct="cloud.storage.removeItem",ut="cloud.storage.getKeys",Yn="companion.getInfo",qn="companion.getPreparationStatus",$n="companion.prepare",Wn="companion.cancelPreparation",Kn="companion.getActiveSession",Jn="companion.launch",Zn="companion.session.write",Xn="companion.session.closeStdin",ei="companion.session.terminate",ti="companion.session.ackOutput",ri="companion.openAttachment",ni="companion.showNotification",Ye=[{method:sn,module:"workspaceCards",capability:sn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:an,module:"auth",capability:an,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:cn,module:"user",capability:cn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:dn,module:"user",capability:dn,requirement:{kind:"none"},risk:"high"},{method:un,module:"user",capability:un,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:ln,module:"share",capability:ln,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:fn,module:"share",capability:fn,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:hn,module:"share",capability:hn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:mn,module:"viewport",capability:mn,requirement:{kind:"none"},risk:"low"},{method:gn,module:"viewport",capability:gn,requirement:{kind:"none"},risk:"low"},{method:ct,module:"viewport",capability:ct,requirement:{kind:"none"},risk:"low"},{method:lr,module:"storage",capability:lr,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:fr,module:"storage",capability:fr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:pn,module:"network",capability:pn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:yn,module:"network",capability:yn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:En,module:"network",capability:En,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:wn,module:"files",capability:wn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:In,module:"files",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"files",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hr,module:"file",capability:hr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mr,module:"file",capability:mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"file",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gr,module:"file",capability:gr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nn,module:"file",capability:Nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pr,module:"file",capability:pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"file",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sn,module:"directory",capability:Sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Er,module:"directory",capability:Er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tn,module:"directory",capability:Tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bn,module:"directory",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:On,module:"ui",capability:On,requirement:{kind:"none"},risk:"low"},{method:_n,module:"ui",capability:_n,requirement:{kind:"none"},risk:"low"},{method:vn,module:"ui",capability:vn,requirement:{kind:"none"},risk:"low"},{method:Ln,module:"device",capability:Ln,requirement:{kind:"none"},risk:"low"},{method:Cn,module:"device",capability:Cn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Rn,module:"device",capability:Rn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Pn,module:"navigation",capability:Pn,requirement:{kind:"none"},risk:"medium"},{method:kn,module:"navigation",capability:kn,requirement:{kind:"none"},risk:"medium"},{method:xn,module:"navigation",capability:xn,requirement:{kind:"none"},risk:"medium"},{method:je,module:"cloud",capability:je,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:dt,module:"cloud",capability:dt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Re,module:"cloud",capability:Re,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vt,module:"cloud",capability:vt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Lt,module:"cloud",capability:Lt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Ct,module:"cloud",capability:Ct,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:ut,module:"cloud",capability:ut,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[Yn,qn,$n,Wn,Kn,Jn,Zn,Xn,ei,ti,ri,ni].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],et="heybox:miniprogram",pc=2,vu="hb_mini_bridge_nonce",yc="sdk.handshake",Pr="runtime.location.probe",Lu="sdk.location.report",Cu="sdk.csp.violation",Ec="operation.progress",Ru="companion.session.output",Pu="companion.session.exit",ku="companion.session.ownershipLost";function xu(e){return!Je(e)||e.namespace!==et||e.version!==1&&e.version!==2||!le(e.nonce)?!1:e.type==="handshake"?le(e.id)&&e.method===yc&&e.error===void 0&&Hu(e.payload):e.type==="request"?le(e.id)&&le(e.method)&&e.error===void 0:e.type==="response"?le(e.id)&&(e.method===void 0||le(e.method))&&(e.error===void 0||Fu(e.error)):e.type==="event"?!le(e.method)||e.error!==void 0?!1:e.method===Ec?e.version===2&&le(e.id)&&zu(e.payload):e.id===void 0||le(e.id):e.type==="cancel"?e.version===2&&le(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Co(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function wc(e){return Je(e)?e.kind==="sandbox"?Ue(e,["kind"]):e.kind==="directory"&&le(e.handleId)&&Ue(e,["kind","handleId"]):!1}function ii(e){return!Je(e)||e.kind!=="file"?!1:le(e.handleId)?Ue(e,["kind","handleId"]):wc(e.root)&&Co(e.relativePath)&&Ue(e,["kind","root","relativePath"])}function Ic(e){return!Je(e)||e.kind!=="directory"?!1:le(e.handleId)?Ue(e,["kind","handleId"]):wc(e.root)&&(e.relativePath==="."||Co(e.relativePath))&&Ue(e,["kind","root","relativePath"])}function Mc(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function ju(e){return!Je(e)||!Tt(e.loaded)||typeof e.lengthComputable!="boolean"||!Ue(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Tt(e.total)&&e.loaded<=e.total:e.total===void 0}function Uu(e){return Je(e)?e.phase==="downloading"?Tt(e.loaded)&&(e.total===void 0||Tt(e.total)&&e.loaded<=e.total)&&Ue(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Tt(e.processed)&&Tt(e.total)&&e.processed<=e.total&&Ue(e,["phase","processed","total"]):!1}function zu(e){return ju(e)||Uu(e)}function Hu(e){return Je(e)&&le(e.href)&&typeof e.userAgent=="string"&&le(e.sdkVersion)}function Fu(e){return Je(e)&&le(e.code)&&typeof e.message=="string"}function Tt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function le(e){return typeof e=="string"&&e.length>0}function Ue(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wr=["userInfo","steamLibrary","share","storage","cloud_storage","filesystem","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Ac=[{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]}];new Set(wr);const Vu=new Set(wr);function Bu(e){return Vu.has(e)}function Se(e){if(!kr(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(!kr(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),!!Bu(o)){if(o==="network"){const s=n.config;if(!kr(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&&(!kr(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 kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const qr=["network","companion","appProtocol"];function Nc(e){if(!Bt(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>qr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Bt(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(!Bt(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(!Bt(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Bt(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>qr.indexOf(n.key)-qr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Gu(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Se(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of qr)!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 Ro(e){const t=Se(e.runtimePermissions),r=Nc(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of wr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Ac.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:{}}: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=Dc(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:wr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Dc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e,t){return Dc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Rt=["identity","profile","steam_account"],Qu=/^[a-z][a-z0-9-]{0,31}$/,Sc=["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"];Ye.map(e=>e.method);function Yu(e){const t=Se(e);return(r,n)=>{if(r.kind==="none")return{allowed:!0};for(const i of r.permissions){const o=t.valid?t.permissions[i]:void 0;if(!o)return{allowed:!1,code:"PERMISSION_NOT_IN_SNAPSHOT",message:`当前运行快照不包含权限: ${i};正式入口需发布包含该声明的新版本,开发入口请重新打开调试`,data:{permission:i,method:n}};if(o.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${i}`,data:{permission:i,method:n}}}return{allowed:!0}}}function qu(e){const t=Se(e),r=Object.values(t.permissions).map(i=>Object.freeze({...i,config:Object.freeze({...i.config})})),n=e&&typeof e=="object"&&"revision"in e?e.revision:void 0;return Object.freeze({schema_version:1,...typeof n=="number"?{revision:n}:{},entries:Object.freeze(r)})}function K(e,t,r){return{code:e,message:t,data:r}}function Po(e){return $u(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?K("RUNTIME_ERROR",e.message):K("UNKNOWN_ERROR","小程序运行时异常",e)}function $u(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Wu(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ku=1e3;function Ju(e,t=Wu()){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<=Ku}const Zu="runtime.gate.probe",Tc=new Set(Ye.map(e=>e.method));class Xu{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=pc;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:et,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:et,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:et,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:et,version:2,nonce:this.nonce,type:"event",id:t,method:Ec,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=Ju(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&&xu(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:et,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:yc,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===Zu){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,K("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Tc.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=Po(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:et,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"&&Tc.has(e)}const bc="METHOD_FORBIDDEN";function Te(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=bc,t}class ae 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 tl=/^[A-Za-z0-9_-]{1,64}$/,is=1e3;function Oc(e){return tl.test(e)?e:nl(e)}function rl(e){return`id_${Oc(e.trim())}`}function gt(e,t){return`hb_miniprogram_${e}_${t}`}function xr(e){return`hb_miniprogram_keys_${e}`}function nl(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)}const os={[sn]:["workspaceCards.requestRefresh"],[an]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[cn]:["account.getCurrentUserId","account.onChange","network.request"],[dn]:["account.getCurrentUserId","account.onChange","network.request"],[un]:["account.getCurrentUserId","account.onChange","network.request"],[ln]:["presentation.setClipboard"],[fn]:["presentation.showShareMenu"],[hn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ct]:["presentation.applyOrientation"],[mn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[gn]:["presentation.setNavigationBarStyle"],[lr]:["storage.getRaw"],[fr]:["storage.setRaw"],[pn]:["network.request"],[yn]:["network.stream","files.transfer","files.access"],[En]:["network.upload","files.access"],[wn]:["files.external"],[In]:["files.external"],[Mn]:["files.save"],[hr]:["files.access"],[mr]:["files.removeFile"],[An]:["files.access"],[gr]:["files.access"],[Nn]:["files.access"],[pr]:["files.access"],[Dn]:["files.access"],[yr]:["files.access"],[Sn]:["files.access"],[Er]:["files.removeDirectory"],[Tn]:["files.access"],[bn]:["files.access"],[On]:["presentation.showToast"],[_n]:["presentation.showLoading"],[vn]:["presentation.hideLoading"],[Ln]:["presentation.vibrate"],[Cn]:["presentation.setClipboard"],[Rn]:["protocol.invoke"],[Pn]:["presentation.close"],[kn]:["presentation.reload"],[xn]:["presentation.openAppPage"],[je]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[dt]:["account.getCurrentUserId","account.onChange","network.request"],[Re]:["account.onChange","network.request"],[vt]:["account.getCurrentUserId","account.onChange","network.request"],[Lt]:["account.getCurrentUserId","account.onChange","network.request"],[Ct]:["account.getCurrentUserId","account.onChange","network.request"],[ut]:["account.getCurrentUserId","account.onChange","network.request"],[Yn]:["companion.getInfo"],[qn]:["companion.getPreparationStatus"],[$n]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Wn]:["companion.cancelPreparation"],[Kn]:["companion.getActiveSession"],[Jn]:["companion.getInfo","companion.launch"],[Zn]:["companion.session.write"],[Xn]:["companion.session.closeStdin"],[ei]:["companion.session.terminate"],[ti]:["companion.session.ackOutput"],[ri]:["companion.openAttachment"],[ni]:["companion.showNotification"]};function il(e,t){if(t[e]!==!0)throw Te(e)}const ol=32*1024*1024,sl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function al(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:ol},i);return cl(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function cl(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:dl(t,ll(e,"content-type"))}}function dl(e,t){ul(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ae("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!sl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function ul(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ae(`Host network response 不支持 charset=${t}`)}function ll(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function k(e){return typeof e=="function"}function ss(e){return(...t)=>{throw Te(e)}}function oe(e){return async(...t)=>{throw Te(e)}}const fl=(e,t)=>{},hl=()=>()=>{};function ml(e){const t={request:k(e.network?.request)?e.network.request.bind(e.network):oe("network.request")},r={getCurrentUserId:k(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):oe("account.getCurrentUserId"),ensureAuthenticated:k(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):oe("account.ensureAuthenticated"),onChange:k(e.account?.onChange)?e.account.onChange.bind(e.account):hl},n={getRaw:k(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):oe("storage.getRaw"),setRaw:k(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):oe("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):oe("presentation.close"),reload:k(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):oe("presentation.reload"),openAppPage:k(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):oe("presentation.openAppPage"),openWindow:k(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):oe("presentation.openWindow"),getViewportMetrics:k(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):ss("presentation.getViewportMetrics"),getNavigationBarHeight:k(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):ss("presentation.getNavigationBarHeight"),setNavigationBarStyle:k(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):oe("presentation.setNavigationBarStyle"),showShareMenu:k(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):oe("presentation.showShareMenu"),setScreenshotChromeHidden:k(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):fl,captureAndShare:k(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):oe("presentation.captureAndShare"),showToast:k(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):oe("presentation.showToast"),showLoading:k(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):oe("presentation.showLoading"),hideLoading:k(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):oe("presentation.hideLoading"),vibrate:k(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):oe("presentation.vibrate"),setClipboard:k(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):oe("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(c=>[c,k(e.companion?.[c])?e.companion[c].bind(e.companion):oe(`companion.${c}`)]));k(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:k(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):oe("protocol.invoke")};return{network:t,account:r,storage:n,presentation:i,companion:s,protocol:a,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...o?{storageDiagnostics:o}:{}}}function gl(e){const t=pl(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),"network.upload":k(e.transfer?.upload?.upload),"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.scopedStorage?.get)||k(e.storage?.getRaw),"storage.setRaw":k(e.scopedStorage?.set)||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),"workspaceCards.requestRefresh":!1,"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),"protocol.invoke":k(e.protocol?.invoke)}}function pl(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 as(e,t){return t?.[e]!==!1}function yl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function _c(e,t={}){const r={};for(const n of Object.keys(os)){const o=os[n].every(a=>e[a]),s=!yl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=as(n,t.callerCapabilities)&&as(n,t.hostCapabilities)&&o&&s}return r}function vc(e={},t={}){const r=gl(e),n=_c(r,t);return{ports:ml(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function lt(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):El(e.signal,t);return{...e,signal:r}}function El(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 wl(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 Il=4,Ml=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Al=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Nl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Dl=["/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 Sl(e,t){const r=Ol(e);return r===null||cs(r,Nl)?!0:t&&cs(r,Dl)}function Tl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Ml.some(r=>t===r||t.endsWith(`.${r}`))}function bl(e){const t=e.trim().toLowerCase();return Al.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Ol(e){let t=e;for(let r=0;r<Il;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return ds(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return ds(t)}function cs(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function ds(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function pt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function us(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Lc(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 d(I,T){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:I,type:T})).catch(()=>{})}catch{}}function l(I){const T=r.get(I);if(!T)throw new Error("Unknown runtime cache scope");return T}function h(I,T){return I.flatMap((A,_)=>{const D=JSON.stringify(I.slice(0,_+1));return[JSON.stringify([D]),JSON.stringify([D,T])]})}function u(I,T){return JSON.stringify(h(I,T).map(A=>n.get(A)??0))}async function f(I,T){const A=l(I),_=JSON.stringify([JSON.stringify(A),...T?[T]:[]]),D=(n.get(_)??0)+1;n.set(_,D),i.add(_);for(const L of a)L(A,T);if(!e.store){i.delete(_),d(T??"*","invalidation");return}try{await e.store.invalidate(A,T)}catch(L){throw d(T??"*","storage_error"),L}n.get(_)===D&&i.delete(_),d(T??"*","invalidation")}function w(I){if(c)throw new Error("Runtime cache manager disposed");const T=o.get(I.namespace);if(T){if(T.sourceCodec!==I.codec||T.definition.codec.version!==I.codec.version||JSON.stringify(T.definition.policy)!==JSON.stringify(I.policy))throw new Error("Conflicting runtime cache namespace");return T.cache}if(!I.namespace||!I.codec.version)throw new Error("Invalid runtime cache definition");const A=Object.freeze({...I.policy}),_=Object.freeze({version:I.codec.version,encode:I.codec.encode.bind(I.codec),decode:I.codec.decode.bind(I.codec),validate:I.codec.validate.bind(I.codec),clone:I.codec.clone.bind(I.codec)}),D=I.namespace;for(const O of[A.ttlMs,A.memoryMaxEntries,A.diskMaxEntries,A.diskMaxBytes,A.maxEntryBytes])if(!Number.isFinite(O)||O<0)throw new Error("Invalid runtime cache policy");const L=new Map,z=new Map,v=new Map;let N=!1;function m(O,C,b){if(c||N||O.aborted||u(C,D)!==b)throw pt()}function p(O){return A.ttlMs>0&&A.persistence==="memory-and-disk"&&!!e.store&&!h(O,D).some(C=>i.has(C))}function g(O,C,b){const x=t();return O.envelopeVersion===1&&JSON.stringify(O.address)===JSON.stringify(C)&&us(O.revisions,b)&&O.payload.byteLength<=A.maxEntryBytes&&Number.isFinite(O.cachedAt)&&Number.isFinite(O.expiresAt)&&O.cachedAt<=x&&O.cachedAt>=0&&O.expiresAt>O.cachedAt&&Math.min(O.expiresAt,O.cachedAt+A.ttlMs)>x}function E(O,C,b,x,j){if(!(A.ttlMs<=0||A.memoryMaxEntries<1)){for(const[U,B]of L)Math.min(B.entry.expiresAt,B.entry.cachedAt+A.ttlMs)<=t()&&L.delete(U);for(L.delete(O);L.size>=Math.floor(A.memoryMaxEntries);){const U=L.keys().next();if(U.done)break;L.delete(U.value)}L.set(O,{entry:C,value:b,epoch:x,persistent:j})}}async function M(O,C,b,x){const j={namespace:D,codecVersion:_.version,scopeIds:C,key:O.key},U=JSON.stringify(j);let B=[],G=p(C);if(G)try{B=await e.store.readRevisions(C,D)}catch{G=!1,d(D,"storage_error")}m(x.signal,C,b);async function Y(){if(!G)return!0;try{return us(B,await e.store.readRevisions(C,D))}catch{return G=!1,d(D,"storage_error"),!1}}const ne=L.get(U);if(A.ttlMs>0&&ne&&ne.epoch===b&&g(ne.entry,j,B)&&ne.persistent===G&&await Y())return m(x.signal,C,b),d(D,"memory_hit"),ne.value;if(L.delete(U),G){let W,pe;try{W=await e.store.read(j,A.maxEntryBytes),W&&g(W,j,B)?pe=_.decode(W.payload):W=void 0}catch{W=void 0,d(D,"storage_error")}if(m(x.signal,C,b),W&&await Y())return m(x.signal,C,b),E(U,W,pe,b,!0),d(D,"disk_hit"),pe}d(D,"miss");const te=_.validate(await O.load(x.signal));m(x.signal,C,b);const ee=_.clone(te);if(!await Y()&&G)throw pt();if(m(x.signal,C,b),A.ttlMs>0){const W=t();let pe;try{pe=_.encode(ee)}catch{return ee}const ts={envelopeVersion:1,address:j,revisions:G?B:[],cachedAt:W,expiresAt:W+A.ttlMs,payload:pe};if(G&&pe.byteLength<=A.maxEntryBytes){let gi=!0,rs=!1;try{gi=await e.store.publish(ts,A),rs=gi}catch{d(D,"storage_error")}if(m(x.signal,C,b),!gi)throw pt();rs&&d(D,"published")}m(x.signal,C,b),E(U,ts,ee,b,G)}return ee}async function S(O){if(c||N||O.signal?.aborted)return Promise.reject(pt());const C=l(O.scope),b=u(C,D);let x;if(p(C)){const G=new AbortController;v.set(G,C);const Y=()=>G.abort();O.signal?.addEventListener("abort",Y,{once:!0});let ne=()=>{};try{x=await Promise.race([e.store.readRevisions(C,D),new Promise((te,ee)=>{const W=()=>ee(pt());G.signal.addEventListener("abort",W,{once:!0}),ne=()=>G.signal.removeEventListener("abort",W)})])}catch{G.signal.aborted||d(D,"storage_error")}finally{ne(),v.delete(G),O.signal?.removeEventListener("abort",Y)}}m(O.signal??new AbortController().signal,C,b);const j=JSON.stringify([C,O.key,b,x]);let U=z.get(j);if(U?.controller.signal.aborted&&(U=void 0),!U){const G=new AbortController;U={ids:C,controller:G,waiters:0,promise:Promise.resolve(void 0)};const Y=U;Y.promise=M(O,C,b,G).finally(()=>{z.get(j)===Y&&z.delete(j)}),z.set(j,Y)}const B=U;return B.waiters+=1,new Promise((G,Y)=>{let ne=!1;function te(W){ne||(ne=!0,O.signal?.removeEventListener("abort",ee),B.controller.signal.removeEventListener("abort",ee),B.waiters-=1,B.waiters===0&&B.controller.abort(),W())}function ee(){te(()=>Y(pt()))}O.signal?.addEventListener("abort",ee,{once:!0}),B.controller.signal.addEventListener("abort",ee,{once:!0}),B.promise.then(W=>te(()=>{try{m(O.signal??new AbortController().signal,C,b),G(_.clone(W))}catch(pe){Y(pe)}}),W=>te(()=>Y(W)))})}function R(O,C){if(C&&C!==D)return;const b=x=>O.every((j,U)=>x[U]===j);for(const[x,j]of L)b(j.entry.address.scopeIds)&&L.delete(x);for(const[x,j]of z)b(j.ids)&&(j.controller.abort(),z.delete(x));for(const[x,j]of v)b(j)&&x.abort()}function F(){if(!N){N=!0,L.clear();for(const O of v.keys())O.abort();v.clear();for(const O of z.values())O.controller.abort();z.clear(),s.delete(F),a.delete(R),o.get(D)?.cache===P&&o.delete(D)}}const P={read:S,invalidateScope:O=>f(O,D),dispose:F};return s.add(F),a.add(R),o.set(D,{definition:{namespace:D,codec:_,policy:A},sourceCodec:I.codec,cache:P}),P}return{createScope(I,T){if(c||!I)throw new Error("Invalid runtime cache scope");const A=Object.freeze({});return r.set(A,[...T?l(T):[],I]),A},register:w,invalidateScope:I=>f(I),dispose(){if(!c){c=!0;for(const I of[...s])I();o.clear(),n.clear(),i.clear()}}}}function _l(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 vl=".hb-runtime-cache-v1",pi=64*1024,yt=1e3,Ll=2048,Gt=32*1024*1024,Cl=1024,$r=new TextEncoder,ls=new TextDecoder("utf-8",{fatal:!0});function Qt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function jr(e){const t=await globalThis.crypto.subtle.digest("SHA-256",$r.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Oe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fs(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Rl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function hs(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Pl(e,t){const r=e.sandbox.directory(vl),n=r.directory("revisions"),i=r.directory("entries");for(const m of[r,n,i,i.directory("capability-check")])hs(m,["directory","file","create","stat","list","remove"]),hs(m.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(m){if(Rl(m))throw s=!0,m}function c(){if(t.signal.aborted)throw Qt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function d(m,p=t.signal){const g=o.then(()=>{if(p.aborted)throw Qt();return c(),m()},()=>{if(p.aborted)throw Qt();return c(),m()}).catch(S=>{throw a(S),S});if(o=g.catch(()=>{}),p.aborted)return Promise.reject(Qt());let E=()=>{};const M=new Promise((S,R)=>{const F=()=>R(Qt());p.addEventListener("abort",F,{once:!0}),E=()=>p.removeEventListener("abort",F)});return Promise.race([g,M]).finally(E)}async function l(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function h(m,p){const g=n.file(`${await jr([m,p??null])}.revision`);await f(g);let E=!1;try{await g.create({recursive:!1,exclusive:!0},t),E=!0}catch(R){a(R),c()}if(E){const R=fs();return await g.write($r.encode(R),t),c(),R}const M=await g.stat(t);if(M.size<1||M.size>128)throw new Error("缓存 revision 文件损坏");const S=ls.decode(await g.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return c(),S}async function u(m){const p=await m.list({limit:yt},t);if(p.length>=yt)throw new Error("缓存目录超过治理上限");return p}async function f(m){try{await m.stat(t);return}catch(g){if(!Ur(g))throw g}if((await u(n)).length>=yt-1)throw new Error("缓存 metadata 超过治理上限")}async function w(m,p){await l();const g=[];for(let E=0;E<m.length;E+=1){const M=m.slice(0,E+1);g.push(await h(M),await h(M,p))}return g}async function I(m){return r.directory(`entries/${await jr([m.namespace,m.codecVersion,m.scopeIds])}`)}async function T(m){return(await I(m)).file(`${await jr(m.key)}.cache`)}async function A(m,p){const g=await m.stat(t);if(g.size<5||g.size>p+pi+4)throw new Error("缓存条目超过大小限制");const E=await m.read(t);if(c(),E.length!==g.size)throw new Error("缓存条目读取不完整");const M=new DataView(E.buffer,E.byteOffset,E.byteLength).getUint32(0);if(M<1||M>pi||M+4>E.length)throw new Error("缓存信封损坏");const S=JSON.parse(ls.decode(E.subarray(4,M+4))),R=E.slice(M+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(F=>typeof F=="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(F=>typeof F=="string"&&F.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==R.length||R.length>p)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:R}}async function _(m){if(!m.remove)throw new Error("Host 不支持缓存文件删除");await m.remove(t)}async function D(m){try{if((await m.file.stat(t)).size!==m.size)return!1;const p=await A(m.file,Gt);return!Oe(p.address,m.entry.address)||!Oe(p.revisions,m.entry.revisions)||p.cachedAt!==m.entry.cachedAt||p.expiresAt!==m.entry.expiresAt||!Oe(await L(p.payload),await L(m.entry.payload))?!1:(await _(m.file),!0)}catch(p){if(Ur(p))return!0;throw p}}async function L(m){const p=await globalThis.crypto.subtle.digest("SHA-256",m);return Array.from(new Uint8Array(p),g=>g.toString(16).padStart(2,"0")).join("")}async function z(){const m=await u(n);let p=0;for(const S of m)if(S.kind==="file"&&(p+=(await S.stat(t)).size,p>Gt))throw new Error("缓存扫描超过字节上限");const g=[];let E=0,M=p;for(const S of await u(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const R of await u(S)){if(R.kind!=="file"||++E>Ll)throw new Error("缓存文件超过治理上限");const F=(await R.stat(t)).size;if(M+=F,M>Gt)throw new Error("缓存扫描超过字节上限");try{const P=await A(R,Gt);g.push({file:R,entry:P,size:(await R.stat(t)).size,bucketName:S.name})}catch(P){a(P),c(),Ur(P)||await _(R)}}}return{entries:g,metadataBytes:p}}async function v(){for(const m of await u(i))if(m.kind==="directory"&&m.remove&&(await u(m)).length===0)try{await m.remove({recursive:!1},t)}catch(p){a(p),c()}}function N(m){const{payload:p,...g}=m,E=$r.encode(JSON.stringify({...g,payloadBytes:p.length}));if(E.length>pi)throw new Error("缓存信封过大");const M=new Uint8Array(4+E.length+p.length);return new DataView(M.buffer).setUint32(0,E.length),M.set(E,4),M.set(p,E.length+4),M}return{readRevisions:(m,p)=>d(()=>w(m,p)),read:(m,p)=>d(async()=>{c();const g=await T(m);let E;try{E=await A(g,p)}catch(M){if(c(),Ur(M))return;throw M}if(!(!Oe(E.address,m)||E.expiresAt<=Date.now())&&Oe(E.revisions,await w(m.scopeIds,m.namespace)))return E}),publish:(m,p)=>d(async()=>{c();const{address:g}=m;if(!Oe(m.revisions,await w(g.scopeIds,g.namespace)))return!1;const E=N(m);if(m.payload.length>p.maxEntryBytes||E.length>p.diskMaxBytes||p.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await l();const M=await I(g),S=await T(g),R=await z(),F=[],P=new Map;for(const b of R.entries){if(b.bucketName===M.name&&b.file.name===S.name)continue;const x=JSON.stringify([b.entry.address.scopeIds,b.entry.address.namespace]);let j=P.get(x);if(j||(j=await w(b.entry.address.scopeIds,b.entry.address.namespace),P.set(x,j)),b.entry.expiresAt<=Date.now()||!Oe(b.entry.revisions,j)){if(!await D(b))throw new Error("缓存治理期间条目已变化")}else F.push(b)}F.sort((b,x)=>b.entry.cachedAt-x.entry.cachedAt);function O(){const b=F.filter(x=>x.bucketName===M.name);return F.length+1>Cl||E.length+R.metadataBytes+F.reduce((x,j)=>x+j.size,0)>Gt||b.length+1>Math.min(p.diskMaxEntries,yt-1)||E.length+b.reduce((x,j)=>x+j.size,0)>p.diskMaxBytes}for(;O();){const b=F.filter(U=>U.bucketName===M.name),j=b.length+1>Math.min(p.diskMaxEntries,yt-1)||E.length+b.reduce((U,B)=>U+B.size,0)>p.diskMaxBytes?b[0]:F[0];if(!j||!await D(j))throw new Error("缓存容量不足或条目已变化");F.splice(F.indexOf(j),1)}await v();const C=await u(i);if(!C.some(b=>b.name===M.name)&&C.length>=yt-1)throw new Error("缓存目录超过治理上限");if(await M.create({recursive:!0,exclusive:!1},t),!Oe(m.revisions,await w(g.scopeIds,g.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},t)}catch(b){a(b),await S.stat(t)}return await S.write(E,t),c(),Oe(m.revisions,await w(g.scopeIds,g.namespace))}),invalidate:(m,p)=>d(async()=>{await l();const g=n.file(`${await jr([m,p??null])}.revision`);await f(g);try{await g.create({recursive:!1,exclusive:!0},t)}catch(E){a(E),await g.stat(t)}await g.write($r.encode(fs()),t),c();try{const{entries:E}=await z();for(const M of E){if(p!==void 0&&M.entry.address.namespace!==p||!m.every((R,F)=>M.entry.address.scopeIds[F]===R))continue;const S=await w(M.entry.address.scopeIds,M.entry.address.namespace);Oe(M.entry.revisions,S)||await D(M)}await v()}catch(E){a(E),c()}})}}function Ur(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const kl="RATE_LIMITED_BY_RUNTIME",xl="RATE_LIMITED",Cc=20,Rc=40,Pc=150,kc=20,xc=1e4,jc=45e3,Uc=1,jl=300*1e3,Ul=64;function Et(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function zl(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Hl(e={}){const t=e.now??Date.now,r=zl(e.coalesceWindowMs,Pc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Et(e.budget?.ratePerSecond,Cc)),burst:Math.max(1,Math.floor(Et(e.budget?.burst,Rc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Et(e.loopDetection?.maxCalls,kc))),windowMs:Math.max(1,Math.floor(Et(e.loopDetection?.windowMs,xc)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Et(e.circuitBreaker?.failureThreshold,Uc))),openMs:Math.max(1,Math.floor(Et(e.circuitBreaker?.openMs,jc)))},s=new Map,a=new Map,c=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function f(N){try{e.onReport?.(N)}catch{}}function w(N,m){if(!i)return{exceeded:!1,count:0};const p=a.get(N)??[],g=m-i.windowMs;let E=0;for(;E<p.length&&p[E]<=g;)E+=1;E>0&&p.splice(0,E);const M=p.length>=i.maxCalls;return M||(p.push(m),p.length>i.maxCalls+1&&p.splice(0,p.length-(i.maxCalls+1))),a.set(N,p),{exceeded:M,count:p.length}}function I(N){if(!n)return!0;const m=Math.max(0,N-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+m*n.ratePerSecond),l.updatedAt=N,l.tokens<1?!1:(l.tokens-=1,!0)}function T(N){if(!n)return 0;const m=Math.max(0,N-l.updatedAt)/1e3,p=Math.min(n.burst,l.tokens+m*n.ratePerSecond);return Math.max(0,Math.ceil((1-p)/n.ratePerSecond*1e3))}function A(N,m,p,g,E){if(!o)return;const M=d.get(m),S=(M?.open?0:M?.failures??0)+1;if(S<o.failureThreshold){d.set(m,{open:!1,openedAt:0,openMs:0,failures:S});return}const R=Math.min(Math.max(o.openMs,g),jl);d.set(m,{open:!0,openedAt:E,openMs:R,failures:S}),h.circuitOpened+=1,f({type:"circuit_opened",capability:N,endpointId:m,status:p,openMs:R,timestamp:E})}function _(N){const m=d.get(N);m&&!m.open&&d.delete(N)}function D(N){for(const[m,p]of s)!p.pending&&p.expiresAt<=N&&s.delete(m);for(;s.size>=Ul;){const m=[...s].find(([,p])=>!p.pending);if(!m)break;s.delete(m[0])}}function L(N,m){if(N===void 0)return;const p=s.get(N);p?.promise===m&&(p.pending=!1)}function z(N,m){if(N===void 0)return;s.get(N)?.promise===m&&s.delete(N)}async function v(N){if(u)return N.load();const m=t();if(o){const M=d.get(N.endpointId);if(M?.open){const S=M.openedAt+M.openMs-m;if(S>0)throw h.circuitRejected+=1,f({type:"circuit_rejected",capability:N.capability,endpointId:N.endpointId,retryAfterMs:S,timestamp:m}),Bl("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:N.endpointId,retryAfterMs:S});d.delete(N.endpointId)}}const p=w(N.endpointId,m);p.exceeded&&i?c.has(N.endpointId)||(c.add(N.endpointId),f({type:"loop_detected",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs,timestamp:m})):c.delete(N.endpointId);const g=r>0?N.coalesceKey:void 0;if(g!==void 0){const M=s.get(g);if(M&&(M.pending||M.expiresAt>m))return h.coalesced+=1,f({type:"coalesced",capability:N.capability,endpointId:N.endpointId,timestamp:m}),M.promise;M&&s.delete(g)}if(p.exceeded&&i)throw h.loopRejected+=1,ms("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs});if(!I(m)){h.budgetRejected+=1;const M=T(m);throw f({type:"budget_exhausted",capability:N.capability,endpointId:N.endpointId,retryAfterMs:M,timestamp:m}),ms("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:N.capability,endpointId:N.endpointId,retryAfterMs:M})}g!==void 0&&D(m);const E=N.load().then(M=>(L(g,E),_(N.endpointId),M),M=>{z(g,E);const S=Fl(M);throw S!==void 0&&A(N.capability,N.endpointId,S,Vl(M),m),M});return g!==void 0&&s.set(g,{endpointId:N.endpointId,promise:E,expiresAt:m+r,pending:!0}),E}return{execute:v,invalidateCoalescing(N){if(N===void 0){s.clear();return}for(const[m,p]of s)N.includes(p.endpointId)&&s.delete(m)},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,N])=>N.open).map(([N])=>N)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Fl(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 Vl(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 ms(e,t){return{code:kl,message:e,data:t}}function Bl(e,t){return{code:xl,message:e,data:t}}const zc=3e4,Hc=6e4,no=1440*60*1e3;function Gl(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??zc)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Hc)):0,steamGameListTtlMs:t?Ql(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Cc,burst:Rc},coalesceWindowMs:r?.coalesceWindowMs??Pc,loopDetection:r?.loopDetection??{maxCalls:kc,windowMs:xc},circuitBreaker:r?.circuitBreaker??{failureThreshold:Uc,openMs:jc}}}}function Ql(e){return e===void 0||!Number.isFinite(e)?no:Math.max(0,Math.floor(e))}function y(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yl(e){return typeof e=="object"&&e!==null}function de(e,t){const r=e.data;if(!Yl(r)||typeof r.status!="string")throw new Error(t);return r}const Fc={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},ql={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 de(e,"工坊小程序详情加载失败")}};function Or(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function $l(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Wl(e){const t=de(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=$l(r.consent_challenge)),{...t,result:n}}const Kl={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=>({...Or(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},Jl={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=>Or(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},Zl={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=>Or(e.runtimeContext),parse(e){const t=de(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}:{}}}}},Xl={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=>({...Or(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Wl(e)},ef={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=>({...Or(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},tf=64;function Vc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??tf)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(h){for(const[u,f]of i)f.expiresAt<=h&&i.delete(u)}function d(h,u,f){if(a||t<=0||f!==s)return;const w=n();for(c(w),i.delete(h);i.size>=r;){const I=i.keys().next();if(I.done)break;i.delete(I.value)}i.set(h,{expiresAt:w+t,value:u})}function l(h,u){if(a)return u();if(t>0){const T=i.get(h);if(T&&T.expiresAt>n())return Promise.resolve(T.value);T&&i.delete(h)}const f=o.get(h);if(f)return f;const w=s,I=u().then(T=>(d(h,T,w),T)).finally(()=>{o.get(h)===I&&o.delete(h)});return o.set(h,I),I}return{read:l,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function rf(e,t){return t?e?"server":"local":"legacy"}function nf(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const of=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],sf=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),af=/authorization|cookie|pkey|password|secret|token/i,Bc=/authorization|cookie|pkey|token|password|secret/i;function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function cf(e){for(const t of Object.keys(e))if(!sf.has(t))throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of of)if(Object.prototype.hasOwnProperty.call(e,t)&&_e(e,t)!==void 0)throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(_e(e,"bodyEncoding")!==void 0&&_e(e,"bodyEncoding")!=="json"&&_e(e,"bodyEncoding")!=="form")throw new ae("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(_e(e,"failurePresentation")!==void 0&&_e(e,"failurePresentation")!=="none")throw new ae("endpoint failurePresentation 必须为 none");if(_e(e,"auth")!==void 0&&_e(e,"auth")!=="none"&&_e(e,"auth")!=="optional"&&_e(e,"auth")!=="required")throw new ae("endpoint auth 必须为 none、optional 或 required")}function rr(e){if(Array.isArray(e))return e.map(rr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))af.test(n)||(r[n]=rr(i));return r}function gs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Bc.test(r)||(t[r]=n);return t}function df(e){if(!e)return;const t=Object.keys(e).find(r=>Bc.test(r));if(t)throw new ae(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Pt 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 ps=1440*60*1e3,uf=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function lf(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,ps):void 0}if(!uf.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,ps):void 0}function ff(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 Gc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class kt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Gc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class _r extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Gc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function hf(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:rr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:gs(o),method:e.method,metadata:{endpointId:e.id},query:rr(n),timeout:e.timeout,url:r},data:rr(a.data),headers:gs(a.headers)||{},status:a.status,statusText:a.statusText}}async function oi(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(cf(t),typeof t.id!="string"||!t.id)throw new ae("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ae("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ae("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;df(a);const c=async()=>{let h;try{h=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(f){throw f instanceof ae?f:new kt({endpointId:t.id,cause:f})}if(h.status<200||h.status>=300)throw new Pt({endpointId:t.id,status:h.status,retryAfterMs:lf(h.headers)});const u=hf(t,r,i,o,s,a,n,h);if(t.parse)try{return await t.parse(u,r)}catch(f){throw new _r({endpointId:t.id,cause:f})}return u.data},d=n.gate;if(!d)return c();const l=ff(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:c})}const mf=new Set(Rt),ko="steam_account",Qc=new Set(Rt.filter(e=>e!==ko)),gf=1e3;function pf(e){const t=new Set,r=Vc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??zc))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??rf(e.networkEnabled===!0,c),l=e.requestPolicyEnabled!==!1,h=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c)return{};if(!e.authorizationContext)throw y("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let P;try{P=await e.authorizationContext.get(e.operationContext)}catch(C){throw oo(C)?yi(C.code,C.message,C):yi("REQUEST_FAILED","读取 Runtime auth context 失败",C)}if(P.steamAccount!==c||P.userDataMode!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const O=P.token.trim();if(!O)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:O}}const f=e.account.onChange(P=>{w(),I("heybox_app_login_change",{isHeyboxAppLoggedIn:!!P})});function w(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function I(P,O){P==="user_info_authorization_change"&&Af(O)&&r.invalidate();for(const C of t)try{C(P,O)}catch{}}function T(){const P=e.identity.get()?.miniProgramId?.trim();if(!P)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return P}function A(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function _(){A();let P;try{P=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw Is(O,e.operationContext.signal,"读取小黑盒账号失败")}return typeof P=="string"&&P.trim()?P.trim():void 0}async function D(P,O){const C=await _();if(i!==O||C!==P)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function L(P){A();try{await e.account.ensureAuthenticated({trustedUserGesture:P,reason:"runtime_auth",signal:e.operationContext.signal})}catch(C){throw Is(C,e.operationContext.signal,"小黑盒登录失败")}const O=await _();if(!O)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return O}async function z(P,O,C=e.operationContext.signal){try{if(C.aborted)throw io();return await Mf(oi(e.network,P,O,{...e.operationContext,credentials:"heybox-session",signal:C,...h?{gate:h}:{}}),C)}catch(b){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):b instanceof ae?y("REQUEST_UNSUPPORTED",b.message):b instanceof _r?y("INVALID_RESPONSE","授权接口响应不合法"):b instanceof kt?y("REQUEST_FAILED","授权请求失败"):b instanceof Pt?l&&(b.status===403||b.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:b.status,...b.retryAfterMs===void 0?{}:{retryAfterMs:b.retryAfterMs}}):y("REQUEST_FAILED",b.message):oo(b)?b:y("REQUEST_FAILED","授权请求失败")}}async function v(P,O){await z(Kl,{runtimeContext:{miniProgramId:P,...await u()},challenge:O}).catch(()=>{})}function N(P){const O=async()=>{const b=Es(e.operationContext.signal);a=b;try{return await P(b.signal)}finally{a===b&&(a=void 0),b.abort()}},C=s.then(O,O);return s=C.then(()=>{},()=>{}),C}async function m(P,O,C,b,x){if(!C)throw await v(P,O.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await v(P,O.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return N(async j=>{await D(b,x);const U=await p(P,O.displayedScopes,j);await D(b,x);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:P,scopes:O.displayedScopes,...U,signal:j})}catch(Y){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await D(b,x),await v(P,O.challenge),yi("REQUEST_FAILED","授权确认界面执行失败",Y))}if(await D(b,x),B.status!=="granted")throw await v(P,O.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const G=wf(B.grantedScopes,O.displayedScopes,c);if(!G.includes("identity"))throw await v(P,O.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return G})}async function p(P,O,C){const b=Es(C),x=setTimeout(()=>b.abort(),gf);try{const j=If(e.miniProgramPresentation),[U,B]=await Promise.all([j?Promise.resolve(j):g(P,b.signal),O.includes("profile")?E(b.signal):Promise.resolve(void 0)]);return{...U?{miniProgram:U}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(x),b.abort()}}async function g(P,O){try{const C=e.identity.get()?.version?.trim(),b=await z(ql,{mini_program_id:P,...C?{miniprogram_version:C}:{}},O),x=wt(b,"小程序公开资料"),j=bt(x.name),U=bt(x.icon_url);return j||U?{...j?{name:j}:{},...U?{avatarUrl:U}:{}}:void 0}catch{return}}async function E(P){try{const O=await z(Fc,void 0,P),C=wt(O,"账号基础信息"),b=bt(C.display_username),x=bt(C.display_avatar);return b||x?{...b?{nickname:b}:{},...x?{avatar:x}:{}}:void 0}catch{return}}async function M(P,O){if(nf(d,"auth.login"),!c&&P.includes(ko))throw y("INVALID_PARAMS","auth.login 参数不合法");const C=T(),b=await L(O),x=i,j=await z(Xl,{runtimeContext:{miniProgramId:C,...await u()},scopes:P});await D(b,x);const U=wt(j,"小程序登录"),B=ws(U,"loginCode"),G=ws(U,"consentChallenge");if(B===G)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Y;if(B)Y=ys(U.loginCode,c);else{const ne=yf(U.consentChallenge,c),te=await m(C,ne,O,b,x);await D(b,x);const ee=await z(ef,{runtimeContext:{miniProgramId:C,...await u()},challenge:ne.challenge,selectedScopes:te});if(await D(b,x),Y=ys(wt(ee,"小程序登录确认"),c),Y.scopes.some(W=>!te.includes(W)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ne of Y.scopes)n.add(ne);return r.invalidate(),I("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),I("user_info_authorization_change",Ei(n,c)),Y}async function S(P,O){const C=i,b=await z(Zl,{runtimeContext:{miniProgramId:O,...await u()}});await D(P,C);const x=Ef(wt(b,"用户本地身份"),c);for(const j of c?Rt:Qc)n.add(j);return I("user_info_authorization_change",Ei(n,c)),x}function R(P){A();const O=T(),C=`${P}\0${O}\0${i}\0${c}`;return r.read(C,()=>S(P,O))}async function F(P){if(!P)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const O=T(),C=i,b=await _();if(!b)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const x=await z(Jl,{runtimeContext:{miniProgramId:O,...await u()}});await D(b,C),wt(x,"用户授权撤销"),w(),I("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:M,getOrCreateLocalIdentity:R,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ei(n,c),revoke:F,onEvent(P){return t.add(P),()=>t.delete(P)},dispose(){o||(o=!0,w(),r.dispose(),f(),t.clear())}}}function yi(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function wt(e,t){if(!H(e))throw y("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 y(n,r)}if(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ys(e,t){if(!H(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=jn(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 y("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function yf(e,t){if(!H(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=jn(e.requestedScopes,"challenge requestedScopes",t),n=jn(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 y("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Ef(e,t){if(!H(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw y("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw y("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 wf(e,t,r){const n=jn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function bt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function If(e){const t=bt(e?.name),r=bt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Es(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 Mf(e,t){return t.aborted?Promise.reject(io()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(io()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function io(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function jn(e,t,r){const n=r?mf:Qc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw y("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ei(e,t){const r=t?Rt:Rt.filter(n=>n!==ko);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ws(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Af(e){return H(e)?Object.values(e).some(t=>t==="denied"):!1}function oo(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Is(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):oo(e)?e:y("REQUEST_FAILED",r)}const Nf=new Set(Rt);function Df(e){return{[an]:async(t,r)=>e.authorization.login(Sf(t),r.trustedUserGesture)}}function Sf(e){if(e===void 0)return["identity"];if(!H(e)||Object.keys(e).some(t=>t!=="scopes"))throw Ms();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Nf.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Ms();return[...e.scopes]}function Ms(){return y("INVALID_PARAMS","auth.login 参数不合法")}const Tf={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 de(e,"排行榜记录删除接口响应异常")}},bf={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 de(e,"当前排行榜记录接口响应异常")}},Of={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 de(e,"排行榜信息接口响应异常")}},_f={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 de(e,"排行榜列表接口响应异常")}},vf={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 de(e,"排行榜提交接口响应异常")}};function Wr(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function q(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:Wr()}function As(e){return e instanceof ae?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Wr());let n;try{n=e()}catch(i){return Promise.reject(As(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Wr())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(Wr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(As(d))))})}const Lf={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"};async function Yc(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await $(()=>oi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(zn(i)||Jt(i,"REQUEST_UNSUPPORTED")||Jt(i,"RATE_LIMITED")||Jt(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ae)throw re("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof kt&&Jt(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Pt){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw re("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw re("UNAUTHORIZED","当前用户未登录")}throw i instanceof kt||i instanceof Pt?Un(e.subject):i instanceof _r?J(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):J(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function xe(e,t,r){if(!me(e)||typeof e.status!="string")throw J(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Cf(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw J(`${t} 响应缺少 result`);return e.result}function qc(e,t){try{return e.onChange(t)}catch(r){if(Jt(r,bc))return()=>{};throw r}}function Cf(e,t){if(e.status==="login"||e.status==="relogin")throw re("UNAUTHORIZED",Kt(e.msg)||"当前用户未登录");const r=Ns(e.result)??Ns(e),n=Kt(r?.user_message)||Kt(e.msg)||Kt(r?.developer_message)||`${t}请求失败`;throw r?re(Rf(r),n,{status:e.status,sbe:r}):re("HEYBOX_API_ERROR",n,{status:e.status})}function Ns(e){return me(e)&&me(e.sbe)?e.sbe:void 0}function Rf(e){const t=Kt(e.developer_message);if(t==="CLOUD_STORAGE_KEY_LIMIT_EXCEEDED")return"STORAGE_QUOTA_EXCEEDED";if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return Lf[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 me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Jt(e,t){return me(e)&&e.code===t}function re(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function J(e){return re("INVALID_RESPONSE",e)}function Un(e){return re("REQUEST_FAILED",`${e}请求失败`)}function zn(e){return e instanceof Error&&e.name==="AbortError"}const Pf="default",Ze="排行榜",kf=/^[A-Za-z0-9_-]{1,64}$/,xf=300*1e3,jf=250,Uf=3;class zf{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=qc(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(vf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,je,Ze);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),wi(o,je)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Yt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(_f,{miniProgramId:r,...t}),s=xe(o,De,Ze);if(!me(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw J(`${De} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw J(`${De} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>wi(a,De)),...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=Yt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(bf,{miniProgramId:n,...t}),c=xe(a,Qe,Ze);if(!me(c))throw J(`${Qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:wi(c.entry,Qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Tf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,dt,Ze);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!me(o)||typeof o.deleted!="boolean")throw J(`${dt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Yt("info"),async()=>{const i=await this.request(Of,{miniProgramId:r,...t}),o=xe(i,Re,Ze);if(!me(o)||typeof o.key!="string"||!kf.test(o.key))throw J(`${Re} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw J(`${Re} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw J(`${Re} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw J(`${Re} 返回的 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=Yt(t,n),d=this.inflight.get(c);if(d)return d.promise;const l=this.accountGeneration,h=o?.generation,u=i().then(f=>(this.assertAccountGeneration(l),o&&s&&o.generation===h&&(r==="list"?s.size>=jf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+xf,value:f})),f)).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>=Uf)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)Ds(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Ds(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw zn(n)?n:Un(Ze)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw re("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw re("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Yt(t,r??Pf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw re("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Yc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Ze,assertUsable:()=>this.assertUsable()},t,r)}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(q(this.options.operationContext.signal),this.disposed)throw re("INVALID_STATE","Cloud capability 已释放")}}function Hf(e){return new zf(e)}function wi(e,t){if(!me(e))throw J(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw J(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw J(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw J(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw J(`${t} 返回的 score 必须是有限数字`);if(!me(e.extra))throw J(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw J(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function Ds(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Yt(...e){return JSON.stringify(e)}const Ff={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.delete.post",method:"POST",path:"/user_miniprogram/cloud/storage/delete",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key}},parse(e,t){return de(e,"云端存储删除接口响应异常")}},Ss={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.get.post",method:"POST",path:"/user_miniprogram/cloud/storage/get",body(e){return{key:e.key,runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return de(e,"云端存储读取接口响应异常")}},Ts={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.keys.post",method:"POST",path:"/user_miniprogram/cloud/storage/keys",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return de(e,"云端存储 key 列表接口响应异常")}},Vf={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.set.post",method:"POST",path:"/user_miniprogram/cloud/storage/set",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key,value:e.value,expected_version:e.expectedVersion,expected_revision:e.expectedRevision}},parse(e,t){return de(e,"云端存储写入接口响应异常")}},Xe="云端存储",Bf=3e4,Gf=128,Qf=500;class Yf{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=qc(t.account,r=>{this.observedUserId=r?.trim()||void 0,this.hasAccountObservation=!0,!(this.boundUserId===void 0||this.boundUserId===this.observedUserId)&&this.invalidateForAccountChange()}),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;cache=new Map;inflight=new Map;keyGenerations=new Map;queues=new Map;activeKeys=new Set;timers=new Map;blockedKeys=new Map;unfinished=new Set;disposed=!1;boundScope;boundUserId;observedUserId;hasAccountObservation=!1;unsubscribeAccountChange;requestGateContext;handleTerminalAbort=()=>this.dispose();async getItem(t){const r=this.accountGeneration;await this.requireCurrentUser(r),this.assertAccountGeneration(r);const n=[...this.unfinished].filter(s=>s.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,o=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),o.found?o.value:void 0)}setItem(t,r){return this.enqueue("set",t,r)}removeItem(t){return this.enqueue("remove",t,"")}async getKeys(){const t=this.accountGeneration;await this.requireCurrentUser(t),this.assertAccountGeneration(t);const r=xe(await this.request(Ts,{}),ut,Xe);if(this.assertAccountGeneration(t),!me(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw J("cloud.storage.getKeys 返回的 keys 必须是字符串数组");const n=new Set(r.keys??[]);for(const i of this.unfinished)i.kind==="set"?n.add(i.key):n.delete(i.key);return[...n]}async enqueue(t,r,n){this.assertUsable(),this.readMiniProgramId();const i=this.accountGeneration;return await this.requireCurrentUser(i),this.assertAccountGeneration(i),t==="set"&&this.blockedKeys.has(r)?Promise.reject(this.blockedKeys.get(r)):new Promise((o,s)=>{const a=this.queues.get(r)??[],c=a.at(-1);if(t==="set"&&c?.kind==="set"&&c.generation===this.accountGeneration&&c.readyAt>Date.now())c.value=n,c.waiters.push({resolve:o,reject:s});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?Qf:0),waiters:[{resolve:o,reject:s}]};a.push(d),this.unfinished.add(d)}this.queues.set(r,a),this.invalidateRead(r),this.drainKey(r)})}async drainKey(t){if(!this.activeKeys.has(t)){this.activeKeys.add(t);try{let r;for(;r=this.queues.get(t)?.[0];){const n=r.readyAt-Date.now();if(n>0){this.timers.has(t)||this.timers.set(t,setTimeout(()=>{this.timers.delete(t),this.drainKey(t)},n));break}this.queues.get(t).shift();try{if(await this.requireCurrentUser(r.generation),this.assertAccountGeneration(r.generation),r.kind==="remove"){const i=xe(await this.request(Ff,{key:t}),Ct,Xe);if(this.assertAccountGeneration(r.generation),!me(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw J("删除结果不合法");this.writeCache(t,{value:"",found:!1,version:0,revision:""}),this.blockedKeys.delete(t)}else{const i=await this.readStored(t,r.generation,!0);if(this.assertAccountGeneration(r.generation),!Number.isSafeInteger(i.version+1))throw J("云存储版本超出安全整数范围");const o=xe(await this.request(Vf,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Lt,Xe);if(this.assertAccountGeneration(r.generation),!me(o)||o.success!==!0)throw J("云存储写入结果不合法");const s=bs({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw J("写入版本凭证不匹配");this.writeCache(t,s)}this.finish(r)}catch(i){if(this.finish(r,i),r.generation===this.accountGeneration){this.cache.delete(t),this.blockedKeys.set(t,i);for(const o of this.queues.get(t)??[])this.finish(o,i);this.queues.delete(t)}}}}finally{this.activeKeys.delete(t),this.queues.get(t)?.length||this.queues.delete(t)}}}async readStored(t,r,n){this.assertAccountGeneration(r);const i=this.cache.get(t);if(i&&(n||i.expiresAt>Date.now()))return i.value;const o=this.inflight.get(t);if(o)return o;const s=this.keyGenerations.get(t)??0,a=this.request(Ss,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=bs(xe(c,vt,Xe));return(this.keyGenerations.get(t)??0)===s&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===a&&this.inflight.delete(t)});return this.inflight.set(t,a),a}writeCache(t,r){this.cache.delete(t),this.cache.size>=Gf&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+Bf,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ss.id,Ts.id])}finish(t,r){if(this.unfinished.delete(t)){t.generation===this.accountGeneration&&this.invalidateRead(t.key);for(const n of t.waiters)r===void 0?n.resolve():n.reject(r)}}dispose(){this.disposed||(this.disposed=!0,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.purge(re("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(re("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw zn(o)?o:Un(Xe)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),re("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),re("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw re("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw re("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw re("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw re("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await $(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw zn(s)?s:Un(Xe)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw re("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Yc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Xe,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(q(this.options.operationContext.signal),this.disposed)throw re("INVALID_STATE","Cloud capability 已释放")}}function qf(e){return new Yf(e)}function bs(e){if(!me(e))throw J("云存储读取结果必须是对象");const t=e.found??!1,r=e.value??"",n=e.version??0,i=e.revision??"";if(typeof t!="boolean"||typeof r!="string"||typeof n!="number"||!Number.isSafeInteger(n)||n<0||typeof i!="string")throw J("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw J("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const $f=/^[A-Za-z0-9_-]{1,64}$/,Os=20,Wf=100,_s=2048,Kf=/^[A-Za-z0-9_-]{1,128}$/,vs=16*1024,Jf=new RegExp("[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]");function Zf(e){const t=Hf(e),r=qf(e);return{handlers:{[je]:async i=>t.submit(Xf(i)),[De]:async i=>t.getList(eh(i)),[Qe]:async i=>t.getCurrentUserEntry(Ii(i,Qe)),[dt]:async i=>t.deleteCurrentUserEntry(Ii(i,dt)),[Re]:async i=>t.getInfo(Ii(i,Re)),[vt]:async i=>r.getItem(Ls(i,vt)),[Lt]:async i=>{const{key:o,value:s}=th(i);return r.setItem(o,s)},[Ct]:async i=>r.removeItem(Ls(i,Ct)),[ut]:async i=>(rh(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function Xf(e){const t=Ft(e,je,!1);if(Vt(t,["key","score","extra"],je),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw ge("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...xo(t.key,je),score:t.score,...t.extra===void 0?{}:{extra:nh(t.extra)}}}function eh(e){if(e===void 0)return{limit:Os};const t=Ft(e,De,!0);Vt(t,["key","limit","cursor"],De);const r=t.limit===void 0?Os:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Wf)throw ge("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...xo(t.key,De),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Ii(e,t){if(e===void 0)return{};const r=Ft(e,t,!0);return Vt(r,["key"],t),xo(r.key,t)}function Ls(e,t){const r=Ft(e,t,!1);return Vt(r,["key"],t),$c(r.key,t)}function th(e){const t=Lt,r=Ft(e,t,!1);Vt(r,["key","value"],t);const n=$c(r.key,t);if(typeof r.value!="string")throw ge("INVALID_PARAMS",`${t} value 必须是字符串`);if(Jf.test(r.value))throw ge("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>vs)throw ge("INVALID_PARAMS",`${t} value 不能超过 ${vs} 字节`);return{key:n,value:r.value}}function rh(e){const t=Ft(e,ut,!0);Vt(t,[],ut)}function $c(e,t){if(typeof e!="string"||!Kf.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Ft(e,t,r){if(e===void 0&&r)return{};if(!Wc(e))throw ge("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Vt(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ge("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function xo(e,t){if(e===void 0)return{};if(typeof e!="string"||!$f.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function nh(e){if(!Wc(e))throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>_s)throw ge("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${_s} 字节`);return e}function Wc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e,t){return{code:e,message:t}}const ih=new Set(["stdio","attachments","notifications"]),Kc=new Set(["windows-x64","macos-arm64"]),oh=new Set(["unsigned","valid","invalid","unknown"]),sh=/^[a-f0-9]{64}$/,ah=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),ch=new Set(Sc),dh=new Set([...Sc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Jc=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 uh(e){const t=async(n,i,o,s)=>{const a=lh(n);try{Ce(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ce(i.signal),c}catch(c){throw ao(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw y("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>fh(d,i)).catch(d=>{throw ao(d)});Ce(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ce(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Yn]:(n,i)=>t(n,i,async(o,s)=>so(await e.companion.getInfo(o,s),o)),[qn]:(n,i)=>t(n,i,async(o,s)=>Cs(await e.companion.getPreparationStatus(o,s))),[$n]:(n,i)=>t(n,i,async(o,s)=>{const a=Cs(await e.companion.getPreparationStatus(o,s));return Ce(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Ce(i.signal),so(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Xc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Wn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Kn]:(n,i)=>t(n,i,async(o,s)=>Rs(await e.companion.getActiveSession(o,s),o)),[Jn]:(n,i)=>t(n,i,async(o,s)=>{const a=Rs(await e.companion.getActiveSession(o,s),o);return Ce(i.signal),a||(await r("launch",o,i),Ce(i.signal),ed(await e.companion.launch(o,s),o))}),[Zn]:(n,i)=>It(n,i,e,"write"),[Xn]:(n,i)=>It(n,i,e,"closeStdin"),[ei]:(n,i)=>It(n,i,e,"terminate"),[ti]:(n,i)=>It(n,i,e,"ackOutput"),[ri]:async(n,i)=>{const o=await It(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[ni]:(n,i)=>It(n,i,e,"showNotification")}}function lh(e){if(!H(e)||typeof e.alias!="string"||!Qu.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ce(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function It(e,t,r,n){if(!H(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{Ce(t.signal);const i=await r.companion[n](hh(e,n),{...r.operationContext,signal:t.signal});return Ce(t.signal),i}catch(i){throw ao(i)}}function be(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Zc(e){return!Array.isArray(e)||e.some(t=>!ih.has(t))?be():Object.freeze([...new Set(e)])}function so(e,t){return!H(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Kc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!oh.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?be():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Zc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function fh(e,t){const r=so(e,t);return!H(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!sh.test(e.sha256)?be():Object.freeze({...r,sha256:e.sha256})}function Xc(e){return H(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}):be():be()}function Cs(e){return H(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Xc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&H(e.error)&&typeof e.error.code=="string"&&ch.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:Jc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):be():be()}function ed(e,t){return!H(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Kc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?be():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Zc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Rs(e,t){return e===void 0?void 0:ed(e,t)}function hh(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Mc(r.data))throw y("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 y("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw y("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw y("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function mh(e){return!H(e)||!ah.has(String(e.reason))?be():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):be():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?be():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function gh(e){if(!H(e)||!H(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||!Mc(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:mh(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 ao(e,t){return H(e)&&typeof e.code=="string"&&dh.has(e.code)?y(e.code,Jc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&H(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Ps=5e3,ks=1e4;function fe(e){throw{code:"INVALID_PARAMS",message:e}}function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function td(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&fe(`${r} 不支持字段: ${n.join(", ")}`)}function ph(e){if(e===void 0)return{intensity:"light",delay:0};if(!jo(e))return fe("device.vibrate 参数必须是对象");td(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return fe("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Ps?fe(`device.vibrate delay 必须是 0-${Ps} 的整数毫秒`):{intensity:r,delay:n}}function yh(e){return jo(e)?(td(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?fe("device.setClipboard text 必须是非空字符串"):e.text.length>ks?fe(`device.setClipboard text 不能超过 ${ks} 字符`):{text:e.text}):fe("device.setClipboard 参数必须是对象")}function Eh(e){return typeof e=="string"?e.trim()?e:fe("device.executeProtocol 协议字符串不能为空"):jo(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?fe("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(co(e,new Set),e):fe("device.executeProtocol 参数必须是协议字符串或协议对象")}function co(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||fe("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":fe("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":fe(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&fe("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)co(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&fe("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))co(i,t);t.delete(r)}function wh(e){return{[Ln]:async t=>{q(e.operationContext.signal),await $(()=>e.presentation.vibrate(ph(t),e.operationContext),e.operationContext.signal)},[Cn]:async t=>{q(e.operationContext.signal),await $(()=>e.presentation.setClipboard(yh(t),e.operationContext),e.operationContext.signal)},[Rn]:async(t,r)=>{const n=lt(e.operationContext,r.signal);q(n.signal);const i=Eh(t);await $(()=>e.protocol.invoke(i,n),n.signal)}}}const Ih=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"]),Mh={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 Ir(e){const t=Uo(e),r=t&&Ih.has(t)?y(t,Mh[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function ke(e){try{return e()}catch(t){throw Ir(t)}}function Uo(e){try{if(!H(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function rd(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):uo,remove:o?s=>e.remove(s):id,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):uo,stat:s=>e.stat(s)})}function nd(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=>rd(e.file(a),n,{allowRemove:o}),directory:a=>nd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):uo,remove:s?(a,c)=>e.remove(a,c):id,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function uo(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function id(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const xs=1024;class Ah{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 zr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=ke(()=>{if(!Array.isArray(t))throw y("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw y("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>xs)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>zr(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!ii(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Dh(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Mr(r.relativePath),o=this.prepareFile(ke(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Sh(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==="."?".":Mr(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:ke(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Hs(t),zr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),ke(()=>{if(!Array.isArray(r))throw y("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw y("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return ke(()=>{if(H(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return zr(n.handle,js(t.ref,n.handle.name))}if(H(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Us(n.handle,Nh(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=vr(r),i=this.prepareFile(ke(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:js(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return ke(()=>{Hs(t);const i=n??t.mode;return zs(t.mode,i),{handle:rd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return ke(()=>{Oh(t,i);const o=n??t.mode;return zs(t.mode,o),{handle:nd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>xs)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Th();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw y("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!bh(t))throw y("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw y("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Te("files.sandbox");return this.prepareDirectory(ke(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Te("files")}}function Mr(e){if(!Co(e))throw y("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function vr(e,t="文件名"){const r=Mr(e);if(r.includes("/"))throw y("INVALID_PARAMS",`${t} 只能是 basename`);return r}function js(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Mr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Nh(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Mr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function zr(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 zs(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Dh(e){return ii(e)||od(),e}function Sh(e){return Ic(e)||od(),e}function od(){throw y("INVALID_PARAMS","文件引用不合法")}function Th(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw y("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function bh(e){return/^[0-9a-f]{32}$/.test(e)}function Hs(e){if(!H(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 y("FILE_IO_FAILED","Host 返回了无效 File handle");vr(e.name,"Host File name")}function Oh(e,t=!1){if(!H(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 y("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw y("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&vr(e.name,"Host Directory name")}const Fs=1e3,_h=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function vh(e){const t=r=>lt(e.operationContext,r.signal);return{files:{[wn]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Lh(r),s=await ye(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[In]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Ch(r),s=await ye(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[Mn]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Rh(r).suggestedName,s=t(n);if(!i.saveFile)throw Te("files.saveFile");const a=await ye(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[hr]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Mt(o.mode),await ye(()=>o.create(Vs(i),t(n)))},[mr]:async(r,n)=>{const i=Ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Mt(o.handle.mode),!o.handle.remove)throw Te(mr);await ye(()=>o.handle.remove(t(n)))},[An]:async(r,n)=>{const i=Ie(r);return Bs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!H(o)||o.kind!=="file")throw Qs()})},[gr]:async(r,n)=>{const i=Ie(r),o=Gs(await ye(()=>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 y("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Nn]:async(r,n)=>{const i=Ie(r,["content"]);typeof i.content!="string"&&Ae("content 必须是字符串");const o=e.registry.resolveFile(i.target);Mt(o.mode),await ye(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[pr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).read(t(n)));return Gs(o)},[Dn]:async(r,n)=>{const i=Ie(r,["content"]),o=e.registry.resolveFile(i.target);Mt(o.mode),await ye(()=>o.write(kh(i.content),t(n)))},[yr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).stat(t(n)));return xh(o)}},directory:{[Sn]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Mt(o.mode),await ye(()=>o.create(Vs(i),t(n)))},[Er]:async(r,n)=>{const i=Ie(r,["recursive"]);if(H(i.target)&&i.target.relativePath===".")throw y("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Mt(o.handle.mode),!o.handle.remove)throw Te(Er);await ye(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Hn(i.recursive,"recursive")},t(n)))},[Tn]:async(r,n)=>{const i=Ie(r);return Bs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!H(o)||o.kind!=="directory")throw Qs()})},[bn]:async(r,n)=>{const i=Ie(r,["limit"]),o=Ph(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ye(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Lh(e){if(e===void 0)return{mode:"read",multiple:!1};H(e)||Ae("pickFiles 参数必须是对象"),si(e,["mode","accept","multiple"]);const t=sd(e.mode,"read"),r=e.multiple===void 0?!1:Hn(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)))&&Ae("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Ch(e){return e===void 0?{mode:"read"}:(H(e)||Ae("pickDirectory 参数必须是对象"),si(e,["mode"]),{mode:sd(e.mode,"read")})}function Rh(e){return H(e)||Ae("saveFile 参数必须是对象"),si(e,["suggestedName"]),{suggestedName:vr(e.suggestedName,"suggestedName")}}function Ie(e,t=[]){return(!H(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Ae("文件操作参数必须包含 target"),si(e,["target",...t]),e}function Vs(e){return{recursive:e.recursive===void 0?!1:Hn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Hn(e.exclusive,"exclusive")}}function sd(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Ae("mode 必须是 read 或 readwrite"),e)}function Hn(e,t){return typeof e!="boolean"&&Ae(`${t} 必须是布尔值`),e}function Ph(e){if(e===void 0)return Fs;if((!Number.isSafeInteger(e)||e<=0)&&Ae("limit 必须是正整数"),e>Fs)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function si(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Ae(`不支持字段: ${r.join(", ")}`)}function Mt(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Mi(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ai(e){if(!e)throw Te("files.external");return e}async function Bs(e){try{return await e(),!0}catch(t){if(_h.has(Uo(t)??""))return!1;throw Ir(t)}}async function ye(e){try{return await e()}catch(t){throw Ir(t)}}function kh(e){return e instanceof Uint8Array||Ae("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Ae("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Gs(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Qs(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function xh(e){if(!H(e)||e.kind!=="file"||!jh(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Uh(e[t]))throw y("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 jh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Uh(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Ae(e){throw y("INVALID_PARAMS",e)}const Hr=4294967296;function zh(e){const t=new Hh;return t.write(e),t.finish()}class Hh{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<Hr?(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=Fh(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<Hr)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/Hr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Hr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Fh(e){const t=new Uint8Array(Vh(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 Vh(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 ad(e){lo(e);const t=zh(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 lo(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)lo(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");lo(s,t+1,r)}r.delete(e)}const Bh=["pc","console","mobile"],Gh=["game","wiki"];function Fn(e){throw{code:"INVALID_PARAMS",message:e}}function Qh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e,t){return typeof e!="string"||!e.trim()?Fn(t):e.trim()}function Ys(e,t,r){return typeof e!="string"||!t.includes(e)?Fn(r):e}function Yh(e){const t={target:"game_detail",appId:qe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Ys(e.gameType,Bh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Ys(e.page,Gh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=qe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=qe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function qh(e){return{target:"user_detail",userId:qe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function $h(e){const t={target:"post_detail",linkId:qe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=qe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=qe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Wh(e){const t={target:"mini_program",miniProgramId:qe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Kh(e){return Qh(e)?e.target==="game_detail"?Yh(e):e.target==="user_detail"?qh(e):e.target==="post_detail"?$h(e):e.target==="mini_program"?Wh(e):Fn("navigation.openAppPage target 不支持"):Fn("navigation.openAppPage options 必须是对象")}function Jh(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 Zh(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Xh(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 em(e){const t=e;return t.target==="game_detail"?Jh(t):t.target==="user_detail"?Zh(t):Xh(t)}const tm="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",rm="data-hb-sdk-fullscreen-exit",nm=3e3,im=2e3,qs="var(--white-70a,rgba(255,255,255,.7))",$s="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function om(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(rm,""),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 ${qs}`,`box-shadow:${$s}`,"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=tm,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,d;function l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){o||(t.style.width=l())}function u(){d?.cancel(),d=void 0}function f(T=im){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=l(),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")},T)}function w(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=qs,t.style.boxShadow=$s,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),f()}async function I(){if(!(s||a)){if(!o){w();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||w()}}}return t.addEventListener("click",I),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=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"})),f(nm),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",I),window.removeEventListener("resize",h),t.remove()}}}const cd=1e4;function dd(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()},cd);return{signal:t.signal,async run(o){try{return await $(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function ud(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 Ni(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Fr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function sm(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??=om(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,f){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in f)u.controller.abort();else if(r={options:u.options,result:f.result},n=u.options,a(u.options),e.onApplied?.(u.options),f.result.supported&&!Ni(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const w of u.subscribers)w.dispose(),"error"in f?w.reject(f.error):w.resolve(f.result);u.subscribers.clear()}}function d(){t&&c(t,{error:Fr()})}function l(u,f){return new Promise((w,I)=>{const T=()=>{u.subscribers.delete(A),A.dispose(),I(Fr()),u.subscribers.size===0&&c(u,{error:Fr()})},A={resolve:w,reject:I,dispose:()=>f?.removeEventListener("abort",T)};u.subscribers.add(A),f?.addEventListener("abort",T,{once:!0}),f?.aborted&&T()})}const h={async apply(u,f,w="api"){if(q(e.operationContext.signal),f?.aborted)throw Fr();const I=ud(u),T=t?.options??n,A={mode:I.orientation??T.mode,hideCapsule:I.fullscreen??T.hideCapsule};A.mode==="landscape"&&(A.hideCapsule=!0);const _=e.presentation.applyOrientation;if(!_)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Ni(t.options,A))return l(t,f);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&Ni(r.options,A))return r.result;r=void 0;const D={options:A,source:w,controller:new AbortController,subscribers:new Set};t=D;const L=l(D,f);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),f||(D.timer=setTimeout(()=>{c(D,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},cd)),$(()=>_.call(e.presentation,A,{...e.operationContext,signal:D.controller.signal}),D.controller.signal).then(z=>c(D,{result:z??{supported:!0}}),z=>c(D,{error:z})),L},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return h}function ld(e){throw{code:"INVALID_PARAMS",message:e}}function Ws(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&ld(`${t} 不支持参数`)}function am(e){return{[Pn]:async t=>{q(e.operationContext.signal),Ws(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[kn]:async t=>{q(e.operationContext.signal),Ws(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[xn]:async(t,r)=>{const n=lt(e.operationContext,r?.signal);q(n.signal);const i=Kh(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=ad(i.extra)}catch{ld("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=dd(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}q(n.signal),await $(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await $(()=>e.presentation.openAppPage(em(i),n),n.signal)}}}const cm=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),dm=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),um=new Set(["range","if-range","a-im"]),lm=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"]),fm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Vr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class hm{constructor(t){this.signal=t}phase="initial";transition(t){if(Vr[t]<=Vr[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Vr[this.phase]<Vr.committed&&this.signal.aborted)throw hd()}normalizeHostError(t,r){return this.throwIfCancelled(),Ho(t,r,this.signal)}}async function mm(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Te("network.download");const o=lt(r.operationContext,t.signal),s=new hm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Em(e,i,o)}catch(l){throw s.normalizeHostError(l,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(l){throw s.normalizeHostError(l,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const l=Im(c);Mm(c,l);const h=Am(c.status,l);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=wm(e,a,l,i);let f=0;const w=pm(h.expectedBytes,e.maxBytes);Si(t,Di(0,h));const I={...o,onProgress(_){!Number.isSafeInteger(_)||_<f||w!==void 0&&_>w||(f=_,Si(t,Di(f,h)))}};s.transition("transfer"),d=!0;let T;try{T=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},I)}catch(_){throw s.normalizeHostError(_,"transfer")}s.transition("committed"),f=gm(T,h,f,e.maxBytes),Si(t,Di(f,h));const A=i.describeFile(u.handle,u.ref);return s.transition("completed"),A}finally{d||ym(n.network,c.body)}}function gm(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 pm(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function ym(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Em(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return fo(i.handle.mode),await _m(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return fo(n.handle.mode),await vm(n.handle,r),{kind:"directory",...n}}function wm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Dm(e,r),o=n.deriveFile(t,i);return fo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Im(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 y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!H(e.headers))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!cm.has(r)||!Array.isArray(n)||n.length===0)throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Mm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw y("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Om(t,dm)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Am(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw y("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw y("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=Nm(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 Nm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Di(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Si(e,t){try{e.postProgress(t)}catch{}}function Dm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Sm(i);if(o&&Kr(o))return o}for(const i of r){const o=Tm(i);if(o&&Kr(o))return o}if(e.suggestedName!==void 0)return zo(e.suggestedName);const n=bm(e.url);return n&&Kr(n)?n:"download.bin"}function Sm(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 Tm(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 bm(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function zo(e){try{vr(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Kr(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Kr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||fm.test(e))}function Om(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function _m(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw fd()}catch(r){throw Ho(r,"file",t.signal)}}async function vm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw fd()}catch(r){throw Ho(r,"file",t.signal)}}function fo(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const Lm={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 Ho(e,t,r){if(r.aborted)return hd();const n=Cm(e);if(n&&lm.has(n)){const o=y(n,Lm[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?y("DOWNLOAD_TIMEOUT","下载网络请求超时"):y("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?y("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):y("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Cm(e){return H(e)&&typeof e.code=="string"?e.code:void 0}function fd(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function hd(){return y("DOWNLOAD_CANCELLED","下载已取消")}function Rm(e){if(!e)return;const t=Object.keys(e).find(r=>um.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Ks={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Pm(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Te("network.upload");const o=lt(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw y("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(u){throw s(),Ir(u)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw y("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw y("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const h=u=>{l||o.signal.aborted||!Number.isSafeInteger(u)||u<d||u>c.size||(d=u,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:u,...f}=e,w=await n.upload(a,{...f,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:h});if(l=!0,!Number.isSafeInteger(w.uploadedBytes)||w.uploadedBytes<d||w.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(w.status>=200&&w.status<300&&w.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:w.uploadedBytes,total:c.size,lengthComputable:!0}),w}catch(u){l=!0;const f=Uo(u);throw f&&Ks[f]?y(f,Ks[f]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):f?.startsWith("FILE_")||f?.startsWith("DIRECTORY_")?Ir(u):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Fo="withCredentials",km=new Set(["url","method","params","data","headers","timeout",Fo]),xm=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Fo]),jm=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Js=3e4,ho=2*1024*1024,Um=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,md=/[\u0000-\u0008\u000A-\u001F\u007F]/,zm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Hm="network.request 不支持 multipart/form-data,请使用专用上传能力";function Fm(e){const t=Vm(e.runtimePermissions),r=rg(e.allowedHttpOrigins);return{[En]:async(n,i)=>{const o=Gm(n,{permission:t,allowedHttpOrigins:r}),s=await Pm(o,i,e),{uploadedBytes:a,...c}=s;return Xs(c)},[yn]:async(n,i)=>{const o=Qm(n,{permission:t,allowedHttpOrigins:r});return mm(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[pn]:async(n,i)=>{const o=lt(e.operationContext,i?.signal);q(o.signal);const s=Bm(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw ig(c)?c:og(c,"REQUEST_UNSUPPORTED")?V("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):V("REQUEST_FAILED","网络请求失败")}return Xs(a)}}}function Vm(e){const t=Se(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Bm(e,t){const r=xt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!km.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);gd(r,"network.request");const i=Vo(r,t,"network.request"),o=qm(r.method),s=r.data;s!==void 0&&Km(s),Zm(i.headers,s);const a=Xm(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 Gm(e,t){const r=xt(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(l=>!n.has(l)))throw V("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Vo(r,t,"network.upload");if(i.official)throw V("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!ii(r.from))throw V("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw V("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw V("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(l=>r[l]!==void 0))throw V("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw V("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Zs(r.fieldName),c=r.fields===void 0?void 0:xt(r.fields,"fields 必须是字符串字典");for(const[l,h]of Object.entries(c??{}))if(Zs(l),typeof h!="string"||l===a)throw V("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw V("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||md.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw V("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ho)throw V("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:zo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Zs(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw V("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Qm(e,t){const r=xt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!xm.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);gd(r,"network.download");const i=Vo(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","network.download timeout 必须是有限正数");Rm(i.headers);const o=ii(r.to),s=Ic(r.to);if(!o&&!s)throw V("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw V("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw V("INVALID_PARAMS","suggestedName 必须是字符串");a=zo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw V("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("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 Vo(e,t,r){const n=Ym(e.url,t.allowedHttpOrigins,r),i=Tl(n);if(i&&!t.permission.useOfficialDomain)throw V("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Sl(n.pathname,i))throw V("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...xt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:$m(e.headers,r),timeout:Wm(e.timeout,r)}}function Ym(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw V("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw V("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function qm(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!jm.has(t))throw V("INVALID_PARAMS","network.request method 不合法");return t}function $m(e,t="network.request"){const r=xt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Um.test(s)||typeof o!="string"||md.test(o))throw V("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(bl(s))throw V("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function gd(e,t){const r=e[Fo];if(r!==void 0&&typeof r!="boolean")throw V("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Wm(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw V("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Js)throw V("INVALID_PARAMS",`${t} timeout 不能超过 ${Js}ms`);return e}}function Km(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw V("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Jm(e)>ho)throw V("INVALID_PARAMS",`network.request data 不能超过 ${ho} 字节`)}function Jm(e){if(typeof e=="string")return Ti(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Ti(e.toString());try{const t=JSON.stringify(e);return t?Ti(t):0}catch{throw V("INVALID_PARAMS","network.request data 必须可序列化")}}function Zm(e,t){const r=pd(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 V("INVALID_PARAMS",Hm)}function Xm(e,t,r){if(t===void 0)return;const n=pd(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)||tg(t))?"form":eg(t)?"json":void 0}function pd(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function eg(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function tg(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function rg(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&&ng(n.hostname)&&t.add(n.origin)}catch{}return t}function ng(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 Xs(e){return Object.keys(e.headers).some(ea)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!ea(t)))}:e}function ea(e){const t=e.trim().toLowerCase();return zm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ig(e){return e instanceof Error&&e.name==="AbortError"}function og(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function xt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw V("INVALID_PARAMS",t);return e}function Ti(e){return new TextEncoder().encode(e).length}function V(e,t){return{code:e,message:t}}function sg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ag(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 cg(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=ag(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function dg(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 yd(e,t){if(e==null)return{};if(!sg(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=cg(e.topicIds),n=dg(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 ug(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function lg(e){try{if(ug(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ce(e){throw{code:"INVALID_PARAMS",message:e}}function Lr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mo(e,t){return typeof e!="string"||!e.trim()?ce(t):e}function fg(e,t){const r=mo(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ce(t):r}catch{return ce(t)}}function hg(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Ed(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 mg(e,t){if(!Lr(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&&!hg(r))return ce("share.showShareMenu channel 不合法");const n=wd(e.extra,"share.showShareMenu");return{title:mo(e.title,"share.showShareMenu title 必须是非空字符串"),description:mo(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Ed(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:fg(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function wd(e,t){if(e!==void 0)try{return ad(e)}catch{return ce(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Id(e,t){return e.invalidMessage&&await $(()=>lg(t.environment),t.operationContext.signal)?ce(e.invalidMessage):e.post}function ta(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function gg(e){const t=e.getViewportMetrics();return{left:0,top:0,width:ta(t.windowWidth,0),height:ta(t.windowHeight,0)}}function go(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ce(t):r}function ra(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ce(t):r}function pg(e){return Lr(e)?{left:go(e.left,"share.screenshot rect.left 必须是非负数字"),top:go(e.top,"share.screenshot rect.top 必须是非负数字"),width:ra(e.width,"share.screenshot rect.width 必须是正数"),height:ra(e.height,"share.screenshot rect.height 必须是正数")}:ce("share.screenshot rect 必须是对象")}function yg(e,t){if(e!=null&&!Lr(e))return ce("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ce("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?ce("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?gg(t):pg(r.rect),...r.delay===void 0?{}:{delay:go(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Eg(e,t){q(t.operationContext.signal);const r=mg(e,t);let n=yd(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Id(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function wg(e,t){if(q(t.operationContext.signal),e!==void 0&&!Lr(e))return ce("share.copyLink 参数必须是对象");const r=wd(e?.extra,"share.copyLink"),n=Ed(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Ig(e,t,r){q(t.operationContext.signal);const n=yd(Lr(e)?e.post:void 0,{method:"share.screenshot"}),i=await Id(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Mg(),{watermarkTheme:a,...c}=r;let d=!1,l,h;try{d=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),l=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),h={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(f){h={status:"rejected",error:f}}finally{l?.()}const u=d?await Ag(t.presentation,s,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(u)throw u;return h.value}function Mg(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Ag(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Ng(e){let t=Promise.resolve();return{[ln]:(r,n)=>wg(r,e),[fn]:(r,n)=>Eg(r,e),[hn]:async(r,n)=>{const i=lt(e.operationContext,n.signal);q(i.signal);const o=yg(r,e.presentation),s=t.then(()=>Ig(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),$(()=>s,i.signal)}}}const na=new WeakMap;function Md(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return rl(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Oc(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Ad(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(c=>{throw r=void 0,c}),i=async(c,d)=>{const l=await n();let h=na.get(t);h||(h=new Map,na.set(t,h));const u=h.get(l)??Promise.resolve(),f=async()=>(q(c.signal,{preserveReason:!0}),d(l)),w=u.catch(()=>{}).then(()=>e.lock?e.lock(l,f):f());h.set(l,w);try{return await w}finally{h.get(l)===w&&h.delete(l)}},o=async(c,d,l=!1)=>{const h=gt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(w=>w.key.startsWith(h)&&w.value!=="").map(w=>w.key.slice(h.length)))];const u=await e.storage.getRaw(xr(c),d);if((u===void 0||u==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let f;try{f=u?JSON.parse(u):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(f)||f.length>is||f.some(w=>typeof w!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(w)))throw new Error("本地数据索引异常");return[...new Set(f)]},s=async(c,d)=>{if(e.diagnostics){const u=gt(c,"");return(await e.diagnostics.listRaw(d)).filter(f=>f.key.startsWith(u)&&f.value!=="").map(f=>({...f,key:f.key.slice(u.length)}))}const l=[],h=await o(c,d);for(let u=0;u<h.length;u+=16){q(d.signal,{preserveReason:!0});const f=await Promise.all(h.slice(u,u+16).map(async w=>{const I=await e.storage.getRaw(gt(c,w),d);return I!==void 0&&I!==""?{area:"local",key:w,value:I}:void 0}));for(const w of f)w&&l.push(w)}return l},a=c=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(c,d){return a(c),i(d,l=>e.storage.getRaw(gt(l,c),d))},set(c,d,l){return a(c),i(l,async h=>{const u=await o(h,l,!0);if(!u.includes(c)&&u.length>=is)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const f=[...new Set([...u,c])];await e.storage.setRaw(xr(h),JSON.stringify(f),l)}q(l.signal,{preserveReason:!0}),await e.storage.setRaw(gt(h,c),d,l),q(l.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const l=await o(d,c);e.diagnostics||await e.storage.setRaw(xr(d),JSON.stringify(l),c);for(let h=0;h<l.length;h+=16){q(c.signal,{preserveReason:!0});const f=(await Promise.allSettled(l.slice(h,h+16).map(w=>e.storage.setRaw(gt(d,w),"",c)))).find(w=>w.status==="rejected");if(f)throw f.reason}q(c.signal,{preserveReason:!0}),await e.storage.setRaw(xr(d),"[]",c)})}}}function Dg(e,t){return typeof navigator<"u"&&navigator.locks?new Promise((r,n)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(r,n)).catch(n)}):t()}const Sg=128,Tg=/^[A-Za-z0-9_-]+$/;function bg(e){const t=e.scopedStorage??Ad({storage:e.storage,resolveScope:()=>Md({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[lr]:async n=>{q(e.operationContext.signal);const i=ia(n,lr,e.storageLimits?.maxKeyLength),o=await $(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:oa(o)}},[fr]:async n=>{q(e.operationContext.signal);const i=Nd(n,"storage.setStorage 参数必须是对象"),o=ia(i,fr,e.storageLimits?.maxKeyLength),s=Og(i.data,e.storageLimits?.maxValueBytes);await $(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(q(e.operationContext.signal),(await $(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?st("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:oa(o),serializedValue:o,bytes:Dd(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function ia(e,t,r=Sg){const i=Nd(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw st("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Tg.test(i))throw st("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Og(e,t){let r;try{r=JSON.stringify(e)}catch{throw st("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw st("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Dd(r)>t)throw st("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function oa(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Nd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw st("INVALID_PARAMS",t);return e}function Dd(e){return new TextEncoder().encode(e).length}function st(e,t){return{code:e,message:t}}const sa=120;function Be(e){throw{code:"INVALID_PARAMS",message:e}}function Bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Be(`${r} 不支持字段: ${n.join(", ")}`)}function _g(e){if(!Bo(e))return Be("ui.showToast 参数必须是对象");if(Sd(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>sa)return Be(`ui.showToast message 不能超过 ${sa} 字符`);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 vg(e){return e===void 0?{dismissible:!1}:Bo(e)?(Sd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Be("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Be("ui.showLoading 参数必须是对象")}function Lg(e){e!==void 0&&(!Bo(e)||Object.keys(e).length)&&Be("ui.hideLoading 不支持参数")}function Cg(e){return{[On]:async t=>{q(e.operationContext.signal),await $(()=>e.presentation.showToast(_g(t),e.operationContext),e.operationContext.signal)},[_n]:async t=>{q(e.operationContext.signal),await $(()=>e.presentation.showLoading(vg(t),e.operationContext),e.operationContext.signal)},[vn]:async t=>{q(e.operationContext.signal),Lg(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Rg={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},Pg=3e4;function kg(e,t,r={}){const n=r.ttlMs??Pg,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let h;try{h=await oi(e,Rg,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof ae?y("REQUEST_UNSUPPORTED",u.message):u instanceof _r?y("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof kt?y("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Pt?i&&(u.status===403||u.status===429)?y("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):y("REQUEST_FAILED",u.message):jg(u)?u:y("REQUEST_FAILED","user home_v2 请求失败")}return xg(h,"user home_v2")}function l(h){const u=Date.now();if(a?.userId===h&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===h&&c.generation===s)return c.promise;const f=s,w=d().then(I=>(s===f&&(a={userId:h,value:I,expiresAt:Date.now()+n}),I)).finally(()=>{c?.promise===w&&(c=void 0)});return c={userId:h,generation:f,promise:w},w}return{get:l,clear(){s+=1,a=void 0,c=void 0}}}function xg(e,t){if(!H(e))throw y("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 y(n,r)}if(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function jg(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Ug={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 de(e,"Steam 游戏库接口响应异常")}};function zg(e,t=no){const r=_l({version:"1",validate:Fg}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):no,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 aa(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 Hg(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 Fg(e){if(!H(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(bi(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw tt();for(const t of e.gameList){if(!H(t)||!po(t.appid)||!po(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw tt();for(const r of["image","icon"])ca(t,r);for(const r of["playtimeForever","playtime2Weeks"])bi(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw tt();if(t.price!==void 0){if(!H(t.price))throw tt();for(const r of["current","initial","deadlineDate"])ca(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])bi(t.price,r)}}return e}function po(e){return typeof e=="number"&&Number.isFinite(e)}function bi(e,t){if(e[t]!==void 0&&!po(e[t]))throw tt()}function ca(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw tt()}function tt(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Td=20,Vg=100,Bg=128,bd=0,Od="weeks",Gg=100,Qg=new Set(["weeks","all","achieved"]);function Yg(){return{nickname:"",avatar:""}}function qg(e){const t=kg(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Lc(),i=zg(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(m,p){const g=JSON.stringify([m,p]);return(!o||o.key!==g)&&(o={key:g,scope:n.createScope(p,n.createScope(m))}),o.scope}function d(){const m=o;o=void 0,m&&n.invalidateScope(m.scope).catch(()=>{}),s.clear()}const l=Vc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Hc))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,f=!1;const w=e.account.onChange(()=>{u+=1,t.clear(),l.invalidate(),d()}),I=e.authorization.onEvent((m,p)=>{m==="user_info_authorization_change"&&Object.values(p).some(g=>g==="denied")&&(u+=1,t.clear(),l.invalidate(),d(),a=a.then(async()=>{if(f)return;const g=await e.account.getCurrentUserId(e.operationContext);typeof g=="string"&&g.trim()&&await n.invalidateScope(c(A(),g.trim()))}).catch(()=>{}))});function T(){if(f||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function A(){const m=e.identity.get()?.miniProgramId?.trim();if(!m)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return m}async function _(){T(),await a,T();let m;try{m=await e.account.getCurrentUserId(e.operationContext)}catch(p){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ua(p)?p:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof m=="string"&&m.trim()?m.trim():void 0}async function D(m,p){const g=await _();if(u!==p||g!==m)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function L(m,p,g=e.operationContext.signal){try{return await oi(e.network,m,p,{...e.operationContext,signal:g,credentials:"heybox-session",...h?{gate:h}:{}})}catch(E){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):E instanceof ae?y("REQUEST_UNSUPPORTED",E.message):E instanceof _r?y("INVALID_RESPONSE","用户接口响应不合法"):E instanceof kt?y("REQUEST_FAILED","用户请求失败"):E instanceof Pt?r&&(E.status===403||E.status===429)?y("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:E.status,...E.retryAfterMs===void 0?{}:{retryAfterMs:E.retryAfterMs}}):y("REQUEST_FAILED",E.message):ua(E)?E:y("REQUEST_FAILED","用户请求失败")}}async function z(){A();const m=u,p=await _();if(!p)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[g,E]=await Promise.all([e.authorization.getOrCreateLocalIdentity(p),v(p).catch(()=>Yg())]);return await D(p,m),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:g.appUserId,profile:E,...g.steamId?{steam_id:g.steamId}:{}}}}function v(m){return l.read(m,()=>L(Fc,void 0).then(p=>{const g=da(p,"账号基础信息");if(g.display_username!==void 0&&typeof g.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(g.display_avatar!==void 0&&typeof g.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:g.display_username??"",avatar:g.display_avatar??""}}))}async function N(m){const p=$g(m),g=A(),E=u,M=await _();if(!M)return d(),{isLogin:!1,isBound:!1,data:null};const S=await t.get(M);await D(M,E);const R=Go(S.steam_id_info);if(Object.keys(R).length===0)return await n.invalidateScope(c(g,M)).catch(()=>{}),await D(M,E),s.delete(JSON.stringify([g,M])),{isLogin:!0,isBound:!1,data:null};const F=JSON.stringify([g,M]),P=c(g,M),O=aa({...p,steamId:void 0},R),C=_d(R.personal_infomation_open??R.personal_information_open),b=JSON.stringify([O??null,C??null]),x=s.get(F);x&&x.identity!==b&&(await n.invalidateScope(P).catch(()=>{}),await D(M,E));const j={identity:b,scope:n.createScope(b,P)};s.set(F,j);const U=aa(p,R),B=U?i.persistent:i.unresolved,G=n.createScope(U??"unresolved",j.scope),Y=async()=>{if(await D(M,E),A()!==g||s.get(F)?.identity!==b)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ne=await B.read({scope:G,key:Hg({miniProgramId:g,userId:M,effectiveSteamId:U,personalInformationOpen:C,query:p}),signal:e.operationContext.signal,load:async te=>{const ee=await L(Ug,{userId:M,...p,personalInformationOpen:C},te);return await Y(),Xg(da(ee,"Steam 游戏库"),p)}}).catch(async te=>{throw await Y(),te});return await Y(),{isLogin:!0,isBound:!0,data:ne}}return{getInfo:z,getSteamGameList:N,async invalidateSteamGameListCache(){const m=A(),p=u,g=await _();if(!g)return;const E=c(m,g);await Promise.all([i.persistent.invalidateScope(E),i.unresolved.invalidateScope(E)]),t.clear(),s.delete(JSON.stringify([m,g])),await D(g,p)},dispose(){f||(f=!0,u+=1,w(),I(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function $g(e){if(e==null)return{limit:Td,offset:bd,sort:Od,includeHidden:!1};if(!H(e))throw Ge("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ge(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Wg(e.limit),offset:Kg(e.offset),sort:Jg(e.sort),includeHidden:Zg(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Bg)throw Ge("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ge("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Gg))}return r}function Wg(e){if(e===void 0)return Td;if(!Number.isInteger(e)||Number(e)<1)throw Ge("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Vg)}function Kg(e){if(e===void 0)return bd;if(!Number.isInteger(e)||Number(e)<0)throw Ge("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Jg(e){if(e===void 0)return Od;if(typeof e!="string"||!Qg.has(e))throw Ge("user.getSteamGameList sort 不支持");return e}function Zg(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ge("user.getSteamGameList includeHidden 必须是 boolean");return e}function Xg(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(ep).filter(a=>a!==void 0),n=Vn(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=_d(e.is_me);return s!==void 0&&(o.isMe=s),o}function ep(e){const t=Go(e),r=Vn(t.appid),n=Vn(t.steam_appid)??r,i=Qo(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};nr(o,"image",t.image),nr(o,"icon",t.appicon??t.icon),ir(o,"playtimeForever",t.playtime_forever),ir(o,"playtime2Weeks",t.playtime_2weeks);const s=rp(t.external_tags??t.tags);s.length&&(o.tags=s);const a=tp(t.price);return a&&(o.price=a),o}function tp(e){const t=Go(e),r={};return nr(r,"current",t.current),nr(r,"initial",t.initial),ir(r,"discount",t.discount),ir(r,"lowestPrice",t.lowest_price),nr(r,"deadlineDate",t.deadline_date),ir(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function da(e,t){if(!H(e))throw y("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 y(n,r)}if(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Go(e){return H(e)?e:{}}function Qo(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function rp(e){return Array.isArray(e)?e.map(Qo).filter(Boolean):[]}function Vn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function _d(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function nr(e,t,r){const n=Qo(r);n&&Object.assign(e,{[t]:n})}function ir(e,t,r){const n=Vn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ge(e){return y("INVALID_PARAMS",e)}function ua(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function np(e){return{[cn]:async t=>(la(t,"user.getInfo"),e.user.getInfo()),[dn]:async(t,r)=>{la(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[un]:async t=>e.user.getSteamGameList(t)}}function la(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function fa(e){throw{code:"INVALID_PARAMS",message:e}}function qt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function vd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Br(e,t,r){return Math.min(vd(e,t),r)}async function ip(e){try{return vd(await e.getNavigationBarHeight(),0)}catch{return 0}}function op(e,t,r,n){const i=Br(e.safeArea?.left,0,t),o=Math.max(i,Br(e.safeArea?.right,t,t)),s=Br(e.safeArea?.top,n,r),a=Math.max(s,Br(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function ha(e){const t=e.getViewportMetrics(),r=qt(t.windowWidth,0),n=qt(t.windowHeight,0),i=await ip(e);return{pixelRatio:qt(t.pixelRatio,1),screenWidth:qt(t.screenWidth,r),screenHeight:qt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:op(t,r,n,i),screenTop:i}}function sp(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 h=++i;ha(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||h!==i)return;const f=JSON.stringify(u);f!==o&&(o=f,r.onViewportChange?.(u))}).catch(()=>{})},c=sm({...r,onApplied:a}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[ct]:async(h,u)=>c.apply(h,u?.signal),[mn]:async()=>(q(r.operationContext.signal),ha(r.presentation)),[gn]:async h=>{if(q(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return fa("viewport.setNavigationBarStyle 参数必须是对象");const u=h.foregroundStyle;if(u!=="light"&&u!=="dark")return fa("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(h,u)=>c.apply({orientation:h.mode,fullscreen:h.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:d}}const ap=new Map(Ye.map(e=>[e.method,e]));function Zt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function cp(e){const t=Yu(e);return r=>t(r.requirement,r.method)}function dp(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=l=>{a||(a=!0,n.removeEventListener("abort",d),l())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>c(()=>o({status:"handled",value:l})),l=>c(()=>s(l)))})}function up(e){const t=cp(e.runtimePermissions),r=Se(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??lp,l=e.onTrace?d():0,h=e.onTrace?`cap_${++n}`:"",u=s===ct?++i:void 0;let f;try{if(e.terminalSignal.aborted)throw Zt("RUNTIME_DESTROYED","小程序 Runtime 已终止");il(s,e.effectiveCapabilities);const w=ap.get(s);if(!w)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const I=t(w),T=!I.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!I.allowed&&!T)throw Zt(I.code,I.message,I.data);const A=e.handlers[s];if(!A)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(f=dd(c.signal));const _=f?{...c,signal:f.signal}:c,D=async()=>{for(const z of e.policies??[]){const v=await z.evaluate({method:s,payload:a,capability:w});if(e.terminalSignal.aborted||f?.signal.aborted)throw pa();if(!v.allowed)throw Zt(v.code,v.message,v.data)}if(e.terminalSignal.aborted||f?.signal.aborted)throw pa();if(u!==void 0){if(ud(a),u<o)throw Zt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return A(a,_)},L=await dp(()=>f?f.run(D):D(),void 0,c,e.terminalSignal);return ma(e.onTrace,ga(h,s,a,l,L),d),L}catch(w){throw ma(e.onTrace,ga(h,s,a,l,{status:"error",error:w}),d),w}finally{f?.dispose()}}}}function lp(){return typeof performance>"u"?Date.now():performance.now()}function ma(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 ga(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:fp(i.error)}:{},...hp(t,r,i)}}function fp(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function hp(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"&&Ld(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 Ld(e){return typeof e=="object"&&e!==null}function pa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function mp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Gl(e.requestPolicy);let n;if(e.files)try{n=Pl(e.files,t)}catch{}const i=Lc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?gp:void 0),s=r.enabled?Hl({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Ah(e.files,e.miniProgramDetail),c=vh({registry:a,picker:e.picker,operationContext:t}),d=pf({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 l,h,u,f=()=>{},w=()=>{};try{l=sp({operationContext:t,presentation:e.hostPresentation,onDisplayChange:v=>e.eventSink.postEvent("display_change",v),onViewportChange:v=>e.eventSink.postEvent("viewport_change",v)}),h=qg({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),f=d.onEvent((v,N)=>e.eventSink.postEvent(v,N)),w=e.hostCompanion?.onSessionEvent?.(v=>{const N=gh(v);!e.terminalSignal.aborted&&N&&e.eventSink.postEvent(N.type,N.payload)})??(()=>{}),u=Zf({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const I=bg({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),T=[{name:"auth",handlers:Df({authorization:d})},{name:"user",handlers:np({user:h,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Ng({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:I.handlers},{name:"network",handlers:Fm({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[sn]:async()=>{throw Zt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Cg({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:wh({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:am({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:v=>l.applyOrientation({mode:"portrait",hideCapsule:!1},v)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:uh({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=pp(T);let _=!1;const D=()=>{_||(_=!0,e.terminalSignal.removeEventListener("abort",D),l?.dispose(),u?.dispose(),f(),w(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?D():e.terminalSignal.addEventListener("abort",D,{once:!0});const L=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:T,handlers:A,allowsCompanionAttachmentAccess:(v,N)=>L.has(v)&&Ld(N)&&a.isCompanionAttachmentRef(N.target),applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,...I.diagnostics?{storageDiagnostics:I.diagnostics}:{},dispose:D}}catch(I){throw l?.dispose(),u?.dispose(),f(),w(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),I}}function gp(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function pp(e){const t=new Map(Ye.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=Ye.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ye.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const yp="heybox-mini-dev:";function ya(e){try{return Ep(new URL(e))}catch{return!1}}function Ep(e){return e.protocol===yp}function wp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ip(e)}function Ip(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 Mp=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Ap(e,t){const r=[],n=Np(e.environmentInfo,r),i=Jr(n?.appVersion,"host.appVersion",r),o=Sp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Dp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Jr(t.miniProgramId),version:Jr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Np(e,t){if(e!=null){if(Cd(e))return e;t.push("environmentInfo")}}function Dp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Sp(e,t){if(e==null)return{name:"unknown",version:null};if(!Cd(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Mp.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:Jr(e.version,"operatingSystem.version",t)}}function Jr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Tp="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",bp="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Op="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",_p="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function vp(e,t,r,n,i="dark"){q(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:fixed;left:${r.left}px;top:${r.top+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const l=e.createElement("div");l.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const u=e.createElement("img");u.src=a?Op:Tp,u.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const f=e.createElement("div");f.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const w=e.createElement("img");w.src=a?_p:bp,w.style.cssText="width:12px;height:12px;flex-shrink:0;";const I=e.createElement("span");I.textContent=t?.trim()||"小程序工坊",I.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const T=e.createElement("div");T.textContent="小黑盒工坊小程序",T.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,f.append(w,I),h.append(u,f),l.append(h,T),s.append(l),e.body.append(s);const A=()=>{s.remove(),n.removeEventListener("abort",A)};n.addEventListener("abort",A,{once:!0});try{return await $(()=>Promise.all([u.decode(),w.decode()]),n),await $(()=>new Promise(_=>{let D=o.requestAnimationFrame(()=>{D=o.requestAnimationFrame(()=>{n.removeEventListener("abort",L),_()})});const L=()=>o.cancelAnimationFrame(D);n.addEventListener("abort",L,{once:!0})}),n),A}catch(_){throw A(),_}}const Lp=1,Rd="allow-scripts allow-same-origin",Cp="",Rp="no-referrer";function Pp(e=Rd){return!e.split(/\s+/).includes("allow-same-origin")}function Ea(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const kp=new Set(["javascript:","data:","blob:","file:"]),wa="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(kp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Fp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function jp(e,t){const r=new URL(e);return r.searchParams.set(vu,t),r.toString()}function Up(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=zp(r)??Hp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function zp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Hp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Ia(e){const t=new URL(e);return Yo(t)?"loopback":qo(t)?"lan":"production"}function Fp(e,t,r){return Vp(e)||Yo(e)||qo(e)&&Gp(t,r)}function Vp(e){return e.protocol==="https:"&&qp(e.hostname)}function Yo(e){return e.protocol==="http:"&&Bp(e.hostname)}function Bp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function qo(e){return e.protocol==="http:"&&Qp(e.hostname)}function Gp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Yo(r)||qo(r)}catch{return!1}}function Qp(e){const t=Yp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Yp(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 qp(e){return e===wa||e.endsWith(`.${wa}`)}const $p=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"]),Wp=new Set(["url","inline","eval","unknown"]),Kp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Jp=/^[a-f0-9]{64}$/,Zp=255,Xp=160,ey=256;function ty(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!$p.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>ey||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Wp.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=ry(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Xp||!Kp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Jp.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 ry(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 ny=/^(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 iy(e){if(!e?.minimumSdkVersion)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=nt(e.minimumSdkVersion),r=e.sdkVersion?nt(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=nt("0.6.0");if(!r){if(Zr(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(Zr(r,t)<0)throw K("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Zr(r,nt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function oy(e,t){if(typeof t!="string"||!nt(t))throw K("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw K("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Pd(e,t){const r=nt(e),n=nt(t);if(!(!r||!n))return Zr(r,n)}function nt(e){const t=ny.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 Zr(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 ai=["android","ios","ohos","windows","macos","linux"],sy="0.9.0",ay=Object.freeze(["android","ios","ohos","windows","macos"]),kd="该小程序暂不支持当前平台",cy="PLATFORM_UNSUPPORTED";function dy(e){return typeof e=="string"&&ai.includes(e)}function uy(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 ly(e){const t=e.manifest;if(!py(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Aa(e.sdkVersion)??Aa(t.sdkVersion);return my(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:hy()}const r=xd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function fy(e){const t=uy(e.operatingSystemName);if(!t)return Dt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Dt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:ai,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=ly({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Dt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):Ma(t,s)}if(r.effectivePlatforms===void 0)return Dt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=xd(r.effectivePlatforms);if("reason"in n)return Dt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=gy(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Ma(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function Ma(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Dt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Dt(e,t={}){return{status:"denied",reason:e,message:kd,...t}}function hy(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:ay,platformsDeclared:!1,policy:"legacy_mobile_default"}}function xd(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(!dy(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(ai.filter(r=>t.has(r)))}}function my(e){if(typeof e!="string"||!e.trim())return!1;const t=Pd(e.trim(),sy);return t!==void 0&&t>=0}function Aa(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function gy(e){return e==="explicit"||e==="legacy_mobile_default"}function py(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const yy=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 Ey(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:wy(i.pathname),sanitizedPathnameHash:Iy(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function wy(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Iy(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 T=0;T<16;T+=1)o[T]=s.getUint32(a+T*4,!1);for(let T=16;T<64;T+=1){const A=o[T-15],_=o[T-2],D=ve(A,7)^ve(A,18)^A>>>3,L=ve(_,17)^ve(_,19)^_>>>10;o[T]=o[T-16]+D+o[T-7]+L>>>0}let[c,d,l,h,u,f,w,I]=i;for(let T=0;T<64;T+=1){const A=I+(ve(u,6)^ve(u,11)^ve(u,25))+(u&f^~u&w)+yy[T]+o[T]>>>0,_=(ve(c,2)^ve(c,13)^ve(c,22))+(c&d^c&l^d&l);I=w,w=f,f=u,u=h+A>>>0,h=l,l=d,d=c,c=A+_>>>0}[c,d,l,h,u,f,w,I].forEach((T,A)=>{i[A]=i[A]+T>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ve(e,t){return e>>>t|e<<32-t}const My=1e4,Oi=2e3,Ay=2,Ny="open-with-native-credential-policy",jd="安全提示",Ud="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Dy{nonce=Ea();runtimeId=Ea();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=vc(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??My,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:(Ry(),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=qu(t.runtimePermissions),this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=iy(t.sdkVersionPolicy);const n=Ap(t,this.identity);if(this.environmentInfo=n.info,n.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${n.invalidFields.join(", ")}`}),this.platformGateDecision=fy({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw xy(this.platformGateDecision);if(this.miniProgramDetail=jy(t),this.effectiveCapabilities=_c(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),Oy(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const i=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const o=await this.confirmDevMiniProgramLaunch(i);if(!this.isInactive()){if(!o){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(vy(i)),this.launchUrl=i,this.miniProgramSrc=jp(i,this.nonce),this.traceSecurityPolicy(i),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(s){if(this.isInactive())return;const a=Po(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ct,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ze(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[ct])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=mp({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,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,prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(Pd(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):vp(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,o)},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=up({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:d,network:l})=>{const h={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};ze(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Xu({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 by(t)?t:zd(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:ya(r)||Na(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??Cy)({message:Ud,title:jd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Ia(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ya(r)&&!Na(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{Da(),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(()=>Da())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Cp),this.iframe.setAttribute("referrerpolicy",Rp),this.iframe.setAttribute("sandbox",Rd)}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(),ze(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(),ze(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{oy(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>=Ay)){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()},Oi),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 文档再验证超时")))},Oi))}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()},Oi))}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===Cu){this.handleCspViolation(t.payload);return}if(t.method!==Lu)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"||!Up(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=ty(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){ze(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Ey(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:Lp,launchUrlType:Ia(t),networkPolicy:Ny})}failRuntime(t){const r=Sy(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),ze(this.options.onError,Ty(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,ze(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ze(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 Sy(e){const t=Po(e);return Bn(e)&&"cause"in e&&zd(t,e.cause),t}function zd(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Ty(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function by(e){return Bn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Bn(e){return!!e&&typeof e=="object"}function ze(e,t){try{e?.(t)}catch{}}function Oy(e,t,r){try{e?.(t,r)}catch{}}function Na(e){try{const t=new URL(e);return t.protocol==="http:"&&wp(t.hostname)}catch{return!1}}function _y(e){try{return new URL(e).origin}catch{return}}function vy(e){return Pp()?"*":_y(e)}function Ly(e){return`${jd}
|
|
2
|
-
|
|
3
|
-
${Ud}
|
|
4
|
-
|
|
5
|
-
URL: ${e}`}function Cy(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Ly(e.url))}function Da(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Ry(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:pc,knownMethodCount:Ye.length,supportsFileCreate:Ye.some(i=>i.method===hr),system:Py(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:At(e?.hardwareConcurrency),maxTouchPoints:At(e?.maxTouchPoints),screen:{width:At(t?.width),height:At(t?.height)},viewport:{width:At(r?.innerWidth),height:At(r?.innerHeight),devicePixelRatio:ky(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function Py(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function At(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function ky(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function xy(e){return K(cy,kd,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function jy(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function Uy(e){if(!Bn(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Bn(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new Dy(e)}const zy=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i,Hy=new Set(["origin","referer","user-agent"]);function Fy(e,t){return al({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=Vy(r),a=await e.authenticatedRequest(s,o);return Qy(a)})}).network}function Vy(e){const t=By(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function By(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!Gy(t)))}function Gy(e){const t=e.trim().toLowerCase();return Hy.has(t)}function Qy(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:Yy(e.headers)??{}}}function Yy(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!qy(t)))}function qy(e){const t=e.trim().toLowerCase();return zy.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function $y(e,t,r){const n=Xy(e.presentation,t);return{account:Jy(e,t,r),network:Fy(e,t),...e.storage===void 0?{}:{storage:Zy(e,t)},...e.storage===void 0?{}:Wy(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function Wy(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function Ky(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function Jy(e,t,r){return{getCurrentUserId:n=>t.run(n.signal,i=>e.account.getCurrentUserId({signal:i})),ensureAuthenticated:n=>t.run(n.signal,i=>e.account.ensureAuthenticated({trustedUserGesture:n.trustedUserGesture,reason:n.reason,signal:i})),onChange:n=>{t.assertActive();const i=e.account.onChange(o=>{t.signal.aborted||n(o)});return r(i)}}}function Zy(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function Xy(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,o=>e.openAppPage(n,{signal:o}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,o=>e.openWindow(n,{signal:o}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,o=>e.applyOrientation(n,{...i,signal:o}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(n,{signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>wl(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{signal:o}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,o=>e.vibrate(n,{signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{signal:o}))),Object.keys(r).length===0?void 0:r}function eE(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw Gr(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(l=>l.aborted);if(i)throw Gr(i.reason);const o=new AbortController;let s;const a=new Promise((l,h)=>{s=h}),c=n.map(l=>{const h=()=>{o.signal.aborted||o.abort(l.reason),s(Gr(l.reason))};return l.addEventListener("abort",h,{once:!0}),{listener:h,source:l}});let d;try{d=Promise.resolve(r(o.signal))}catch(l){d=Promise.reject(l)}try{const l=await Promise.race([d,a]),h=n.find(u=>u.aborted);if(h)throw Gr(h.reason);return l}finally{for(const{listener:l,source:h}of c)h.removeEventListener("abort",l)}}}}function Gr(e){return new DOMException("Web Host operation aborted","AbortError")}async function tE(e){const t=eE(),r=new Set;let n=!1;const i=u=>{if(n||t.signal.aborted)return _i(u),()=>{};let f=!0;const w=()=>{f&&(f=!1,r.delete(w),_i(u))};return r.add(w),w},o=()=>s(e.signal.reason),s=u=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(u);for(const f of[...r])f();e.onDispose&&_i(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=$y(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Ad({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:Dg,resolveScope:async()=>Md((await h()).configuration)}));const c=vc(a,{hostCapabilities:e.hostCapabilities}),d=Ky(e,t);let l;const h=()=>l??=t.run(void 0,u=>e.resolveLaunch(u));return{platform:"web",ports:a,environment:d,resolveLaunch:h,...e.authPresentation===void 0?{}:{authPresentation:rE(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function _i(e){try{e()}catch{}}function rE(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Nt={},vi,Sa;function nE(){return Sa||(Sa=1,vi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),vi}var Li={},He={},Ta;function ft(){if(Ta)return He;Ta=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return He.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},He.getSymbolTotalCodewords=function(n){return t[n]},He.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},He.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},He.isKanjiModeEnabled=function(){return typeof e<"u"},He.toSJIS=function(n){return e(n)},He}var Ci={},ba;function $o(){return ba||(ba=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(Ci)),Ci}var Ri,Oa;function iE(){if(Oa)return Ri;Oa=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ri=e,Ri}var Pi,_a;function oE(){if(_a)return Pi;_a=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Pi=e,Pi}var ki={},va;function sE(){return va||(va=1,(function(e){const t=ft().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(ki)),ki}var xi={},La;function aE(){if(La)return xi;La=1;const e=ft().getSymbolSize,t=7;return xi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},xi}var ji={},Ca;function cE(){return Ca||(Ca=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,l=null;for(let h=0;h<o;h++){a=c=0,d=l=null;for(let u=0;u<o;u++){let f=i.get(h,u);f===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=f,a=1),f=i.get(u,h),f===l?c++:(c>=5&&(s+=t.N1+(c-5)),l=f,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let l=0;l<o;l++)a=a<<1&2047|i.get(d,l),l>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(l,d),l>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const l=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),l<c&&(c=l,a=d)}return a}})(ji)),ji}var Qr={},Ra;function Hd(){if(Ra)return Qr;Ra=1;const e=$o(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Qr.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},Qr.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},Qr}var Ui={},$t={},Pa;function dE(){if(Pa)return $t;Pa=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),$t.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},$t.exp=function(n){return e[n]},$t.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},$t}var ka;function uE(){return ka||(ka=1,(function(e){const t=dE();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(Ui)),Ui}var zi,xa;function lE(){if(xa)return zi;xa=1;const e=uE();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},zi=t,zi}var Hi={},Fi={},Vi={},ja;function Fd(){return ja||(ja=1,Vi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Vi}var Le={},Ua;function Vd(){if(Ua)return Le;Ua=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
6
|
-
]))+`;Le.KANJI=new RegExp(r,"g"),Le.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Le.BYTE=new RegExp(n,"g"),Le.NUMERIC=new RegExp(e,"g"),Le.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Le.testKanji=function(c){return i.test(c)},Le.testNumeric=function(c){return o.test(c)},Le.testAlphanumeric=function(c){return s.test(c)},Le}var za;function ht(){return za||(za=1,(function(e){const t=Fd(),r=Vd();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(Fi)),Fi}var Ha;function fE(){return Ha||(Ha=1,(function(e){const t=ft(),r=Hd(),n=$o(),i=ht(),o=Fd(),s=7973,a=t.getBCHDigit(s);function c(u,f,w){for(let I=1;I<=40;I++)if(f<=e.getCapacity(I,w,u))return I}function d(u,f){return i.getCharCountIndicator(u,f)+4}function l(u,f){let w=0;return u.forEach(function(I){const T=d(I.mode,f);w+=T+I.getBitsLength()}),w}function h(u,f){for(let w=1;w<=40;w++)if(l(u,w)<=e.getCapacity(w,f,i.MIXED))return w}e.from=function(f,w){return o.isValid(f)?parseInt(f,10):w},e.getCapacity=function(f,w,I){if(!o.isValid(f))throw new Error("Invalid QR Code version");typeof I>"u"&&(I=i.BYTE);const T=t.getSymbolTotalCodewords(f),A=r.getTotalCodewordsCount(f,w),_=(T-A)*8;if(I===i.MIXED)return _;const D=_-d(I,f);switch(I){case i.NUMERIC:return Math.floor(D/10*3);case i.ALPHANUMERIC:return Math.floor(D/11*2);case i.KANJI:return Math.floor(D/13);case i.BYTE:default:return Math.floor(D/8)}},e.getBestVersionForData=function(f,w){let I;const T=n.from(w,n.M);if(Array.isArray(f)){if(f.length>1)return h(f,T);if(f.length===0)return 1;I=f[0]}else I=f;return c(I.mode,I.getLength(),T)},e.getEncodedBits=function(f){if(!o.isValid(f)||f<7)throw new Error("Invalid QR Code version");let w=f<<12;for(;t.getBCHDigit(w)-a>=0;)w^=s<<t.getBCHDigit(w)-a;return f<<12|w}})(Hi)),Hi}var Bi={},Fa;function hE(){if(Fa)return Bi;Fa=1;const e=ft(),t=1335,r=21522,n=e.getBCHDigit(t);return Bi.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},Bi}var Gi={},Qi,Va;function mE(){if(Va)return Qi;Va=1;const e=ht();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},Qi=t,Qi}var Yi,Ba;function gE(){if(Ba)return Yi;Ba=1;const e=ht(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},Yi=r,Yi}var qi,Ga;function pE(){if(Ga)return qi;Ga=1;const e=ht();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},qi=t,qi}var $i,Qa;function yE(){if(Qa)return $i;Qa=1;const e=ht(),t=ft();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
|
|
7
|
-
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},$i=r,$i}var Wi={exports:{}},Ya;function EE(){return Ya||(Ya=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,l,h,u,f,w,I,T;!a.empty();){c=a.pop(),d=c.value,h=c.cost,u=r[d]||{};for(l in u)u.hasOwnProperty(l)&&(f=u[l],w=h+f,I=s[l],T=typeof s[l]>"u",(T||I>w)&&(s[l]=w,a.push(l,w),o[l]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var A=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(A)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Wi)),Wi.exports}var qa;function wE(){return qa||(qa=1,(function(e){const t=ht(),r=mE(),n=gE(),i=pE(),o=yE(),s=Vd(),a=ft(),c=EE();function d(A){return unescape(encodeURIComponent(A)).length}function l(A,_,D){const L=[];let z;for(;(z=A.exec(D))!==null;)L.push({data:z[0],index:z.index,mode:_,length:z[0].length});return L}function h(A){const _=l(s.NUMERIC,t.NUMERIC,A),D=l(s.ALPHANUMERIC,t.ALPHANUMERIC,A);let L,z;return a.isKanjiModeEnabled()?(L=l(s.BYTE,t.BYTE,A),z=l(s.KANJI,t.KANJI,A)):(L=l(s.BYTE_KANJI,t.BYTE,A),z=[]),_.concat(D,L,z).sort(function(N,m){return N.index-m.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function u(A,_){switch(_){case t.NUMERIC:return r.getBitsLength(A);case t.ALPHANUMERIC:return n.getBitsLength(A);case t.KANJI:return o.getBitsLength(A);case t.BYTE:return i.getBitsLength(A)}}function f(A){return A.reduce(function(_,D){const L=_.length-1>=0?_[_.length-1]:null;return L&&L.mode===D.mode?(_[_.length-1].data+=D.data,_):(_.push(D),_)},[])}function w(A){const _=[];for(let D=0;D<A.length;D++){const L=A[D];switch(L.mode){case t.NUMERIC:_.push([L,{data:L.data,mode:t.ALPHANUMERIC,length:L.length},{data:L.data,mode:t.BYTE,length:L.length}]);break;case t.ALPHANUMERIC:_.push([L,{data:L.data,mode:t.BYTE,length:L.length}]);break;case t.KANJI:_.push([L,{data:L.data,mode:t.BYTE,length:d(L.data)}]);break;case t.BYTE:_.push([{data:L.data,mode:t.BYTE,length:d(L.data)}])}}return _}function I(A,_){const D={},L={start:{}};let z=["start"];for(let v=0;v<A.length;v++){const N=A[v],m=[];for(let p=0;p<N.length;p++){const g=N[p],E=""+v+p;m.push(E),D[E]={node:g,lastCount:0},L[E]={};for(let M=0;M<z.length;M++){const S=z[M];D[S]&&D[S].node.mode===g.mode?(L[S][E]=u(D[S].lastCount+g.length,g.mode)-u(D[S].lastCount,g.mode),D[S].lastCount+=g.length):(D[S]&&(D[S].lastCount=g.length),L[S][E]=u(g.length,g.mode)+4+t.getCharCountIndicator(g.mode,_))}}z=m}for(let v=0;v<z.length;v++)L[z[v]].end=0;return{map:L,table:D}}function T(A,_){let D;const L=t.getBestModeForData(A);if(D=t.from(_,L),D!==t.BYTE&&D.bit<L.bit)throw new Error('"'+A+'" cannot be encoded with mode '+t.toString(D)+`.
|
|
8
|
-
Suggested mode is: `+t.toString(L));switch(D===t.KANJI&&!a.isKanjiModeEnabled()&&(D=t.BYTE),D){case t.NUMERIC:return new r(A);case t.ALPHANUMERIC:return new n(A);case t.KANJI:return new o(A);case t.BYTE:return new i(A)}}e.fromArray=function(_){return _.reduce(function(D,L){return typeof L=="string"?D.push(T(L,null)):L.data&&D.push(T(L.data,L.mode)),D},[])},e.fromString=function(_,D){const L=h(_,a.isKanjiModeEnabled()),z=w(L),v=I(z,D),N=c.find_path(v.map,"start","end"),m=[];for(let p=1;p<N.length-1;p++)m.push(v.table[N[p]].node);return e.fromArray(f(m))},e.rawSplit=function(_){return e.fromArray(h(_,a.isKanjiModeEnabled()))}})(Gi)),Gi}var $a;function IE(){if($a)return Li;$a=1;const e=ft(),t=$o(),r=iE(),n=oE(),i=sE(),o=aE(),s=cE(),a=Hd(),c=lE(),d=fE(),l=hE(),h=ht(),u=wE();function f(v,N){const m=v.size,p=o.getPositions(N);for(let g=0;g<p.length;g++){const E=p[g][0],M=p[g][1];for(let S=-1;S<=7;S++)if(!(E+S<=-1||m<=E+S))for(let R=-1;R<=7;R++)M+R<=-1||m<=M+R||(S>=0&&S<=6&&(R===0||R===6)||R>=0&&R<=6&&(S===0||S===6)||S>=2&&S<=4&&R>=2&&R<=4?v.set(E+S,M+R,!0,!0):v.set(E+S,M+R,!1,!0))}}function w(v){const N=v.size;for(let m=8;m<N-8;m++){const p=m%2===0;v.set(m,6,p,!0),v.set(6,m,p,!0)}}function I(v,N){const m=i.getPositions(N);for(let p=0;p<m.length;p++){const g=m[p][0],E=m[p][1];for(let M=-2;M<=2;M++)for(let S=-2;S<=2;S++)M===-2||M===2||S===-2||S===2||M===0&&S===0?v.set(g+M,E+S,!0,!0):v.set(g+M,E+S,!1,!0)}}function T(v,N){const m=v.size,p=d.getEncodedBits(N);let g,E,M;for(let S=0;S<18;S++)g=Math.floor(S/3),E=S%3+m-8-3,M=(p>>S&1)===1,v.set(g,E,M,!0),v.set(E,g,M,!0)}function A(v,N,m){const p=v.size,g=l.getEncodedBits(N,m);let E,M;for(E=0;E<15;E++)M=(g>>E&1)===1,E<6?v.set(E,8,M,!0):E<8?v.set(E+1,8,M,!0):v.set(p-15+E,8,M,!0),E<8?v.set(8,p-E-1,M,!0):E<9?v.set(8,15-E-1+1,M,!0):v.set(8,15-E-1,M,!0);v.set(p-8,8,1,!0)}function _(v,N){const m=v.size;let p=-1,g=m-1,E=7,M=0;for(let S=m-1;S>0;S-=2)for(S===6&&S--;;){for(let R=0;R<2;R++)if(!v.isReserved(g,S-R)){let F=!1;M<N.length&&(F=(N[M]>>>E&1)===1),v.set(g,S-R,F),E--,E===-1&&(M++,E=7)}if(g+=p,g<0||m<=g){g-=p,p=-p;break}}}function D(v,N,m){const p=new r;m.forEach(function(R){p.put(R.mode.bit,4),p.put(R.getLength(),h.getCharCountIndicator(R.mode,v)),R.write(p)});const g=e.getSymbolTotalCodewords(v),E=a.getTotalCodewordsCount(v,N),M=(g-E)*8;for(p.getLengthInBits()+4<=M&&p.put(0,4);p.getLengthInBits()%8!==0;)p.putBit(0);const S=(M-p.getLengthInBits())/8;for(let R=0;R<S;R++)p.put(R%2?17:236,8);return L(p,v,N)}function L(v,N,m){const p=e.getSymbolTotalCodewords(N),g=a.getTotalCodewordsCount(N,m),E=p-g,M=a.getBlocksCount(N,m),S=p%M,R=M-S,F=Math.floor(p/M),P=Math.floor(E/M),O=P+1,C=F-P,b=new c(C);let x=0;const j=new Array(M),U=new Array(M);let B=0;const G=new Uint8Array(v.buffer);for(let W=0;W<M;W++){const pe=W<R?P:O;j[W]=G.slice(x,x+pe),U[W]=b.encode(j[W]),x+=pe,B=Math.max(B,pe)}const Y=new Uint8Array(p);let ne=0,te,ee;for(te=0;te<B;te++)for(ee=0;ee<M;ee++)te<j[ee].length&&(Y[ne++]=j[ee][te]);for(te=0;te<C;te++)for(ee=0;ee<M;ee++)Y[ne++]=U[ee][te];return Y}function z(v,N,m,p){let g;if(Array.isArray(v))g=u.fromArray(v);else if(typeof v=="string"){let F=N;if(!F){const P=u.rawSplit(v);F=d.getBestVersionForData(P,m)}g=u.fromString(v,F||40)}else throw new Error("Invalid data");const E=d.getBestVersionForData(g,m);if(!E)throw new Error("The amount of data is too big to be stored in a QR Code");if(!N)N=E;else if(N<E)throw new Error(`
|
|
9
|
-
The chosen QR Code version cannot contain this amount of data.
|
|
10
|
-
Minimum version required to store current data is: `+E+`.
|
|
11
|
-
`);const M=D(N,m,g),S=e.getSymbolSize(N),R=new n(S);return f(R,N),w(R),I(R,N),A(R,m,0),N>=7&&T(R,N),_(R,M),isNaN(p)&&(p=s.getBestMask(R,A.bind(null,R,m))),s.applyMask(p,R),A(R,m,p),{modules:R,version:N,errorCorrectionLevel:m,maskPattern:p,segments:g}}return Li.create=function(N,m){if(typeof N>"u"||N==="")throw new Error("No input text");let p=t.M,g,E;return typeof m<"u"&&(p=t.from(m.errorCorrectionLevel,t.M),g=d.from(m.version),E=s.from(m.maskPattern),m.toSJISFunc&&e.setToSJISFunction(m.toSJISFunc)),z(N,g,p,E)},Li}var Ki={},Ji={},Wa;function Bd(){return Wa||(Wa=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),l=o.margin*c,h=[o.color.light,o.color.dark];for(let u=0;u<d;u++)for(let f=0;f<d;f++){let w=(u*d+f)*4,I=o.color.light;if(u>=l&&f>=l&&u<d-l&&f<d-l){const T=Math.floor((u-l)/c),A=Math.floor((f-l)/c);I=h[a[T*s+A]?1:0]}n[w++]=I.r,n[w++]=I.g,n[w++]=I.b,n[w]=I.a}}})(Ji)),Ji}var Ka;function ME(){return Ka||(Ka=1,(function(e){const t=Bd();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const l=t.getImageWidth(o.modules.size,c),h=d.getContext("2d"),u=h.createImageData(l,l);return t.qrToImageData(u.data,o,c),r(h,d,l),h.putImageData(u,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),l=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(l,h.quality)}})(Ki)),Ki}var Zi={},Ja;function AE(){if(Ja)return Zi;Ja=1;const e=Bd();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,l=0;for(let h=0;h<i.length;h++){const u=Math.floor(h%o),f=Math.floor(h/o);!u&&!d&&(d=!0),i[h]?(l++,h>0&&u>0&&i[h-1]||(a+=d?r("M",u+s,.5+f+s):r("m",c,0),c=0,d=!1),u+1<o&&i[h+1]||(a+=r("h",l),l=0)):c++}return a}return Zi.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,l=o.modules.data,h=d+c.margin*2,u=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",f="<path "+t(c.color.dark,"stroke")+' d="'+n(l,d,c.margin)+'"/>',w='viewBox="0 0 '+h+" "+h+'"',T='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+w+' shape-rendering="crispEdges">'+u+f+`</svg>
|
|
12
|
-
`;return typeof a=="function"&&a(null,T),T},Zi}var Za;function NE(){if(Za)return Nt;Za=1;const e=nE(),t=IE(),r=ME(),n=AE();function i(o,s,a,c,d){const l=[].slice.call(arguments,1),h=l.length,u=typeof l[h-1]=="function";if(!u&&!e())throw new Error("Callback required as last argument");if(u){if(h<2)throw new Error("Too few arguments provided");h===2?(d=a,a=s,s=c=void 0):h===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=s,s=c=void 0):h===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(f,w){try{const I=t.create(a,c);f(o(I,s,c))}catch(I){w(I)}})}try{const f=t.create(a,c);d(null,o(f,s,c))}catch(f){d(f)}}return Nt.create=t.create,Nt.toCanvas=i.bind(null,r.render),Nt.toDataURL=i.bind(null,r.renderToDataURL),Nt.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Nt}var DE=NE();const SE="/__hb_sdk__/dev-context";function Xa(e,t){return Ar(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:Ar(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}function or(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Nc(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:Gu({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function TE(e){if(!Ar(e)||!ec(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Ar(t)||!ec(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const bE={networkRequest:{status:"disabled",useOfficialDomain:!1}};function ci(e){const t=Se(e.localDevGrant?Ro({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:vE()}function OE(e,t,r){return r?.localDevGrant?Ro({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Gd(e,t,t.networkRequest.useOfficialDomain)}function _E(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=ci({...e,localDevGrant:void 0});return Gd(e.runtimePermissions,t,!1)}function vE(){return{networkRequest:{...bE.networkRequest}}}function Gd(e,t,r){const n=Se(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of wr){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:{key:s,status:a.status,config:{}})}const o=Ar(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function ec(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function LE(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(h){a={ok:!1},!n&&!c.signal.aborted&&s(h);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let l;try{l=e.apply(d)}catch(h){a={ok:!1},n||s(h);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(l))try{await e.onChanged(l)}catch(h){a={ok:!1},n||s(h)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function CE(e){return LE({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function RE(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const PE={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function kE(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
|
|
13
|
-
<div class="hb-sdk-auth-dialog__panel">
|
|
14
|
-
<h2>授权请求</h2>
|
|
15
|
-
<p class="hb-sdk-auth-dialog__app">${Xi(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
16
|
-
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${Xi(PE[a]||a)}</li>`).join("")}</ul>
|
|
17
|
-
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Xi(e.userProfile.nickname)}</p>`:""}
|
|
18
|
-
<div class="hb-sdk-auth-dialog__actions">
|
|
19
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
20
|
-
<button type="button" class="primary" data-action="allow">允许</button>
|
|
21
|
-
</div>
|
|
22
|
-
</div>
|
|
23
|
-
`;const i=a=>{s(),t(a)},o=()=>{s(),r(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),n.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}function Xi(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function xE(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:ns,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:ai},sdkVersion:ns},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const tc="hb-sdk-action-dialog-style";function di(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}FE();const n=document.createElement("div");n.className="hb-sdk-action-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
|
|
24
|
-
<div class="hb-sdk-action-dialog__panel">
|
|
25
|
-
<h2>${rc(e.title)}</h2>
|
|
26
|
-
<pre class="hb-sdk-action-dialog__detail">${rc(e.detail)}</pre>
|
|
27
|
-
<div class="hb-sdk-action-dialog__actions">
|
|
28
|
-
<button type="button" class="primary" data-action="confirm">确定</button>
|
|
29
|
-
</div>
|
|
30
|
-
</div>
|
|
31
|
-
`;const i=()=>{s(),t()},o=()=>{s(),r(e.signal?.reason)},s=()=>{e.signal?.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="confirm"]')?.addEventListener("click",i),e.signal?.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}async function jE(e,t){await di({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+jt(e.params)].join(`
|
|
32
|
-
`),signal:t.signal})}async function UE(e,t){await di({title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+jt(e.extra)].join(`
|
|
33
|
-
`),signal:t.signal})}async function zE(e,t){await di({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+jt(e.channel),"post: "+jt(e.post)].join(`
|
|
34
|
-
`),signal:t.signal})}async function HE(e,t){await di({title:"截图分享",detail:["rect: "+jt(e.rect),"post: "+jt(e.post)].join(`
|
|
35
|
-
`),signal:t.signal})}function jt(e){return JSON.stringify(e,null,2)}function rc(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function FE(){if(document.getElementById(tc))return;const e=document.createElement("style");e.id=tc,e.textContent=`
|
|
36
|
-
.hb-sdk-action-dialog {
|
|
37
|
-
position: absolute;
|
|
38
|
-
inset: 0;
|
|
39
|
-
z-index: 40;
|
|
40
|
-
display: grid;
|
|
41
|
-
place-items: center;
|
|
42
|
-
padding: 24px;
|
|
43
|
-
background: rgba(15, 23, 42, 0.45);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
.hb-sdk-action-dialog__panel {
|
|
47
|
-
width: min(420px, 100%);
|
|
48
|
-
border-radius: 12px;
|
|
49
|
-
padding: 20px;
|
|
50
|
-
background: #fff;
|
|
51
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
.hb-sdk-action-dialog__panel h2 {
|
|
55
|
-
margin: 0 0 8px;
|
|
56
|
-
font-size: 18px;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
.hb-sdk-action-dialog__detail {
|
|
60
|
-
margin: 0 0 16px;
|
|
61
|
-
max-height: 40vh;
|
|
62
|
-
overflow: auto;
|
|
63
|
-
color: #1f2933;
|
|
64
|
-
font-family: inherit;
|
|
65
|
-
font-size: 12px;
|
|
66
|
-
line-height: 1.6;
|
|
67
|
-
white-space: pre-wrap;
|
|
68
|
-
overflow-wrap: anywhere;
|
|
69
|
-
word-break: break-word;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
.hb-sdk-action-dialog__actions {
|
|
73
|
-
display: flex;
|
|
74
|
-
justify-content: flex-end;
|
|
75
|
-
gap: 8px;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
.hb-sdk-action-dialog__actions button {
|
|
79
|
-
min-height: 36px;
|
|
80
|
-
border: 1px solid #cad5e2;
|
|
81
|
-
border-radius: 6px;
|
|
82
|
-
padding: 0 12px;
|
|
83
|
-
background: #fff;
|
|
84
|
-
cursor: pointer;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
.hb-sdk-action-dialog__actions .primary {
|
|
88
|
-
border-color: #2563eb;
|
|
89
|
-
color: #fff;
|
|
90
|
-
background: #2563eb;
|
|
91
|
-
}
|
|
92
|
-
`,document.head.appendChild(e)}const VE=44;function BE(e){const t=()=>e.isCapsuleHidden?.()?0:VE;return{...e.applyDisplay?{applyOrientation:async(r,n)=>(await e.applyDisplay(r,n.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>{const r=e.getDeviceMetrics?.();return r?{windowWidth:r.screenWidth,windowHeight:r.screenHeight,screenWidth:r.screenWidth,screenHeight:r.screenHeight,pixelRatio:r.pixelRatio,safeArea:{top:r.safeAreaInsets.top+t(),right:r.screenWidth-r.safeAreaInsets.right,bottom:r.screenHeight-r.safeAreaInsets.bottom,left:r.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}},getNavigationBarHeight:()=>{const r=e.getDeviceMetrics?.().statusBarHeight;return r===void 0?0:r+t()},setNavigationBarStyle:r=>{document.documentElement.dataset.navigationBarStyle=r,e.onNavigationBarStyleChange?.(r)},setClipboard:async({text:r})=>{await navigator.clipboard.writeText(r)},showToast:async({message:r,status:n})=>{e.pushLog("host.message",{message:r,status:n}),await pu({message:r,status:n})},showLoading:gu,hideLoading:mu,vibrate:hu,openAppPage:jE,openWindow:UE,showShareMenu:zE,captureAndShare:HE,setScreenshotChromeHidden:fu}}const nc=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Yr=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],ic={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class GE{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...nc];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ue("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:ic[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:Yr[0]),i.operation.promise;let o,s;const a=new Promise((d,l)=>{o=d,s=l}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:Yr[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Yr.forEach((l,h)=>{const u=this.schedule(()=>{if(c.timers.delete(u),!c.cancelled){d.status={state:"preparing",progress:l};try{c.listeners.forEach(f=>f(l))}catch(f){c.cancelled=!0;for(const w of c.timers)this.clearSchedule(w);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:f instanceof Error?f.message:String(f)}),c.reject(f);return}if(this.diagnostic("prepare.progress",n,{phase:l.phase}),h===Yr.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ue("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},h+1);c.timers.add(u)})}return a}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(ue("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(ku,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw ue("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ue("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ue("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:ic[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
|
|
93
|
-
`),this.queueOutput(o,"stderr",1,`fake:diagnostic
|
|
94
|
-
`)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw ue("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ue("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw ue("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ue("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
|
|
95
|
-
`);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ue("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ue("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw ue("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(Ru,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(Pu,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw ue("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ue("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!nc.includes(t))throw ue("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const QE=Object.freeze({[Yn]:!0,[qn]:!0,[$n]:!0,[Wn]:!0,[Kn]:!0,[Jn]:!0,[Zn]:!0,[Xn]:!0,[ei]:!0,[ti]:!0,[ri]:!0,[ni]:!0,[pr]:!0,[gr]:!0,[yr]:!0});function YE(e){return new GE(e)}function ue(e,t){return Object.assign(new Error(t),{code:e})}const qE=/^[A-Za-z0-9_-]{22}$/,$E="https://api.xiaoheihe.cn/open_inapp/";function WE(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!qE.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function KE(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${$E}#${r}`}function JE(e){const t=Se(e.runtimePermissions),r=Ro({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Se(e.publishedRuntimePermissions),o=Se(r.runtimePermissions);for(const s of Ac){const a=s.key,c={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[a]??s.name;if(!e.declaredPermissions?.[a]?.enabled)continue;const d=t.valid&&t.permissions[a]?.status==="enabled",l=r.temporaryPermissionKeys.some(h=>h===a);n.push({key:a,label:c,state:s.access==="declaration"?"declared":d?"approved":l?"temporary":"unavailable",facts:{platformApproval:s.access==="declaration"?null:d,temporary:l,effective:o.permissions[a]?.status==="enabled",online:i.valid?i.permissions[a]?.status??"missing":"unknown"},...l?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[a]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...a==="appProtocol"?{highestRisk:!0}:{},...s.access!=="declaration"&&!d&&!l?{reason:a==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const s=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:s?"approved":"unavailable",...s?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function it(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const ZE="__hb_sdk_mini_dev__",XE="hb-sdk:mini-dev-console",ew="__hb_sdk_mini_dev_console_installed__",oc=ew;function tw(e,t=console){nw(t,e,t)}const rw=["log","debug","info","warn","error"];function nw(e,t,r){if(!r||r[oc]===!0)return!1;let n=!1;for(const i of rw){const o=e[i];if(typeof o!="function")continue;const s=function(...a){try{t(i,a)}catch{}return o.apply(this,a)};try{e[i]=s,n=!0}catch{return n}}return n&&(r[oc]=!0),n}const yo=1,sc=64*1024,iw=64,ow=/^[A-Za-z0-9_-]{22}$/;class Ee extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function sw(e,t=!1){const r=cw(e,t);switch(Eo(r,"Server message"),dw(r),r.type){case"grant":return sr(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),ar(r.connectionEpoch,"connectionEpoch"),ot(r.nextClientSequence,"nextClientSequence"),ot(r.nextServerSequence,"nextServerSequence"),ac(r.snapshot),r;case"event":return sr(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),ar(r.connectionEpoch,"connectionEpoch"),ot(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ke("event must be account.changed or status.changed"),ac(r.snapshot),r;case"heartbeat":return sr(r,["version","type","connectionEpoch","sequence"],"heartbeat"),ar(r.connectionEpoch,"connectionEpoch"),ot(r.sequence,"sequence"),r;default:return Ke("Unknown server message type")}}function aw(e){const t=e.connectionEpoch;ar(t,"connectionEpoch"),ot(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(ar(n.connectionEpoch,"connectionEpoch"),ot(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Ee("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Ee("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Ee("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function cw(e,t){if(t)throw new Ee("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Ee("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>sc)throw new Ee("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>sc)throw new Ee("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return uw(e),JSON.parse(e)}catch(r){throw r instanceof Ee?r:new Ee("INVALID_JSON","Channel frame must contain strict JSON")}}function ac(e){Eo(e,"snapshot"),sr(e,["account","permissions"],"snapshot"),Eo(e.account,"snapshot.account"),sr(e.account,["revision"],"snapshot.account"),ot(e.account.revision,"snapshot.account.revision"),TE(e.permissions)||Ke("snapshot.permissions is invalid")}function dw(e){e.version!==yo&&Ke("version must be 1")}function Eo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ke(`${t} must be a plain JSON object`)}function sr(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&Ke(`${r} fields are invalid`)}function ot(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ke(`${t} must be a non-negative safe integer`)}function ar(e,t){(typeof e!="string"||!ow.test(e))&&Ke(`${t} must be a 22-character base64url value`)}function Ke(e){throw new Ee("INVALID_MESSAGE",e)}function uw(e){new lw(e).scan()}class lw{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=iw)throw new Ee("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new Ee("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const cc=[1e3,2e3,4e3,8e3,15e3];function fw(e){const t=new Set,r=e.webSocketFactory??(g=>new WebSocket(g)),n=e.randomValues??(g=>crypto.getRandomValues(g)),i=e.timers??{clearTimeout:g=>window.clearTimeout(g),setTimeout:(g,E)=>window.setTimeout(g,E)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,l,h=!1,u=0,f,w=!1,I=!1;const T=new Set,A=(g,E)=>{if(!(!e.onDiagnostic||T.has(g))){T.add(g);try{e.onDiagnostic({phase:g,...E?{code:E}:{}})}catch{}}},_=(g,E,M=!1)=>{if(l&&g.account.revision<l.account.revision)return;const S=l&&JSON.stringify(g)===JSON.stringify(l);if(l=g,!(S&&!M))for(const R of t)R(g,E)},D=()=>{if(h||f!==void 0||c)return;const g=cc[Math.min(u,cc.length-1)];u+=1,f=i.setTimeout(()=>{f=void 0,p()},g)},L=()=>{h||!w||c||(f!==void 0&&(i.clearTimeout(f),f=void 0),p())},z=()=>{a()&&L()},v=()=>{s&&!s.hidden&&L()},N=()=>{I||(I=!0,o?.addEventListener("online",z),s?.addEventListener("visibilitychange",v))},m=()=>{I&&(I=!1,o?.removeEventListener("online",z),s?.removeEventListener("visibilitychange",v))},p=()=>{if(h||c)return;w=!0,N(),f!==void 0&&(i.clearTimeout(f),f=void 0);let g,E;try{g=r(e.url)}catch{A("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),D();return}try{E=mw(n)}catch{A("entropy","NONCE_GENERATION_FAILED");try{g?.close(1011,"channel initialization failed")}catch{}D();return}c=g;let M,S,R;const F=()=>{g.removeEventListener("open",O),g.removeEventListener("message",C),g.removeEventListener("close",b),g.removeEventListener("error",x),d===F&&(d=void 0)},P=()=>{if(c===g){c=void 0,F();try{g.close(1008,"invalid channel state")}catch{}D()}},O=()=>{if(!(h||c!==g))try{g.send(JSON.stringify({version:yo,type:"hello",csrfToken:e.csrfToken,clientNonce:E}))}catch{A("send","HELLO_SEND_FAILED"),P()}},C=j=>{if(h||c!==g)return;if(typeof j.data!="string"){A("parse","TEXT_FRAME_REQUIRED"),P();return}let U;try{U=sw(j.data)}catch(B){A("parse",B instanceof Ee?B.code:"INVALID_MESSAGE"),P();return}if(U.type==="grant"){if(R){A("sequence","DUPLICATE_GRANT"),P();return}M=U.connectionEpoch,S=U.nextClientSequence,R=aw({connectionEpoch:M,nextSequence:U.nextServerSequence}),u=0,T.clear(),_(U.snapshot,{type:"grant"});return}if(!R||!M||S===void 0){A("sequence","MESSAGE_BEFORE_GRANT"),P();return}try{R.accept(U)}catch{A("sequence","INVALID_SEQUENCE"),P();return}if(U.type==="heartbeat"){try{g.send(JSON.stringify({version:yo,type:"heartbeat.ack",connectionEpoch:M,sequence:S}))}catch{A("send","HEARTBEAT_ACK_SEND_FAILED"),P()}S=S===Number.MAX_SAFE_INTEGER?void 0:S+1;return}_(U.snapshot,{type:"event",event:U.event},!0)},b=()=>{c===g&&(A("close","SOCKET_CLOSED"),c=void 0,F(),D())},x=()=>{A("open","SOCKET_ERROR"),P()};g.addEventListener("open",O),g.addEventListener("message",C),g.addEventListener("close",b),g.addEventListener("error",x),d=F};return{connect:p,subscribeUpdates(g){return t.add(g),()=>t.delete(g)},dispose(){if(h)return;h=!0,w=!1,m(),f!==void 0&&i.clearTimeout(f),f=void 0;const g=c;c=void 0,d?.(),g?.close(1e3,"client disposed"),t.clear()}}}function hw(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function mw(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=hw(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{tw((e,t)=>{br(`console.${e}`,{source:"host",message:t.map(r=>Kd(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const gw="/__hb_sdk_bootstrap__",pw="/__hb_sdk__/mobile-launch-redirect",yw="/__hb_sdk__/network",Ew="/session/status",ww="/session/request",Iw="/session/events",Mw=320,Aw=1e3,Nw=1e3,Dw=15e3,dc="dark",Qd=new URL(location.href).searchParams,Yd=Qd.get("mini_url"),mt=Qd.get("ui_preview")==="1",Z={device:Wt("#device"),get mobileLanSelect(){return Wt("#mobile-lan-select")},get mobileQrImage(){return Wt("#mobile-qr-image")},get mobileQrStatus(){return Wt("#mobile-qr-status")},storageSnapshot:Wt("#storage-snapshot")};if(!Yd&&!mt)throw Z.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const qd=Yd??"about:blank",ie=await Jo();Q.openPlatformBaseUrl=ie.openPlatformBaseUrl;Q.devReadiness=ie.devReadiness;Q.miniProgramSupportsDesktop=ie.miniProgramSupportsDesktop;Q.desktopLaunch.workspaceCardsEnabled=ie.workspaceCardsEnabled;let Fe=ie.lanAddresses,Xr=ie.defaultLanAddressId,St=ie.mobileLaunchRedirect,Wo=ie.nativeAppLaunchUnavailableReason,cr=ie.devSessionId,wo=ie.miniProgramManifestAccessToken,Xt=ie.workspaceCardsEnabled,en=ie,Ko=fi(ie),Ne=ie.devContext,Ot=ie.browserDevContext,he=or(Ot);Qn();let Ut=ci(he),X=!1,ui=0;const li=new AbortController;let Pe=0,_t,Nr,tn=0,$e,Io,Mo,Ve=0,We=!1,rn,Ao,eo=!1;const dr=Du({apply:Su,waitForLayout:async e=>{await Tu(),await bu(e),await Ou(e)}});let No,Do,uc=Date.now(),er=!1,lc=Promise.resolve(),ur=-1,Dr=!1,at,So,To,nn,rt;const Gn=new Set,bo=YE({onDiagnostic:({action:e,alias:t,detail:r})=>Me(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),zt=CE({applyStatus:e=>tu(e,!0),fetchStatus:e=>eu(cu(li.signal,e)),getCanonicalRevision:()=>ur,onError:Kw,reconcile:()=>xw(ui)}),Oo=RE({connectEvents:ru,invalidate:()=>zt.invalidate(),isDisposed:()=>X,maxDelayMs:Dw,minDelayMs:Nw,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let to=0,tr="",ro=!1,_o;await vo(!1);ou();au(su(ie));mt&&Ow();hi();mt||await Wd();await Cr("initial");mt||(ru(),Pw());Sw();zw();function $d(){!mt&&!X&&(_o=window.setTimeout(()=>{Wd().finally($d)},1e3))}$d();async function Wd(){if(!(ro||X)){ro=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${to}&limit=500`,{signal:AbortSignal.any([li.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(X)return;if(tr&&t.epoch!==tr){to=0,tr=t.epoch;return}tr=t.epoch,Q.logDevices=t.devices,t.gap&&br("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=yu(r.method||`console.${r.level}`,{...r,source:"app"},r.timestamp,r.level==="debug"?"log":r.level);n.source=r.source,n.summary=r.message,n.detail=r,n.deviceSessionId=r.deviceSessionId,n.deviceName=t.devices.find(i=>i.id===r.deviceSessionId)?.name,n.dedupeKey=void 0,fc(n)}to=t.nextCursor}catch{}finally{ro=!1}}}function Sw(){window.addEventListener("beforeunload",Jw),window.addEventListener("hb-sdk:restart-runtime",Zd),window.addEventListener("hb-sdk:refresh-storage",hi),window.addEventListener("hb-sdk:qr-open-change",Jd),window.addEventListener("message",Tw),No=Eu(()=>document.querySelector("#host-fullscreen-exit-mount")),Do=wu(()=>Q.devicePresetId,()=>dr.notifyViewportChange(),{flush:"post"})}function Tw(e){const t=e.data;if(e.source===null||!we(t)||t.type!==XE||!we(t.detail))return;const r=t.detail;r.level!=="log"&&r.level!=="debug"&&r.level!=="info"&&r.level!=="warn"&&r.level!=="error"||!Array.isArray(r.args)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||br(`console.${r.level}`,{source:"app",message:r.args.map(n=>Kd(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function Kd(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
96
|
-
`).slice(0,4).join(`
|
|
97
|
-
`):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function Jd(e){const t=e.detail?.open===!0;t!==We&&(We=t,Ve+=1,mi(),t&&(Z.mobileLanSelect.addEventListener("change",bw),nu(),Rr()))}function bw(){We&&Rr()}function Zd(){Sr("manual restart")}function Sr(e){X||_t!==void 0||(Me("runtime.restart",{boundary:Pe+1}),_t=window.setTimeout(()=>{_t=void 0,X||Cr(e)},0))}async function Cr(e){if(er)return;const t=++Pe;if(Nr=void 0,Tr(e),Xd(),Q.runtimeStatus="loading",lu(Ut),Z.device.replaceChildren(),mt){Z.device.innerHTML=`
|
|
98
|
-
<div class="browser-mock-preview">
|
|
99
|
-
<span class="browser-mock-preview__icon">UI</span>
|
|
100
|
-
<strong>Browser Mock</strong>
|
|
101
|
-
<small>mp_preview</small>
|
|
102
|
-
</div>`,Q.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=ZE,Z.device.appendChild(r);const n=new AbortController;Io=n;let i=!1;try{const o=await tE(_w(n.signal,t));if(X||t!==Pe){o.dispose();return}Mo=o.dispose,o.ports.companion=bo.port;const s=Uy({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,...QE},authPresentation:o.authPresentation,companionPresentation:bo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{Q.runtimeStatus="ready",Me("runtime.ready",{generation:t})},onTrace:a=>Cw(t,a),onError:()=>{i=!0,Q.runtimeStatus="error"},onCapabilityTrace:a=>{tr||Me(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&hi()}});$e=s,await s.start()}catch(o){if(X||t!==Pe||n.signal.aborted)return;Q.runtimeStatus="error",i||Me("runtime.start.failed",Iu(o))}}function Ow(){Me("runtime.ready",{generation:1}),br("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),Me("user.getInfo",{durationMs:34,outcome:"success"}),Me("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function _w(e,t){const r=he,n=cr,i=OE(r.runtimePermissions,Ut,r);return{signal:e,account:{async getCurrentUserId(){return(await vo(!1,e)).user_id},async ensureAuthenticated({signal:o}){await vo(!1,o)},onChange(o){return Gn.add(o),()=>Gn.delete(o)}},authenticatedRequest:Rw,storage:{area:"local",storage:localStorage},presentation:BE({close:async()=>{mc(),$e?.destroy(),dr.reset(),Xd(),Q.runtimeStatus="closed"},reload:()=>{!X&&t===Pe&&(Nr=t)},onNavigationBarStyleChange:hc,pushLog:Me,getDeviceMetrics:()=>_u.value,applyDisplay:(o,s)=>dr.applyDisplay(o,s),isCapsuleHidden:()=>Q.display.capsuleHidden,onViewportChange:o=>dr.onViewportChange(o)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:o=>{document.title=o}},resolveLaunch:async()=>({configuration:xE({launchUrl:qd,runtimePermissions:i,...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:Mu.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:o=>kE(o)},protocol:vw()}}function vw(){return{async invoke(e){Me("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:Lw(e)})}}}function Lw(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return we(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Xd(){document.documentElement.dataset.navigationBarStyle=dc,hc(dc)}function Cw(e,t){const r=Au(t,e);r&&fc(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Nr!==e||e!==Pe)&&(Nr=void 0,Sr("navigation.reload"))}async function Rw(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await Zo(n?yw:ww,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&zt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function vo(e,t){const r=ui,n=await eu(cu(li.signal,t));return du(r)?tu(n,e).status:Lo()}async function eu(e){return await(await fetch(Ew,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function tu(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<ur)return{changed:!1,status:Lo()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?se(e.nickname):void 0,i=e.authenticated?se(e.avatar):void 0,o=e.revision!==ur||e.authenticated!==Dr||r!==at||n!==So||i!==To;return ur=e.revision,Dr=e.authenticated,at=r,So=n,To=i,ou(),t&&o&&Gn.forEach(s=>s(at)),{changed:o,status:Lo()}}function Lo(){return{authenticated:Dr,revision:ur,...Dr&&at?{user_id:at}:{}}}function Pw(){if(!(!ie.csrfToken||X))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",rt=fw({csrfToken:ie.csrfToken,onDiagnostic:t=>Me("channel.diagnostic",t),url:e.toString()}),rt.subscribeUpdates((t,r)=>kw(t,r)),rt.connect()}catch{rt?.dispose(),rt=void 0}}function kw(e,t){zt.invalidate(e.account.revision),eI(Ut,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Cr("status changed"):(Ut=lu(e.permissions),jw())}function ru(){if(nn?.close(),nn=void 0,!at||X)return;const e=new EventSource(Iw);nn=e,e.addEventListener("account-invalidated",()=>{zt.invalidate()}),e.addEventListener("account-revision",()=>{zt.invalidate()}),e.onopen=()=>{Oo.reset()},e.onerror=()=>{e.close(),Oo.schedule()}}async function xw(e){du(e)&&await Cr("account revision changed")}function Tr(e){tn+=1,mc(),$e&&bo.reset(),$e?.destroy(),$e=void 0,Io?.abort(new DOMException(e,"AbortError")),Io=void 0,Mo?.(),Mo=void 0,dr.reset()}async function jw(){X||(await Cr("permission changed"),!X&&await Rr())}async function Jo(){const e=await fetch(gw,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!we(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=uu(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Ht;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:Uw(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:Xa(t.devContext,t.runtimePermissions),browserDevContext:Xa(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(Xw):[],loginAvailable:t.loginAvailable===!0,miniProgram:$w(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0}}function Uw(e){if(!we(e))return;const t=s=>{if(!(!we(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!we(e.companion))return;const o=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>we(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}async function Zo(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),ie.csrfToken&&r.set("x-hb-sdk-csrf",ie.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function zw(){Xo(),mt||(Ao=window.setInterval(()=>{qw()},Aw))}function nu(e=Z.mobileLanSelect.options.length>0?Z.mobileLanSelect.value:void 0){Z.mobileLanSelect.replaceChildren();for(const t of Fe){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,Z.mobileLanSelect.appendChild(r)}e&&Fe.some(({id:t})=>t===e)?Z.mobileLanSelect.value=e:Xr&&Fe.some(({id:t})=>t===Xr)?Z.mobileLanSelect.value=Xr:Fe[0]&&(Z.mobileLanSelect.value=Fe[0].id),Z.mobileLanSelect.disabled=Fe.length===0}async function Rr(){if(X)return;const e=++Ve;if(mi(),Ne.source!=="remote"||!Ne.localDevLaunchToken||Ne.expiresAt!==void 0&&Ne.expiresAt<=Date.now()){Z.mobileQrImage.removeAttribute("src"),Z.mobileQrStatus.textContent=Wo||"需要有效的本地调试启动票";return}const t=Zw();if(!t?.mobileAppQrPayload){Z.mobileQrImage.removeAttribute("src"),Z.mobileQrStatus.textContent="未发现可用的局域网地址";return}Z.mobileQrStatus.textContent="正在生成二维码...";try{const r=await Gw(t);if(e!==Ve||X)return;const n=await Hw(r.address,r.expiresAt);if(e!==Ve||X)return;const i=await DE.toDataURL(n.payload,{width:Mw,margin:1});if(e!==Ve||X)return;Z.mobileQrImage.src=i,Z.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,Yw(n.expiresAt,e)}catch(r){if(e!==Ve||X)return;if(r instanceof Ht){on();return}Z.mobileQrImage.removeAttribute("src"),Z.mobileQrStatus.textContent=es(r)}}async function Hw(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await Fw(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:KE(WE({host:e.address,port:location.port,token:n.token}))}}catch{throw new Ht}}async function Fw(e,t){if(St?.addressId===e.id)return St;if(!St)return;const r=await Zo(pw,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:St.token})});if(!r.ok)throw new Ht;const n=await r.json(),i=we(n)?uu({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Ht;return St=i,en={...en,mobileLaunchRedirect:i},Ko=fi(en),i}async function Vw(e){const t=await Jo(),r=Bw(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return iu(t),{...r,mobileAppQrPayload:n}}function Bw(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function iu(e){const t=it(he);Q.devReadiness=e.devReadiness,Q.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Xt=e.workspaceCardsEnabled,en=e,Ko=fi(e),Ne=e.devContext,Ot=e.browserDevContext,he=or(Ot),Ut=ci(he),Qn(),Fe=e.lanAddresses,Xr=e.defaultLanAddressId,St=e.mobileLaunchRedirect,Wo=e.nativeAppLaunchUnavailableReason,cr=e.devSessionId,wo=e.miniProgramManifestAccessToken,au(su(e)),We&&nu(),Xo(),t!==it(he)&&(Pe+=1,Tr("local permission context changed"),Sr("local permission context changed"))}function Qn(){Q.localPermissions=JE(he),Q.devContextWarning=he.source==="anonymous"?"未连接线上上下文":he.warning?"本地上下文受限,请检查 CLI 状态":""}function Xo(){let e;try{e=Nu(qd)}catch{}const t=Ne.miniProgramId?.trim().toLowerCase();let r=Wo?.trim()??"";!r&&(Ne.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Ne.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Xt&&!cr&&(r="本地调试会话尚未就绪"),!r&&Ne.expiresAt!==void 0&&Ne.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),gc({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Xt&&cr?{devSessionId:cr}:{},...Xt&&wo?{miniProgramManifestToken:wo}:{},workspaceCardsEnabled:Xt,ready:r==="",...r?{unavailableReason:r}:{}})}class Ht extends Error{}async function Gw(e){const t=lc.then(()=>Qw(e));return lc=t.then(()=>{},()=>{}),t}async function Qw(e){const t=new URL(e.appUrl),r=new URL(SE,location.origin),n=await Zo(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:_E(Ne)})}),i=await n.json();if(!n.ok||!we(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await Vw(e.id),expiresAt:i.expires_at}}function Yw(e,t){rn=window.setTimeout(()=>{!X&&We&&t===Ve&&Rr()},Math.max(1e3,e-Date.now()-3e4))}async function qw(){if(!(eo||X)){eo=!0;try{const e=await Jo();uc=Date.now();const t=er;er=!1;const r=fi(e);if(!t&&r===Ko&&it(or(e.browserDevContext))===it(he)){Ot=e.browserDevContext,he=or(Ot),Qn();return}iu(e),t&&Sr("CLI dev session reconnected"),We&&Rr()}catch(e){e instanceof Ht&&on();const t=or(Ot);it(t)!==it(he)&&(he=t,Ut=ci(he),Qn(),Pe+=1,Tr("local permission context expired"),Sr("local permission context expired"),Xo(),We&&on()),Date.now()-uc>=3e4&&!er&&(er=!0,Pe+=1,Tr("CLI dev session disconnected"),Z.device.replaceChildren(),Q.runtimeStatus="closed",Q.localPermissions=[],Q.devContextWarning="调试会话已断开",gc({ready:!1,unavailableReason:"调试会话已断开"}),Q.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},We&&on())}finally{eo=!1}}}function on(){Ve+=1,mi(),Z.mobileQrImage.removeAttribute("src"),Z.mobileQrStatus.textContent="Mobile 短链接配置无效"}function fi(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{permissionContext:it(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled})}function ou(){if(!Dr){Q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Q.account={authenticated:!0,avatar:To??"",nickname:So||at||"已登录"}}function su(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function au(e){if(!!!e?.miniProgramId||!e){Q.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Q.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function $w(e){if(e===null)return null;if(!we(e))return;const t=se(e.miniProgramId)??se(e.mini_program_id);if(t)return{miniProgramId:t,...se(e.name)?{name:se(e.name)}:{},...se(e.iconUrl)??se(e.icon_url)?{iconUrl:se(e.iconUrl)??se(e.icon_url)}:{},...se(e.status)?{status:se(e.status)}:{},...se(e.version)?{version:se(e.version)}:{},...se(e.developerName)??se(e.developer_name)?{developerName:se(e.developerName)??se(e.developer_name)}:{}}}function se(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function hi(){const e=++tn,t=$e,r=t?.diagnostics.storage;if(!r){Q.storage=[],Q.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(X||e!==tn||t!==$e)return;Q.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Q.storageError=""}catch(n){if(X||e!==tn||t!==$e)return;Q.storage=[],Q.storageError=es(n)}}function Ww(e,t){Me("host.message",{message:e,status:t})}function Kw(e){X||Ww(es(e),"error")}function Me(e,t){br(e,t)}function Jw(){_o!==void 0&&window.clearTimeout(_o),!X&&(X=!0,window.removeEventListener("hb-sdk:restart-runtime",Zd),window.removeEventListener("hb-sdk:refresh-storage",hi),window.removeEventListener("hb-sdk:qr-open-change",Jd),ui+=1,li.abort(new DOMException("Browser Dev Host disposed","AbortError")),zt.dispose(),Pe+=1,Tr("Browser Dev Host disposed"),nn?.close(),rt?.dispose(),rt=void 0,Oo.dispose(),Nr=void 0,_t!==void 0&&window.clearTimeout(_t),_t=void 0,mi(),Ao!==void 0&&window.clearInterval(Ao),Gn.clear(),No?.(),No=void 0,Do?.(),Do=void 0)}function mi(){rn!==void 0&&window.clearTimeout(rn),rn=void 0}function cu(e,t){return t?AbortSignal.any([e,t]):e}function du(e){return!X&&e===ui}function Zw(){return Fe.find(({id:e})=>e===Z.mobileLanSelect.value)}function Xw(e){return we(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function uu(e){if(!(!we(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function lu(e){return{networkRequest:{...e.networkRequest}}}function eI(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function es(e){return e instanceof Error&&e.message?e.message:"操作失败"}function we(e){return Object.prototype.toString.call(e)==="[object Object]"}function Wt(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
|